16 Commits

Author SHA1 Message Date
1e6e23359a update db create models 2026-08-10 12:58:01 +05:30
1798d5e4de defination add on init.py code 2026-08-10 11:46:45 +05:30
6032ceb03a Merge pull request 'pankaj-dev' (#32) from pankaj-dev into main
Reviewed-on: #32
2026-08-10 05:49:00 +00:00
3dc9ffbc86 Merge pull request 'Add LDAP Aunthentication' (#18) from prajakta-devs into pankaj-dev
Reviewed-on: #18
Reviewed-by: Pankaj J Patil <pankajjpatil2001@gmail.com>
2026-08-10 05:48:01 +00:00
caa67976c7 Merge pull request 'Formated Client & Subctr Report' (#30) from Laxmii-Devs into main
Reviewed-on: #30
Reviewed-by: Pankaj J Patil <pankajjpatil2001@gmail.com>
2026-08-10 05:31:40 +00:00
89bd47ed7f Merge pull request 'update Dashboard on rate model and total show' (#29) from pankaj-dev into main
Reviewed-on: #29
Reviewed-by: laxmibamnale <laxmibamnale2702@gmail.com>
2026-08-08 12:35:18 +00:00
01f6831e9c Formated Client & Subctr Report 2026-08-08 17:44:47 +05:30
8ca8cbeab9 update Dashboard on rate model and total show 2026-08-08 16:54:15 +05:30
80d4e82f9b Merge pull request 'pankaj-dev' (#27) from pankaj-dev into main
Reviewed-on: #27
2026-08-08 07:30:36 +00:00
2769179a5a Merge branch 'main' of http://gitea.lcepl.org/pjpatil12/Comparison_Project into pankaj-dev 2026-08-08 12:55:03 +05:30
10511c959f Merge pull request 'Changes done in client report page' (#26) from Prajakta-main into main
Reviewed-on: #26
Reviewed-by: Pankaj J Patil <pankajjpatil2001@gmail.com>
Reviewed-by: Swapnil9693 <swapnil.dahiphale005@gmail.com>
Reviewed-by: laxmibamnale <laxmibamnale2702@gmail.com>
2026-08-08 07:02:37 +00:00
272705e437 Changes done in client report page 2026-08-08 11:25:22 +05:30
4baf8378c7 Added on Client rate model 2026-08-08 10:34:07 +05:30
06fe162198 edit .gitignore file 2026-08-07 13:51:58 +05:30
d5d69a5ba5 Merge pull request 'subctr location filter, MH NO. search, subctr manadatory field removed, added select all for delete and also all edit at once feature added' (#24) from swapnil-dev into main
Reviewed-on: #24
Reviewed-by: Pankaj J Patil <pankajjpatil2001@gmail.com>
2026-08-07 07:44:07 +00:00
b380ed510b Add LDAP Aunthentication 2026-08-06 18:17:33 +05:30
26 changed files with 3999 additions and 594 deletions

20
.env
View File

@@ -4,7 +4,7 @@
FLASK_ENV=development FLASK_ENV=development
FLASK_DEBUG=True FLASK_DEBUG=True
FLASK_HOST=0.0.0.0 FLASK_HOST=0.0.0.0
FLASK_PORT=5015 FLASK_PORT=5011
# ----------------------------- # -----------------------------
# Security # Security
@@ -23,15 +23,17 @@ DB_USER=root
DB_PASSWORD=root DB_PASSWORD=root
# DATABASE_URL=mysql+pymysql://root:root@localhost/comparisondb # DATABASE_URL=mysql+pymysql://root:root@localhost/comparisondb
# ----------------------------- # -----------------------------
# LDAP Configuration new # LDAP Configuration
# ----------------------------- # -----------------------------
LDAP_SERVER=ldap://host.docker.internal USE_LDAP_AUTH=true
LDAP_PORT=389
LDAP_USE_SSL=False
LDAP_URL=ldap://192.168.0.25:389
LDAP_BIND_DN=cn=admin,dc=lcepl,dc=org
LDAP_BIND_PASSWORD=Lcepl1950@2026
LDAP_BASE_DN=dc=lcepl,dc=org
LDAP_DOMAIN=lcepl.org LDAP_DOMAIN=lcepl.org
LDAP_BASE_DN=DC=lcepl,DC=org
LDAP_SEARCH_BASE=OU=Users,DC=lcepl,DC=org # OpenLDAP standard username attribute
LDAP_SEARCH_FILTER=(uid={username})

5
.gitignore vendored
View File

@@ -11,8 +11,11 @@ app/static/uploads/
# Ignore env files # Ignore env files
venv venv
# Ignore Log files ss # Ignore Log files
logs/ logs/
logs/app.log
logs/debug.log
logs/error.log
*.log *.log

View File

@@ -5,20 +5,23 @@ WORKDIR /app
# Install system dependencies # Install system dependencies
RUN apt-get update && apt-get install -y \ RUN apt-get update && apt-get install -y \
gcc \ gcc \
default-libmysqlclient-dev \
pkg-config \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# Copy requirements and install Python dependencies # Copy requirements and install Python dependencies
COPY requirements.txt . COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt RUN pip install --no-cache-dir -r requirements.txt gunicorn
# Copy application code # Copy application code
COPY . . COPY . .
# Create necessary directories # Create necessary directories
RUN mkdir -p app/logs app/static/uploads app/static/downloads RUN mkdir -p app/logs app/static/uploads app/static/downloads
ENV FLASK_APP=run.py
# Expose port # Expose port
EXPOSE 5001 EXPOSE 5001
# Run the application # Run the application with Gunicorn (production WSGI server)
CMD ["python", "run.py"] CMD ["gunicorn", "--bind", "0.0.0.0:5001", "run:app"]

View File

@@ -1,6 +1,6 @@
from flask import Flask, redirect, url_for from flask import Flask, redirect, url_for
from app.config import Config from app.config import Config
from app.services.db_service import db from app.services.db_service import db, migrate
from app.services.logger_service import LoggerService from app.services.logger_service import LoggerService
def create_app(): def create_app():
@@ -9,6 +9,11 @@ def create_app():
# Initialize extensions # Initialize extensions
db.init_app(app) db.init_app(app)
migrate.init_app(app, db)
with app.app_context():
import_all_models()
db.create_all()
# Initialize Logger # Initialize Logger
LoggerService.init_app(app) LoggerService.init_app(app)
@@ -26,6 +31,19 @@ def create_app():
return app return app
def import_all_models():
"""
Dynamically imports every module inside app/models/
so that db.create_all() knows about all tables (User, etc).
"""
import pkgutil
import importlib
import app.models as models_package
for _, module_name, _ in pkgutil.iter_modules(models_package.__path__):
importlib.import_module(f"app.models.{module_name}")
def register_blueprints(app): def register_blueprints(app):
from app.routes.auth import auth_bp from app.routes.auth import auth_bp
from app.routes.user_routes import user_bp from app.routes.user_routes import user_bp
@@ -35,8 +53,6 @@ def register_blueprints(app):
from app.routes.file_report import file_report_bp from app.routes.file_report import file_report_bp
from app.routes.generate_comparison_report import generate_report_bp from app.routes.generate_comparison_report import generate_report_bp
from app.routes.file_format import file_format_bp from app.routes.file_format import file_format_bp
# new
from app.routes.activity_routes import activity_bp from app.routes.activity_routes import activity_bp
from app.routes.engineering_master_routes import engi_bp from app.routes.engineering_master_routes import engi_bp
@@ -47,9 +63,7 @@ def register_blueprints(app):
app.register_blueprint(file_import_bp) app.register_blueprint(file_import_bp)
app.register_blueprint(file_report_bp) app.register_blueprint(file_report_bp)
app.register_blueprint(generate_report_bp) app.register_blueprint(generate_report_bp)
app.register_blueprint(file_format_bp) app.register_blueprint(file_format_bp )
# new
app.register_blueprint(activity_bp) app.register_blueprint(activity_bp)
app.register_blueprint(engi_bp) app.register_blueprint(engi_bp)

View File

@@ -1,4 +1,6 @@
import os import os
# project base url
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
class Config: class Config:
# secret key # secret key
@@ -21,14 +23,23 @@ class Config:
) )
SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_TRACK_MODIFICATIONS = False
# uploads folder path
UPLOAD_FOLDER = os.path.join(BASE_DIR, "static", "uploads")
# file extension
ALLOWED_EXTENSIONS = {"xlsx", "xls", "csv"}
# ---------------- LDAP settings ----------------
# LDAP Configuration New USE_LDAP_AUTH = os.getenv("USE_LDAP_AUTH", "false").lower() == "true"
LDAP_SERVER = os.getenv("LDAP_SERVER") # e.g. "ldap://192.168.0.25:389" or "ldaps://192.168.0.25:636" (preferred, encrypted)
LDAP_PORT = int(os.getenv("LDAP_PORT", 389)) LDAP_SERVER = os.getenv("LDAP_URL", "ldap://192.168.0.25:389")
LDAP_USE_SSL = os.getenv("LDAP_USE_SSL", "False").lower() == "true" # Service/admin account used only to SEARCH for a user's real DN.
# The user's own password is never used for this bind.
LDAP_BASE_DN = os.getenv("LDAP_BASE_DN") LDAP_BIND_DN = os.getenv("LDAP_BIND_DN", "cn=admin,dc=lcepl,dc=org")
LDAP_DOMAIN = os.getenv("LDAP_DOMAIN") LDAP_BIND_PASSWORD = os.getenv("LDAP_BIND_PASSWORD", "")
# Base DN to search for user entries under
LDAP_SEARCH_BASE = os.getenv("LDAP_SEARCH_BASE") LDAP_BASE_DN = os.getenv("LDAP_BASE_DN", "dc=lcepl,dc=org")
# Used only as a fallback to build an email if the directory entry has none
LDAP_DOMAIN = os.getenv("LDAP_DOMAIN", "lcepl.org")
# Filter used to find the user's entry by their login username.
# Standard OpenLDAP attribute is "uid". Active Directory would use sAMAccountName.
LDAP_SEARCH_FILTER = os.getenv("LDAP_SEARCH_FILTER", "(uid={username})")

View File

@@ -0,0 +1,20 @@
from app import db
from datetime import datetime
class ClientRate(db.Model):
__tablename__ = "client_rates"
id = db.Column(db.Integer, primary_key=True)
category = db.Column(db.String(50), nullable=False)
item_code = db.Column(db.String(50), nullable=False)
item_name = db.Column(db.String(200), nullable=False)
unit = db.Column(db.String(20))
rate = db.Column(db.Numeric(12,2), nullable=False)
effective_from = db.Column(db.Date, nullable=False)
effective_to = db.Column(db.Date)
status = db.Column(db.String(20), default="Active")
created_at = db.Column(db.DateTime, default=datetime.now)
def __repr__(self):
return f"< Client Rate {self.item_name}>"

View File

@@ -7,10 +7,13 @@ class User(db.Model):
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200), nullable=False) name = db.Column(db.String(200), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(255), nullable=False) password_hash = db.Column(db.String(255), nullable=True)
auth_source = db.Column(db.String(20), nullable=False, default="local")
def set_password(self, password): def set_password(self, password):
self.password_hash = generate_password_hash(password) self.password_hash = generate_password_hash(password)
def check_password(self, password): def check_password(self, password):
if not self.password_hash:
return False
return check_password_hash(self.password_hash, password) return check_password_hash(self.password_hash, password)

View File

@@ -1,98 +1,49 @@
from flask import (Blueprint, render_template, request, redirect, url_for, flash, session, current_app) from flask import Blueprint, render_template, request, redirect, url_for, flash, session
from app.services.user_service import UserService from app.services.user_service import UserService
from app.constants.messages import SuccessMessage, ErrorMessage
from app.constants.http_status import HTTPStatus
auth_bp = Blueprint("auth", __name__) auth_bp = Blueprint("auth", __name__)
# ==========================
# LOGIN
# ==========================
@auth_bp.route("/login", methods=["GET", "POST"]) @auth_bp.route("/login", methods=["GET", "POST"])
def login(): def login():
if session.get("user_id"): if session.get("user_id"):
current_app.logger.info("User already logged in.")
return redirect(url_for("dashboard.dashboard")) return redirect(url_for("dashboard.dashboard"))
if request.method == "POST": if request.method == "POST":
email = request.form.get("email")
try: password = request.form.get("password")
email = request.form.get("email", "").strip()
password = request.form.get("password", "")
if not email or not password:
flash(ErrorMessage.INVALID_REQUEST, "danger")
current_app.logger.warning("Login failed. Email or password missing.")
return render_template("login.html", title="Login")
user = UserService.validate_login(email, password) user = UserService.validate_login(email, password)
if user: if user:
session.clear()
session["user_id"] = user.id session["user_id"] = user.id
session["user_name"] = user.name session["user_name"] = user.name
session["email"] = user.email session["user_email"] = user.email
session.permanent = True flash("Login successful", "success")
current_app.logger.info(f"Login successful. User={user.name}")
flash(SuccessMessage.LOGIN, "success")
return redirect(url_for("dashboard.dashboard")) return redirect(url_for("dashboard.dashboard"))
current_app.logger.warning(f"Invalid login attempt. Email={email}") flash("Invalid email or password", "danger")
flash(ErrorMessage.LOGIN_FAILED,"danger")
except Exception as e:
current_app.logger.exception("Login Error" )
flash(ErrorMessage.INTERNAL_SERVER_ERROR,"danger")
return render_template("login.html", title="Login") return render_template("login.html", title="Login")
# ==========================
# LOGOUT
# ==========================
@auth_bp.route("/logout") @auth_bp.route("/logout")
def logout(): def logout():
username = session.get("user_name", "Unknown")
session.clear() session.clear()
current_app.logger.info(f"Logout successful. User={username}") flash("Logged out successfully", "info")
flash(SuccessMessage.LOGOUT,"info")
return redirect(url_for("auth.login")) return redirect(url_for("auth.login"))
# ==========================
# REGISTER
# ==========================
@auth_bp.route("/register", methods=["GET", "POST"]) @auth_bp.route("/register", methods=["GET", "POST"])
def register(): def register():
if request.method == "POST": if request.method == "POST":
try: name = request.form.get("name")
name = request.form.get("name", "").strip() email = request.form.get("email")
email = request.form.get("email", "").strip() password = request.form.get("password")
password = request.form.get("password", "")
if not name or not email or not password:
flash(ErrorMessage.INVALID_REQUEST,"danger")
return redirect(url_for("auth.register"))
user = UserService.register_user(name, email, password) user = UserService.register_user(name, email, password)
if not user: if not user:
current_app.logger.warning(f"Duplicate Registration: {email}") flash("Email already exists", "danger")
flash(ErrorMessage.DUPLICATE_ENTRY,"danger")
return redirect(url_for("auth.register")) return redirect(url_for("auth.register"))
current_app.logger.info(f"New user registered: {email}") flash("User registered successfully", "success")
flash(SuccessMessage.CREATED,"success")
return redirect(url_for("auth.login")) return redirect(url_for("auth.login"))
except Exception: return render_template("register.html", title="Register")
current_app.logger.exception("User Registration Failed" )
flash(ErrorMessage.INTERNAL_SERVER_ERROR,"danger")
return render_template("register.html",title="Register")

File diff suppressed because it is too large Load Diff

View File

@@ -6,10 +6,11 @@ from flask import (
url_for, url_for,
flash, jsonify flash, jsonify
) )
from app.constants.messages import SuccessMessage, ErrorMessage
from app.models.subcontractor_model import Subcontractor from app.models.subcontractor_model import Subcontractor
from app.services.subcontractor_rate_service import SubcontractorRateService from app.services.subcontractor_rate_service import SubcontractorRateService
from app.constants.messages import SuccessMessage, ErrorMessage from app.services.client_rate_service import ClientRateService
engi_bp = Blueprint( engi_bp = Blueprint(
"engineering", "engineering",
@@ -27,17 +28,60 @@ def engineering_master():
title="Engineering Masters" title="Engineering Masters"
) )
# Client rate model #---------------------- Client rate model -------------------------------
@engi_bp.route("/client-rate") @engi_bp.route("/client-rate", methods=["GET", "POST"])
def client_rates(): def client_rate_master():
if request.method == "POST":
result = ClientRateService.save_or_update(request.form)
if result["success"]:
flash(result["message"], "success")
return redirect(url_for("engineering.client_rate_master"))
else:
flash(result["message"], "danger")
rates = ClientRateService.get_all_rates()
return render_template( return render_template(
"engineering/client_rate.html", "engineering/client_rate.html",
title="Client Rate Master" title="Client Rate Master",
rates=rates
) )
@engi_bp.route("/client-rate/edit/<int:rate_id>", methods=["GET", "POST"])
def client_edit_rate(rate_id):
if request.method == "POST":
result = ClientRateService.save_or_update(request.form)
if result["success"]:
flash(result["message"], "success")
return redirect(url_for("engineering.client_rate_master"))
flash(result["message"], "danger")
rate = ClientRateService.get_rate(rate_id)
rates = ClientRateService.get_all_rates()
return render_template(
"engineering/client_rate.html",
rate=rate,
rates=rates
)
@engi_bp.route("/client-rate/delete/<int:rate_id>")
def client_delete_rate(rate_id):
ClientRateService.delete_rate(rate_id)
flash("Rate deleted successfully.", "success")
return redirect(url_for("engineering.client_rate_master"))
# -------------------- Sub-Contractor -------------------------------------
@engi_bp.route("/subcontractor-rate", methods=["GET", "POST"]) @engi_bp.route("/subcontractor-rate", methods=["GET", "POST"])
def add_subcontractor_rates(): def subcontractor_rate_master():
subcontractors = Subcontractor.query.filter_by(status="Active").all() subcontractors = Subcontractor.query.filter_by(status="Active").all()
@@ -45,7 +89,7 @@ def add_subcontractor_rates():
result = SubcontractorRateService.save_or_update(request.form) result = SubcontractorRateService.save_or_update(request.form)
if result["success"]: if result["success"]:
flash(result["message"], "success") flash(result["message"], "success")
return redirect(url_for("engineering.add_subcontractor_rates")) return redirect(url_for("engineering.subcontractor_rate_master"))
else: else:
flash(result["message"], "danger") flash(result["message"], "danger")
@@ -59,7 +103,7 @@ def add_subcontractor_rates():
) )
@engi_bp.route("/subcontractor-rate/edit/<int:rate_id>", methods=["GET", "POST"]) @engi_bp.route("/subcontractor-rate/edit/<int:rate_id>", methods=["GET", "POST"])
def edit_rate(rate_id): def subcontractor_edit_rate(rate_id):
subcontractors = Subcontractor.query.filter_by(status="Active").all() subcontractors = Subcontractor.query.filter_by(status="Active").all()
@@ -69,7 +113,7 @@ def edit_rate(rate_id):
if result["success"]: if result["success"]:
flash(result["message"], "success") flash(result["message"], "success")
return redirect(url_for("engineering.add_subcontractor_rates")) return redirect(url_for("engineering.subcontractor_rate_master"))
flash(result["message"], "danger") flash(result["message"], "danger")
@@ -85,10 +129,10 @@ def edit_rate(rate_id):
) )
@engi_bp.route("/subcontractor-rate/delete/<int:rate_id>") @engi_bp.route("/subcontractor-rate/delete/<int:rate_id>")
def delete_rate(rate_id): def subcontractor_delete_rate(rate_id):
SubcontractorRateService.delete_rate(rate_id) SubcontractorRateService.delete_rate(rate_id)
flash("Rate deleted successfully.", "success") flash("Rate deleted successfully.", "success")
return redirect(url_for("engineering.add_subcontractor_rates")) return redirect(url_for("engineering.subcontractor_rate_master"))
@engi_bp.route("/check-rate") @engi_bp.route("/check-rate")

View File

@@ -1,5 +1,6 @@
import pandas as pd import pandas as pd
import io import io
from datetime import datetime
from flask import Blueprint, render_template, request, send_file, flash, jsonify,redirect, url_for from flask import Blueprint, render_template, request, send_file, flash, jsonify,redirect, url_for
from app.utils.helpers import login_required from app.utils.helpers import login_required
from app.utils.regex_utils import RegularExpression from app.utils.regex_utils import RegularExpression
@@ -18,7 +19,7 @@ from app.models.tr_ex_client_model import TrenchExcavationClient
from app.models.mh_dc_client_model import ManholeDomesticChamberClient from app.models.mh_dc_client_model import ManholeDomesticChamberClient
from app.models.laying_client_model import LayingClient 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 --- # --- BLUEPRINT DEFINITION ---
@@ -114,9 +115,6 @@ def add_action_columns(df, model_key):
# ---------------- SELECT-ALL HEADER ---------------- # ---------------- SELECT-ALL HEADER ----------------
def add_select_all_header(table_html, model_key): 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( return table_html.replace(
"<th>Select</th>", "<th>Select</th>",
f'<th><input type="checkbox" class="select-all-checkbox" ' f'<th><input type="checkbox" class="select-all-checkbox" '
@@ -135,7 +133,10 @@ def add_data_field_attrs(table_html, raw_fields):
Uses match spans (not string search-and-replace) to rebuild each row, Uses match spans (not string search-and-replace) to rebuild each row,
because a naive .replace() on duplicate cell text (e.g. two cells 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 total_cols = 1 + len(raw_fields) + 2 # Select + data columns + Update + Delete
def process_row(m): def process_row(m):
@@ -173,16 +174,131 @@ def render_table_or_empty(df, model_key, table_class, raw_fields=None):
JS registered after it - including the select-all checkbox handler JS registered after it - including the select-all checkbox handler
for the OTHER tables on the page. Returning a plain message instead for the OTHER tables on the page. Returning a plain message instead
of an empty <table class="datatable"> avoids ever handing DataTables 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: if df.empty:
return '<div class="alert alert-info mb-0">No records found.</div>' return '<div class="alert alert-info mb-0">No records found.</div>'
html = df.to_html(classes=table_class, index=False, escape=False) html = df.to_html(classes=table_class, index=False, escape=False)
html = add_select_all_header(html, model_key) 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 return html
# ---------------- EXCEL SHEET FORMATTING (Tr.Ex / Mh.Ex / MH & DC / Pipe Laying) ----------------
SHEET_TITLES = {
"Tr.Ex": "TRENCH EXCAVATION",
"Mh.Ex": "MANHOLE EXCAVATION",
"MH & DC": "MANHOLE DOMESTIC CHAMBER",
"Pipe Laying": "PIPE LAYING",
}
def format_detail_sheet(workbook, worksheet, df, sheet_name, contractor_name="", ra_bill_no="", report_date=""):
"""
Writes an info line (Category / Contractor / RA Bill No / Date) at the
top, followed by a bold/bordered table with sensible column widths
and a frozen header row.
Assumes df.to_excel(..., startrow=1) already wrote the header at row 1
and the data starting at row 2 - this function overwrites those rows
with formatting and fills in row 0 with the info line.
"""
if df.empty:
return
header_format = workbook.add_format({
"bold": True,
"bg_color": "#D9EAD3",
"border": 1,
"align": "center",
"valign": "vcenter",
"text_wrap": True
})
text_format = workbook.add_format({
"border": 1,
"valign": "vcenter"
})
number_format = workbook.add_format({
"border": 1,
"valign": "vcenter",
"num_format": "#,##0.00"
})
n_rows, n_cols = df.shape
header_row = 1 # matches startrow=1 used in df.to_excel()
# -----------------------------------------------------
# INFO LINE (row 0) - separate cells, not one merged block,
# so each field (RA Bill No, Date, etc.) can be clicked/copied
# on its own. Always starts at column 0, so position is
# consistent regardless of how many table columns exist.
# -----------------------------------------------------
last_col = max(n_cols - 1, 0)
report_title = SHEET_TITLES.get(sheet_name, sheet_name.upper())
label_format = workbook.add_format({"bold": True})
value_format = workbook.add_format({})
info_fields = [("Category:", report_title)]
# Client reports don't have a single contractor (data can span
# multiple subcontractors), so this field is only shown when a
# contractor name is actually passed in (Subcontractor report).
if contractor_name:
info_fields.append(("Contractor:", contractor_name))
info_fields.append(("RA Bill No:", ra_bill_no or "All"))
info_fields.append(("Date:", report_date))
col = 0
for label, value in info_fields:
worksheet.write(0, col, label, label_format)
worksheet.write(0, col + 1, value, value_format)
col += 3 # leave one blank column as a visual gap before next field
# Fill any remaining columns on row 0 with a blank bordered cell so
# the row reads cleanly if the sheet is wider than the info fields.
if last_col > col:
worksheet.write_blank(0, col, None)
# -----------------------------------------------------
# TABLE HEADER (row 1) - re-write with formatting
# -----------------------------------------------------
for col_idx, col_name in enumerate(df.columns):
worksheet.write(header_row, col_idx, col_name, header_format)
# -----------------------------------------------------
# TABLE BODY (rows 2+) - borders / number formatting
# -----------------------------------------------------
for row_idx in range(n_rows):
for col_idx, col_name in enumerate(df.columns):
value = df.iat[row_idx, col_idx]
if pd.isna(value):
worksheet.write(header_row + 1 + row_idx, col_idx, "", text_format)
elif isinstance(value, (int, float)):
worksheet.write_number(header_row + 1 + row_idx, col_idx, float(value), number_format)
else:
worksheet.write(header_row + 1 + row_idx, col_idx, str(value), text_format)
# Auto width columns based on header + content length
for col_idx, col_name in enumerate(df.columns):
max_len = len(str(col_name))
if n_rows:
col_values = df.iloc[:, col_idx].astype(str)
content_max = col_values.map(len).max()
max_len = max(max_len, content_max)
worksheet.set_column(col_idx, col_idx, min(max_len + 4, 30))
worksheet.freeze_panes(header_row + 1, 1)
worksheet.set_row(header_row, 30)
# ---------------- FETCH ---------------- # ---------------- FETCH ----------------
@@ -302,7 +418,11 @@ def delete_records():
"tr": TrenchExcavation, "tr": TrenchExcavation,
"mh": ManholeExcavation, "mh": ManholeExcavation,
"dc": ManholeDomesticChamber, "dc": ManholeDomesticChamber,
"laying": Laying "laying": Laying,
"tr_client": TrenchExcavationClient,
"mh_client": ManholeExcavationClient,
"dc_client": ManholeDomesticChamberClient,
"laying_client": LayingClient
} }
ModelClass = model_map.get(model) ModelClass = model_map.get(model)
@@ -330,7 +450,8 @@ def delete_records():
@file_report_bp.route("/bulk_update", methods=["POST"]) @file_report_bp.route("/bulk_update", methods=["POST"])
@login_required @login_required
def bulk_update(): 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": {...}, ... } { "tr": { "5": {"MH_NO": "12A", "Location": "Pune"}, ... }, "mh": {...}, ... }
Field names are validated against each model's real table columns Field names are validated against each model's real table columns
@@ -389,7 +510,11 @@ def edit_record(model, record_id):
"tr": TrenchExcavation, "tr": TrenchExcavation,
"mh": ManholeExcavation, "mh": ManholeExcavation,
"dc": ManholeDomesticChamber, "dc": ManholeDomesticChamber,
"laying": Laying "laying": Laying,
"tr_client": TrenchExcavationClient,
"mh_client": ManholeExcavationClient,
"dc_client": ManholeDomesticChamberClient,
"laying_client": LayingClient
} }
ModelClass = model_map.get(model) ModelClass = model_map.get(model)
@@ -414,7 +539,10 @@ def edit_record(model, record_id):
try: try:
db.session.commit() db.session.commit()
flash("Record updated successfully.", "success") 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")) return redirect(url_for("file_report.report_file"))
except Exception as e: except Exception as e:
@@ -551,6 +679,16 @@ def report_file():
# DOWNLOAD EXCEL # DOWNLOAD EXCEL
# =================================================== # ===================================================
if action in ["excel", "excel_all"]: if action in ["excel", "excel_all"]:
# Look up the contractor's real name once, up front, so it can
# be shown in the title block of every sheet.
sc_obj = next(
(s for s in subcontractors if str(s.id) == str(subcontractor_id)),
None
)
contractor_display_name = sc_obj.subcontractor_name if sc_obj else ""
report_date = datetime.now().strftime("%d-%b-%Y")
output = io.BytesIO() output = io.BytesIO()
with pd.ExcelWriter(output,engine="xlsxwriter") as writer: with pd.ExcelWriter(output,engine="xlsxwriter") as writer:
@@ -558,7 +696,6 @@ def report_file():
abstract = AbstractReportService(subcontractor_id=subcontractor_id,ra_bill_no=ra_bill_no) abstract = AbstractReportService(subcontractor_id=subcontractor_id,ra_bill_no=ra_bill_no)
abstract.generate(workbook) abstract.generate(workbook)
sheet_map = [ sheet_map = [
(bill.df_tr, "Tr.Ex"), (bill.df_tr, "Tr.Ex"),
(bill.df_mh, "Mh.Ex"), (bill.df_mh, "Mh.Ex"),
@@ -567,17 +704,24 @@ def report_file():
] ]
for df, sheet_name in sheet_map: for df, sheet_name in sheet_map:
if not df.empty: if not df.empty:
df.to_excel(writer, sheet_name=sheet_name, index=False) # Use a copy for the export only - bill.df_tr etc. still
# need the real "Id" column later for the Edit/Delete
# buttons on the web preview table.
export_df = df.drop(columns=["Id"], errors="ignore").copy()
export_df.insert(0, "Sr No", range(1, len(export_df) + 1))
export_df.to_excel(writer, sheet_name=sheet_name, index=False, startrow=1)
worksheet = writer.sheets[sheet_name]
format_detail_sheet(
workbook, worksheet, export_df, sheet_name,
contractor_name=contractor_display_name,
ra_bill_no=ra_bill_no,
report_date=report_date
)
writer.close() writer.close()
output.seek(0) output.seek(0)
sc_name = re.sub(r'[^A-Za-z0-9_-]+', '_', contractor_display_name or "Subcontractor").strip('_')
sc_obj = next(
(s for s in subcontractors if str(s.id) == str(subcontractor_id)),
None
)
sc_name = sc_obj.subcontractor_name if sc_obj else "Subcontractor"
sc_name = re.sub(r'[^A-Za-z0-9_-]+', '_', sc_name).strip('_')
name_parts = [sc_name] name_parts = [sc_name]
@@ -628,7 +772,6 @@ def report_file():
} }
# this are html classes # this are html classes
# table_class = ( "table " "table-bordered" "table-hover " "table-striped " "table-sm " "align-middle " "datatable " "mb-0")
table_class = ( table_class = (
"table " "table "
"table-bordered " "table-bordered "
@@ -672,22 +815,65 @@ class ClientBill:
self.df_dc = pd.DataFrame() self.df_dc = pd.DataFrame()
self.df_laying = pd.DataFrame() self.df_laying = pd.DataFrame()
def Fetch(self, RA_Bill_No): def Fetch(self, RA_Bill_No=None, location=None, mh_no=None):
trench = TrenchExcavationClient.query.filter_by(RA_Bill_No=RA_Bill_No).all() filters = {}
mh = ManholeExcavationClient.query.filter_by(RA_Bill_No=RA_Bill_No).all() if RA_Bill_No:
dc = ManholeDomesticChamberClient.query.filter_by(RA_Bill_No=RA_Bill_No).all() filters["RA_Bill_No"] = RA_Bill_No
lay = LayingClient.query.filter_by(RA_Bill_No=RA_Bill_No).all()
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_tr = pd.DataFrame([c.serialize() for c in trench])
self.df_mh = pd.DataFrame([c.serialize() for c in mh]) self.df_mh = pd.DataFrame([c.serialize() for c in mh])
self.df_dc = pd.DataFrame([c.serialize() for c in dc]) self.df_dc = pd.DataFrame([c.serialize() for c in dc])
self.df_laying = pd.DataFrame([c.serialize() for c in lay]) self.df_laying = pd.DataFrame([c.serialize() for c in lay])
drop_cols = ["created_at", "_sa_instance_state"]
drop_cols = ["id", "created_at", "_sa_instance_state"]
for df in [self.df_tr, self.df_mh, self.df_dc, self.df_laying]: for df in [self.df_tr, self.df_mh, self.df_dc, self.df_laying]:
if not df.empty: if not df.empty:
df.drop(columns=drop_cols, errors="ignore", inplace=True) df.drop(columns=drop_cols, errors="ignore", inplace=True)
format_column_names(df)
# --- CLIENT REPORT (PREVIEW + DOWNLOAD) --- # --- CLIENT REPORT (PREVIEW + DOWNLOAD) ---
@@ -695,23 +881,41 @@ class ClientBill:
@login_required @login_required
def client_report(): def client_report():
tables = {"tr": None, "mh": None, "dc": None, "laying": None} tables = None
ra_val = "" 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": if request.method == "POST":
# ⚠ MUST match HTML name RA_Bill_No = request.form.get("RA_Bill_No", "").strip()
RA_Bill_No = request.form.get("RA_Bill_No") location = request.form.get("location", "").strip()
action = request.form.get("action") mh_no = request.form.get("mh_no", "").strip()
category = request.form.get("category", "")
action = request.form.get("action", "preview")
ra_val = RA_Bill_No ra_val = RA_Bill_No
location_val = location
mh_no_val = mh_no
category_val = category
if not RA_Bill_No: if not RA_Bill_No:
flash("Please enter RA Bill No.", "danger") 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 -------- # -------- FETCH CLIENT DATA --------
bill_gen = ClientBill() bill_gen = ClientBill()
bill_gen.Fetch(RA_Bill_No) bill_gen.Fetch(RA_Bill_No, location, mh_no)
# If no data # If no data
if ( if (
@@ -721,36 +925,121 @@ def client_report():
bill_gen.df_laying.empty bill_gen.df_laying.empty
): ):
flash(f"No Client records found for RA Bill {RA_Bill_No}", "warning") 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 -------- # -------- DOWNLOAD --------
if action == "download": if action == "download":
report_date = datetime.now().strftime("%d-%b-%Y")
output = io.BytesIO() output = io.BytesIO()
with pd.ExcelWriter(output, engine="xlsxwriter") as writer: with pd.ExcelWriter(output, engine="xlsxwriter") as writer:
bill_gen.df_tr.to_excel(writer, index=False, sheet_name="Trench") workbook = writer.book
bill_gen.df_mh.to_excel(writer, index=False, sheet_name="MH") abstract_service.generate(workbook)
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") sheet_map = [
(bill_gen.df_tr, "Tr.Ex"),
(bill_gen.df_mh, "Mh.Ex"),
(bill_gen.df_dc, "MH & DC"),
(bill_gen.df_laying, "Pipe Laying"),
]
for df, sheet_name in sheet_map:
if not df.empty:
# Use a copy for the export only, same as the
# Subcontractor report, so the formatted sheet gets
# a clean "Sr No" column instead of the raw Id.
export_df = df.drop(columns=["Id"], errors="ignore").copy()
export_df.insert(0, "Sr No", range(1, len(export_df) + 1))
export_df.to_excel(writer, sheet_name=sheet_name, index=False, startrow=1)
worksheet = writer.sheets[sheet_name]
format_detail_sheet(
workbook, worksheet, export_df, sheet_name,
contractor_name="",
ra_bill_no=RA_Bill_No,
report_date=report_date
)
output.seek(0) output.seek(0)
filename_parts = [f"Client_RA_{re.sub(r'[^A-Za-z0-9_-]+', '_', RA_Bill_No)}"]
if location:
filename_parts.append(re.sub(r'[^A-Za-z0-9_-]+', '_', location).strip('_'))
if category and category != "all":
filename_parts.append(category.upper())
filename = "_".join(filename_parts) + "_Report.xlsx"
return send_file( return send_file(
output, output,
download_name=f"Client_RA_{RA_Bill_No}_Report.xlsx", download_name=filename,
as_attachment=True 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) has_data = {
tables["mh"] = bill_gen.df_mh.to_html(classes=table_class, index=False) "tr": not bill_gen.df_tr.empty,
tables["dc"] = bill_gen.df_dc.to_html(classes=table_class, index=False) "mh": not bill_gen.df_mh.empty,
tables["laying"] = bill_gen.df_laying.to_html(classes=table_class, index=False) "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): def format_column_names(df):

View File

@@ -1,3 +1,4 @@
import re
from sqlalchemy import func from sqlalchemy import func
from app import db 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.manhole_domestic_chamber_model import ManholeDomesticChamber
from app.models.laying_model import Laying 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: class AbstractReportService:
@@ -357,3 +365,214 @@ class AbstractReportService:
""" """
return html 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

@@ -0,0 +1,97 @@
from app.services.db_service import db
from app.models.client_rate_model import ClientRate
from sqlalchemy import func
class ClientRateService:
@staticmethod
def save_or_update(form):
rate_id = form.get("id")
category = form.get("category")
item_name = form.get("item_name").strip()
# -----------------------------
# Duplicate Validation
# -----------------------------
duplicate = (
ClientRate.query
.filter(
ClientRate.category == category,
func.lower(ClientRate.item_name) == item_name.lower()
)
.first()
)
# Ignore current record while editing
if duplicate and (not rate_id or duplicate.id != int(rate_id)):
return {
"success": False,
"message": "Category and Rate already exists for this Client."
}
# -----------------------------
# Insert / Update
# -----------------------------
if rate_id:
rate = ClientRate.query.get_or_404(rate_id)
else:
rate = ClientRate()
rate.category = category
rate.item_code = form.get("item_code")
rate.item_name = item_name
rate.unit = form.get("unit")
rate.rate = form.get("rate")
rate.effective_from = form.get("effective_from")
rate.effective_to = form.get("effective_to") or None
rate.status = form.get("status")
if not rate_id:
db.session.add(rate)
db.session.commit()
return {
"success": True,
"message": "Saved Successfully."
}
@staticmethod
def get_all_rates():
return (
ClientRate.query
.order_by(ClientRate.created_at.desc())
.all()
)
@staticmethod
def get_rate(rate_id):
return ClientRate.query.get_or_404(rate_id)
def delete_rate(rate_id):
rate = ClientRate.query.get_or_404(rate_id)
db.session.delete(rate)
db.session.commit()
@staticmethod
def check_duplicate(subcontractor_id, category, item_name, rate_id=None):
query = ClientRate.query.filter(
ClientRate.category == category,
func.lower(ClientRate.item_name) == item_name.strip().lower()
)
if rate_id:
query = query.filter(ClientRate.id != int(rate_id))
return query.first() is not None

View File

@@ -1,130 +1,72 @@
from ldap3 import (
Server,
Connection,
ALL,
NTLM,
SIMPLE,
SUBTREE
)
from flask import current_app from flask import current_app
from app.config import Config from ldap3 import Server, Connection, ALL, SUBTREE
from ldap3.core.exceptions import LDAPException
class LDAPService: class LDAPService:
""" """
LDAP / Active Directory Authentication Service Handles authentication against an LDAP / OpenLDAP server using the
standard "search + bind" pattern:
1. Bind with a service/admin account just to SEARCH for the user's DN.
2. Re-bind using that DN + the password the user typed, to verify it.
The user's typed password is only ever used in step 2, never sent
anywhere else.
""" """
@staticmethod @staticmethod
def authenticate(username, password): def authenticate(username, password):
"""
Authenticate LDAP User
Returns:
{
"success": True,
"user": {
"username": "...",
"name": "...",
"email": "..."
}
}
OR
{
"success": False,
"message": "Invalid username or password"
}
"""
if not username or not password: if not username or not password:
return { return None
"success": False,
"message": "Username and Password are required."
}
server = Server(current_app.config["LDAP_SERVER"], get_info=ALL)
# --- Step 1: bind as the admin/service account to search the directory ---
try: try:
admin_conn = Connection(
# -----------------------------------
# LDAP SERVER
# -----------------------------------
server = Server(
Config.LDAP_SERVER,
port=Config.LDAP_PORT,
use_ssl=Config.LDAP_USE_SSL,
get_info=ALL
)
# -----------------------------------
# Login Format
#
# username@domain.com
# -----------------------------------
user_dn = f"{username}@{Config.LDAP_DOMAIN}"
conn = Connection(
server, server,
user=user_dn, user=current_app.config["LDAP_BIND_DN"],
password=password, password=current_app.config["LDAP_BIND_PASSWORD"],
authentication=SIMPLE, auto_bind=True,
auto_bind=True
) )
except LDAPException as e:
current_app.logger.error(f"LDAP service account bind failed: {e}")
return None
# ----------------------------------- # --- Step 2: find the user's real DN + profile attributes ---
# Search User try:
# ----------------------------------- search_filter = current_app.config["LDAP_SEARCH_FILTER"].format(username=username)
search_filter = f"(sAMAccountName={username})" admin_conn.search(
search_base=current_app.config["LDAP_BASE_DN"],
conn.search(
search_base=Config.LDAP_SEARCH_BASE,
search_filter=search_filter, search_filter=search_filter,
search_scope=SUBTREE, search_scope=SUBTREE,
attributes=[ attributes=["cn", "mail", "uid"],
"displayName",
"mail",
"givenName",
"sn",
"cn"
]
) )
except LDAPException as e:
current_app.logger.error(f"LDAP search failed for '{username}': {e}")
admin_conn.unbind()
return None
display_name = username if not admin_conn.entries:
email = "" current_app.logger.warning(f"LDAP user not found: {username}")
admin_conn.unbind()
return None
if conn.entries: entry = admin_conn.entries[0]
user_dn = entry.entry_dn
entry = conn.entries[0] name = str(entry.cn) if "cn" in entry and entry.cn.value else username
email = (
if "displayName" in entry: str(entry.mail)
display_name = str(entry.displayName) if "mail" in entry and entry.mail.value
else f"{username}@{current_app.config['LDAP_DOMAIN']}"
if "mail" in entry:
email = str(entry.mail)
conn.unbind()
current_app.logger.info(
f"LDAP Login Success : {username}"
) )
admin_conn.unbind()
return { # --- Step 3: the actual auth check - bind AS the user with their password ---
"success": True, try:
"user": { user_conn = Connection(server, user=user_dn, password=password, auto_bind=True)
"username": username, user_conn.unbind()
"name": display_name, except LDAPException as e:
"email": email current_app.logger.warning(f"LDAP authentication failed for '{username}': {e}")
} return None
}
except Exception as ex: return {"username": username, "name": name, "email": email}
current_app.logger.warning(
f"LDAP Login Failed : {username} : {str(ex)}"
)
return {
"success": False,
"message": "Invalid Username or Password."
}

View File

@@ -1,6 +1,7 @@
from flask import current_app
from app.models.user_model import User from app.models.user_model import User
from app.services.db_service import db from app.services.db_service import db
from flask import current_app from app.services.ldap_service import LDAPService
class UserService: class UserService:
@@ -9,21 +10,57 @@ class UserService:
if User.query.filter_by(email=email).first(): if User.query.filter_by(email=email).first():
return None return None
user = User(name=name, email=email) user = User(name=name, email=email, auth_source="local")
user.set_password(password) user.set_password(password)
db.session.add(user) db.session.add(user)
db.session.commit() db.session.commit()
current_app.logger.info("User list viewed")
return user return user
@staticmethod @staticmethod
def validate_login(email, password): def validate_login(identifier, password):
user = User.query.filter_by(email=email).first() """
identifier = whatever was typed in the login form. Can be an email
(local users) or an LDAP username, depending on USE_LDAP_AUTH.
"""
if current_app.config.get("USE_LDAP_AUTH"):
ldap_user = UserService._validate_ldap_login(identifier, password)
if ldap_user:
return ldap_user
return None
user = User.query.filter_by(email=identifier).first()
if user and user.check_password(password): if user and user.check_password(password):
return user return user
return None return None
@staticmethod
def _validate_ldap_login(username, password):
ldap_info = LDAPService.authenticate(username, password)
if not ldap_info:
return None
return UserService._get_or_create_ldap_user(ldap_info)
@staticmethod
def _get_or_create_ldap_user(ldap_info):
"""
LDAP is the source of truth for the password. We still keep a row in
our local `users` table (no password) so the rest of the app - which
expects a User with an id - keeps working unchanged.
"""
user = User.query.filter_by(email=ldap_info["email"]).first()
if user is None:
user = User(
name=ldap_info["name"],
email=ldap_info["email"],
auth_source="ldap",
)
db.session.add(user)
db.session.commit()
elif user.name != ldap_info["name"]:
user.name = ldap_info["name"]
db.session.commit()
return user
@staticmethod @staticmethod
def get_all_users(): def get_all_users():
return User.query.all() return User.query.all()

View File

@@ -1,74 +1,347 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% 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"> <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="row g-3">
<div class="col-md-6"> <div class="col-lg-3">
<button type="submit" name="action" value="preview" class="btn btn-secondary w-100">Preview <label class="form-label fw-semibold">
Data</button> 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>
<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>
<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> </div>
</form> </form>
</div>
</div> </div>
{% if tables.tr or tables.mh or tables.dc or tables.laying %} {% if tables %}
<div class="card shadow-sm p-4"> {% set show_all = (not category_val) or category_val == 'all' %}
<h4 class="mb-3">Table Preview</h4> <!-- 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"> <li class="nav-item">
<button class="nav-link active" id="tr-tab" data-bs-toggle="tab" data-bs-target="#tr" <button class="nav-link {% if category_val == 'tr' %}active{% endif %}" data-bs-toggle="tab"
type="button">Tr.Ex </button> data-bs-target="#tr">
</li> <i class="bi bi-cone-striped"></i> Trench Excavation
<li class="nav-item">
<button class="nav-link" id="mh-tab" data-bs-toggle="tab" data-bs-target="#mh" type="button">Mh.Ex
</button> </button>
</li> </li>
{% endif %}
{% if show_all or category_val == 'mh' %}
<li class="nav-item"> <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> </button>
</li> </li>
{% endif %}
{% if show_all or category_val == 'dc' %}
<li class="nav-item"> <li class="nav-item">
<button class="nav-link" id="laying-tab" data-bs-toggle="tab" data-bs-target="#laying" type="button">Laying <button class="nav-link {% if category_val == 'dc' %}active{% endif %}" data-bs-toggle="tab"
& Bedding </button> data-bs-target="#dc">
<i class="bi bi-grid-3x3"></i> Manhole & Domestic Chambers Construction
</button>
</li> </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> </ul>
</div>
<div class="tab-content mt-3" id="reportTabsContent"> <div class="card-body">
<div class="tab-pane fade show active" id="tr" role="tabpanel"> <div class="tab-content">
<div class="table-responsive" style="max-height: 500px;">
<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 }} {{ tables.tr|safe }}
</div> </div>
</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 %} {% 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> </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> </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 %} {% endblock %}

View File

@@ -14,7 +14,353 @@
</div> </div>
<div class="card-body">
<form method="POST" id="rateForm">
<!-- Hidden ID -->
<input type="hidden" id="rate_id" name="id" value="{{ rate.id if rate else '' }}">
<div class="row">
<!-- Category -->
<div class="col-md-4 mb-3">
<label class="form-label fw-bold"> Category </label>
<select id="category" name="category" class="form-select" required>
<option value="">-- Select Category --</option>
<option value="trench_excavation"
{% if rate and rate.category=="trench_excavation" %}selected{% endif %}>
Trench Excavation
</option>
<option value="manhole_excavation"
{% if rate and rate.category=="manhole_excavation" %}selected{% endif %}>
Manhole Excavation
</option>
<option value="Manhole_Domestic_Chamber"
{% if rate and rate.category=="Manhole_Domestic_Chamber" %}selected{% endif %}>
MH & Domestic Chamber
</option>
<option value="Laying"
{% if rate and rate.category=="Laying" %}selected{% endif %}>
Pipe Laying
</option>
</select>
</div>
<!-- Status -->
<div class="col-md-4 mb-3">
<label class="form-label fw-bold"> Status </label>
<select name="status" class="form-select">
<option value="Active"
{% if not rate or rate.status=="Active" %}selected{% endif %}>
Active
</option>
<option value="Inactive"
{% if rate and rate.status=="Inactive" %}selected{% endif %}>
Inactive
</option>
</select>
</div>
</div>
<div class="row">
<!-- Item Code -->
<div class="col-md-3 mb-3">
<label class="form-label fw-bold"> Item Code </label>
<input type="text" name="item_code" class="form-control" value="{{ rate.item_code if rate else '' }}" required>
</div>
<!-- Item Name -->
<div class="col-md-5 mb-3">
<label class="form-label fw-bold"> Item Name </label>
<input type="text"
id="item_name"
name="item_name"
class="form-control"
autocomplete="off"
value="{{ rate.item_name if rate else '' }}"
required>
<small id="duplicateMessage"
class="text-danger"
style="display:none;">
</small>
</div> </div>
<!-- Unit -->
<div class="col-md-2 mb-3">
<label class="form-label fw-bold">Unit</label>
<select name="unit" class="form-select">
<option value="Cum"
{% if not rate or rate.unit=="Cum" %}selected{% endif %}>
Cum
</option>
<option value="Nos"
{% if rate and rate.unit=="Nos" %}selected{% endif %}>
Nos
</option>
<option value="Rmt"
{% if rate and rate.unit=="Rmt" %}selected{% endif %}>
Rmt
</option>
<option value="Sqm"
{% if rate and rate.unit=="Sqm" %}selected{% endif %}>
Sqm
</option>
</select>
</div>
<!-- Rate -->
<div class="col-md-2 mb-3">
<label class="form-label fw-bold">Rate</label>
<input type="number" step="0.01" name="rate" class="form-control" value="{{ rate.rate if rate else '' }}" required>
</div>
</div>
<div class="row">
<div class="col-md-3 mb-3">
<label class="form-label fw-bold"> Effective From </label>
<input type="date" name="effective_from" class="form-control" value="{{ rate.effective_from if rate else '' }}" required>
</div>
<div class="col-md-3 mb-3">
<label class="form-label fw-bold"> Effective To </label>
<input type="date" name="effective_to" class="form-control" value="{{ rate.effective_to if rate else '' }}">
</div>
</div>
<hr>
<div class="text-end">
<a href="{{ url_for('engineering.client_rate_master') }}" class="btn btn-secondary">
<i class="bi bi-arrow-clockwise"></i> Reset
</a>
<button type="submit" id="saveBtn" class="btn btn-success">
{% if rate %}
<i class="bi bi-pencil-square"></i>
Update Rate
{% else %}
<i class="bi bi-check-circle"></i>
Save Rate
{% endif %}
</button>
</div>
</form>
</div>
</div>
<!-- Table -->
<div class="card shadow mt-4">
<div class="card-header bg-dark text-white">
<h5 class="mb-0">
<i class="bi bi-table"></i>Rate List
</h5>
</div>
<div class="card-body">
<table class="table table-bordered table-hover table-striped" id="rateTable">
<thead class="table-primary">
<tr>
<th>#</th>
<th>Category</th>
<th>Item Code</th>
<th>Item Name</th>
<th>Unit</th>
<th>Rate</th>
<th>Status</th>
<th width="130">Action</th>
</tr>
</thead>
<tbody>
{% for row in rates %}
<tr>
<td>{{ loop.index }}</td>
<td>{{ row.category }}</td>
<td>{{ row.item_code }}</td>
<td>{{ row.item_name }}</td>
<td>{{ row.unit }}</td>
<td>{{ row.rate }}</td>
<td>
{% if row.status=="Active" %}
<span class="badge bg-success">
Active
</span>
{% else %}
<span class="badge bg-danger">
Inactive
</span>
{% endif %}
</td>
<td>
<a href="{{ url_for('engineering.client_edit_rate', rate_id=row.id) }}" class="btn btn-warning btn-sm">
<i class="bi bi-pencil-square"></i>
</a>
<a href="{{ url_for('engineering.client_delete_rate', rate_id=row.id) }}"
class="btn btn-danger btn-sm" onclick="return confirm('Delete this Item:{{row.item_name}} & Rate:{{row.rate}} ?')">
<i class="bi bi-trash"></i>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<script>
$(document).ready(function () {
// ----------------------------
// DataTable
// ----------------------------
$("#rateTable").DataTable({
responsive: true,
pageLength: 10,
destroy: true
});
// ----------------------------
// Validate on field change
// ----------------------------
$("#subcontractor_id, #category").on("change", function () {
clearValidation();
checkDuplicateRate();
});
// ----------------------------
// Validate while typing
// ----------------------------
let timer;
$("#item_name").on("keyup input", function () {
clearTimeout(timer);
timer = setTimeout(function () {
checkDuplicateRate();
}, 300);
});
// Edit Mode
checkDuplicateRate();
// ----------------------------
// Prevent Submit
// ----------------------------
$("#rateForm").submit(function (e) {
if ($("#saveBtn").prop("disabled")) {
e.preventDefault();
$("#item_name").focus();
return false;
}
});
});
//=========================================
// Reset Validation
//=========================================
function clearValidation() {
$("#duplicateMessage")
.hide()
.text("")
.removeClass("text-success text-danger");
$("#item_name")
.removeClass("is-valid is-invalid");
$("#saveBtn").prop("disabled", false);
}
//=========================================
// Duplicate Validation
//=========================================
function checkDuplicateRate() {
let subcontractor = $("#subcontractor_id").val();
let category = $("#category").val();
let item_name = $("#item_name").val().trim();
let rate_id = $("#rate_id").val();
// Mandatory fields
if (
subcontractor == "" ||
category == "" ||
item_name.length < 2
) {
clearValidation();
return;
}
$.ajax({
url: "{{ url_for('engineering.check_rate') }}",
type: "GET",
dataType: "json",
data: {
subcontractor_id: subcontractor,
category: category,
item_name: item_name,
rate_id: rate_id
},
success: function (response) {
if (response.exists) {
$("#duplicateMessage")
.text("This Item Name already exists for the selected Subcontractor and Category.")
.removeClass("text-success")
.addClass("text-danger")
.show();
$("#item_name")
.removeClass("is-valid")
.addClass("is-invalid");
$("#saveBtn").prop("disabled", true);
}
else {
$("#duplicateMessage")
.text("Item Name is available.")
.removeClass("text-danger")
.addClass("text-success")
.show();
$("#item_name")
.removeClass("is-invalid")
.addClass("is-valid");
$("#saveBtn").prop("disabled", false);
}
},
error: function () {
clearValidation();
}
});
}
</script>
{% endblock %} {% endblock %}

View File

@@ -4,14 +4,12 @@
<div class="container-fluid mt-4"> <div class="container-fluid mt-4">
<div class="card shadow"> <div class="card shadow">
<!-- Heading -->
<div class="card-header bg-primary text-white d-flex justify-content-between align-items-center"> <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
<h4 class="mb-0"> <h4 class="mb-0">
<i class="bi bi-currency-rupee"></i> <i class="bi bi-currency-rupee"></i>
Subcontractor Rate Master Subcontractor Rate Master
</h4> </h4>
</div> </div>
<div class="card-body"> <div class="card-body">
@@ -67,23 +65,6 @@
</select> </select>
</div> </div>
<!-- Status -->
<div class="col-md-4 mb-3">
<label class="form-label fw-bold"> Status </label>
<select name="status" class="form-select">
<option value="Active"
{% if not rate or rate.status=="Active" %}selected{% endif %}>
Active
</option>
<option value="Inactive"
{% if rate and rate.status=="Inactive" %}selected{% endif %}>
Inactive
</option>
</select>
</div>
</div> </div>
<div class="row"> <div class="row">
@@ -95,7 +76,7 @@
</div> </div>
<!-- Item Name --> <!-- Item Name -->
<div class="col-md-5 mb-3"> <div class="col-md-4 mb-3">
<label class="form-label fw-bold"> Item Name </label> <label class="form-label fw-bold"> Item Name </label>
<input type="text" <input type="text"
id="item_name" id="item_name"
@@ -116,6 +97,7 @@
<div class="col-md-2 mb-3"> <div class="col-md-2 mb-3">
<label class="form-label fw-bold">Unit</label> <label class="form-label fw-bold">Unit</label>
<select name="unit" class="form-select"> <select name="unit" class="form-select">
<option value=""> -- Select Unit -- </option>
<option value="Cum" <option value="Cum"
{% if not rate or rate.unit=="Cum" %}selected{% endif %}> {% if not rate or rate.unit=="Cum" %}selected{% endif %}>
Cum Cum
@@ -136,28 +118,46 @@
</div> </div>
<!-- Rate --> <!-- Rate -->
<div class="col-md-2 mb-3"> <div class="col-md-3 mb-3">
<label class="form-label fw-bold">Rate</label> <label class="form-label fw-bold">Rate</label>
<input type="number" step="0.01" name="rate" class="form-control" value="{{ rate.rate if rate else '' }}" required> <input type="number" step="0.01" name="rate" class="form-control" value="{{ rate.rate if rate else '' }}" required>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<!-- Effective From -->
<div class="col-md-3 mb-3"> <div class="col-md-3 mb-3">
<label class="form-label fw-bold"> Effective From </label> <label class="form-label fw-bold"> Effective From </label>
<input type="date" name="effective_from" class="form-control" value="{{ rate.effective_from if rate else '' }}" required> <input type="date" name="effective_from" class="form-control" value="{{ rate.effective_from if rate else '' }}" required>
</div> </div>
<!-- Effective To -->
<div class="col-md-3 mb-3"> <div class="col-md-3 mb-3">
<label class="form-label fw-bold"> Effective To </label> <label class="form-label fw-bold"> Effective To </label>
<input type="date" name="effective_to" class="form-control" value="{{ rate.effective_to if rate else '' }}"> <input type="date" name="effective_to" class="form-control" value="{{ rate.effective_to if rate else '' }}">
</div> </div>
<!-- Status -->
<div class="col-md-3 mb-3">
<label class="form-label fw-bold"> Status </label>
<select name="status" class="form-select">
<option value="Active"
{% if not rate or rate.status=="Active" %}selected{% endif %}>
Active
</option>
<option value="Inactive"
{% if rate and rate.status=="Inactive" %}selected{% endif %}>
Inactive
</option>
</select>
</div>
</div> </div>
<hr> <hr>
<div class="text-end"> <div class="text-end">
<a href="{{ url_for('engineering.add_subcontractor_rates') }}" class="btn btn-secondary"> <a href="{{ url_for('engineering.subcontractor_rate_master') }}" class="btn btn-secondary">
<i class="bi bi-arrow-clockwise"></i> Reset <i class="bi bi-arrow-clockwise"></i> Reset
</a> </a>
@@ -222,11 +222,11 @@
</td> </td>
<td> <td>
<a href="{{ url_for('engineering.edit_rate', rate_id=row.id) }}" class="btn btn-warning btn-sm"> <a href="{{ url_for('engineering.subcontractor_edit_rate', rate_id=row.id) }}" class="btn btn-warning btn-sm">
<i class="bi bi-pencil-square"></i> <i class="bi bi-pencil-square"></i>
</a> </a>
<a href="{{ url_for('engineering.delete_rate', rate_id=row.id) }}" <a href="{{ url_for('engineering.subcontractor_delete_rate', rate_id=row.id) }}"
class="btn btn-danger btn-sm" onclick="return confirm('Delete this Item:{{row.item_name}} & Rate:{{row.rate}} ?')"> class="btn btn-danger btn-sm" onclick="return confirm('Delete this Item:{{row.item_name}} & Rate:{{row.rate}} ?')">
<i class="bi bi-trash"></i> <i class="bi bi-trash"></i>
</a> </a>

View File

@@ -32,7 +32,7 @@
Manage subcontractor-wise rates. Manage subcontractor-wise rates.
</p> </p>
<a href="{{ url_for('engineering.add_subcontractor_rates') }}" <a href="{{ url_for('engineering.subcontractor_rate_master') }}"
class="btn btn-success"> class="btn btn-success">
<i class="bi bi-arrow-right-circle"></i> <i class="bi bi-arrow-right-circle"></i>
@@ -62,7 +62,7 @@
Manage client standard rates. Manage client standard rates.
</p> </p>
<a href="{{ url_for('engineering.client_rates') }}" <a href="{{ url_for('engineering.client_rate_master') }}"
class="btn btn-primary"> class="btn btn-primary">
<i class="bi bi-arrow-right-circle"></i> <i class="bi bi-arrow-right-circle"></i>

View File

@@ -142,11 +142,21 @@
<tr> <tr>
<th>Sr No</th> <th>Sr No</th>
<th>Strata Type & Depth</th> <th>Strata Type & Depth</th>
<th class="text-end">Client Qty</th> <th class="text-end">Client Qty</th>
<th class="text-end">Client Rate</th>
<th class="text-end">Client Amount</th>
<th class="text-end">Sub Contractor Qty</th> <th class="text-end">Sub Contractor Qty</th>
<th class="text-end">Difference</th> <th class="text-end">Sub Rate</th>
<th class="text-end">Sub Amount</th>
<th class="text-end">Qty Difference</th>
<th class="text-end">Rate Difference</th>
<th class="text-end">Amount Difference</th>
</tr> </tr>
</thead> </thead>
<tbody></tbody> <tbody></tbody>
</table> </table>
</div> </div>
@@ -162,13 +172,11 @@
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script> <script>
let barChart; let barChart;
let raBillChoice; let raBillChoice;
/* Load RA Bills */ /* Load RA Bills */
function loadRABills(){ function loadRABills(){
let subcontractor = document.getElementById("subcontractor").value let subcontractor = document.getElementById("subcontractor").value
let category = document.getElementById("category").value let category = document.getElementById("category").value
@@ -176,30 +184,21 @@
return; return;
if (!subcontractor || !category) { if (!subcontractor || !category) {
raBillChoice.clearStore(); raBillChoice.clearStore();
return; return;
} }
fetch(`/dashboard/api/get-ra-bills?subcontractor=${subcontractor}&category=${category}`) fetch(`/dashboard/api/get-ra-bills?subcontractor=${subcontractor}&category=${category}`)
.then(res => res.json()) .then(res => res.json())
.then(data => { .then(data => {
raBillChoice.clearStore(); raBillChoice.clearStore();
let choices = []; let choices = [];
data.ra_bills.forEach(function(bill){ data.ra_bills.forEach(function(bill){
choices.push({ choices.push({
value: bill, value: bill,
label: bill label: bill
}); });
}); });
raBillChoice.setChoices( raBillChoice.setChoices(
@@ -208,7 +207,6 @@
"label", "label",
true true
); );
}); });
} }
@@ -327,38 +325,87 @@
} }
/* TABLE */ /* TABLE */
function drawTable(data){ function drawTable(data) {
let html = "";
for (let i = 0; i < data.labels.length; i++) {
let html='';
for(let i=0;i<data.labels.length;i++){
const clientQty = Number(data.client_qty[i] || 0); const clientQty = Number(data.client_qty[i] || 0);
const subQty = Number(data.sub_qty[i] || 0); const subQty = Number(data.sub_qty[i] || 0);
const diff = clientQty - subQty;
html+=` const clientRate = Number(data.client_rate[i] || 0);
const subRate = Number(data.sub_rate[i] || 0);
const clientAmount = Number(data.client_amount[i] || 0);
const subAmount = Number(data.sub_amount[i] || 0);
const qtyDiff = Number(data.qty_difference[i] || 0 );
const rateDiff = Number(data.rate_difference[i] || 0 );
const amountDiff = Number(data.amount_difference[i] || 0 );
html += `
<tr> <tr>
<td class="text-center">${i + 1}</td> <td class="text-center">
<td>${data.labels[i]}</td> ${i + 1}
<td class="text-end">${data.client_qty[i]}</td> </td>
<td class="text-end">${data.sub_qty[i]}</td>
<td class="text-end fw-bold ${diff >= 0 ? 'text-success' : 'text-danger'}">${diff.toFixed(2)}</td> <td>
${data.labels[i]}
</td>
<!-- CLIENT -->
<td class="text-end">
${clientQty.toFixed(2)}
</td>
<td class="text-end">
${clientRate.toFixed(2)}
</td>
<td class="text-end fw-bold">
${clientAmount.toFixed(2)}
</td>
<!-- SUBCONTRACTOR -->
<td class="text-end">
${subQty.toFixed(2)}
</td>
<td class="text-end">
${subRate.toFixed(2)}
</td>
<td class="text-end fw-bold">
${subAmount.toFixed(2)}
</td>
<!-- DIFFERENCES -->
<td class="text-end fw-bold
${qtyDiff >= 0 ? 'text-success' : 'text-danger'}">
${qtyDiff.toFixed(2)}
</td>
<td class="text-end fw-bold
${rateDiff >= 0 ? 'text-success' : 'text-danger'}">
${rateDiff.toFixed(2)}
</td>
<td class="text-end fw-bold
${amountDiff >= 0 ? 'text-success' : 'text-danger'}">
${amountDiff.toFixed(2)}
</td>
</tr> </tr>
`; `;
} }
document.querySelector("#resultTable tbody").innerHTML = html; document.querySelector(
"#resultTable tbody"
).innerHTML = html;
} }
/* EVENTS */ /* EVENTS */
document.getElementById("subcontractor").addEventListener("change", loadRABills); document.getElementById("subcontractor").addEventListener("change", loadRABills);
document.getElementById("category").addEventListener("change", loadRABills); document.getElementById("category").addEventListener("change", loadRABills);
document.getElementById("searchBtn").addEventListener("click", loadDashboard); document.getElementById("searchBtn").addEventListener("click", loadDashboard);
document.getElementById("resetBtn").addEventListener("click", function () {location.reload();}); document.getElementById("resetBtn").addEventListener("click", function () {location.reload();});
document.addEventListener("DOMContentLoaded", function () { document.addEventListener("DOMContentLoaded", function () {

View File

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

View File

@@ -17,9 +17,11 @@ services:
build: . build: .
container_name: comparison_app container_name: comparison_app
restart: always restart: always
env_file:
- .env
environment: environment:
FLASK_ENV: development FLASK_ENV: production
FLASK_DEBUG: "True" FLASK_DEBUG: "False"
FLASK_HOST: "0.0.0.0" FLASK_HOST: "0.0.0.0"
FLASK_PORT: "5001" FLASK_PORT: "5001"

View File

@@ -1,3 +0,0 @@
2026-08-06 12:44:45 | INFO | User=System | IP=- | - | - | ======================================================================
2026-08-06 12:44:45 | INFO | User=System | IP=- | - | - | Application Started Successfully
2026-08-06 12:44:45 | INFO | User=System | IP=- | - | - | ======================================================================

View File

@@ -1,4 +1,5 @@
Flask Flask
ldap3
pandas pandas
openpyxl openpyxl
xlrd xlrd
@@ -9,4 +10,3 @@ xlsxwriter
matplotlib matplotlib
flask_sqlalchemy flask_sqlalchemy
flask_migrate flask_migrate
weasyprint

4
run.py
View File

@@ -1,15 +1,11 @@
from dotenv import load_dotenv from dotenv import load_dotenv
load_dotenv() load_dotenv()
from app import create_app from app import create_app
from app.services.db_service import db
import os import os
app = create_app() app = create_app()
if __name__ == "__main__": if __name__ == "__main__":
with app.app_context():
db.create_all()
app.run( app.run(
host=os.getenv("FLASK_HOST"), host=os.getenv("FLASK_HOST"),
port=int(os.getenv("FLASK_PORT")), port=int(os.getenv("FLASK_PORT")),