import hashlib
import os
import uuid
import re
from urllib.parse import urlparse
from datetime import datetime, timedelta
from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app, abort, jsonify
from flask_login import login_required, current_user
from sqlalchemy import func, or_, text, create_engine, and_, case
from decimal import Decimal
from openpyxl import load_workbook
from werkzeug.utils import secure_filename
from app import db, services

from app.utils import require_perm
from app.models import (
    Quote, QuoteItem, User, LeadService, Client, ClientBranch, AuditLog, Currency, CurrencyRateMaster,
    JobcardServiceFieldMaster,
    OperationsJobcard,
    OperationsJobcardService,
    OperationsJobcardFieldValue, VendorMaster, VendorPrivacyTombstone, EmployeeProfile, CompanyBranch,
    OperationsChecklistQuestion, OperationsChecklistResponse,
    OperationsJobcardTransferHistory, ProformaInvoice, Invoice, CreditNote,
    OperationsChecklistMaster, OperationsQCChecklistMaster, OperationsQCChecklistQuestion, OperationsQCChecklistResponse, OperationsJobcardAssignment,
    OperationsJobcardReopenRequest, OperationsJobcardClosureApprovalRequest,
    OperationsClientDeadlineExtensionRequest,
    OperationsClientDeadlineExtensionHistory,
    OperationsInternalProcessMaster, OperationsJobcardProcess,
    OperationsJobcardProcessAssignment,
    OperationsJobcardMTPEEntry,
    XbenchSeverityMaster, XbenchCategoryMaster, XbenchReport, XbenchReportCategory,
    OperationsWorkloadStandard, OperationsJobcardWorkloadEntry,
    OperationsKpiProfile, Designation, WorkforceGroup,
    PmServiceProductivityStandard, PmKpiProfile,
    SoftwareResourceProfile, SoftwareVendor, SoftwareAssignment, SoftwareTimeEntry, SoftwareSubtask,
    JobcardAdvanceBilling, SoftwareSaaSJobcardCost, SoftwareSaaSBilling, SoftwareSaaSSubscription,
)

operations_bp = Blueprint("operations", __name__, url_prefix="/operations", template_folder="../templates")

from app.services.operations_workload_service import (
    assignment_display_name,
    build_capacity_dashboard,
    build_operations_kpi_dashboard,
    build_workload_dashboard,
    create_workload_entry,
    missing_workload_assignments,
    required_assignments_for_jobcard,
    team_user_ids,
    workload_completion_summary,
    workload_filter_options,
)


from app.services.margin import get_margin_threshold_percent

from app.services.pm_kpi_service import (
    build_workload_dashboard as build_pm_workload_dashboard,
    build_capacity_dashboard as build_pm_capacity_dashboard,
    build_kpi_dashboard as build_pm_kpi_dashboard,
    filter_options as pm_filter_options,
    visible_pm_user_ids,
    pm_user_query,
)

FOURPLACES = Decimal("0.0001")

DEADLINE_EXTENSION_SALES_PERMISSION = "operations.deadline_extension.sales_approve"
DEADLINE_EXTENSION_ADMIN_PERMISSION = "operations.deadline_extension.admin_approve"
DEADLINE_EXTENSION_VIEW_PERMISSION = "operations.deadline_extension.view"
DEADLINE_EXTENSION_PENDING_STATUSES = ("Pending Sales", "Pending Admin")


def _deadline_extension_quote_owner(jobcard):
    """Return the Sales owner responsible for deadline-extension approval."""
    quote = getattr(jobcard, "quote", None)
    opportunity = getattr(quote, "opportunity", None) if quote else None

    if opportunity and opportunity.owner_id:
        return opportunity.owner

    # Safe legacy fallback for quotes whose opportunity owner is blank.
    if quote and quote.created_by_id:
        return quote.created_by

    return None


def _deadline_extension_history(request_row, action, from_status, to_status, remark=None):
    db.session.add(
        OperationsClientDeadlineExtensionHistory(
            request_id=request_row.id,
            action=action,
            from_status=from_status,
            to_status=to_status,
            remark=_clean(remark),
            acted_by_id=current_user.id,
            acted_at=_now_ist(),
        )
    )


def _complete_deadline_extension(request_row, approval_remark=None):
    """Atomically apply an approved extension to both jobcard and quote."""
    jobcard = request_row.jobcard
    quote = request_row.quote
    old_status = request_row.status

    jobcard.client_deadline = request_row.proposed_deadline
    quote.client_deadline = request_row.proposed_deadline
    request_row.status = "Approved"
    request_row.completed_at = _now_ist()

    _deadline_extension_history(
        request_row,
        "Deadline Extended",
        old_status,
        "Approved",
        approval_remark,
    )


REOPEN_REASON_OPTIONS = [
    "Client requested changes",
    "Correction in service line",
    "Vendor task rework",
    "Vendor amount correction",
    "Internal task rework",
    "Checklist correction",
    "Billing branch / closure detail correction",
    "Wrong jobcard closed",
    "Additional client work after Credit Note",
    "Other",
]
LANGUAGE_PAIRS = [
    "English to Hindi",
    "Hindi to English",
    "English to Tamil",
    "Tamil to English",
    "English to Telugu",
    "Telugu to English",
    "English to Bengali",
    "Bengali to English",
    "English to Marathi",
    "Marathi to English",
    "English to Gujarati",
    "Gujarati to English",
    "English to Kannada",
    "Kannada to English",
    "English to Malayalam",
    "Malayalam to English",
    "English to Punjabi",
    "Punjabi to English",
    "Other",
]

MT_NAMES = [
    "Google Translate",
    "Microsoft Translator",
    "DeepL",
    "Amazon Translate",
    "ChatGPT",
    "Gemini",
    "Custom MT Engine",
    "Other",
]



def _normalize_xbench_category_name(value):
    return re.sub(r"\s+", " ", str(value or "").strip()).casefold()


def _is_translation_service(service):
    if not service:
        return False
    values = [getattr(service, "service_name", None)]
    linked_service = getattr(service, "service", None)
    if linked_service:
        values.extend([
            getattr(linked_service, "name", None),
            getattr(linked_service, "service_name", None),
        ])
    return any("translation" in str(value or "").strip().casefold() for value in values)


def _save_xbench_report_file(uploaded_file):
    if not uploaded_file or not uploaded_file.filename:
        return None, None, None

    original_filename = secure_filename(uploaded_file.filename)
    extension = os.path.splitext(original_filename)[1].lower()
    if extension not in {".xlsx", ".xlsm"}:
        raise ValueError("Only Xbench Excel files in .xlsx or .xlsm format are allowed.")

    upload_root = os.path.join(current_app.root_path, "static", "uploads", "xbench_reports")
    os.makedirs(upload_root, exist_ok=True)

    stored_filename = f"{uuid.uuid4().hex}{extension}"
    absolute_path = os.path.join(upload_root, stored_filename)
    uploaded_file.save(absolute_path)

    relative_path = f"uploads/xbench_reports/{stored_filename}"
    return original_filename, stored_filename, relative_path


def _parse_xbench_summary(absolute_path):
    workbook = load_workbook(absolute_path, data_only=True, read_only=True)
    if not workbook.sheetnames:
        raise ValueError("The uploaded workbook does not contain any worksheet.")

    worksheet = workbook[workbook.sheetnames[0]]
    xbench_version = None
    summary_started = False
    categories = []

    for row in worksheet.iter_rows(min_row=1, max_row=min(worksheet.max_row, 80), values_only=True):
        first = str(row[0] or "").strip() if len(row) > 0 else ""
        second = str(row[1] or "").strip() if len(row) > 1 else ""
        fourth = str(row[3] or "").strip() if len(row) > 3 else ""

        if "apsic xbench" in fourth.casefold():
            xbench_version = fourth

        if first.casefold() == "selected qa checks":
            summary_started = True
            continue

        if not summary_started:
            continue

        if first.casefold() == "checklists":
            break

        if not first and not second:
            continue

        group_match = re.match(r"^(.*?)\s*\((\d+)\s+issues?\)\s*$", first, re.IGNORECASE)
        if not group_match or not second:
            continue

        group_name = group_match.group(1).strip()
        for raw_item in [item.strip() for item in second.split(",") if item.strip()]:
            item_match = re.match(r"^(.*?)\s*\((\d+)\)\s*$", raw_item)
            if item_match:
                category_name = item_match.group(1).strip()
                issue_count = int(item_match.group(2))
            else:
                category_name = raw_item.strip()
                issue_count = 0

            if category_name:
                categories.append({
                    "group": group_name,
                    "category": category_name,
                    "count": issue_count,
                })

    if not categories:
        raise ValueError("No Xbench category summary was found. Please upload the original exported Xbench QA Excel report.")

    return {
        "xbench_version": xbench_version,
        "categories": categories,
        "total_issue_count": sum(item["count"] for item in categories),
    }


def _active_translation_assignments(service):
    """Return active production assignees whose work is being quality checked."""
    if not service:
        return []

    return (
        OperationsJobcardAssignment.query
        .filter_by(jobcard_service_id=service.id, assignment_type="PRODUCTION")
        .filter(OperationsJobcardAssignment.status.notin_(["Replaced", "Cancelled", "Rejected"]))
        .order_by(OperationsJobcardAssignment.assigned_at.asc(), OperationsJobcardAssignment.id.asc())
        .all()
    )


def _translator_identity(production_assignment):
    if production_assignment.assigned_to_type == "VENDOR" and production_assignment.vendor:
        return {
            "name": production_assignment.vendor.name or f"Vendor #{production_assignment.vendor_id}",
            "type": "VENDOR",
            "vendor_id": production_assignment.vendor_id,
            "internal_user_id": None,
        }

    if production_assignment.assigned_to_type == "INTERNAL" and production_assignment.internal_user:
        return {
            "name": production_assignment.internal_user.name or f"User #{production_assignment.internal_user_id}",
            "type": "INTERNAL",
            "vendor_id": None,
            "internal_user_id": production_assignment.internal_user_id,
        }

    return {
        "name": f"Production assignment #{production_assignment.id}",
        "type": production_assignment.assigned_to_type or "UNKNOWN",
        "vendor_id": production_assignment.vendor_id,
        "internal_user_id": production_assignment.internal_user_id,
    }


def _record_xbench_submission(assignment, require_all=True):
    """Store translator-wise Xbench evidence.

    When require_all is False, only rows explicitly selected in the submitted form
    are saved. When require_all is True, every active production assignment must
    already have evidence or provide a new decision in the same request.
    """
    svc = assignment.jobcard_service
    if not _is_translation_service(svc):
        return True, None

    translators = _active_translation_assignments(svc)
    if not translators:
        return False, "No active production translator assignment was found for this Translation line item."

    existing_ids = {
        row.production_assignment_id
        for row in XbenchReport.query.filter_by(qc_assignment_id=assignment.id).all()
        if row.production_assignment_id
    }

    prepared = []
    saved_absolute_paths = []
    submitted_count = 0

    try:
        for production_assignment in translators:
            row_key = str(production_assignment.id)
            answer = _clean(request.form.get(f"xbench_answer_{row_key}")).lower()
            identity = _translator_identity(production_assignment)

            if not answer:
                if require_all and production_assignment.id not in existing_ids:
                    return False, f"Please save an Xbench report decision for translator: {identity['name']}."
                continue

            if answer not in {"yes", "no"}:
                return False, f"Please select Yes or No for translator: {identity['name']}."

            submitted_count += 1
            report = XbenchReport(
                jobcard_id=svc.jobcard_id,
                jobcard_service_id=svc.id,
                qc_assignment_id=assignment.id,
                production_assignment_id=production_assignment.id,
                translator_vendor_id=identity["vendor_id"],
                translator_internal_user_id=identity["internal_user_id"],
                translator_name_snapshot=identity["name"],
                translator_type_snapshot=identity["type"],
                is_uploaded=(answer == "yes"),
                uploaded_by_id=current_user.id,
                uploaded_at=_now_ist(),
                parsing_status="Not Required" if answer == "no" else "Pending",
            )

            if answer == "no":
                reason = _clean(request.form.get(f"xbench_reason_{row_key}"))
                if not reason:
                    return False, f"Please provide the reason for not uploading the Xbench report for {identity['name']}."
                report.not_uploaded_reason = reason
                prepared.append((report, None))
                continue

            uploaded_file = request.files.get(f"xbench_file_{row_key}")
            if not uploaded_file or not uploaded_file.filename:
                return False, f"Please upload the Xbench Excel report for {identity['name']}."

            original_filename, stored_filename, relative_path = _save_xbench_report_file(uploaded_file)
            absolute_path = os.path.join(current_app.root_path, "static", relative_path)
            saved_absolute_paths.append(absolute_path)
            parsed = _parse_xbench_summary(absolute_path)

            report.original_filename = original_filename
            report.stored_filename = stored_filename
            report.file_path = relative_path
            report.xbench_version = parsed["xbench_version"]
            report.total_issue_count = parsed["total_issue_count"]
            report.parsing_status = "Parsed"
            prepared.append((report, parsed))

        if not require_all and submitted_count == 0:
            return False, "Select Yes or No for at least one translator before saving Xbench evidence."

        detected_at = _now_ist()
        for report, parsed in prepared:
            db.session.add(report)
            db.session.flush()

            if not parsed:
                continue

            for item in parsed["categories"]:
                normalized_name = _normalize_xbench_category_name(item["category"])
                category = XbenchCategoryMaster.query.filter_by(normalized_name=normalized_name).first()

                if not category:
                    category = XbenchCategoryMaster(
                        category_name=item["category"],
                        normalized_name=normalized_name,
                        category_group=item["group"],
                        is_active=True,
                        is_system_generated=True,
                        first_detected_at=detected_at,
                        last_detected_at=detected_at,
                    )
                    db.session.add(category)
                    db.session.flush()
                else:
                    category.last_detected_at = detected_at
                    if not category.category_group:
                        category.category_group = item["group"]

                severity = category.severity
                db.session.add(XbenchReportCategory(
                    report_id=report.id,
                    category_id=category.id,
                    category_name_snapshot=category.category_name,
                    category_group_snapshot=item["group"],
                    issue_count=item["count"],
                    severity_id_snapshot=severity.id if severity else None,
                    severity_name_snapshot=severity.severity_name if severity else None,
                ))

        return True, None

    except Exception as exc:
        for absolute_path in saved_absolute_paths:
            try:
                if os.path.exists(absolute_path):
                    os.remove(absolute_path)
            except OSError:
                pass
        return False, str(exc)

def _is_mtpe_process_selected(process_ids):
    if not process_ids:
        return False

    rows = (
        OperationsInternalProcessMaster.query
        .filter(OperationsInternalProcessMaster.id.in_(process_ids))
        .all()
    )

    for row in rows:
        code = (row.code or "").lower()
        name = (row.name or "").lower()

        if code == "mtpe" or name == "mtpe" or "mtpe" in code or "mtpe" in name:
            return True

    return False

def _rate4(value):
    try:
        return Decimal(str(value or "0")).quantize(FOURPLACES)
    except Exception:
        return Decimal("0.0000")

def _parse_mtpe_accuracy(raw_value):
    raw_value = _clean(raw_value)

    if not raw_value:
        return None

    try:
        accuracy = Decimal(str(raw_value))
    except Exception:
        return "INVALID"

    if accuracy < 0 or accuracy > 100:
        return "INVALID"

    return accuracy

def _get_operations_users():
    users = (
        User.query
        .join(EmployeeProfile, EmployeeProfile.user_id == User.id)
        .filter(User.is_active == True)
        .filter(func.lower(EmployeeProfile.department) == "operations")
        .order_by(User.name.asc())
        .all()
    )

    if not users:
        users = User.query.filter_by(is_active=True).order_by(User.name.asc()).all()

    return users

def _now_ist():
    return datetime.utcnow() + timedelta(hours=5, minutes=30)

def _dec(value, default="0"):
    try:
        return Decimal(str(value if value is not None else default))
    except Exception:
        return Decimal(str(default))


def _currency_code(value):
    code = str(value or "INR").strip().upper()
    # Historical quotes/vendors can store EURO while Currency Rate Master
    # uses the ISO code EUR. Keep both forms interoperable.
    return {"EURO": "EUR", "EUROS": "EUR", "€": "EUR"}.get(code, code)


def _currency_to_inr_rate(currency_code, conversion_date=None):
    """
    Return INR conversion rate for 1 unit of currency.

    Historical data can contain EURO while the rate master may contain EUR.
    Use simple exact lookups over known aliases so this works reliably across
    older SQLAlchemy/MySQL combinations as well as current installations.
    """
    code = _currency_code(currency_code)

    if code == "INR":
        return Decimal("1")

    if conversion_date is None:
        conversion_date = datetime.utcnow()

    year = conversion_date.year
    month = conversion_date.month

    lookup_codes = [code]
    if code == "EUR":
        lookup_codes = ["EUR", "EURO", "EUROS"]

    # Prefer the transaction month/year.  Try aliases one-by-one instead of
    # using CASE/UPPER/IN expressions, which can behave differently on older
    # SQLAlchemy/MySQL stacks.
    row = None
    for candidate in lookup_codes:
        row = (
            CurrencyRateMaster.query
            .filter_by(year=year, month=month, currency_code=candidate)
            .order_by(CurrencyRateMaster.id.desc())
            .first()
        )
        if row and row.rate_to_inr:
            rate = _dec(row.rate_to_inr)
            if rate > 0:
                return rate

    # Fallback to the latest configured rate for any accepted alias.
    latest = None
    for candidate in lookup_codes:
        candidate_row = (
            CurrencyRateMaster.query
            .filter_by(currency_code=candidate)
            .order_by(
                CurrencyRateMaster.year.desc(),
                CurrencyRateMaster.month.desc(),
                CurrencyRateMaster.id.desc(),
            )
            .first()
        )
        if candidate_row:
            if latest is None or (candidate_row.year, candidate_row.month, candidate_row.id) > (latest.year, latest.month, latest.id):
                latest = candidate_row

    if latest and latest.rate_to_inr:
        rate = _dec(latest.rate_to_inr)
        if rate > 0:
            return rate

    current_app.logger.warning(
        "Currency conversion rate not found currency=%s normalized=%s year=%s month=%s aliases=%s",
        currency_code, code, year, month, lookup_codes
    )
    return None

def _amount_to_inr(amount, currency_code, conversion_date=None):
    rate = _currency_to_inr_rate(currency_code, conversion_date)

    if rate is None:
        return None

    return _dec(amount) * rate



def _assignment_vendor_currency(assignment):
    vendor = getattr(assignment, "vendor", None)

    if not vendor and getattr(assignment, "vendor_id", None):
        vendor = VendorMaster.query.get(assignment.vendor_id)

    return _currency_code(getattr(vendor, "currency", None))

def get_pms_engine():
    external_uri = current_app.config.get("PMS_DB_URI")
    if not external_uri:
        raise Exception("PMS_DB_URI is not configured.")
    return create_engine(
        external_uri,
        pool_pre_ping=True,
        fast_executemany=False
    )


def fetch_pms_vendors():
    engine = get_pms_engine()

    sql = text("""
        SELECT 
            TranslatorId,
            Name,
            Status,
            Email,
            Phone,
            Currency,
            ProfileSummary
        FROM Usermasters
        WHERE Status = 1
            AND Name IS NOT NULL
            AND LTRIM(RTRIM(Name)) <> ''
        ORDER BY Name ASC
    """)

    with engine.begin() as conn:
        return conn.execute(sql).mappings().all()

def _redirect_after_internal_assignment_transfer(assignment):
    if assignment.assignment_type == "QC":
        return redirect(url_for("operations.qc_tasks"))

    return redirect(url_for("operations.internal_tasks"))

def push_job_to_pms(jobcard, service_row, vendor, wordcount, rate, flat_rate, deadline, special_instruction, checklist_url=None, assignment_id=None):
    engine = get_pms_engine()

    quote = jobcard.quote
    quote_item = service_row.quote_item

    vendor_currency = (
        getattr(vendor, "currency", None)
        or (quote.currency if quote else None)
        or "INR"
    )
    vendor_currency = str(vendor_currency).strip().upper()

    # Convert values safely
    qty_decimal = Decimal(str(wordcount or 0))
    rate_decimal = _rate4(rate)
    is_flat_rate = 1 if int(flat_rate or 0) == 1 else 0

    # TotalAmount logic:
    # If flat rate is checked, TotalAmount = Rate
    # Otherwise TotalAmount = Rate * Qty
    if is_flat_rate:
        total_amount = rate_decimal
    else:
        total_amount = qty_decimal * rate_decimal

    sql = text("""
        INSERT INTO jobs
        (
            Jobcardno, Nexusjobcard, Language, Wordcount, Rate, FlatRate,
            TotalAmount, CurrencyType, Deadline, PMName, SpecialInstruction,
            CheckListLinks,
            jobstatus, IsDeleted, CreatedOn, ModifiedOn,
            RecordId, AssignId, TransId, Isinvited, InvoiceId,
            PmEmail, IsSingleAssignment, InvitationId, CheckListStatus, BillStatus
        )
        VALUES
        (
            :jobcard_no, :nexus_jobcard, :language, :wordcount, :rate, :flat_rate,
            :total_amount, :currency_type, :deadline, :pm_name, :special_instruction,
            :checklist_links,
            :jobstatus, :is_deleted, :created_on, :modified_on,
            :record_id, :assign_id, :trans_id, :is_invited, :invoice_id,
            :pm_email, :is_single_assignment, :invitation_id, :checklist_status, :bill_status
        )
    """)

    parsed_deadline = None

    if deadline:
        parsed_deadline = datetime.strptime(
            deadline,
            "%Y-%m-%dT%H:%M"
        ).strftime("%Y-%m-%d %H:%M:%S")

    with engine.begin() as conn:
        now = _now_ist().replace(microsecond=0)

        conn.execute(sql, {
            # Existing numeric PMS jobcard number
            "jobcard_no": int(jobcard.jobcard_code.replace("JC-", "")),

            # New Nexus jobcard column
            "nexus_jobcard": str(jobcard.jobcard_code or "")[:100],

            "language": str(quote_item.description if quote_item else service_row.service_name or "")[:500],
            "wordcount": int(qty_decimal or 0),
            "rate": float(rate_decimal or 0),
            "flat_rate": is_flat_rate,
            "total_amount": float(total_amount or 0),

            "currency_type": vendor_currency[:50],
            "deadline": parsed_deadline,
            "pm_name": str(current_user.name or "")[:100],

            # Only user-entered instruction, no checklist URL appended here
            "special_instruction": str(special_instruction or "")[:4000],

            # Checklist URL goes to dedicated PMS column
            "checklist_links": str(checklist_url or "")[:1000],

            "jobstatus": "Assigned",
            "is_deleted": 0,

            "created_on": now.strftime("%Y-%m-%d %H:%M:%S"),
            "modified_on": now.strftime("%Y-%m-%d %H:%M:%S"),

            "record_id": 0,
            "assign_id": int(assignment_id or 0),
            "trans_id": int(vendor.external_translator_id or 0),

            "is_invited": 0,
            "invoice_id": 0,

            "pm_email": str(current_user.email or "")[:255],

            "is_single_assignment": 1,
            "invitation_id": 0,
            "checklist_status": 1,
            "bill_status": 0,
        })

def _normalize_pms_status(value):
    return str(value or "").strip().lower()


def _fetch_pms_status_for_assignment(assignment):
    """
    Fetch one external PMS job status using CheckListLinks.
    We use CheckListLinks because it is unique per Nexus assignment.
    """
    if not assignment.external_checklist_url:
        return None, "No external checklist URL found for this assignment."

    engine = get_pms_engine()

    sql = text("""
        SELECT TOP 1
            jobstatus,
            ModifiedOn,
            CheckListLinks
        FROM jobs
        WHERE LTRIM(RTRIM(ISNULL(CheckListLinks, ''))) = :checklist_url
          AND ISNULL(IsDeleted, 0) = 0
        ORDER BY ModifiedOn DESC
    """)

    with engine.begin() as conn:
        row = conn.execute(sql, {
            "checklist_url": str(assignment.external_checklist_url).strip()
        }).mappings().first()

    if not row:
        return None, "No matching PMS job found."

    return row, None

def delete_pms_job_for_replaced_assignment(assignment):
    """
    Soft-delete the linked TransApp/PMS job when an external vendor assignment
    is replaced in Nexus.

    Matching is done using CheckListLinks because it is unique per Nexus assignment.
    """
    checklist_url = str(getattr(assignment, "external_checklist_url", "") or "").strip()

    if not checklist_url:
        return {
            "deleted": 0,
            "skipped": 1,
            "message": "No external checklist URL found for this assignment."
        }

    engine = get_pms_engine()

    sql = text("""
        UPDATE jobs
        SET
            IsDeleted = 1,
            jobstatus = :jobstatus,
            ModifiedOn = :modified_on
        WHERE LTRIM(RTRIM(ISNULL(CheckListLinks, ''))) = :checklist_url
          AND ISNULL(IsDeleted, 0) = 0
    """)

    now = _now_ist().replace(microsecond=0)

    with engine.begin() as conn:
        result = conn.execute(sql, {
            "jobstatus": "Cancelled",
            "modified_on": now.strftime("%Y-%m-%d %H:%M:%S"),
            "checklist_url": checklist_url,
        })

    deleted_count = result.rowcount or 0

    if deleted_count > 0:
        return {
            "deleted": deleted_count,
            "skipped": 0,
            "message": f"{deleted_count} TransApp/PMS job line deleted."
        }

    return {
        "deleted": 0,
        "skipped": 1,
        "message": "No active matching TransApp/PMS job line found."
    }

def _apply_pms_status_to_assignment(assignment, pms_status):
    """
    Applies PMS jobstatus to Nexus assignment.

    PMS status expected:
    - Assigned
    - Completed

    We only auto-complete Nexus when PMS is completed.
    """
    normalized_status = _normalize_pms_status(pms_status)

    if normalized_status not in ["completed", "complete"]:
        return False, f"PMS status is '{pms_status}', no Nexus update required."

    if assignment.status in ["Completed", "Cancelled", "Replaced", "Rejected"]:
        return False, f"Nexus assignment already {assignment.status}."

    svc = assignment.jobcard_service
    jobcard = svc.jobcard

    assignment.status = "Completed"
    assignment.completed_at = _now_ist()

    completed_qty = _completed_qty_for_service(svc)
    required_qty = Decimal(str(svc.total_quantity or 0))

    if completed_qty >= required_qty:
        if not _has_pending_qc(svc):
            svc.status = "Completed"
            svc.completed_at = svc.completed_at or _now_ist()
        else:
            svc.status = "QC Pending"
    else:
        _refresh_service_assignment_status(svc)
        svc.completed_at = None

    _refresh_jobcard_status(jobcard)

    return True, "Assignment marked Completed from PMS."
        
def update_pms_jobs_to_raise_invoice(jobcard):
    """
    When a Nexus jobcard is closed / Ready For Billing,
    update all linked external PMS jobs to RaiseInvoice.

    Matching is done through CheckListLinks because it is unique per Nexus assignment.
    """
    vendor_assignments = (
        OperationsJobcardAssignment.query
        .join(
            OperationsJobcardService,
            OperationsJobcardService.id == OperationsJobcardAssignment.jobcard_service_id
        )
        .filter(OperationsJobcardService.jobcard_id == jobcard.id)
        .filter(OperationsJobcardAssignment.assignment_type == "PRODUCTION")
        .filter(OperationsJobcardAssignment.assigned_to_type == "VENDOR")
        .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"]))
        .filter(OperationsJobcardAssignment.external_checklist_url.isnot(None))
        .all()
    )

    if not vendor_assignments:
        return {
            "updated": 0,
            "skipped": 0,
            "errors": []
        }

    engine = get_pms_engine()

    sql = text("""
        UPDATE jobs
        SET
            jobstatus = :jobstatus,
            ModifiedOn = :modified_on
        WHERE LTRIM(RTRIM(ISNULL(CheckListLinks, ''))) = :checklist_url
          AND ISNULL(IsDeleted, 0) = 0
          AND ISNULL(jobstatus, '') <> :jobstatus
    """)

    updated_count = 0
    skipped_count = 0
    errors = []

    now = _now_ist().replace(microsecond=0)

    with engine.begin() as conn:
        for assignment in vendor_assignments:
            checklist_url = str(assignment.external_checklist_url or "").strip()

            if not checklist_url:
                skipped_count += 1
                continue

            try:
                result = conn.execute(sql, {
                    "jobstatus": "RaiseInvoice",
                    "modified_on": now.strftime("%Y-%m-%d %H:%M:%S"),
                    "checklist_url": checklist_url,
                })

                if result.rowcount and result.rowcount > 0:
                    updated_count += result.rowcount
                else:
                    skipped_count += 1

            except Exception as e:
                skipped_count += 1
                errors.append(f"Assignment #{assignment.id}: {str(e)}")

    return {
        "updated": updated_count,
        "skipped": skipped_count,
        "errors": errors
    }

def _clean(v):
    return (v or "").strip()


def _safe_operations_return_url(default_endpoint, **default_values):
    """
    Return to the page that submitted the form when it belongs to this app.
    A hidden `return_to` value takes priority, followed by the HTTP referrer.
    """
    fallback = url_for(default_endpoint, **default_values)
    candidate = _clean(request.form.get("return_to")) or _clean(request.args.get("return_to")) or request.referrer

    if not candidate:
        return fallback

    try:
        parsed = urlparse(candidate)
        current_host = (request.host or "").lower()
        candidate_host = (parsed.netloc or "").lower()

        if parsed.scheme and parsed.scheme not in ("http", "https"):
            return fallback
        if candidate_host and candidate_host != current_host:
            return fallback

        if candidate_host:
            path = parsed.path or "/"
            if parsed.query:
                path += "?" + parsed.query
            if parsed.fragment:
                path += "#" + parsed.fragment
            return path

        if candidate.startswith("/") and not candidate.startswith("//"):
            return candidate
    except Exception:
        return fallback

    return fallback


XBENCH_SEVERITY_SCALE = (
    {"score": 1, "name": "Minor", "code": "MINOR", "color": "#64748B"},
    {"score": 2, "name": "Low", "code": "LOW", "color": "#0EA5E9"},
    {"score": 3, "name": "Medium", "code": "MEDIUM", "color": "#F59E0B"},
    {"score": 4, "name": "Critical", "code": "CRITICAL", "color": "#F97316"},
    {"score": 5, "name": "Highly Critical", "code": "HIGHLY_CRITICAL", "color": "#DC2626"},
)


def _ensure_xbench_severity_scale():
    """Create/update the fixed 1-5 Xbench criticality scale."""
    changed = False

    for row in XBENCH_SEVERITY_SCALE:
        severity = XbenchSeverityMaster.query.filter(
            or_(
                XbenchSeverityMaster.severity_code == row["code"],
                func.lower(XbenchSeverityMaster.severity_name) == row["name"].lower(),
            )
        ).order_by(XbenchSeverityMaster.id.asc()).first()

        if not severity:
            severity = XbenchSeverityMaster(
                severity_name=row["name"],
                severity_code=row["code"],
                severity_rank=row["score"],
                color_code=row["color"],
                is_active=True,
                created_at=_now_ist(),
                updated_at=_now_ist(),
            )
            db.session.add(severity)
            changed = True
            continue

        row_changed = False
        if severity.severity_name != row["name"]:
            severity.severity_name = row["name"]
            row_changed = True
        if severity.severity_code != row["code"]:
            severity.severity_code = row["code"]
            row_changed = True
        if severity.severity_rank != row["score"]:
            severity.severity_rank = row["score"]
            row_changed = True
        if severity.color_code != row["color"]:
            severity.color_code = row["color"]
            row_changed = True
        if not severity.is_active:
            severity.is_active = True
            row_changed = True

        if row_changed:
            severity.updated_at = _now_ist()
            changed = True

    if changed:
        db.session.flush()


def _jobcard_code_next():
    last = OperationsJobcard.query.order_by(OperationsJobcard.id.desc()).first()
    nxt = (last.id + 1) if last else 1
    return f"JC-{nxt:06d}"


def _save_jobcard_file(file_obj):
    if not file_obj or not file_obj.filename:
        return None

    upload_root = os.path.join(current_app.root_path, "static", "uploads", "jobcards")
    os.makedirs(upload_root, exist_ok=True)

    ext = os.path.splitext(file_obj.filename)[1]
    unique_name = f"{uuid.uuid4().hex}{ext}"
    abs_path = os.path.join(upload_root, unique_name)
    file_obj.save(abs_path)

    return f"uploads/jobcards/{unique_name}"

def _ensure_jobcard_field_values_for_service(jc_service):
    """
    Ensures field value rows exist for a jobcard service line.
    Useful when quote items are added after jobcard creation.
    """
    if not jc_service or not jc_service.service_id:
        return

    fields = (
        JobcardServiceFieldMaster.query
        .filter_by(service_id=jc_service.service_id, is_active=True)
        .order_by(
            JobcardServiceFieldMaster.sort_order.asc(),
            JobcardServiceFieldMaster.id.asc()
        )
        .all()
    )

    if not fields:
        return

    existing_field_master_ids = {
        row.field_master_id
        for row in OperationsJobcardFieldValue.query
        .filter_by(jobcard_service_id=jc_service.id)
        .all()
    }

    for field in fields:
        if field.id in existing_field_master_ids:
            continue

        db.session.add(OperationsJobcardFieldValue(
            jobcard_service_id=jc_service.id,
            field_master_id=field.id,
            field_key=field.field_key,
            field_value=None,
            file_path=None,
        ))


def _missing_required_jobcard_fields(jc_service):
    """
    Returns active required fields that are missing value/file for a jobcard service line.
    """
    if not jc_service or not jc_service.service_id:
        return []

    _ensure_jobcard_field_values_for_service(jc_service)

    rows = (
        db.session.query(JobcardServiceFieldMaster, OperationsJobcardFieldValue)
        .outerjoin(
            OperationsJobcardFieldValue,
            (OperationsJobcardFieldValue.field_master_id == JobcardServiceFieldMaster.id)
            & (OperationsJobcardFieldValue.jobcard_service_id == jc_service.id)
        )
        .filter(JobcardServiceFieldMaster.service_id == jc_service.service_id)
        .filter(JobcardServiceFieldMaster.is_active == True)
        .filter(JobcardServiceFieldMaster.is_required == True)
        .order_by(
            JobcardServiceFieldMaster.sort_order.asc(),
            JobcardServiceFieldMaster.id.asc()
        )
        .all()
    )

    missing = []

    for field, value_row in rows:
        has_value = False

        if value_row:
            has_value = bool(
                (value_row.field_value or "").strip()
                or (value_row.file_path or "").strip()
            )

        if not has_value:
            missing.append(field)

    return missing


def _jobcard_service_fields_grouped(jc_service):
    """
    Returns active field masters and existing values for display/edit.
    """
    if not jc_service or not jc_service.service_id:
        return []

    _ensure_jobcard_field_values_for_service(jc_service)

    rows = (
        db.session.query(JobcardServiceFieldMaster, OperationsJobcardFieldValue)
        .outerjoin(
            OperationsJobcardFieldValue,
            (OperationsJobcardFieldValue.field_master_id == JobcardServiceFieldMaster.id)
            & (OperationsJobcardFieldValue.jobcard_service_id == jc_service.id)
        )
        .filter(JobcardServiceFieldMaster.service_id == jc_service.service_id)
        .filter(JobcardServiceFieldMaster.is_active == True)
        .order_by(
            JobcardServiceFieldMaster.sort_order.asc(),
            JobcardServiceFieldMaster.id.asc()
        )
        .all()
    )

    return rows

def _missing_required_fields_for_services_bulk(services):
    """
    Bulk version of _missing_required_jobcard_fields().
    Avoids running separate queries for every service line on view_jobcard.
    """
    result = {}

    services = services or []
    service_db_ids = [s.id for s in services]
    service_master_ids = list({s.service_id for s in services if s.service_id})

    for svc in services:
        result[svc.id] = []

    if not service_db_ids or not service_master_ids:
        return result

    rows = (
        db.session.query(
            OperationsJobcardService.id.label("jobcard_service_id"),
            JobcardServiceFieldMaster
        )
        .join(
            JobcardServiceFieldMaster,
            JobcardServiceFieldMaster.service_id == OperationsJobcardService.service_id
        )
        .outerjoin(
            OperationsJobcardFieldValue,
            and_(
                OperationsJobcardFieldValue.jobcard_service_id == OperationsJobcardService.id,
                OperationsJobcardFieldValue.field_master_id == JobcardServiceFieldMaster.id
            )
        )
        .filter(OperationsJobcardService.id.in_(service_db_ids))
        .filter(JobcardServiceFieldMaster.service_id.in_(service_master_ids))
        .filter(JobcardServiceFieldMaster.is_active == True)
        .filter(JobcardServiceFieldMaster.is_required == True)
        .filter(
            or_(
                OperationsJobcardFieldValue.id.is_(None),
                and_(
                    or_(
                        OperationsJobcardFieldValue.field_value.is_(None),
                        OperationsJobcardFieldValue.field_value == ""
                    ),
                    or_(
                        OperationsJobcardFieldValue.file_path.is_(None),
                        OperationsJobcardFieldValue.file_path == ""
                    )
                )
            )
        )
        .order_by(
            OperationsJobcardService.id.asc(),
            JobcardServiceFieldMaster.sort_order.asc(),
            JobcardServiceFieldMaster.id.asc()
        )
        .all()
    )

    for jobcard_service_id, field in rows:
        result.setdefault(jobcard_service_id, []).append(field)

    return result


def _remaining_qty_for_services_bulk(services, assignments_by_service=None):
    """
    Bulk version of _remaining_qty_for_service().
    Uses already-loaded assignments where possible.
    """
    result = {}

    services = services or []

    if assignments_by_service is None:
        service_ids = [s.id for s in services]
        assignments_by_service = _assignments_by_service(service_ids)

    for svc in services:
        total_qty = Decimal(str(svc.total_quantity or 0))
        assigned_qty = Decimal("0")

        for a in assignments_by_service.get(svc.id, []):
            if (
                a.assignment_type == "PRODUCTION"
                and a.parent_assignment_id is None
                and a.status not in ["Replaced", "Cancelled", "Rejected"]
            ):
                assigned_qty += Decimal(str(a.assigned_qty or 0))

        remaining = total_qty - assigned_qty

        if remaining < 0:
            remaining = Decimal("0")

        if assigned_qty > total_qty:
            svc.status = "Over Assigned"

        result[svc.id] = remaining

    return result


def _jobcard_commercial_overview_fast(jobcard, assignments_by_service=None, process_assignment_rows=None):
    """
    Commercial overview in INR.

    Quote subtotal is converted from quote currency to INR.
    External vendor rates are converted from vendor currency to INR.
    Profit margin is calculated only in INR.
    """
    if assignments_by_service is None:
        services = jobcard.services.order_by(OperationsJobcardService.id.asc()).all()
        service_ids = [s.id for s in services]
        assignments_by_service = _assignments_by_service(service_ids)

    quote_currency = _currency_code(jobcard.quote.currency if jobcard.quote else "INR")
    quote_amount_original = Decimal("0")
    quote_conversion_date = (
        jobcard.quote.created_at
        if jobcard.quote and getattr(jobcard.quote, "created_at", None)
        else getattr(jobcard, "created_at", None)
    )

    # Recurring SaaS Jobcards represent one billing cycle, not the full source
    # quotation. Use the exact SaaS billing amount for margin calculations.
    saas_billing_row = SoftwareSaaSBilling.query.filter_by(jobcard_id=jobcard.id).first()
    if saas_billing_row:
        quote_amount_original = _dec(saas_billing_row.total_amount)
        if saas_billing_row.subscription:
            quote_currency = _currency_code(saas_billing_row.subscription.currency or quote_currency)
        quote_conversion_date = saas_billing_row.billing_date or quote_conversion_date
    elif jobcard.quote:
        quote_amount_original = (
            _dec(jobcard.quote.subtotal) - _dec(jobcard.quote.discount)
        )
        if quote_amount_original < 0:
            quote_amount_original = Decimal("0")

    quote_amount_ex_tax = _amount_to_inr(
        quote_amount_original,
        quote_currency,
        quote_conversion_date
    )

    missing_currency_rates = []

    if quote_amount_ex_tax is None:
        missing_currency_rates.append(quote_currency)
        quote_amount_ex_tax = Decimal("0")

    total_vendor_costs = Decimal("0")

    for assignment_rows in assignments_by_service.values():
        for a in assignment_rows:
            if (
                a.assignment_type == "PRODUCTION"
                and a.assigned_to_type == "VENDOR"
                and a.status not in ["Replaced", "Cancelled", "Rejected"]
            ):
                rate = _dec(a.rate)
                qty = _dec(a.assigned_qty)

                vendor_cost_original = rate if a.flat_rate else qty * rate
                vendor_currency = _assignment_vendor_currency(a)

                vendor_conversion_date = (
                    getattr(a, "assigned_at", None)
                    or getattr(a, "created_at", None)
                    or getattr(jobcard, "created_at", None)
                )

                vendor_cost_inr = _amount_to_inr(
                    vendor_cost_original,
                    vendor_currency,
                    vendor_conversion_date
                )

                if vendor_cost_inr is None:
                    missing_currency_rates.append(vendor_currency)
                    continue

                total_vendor_costs += vendor_cost_inr

    if process_assignment_rows is None:
        process_assignment_rows = (
            OperationsJobcardProcessAssignment.query
            .join(
                OperationsJobcardProcess,
                OperationsJobcardProcess.id == OperationsJobcardProcessAssignment.jobcard_process_id
            )
            .filter(OperationsJobcardProcess.jobcard_id == jobcard.id)
            .filter(OperationsJobcardProcessAssignment.assigned_to_type == "VENDOR")
            .filter(OperationsJobcardProcessAssignment.status.notin_(["Cancelled"]))
            .all()
        )

    for a in process_assignment_rows:
        if a.assigned_to_type != "VENDOR" or a.status in ["Cancelled"]:
            continue

        rate = _dec(a.rate)
        qty = _dec(a.assigned_qty)

        vendor_cost_original = rate if a.flat_rate else qty * rate
        vendor_currency = _assignment_vendor_currency(a)

        vendor_conversion_date = (
                    getattr(a, "assigned_at", None)
                    or getattr(a, "created_at", None)
                    or getattr(jobcard, "created_at", None)
                )

        vendor_cost_inr = _amount_to_inr(
            vendor_cost_original,
            vendor_currency,
            vendor_conversion_date
        )

        if vendor_cost_inr is None:
            missing_currency_rates.append(vendor_currency)
            continue

        total_vendor_costs += vendor_cost_inr

    # Software SaaS vendor invoices/costs are stored separately from the
    # Translation vendor assignment tables. Include them in the same INR
    # commercial overview so profit margin uses Currency Rate Master.
    software_service_ids = [svc.id for svc in jobcard.services.all()]
    if software_service_ids:
        software_cost_rows = (SoftwareSaaSJobcardCost.query
                              .filter(SoftwareSaaSJobcardCost.jobcard_service_id.in_(software_service_ids))
                              .all())
        for cost_row in software_cost_rows:
            vendor_currency = _currency_code(
                cost_row.vendor_currency
                or (cost_row.vendor.currency if cost_row.vendor else "INR")
            )
            if cost_row.vendor_cost_inr is not None and _dec(cost_row.conversion_rate_to_inr) > 0:
                total_vendor_costs += _dec(cost_row.vendor_cost_inr)
                continue
            converted = _amount_to_inr(
                cost_row.vendor_cost,
                vendor_currency,
                getattr(cost_row, "updated_at", None) or getattr(jobcard, "created_at", None)
            )
            if converted is None:
                missing_currency_rates.append(vendor_currency)
                continue
            total_vendor_costs += converted

    profit_amount = quote_amount_ex_tax - total_vendor_costs

    if quote_amount_ex_tax > 0:
        profit_margin_pct = (profit_amount / quote_amount_ex_tax) * Decimal("100")
    else:
        profit_margin_pct = None

    return {
        "currency": "INR",
        "quote_currency": quote_currency,
        "quote_amount_original": quote_amount_original,
        "quote_amount_ex_tax": quote_amount_ex_tax,
        "total_vendor_costs": total_vendor_costs,
        "profit_amount": profit_amount,
        "profit_margin_pct": profit_margin_pct,
        "missing_currency_rates": sorted(set(missing_currency_rates)),
    }

def _refresh_jobcard_status(jobcard):
    if jobcard.status == "Closure Approval Pending":
        return
    
    services = jobcard.services.all()

    if not services:
        jobcard.status = "Submitted"
        return

    statuses = [s.status for s in services]

    if all(s == "Completed" for s in statuses):
        jobcard.status = "Completed"

    elif any(s == "QC Pending" for s in statuses):
        jobcard.status = "QC Pending"

    elif any(s == "Completed" for s in statuses):
        jobcard.status = "In Progress"

    elif all(s == "Assigned" for s in statuses):
        jobcard.status = "Assigned"

    elif any(s == "Over Assigned" for s in statuses):
        jobcard.status = "Over Assigned"

    elif any(s in ("Assigned", "Partially Assigned") for s in statuses):
        jobcard.status = "Partially Assigned"

    else:
        jobcard.status = "Submitted"

def _assigned_qty_for_service(svc):
    """
    Counts only PM/top-level production assignment qty.
    Child delegated assignments must not increase service assigned qty.
    """
    total = (
        db.session.query(
            func.coalesce(func.sum(OperationsJobcardAssignment.assigned_qty), 0)
        )
        .filter(
            OperationsJobcardAssignment.jobcard_service_id == svc.id,
            OperationsJobcardAssignment.assignment_type == "PRODUCTION",
            OperationsJobcardAssignment.parent_assignment_id.is_(None),
            OperationsJobcardAssignment.status.notin_(["Replaced", "Cancelled", "Rejected"])
        )
        .scalar()
    )

    return Decimal(str(total or 0))

def _active_child_assignments(parent_assignment):
    return (
        OperationsJobcardAssignment.query
        .filter_by(parent_assignment_id=parent_assignment.id)
        .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"]))
        .order_by(OperationsJobcardAssignment.id.asc())
        .all()
    )


def _delegated_qty_for_assignment(parent_assignment):
    total = (
        db.session.query(
            func.coalesce(func.sum(OperationsJobcardAssignment.assigned_qty), 0)
        )
        .filter(
            OperationsJobcardAssignment.parent_assignment_id == parent_assignment.id,
            OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"])
        )
        .scalar()
    )

    return Decimal(str(total or 0))


def _remaining_delegatable_qty(parent_assignment):
    assigned_qty = Decimal(str(parent_assignment.assigned_qty or 0))
    delegated_qty = _delegated_qty_for_assignment(parent_assignment)

    remaining = assigned_qty - delegated_qty

    if remaining < 0:
        remaining = Decimal("0")

    return remaining

def _delegation_summary_for_assignment(parent_assignment):
    child_rows = _active_child_assignments(parent_assignment)

    delegated_qty = Decimal("0")
    completed_qty = Decimal("0")

    for child in child_rows:
        child_qty = Decimal(str(child.assigned_qty or 0))
        delegated_qty += child_qty

        if child.status == "Completed":
            completed_qty += child_qty

    parent_qty = Decimal(str(parent_assignment.assigned_qty or 0))
    remaining_qty = parent_qty - delegated_qty

    if remaining_qty < 0:
        remaining_qty = Decimal("0")

    return {
        "child_rows": child_rows,
        "parent_qty": parent_qty,
        "delegated_qty": delegated_qty,
        "completed_qty": completed_qty,
        "remaining_qty": remaining_qty,
    }


def _completed_qty_for_service(svc):
    """
    Calculates completed qty without double-counting delegated child tasks.

    Logic:
    - If top-level assignment has no child tasks:
      count full qty if parent is Completed.
    - If top-level assignment has child tasks:
      count completed child qty.
      Also count parent's non-delegated remaining qty if parent itself is Completed.
    """
    total_completed = Decimal("0")

    top_level_rows = (
        OperationsJobcardAssignment.query
        .filter_by(
            jobcard_service_id=svc.id,
            assignment_type="PRODUCTION"
        )
        .filter(OperationsJobcardAssignment.parent_assignment_id.is_(None))
        .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"]))
        .all()
    )

    for parent in top_level_rows:
        parent_qty = Decimal(str(parent.assigned_qty or 0))
        child_rows = _active_child_assignments(parent)

        if not child_rows:
            if parent.status == "Completed":
                total_completed += parent_qty
            continue

        delegated_qty = Decimal("0")

        for child in child_rows:
            child_qty = Decimal(str(child.assigned_qty or 0))
            delegated_qty += child_qty

            if child.status == "Completed":
                total_completed += child_qty

        parent_self_qty = parent_qty - delegated_qty
        if parent_self_qty < 0:
            parent_self_qty = Decimal("0")

        if parent_self_qty > 0 and parent.status == "Completed":
            total_completed += parent_self_qty

    return total_completed

def _remaining_qty_for_service(svc):

    total_qty = Decimal(str(svc.total_quantity or 0))

    assigned_qty = _assigned_qty_for_service(svc)

    remaining = total_qty - assigned_qty

    # Prevent negative remaining after quote edit sync
    if remaining < 0:
        remaining = Decimal("0")

    # Auto-mark over-assigned services
    if assigned_qty > total_qty:
        svc.status = "Over Assigned"

    return remaining

def _assignments_by_service(service_ids):
    data = {}

    if not service_ids:
        return data

    rows = (
        OperationsJobcardAssignment.query
        .filter(OperationsJobcardAssignment.jobcard_service_id.in_(service_ids))
        .order_by(
            OperationsJobcardAssignment.jobcard_service_id.asc(),
            OperationsJobcardAssignment.assignment_type.asc(),
            OperationsJobcardAssignment.id.asc()
        )
        .all()
    )

    for row in rows:
        data.setdefault(row.jobcard_service_id, []).append(row)

    return data

def _jobcard_commercial_overview(jobcard, assignments_by_service=None):
    """
    Commercial overview in INR.

    Used during jobcard closure and low-margin approval.
    """
    if assignments_by_service is None:
        services = jobcard.services.order_by(OperationsJobcardService.id.asc()).all()
        service_ids = [s.id for s in services]
        assignments_by_service = _assignments_by_service(service_ids)

    quote_currency = _currency_code(jobcard.quote.currency if jobcard.quote else "INR")
    quote_amount_original = _dec(jobcard.quote.subtotal if jobcard.quote else 0)
    quote_conversion_date = (
        jobcard.quote.created_at
        if jobcard.quote and getattr(jobcard.quote, "created_at", None)
        else getattr(jobcard, "created_at", None)
    )

    saas_billing_row = SoftwareSaaSBilling.query.filter_by(jobcard_id=jobcard.id).first()
    if saas_billing_row:
        quote_amount_original = _dec(saas_billing_row.total_amount)
        if saas_billing_row.subscription:
            quote_currency = _currency_code(saas_billing_row.subscription.currency or quote_currency)
        quote_conversion_date = saas_billing_row.billing_date or quote_conversion_date

    quote_amount_ex_tax = _amount_to_inr(
        quote_amount_original,
        quote_currency,
        quote_conversion_date
    )

    missing_currency_rates = []

    if quote_amount_ex_tax is None:
        missing_currency_rates.append(quote_currency)
        quote_amount_ex_tax = Decimal("0")

    total_vendor_costs = Decimal("0")

    for assignment_rows in assignments_by_service.values():
        for a in assignment_rows:
            if (
                a.assignment_type == "PRODUCTION"
                and a.assigned_to_type == "VENDOR"
                and a.status not in ["Replaced", "Cancelled", "Rejected"]
            ):
                rate = _dec(a.rate)
                qty = _dec(a.assigned_qty)

                vendor_cost_original = rate if a.flat_rate else qty * rate
                vendor_currency = _assignment_vendor_currency(a)

                vendor_conversion_date = (
                    getattr(a, "assigned_at", None)
                    or getattr(a, "created_at", None)
                    or getattr(jobcard, "created_at", None)
                )

                vendor_cost_inr = _amount_to_inr(
                    vendor_cost_original,
                    vendor_currency,
                    vendor_conversion_date
                )

                if vendor_cost_inr is None:
                    missing_currency_rates.append(vendor_currency)
                    continue

                total_vendor_costs += vendor_cost_inr

    process_vendor_rows = (
        OperationsJobcardProcessAssignment.query
        .join(
            OperationsJobcardProcess,
            OperationsJobcardProcess.id == OperationsJobcardProcessAssignment.jobcard_process_id
        )
        .filter(OperationsJobcardProcess.jobcard_id == jobcard.id)
        .filter(OperationsJobcardProcessAssignment.assigned_to_type == "VENDOR")
        .filter(OperationsJobcardProcessAssignment.status.notin_(["Cancelled"]))
        .all()
    )

    for a in process_vendor_rows:
        rate = _dec(a.rate)
        qty = _dec(a.assigned_qty)

        vendor_cost_original = rate if a.flat_rate else qty * rate
        vendor_currency = _assignment_vendor_currency(a)

        vendor_conversion_date = (
                    getattr(a, "assigned_at", None)
                    or getattr(a, "created_at", None)
                    or getattr(jobcard, "created_at", None)
                )

        vendor_cost_inr = _amount_to_inr(
            vendor_cost_original,
            vendor_currency,
            vendor_conversion_date
        )

        if vendor_cost_inr is None:
            missing_currency_rates.append(vendor_currency)
            continue

        total_vendor_costs += vendor_cost_inr

    software_service_ids = [svc.id for svc in jobcard.services.all()]
    if software_service_ids:
        software_cost_rows = (SoftwareSaaSJobcardCost.query
                              .filter(SoftwareSaaSJobcardCost.jobcard_service_id.in_(software_service_ids))
                              .all())
        for cost_row in software_cost_rows:
            vendor_currency = _currency_code(
                cost_row.vendor_currency
                or (cost_row.vendor.currency if cost_row.vendor else "INR")
            )
            if cost_row.vendor_cost_inr is not None and _dec(cost_row.conversion_rate_to_inr) > 0:
                total_vendor_costs += _dec(cost_row.vendor_cost_inr)
                continue
            converted = _amount_to_inr(
                cost_row.vendor_cost, vendor_currency,
                getattr(cost_row, "updated_at", None) or getattr(jobcard, "created_at", None)
            )
            if converted is None:
                missing_currency_rates.append(vendor_currency)
                continue
            total_vendor_costs += converted

    profit_amount = quote_amount_ex_tax - total_vendor_costs

    if quote_amount_ex_tax > 0:
        profit_margin_pct = (profit_amount / quote_amount_ex_tax) * Decimal("100")
    else:
        profit_margin_pct = None

    return {
        "currency": "INR",
        "quote_currency": quote_currency,
        "quote_amount_original": quote_amount_original,
        "quote_amount_ex_tax": quote_amount_ex_tax,
        "total_vendor_costs": total_vendor_costs,
        "profit_amount": profit_amount,
        "profit_margin_pct": profit_margin_pct,
        "missing_currency_rates": sorted(set(missing_currency_rates)),
    }

def _jobcard_closure_blocker(jobcard):
    services = jobcard.services.all()

    # Self-heal historical/stale QC Pending states.  A rejected/cancelled/
    # replaced QC assignment is non-active and must not keep a service open.
    # QC Pending means the production/service work had already reached its
    # completion gate, so when no active QC remains the line can return to
    # Completed safely.
    for s in services:
        if s.status == "QC Pending" and not _has_pending_qc(s):
            s.status = "Completed"
            s.completed_at = s.completed_at or _now_ist()

    pending_services = [
        s for s in services
        if s.status != "Completed"
    ]

    if pending_services:
        return "All service lines must be completed before closing jobcard."

    pending_qc = [
        s for s in services
        if _has_pending_qc(s)
    ]

    if pending_qc:
        return "QC is pending for one or more service lines. Complete QC before closing jobcard."

    pending_checklists = []

    for s in services:
        if s.checklist_questions.count() <= 0:
            continue

        production_assignments = (
            OperationsJobcardAssignment.query
            .filter_by(
                jobcard_service_id=s.id,
                assignment_type="PRODUCTION"
            )
            .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"]))
            .all()
        )

        incomplete = []

        for a in production_assignments:
            # If parent is fully delegated, child checklists matter, not parent checklist
            if a.parent_assignment_id is None and a.status == "Delegated":
                continue

            if a.checklist_status != "Submitted":
                incomplete.append(a)

        if incomplete:
            pending_checklists.append(s)

    if pending_checklists:
        return "All required service checklists must be submitted before closing jobcard."

    return None

def _qc_assignments_for_service(svc):
    return (
        OperationsJobcardAssignment.query
        .filter_by(
            jobcard_service_id=svc.id,
            assignment_type="QC"
        )
        .order_by(OperationsJobcardAssignment.id.asc())
        .all()
    )

def _refresh_service_status_after_change(svc):
    """
    Recalculate service status after assignment/QC changes.

    Production status is based on assigned/completed qty.
    QC Pending overrides Completed only when production is completed
    and there are pending QC assignments.
    """
    completed_qty = _completed_qty_for_service(svc)
    total_qty = Decimal(str(svc.total_quantity or 0))
    assigned_qty = _assigned_qty_for_service(svc)

    if assigned_qty > total_qty:
        svc.status = "Over Assigned"
        svc.completed_at = None
        return

    if completed_qty >= total_qty and total_qty > 0:
        if _has_pending_qc(svc):
            svc.status = "QC Pending"
            svc.completed_at = None
        else:
            svc.status = "Completed"
            svc.completed_at = svc.completed_at or _now_ist()
        return

    svc.completed_at = None

    if assigned_qty <= 0:
        svc.status = "Submitted"
    elif assigned_qty < total_qty:
        svc.status = "Partially Assigned"
    else:
        svc.status = "Assigned"

def _has_pending_qc(svc):
    qc_rows = _qc_assignments_for_service(svc)

    for a in qc_rows:
        if a.status in ["Cancelled", "Replaced", "Rejected"]:
            continue

        # Fully delegated parent QC should not itself block completion.
        if a.parent_assignment_id is None and a.status == "Delegated":
            child_rows = _active_child_assignments(a)
            if child_rows and all(c.status == "Completed" for c in child_rows):
                continue

        if a.status != "Completed":
            return True

    return False

def _mark_service_completed_manually(svc):
    """
    Manually marks a service line as completed by PM.

    This is intentionally not based only on assigned/completed quantity,
    because PM can complete a service even when:
    - no production assignment exists
    - multiple QC assignments exist
    - assignment quantity logic should not overwrite manual completion
    """
    jobcard = svc.jobcard

    if _has_pending_qc(svc):
        svc.status = "QC Pending"
        svc.completed_at = None
    else:
        svc.status = "Completed"
        svc.completed_at = _now_ist()

    _refresh_jobcard_status(jobcard)

def _jobcard_is_reopened_billing_cycle(jobcard):
    """
    Return True while an invoiced jobcard is in the formally approved
    Credit Note reopen cycle and is waiting for its fresh invoice cycle.

    Historical PI / Invoice rows intentionally remain active for audit, so
    they must not lock Operations during this specific reopened cycle.
    """
    if not jobcard or not jobcard.quote_id:
        return False

    approved_reopen = (
        OperationsJobcardReopenRequest.query
        .filter_by(jobcard_id=jobcard.id, status="Approved")
        .order_by(OperationsJobcardReopenRequest.id.desc())
        .first()
    )
    if not approved_reopen:
        return False

    quote = jobcard.quote
    if not quote:
        return False

    return getattr(quote, "invoice_request_status", None) != "Approved"


def _jobcard_is_locked(jobcard):
    if jobcard.status in ["Ready For Billing", "Closure Approval Pending"]:
        return True

    # During an approved Credit Note reopen cycle, the old PI / Invoice are
    # historical billing documents and must not prevent fresh Operations work.
    if _jobcard_is_reopened_billing_cycle(jobcard):
        return False

    latest_pi = None
    latest_invoice = None

    if jobcard.quote_id:
        latest_pi = (
            ProformaInvoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(ProformaInvoice.status != "Cancelled")
            .first()
        )

        latest_invoice = (
            Invoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(Invoice.status != "Cancelled")
            .first()
        )

    return True if latest_pi or latest_invoice else False


def _can_pm_manage_jobcard(jobcard):
    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id

    return (
        owner_id == current_user.id
        or current_user.has_perm("operations.jobcard.view_all")
    )

def _get_team_user_ids_for_manager(user_id):
    """
    Returns User IDs reporting to the given manager.

    This assumes EmployeeProfile has:
    - user_id
    - reporting_manager_user_id

    If your column name is different, only change EmployeeProfile.reporting_manager_user_id below.
    """
    rows = (
        EmployeeProfile.query
        .filter(EmployeeProfile.reporting_manager_user_id == user_id)
        .all()
    )

    return [row.user_id for row in rows if row.user_id]
OPERATIONS_WORKFORCE_CODE = "OPERATIONS"


def _operations_user_query():
    """Active users explicitly assigned to the Operations workforce group."""
    return (
        User.query
        .join(WorkforceGroup, WorkforceGroup.id == User.workforce_group_id)
        .filter(
            User.is_active.is_(True),
            WorkforceGroup.is_active.is_(True),
            func.upper(WorkforceGroup.code) == OPERATIONS_WORKFORCE_CODE,
        )
    )


def _is_workload_user(user):
    """Return True only when the user belongs to the Operations group."""
    group = getattr(user, "workforce_group", None)
    return bool(
        user
        and user.is_active
        and group
        and group.is_active
        and (group.code or "").strip().upper() == OPERATIONS_WORKFORCE_CODE
    )


def _normalize_effective_service_assignment_status(assignment):
    """
    If parent task is Delegated and all active child tasks are Completed,
    mark parent as Completed so workload does not keep showing it as Delegated.
    """
    if not assignment:
        return

    if assignment.status != "Delegated":
        return

    if assignment.parent_assignment_id is not None:
        return

    child_rows = _active_child_assignments(assignment)

    if child_rows and all(child.status == "Completed" for child in child_rows):
        assignment.status = "Completed"
        assignment.completed_at = assignment.completed_at or _now_ist()


def _normalize_effective_process_assignment_status(assignment):
    """
    If parent process task is Delegated and all active child tasks are Completed,
    mark parent as Completed.
    """
    if not assignment:
        return

    if assignment.status != "Delegated":
        return

    if assignment.parent_assignment_id is not None:
        return

    child_rows = _active_child_process_assignments(assignment)

    if child_rows and all(child.status == "Completed" for child in child_rows):
        assignment.status = "Completed"
        assignment.completed_at = assignment.completed_at or _now_ist()

def _get_workload_scope_user_ids():
    """
    Workload visibility:
    - view_all permission: all active non-sales users
    - reporting manager: self + direct reports, excluding sales/sales manager
    - normal user: only self if non-sales
    """
    if current_user.has_perm("operations.jobcard.view_all"):
        return [u.id for u in _operations_user_query().all()]

    reportee_ids = _get_team_user_ids_for_manager(current_user.id)
    candidate_ids = list(set([current_user.id] + reportee_ids))

    return [
        u.id
        for u in _operations_user_query().filter(User.id.in_(candidate_ids)).all()
    ]

def _build_user_workload_summary(user_ids):
    """
    Builds workload summary for selected users using grouped queries.
    Covers:
    - Production service tasks
    - QC tasks
    - Internal process tasks
    - Owned jobcards
    """
    today_start = _now_ist().replace(hour=0, minute=0, second=0, microsecond=0)
    next_7_days = today_start + timedelta(days=7)

    summary = {}

    users = (
        User.query
        .filter(User.id.in_(user_ids))
        .order_by(User.name.asc())
        .all()
    )

    for user in users:
        summary[user.id] = {
            "user": user,
            "production_total": 0,
            "production_assigned": 0,
            "production_in_progress": 0,
            "production_on_hold": 0,
            "production_completed": 0,

            "qc_total": 0,
            "qc_assigned": 0,
            "qc_in_progress": 0,
            "qc_on_hold": 0,
            "qc_completed": 0,

            "process_total": 0,
            "process_assigned": 0,
            "process_in_progress": 0,
            "process_on_hold": 0,
            "process_completed": 0,

            "jobcards_owned": 0,
            "jobcards_submitted": 0,
            "jobcards_assigned": 0,
            "jobcards_in_progress": 0,
            "jobcards_qc_pending": 0,
            "jobcards_completed": 0,

            "overdue": 0,
            "due_soon": 0,
            "active_total": 0,
            "completed_total": 0,
            "total_workload": 0,
        }

    if not user_ids:
        return summary
    
    delegated_service_parents = (
        OperationsJobcardAssignment.query
        .filter(OperationsJobcardAssignment.assigned_to_type == "INTERNAL")
        .filter(OperationsJobcardAssignment.internal_user_id.in_(user_ids))
        .filter(OperationsJobcardAssignment.parent_assignment_id.is_(None))
        .filter(OperationsJobcardAssignment.status == "Delegated")
        .all()
    )

    for row in delegated_service_parents:
        _normalize_effective_service_assignment_status(row)

    delegated_process_parents = (
        OperationsJobcardProcessAssignment.query
        .filter(OperationsJobcardProcessAssignment.assigned_to_type == "INTERNAL")
        .filter(OperationsJobcardProcessAssignment.internal_user_id.in_(user_ids))
        .filter(OperationsJobcardProcessAssignment.parent_assignment_id.is_(None))
        .filter(OperationsJobcardProcessAssignment.status == "Delegated")
        .all()
    )

    for row in delegated_process_parents:
        _normalize_effective_process_assignment_status(row)

    db.session.flush()

    # -----------------------------
    # Production and QC assignments
    # -----------------------------
    assignment_rows = (
        db.session.query(
            OperationsJobcardAssignment.internal_user_id.label("user_id"),
            OperationsJobcardAssignment.assignment_type.label("assignment_type"),
            OperationsJobcardAssignment.status.label("status"),
            func.count(OperationsJobcardAssignment.id).label("count")
        )
        .filter(OperationsJobcardAssignment.assigned_to_type == "INTERNAL")
        .filter(OperationsJobcardAssignment.internal_user_id.in_(user_ids))
        .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"]))
        .group_by(
            OperationsJobcardAssignment.internal_user_id,
            OperationsJobcardAssignment.assignment_type,
            OperationsJobcardAssignment.status
        )
        .all()
    )

    for row in assignment_rows:
        data = summary.get(row.user_id)
        if not data:
            continue

        status = row.status or "Assigned"
        count = int(row.count or 0)

        if row.assignment_type == "PRODUCTION":
            data["production_total"] += count

            if status == "Assigned":
                data["production_assigned"] += count
            elif status == "In Progress":
                data["production_in_progress"] += count
            elif status == "On Hold":
                data["production_on_hold"] += count
            elif status == "Completed":
                data["production_completed"] += count

        elif row.assignment_type == "QC":
            data["qc_total"] += count

            if status == "Assigned":
                data["qc_assigned"] += count
            elif status == "In Progress":
                data["qc_in_progress"] += count
            elif status == "On Hold":
                data["qc_on_hold"] += count
            elif status == "Completed":
                data["qc_completed"] += count

    # -----------------------------
    # Internal process assignments
    # -----------------------------
    process_rows = (
        db.session.query(
            OperationsJobcardProcessAssignment.internal_user_id.label("user_id"),
            OperationsJobcardProcessAssignment.status.label("status"),
            func.count(OperationsJobcardProcessAssignment.id).label("count")
        )
        .filter(OperationsJobcardProcessAssignment.assigned_to_type == "INTERNAL")
        .filter(OperationsJobcardProcessAssignment.internal_user_id.in_(user_ids))
        .filter(OperationsJobcardProcessAssignment.status != "Cancelled")
        .group_by(
            OperationsJobcardProcessAssignment.internal_user_id,
            OperationsJobcardProcessAssignment.status
        )
        .all()
    )

    for row in process_rows:
        data = summary.get(row.user_id)
        if not data:
            continue

        status = row.status or "Assigned"
        count = int(row.count or 0)

        data["process_total"] += count

        if status == "Assigned":
            data["process_assigned"] += count
        elif status == "In Progress":
            data["process_in_progress"] += count
        elif status == "On Hold":
            data["process_on_hold"] += count
        elif status == "Completed":
            data["process_completed"] += count

    # -----------------------------
    # Owned jobcards
    # -----------------------------
    jobcard_rows = (
        db.session.query(
            OperationsJobcard.current_owner_id.label("user_id"),
            OperationsJobcard.status.label("status"),
            func.count(OperationsJobcard.id).label("count")
        )
        .filter(OperationsJobcard.current_owner_id.in_(user_ids))
        .group_by(
            OperationsJobcard.current_owner_id,
            OperationsJobcard.status
        )
        .all()
    )

    for row in jobcard_rows:
        data = summary.get(row.user_id)
        if not data:
            continue

        status = row.status or "Submitted"
        count = int(row.count or 0)

        data["jobcards_owned"] += count

        if status == "Submitted":
            data["jobcards_submitted"] += count
        elif status in ["Assigned", "Partially Assigned", "Over Assigned"]:
            data["jobcards_assigned"] += count
        elif status == "In Progress":
            data["jobcards_in_progress"] += count
        elif status == "QC Pending":
            data["jobcards_qc_pending"] += count
        elif status == "Completed":
            data["jobcards_completed"] += count

    # -----------------------------
    # Overdue and due soon: service/QC assignments
    # -----------------------------
    deadline_rows = (
        db.session.query(
            OperationsJobcardAssignment.internal_user_id.label("user_id"),
            func.sum(
                case(
                    (
                        OperationsJobcardAssignment.deadline < today_start,
                        1
                    ),
                    else_=0
                )
            ).label("overdue_count"),
            func.sum(
                case(
                    (
                        and_(
                            OperationsJobcardAssignment.deadline >= today_start,
                            OperationsJobcardAssignment.deadline <= next_7_days
                        ),
                        1
                    ),
                    else_=0
                )
            ).label("due_soon_count")
        )
        .filter(OperationsJobcardAssignment.assigned_to_type == "INTERNAL")
        .filter(OperationsJobcardAssignment.internal_user_id.in_(user_ids))
        .filter(OperationsJobcardAssignment.status.notin_(["Completed", "Cancelled", "Replaced", "Rejected"]))
        .filter(OperationsJobcardAssignment.deadline.isnot(None))
        .group_by(OperationsJobcardAssignment.internal_user_id)
        .all()
    )

    for row in deadline_rows:
        data = summary.get(row.user_id)
        if not data:
            continue

        data["overdue"] += int(row.overdue_count or 0)
        data["due_soon"] += int(row.due_soon_count or 0)

    # -----------------------------
    # Overdue and due soon: process assignments
    # -----------------------------
    process_deadline_rows = (
        db.session.query(
            OperationsJobcardProcessAssignment.internal_user_id.label("user_id"),
            func.sum(
                case(
                    (
                        OperationsJobcardProcessAssignment.deadline < today_start,
                        1
                    ),
                    else_=0
                )
            ).label("overdue_count"),
            func.sum(
                case(
                    (
                        and_(
                            OperationsJobcardProcessAssignment.deadline >= today_start,
                            OperationsJobcardProcessAssignment.deadline <= next_7_days
                        ),
                        1
                    ),
                    else_=0
                )
            ).label("due_soon_count")
        )
        .filter(OperationsJobcardProcessAssignment.assigned_to_type == "INTERNAL")
        .filter(OperationsJobcardProcessAssignment.internal_user_id.in_(user_ids))
        .filter(OperationsJobcardProcessAssignment.status.notin_(["Completed", "Cancelled"]))
        .filter(OperationsJobcardProcessAssignment.deadline.isnot(None))
        .group_by(OperationsJobcardProcessAssignment.internal_user_id)
        .all()
    )

    for row in process_deadline_rows:
        data = summary.get(row.user_id)
        if not data:
            continue

        data["overdue"] += int(row.overdue_count or 0)
        data["due_soon"] += int(row.due_soon_count or 0)

    for data in summary.values():
        data["completed_total"] = (
            data["production_completed"]
            + data["qc_completed"]
            + data["process_completed"]
            + data["jobcards_completed"]
        )

        data["total_workload"] = (
            data["production_total"]
            + data["qc_total"]
            + data["process_total"]
            + data["jobcards_owned"]
        )

        data["active_total"] = (
            data["total_workload"]
            - data["completed_total"]
        )

    return summary

def _parse_decimal_form_value(raw_value, default="0"):
    try:
        return Decimal(str(raw_value or default))
    except Exception:
        return Decimal(default)


def _complete_production_assignment_safely(assignment):
    """
    Reuses existing completion rules:
    - assignment must be PRODUCTION
    - checklist must be submitted if checklist exists
    - service/jobcard status is recalculated
    """
    if assignment.assignment_type != "PRODUCTION":
        return False, "Invalid production assignment."

    if assignment.status in ["Completed", "Cancelled", "Replaced", "Rejected"]:
        return False, "Assignment is already completed/cancelled/replaced."

    svc = assignment.jobcard_service
    jobcard = svc.jobcard

    if svc.checklist_questions.count() > 0 and assignment.checklist_status != "Submitted":
        return False, "Checklist pending."

    assignment.status = "Completed"
    assignment.completed_at = _now_ist()

    completed_qty = _completed_qty_for_service(svc)
    required_qty = Decimal(str(svc.total_quantity or 0))

    if completed_qty >= required_qty:
        if not _has_pending_qc(svc):
            svc.status = "Completed"
            svc.completed_at = svc.completed_at or _now_ist()
        else:
            svc.status = "QC Pending"
    else:
        _refresh_service_assignment_status(svc)
        svc.completed_at = None

    _refresh_jobcard_status(jobcard)

    return True, None


def _complete_qc_assignment_safely(assignment):
    """
    Reuses existing QC completion logic.
    """
    if assignment.assignment_type != "QC":
        return False, "Invalid QC assignment."

    if assignment.status in ["Completed", "Cancelled", "Replaced", "Rejected"]:
        return False, "QC assignment already completed/cancelled/replaced."

    svc = assignment.jobcard_service
    jobcard = svc.jobcard

    assignment.status = "Completed"
    assignment.completed_at = _now_ist()

    if not _has_pending_qc(svc):
        completed_qty = _completed_qty_for_service(svc)
        required_qty = Decimal(str(svc.total_quantity or 0))

        if completed_qty >= required_qty:
            svc.status = "Completed"
            svc.completed_at = svc.completed_at or _now_ist()
        else:
            _refresh_service_assignment_status(svc)
    else:
        svc.status = "QC Pending"

    _refresh_jobcard_status(jobcard)

    return True, None

def _refresh_service_assignment_status(svc):

    total_qty = Decimal(str(svc.total_quantity or 0))

    assigned_qty = _assigned_qty_for_service(svc)

    # Safety for quote edit sync
    if assigned_qty > total_qty:
        svc.status = "Over Assigned"

    elif assigned_qty <= 0:
        svc.status = "Submitted"

    elif assigned_qty < total_qty:
        svc.status = "Partially Assigned"

    else:
        svc.status = "Assigned"



def _jobcard_reopen_credit_note(jobcard):
    """
    Return the generated Credit Note that permits an already-invoiced jobcard
    to enter a new operational/billing cycle.

    Historical PI/Invoice records are intentionally preserved.  An invoiced
    jobcard may be reopened only after the most recent active invoice for the
    jobcard/quote has a non-cancelled generated Credit Note.
    """
    if not jobcard:
        return None

    latest_invoice = (
        Invoice.query
        .filter(
            or_(
                Invoice.jobcard_id == jobcard.id,
                Invoice.quote_id == jobcard.quote_id,
            ),
            Invoice.status != "Cancelled",
        )
        .order_by(Invoice.id.desc())
        .first()
    )
    if not latest_invoice:
        return None

    return (
        CreditNote.query
        .filter(
            CreditNote.invoice_id == latest_invoice.id,
            CreditNote.status != "Cancelled",
        )
        .order_by(CreditNote.id.desc())
        .first()
    )

def _reopen_selected_service_lines(jobcard, service_ids):
    service_ids = set(int(sid) for sid in (service_ids or []) if sid)

    if not service_ids:
        return 0

    reopened_count = 0

    services = jobcard.services.all()

    for svc in services:
        if svc.id not in service_ids:
            continue

        # Move service line out of Completed state.
        # Assignment/checklist history is preserved for audit.
        svc.completed_at = None

        # Recalculate service status based on active production assignment qty.
        _refresh_service_assignment_status(svc)

        reopened_count += 1

    return reopened_count

def _apply_jobcard_reopen_approval(row, approval_remark=None, reopen_service_ids=None):
    jobcard = row.jobcard

    row.status = "Approved"
    row.approved_by_id = current_user.id
    row.approved_at = _now_ist()
    row.approval_remark = approval_remark or "Approved and jobcard reopened."

    jobcard.ready_for_billing_at = None
    jobcard.ready_for_billing_by_id = None
    jobcard.closed_at = None
    jobcard.closed_by_id = None
    jobcard.closure_remark = None
    jobcard.billing_company_branch_id = None

    # A reopened sample job becomes an ordinary open job again. It can later
    # be re-closed as either sample or billable based on the new closure.
    jobcard.is_sample_job = False
    jobcard.sample_reason = None
    jobcard.sample_marked_at = None
    jobcard.sample_marked_by_id = None

    reopened_service_count = _reopen_selected_service_lines(
        jobcard,
        reopen_service_ids
    )

    if reopened_service_count > 0:
        _refresh_jobcard_status(jobcard)
    else:
        jobcard.status = "Completed"

    if jobcard.quote:
        jobcard.quote.ops_assignment_status = "Completed"

        # Start a fresh PI -> Invoice request cycle without deleting or
        # cancelling the historical PI/Invoice/Credit Note chain.
        jobcard.quote.pi_request_status = None
        jobcard.quote.pi_requested_at = None
        jobcard.quote.pi_requested_by_id = None
        jobcard.quote.pi_request_note = None
        jobcard.quote.invoice_request_status = None
        jobcard.quote.invoice_requested_at = None
        jobcard.quote.invoice_requested_by_id = None
        jobcard.quote.invoice_request_note = None

    return reopened_service_count

def _refresh_jobcard_status_from_assignments(jobcard):
    """
    Recalculate all service/jobcard statuses with a bounded number of queries.

    Older logic called _refresh_service_status_after_change() for every service,
    which in turn queried assignments, child assignments and QC rows repeatedly.
    On jobcards with many service lines this made assignment/completion noticeably
    slow.  This version loads all assignments once and performs the same status
    calculation in memory.
    """
    if jobcard.status == "Closure Approval Pending":
        return

    services = (
        OperationsJobcardService.query
        .filter_by(jobcard_id=jobcard.id)
        .order_by(OperationsJobcardService.id.asc())
        .all()
    )

    if not services:
        jobcard.status = "Submitted"
        return

    service_ids = [svc.id for svc in services]

    assignment_rows = (
        OperationsJobcardAssignment.query
        .filter(OperationsJobcardAssignment.jobcard_service_id.in_(service_ids))
        .order_by(OperationsJobcardAssignment.id.asc())
        .all()
    ) if service_ids else []

    rows_by_service = {}
    children_by_parent = {}

    for row in assignment_rows:
        rows_by_service.setdefault(row.jobcard_service_id, []).append(row)
        if row.parent_assignment_id is not None:
            children_by_parent.setdefault(row.parent_assignment_id, []).append(row)

    inactive_statuses = {"Cancelled", "Replaced", "Rejected"}

    for svc in services:
        total_qty = Decimal(str(svc.total_quantity or 0))
        service_rows = rows_by_service.get(svc.id, [])

        production_parents = [
            row for row in service_rows
            if row.assignment_type == "PRODUCTION"
            and row.parent_assignment_id is None
            and row.status not in inactive_statuses
        ]

        assigned_qty = sum(
            (Decimal(str(row.assigned_qty or 0)) for row in production_parents),
            Decimal("0")
        )

        completed_qty = Decimal("0")

        for parent in production_parents:
            parent_qty = Decimal(str(parent.assigned_qty or 0))
            child_rows = [
                child for child in children_by_parent.get(parent.id, [])
                if child.status not in inactive_statuses
            ]

            if not child_rows:
                if parent.status == "Completed":
                    completed_qty += parent_qty
                continue

            delegated_qty = Decimal("0")
            for child in child_rows:
                child_qty = Decimal(str(child.assigned_qty or 0))
                delegated_qty += child_qty
                if child.status == "Completed":
                    completed_qty += child_qty

            parent_self_qty = parent_qty - delegated_qty
            if parent_self_qty < 0:
                parent_self_qty = Decimal("0")

            if parent_self_qty > 0 and parent.status == "Completed":
                completed_qty += parent_self_qty

        pending_qc = False
        qc_rows = [
            row for row in service_rows
            if row.assignment_type == "QC" and row.status not in inactive_statuses
        ]

        for qc in qc_rows:
            if qc.parent_assignment_id is None and qc.status == "Delegated":
                child_rows = [
                    child for child in children_by_parent.get(qc.id, [])
                    if child.status not in inactive_statuses
                ]
                if child_rows and all(child.status == "Completed" for child in child_rows):
                    continue

            if qc.status != "Completed":
                pending_qc = True
                break

        if assigned_qty > total_qty:
            svc.status = "Over Assigned"
            svc.completed_at = None
        elif completed_qty >= total_qty and total_qty > 0:
            if pending_qc:
                svc.status = "QC Pending"
                svc.completed_at = None
            else:
                svc.status = "Completed"
                svc.completed_at = svc.completed_at or _now_ist()
        else:
            svc.completed_at = None
            if assigned_qty <= 0:
                svc.status = "Submitted"
            elif assigned_qty < total_qty:
                svc.status = "Partially Assigned"
            else:
                svc.status = "Assigned"

    statuses = [svc.status for svc in services]

    if any(status == "QC Pending" for status in statuses):
        jobcard.status = "QC Pending"
    elif all(status == "Completed" for status in statuses):
        jobcard.status = "Completed"
    elif any(status == "Over Assigned" for status in statuses):
        jobcard.status = "Over Assigned"
    elif any(status == "Completed" for status in statuses):
        jobcard.status = "In Progress"
    elif all(status == "Assigned" for status in statuses):
        jobcard.status = "Assigned"
    elif any(status in ("Assigned", "Partially Assigned") for status in statuses):
        jobcard.status = "Partially Assigned"
    else:
        jobcard.status = "Submitted"


def _active_child_process_assignments(parent_assignment):
    return (
        OperationsJobcardProcessAssignment.query
        .filter_by(parent_assignment_id=parent_assignment.id)
        .filter(OperationsJobcardProcessAssignment.status != "Cancelled")
        .order_by(OperationsJobcardProcessAssignment.id.asc())
        .all()
    )


def _delegated_qty_for_process_assignment(parent_assignment):
    total = (
        db.session.query(
            func.coalesce(func.sum(OperationsJobcardProcessAssignment.assigned_qty), 0)
        )
        .filter(
            OperationsJobcardProcessAssignment.parent_assignment_id == parent_assignment.id,
            OperationsJobcardProcessAssignment.status != "Cancelled"
        )
        .scalar()
    )

    return Decimal(str(total or 0))


def _delegation_summary_for_process_assignment(parent_assignment):
    child_rows = _active_child_process_assignments(parent_assignment)

    delegated_qty = Decimal("0")
    completed_qty = Decimal("0")

    for child in child_rows:
        child_qty = Decimal(str(child.assigned_qty or 0))
        delegated_qty += child_qty

        if child.status == "Completed":
            completed_qty += child_qty

    parent_qty = Decimal(str(parent_assignment.assigned_qty or 0))
    remaining_qty = parent_qty - delegated_qty

    if remaining_qty < 0:
        remaining_qty = Decimal("0")

    return {
        "child_rows": child_rows,
        "parent_qty": parent_qty,
        "delegated_qty": delegated_qty,
        "completed_qty": completed_qty,
        "remaining_qty": remaining_qty,
    }


def _is_process_assignment_effectively_completed(assignment):
    if assignment.status == "Completed":
        return True

    if assignment.status == "Delegated" and assignment.parent_assignment_id is None:
        child_rows = _active_child_process_assignments(assignment)

        if child_rows and all(child.status == "Completed" for child in child_rows):
            return True

    return False


def _refresh_jobcard_process_status(jobcard_process):
    active_assignments = [
        a for a in jobcard_process.assignments.all()
        if a.status != "Cancelled"
    ]

    if active_assignments and all(_is_process_assignment_effectively_completed(a) for a in active_assignments):
        jobcard_process.status = "Completed"
    elif any(a.status == "In Progress" for a in active_assignments):
        jobcard_process.status = "In Progress"
    elif any(a.status == "On Hold" for a in active_assignments):
        jobcard_process.status = "On Hold"
    elif any(a.status in ["Assigned", "Delegated", "Completed"] for a in active_assignments):
        jobcard_process.status = "Assigned"
    else:
        jobcard_process.status = "Pending"

@operations_bp.route("/jobcard-fields", methods=["GET", "POST"])
@login_required
@require_perm("operations.jobcard.manage_fields")
def jobcard_field_master():
    if request.method == "POST":
        action = request.form.get("action")

        if action == "create":
            service_id = request.form.get("service_id", type=int)
            field_label = _clean(request.form.get("field_label"))
            field_key = _clean(request.form.get("field_key")).lower().replace(" ", "_")
            field_type = _clean(request.form.get("field_type")) or "text"
            options = _clean(request.form.get("options"))
            is_required = True if request.form.get("is_required") == "1" else False
            sort_order = request.form.get("sort_order", type=int) or 1
            is_active = True if request.form.get("is_active") == "1" else False

            if not service_id or not field_label or not field_key:
                flash("Service, field label and field key are required.", "danger")
                return redirect(url_for("operations.jobcard_field_master"))

            row = JobcardServiceFieldMaster(
                service_id=service_id,
                field_label=field_label,
                field_key=field_key,
                field_type=field_type,
                options=options or None,
                is_required=is_required,
                sort_order=sort_order,
                is_active=is_active,
            )
            db.session.add(row)
            db.session.commit()
            flash("Jobcard field added successfully.", "success")
            return redirect(url_for("operations.jobcard_field_master"))

        if action == "update":
            row = JobcardServiceFieldMaster.query.get_or_404(request.form.get("field_id", type=int))
            row.service_id = request.form.get("service_id", type=int) or row.service_id
            row.field_label = _clean(request.form.get("field_label")) or row.field_label
            row.field_key = _clean(request.form.get("field_key")).lower().replace(" ", "_") or row.field_key
            row.field_type = _clean(request.form.get("field_type")) or row.field_type
            row.options = _clean(request.form.get("options")) or None
            row.is_required = True if request.form.get("is_required") == "1" else False
            row.sort_order = request.form.get("sort_order", type=int) or row.sort_order
            row.is_active = True if request.form.get("is_active") == "1" else False
            db.session.commit()
            flash("Jobcard field updated successfully.", "success")
            return redirect(url_for("operations.jobcard_field_master"))

        if action == "delete":
            row = JobcardServiceFieldMaster.query.get_or_404(request.form.get("field_id", type=int))
            db.session.delete(row)
            db.session.commit()
            flash("Jobcard field deleted successfully.", "success")
            return redirect(url_for("operations.jobcard_field_master"))

    services = LeadService.query.filter_by(is_active=True).order_by(LeadService.name.asc()).all()
    rows = (
        JobcardServiceFieldMaster.query
        .join(LeadService, LeadService.id == JobcardServiceFieldMaster.service_id)
        .order_by(LeadService.name.asc(), JobcardServiceFieldMaster.sort_order.asc())
        .all()
    )

    return render_template("operations/jobcard_field_master.html", services=services, rows=rows)

def _ensure_qc_checklist_questions(assignment):
    """Create an assignment-level snapshot from the active service-wise QC checklist master."""
    if not assignment or assignment.assignment_type != "QC" or not assignment.jobcard_service:
        return []

    existing = (
        OperationsQCChecklistQuestion.query
        .filter_by(assignment_id=assignment.id)
        .order_by(
            OperationsQCChecklistQuestion.category.asc(),
            OperationsQCChecklistQuestion.sort_order.asc(),
            OperationsQCChecklistQuestion.id.asc(),
        )
        .all()
    )
    if existing:
        return existing

    service_id = assignment.jobcard_service.service_id
    if not service_id:
        return []

    masters = (
        OperationsQCChecklistMaster.query
        .filter_by(service_id=service_id, is_active=True)
        .order_by(
            OperationsQCChecklistMaster.category.asc(),
            OperationsQCChecklistMaster.sort_order.asc(),
            OperationsQCChecklistMaster.id.asc(),
        )
        .all()
    )

    for master in masters:
        db.session.add(OperationsQCChecklistQuestion(
            assignment_id=assignment.id,
            jobcard_service_id=assignment.jobcard_service_id,
            master_id=master.id,
            category=master.category or "General",
            question_text=master.question_text,
            question_type=master.question_type or "checkbox",
            options=master.options,
            is_required=bool(master.is_required),
            severity=master.severity,
            weight=master.weight or 0,
            failure_action=master.failure_action,
            sort_order=master.sort_order or 1,
        ))

    if masters:
        db.session.flush()

    return (
        OperationsQCChecklistQuestion.query
        .filter_by(assignment_id=assignment.id)
        .order_by(
            OperationsQCChecklistQuestion.category.asc(),
            OperationsQCChecklistQuestion.sort_order.asc(),
            OperationsQCChecklistQuestion.id.asc(),
        )
        .all()
    )


def _save_qc_checklist_upload(file_obj, assignment_id, question_id):
    if not file_obj or not getattr(file_obj, "filename", None):
        return None
    original = secure_filename(file_obj.filename)
    if not original:
        return None
    extension = os.path.splitext(original)[1].lower()
    allowed = {".pdf", ".doc", ".docx", ".xls", ".xlsx", ".xlsm", ".csv", ".txt", ".png", ".jpg", ".jpeg", ".zip"}
    if extension not in allowed:
        raise ValueError("Unsupported evidence file type.")
    relative_dir = os.path.join("uploads", "qc_checklists", str(assignment_id))
    absolute_dir = os.path.join(current_app.static_folder, relative_dir)
    os.makedirs(absolute_dir, exist_ok=True)
    filename = f"q{question_id}_{uuid.uuid4().hex[:12]}{extension}"
    file_obj.save(os.path.join(absolute_dir, filename))
    return os.path.join(relative_dir, filename).replace(os.sep, "/")


def _qc_checklist_completion_state(assignment):
    questions = _ensure_qc_checklist_questions(assignment)
    responses = {r.question_id: r for r in OperationsQCChecklistResponse.query.filter_by(assignment_id=assignment.id).all()}
    missing = []
    for question in questions:
        response = responses.get(question.id)
        if not question.is_required:
            continue
        if not response:
            missing.append(question.question_text)
            continue
        if question.question_type == "file":
            if not response.file_path:
                missing.append(question.question_text)
        elif question.question_type == "checkbox":
            if str(response.response_value or "").lower() not in {"1", "true", "yes", "checked"}:
                missing.append(question.question_text)
        elif not str(response.response_value or "").strip():
            missing.append(question.question_text)
    return questions, responses, missing


@operations_bp.route("/qc-checklist-master", methods=["GET", "POST"])
@login_required
@require_perm("operations.checklist_master.manage")
def qc_checklist_master():
    allowed_types = {"checkbox", "text", "textarea", "mcq", "file", "pass_fail", "number", "date", "percentage"}
    allowed_severities = {"", "Critical", "High", "Medium", "Low", "Informational"}
    allowed_failure_actions = {"", "Block Completion", "Require Remark", "Create Rework", "Warning Only"}

    if request.method == "POST":
        action = _clean(request.form.get("action"))
        master_id = request.form.get("master_id", type=int)
        row = OperationsQCChecklistMaster.query.get_or_404(master_id) if action in {"update", "delete"} else None

        if action == "delete":
            db.session.delete(row)
            db.session.commit()
            flash("QC checklist master question deleted successfully.", "success")
            return redirect(url_for("operations.qc_checklist_master"))

        service_id = request.form.get("service_id", type=int)
        category = _clean(request.form.get("category")) or "General"
        question_text = _clean(request.form.get("question_text"))
        question_type = (_clean(request.form.get("question_type")) or "checkbox").lower()
        options = _clean(request.form.get("options")) or None
        is_required = request.form.get("is_required") == "1"
        severity = _clean(request.form.get("severity")) or None
        weight = request.form.get("weight", type=float) or 0
        failure_action = _clean(request.form.get("failure_action")) or None
        sort_order = request.form.get("sort_order", type=int) or 1
        is_active = request.form.get("is_active") == "1"

        if not service_id or not question_text:
            flash("Service and question are required.", "danger")
            return redirect(url_for("operations.qc_checklist_master"))
        if question_type not in allowed_types:
            flash("Invalid QC checklist question type.", "danger")
            return redirect(url_for("operations.qc_checklist_master"))
        if (severity or "") not in allowed_severities or (failure_action or "") not in allowed_failure_actions:
            flash("Invalid severity or failure action.", "danger")
            return redirect(url_for("operations.qc_checklist_master"))
        if question_type == "mcq" and not options:
            flash("MCQ questions require comma-separated options.", "danger")
            return redirect(url_for("operations.qc_checklist_master"))

        if action == "create":
            row = OperationsQCChecklistMaster(created_by_id=current_user.id)
            db.session.add(row)

        row.service_id = service_id
        row.category = category
        row.question_text = question_text
        row.question_type = question_type
        row.options = options
        row.is_required = is_required
        row.severity = severity
        row.weight = weight
        row.failure_action = failure_action
        row.sort_order = sort_order
        row.is_active = is_active
        db.session.commit()
        flash("QC checklist master question saved successfully.", "success")
        return redirect(url_for("operations.qc_checklist_master"))

    services = LeadService.query.filter_by(is_active=True).order_by(LeadService.name.asc()).all()
    rows = (
        OperationsQCChecklistMaster.query
        .join(LeadService, LeadService.id == OperationsQCChecklistMaster.service_id)
        .order_by(LeadService.name.asc(), OperationsQCChecklistMaster.category.asc(), OperationsQCChecklistMaster.sort_order.asc(), OperationsQCChecklistMaster.id.asc())
        .all()
    )
    return render_template("operations/qc_checklist_master.html", services=services, rows=rows)


@operations_bp.route("/checklist-master", methods=["GET", "POST"])
@login_required
@require_perm("operations.checklist_master.manage")
def checklist_master():
    if request.method == "POST":
        action = request.form.get("action")

        if action == "create":
            service_id = request.form.get("service_id", type=int)
            question_text = _clean(request.form.get("question_text"))
            question_type = _clean(request.form.get("question_type")) or "checkbox"
            options = _clean(request.form.get("options"))
            is_required = True if request.form.get("is_required") == "1" else False
            sort_order = request.form.get("sort_order", type=int) or 1
            is_active = True if request.form.get("is_active") == "1" else False

            if not service_id or not question_text:
                flash("Service and question are required.", "danger")
                return redirect(url_for("operations.checklist_master"))

            db.session.add(OperationsChecklistMaster(
                service_id=service_id,
                question_text=question_text,
                question_type=question_type,
                options=options or None,
                is_required=is_required,
                sort_order=sort_order,
                is_active=is_active,
                created_by_id=current_user.id,
            ))
            db.session.commit()

            flash("Checklist master question added successfully.", "success")
            return redirect(url_for("operations.checklist_master"))

        if action == "update":
            row = OperationsChecklistMaster.query.get_or_404(
                request.form.get("master_id", type=int)
            )

            row.service_id = request.form.get("service_id", type=int) or row.service_id
            row.question_text = _clean(request.form.get("question_text")) or row.question_text
            row.question_type = _clean(request.form.get("question_type")) or row.question_type
            row.options = _clean(request.form.get("options")) or None
            row.is_required = True if request.form.get("is_required") == "1" else False
            row.sort_order = request.form.get("sort_order", type=int) or row.sort_order
            row.is_active = True if request.form.get("is_active") == "1" else False

            db.session.commit()
            flash("Checklist master question updated successfully.", "success")
            return redirect(url_for("operations.checklist_master"))

        if action == "delete":
            row = OperationsChecklistMaster.query.get_or_404(
                request.form.get("master_id", type=int)
            )
            db.session.delete(row)
            db.session.commit()

            flash("Checklist master question deleted successfully.", "success")
            return redirect(url_for("operations.checklist_master"))

    services = LeadService.query.filter_by(is_active=True).order_by(LeadService.name.asc()).all()

    rows = (
        OperationsChecklistMaster.query
        .join(LeadService, LeadService.id == OperationsChecklistMaster.service_id)
        .order_by(LeadService.name.asc(), OperationsChecklistMaster.sort_order.asc(), OperationsChecklistMaster.id.asc())
        .all()
    )

    return render_template(
        "operations/checklist_master.html",
        services=services,
        rows=rows
    )

@operations_bp.route("/quotes/<int:quote_id>/assign-jobcard", methods=["GET", "POST"])
@login_required
@require_perm("operations.jobcard.create")
def assign_jobcard_from_quote(quote_id):
    quote = Quote.query.get_or_404(quote_id)

    if not getattr(quote, "proposal_confirmed_at", None):
        flash("Jobcard can be created only after proposal is confirmed.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=quote.id))
    
    if quote.ops_assigned_to_id != current_user.id:
        flash("This quote is not assigned to you for jobcard creation.", "danger")
        return redirect(url_for("operations.jobcard_requests"))

    existing = OperationsJobcard.query.filter_by(quote_id=quote.id).first()
    if existing:
        flash("Operations jobcard already exists for this quote.", "info")
        return redirect(url_for("operations.view_jobcard", jobcard_id=existing.id))

    items = quote.items.order_by(QuoteItem.sort_order.asc(), QuoteItem.id.asc()).all()

    service_ids = list({it.service_id for it in items if it.service_id})
    fields_by_service = {}
    if service_ids:
        fields = (
            JobcardServiceFieldMaster.query
            .filter(JobcardServiceFieldMaster.service_id.in_(service_ids))
            .filter(JobcardServiceFieldMaster.is_active == True)
            .order_by(JobcardServiceFieldMaster.service_id.asc(), JobcardServiceFieldMaster.sort_order.asc())
            .all()
        )
        for f in fields:
            fields_by_service.setdefault(f.service_id, []).append(f)

    internal_processes = (
        OperationsInternalProcessMaster.query
        .filter_by(is_active=True)
        .order_by(
            OperationsInternalProcessMaster.sort_order.asc(),
            OperationsInternalProcessMaster.name.asc()
        )
        .all()
    )


    if request.method == "POST":
        
        selected_process_ids = request.form.getlist("internal_process_ids", type=int)
        mtpe_required = _is_mtpe_process_selected(selected_process_ids)

        jobcard = OperationsJobcard(
            jobcard_code=_jobcard_code_next(),
            quote_id=quote.id,
            client_id=quote.client_id,
            branch_id=quote.branch_id,
            assigned_to_id=current_user.id,
            assigned_by_id=quote.ops_assigned_by_id or current_user.id,
            status="Submitted",
            submitted_at=_now_ist(),
            current_owner_id=current_user.id,
            client_deadline=quote.client_deadline,

            # Only mark whether MTPE is required.
            # Details will be filled after jobcard creation.
            mtpe_required=mtpe_required,
        )
        db.session.add(jobcard)
        db.session.flush()


        if selected_process_ids:
            process_rows = (
                OperationsInternalProcessMaster.query
                .filter(OperationsInternalProcessMaster.id.in_(selected_process_ids))
                .filter(OperationsInternalProcessMaster.is_active == True)
                .all()
            )

            for process in process_rows:
                db.session.add(OperationsJobcardProcess(
                    jobcard_id=jobcard.id,
                    process_master_id=process.id,
                    is_required=True,
                    status="Pending",
                    created_by_id=current_user.id,
                    created_at=_now_ist()
                ))

        for item in items:
            service_name = item.service.name if getattr(item, "service", None) else None

            jc_service = OperationsJobcardService(
                jobcard_id=jobcard.id,
                quote_item_id=item.id,
                service_id=item.service_id,
                service_name=service_name,
                status="Submitted",
                total_quantity=item.qty or 0,
                completed_quantity=0,
            )
            db.session.add(jc_service)
            db.session.flush()

            for field in fields_by_service.get(item.service_id, []):
                input_name = f"field_{item.id}_{field.id}"

                file_path = None
                field_value = None

                if field.field_type == "file":
                    file_path = _save_jobcard_file(request.files.get(input_name))
                else:
                    field_value = _clean(request.form.get(input_name))

                if field.is_required and not field_value and not file_path:
                    db.session.rollback()
                    flash(f"Required field missing: {field.field_label}", "danger")
                    return redirect(url_for("operations.assign_jobcard_from_quote", quote_id=quote.id))

                db.session.add(OperationsJobcardFieldValue(
                    jobcard_service_id=jc_service.id,
                    field_master_id=field.id,
                    field_key=field.field_key,
                    field_value=field_value,
                    file_path=file_path,
                ))
        quote.ops_assignment_status = "Jobcard Created"
        db.session.commit()
        flash("Operations jobcard created successfully.", "success")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    return render_template(
        "operations/assign_jobcard.html",
        quote=quote,
        items=items,
        fields_by_service=fields_by_service,
        internal_processes=internal_processes,
    )

def _software_jobcard_type(jobcard):
    """Return SOFTWARE subtype when every execution line belongs to Software."""
    services = jobcard.services.order_by(OperationsJobcardService.id.asc()).all()
    if not services:
        return None
    software_rows = []
    subcategories = set()
    for row in services:
        service = getattr(row, "service", None)
        category = getattr(service, "category", None) if service else None
        if not category or (category.name or "").strip().casefold() != "software":
            return None
        software_rows.append(row)
        sub = getattr(service, "sub_category", None)
        if sub and sub.name:
            subcategories.add(sub.name.strip().casefold())
    if not software_rows:
        return None
    if len(subcategories) == 1:
        value = next(iter(subcategories))
        if value == "saas products":
            return "SAAS"
        if value == "amc":
            return "AMC"
        if value == "development":
            return "DEVELOPMENT"
    return "SOFTWARE"


def _jobcard_advance_billing_context(jobcard):
    rows = (JobcardAdvanceBilling.query.filter_by(jobcard_id=jobcard.id)
            .order_by(JobcardAdvanceBilling.id.asc()).all())
    invoiced = Decimal("0")
    pending = Decimal("0")
    for row in rows:
        amount = Decimal(str(row.requested_amount or 0))
        if row.status == "INVOICED" and row.invoice and row.invoice.status != "Cancelled":
            invoiced += amount
        elif row.status in ("PI_REQUESTED", "PI_RAISED", "INVOICE_REQUESTED"):
            pending += amount
    quote = jobcard.quote
    contract_value = Decimal("0")
    if quote:
        contract_value = max(Decimal(str(quote.subtotal or 0)) - Decimal(str(quote.discount or 0)), Decimal("0"))
    return {"rows": rows, "invoiced": invoiced, "pending": pending,
            "contract_value": contract_value, "balance": max(contract_value - invoiced, Decimal("0"))}


def _render_software_jobcard(jobcard, software_type):
    services = jobcard.services.order_by(OperationsJobcardService.id.asc()).all()
    service_ids = [row.id for row in services]
    assignments = (
        SoftwareAssignment.query
        .filter(SoftwareAssignment.jobcard_service_id.in_(service_ids))
        .order_by(SoftwareAssignment.id.desc())
        .all()
        if service_ids else []
    )
    assignments_by_service = {}
    logged_hours = {}
    estimated_costs = {}
    actual_costs = {}
    for row in assignments:
        assignments_by_service.setdefault(row.jobcard_service_id, []).append(row)
        logged = (
            db.session.query(func.coalesce(func.sum(SoftwareTimeEntry.hours), 0))
            .filter(SoftwareTimeEntry.assignment_id == row.id)
            .scalar() or 0
        )
        logged_hours[row.id] = logged
        fixed_cost = Decimal(str(row.fixed_cost or 0))
        hourly_cost = Decimal(str(row.hourly_cost or 0))
        estimated_hours = Decimal(str(row.estimated_hours or 0))
        estimated_costs[row.id] = fixed_cost if fixed_cost > 0 else (estimated_hours * hourly_cost)
        actual_costs[row.id] = fixed_cost if fixed_cost > 0 else (Decimal(str(logged or 0)) * hourly_cost)

    resources = (
        SoftwareResourceProfile.query
        .filter_by(is_active=True)
        .join(User, SoftwareResourceProfile.user_id == User.id)
        .order_by(User.name.asc())
        .all()
    )
    software_vendors = SoftwareVendor.query.filter_by(is_active=True).order_by(SoftwareVendor.vendor_name.asc()).all()
    saas_costs = {
        row.jobcard_service_id: row
        for row in SoftwareSaaSJobcardCost.query.filter(SoftwareSaaSJobcardCost.jobcard_service_id.in_(service_ids)).all()
    } if service_ids else {}
    saas_billing = SoftwareSaaSBilling.query.filter_by(jobcard_id=jobcard.id).first()
    latest_pi = (ProformaInvoice.query.filter_by(jobcard_id=jobcard.id)
                 .filter(ProformaInvoice.status != "Cancelled")
                 .order_by(ProformaInvoice.id.desc()).first())
    latest_invoice = (Invoice.query.filter_by(jobcard_id=jobcard.id)
                      .filter(Invoice.status != "Cancelled")
                      .order_by(Invoice.id.desc()).first())
    # Legacy first SaaS invoices may pre-date the jobcard link. Resolve them from
    # the subscription lifecycle so the Jobcard still shows Invoice Raised.
    if not latest_invoice:
        first_invoice_id = next((x.first_invoice_id for x in SoftwareSaaSSubscription.query.filter_by(source_jobcard_id=jobcard.id).all() if x.first_invoice_id), None)
        if first_invoice_id:
            latest_invoice = Invoice.query.get(first_invoice_id)
    commercial_overview = _jobcard_commercial_overview_fast(jobcard, assignments_by_service={})
    subtasks_by_assignment = {}
    if assignments:
        for subtask in (SoftwareSubtask.query
                        .filter(SoftwareSubtask.assignment_id.in_([x.id for x in assignments]))
                        .order_by(SoftwareSubtask.id.asc()).all()):
            subtasks_by_assignment.setdefault(subtask.assignment_id, []).append(subtask)
    advance_billing = _jobcard_advance_billing_context(jobcard)

    saas_subscriptions_by_quote_item = {
        row.quote_item_id: row
        for row in SoftwareSaaSSubscription.query.filter(
            SoftwareSaaSSubscription.source_jobcard_id == jobcard.id,
            SoftwareSaaSSubscription.quote_item_id.in_([
                svc.quote_item_id for svc in services if svc.quote_item_id
            ])
        ).all()
    } if services else {}

    return render_template(
        "operations/view_software_jobcard.html",
        jobcard=jobcard,
        software_type=software_type,
        services=services,
        assignments_by_service=assignments_by_service,
        total_assignments=len(assignments),
        logged_hours=logged_hours,
        estimated_costs=estimated_costs,
        actual_costs=actual_costs,
        resources=resources,
        software_vendors=software_vendors,
        saas_costs=saas_costs,
        saas_billing=saas_billing,
        latest_pi=latest_pi,
        latest_invoice=latest_invoice,
        commercial_overview=commercial_overview,
        saas_subscriptions_by_quote_item=saas_subscriptions_by_quote_item,
        subtasks_by_assignment=subtasks_by_assignment,
        advance_billing=advance_billing,
    )


@operations_bp.route("/jobcards/<int:jobcard_id>/advance-billing/request", methods=["POST"])
@login_required
@require_perm("proforma.request")
def request_advance_billing(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)
    quote = jobcard.quote
    if not quote:
        flash("This Jobcard is not linked to a quotation.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
    if getattr(jobcard, "is_sample_job", False) or jobcard.status == "Sample Completed":
        flash("Advance billing is not available for Sample / Non-Billable Jobcards.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
    if jobcard.status in ("Ready For Billing", "Completed"):
        flash("This Jobcard is already closed. Please use the normal final PI request.", "warning")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
    if not getattr(quote, "proposal_confirmed_at", None) or not quote.status or quote.status.name != "Sent":
        flash("Advance billing is available only after the proposal is confirmed and sent.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
    if getattr(quote, "pi_request_status", None) in ("Pending", "Approval Pending"):
        flash("Another PI request is already in progress for this quotation.", "warning")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
    final_pi = (ProformaInvoice.query.filter_by(jobcard_id=jobcard.id, advance_billing_id=None)
                .filter(ProformaInvoice.status != "Cancelled").first())
    if final_pi:
        flash("Final PI has already been generated for this Jobcard; advance billing is no longer available.", "warning")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
    try:
        amount = Decimal(str(request.form.get("amount") or "0"))
    except Exception:
        amount = Decimal("0")
    ctx = _jobcard_advance_billing_context(jobcard)
    available = max(ctx["contract_value"] - ctx["invoiced"] - ctx["pending"], Decimal("0"))
    if amount <= 0:
        flash("Enter a valid advance billing amount.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
    if amount > available:
        flash("Advance amount cannot exceed the available balance of {} {}.".format(quote.currency or "INR", available), "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))
    row = JobcardAdvanceBilling(jobcard_id=jobcard.id, quote_id=quote.id, requested_amount=amount,
                                currency=(quote.currency or "INR"), note=(request.form.get("note") or "").strip() or None,
                                status="PI_REQUESTED", requested_by_id=current_user.id)
    db.session.add(row)
    db.session.flush()
    quote.pi_requested_at = datetime.utcnow()
    quote.pi_requested_by_id = current_user.id
    quote.pi_request_note = "Advance billing request #{} for {} {}{}".format(row.id, quote.currency or "INR", amount, (" - " + row.note) if row.note else "")
    quote.pi_request_status = "Pending"
    quote.pi_requested_jobcard_id = jobcard.id
    quote.invoice_request_status = None
    quote.invoice_requested_jobcard_id = None
    db.session.commit()
    flash("Advance PI request sent to Finance.", "success")
    return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))


@operations_bp.route("/jobcards/<int:jobcard_id>")
@login_required
@require_perm("operations.jobcard.view")
def view_jobcard(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

    software_type = _software_jobcard_type(jobcard)
    if software_type:
        return _render_software_jobcard(jobcard, software_type)

    latest_pi = None
    latest_invoice = None

    if jobcard.quote_id:
        latest_pi = (
            ProformaInvoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(ProformaInvoice.status != "Cancelled")
            .order_by(ProformaInvoice.id.desc())
            .first()
        )

        latest_invoice = (
            Invoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(Invoice.status != "Cancelled")
            .order_by(Invoice.id.desc())
            .first()
        )

    operation_users = _get_operations_users()

    company_branches = (
        CompanyBranch.query
        .filter_by(is_active=True)
        .order_by(CompanyBranch.branch_name.asc())
        .all()
    )

    vendors = (
        VendorMaster.query
        .filter_by(is_active=True)
        .order_by(VendorMaster.name.asc())
        .all()
    )

    services = jobcard.services.order_by(OperationsJobcardService.id.asc()).all()
    service_ids = [s.id for s in services]

    # One query for all assignments.
    assignments_by_service = _assignments_by_service(service_ids)

    # Bulk missing required field check.
    # Important: No _ensure_jobcard_field_values_for_service() here.
    # That function inserts missing rows and commits on every view, which slows page load.
    missing_required_fields_by_service = _missing_required_fields_for_services_bulk(services)

    # Bulk remaining quantity calculation using already loaded assignments.
    remaining_qty_by_service = _remaining_qty_for_services_bulk(
        services,
        assignments_by_service=assignments_by_service
    )

    jobcard_processes = (
        OperationsJobcardProcess.query
        .filter_by(jobcard_id=jobcard.id)
        .join(
            OperationsInternalProcessMaster,
            OperationsInternalProcessMaster.id == OperationsJobcardProcess.process_master_id
        )
        .order_by(
            OperationsInternalProcessMaster.sort_order.asc(),
            OperationsInternalProcessMaster.name.asc()
        )
        .all()
    )

    process_assignment_rows = (
        OperationsJobcardProcessAssignment.query
        .join(
            OperationsJobcardProcess,
            OperationsJobcardProcess.id == OperationsJobcardProcessAssignment.jobcard_process_id
        )
        .filter(OperationsJobcardProcess.jobcard_id == jobcard.id)
        .order_by(OperationsJobcardProcessAssignment.id.desc())
        .all()
    )

    process_assignments_by_process = {}
    for row in process_assignment_rows:
        process_assignments_by_process.setdefault(row.jobcard_process_id, []).append(row)

    commercial_overview = _jobcard_commercial_overview_fast(
        jobcard,
        assignments_by_service=assignments_by_service,
        process_assignment_rows=process_assignment_rows
    )

    pending_reopen_request = (
        OperationsJobcardReopenRequest.query
        .filter_by(jobcard_id=jobcard.id, status="Pending")
        .first()
    )

    # Normal closed jobcards can be reopened when they have not yet been
    # invoiced.  Once invoiced, a generated Credit Note is mandatory before
    # the reopen request becomes available again.
    reopen_credit_note = _jobcard_reopen_credit_note(jobcard)
    can_request_reopen_jobcard = (latest_invoice is None) or (reopen_credit_note is not None)
    reopened_billing_cycle = _jobcard_is_reopened_billing_cycle(jobcard)

    pending_closure_approval_request = (
        OperationsJobcardClosureApprovalRequest.query
        .filter_by(jobcard_id=jobcard.id, status="Pending")
        .first()
    )

    latest_closure_approval_request = (
        OperationsJobcardClosureApprovalRequest.query
        .filter_by(jobcard_id=jobcard.id)
        .order_by(OperationsJobcardClosureApprovalRequest.id.desc())
        .first()
    )

    mtpe_entries = (
        OperationsJobcardMTPEEntry.query
        .filter_by(jobcard_id=jobcard.id)
        .order_by(OperationsJobcardMTPEEntry.id.desc())
        .all()
    )

    workload_summary = workload_completion_summary(jobcard)
    _, workload_standards_payload = _active_workload_standards_payload()

    deadline_extension_requests = (
        OperationsClientDeadlineExtensionRequest.query
        .filter_by(jobcard_id=jobcard.id)
        .order_by(OperationsClientDeadlineExtensionRequest.id.desc())
        .all()
    )
    pending_deadline_extension_request = next(
        (
            row
            for row in deadline_extension_requests
            if row.status in DEADLINE_EXTENSION_PENDING_STATUSES
        ),
        None,
    )
    latest_approved_deadline_extension = next(
        (row for row in deadline_extension_requests if row.status == "Approved"),
        None,
    )
    deadline_extension_quote_owner = _deadline_extension_quote_owner(jobcard)
    advance_billing = _jobcard_advance_billing_context(jobcard)

    return render_template(
        "operations/view_jobcard.html",
        jobcard=jobcard,
        operation_users=operation_users,
        company_branches=company_branches,
        latest_pi=latest_pi,
        latest_invoice=latest_invoice,
        assignments_by_service=assignments_by_service,
        vendors=vendors,
        pending_reopen_request=pending_reopen_request,
        can_request_reopen_jobcard=can_request_reopen_jobcard,
        reopen_credit_note=reopen_credit_note,
        reopened_billing_cycle=reopened_billing_cycle,
        pending_closure_approval_request=pending_closure_approval_request,
        latest_closure_approval_request=latest_closure_approval_request,
        commercial_overview=commercial_overview,
        reopen_reason_options=REOPEN_REASON_OPTIONS,
        jobcard_processes=jobcard_processes,
        process_assignments_by_process=process_assignments_by_process,
        language_pairs=LANGUAGE_PAIRS,
        mt_names=MT_NAMES,
        mtpe_entries=mtpe_entries,
        remaining_qty_by_service=remaining_qty_by_service,
        missing_required_fields_by_service=missing_required_fields_by_service,
        workload_summary=workload_summary,
        workload_standards_payload=workload_standards_payload,
        deadline_extension_requests=deadline_extension_requests,
        pending_deadline_extension_request=pending_deadline_extension_request,
        latest_approved_deadline_extension=latest_approved_deadline_extension,
        deadline_extension_quote_owner=deadline_extension_quote_owner,
        advance_billing=advance_billing,
    )

@operations_bp.route("/services/<int:service_id>/fields", methods=["GET", "POST"])
@login_required
@require_perm("operations.jobcard.view")
def update_jobcard_service_fields(service_id):
    svc = OperationsJobcardService.query.get_or_404(service_id)
    jobcard = svc.jobcard

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id

    if owner_id != current_user.id and not current_user.has_perm("operations.jobcard.view_all"):
        abort(403)

    if _jobcard_is_locked(jobcard):
        flash("Service fields cannot be updated because this jobcard is closed, billing exists, or closure approval is pending.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    _ensure_jobcard_field_values_for_service(svc)

    field_rows = _jobcard_service_fields_grouped(svc)

    if request.method == "POST":
        for field, value_row in field_rows:
            input_name = f"field_{field.id}"

            file_path = None
            field_value = None

            if field.field_type == "file":
                uploaded_file = request.files.get(input_name)
                file_path = _save_jobcard_file(uploaded_file)

                existing_file = value_row.file_path if value_row else None

                if field.is_required and not file_path and not existing_file:
                    flash(f"Required field missing: {field.field_label}", "danger")
                    return redirect(url_for("operations.update_jobcard_service_fields", service_id=svc.id))

            else:
                field_value = _clean(request.form.get(input_name))

                if field.is_required and not field_value:
                    flash(f"Required field missing: {field.field_label}", "danger")
                    return redirect(url_for("operations.update_jobcard_service_fields", service_id=svc.id))

            if not value_row:
                value_row = OperationsJobcardFieldValue(
                    jobcard_service_id=svc.id,
                    field_master_id=field.id,
                    field_key=field.field_key
                )
                db.session.add(value_row)

            if field.field_type == "file":
                if file_path:
                    value_row.file_path = file_path
            else:
                value_row.field_value = field_value

            value_row.field_key = field.field_key

        db.session.commit()

        flash("Service required fields updated successfully.", "success")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    return render_template(
        "operations/jobcard_service_fields.html",
        jobcard=jobcard,
        svc=svc,
        field_rows=field_rows,
    )

@operations_bp.route("/jobcards")
@login_required
@require_perm("operations.jobcard.view")
def my_jobcards():
    return _jobcard_list_page(scope="my")


@operations_bp.route("/jobcards/all")
@login_required
@require_perm("operations.jobcard.view_all")
def all_jobcards():
    return _jobcard_list_page(scope="all")


def _jobcard_list_page(scope="my"):
    q = _clean(request.args.get("q"))
    status = _clean(request.args.get("status"))
    billing_filter = _clean(request.args.get("billing_filter")) or "open"
    assigned_to_id = request.args.get("assigned_to_id", type=int)
    assigned_by_id = request.args.get("assigned_by_id", type=int)
    service_id = request.args.get("service_id", type=int)
    client_id = request.args.get("client_id", type=int)
    branch_id = request.args.get("branch_id", type=int)
    created_from = _clean(request.args.get("created_from"))
    created_to = _clean(request.args.get("created_to"))
    assignment_filter = _clean(request.args.get("assignment_filter"))
    qc_filter = _clean(request.args.get("qc_filter"))
    deadline_filter = _clean(request.args.get("deadline_filter"))
    client_deadline_filter = _clean(request.args.get("client_deadline_filter"))
    page = request.args.get("page", 1, type=int)
    per_page = 20

    query = (
        OperationsJobcard.query
        .outerjoin(Quote, Quote.id == OperationsJobcard.quote_id)
        .outerjoin(
            Invoice,
            and_(
                Invoice.quote_id == OperationsJobcard.quote_id,
                Invoice.status != "Cancelled"
            )
        )
    )

    if scope == "my":
        query = query.filter(or_(
            OperationsJobcard.assigned_to_id == current_user.id,
            OperationsJobcard.current_owner_id == current_user.id
        ))

    if q:
        like = f"%{q}%"
        query = query.outerjoin(Client, Client.id == OperationsJobcard.client_id).filter(or_(
            OperationsJobcard.jobcard_code.ilike(like),
            Quote.quote_code.ilike(like),
            Client.company_name.ilike(like),
        ))

    if status:
        query = query.filter(OperationsJobcard.status == status)

    if assigned_to_id and scope == "all":
        query = query.filter(or_(
            OperationsJobcard.assigned_to_id == assigned_to_id,
            OperationsJobcard.current_owner_id == assigned_to_id
        ))

    if assigned_by_id:
        query = query.filter(OperationsJobcard.assigned_by_id == assigned_by_id)

    if client_id:
        query = query.filter(OperationsJobcard.client_id == client_id)

    if branch_id:
        query = query.filter(OperationsJobcard.branch_id == branch_id)

    if service_id:
        query = query.filter(
            OperationsJobcard.services.any(OperationsJobcardService.service_id == service_id)
        )

    try:
        if created_from:
            query = query.filter(OperationsJobcard.created_at >= datetime.strptime(created_from, "%Y-%m-%d"))
        if created_to:
            created_to_dt = datetime.strptime(created_to, "%Y-%m-%d") + timedelta(days=1)
            query = query.filter(OperationsJobcard.created_at < created_to_dt)
    except ValueError:
        flash("Invalid created date filter ignored.", "warning")

    if assignment_filter == "unassigned":
        query = query.filter(~OperationsJobcard.services.any(
            OperationsJobcardService.assignments.any(
                OperationsJobcardAssignment.status.notin_(["Replaced", "Cancelled", "Rejected"])
            )
        ))
    elif assignment_filter == "assigned":
        query = query.filter(OperationsJobcard.services.any(
            OperationsJobcardService.assignments.any(
                OperationsJobcardAssignment.status.notin_(["Replaced", "Cancelled", "Rejected"])
            )
        ))
    elif assignment_filter == "vendor":
        query = query.filter(OperationsJobcard.services.any(
            OperationsJobcardService.assignments.any(and_(
                OperationsJobcardAssignment.assignment_type == "PRODUCTION",
                OperationsJobcardAssignment.assigned_to_type == "VENDOR",
                OperationsJobcardAssignment.status.notin_(["Replaced", "Cancelled", "Rejected"]),
            ))
        ))
    elif assignment_filter == "internal":
        query = query.filter(OperationsJobcard.services.any(
            OperationsJobcardService.assignments.any(and_(
                OperationsJobcardAssignment.assignment_type == "PRODUCTION",
                OperationsJobcardAssignment.assigned_to_type == "INTERNAL",
                OperationsJobcardAssignment.status.notin_(["Replaced", "Cancelled", "Rejected"]),
            ))
        ))

    if qc_filter == "pending":
        query = query.filter(OperationsJobcard.services.any(
            OperationsJobcardService.assignments.any(and_(
                OperationsJobcardAssignment.assignment_type == "QC",
                OperationsJobcardAssignment.status.notin_(["Completed", "Replaced", "Cancelled", "Rejected"]),
            ))
        ))
    elif qc_filter == "completed":
        query = query.filter(OperationsJobcard.services.any(
            OperationsJobcardService.assignments.any(and_(
                OperationsJobcardAssignment.assignment_type == "QC",
                OperationsJobcardAssignment.status == "Completed",
            ))
        ))
    elif qc_filter == "not_assigned":
        query = query.filter(~OperationsJobcard.services.any(
            OperationsJobcardService.assignments.any(and_(
                OperationsJobcardAssignment.assignment_type == "QC",
                OperationsJobcardAssignment.status.notin_(["Replaced", "Cancelled", "Rejected"]),
            ))
        ))

    now_ist = _now_ist()
    if deadline_filter == "overdue":
        query = query.filter(OperationsJobcard.services.any(
            OperationsJobcardService.assignments.any(and_(
                OperationsJobcardAssignment.deadline.isnot(None),
                OperationsJobcardAssignment.deadline < now_ist,
                OperationsJobcardAssignment.status.notin_(["Completed", "Replaced", "Cancelled", "Rejected"]),
            ))
        ))
    elif deadline_filter == "due_today":
        start_today = now_ist.replace(hour=0, minute=0, second=0, microsecond=0)
        end_today = start_today + timedelta(days=1)
        query = query.filter(OperationsJobcard.services.any(
            OperationsJobcardService.assignments.any(and_(
                OperationsJobcardAssignment.deadline >= start_today,
                OperationsJobcardAssignment.deadline < end_today,
                OperationsJobcardAssignment.status.notin_(["Completed", "Replaced", "Cancelled", "Rejected"]),
            ))
        ))
    elif deadline_filter == "no_deadline":
        query = query.filter(OperationsJobcard.services.any(
            OperationsJobcardService.assignments.any(and_(
                OperationsJobcardAssignment.deadline.is_(None),
                OperationsJobcardAssignment.status.notin_(["Replaced", "Cancelled", "Rejected"]),
            ))
        ))

    # Client commitment deadline is separate from internal/vendor assignment
    # deadlines. Prefer the deadline stored on the jobcard and fall back to
    # the linked quote only when the jobcard value is blank.
    effective_client_deadline = func.coalesce(
        OperationsJobcard.client_deadline,
        Quote.client_deadline,
    )

    if client_deadline_filter == "missing":
        query = query.filter(effective_client_deadline.is_(None))
    elif client_deadline_filter == "available":
        query = query.filter(effective_client_deadline.isnot(None))
    elif client_deadline_filter == "overdue_open":
        query = query.filter(
            effective_client_deadline.isnot(None),
            effective_client_deadline < now_ist,
            OperationsJobcard.closed_at.is_(None),
            OperationsJobcard.status.notin_(
                ["Ready For Billing", "Cancelled"]
            ),
        )
    elif client_deadline_filter == "due_today":
        start_today = now_ist.replace(
            hour=0,
            minute=0,
            second=0,
            microsecond=0,
        )
        end_today = start_today + timedelta(days=1)
        query = query.filter(
            effective_client_deadline >= start_today,
            effective_client_deadline < end_today,
        )

    if billing_filter == "invoice_raised":
        query = query.filter(Invoice.id.isnot(None))
    elif billing_filter == "all":
        pass
    else:
        query = query.filter(Invoice.id.is_(None))

    query = query.distinct(OperationsJobcard.id)

    summary_jobcards = query.order_by(None).all()
    summary_quote_ids = [jc.quote_id for jc in summary_jobcards if jc.quote_id]

    summary_pi_quote_ids = set()
    summary_invoice_quote_ids = set()

    if summary_quote_ids:
        summary_pi_quote_ids = set(
            row[0] for row in
            db.session.query(ProformaInvoice.quote_id)
            .filter(ProformaInvoice.quote_id.in_(summary_quote_ids))
            .filter(ProformaInvoice.status != "Cancelled")
            .distinct()
            .all()
        )

        summary_invoice_quote_ids = set(
            row[0] for row in
            db.session.query(Invoice.quote_id)
            .filter(Invoice.quote_id.in_(summary_quote_ids))
            .filter(Invoice.status != "Cancelled")
            .distinct()
            .all()
        )

    summary = {
        "total": len(summary_jobcards),
        "submitted": sum(1 for jc in summary_jobcards if jc.status == "Submitted"),
        "assigned": sum(1 for jc in summary_jobcards if jc.status in [
            "Assigned", "Partially Assigned", "Vendor Assigned", "Internal Assigned", "Over Assigned"
        ]),
        "in_progress": sum(1 for jc in summary_jobcards if jc.status == "In Progress"),
        "completed": sum(1 for jc in summary_jobcards if jc.status in ["Completed", "Sample Completed"]),
        "ready_for_billing": sum(1 for jc in summary_jobcards if jc.status == "Ready For Billing" and jc.quote_id not in summary_pi_quote_ids and jc.quote_id not in summary_invoice_quote_ids),
        "pi_raised": sum(1 for jc in summary_jobcards if jc.quote_id in summary_pi_quote_ids and jc.quote_id not in summary_invoice_quote_ids),
        "invoice_raised": sum(1 for jc in summary_jobcards if jc.quote_id in summary_invoice_quote_ids),
        "missing_client_deadline": sum(
            1
            for jc in summary_jobcards
            if not (
                jc.client_deadline
                or (
                    jc.quote.client_deadline
                    if jc.quote
                    else None
                )
            )
        ),
    }

    query = query.order_by(OperationsJobcard.created_at.desc(), OperationsJobcard.id.desc())
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)

    users = User.query.filter_by(is_active=True).order_by(User.name.asc()).all()
    services_master = LeadService.query.order_by(LeadService.name.asc()).all()
    clients = Client.query.order_by(Client.company_name.asc()).all()
    branches = ClientBranch.query.order_by(ClientBranch.branch_location.asc()).all()

    statuses = [
        "Submitted", "Partially Assigned", "Assigned", "Over Assigned", "QC Pending",
        "In Progress", "On Hold", "Completed", "Sample Completed", "Closure Approval Pending",
        "Ready For Billing", "Cancelled",
    ]

    jobcards_on_page = pagination.items
    quote_ids = [jc.quote_id for jc in jobcards_on_page if jc.quote_id]
    latest_pi_by_quote = {}
    latest_invoice_by_quote = {}

    if quote_ids:
        pi_rows = ProformaInvoice.query.filter(ProformaInvoice.quote_id.in_(quote_ids)).filter(ProformaInvoice.status != "Cancelled").order_by(ProformaInvoice.quote_id.asc(), ProformaInvoice.id.desc()).all()
        for pi in pi_rows:
            if pi.quote_id not in latest_pi_by_quote:
                latest_pi_by_quote[pi.quote_id] = pi

        invoice_rows = Invoice.query.filter(Invoice.quote_id.in_(quote_ids)).filter(Invoice.status != "Cancelled").order_by(Invoice.quote_id.asc(), Invoice.id.desc()).all()
        for inv in invoice_rows:
            if inv.quote_id not in latest_invoice_by_quote:
                latest_invoice_by_quote[inv.quote_id] = inv

    return render_template(
        "operations/jobcards_list.html",
        pagination=pagination, users=users, services_master=services_master,
        clients=clients, branches=branches, statuses=statuses,
        q=q, status=status, billing_filter=billing_filter,
        assigned_to_id=assigned_to_id, assigned_by_id=assigned_by_id,
        service_id=service_id, client_id=client_id, branch_id=branch_id,
        created_from=created_from, created_to=created_to,
        assignment_filter=assignment_filter, qc_filter=qc_filter,
        deadline_filter=deadline_filter,
        client_deadline_filter=client_deadline_filter,
        scope=scope, summary=summary,
        latest_pi_by_quote=latest_pi_by_quote,
        latest_invoice_by_quote=latest_invoice_by_quote,
    )

def _xbench_average_ratings_for_assignees():
    """Return issue-weighted Xbench averages for vendor and internal translators.

    Only the latest report for each QC-assignment/production-assignment pair is
    counted, matching the Translator Xbench Ratings dashboard logic.
    """
    reports = (
        XbenchReport.query
        .filter(
            XbenchReport.is_uploaded.is_(True),
            XbenchReport.parsing_status == "Parsed",
        )
        .order_by(XbenchReport.uploaded_at.desc(), XbenchReport.id.desc())
        .all()
    )

    latest_reports = []
    seen_keys = set()
    for report in reports:
        key = (report.qc_assignment_id, report.production_assignment_id)
        if key in seen_keys:
            continue
        seen_keys.add(key)
        latest_reports.append(report)

    vendor_totals = {}
    internal_totals = {}

    for report in latest_reports:
        if report.translator_type_snapshot == "VENDOR" and report.translator_vendor_id:
            target = vendor_totals.setdefault(
                report.translator_vendor_id,
                {"weighted_points": 0, "mapped_issues": 0},
            )
        elif report.translator_type_snapshot == "INTERNAL" and report.translator_internal_user_id:
            target = internal_totals.setdefault(
                report.translator_internal_user_id,
                {"weighted_points": 0, "mapped_issues": 0},
            )
        else:
            continue

        for category_count in report.category_counts.all():
            issue_count = int(category_count.issue_count or 0)
            if issue_count <= 0:
                continue

            severity_rank = None
            if category_count.category and category_count.category.severity:
                severity_rank = category_count.category.severity.severity_rank
            elif category_count.severity_snapshot:
                severity_rank = category_count.severity_snapshot.severity_rank

            if severity_rank in (1, 2, 3, 4, 5):
                target["weighted_points"] += issue_count * severity_rank
                target["mapped_issues"] += issue_count

    vendor_ratings = {
        entity_id: round(values["weighted_points"] / values["mapped_issues"], 2)
        for entity_id, values in vendor_totals.items()
        if values["mapped_issues"]
    }
    internal_ratings = {
        entity_id: round(values["weighted_points"] / values["mapped_issues"], 2)
        for entity_id, values in internal_totals.items()
        if values["mapped_issues"]
    }

    return vendor_ratings, internal_ratings


def _vendor_assignment_allowed(vendor):
    if not vendor:
        return False, "Vendor not found."
    try:
        return vendor.assignment_eligibility(datetime.utcnow())
    except Exception:
        return bool(vendor.is_active), None if vendor.is_active else "Vendor is inactive."


def _eligible_assignment_vendors():
    vendors = _eligible_assignment_vendors()
    return [v for v in vendors if _vendor_assignment_allowed(v)[0]]


@operations_bp.route("/jobcards/<int:jobcard_id>/vendor-assignment", methods=["GET", "POST"])
@login_required
@require_perm("operations.vendor.assign")
def vendor_assignment(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

    vendors = VendorMaster.query.filter_by(is_active=True).order_by(VendorMaster.name.asc()).all()

    internal_users = (
        User.query
        .join(EmployeeProfile, EmployeeProfile.user_id == User.id)
        .filter(User.is_active == True)
        .filter(func.lower(EmployeeProfile.department) == "operations")
        .order_by(User.name.asc())
        .all()
    )

    vendor_xbench_ratings, internal_xbench_ratings = _xbench_average_ratings_for_assignees()

    services = jobcard.services.order_by(OperationsJobcardService.id.asc()).all()
    jobcard_service_ids = [s.id for s in services]
    service_ids = list({s.service_id for s in services if s.service_id})

    existing_checklists_by_service = {}
    master_checklists_by_service = {}

    if jobcard_service_ids:
        existing_rows = (
            OperationsChecklistQuestion.query
            .filter(OperationsChecklistQuestion.jobcard_service_id.in_(jobcard_service_ids))
            .order_by(
                OperationsChecklistQuestion.jobcard_service_id.asc(),
                OperationsChecklistQuestion.sort_order.asc(),
                OperationsChecklistQuestion.id.asc()
            )
            .all()
        )

        for row in existing_rows:
            existing_checklists_by_service.setdefault(row.jobcard_service_id, []).append(row)

    if service_ids:
        master_rows = (
            OperationsChecklistMaster.query
            .filter(OperationsChecklistMaster.service_id.in_(service_ids))
            .filter(OperationsChecklistMaster.is_active == True)
            .order_by(
                OperationsChecklistMaster.service_id.asc(),
                OperationsChecklistMaster.sort_order.asc(),
                OperationsChecklistMaster.id.asc()
            )
            .all()
        )

        for row in master_rows:
            master_checklists_by_service.setdefault(row.service_id, []).append(row)

    # Load assignments once and reuse them for remaining-quantity calculation.
    # Previously _remaining_qty_for_service() executed a SUM query for every
    # service line before assignments were loaded, which became expensive on
    # larger jobcards.
    assignments_by_service = _assignments_by_service(jobcard_service_ids)
    remaining_qty_by_service = _remaining_qty_for_services_bulk(
        services,
        assignments_by_service=assignments_by_service
    )

    if request.method == "POST":
        try:
            assigned_any = False

            for svc in services:
                assigned_qty = Decimal(str(request.form.get(f"assigned_qty_{svc.id}") or 0))

                # Skip untouched service lines before running any validation or
                # quantity queries.  A jobcard may contain many lines while the
                # PM is assigning only one of them.
                if assigned_qty <= 0:
                    continue

                missing_fields = _missing_required_jobcard_fields(svc)
                if missing_fields:
                    missing_labels = ", ".join([f.field_label for f in missing_fields])
                    flash(
                        f"Please complete required jobcard fields for {svc.service_name or 'service line'} before assignment: {missing_labels}",
                        "danger"
                    )
                    return redirect(url_for("operations.update_jobcard_service_fields", service_id=svc.id))

                if svc.status == "Completed":
                    continue

                assignment_type = request.form.get(f"assignment_type_{svc.id}") or "VENDOR"

                if assignment_type == "INTERNAL":
                    internal_user_id = request.form.get(f"internal_user_id_{svc.id}", type=int)
                    internal_user = User.query.get(internal_user_id) if internal_user_id else None

                    if not internal_user:
                        continue

                    internal_deadline = request.form.get(f"internal_deadline_{svc.id}") or None
                    internal_instruction = request.form.get(f"internal_instruction_{svc.id}") or ""
                    file_title = _clean(request.form.get(f"internal_assignment_file_title_{svc.id}"))
                    file_path = _save_jobcard_file(request.files.get(f"internal_assignment_file_{svc.id}"))

                    assignment = OperationsJobcardAssignment(
                        jobcard_service_id=svc.id,
                        assignment_type="PRODUCTION",
                        assigned_to_type="INTERNAL",
                        internal_user_id=internal_user.id,
                        assigned_qty=assigned_qty,
                        deadline=datetime.strptime(internal_deadline, "%Y-%m-%dT%H:%M") if internal_deadline else None,
                        instruction=internal_instruction,
                        status="Assigned",
                        file_title=file_title or None,
                        file_path=file_path or None,
                        additional_instruction=internal_instruction or None,
                        assigned_at=_now_ist()
                    )

                    db.session.add(assignment)
                    db.session.flush()

                    if request.form.get("capture_workload_{}".format(svc.id)) == "1":
                        standard_id = request.form.get("workload_standard_id", type=int)
                        standard = OperationsWorkloadStandard.query.get(standard_id) if standard_id else None
                        workload_quantity = request.form.get("workload_quantity_{}".format(svc.id)) or assigned_qty
                        if not standard or not standard.is_active:
                            raise ValueError("Select a valid workload classification before saving internal workload.")
                        create_workload_entry(
                            assignment=assignment,
                            standard=standard,
                            quantity=workload_quantity,
                            user_id=current_user.id,
                            source="ASSIGNMENT_ENTRY",
                        )

                    assigned_any = True

                else:
                    vendor_id = request.form.get(f"vendor_id_{svc.id}", type=int)
                    vendor = VendorMaster.query.get(vendor_id) if vendor_id else None

                    if not vendor:
                        continue
                    allowed, block_reason = _vendor_assignment_allowed(vendor)
                    if not allowed:
                        raise ValueError("{} cannot be assigned: {}".format(vendor.name, block_reason or "vendor is not eligible"))

                    wordcount = assigned_qty
                    rate = request.form.get(f"rate_{svc.id}") or 0
                    rate_decimal = _rate4(rate)
                    deadline = request.form.get(f"deadline_{svc.id}") or None
                    special_instruction = request.form.get(f"special_instruction_{svc.id}") or ""
                    flat_rate = 1 if request.form.get(f"flat_rate_{svc.id}") == "1" else 0
                    file_title = _clean(request.form.get(f"assignment_file_title_{svc.id}"))
                    file_path = _save_jobcard_file(request.files.get(f"assignment_file_{svc.id}"))

                    assignment = OperationsJobcardAssignment(
                        jobcard_service_id=svc.id,
                        assignment_type="PRODUCTION",
                        assigned_to_type="VENDOR",
                        vendor_id=vendor.id,
                        assigned_qty=assigned_qty,
                        rate=rate_decimal,
                        flat_rate=True if flat_rate == 1 else False,
                        deadline=datetime.strptime(deadline, "%Y-%m-%dT%H:%M") if deadline else None,
                        instruction=special_instruction,
                        status="Assigned",
                        assigned_at=_now_ist(),
                        file_title=file_title or None,
                        file_path=file_path or None,
                        additional_instruction=special_instruction or None,
                        external_checklist_token=uuid.uuid4().hex
                    )

                    db.session.add(assignment)
                    db.session.flush()

                    assignment.external_checklist_url = url_for(
                        "operations.external_checklist",
                        token=assignment.external_checklist_token,
                        _external=True
                    )

                    push_job_to_pms(
                        jobcard=jobcard,
                        service_row=svc,
                        vendor=vendor,
                        wordcount=wordcount,
                        rate=rate_decimal,
                        flat_rate=flat_rate,
                        deadline=deadline,
                        special_instruction=special_instruction,
                        checklist_url=assignment.external_checklist_url,
                        assignment_id=assignment.id
                    )

                    assigned_any = True

                checklist_labels = request.form.getlist(f"checklist_label_{svc.id}[]")
                checklist_types = request.form.getlist(f"checklist_type_{svc.id}[]")
                checklist_options = request.form.getlist(f"checklist_options_{svc.id}[]")
                checklist_required = request.form.getlist(f"checklist_required_{svc.id}[]")

                existing_questions = (
                    OperationsChecklistQuestion.query
                    .filter_by(jobcard_service_id=svc.id)
                    .count()
                )

                if existing_questions == 0:

                    for idx, label in enumerate(checklist_labels):
                        label = _clean(label)

                        if not label:
                            continue

                        qtype = checklist_types[idx] if idx < len(checklist_types) else "checkbox"
                        opts = checklist_options[idx] if idx < len(checklist_options) else ""

                        db.session.add(OperationsChecklistQuestion(
                            jobcard_service_id=svc.id,
                            question_text=label,
                            question_type=qtype,
                            options=opts or None,
                            is_required=str(idx) in checklist_required,
                            sort_order=idx + 1,
                            created_by_id=current_user.id,
                        ))


            if assigned_any:
                _refresh_jobcard_status_from_assignments(jobcard)
                db.session.commit()
                flash("Assignment completed successfully.", "success")
            else:
                flash("No new assignment selected.", "warning")

            return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

        except Exception as e:
            db.session.rollback()
            flash(f"Assignment failed: {str(e)}", "danger")

    _, workload_standards_payload = _active_workload_standards_payload()

    return render_template(
        "operations/vendor_assignment.html",
        jobcard=jobcard,
        services=services,
        vendors=vendors,
        internal_users=internal_users,
        master_checklists_by_service=master_checklists_by_service,
        existing_checklists_by_service=existing_checklists_by_service,
        remaining_qty_by_service=remaining_qty_by_service,
        assignments_by_service=assignments_by_service,
        vendor_xbench_ratings=vendor_xbench_ratings,
        internal_xbench_ratings=internal_xbench_ratings,
        workload_standards_payload=workload_standards_payload,
    )

@operations_bp.route("/jobcards/<int:jobcard_id>/bulk-production-assign", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def bulk_production_assignment(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

    if not _can_pm_manage_jobcard(jobcard):
        abort(403)

    if _jobcard_is_locked(jobcard):
        flash("Bulk assignment is not allowed because this jobcard is closed, billing exists, or closure approval is pending.", "danger")
        return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

    service_ids = request.form.getlist("bulk_service_ids[]", type=int)

    if not service_ids:
        flash("Please select at least one service line for bulk assignment.", "danger")
        return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

    assigned_count = 0
    skipped_count = 0
    errors = []

    try:
        services = (
            OperationsJobcardService.query
            .filter(OperationsJobcardService.jobcard_id == jobcard.id)
            .filter(OperationsJobcardService.id.in_(service_ids))
            .order_by(OperationsJobcardService.id.asc())
            .all()
        )

        for svc in services:
            missing_fields = _missing_required_jobcard_fields(svc)
            if missing_fields:
                missing_labels = ", ".join([f.field_label for f in missing_fields])
                errors.append(
                    f"{svc.service_name or 'Service line'}: required fields missing - {missing_labels}"
                )
                continue

            remaining_qty = _remaining_qty_for_service(svc)


            assigned_qty = _parse_decimal_form_value(
                request.form.get(f"bulk_assigned_qty_{svc.id}")
            )

            if assigned_qty <= 0:
                skipped_count += 1
                continue

            if svc.status == "Completed":
                skipped_count += 1
                continue

            assignment_type = request.form.get(f"bulk_assignment_type_{svc.id}") or "VENDOR"

            if assignment_type == "INTERNAL":
                internal_user_id = request.form.get(f"bulk_internal_user_id_{svc.id}", type=int)
                internal_user = User.query.get(internal_user_id) if internal_user_id else None

                if not internal_user:
                    errors.append(f"{svc.service_name}: internal user missing.")
                    continue

                internal_deadline = request.form.get(f"bulk_internal_deadline_{svc.id}") or None
                internal_instruction = request.form.get(f"bulk_internal_instruction_{svc.id}") or ""

                assignment = OperationsJobcardAssignment(
                    jobcard_service_id=svc.id,
                    assignment_type="PRODUCTION",
                    assigned_to_type="INTERNAL",
                    internal_user_id=internal_user.id,
                    assigned_qty=assigned_qty,
                    deadline=datetime.strptime(internal_deadline, "%Y-%m-%dT%H:%M") if internal_deadline else None,
                    instruction=internal_instruction,
                    additional_instruction=internal_instruction or None,
                    status="Assigned",
                    assigned_by_id=current_user.id,
                    assigned_at=_now_ist()
                )

                db.session.add(assignment)
                assigned_count += 1

            else:
                vendor_id = request.form.get(f"bulk_vendor_id_{svc.id}", type=int)
                vendor = VendorMaster.query.get(vendor_id) if vendor_id else None

                if not vendor:
                    errors.append(f"{svc.service_name}: vendor missing.")
                    continue
                allowed, block_reason = _vendor_assignment_allowed(vendor)
                if not allowed:
                    errors.append("{}: {} cannot be assigned - {}".format(svc.service_name, vendor.name, block_reason or "vendor is not eligible"))
                    continue

                rate = request.form.get(f"bulk_rate_{svc.id}") or 0
                rate_decimal = _rate4(rate)
                deadline = request.form.get(f"bulk_deadline_{svc.id}") or None
                special_instruction = request.form.get(f"bulk_special_instruction_{svc.id}") or ""
                flat_rate = 1 if request.form.get(f"bulk_flat_rate_{svc.id}") == "1" else 0

                assignment = OperationsJobcardAssignment(
                    jobcard_service_id=svc.id,
                    assignment_type="PRODUCTION",
                    assigned_to_type="VENDOR",
                    vendor_id=vendor.id,
                    assigned_qty=assigned_qty,
                    rate=rate_decimal,
                    flat_rate=True if flat_rate == 1 else False,
                    deadline=datetime.strptime(deadline, "%Y-%m-%dT%H:%M") if deadline else None,
                    instruction=special_instruction,
                    additional_instruction=special_instruction or None,
                    status="Assigned",
                    assigned_by_id=current_user.id,
                    assigned_at=_now_ist(),
                    external_checklist_token=uuid.uuid4().hex
                )

                db.session.add(assignment)
                db.session.flush()

                assignment.external_checklist_url = url_for(
                    "operations.external_checklist",
                    token=assignment.external_checklist_token,
                    _external=True
                )

                push_job_to_pms(
                    jobcard=jobcard,
                    service_row=svc,
                    vendor=vendor,
                    wordcount=assigned_qty,
                    rate=rate_decimal,
                    flat_rate=flat_rate,
                    deadline=deadline,
                    special_instruction=special_instruction,
                    checklist_url=assignment.external_checklist_url,
                    assignment_id=assignment.id
                )

                assigned_count += 1

            # Create checklist from master only if no service checklist exists.
            existing_questions = (
                OperationsChecklistQuestion.query
                .filter_by(jobcard_service_id=svc.id)
                .count()
            )

            if existing_questions == 0:
                master_rows = (
                    OperationsChecklistMaster.query
                    .filter_by(service_id=svc.service_id, is_active=True)
                    .order_by(
                        OperationsChecklistMaster.sort_order.asc(),
                        OperationsChecklistMaster.id.asc()
                    )
                    .all()
                )

                for idx, master in enumerate(master_rows):
                    db.session.add(OperationsChecklistQuestion(
                        jobcard_service_id=svc.id,
                        question_text=master.question_text,
                        question_type=master.question_type,
                        options=master.options,
                        is_required=master.is_required,
                        sort_order=master.sort_order or idx + 1,
                        created_by_id=current_user.id,
                    ))


        if errors:
            db.session.rollback()
            flash("Bulk assignment failed: " + " | ".join(errors), "danger")
            return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

        if assigned_count > 0:
            _refresh_jobcard_status_from_assignments(jobcard)
            db.session.commit()
            flash(f"Bulk assignment completed. {assigned_count} line(s) assigned. {skipped_count} skipped.", "success")
        else:
            db.session.rollback()
            flash("No valid service lines were selected for assignment.", "warning")

    except Exception as e:
        db.session.rollback()
        flash(f"Bulk assignment failed: {str(e)}", "danger")

    return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

def _safe_text(v, max_len=None):
    value = str(v or "").strip()
    value = value.replace("\x00", "")

    if max_len:
        value = value[:max_len]

    return value


@operations_bp.route("/vendors/sync", methods=["POST"])
@login_required
@require_perm("operations.vendor.manage")
def sync_vendors_from_pms():
    jobcard_id = request.form.get("jobcard_id")

    try:
        rows = fetch_pms_vendors()
        synced = 0
        skipped = 0

        for r in rows:
            translator_id = _safe_text(r.get("TranslatorId"), 50)
            name = _safe_text(r.get("Name"), 255)

            if not translator_id or not name:
                skipped += 1
                continue

            # GDPR erasure tombstones prevent a later PMS sync from silently
            # recreating a vendor whose portal profile was deliberately erased.
            translator_hash = hashlib.sha256(translator_id.strip().lower().encode("utf-8")).hexdigest()
            if VendorPrivacyTombstone.query.filter_by(external_identifier_hash=translator_hash).first():
                skipped += 1
                continue

            with db.session.no_autoflush:
                vendor = VendorMaster.query.filter_by(
                    external_translator_id=translator_id
                ).first()

            if not vendor:
                vendor = VendorMaster(
                    external_translator_id=translator_id,
                    name=name
                )
                db.session.add(vendor)

            vendor.name = name
            vendor.status = _safe_text(r.get("Status"), 50)
            vendor.email = _safe_text(r.get("Email"), 255)
            vendor.phone = _safe_text(r.get("Phone"), 50)
            vendor.currency = _safe_text(r.get("Currency"), 20)
            vendor.profile_summary = _safe_text(r.get("ProfileSummary"))
            vendor.is_active = True if str(r.get("Status")) in ("1", "True", "true") else False
            vendor.last_synced_at = datetime.utcnow()

            synced += 1

        db.session.commit()
        flash(f"Vendor sync completed. {synced} vendor(s) updated. {skipped} skipped.", "success")

    except Exception as e:
        db.session.rollback()
        flash(f"Vendor sync failed: {str(e)}", "danger")

    if jobcard_id:
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard_id))

    return redirect(url_for("operations.dashboard"))

@operations_bp.route("/internal-tasks", methods=["GET"])
@login_required
@require_perm("operations.internal_tasks.view")
def internal_tasks():

    q = _clean(request.args.get("q"))
    status = _clean(request.args.get("status"))
    page = request.args.get("page", 1, type=int)
    per_page = 20

    # -----------------------------
    # Normal service internal tasks
    # -----------------------------
    normal_query = (
        OperationsJobcardAssignment.query
        .join(
            OperationsJobcardService,
            OperationsJobcardService.id == OperationsJobcardAssignment.jobcard_service_id
        )
        .join(
            OperationsJobcard,
            OperationsJobcard.id == OperationsJobcardService.jobcard_id
        )
        .outerjoin(
            Quote,
            Quote.id == OperationsJobcard.quote_id
        )
        .filter(
            OperationsJobcardAssignment.assignment_type == "PRODUCTION"
        )
        .filter(
            OperationsJobcardAssignment.assigned_to_type == "INTERNAL"
        )
        .filter(
            OperationsJobcardAssignment.internal_user_id == current_user.id
        )
    )

    if q:
        like = f"%{q}%"
        normal_query = normal_query.filter(or_(
            OperationsJobcard.jobcard_code.ilike(like),
            Quote.quote_code.ilike(like),
            OperationsJobcardService.service_name.ilike(like),
            OperationsJobcardService.service_name.ilike(like),
        ))

    if status:
        normal_query = normal_query.filter(
            OperationsJobcardAssignment.status == status
        )

    normal_rows = normal_query.all()

    normal_items = []
    for row in normal_rows:
        svc = row.jobcard_service
        jobcard = svc.jobcard if svc else None
        quote = jobcard.quote if jobcard else None

        normal_items.append({
            "task_type": "SERVICE",
            "id": row.id,
            "assignment": row,
            "process_assignment": None,
            "quote": quote,
            "jobcard": jobcard,
            "service_name": svc.service_name if svc else "—",
            "line_title": svc.service_name if svc else "—",
            "line_subtitle": row.instruction or row.additional_instruction or "",
            "quantity": row.assigned_qty or 0,
            "assigned_at": row.assigned_at,
            "status": row.status or "Assigned",
            "checklist_status": row.checklist_status,
            "detail_url": url_for("operations.internal_task_detail", assignment_id=row.id),
        })

    # -----------------------------------
    # Internal process task assignments
    # -----------------------------------
    process_query = (
        OperationsJobcardProcessAssignment.query
        .join(
            OperationsJobcardProcess,
            OperationsJobcardProcess.id == OperationsJobcardProcessAssignment.jobcard_process_id
        )
        .join(
            OperationsInternalProcessMaster,
            OperationsInternalProcessMaster.id == OperationsJobcardProcess.process_master_id
        )
        .join(
            OperationsJobcard,
            OperationsJobcard.id == OperationsJobcardProcess.jobcard_id
        )
        .outerjoin(
            Quote,
            Quote.id == OperationsJobcard.quote_id
        )
        .outerjoin(
            OperationsJobcardService,
            OperationsJobcardService.id == OperationsJobcardProcessAssignment.jobcard_service_id
        )
        .filter(
            OperationsJobcardProcessAssignment.assigned_to_type == "INTERNAL"
        )
        .filter(
            OperationsJobcardProcessAssignment.internal_user_id == current_user.id
        )
    )

    if q:
        like = f"%{q}%"
        process_query = process_query.filter(or_(
            OperationsJobcard.jobcard_code.ilike(like),
            Quote.quote_code.ilike(like),
            OperationsInternalProcessMaster.name.ilike(like),
            OperationsInternalProcessMaster.code.ilike(like),
            OperationsJobcardService.service_name.ilike(like),
        ))

    if status:
        process_query = process_query.filter(
            OperationsJobcardProcessAssignment.status == status
        )

    process_rows = process_query.all()

    process_items = []
    for row in process_rows:
        jobcard_process = row.jobcard_process
        process_master = jobcard_process.process_master if jobcard_process else None
        jobcard = jobcard_process.jobcard if jobcard_process else None
        quote = jobcard.quote if jobcard else None
        svc = row.jobcard_service

        process_items.append({
            "task_type": "PROCESS",
            "id": row.id,
            "assignment": None,
            "process_assignment": row,
            "quote": quote,
            "jobcard": jobcard,
            "service_name": svc.service_name if svc else "—",
            "line_title": process_master.name if process_master else "Internal Process",
            "line_subtitle": svc.service_name if svc else "",
            "quantity": row.assigned_qty or 0,
            "assigned_at": row.assigned_at,
            "status": row.status or "Assigned",
            "checklist_status": None,
            "detail_url": url_for("operations.internal_process_task_detail", assignment_id=row.id),
        })

    # Combine both task types
    all_items = normal_items + process_items

    all_items.sort(
        key=lambda x: x["assigned_at"] or datetime.min,
        reverse=True
    )

    total_items = len(all_items)
    start = (page - 1) * per_page
    end = start + per_page
    paginated_items = all_items[start:end]

    class SimplePagination:
        def __init__(self, items, page, per_page, total):
            self.items = items
            self.page = page
            self.per_page = per_page
            self.total = total
            self.pages = (total + per_page - 1) // per_page if total else 0

        @property
        def has_prev(self):
            return self.page > 1

        @property
        def has_next(self):
            return self.page < self.pages

        @property
        def prev_num(self):
            return self.page - 1

        @property
        def next_num(self):
            return self.page + 1

        def iter_pages(self, left_edge=2, left_current=2, right_current=3, right_edge=2):
            last = 0
            for num in range(1, self.pages + 1):
                if (
                    num <= left_edge
                    or (num > self.page - left_current - 1 and num < self.page + right_current)
                    or num > self.pages - right_edge
                ):
                    if last + 1 != num:
                        yield None
                    yield num
                    last = num

    pagination = SimplePagination(
        items=paginated_items,
        page=page,
        per_page=per_page,
        total=total_items
    )

    statuses = [
        "Assigned",
        "In Progress",
        "Completed",
        "On Hold",
        "Delegated"
    ]

    internal_transfer_users = [
        u for u in _get_operations_users()
        if u.id != current_user.id
    ]

    summary = {
        "total": total_items,
        "assigned": sum(1 for x in all_items if x["status"] == "Assigned"),
        "in_progress": sum(1 for x in all_items if x["status"] == "In Progress"),
        "completed": sum(1 for x in all_items if x["status"] == "Completed"),
    }

    return render_template(
        "operations/internal_tasks.html",
        pagination=pagination,
        q=q,
        status=status,
        statuses=statuses,
        internal_transfer_users=internal_transfer_users,
        summary=summary,
    )

@operations_bp.route("/internal-process-tasks/<int:assignment_id>", methods=["GET"])
@login_required
@require_perm("operations.internal_tasks.view")
def internal_process_task_detail(assignment_id):
    assignment = OperationsJobcardProcessAssignment.query.get_or_404(assignment_id)

    if assignment.assigned_to_type != "INTERNAL" or assignment.internal_user_id != current_user.id:
        abort(403)

    statuses = ["Assigned", "In Progress", "Completed", "On Hold"]

    process_code = ""
    process_name = ""

    if assignment.jobcard_process and assignment.jobcard_process.process_master:
        process_code = (assignment.jobcard_process.process_master.code or "").lower()
        process_name = (assignment.jobcard_process.process_master.name or "").lower()

    is_mtpe_task = (
        process_code == "mtpe"
        or process_name == "mtpe"
        or "mtpe" in process_code
        or "mtpe" in process_name
    )

    language_pairs = [
        "English to Hindi",
        "Hindi to English",
        "English to Tamil",
        "Tamil to English",
        "English to Telugu",
        "Telugu to English",
        "English to Bengali",
        "Bengali to English",
        "English to Marathi",
        "Marathi to English",
        "English to Gujarati",
        "Gujarati to English",
        "English to Kannada",
        "Kannada to English",
        "English to Malayalam",
        "Malayalam to English",
        "English to Punjabi",
        "Punjabi to English",
        "Other",
    ]

    mt_names = [
        "Google Translate",
        "Microsoft Translator",
        "DeepL",
        "Amazon Translate",
        "ChatGPT",
        "Gemini",
        "Custom MT Engine",
        "Other",
    ]

    internal_transfer_users = [
        u for u in _get_operations_users()
        if u.id != current_user.id
    ]

    delegation_summary = _delegation_summary_for_process_assignment(assignment)

    jobcard = assignment.jobcard_process.jobcard if assignment.jobcard_process else None

    can_delegate_assignment = (
        assignment.parent_assignment_id is None
        and assignment.assigned_to_type == "INTERNAL"
        and assignment.status not in ["Completed", "Rejected"]
        and delegation_summary["remaining_qty"] > 0
        and jobcard
        and jobcard.status not in ["Ready For Billing", "Closure Approval Pending"]
    )

    return render_template(
        "operations/internal_process_task_detail.html",
        assignment=assignment,
        statuses=statuses,
        is_mtpe_task=is_mtpe_task,
        language_pairs=language_pairs,
        mt_names=mt_names,
        internal_transfer_users=internal_transfer_users,
        delegation_summary=delegation_summary,
        delegated_child_rows=delegation_summary["child_rows"],
        is_deadline_passed=bool(assignment.deadline and _now_ist() > assignment.deadline),
        remaining_delegatable_qty=delegation_summary["remaining_qty"],
        delegated_qty=delegation_summary["delegated_qty"],
        completed_delegated_qty=delegation_summary["completed_qty"],
        can_delegate_assignment=can_delegate_assignment,
    )

@operations_bp.route("/internal-process-tasks/<int:assignment_id>/status", methods=["POST"])
@login_required
@require_perm("operations.internal_tasks.update")
def update_internal_process_task_status(assignment_id):
    assignment = OperationsJobcardProcessAssignment.query.get_or_404(assignment_id)

    if assignment.assigned_to_type != "INTERNAL" or assignment.internal_user_id != current_user.id:
        abort(403)
    
    if assignment.status == "Delegated":
        flash("This parent internal process task is fully delegated. Complete delegated child tasks instead.", "danger")
        return redirect(url_for("operations.internal_process_task_detail", assignment_id=assignment.id))

    new_status = request.form.get("status")
    completion_remark = _clean(request.form.get("completion_remark"))
    now_ist = _now_ist()
    is_late_completion = bool(
        new_status == "Completed"
        and assignment.deadline
        and now_ist > assignment.deadline
    )

    if new_status not in ["Assigned", "In Progress", "Completed", "On Hold"]:
        flash("Invalid status selected.", "danger")
        return redirect(url_for("operations.internal_process_task_detail", assignment_id=assignment.id))

    process_code = ""
    process_name = ""

    if assignment.jobcard_process and assignment.jobcard_process.process_master:
        process_code = (assignment.jobcard_process.process_master.code or "").lower()
        process_name = (assignment.jobcard_process.process_master.name or "").lower()

    is_mtpe_task = (
        process_code == "mtpe"
        or process_name == "mtpe"
        or "mtpe" in process_code
        or "mtpe" in process_name
    )

    if is_mtpe_task:
        mtpe_language_pair = _clean(request.form.get("mtpe_language_pair"))
        mtpe_mt_name = _clean(request.form.get("mtpe_mt_name"))
        mtpe_accuracy_raw = _clean(request.form.get("mtpe_accuracy"))
        mtpe_feedback = _clean(request.form.get("mtpe_feedback"))
        mtpe_remarks = _clean(request.form.get("mtpe_remarks"))

        if mtpe_accuracy_raw:
            try:
                mtpe_accuracy = Decimal(str(mtpe_accuracy_raw))
            except Exception:
                flash("MTPE Accuracy must be a valid number.", "danger")
                return redirect(url_for("operations.internal_process_task_detail", assignment_id=assignment.id))

            if mtpe_accuracy < 0 or mtpe_accuracy > 100:
                flash("MTPE Accuracy must be between 0 and 100.", "danger")
                return redirect(url_for("operations.internal_process_task_detail", assignment_id=assignment.id))
        else:
            mtpe_accuracy = None

        if new_status == "Completed":
            missing_fields = []

            if not mtpe_language_pair:
                missing_fields.append("Language Pair")

            if not mtpe_mt_name:
                missing_fields.append("MT Name")

            if mtpe_accuracy is None:
                missing_fields.append("Accuracy")

            if not mtpe_feedback:
                missing_fields.append("Post Editor Feedback")

            if not mtpe_remarks:
                missing_fields.append("Remarks")

            if missing_fields:
                flash(
                    "Please fill MTPE details before completing this task: " + ", ".join(missing_fields),
                    "danger"
                )
                return redirect(url_for("operations.internal_process_task_detail", assignment_id=assignment.id))

        assignment.mtpe_language_pair = mtpe_language_pair or None
        assignment.mtpe_mt_name = mtpe_mt_name or None
        assignment.mtpe_accuracy = mtpe_accuracy
        assignment.mtpe_feedback = mtpe_feedback or None
        assignment.mtpe_remarks = mtpe_remarks or None

    assignment.status = new_status

    if new_status == "Completed":
        assignment.completed_at = now_ist
        assignment.completion_remark = completion_remark if is_late_completion else None
    else:
        assignment.completed_at = None
        assignment.completion_remark = None

    if assignment.parent_assignment_id:
        parent = OperationsJobcardProcessAssignment.query.get(assignment.parent_assignment_id)
        _normalize_effective_process_assignment_status(parent)

    jobcard_process = assignment.jobcard_process
    _refresh_jobcard_process_status(jobcard_process)

    db.session.commit()

    flash("Internal process task status updated successfully.", "success")
    return redirect(url_for("operations.internal_process_task_detail", assignment_id=assignment.id))

@operations_bp.route("/internal-assignments/<int:assignment_id>/transfer", methods=["POST"])
@login_required
@require_perm("operations.internal_tasks.update")
def transfer_internal_assignment(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if assignment.assigned_to_type != "INTERNAL":
        abort(403)

    if assignment.internal_user_id != current_user.id:
        abort(403)

    if assignment.assignment_type not in ["PRODUCTION", "QC"]:
        flash("Only internal production or QC tasks can be transferred.", "danger")
        return _redirect_after_internal_assignment_transfer(assignment)

    if assignment.status == "Completed":
        flash("Completed tasks cannot be transferred.", "danger")
        return _redirect_after_internal_assignment_transfer(assignment)

    svc = assignment.jobcard_service
    jobcard = svc.jobcard

    if jobcard.status in ["Ready For Billing", "Closure Approval Pending"]:
        flash("Tasks cannot be transferred after jobcard closure or while closure approval is pending.", "danger")
        return _redirect_after_internal_assignment_transfer(assignment)

    latest_pi = None
    latest_invoice = None

    if jobcard.quote_id:
        latest_pi = (
            ProformaInvoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(ProformaInvoice.status != "Cancelled")
            .first()
        )

        latest_invoice = (
            Invoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(Invoice.status != "Cancelled")
            .first()
        )

    if latest_pi or latest_invoice:
        flash("Tasks cannot be transferred because PI or Invoice already exists.", "danger")
        return _redirect_after_internal_assignment_transfer(assignment)

    new_user_id = request.form.get("new_internal_user_id", type=int)
    transfer_reason = _clean(request.form.get("transfer_reason"))

    if not new_user_id:
        flash("Please select a user to transfer this task.", "danger")
        return _redirect_after_internal_assignment_transfer(assignment)

    if new_user_id == current_user.id:
        flash("You cannot transfer the task to yourself.", "danger")
        return _redirect_after_internal_assignment_transfer(assignment)

    if not transfer_reason:
        flash("Transfer reason is required.", "danger")
        return _redirect_after_internal_assignment_transfer(assignment)

    eligible_users = _get_operations_users()
    eligible_user_ids = {u.id for u in eligible_users}

    if new_user_id not in eligible_user_ids:
        flash("Selected user is not eligible for internal task transfer.", "danger")
        return _redirect_after_internal_assignment_transfer(assignment)

    new_user = User.query.get(new_user_id)

    if not new_user or not new_user.is_active:
        flash("Invalid user selected.", "danger")
        return _redirect_after_internal_assignment_transfer(assignment)

    old_user = assignment.internal_user

    transfer_note = (
        f"Transferred on {_now_ist().strftime('%d-%m-%Y %I:%M %p')} "
        f"from {old_user.name if old_user else '—'} "
        f"to {new_user.name}. "
        f"Reason: {transfer_reason}"
    )

    existing_additional_instruction = assignment.additional_instruction or ""

    if existing_additional_instruction:
        assignment.additional_instruction = f"{existing_additional_instruction}\n\n{transfer_note}"
    else:
        assignment.additional_instruction = transfer_note

    assignment.internal_user_id = new_user.id

    # Optional but useful: makes the task appear fresh in the new user's task list.
    assignment.assigned_at = _now_ist()

    db.session.commit()

    flash(f"Task transferred successfully to {new_user.name}.", "success")
    return _redirect_after_internal_assignment_transfer(assignment)

@operations_bp.route("/internal-assignments/<int:assignment_id>/delegate", methods=["POST"])
@login_required
@require_perm("operations.internal_tasks.update")
def delegate_internal_assignment(assignment_id):
    parent = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if parent.assigned_to_type != "INTERNAL":
        abort(403)

    if parent.internal_user_id != current_user.id:
        abort(403)

    if parent.parent_assignment_id is not None:
        flash("Delegated tasks cannot be delegated again.", "danger")
        return _redirect_after_internal_assignment_transfer(parent)

    if parent.assignment_type not in ["PRODUCTION", "QC"]:
        flash("Only internal production or QC tasks can be delegated.", "danger")
        return _redirect_after_internal_assignment_transfer(parent)

    if parent.status == "Completed":
        flash("Completed tasks cannot be delegated.", "danger")
        return _redirect_after_internal_assignment_transfer(parent)

    svc = parent.jobcard_service
    jobcard = svc.jobcard

    if jobcard.status in ["Ready For Billing", "Closure Approval Pending"]:
        flash("Tasks cannot be delegated after jobcard closure or while closure approval is pending.", "danger")
        return _redirect_after_internal_assignment_transfer(parent)

    latest_pi = None
    latest_invoice = None

    if jobcard.quote_id:
        latest_pi = (
            ProformaInvoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(ProformaInvoice.status != "Cancelled")
            .first()
        )

        latest_invoice = (
            Invoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(Invoice.status != "Cancelled")
            .first()
        )

    if latest_pi or latest_invoice:
        flash("Tasks cannot be delegated because PI or Invoice already exists.", "danger")
        return _redirect_after_internal_assignment_transfer(parent)

    user_ids = request.form.getlist("delegate_user_id[]")
    qty_values = request.form.getlist("delegate_qty[]")
    deadline_values = request.form.getlist("delegate_deadline[]")
    instruction_values = request.form.getlist("delegate_instruction[]")

    if not user_ids:
        flash("Please add at least one resource for delegation.", "danger")
        return _redirect_after_internal_assignment_transfer(parent)

    eligible_users = _get_operations_users()
    eligible_user_ids = {u.id for u in eligible_users}

    # Important: calculate existing delegated quantity BEFORE adding new child rows.
    existing_delegated_qty = _delegated_qty_for_assignment(parent)
    parent_qty = Decimal(str(parent.assigned_qty or 0))
    remaining_qty = parent_qty - existing_delegated_qty

    if remaining_qty < 0:
        remaining_qty = Decimal("0")

    if remaining_qty <= 0:
        parent.status = "Delegated"
        parent.delegated_at = parent.delegated_at or _now_ist()
        db.session.commit()

        flash("This task is already fully delegated. No remaining quantity is available.", "warning")
        return _redirect_after_internal_assignment_transfer(parent)

    total_new_qty = Decimal("0")
    parsed_rows = []

    for idx, raw_user_id in enumerate(user_ids):
        if not str(raw_user_id).isdigit():
            continue

        delegate_user_id = int(raw_user_id)

        if delegate_user_id == current_user.id:
            flash("You cannot delegate a task to yourself.", "danger")
            return _redirect_after_internal_assignment_transfer(parent)

        if delegate_user_id not in eligible_user_ids:
            flash("Selected user is not eligible for delegation.", "danger")
            return _redirect_after_internal_assignment_transfer(parent)

        raw_qty = qty_values[idx] if idx < len(qty_values) else "0"

        try:
            qty = Decimal(str(raw_qty or 0))
        except Exception:
            qty = Decimal("0")

        if qty <= 0:
            continue

        deadline_raw = deadline_values[idx] if idx < len(deadline_values) else None
        instruction = instruction_values[idx] if idx < len(instruction_values) else ""

        deadline = None
        if deadline_raw:
            deadline = datetime.strptime(deadline_raw, "%Y-%m-%dT%H:%M")

        parsed_rows.append({
            "user_id": delegate_user_id,
            "qty": qty,
            "deadline": deadline,
            "instruction": _clean(instruction),
        })

        total_new_qty += qty

    if not parsed_rows:
        flash("Please enter valid delegation details.", "danger")
        return _redirect_after_internal_assignment_transfer(parent)

    if total_new_qty > remaining_qty:
        flash(
            f"Delegated quantity exceeds remaining available quantity. Available: {remaining_qty}",
            "danger"
        )
        return _redirect_after_internal_assignment_transfer(parent)

    for row in parsed_rows:
        child = OperationsJobcardAssignment(
            jobcard_service_id=parent.jobcard_service_id,
            parent_assignment_id=parent.id,
            assignment_type=parent.assignment_type,
            assigned_to_type="INTERNAL",
            internal_user_id=row["user_id"],
            assigned_qty=row["qty"],
            deadline=row["deadline"] or parent.deadline,
            instruction=row["instruction"] or parent.instruction,
            additional_instruction=row["instruction"] or parent.additional_instruction,
            status="Assigned",
            checklist_status="Pending" if parent.assignment_type == "PRODUCTION" else None,
            file_title=parent.file_title,
            file_path=parent.file_path,
            assigned_by_id=current_user.id,
            assigned_at=_now_ist(),
        )

        db.session.add(child)

    new_total_delegated_qty = existing_delegated_qty + total_new_qty

    if new_total_delegated_qty >= parent_qty:
        parent.status = "Delegated"
        parent.delegated_at = _now_ist()
    else:
        # Keep parent open so remaining quantity can still be delegated later.
        if parent.status == "Delegated":
            parent.status = "Assigned"

    db.session.commit()

    remaining_after = parent_qty - new_total_delegated_qty
    if remaining_after < 0:
        remaining_after = Decimal("0")

    flash(
        f"Task delegated successfully. Remaining quantity available for delegation: {remaining_after}",
        "success"
    )
    return _redirect_after_internal_assignment_transfer(parent)

@operations_bp.route("/internal-process-assignments/<int:assignment_id>/delegate", methods=["POST"])
@login_required
@require_perm("operations.internal_tasks.update")
def delegate_internal_process_assignment(assignment_id):
    parent = OperationsJobcardProcessAssignment.query.get_or_404(assignment_id)

    if parent.assigned_to_type != "INTERNAL":
        abort(403)

    if parent.internal_user_id != current_user.id:
        abort(403)

    if parent.parent_assignment_id is not None:
        flash("Delegated internal process tasks cannot be delegated again.", "danger")
        return redirect(url_for("operations.internal_process_task_detail", assignment_id=parent.id))

    if parent.status == "Completed":
        flash("Completed internal process tasks cannot be delegated.", "danger")
        return redirect(url_for("operations.internal_process_task_detail", assignment_id=parent.id))

    jobcard_process = parent.jobcard_process
    jobcard = jobcard_process.jobcard if jobcard_process else None

    if not jobcard:
        flash("Jobcard not found for this process task.", "danger")
        return redirect(url_for("operations.internal_tasks"))

    if jobcard.status in ["Ready For Billing", "Closure Approval Pending"]:
        flash("Tasks cannot be delegated after jobcard closure or while closure approval is pending.", "danger")
        return redirect(url_for("operations.internal_process_task_detail", assignment_id=parent.id))

    latest_pi = None
    latest_invoice = None

    if jobcard.quote_id:
        latest_pi = (
            ProformaInvoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(ProformaInvoice.status != "Cancelled")
            .first()
        )

        latest_invoice = (
            Invoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(Invoice.status != "Cancelled")
            .first()
        )

    if latest_pi or latest_invoice:
        flash("Tasks cannot be delegated because PI or Invoice already exists.", "danger")
        return redirect(url_for("operations.internal_process_task_detail", assignment_id=parent.id))

    user_ids = request.form.getlist("delegate_user_id[]")
    qty_values = request.form.getlist("delegate_qty[]")
    deadline_values = request.form.getlist("delegate_deadline[]")
    instruction_values = request.form.getlist("delegate_instruction[]")

    if not user_ids:
        flash("Please add at least one resource for delegation.", "danger")
        return redirect(url_for("operations.internal_process_task_detail", assignment_id=parent.id))

    eligible_users = _get_operations_users()
    eligible_user_ids = {u.id for u in eligible_users}

    existing_delegated_qty = _delegated_qty_for_process_assignment(parent)
    parent_qty = Decimal(str(parent.assigned_qty or 0))
    remaining_qty = parent_qty - existing_delegated_qty

    if remaining_qty < 0:
        remaining_qty = Decimal("0")

    if remaining_qty <= 0:
        parent.status = "Delegated"
        parent.delegated_at = parent.delegated_at or _now_ist()
        db.session.commit()

        flash("This internal process task is already fully delegated.", "warning")
        return redirect(url_for("operations.internal_process_task_detail", assignment_id=parent.id))

    total_new_qty = Decimal("0")
    parsed_rows = []

    for idx, raw_user_id in enumerate(user_ids):
        if not str(raw_user_id).isdigit():
            continue

        delegate_user_id = int(raw_user_id)

        if delegate_user_id == current_user.id:
            flash("You cannot delegate a task to yourself.", "danger")
            return redirect(url_for("operations.internal_process_task_detail", assignment_id=parent.id))

        if delegate_user_id not in eligible_user_ids:
            flash("Selected user is not eligible for delegation.", "danger")
            return redirect(url_for("operations.internal_process_task_detail", assignment_id=parent.id))

        raw_qty = qty_values[idx] if idx < len(qty_values) else "0"

        try:
            qty = Decimal(str(raw_qty or 0))
        except Exception:
            qty = Decimal("0")

        if qty <= 0:
            continue

        deadline_raw = deadline_values[idx] if idx < len(deadline_values) else None
        instruction = instruction_values[idx] if idx < len(instruction_values) else ""

        deadline = None
        if deadline_raw:
            deadline = datetime.strptime(deadline_raw, "%Y-%m-%dT%H:%M")

        parsed_rows.append({
            "user_id": delegate_user_id,
            "qty": qty,
            "deadline": deadline,
            "instruction": _clean(instruction),
        })

        total_new_qty += qty

    if not parsed_rows:
        flash("Please enter valid delegation details.", "danger")
        return redirect(url_for("operations.internal_process_task_detail", assignment_id=parent.id))

    if total_new_qty > remaining_qty:
        flash(
            f"Delegated quantity exceeds remaining available quantity. Available: {remaining_qty}",
            "danger"
        )
        return redirect(url_for("operations.internal_process_task_detail", assignment_id=parent.id))

    for row in parsed_rows:
        child = OperationsJobcardProcessAssignment(
            parent_assignment_id=parent.id,
            jobcard_process_id=parent.jobcard_process_id,
            jobcard_service_id=parent.jobcard_service_id,
            assigned_to_type="INTERNAL",
            internal_user_id=row["user_id"],
            assigned_qty=row["qty"],
            rate=parent.rate,
            flat_rate=parent.flat_rate,
            deadline=row["deadline"] or parent.deadline,
            instruction=row["instruction"] or parent.instruction,
            additional_instruction=row["instruction"] or parent.additional_instruction,
            status="Assigned",
            file_title=parent.file_title,
            file_path=parent.file_path,
            assigned_by_id=current_user.id,
            assigned_at=_now_ist(),
        )

        db.session.add(child)

    new_total_delegated_qty = existing_delegated_qty + total_new_qty

    if new_total_delegated_qty >= parent_qty:
        parent.status = "Delegated"
        parent.delegated_at = _now_ist()
    else:
        if parent.status == "Delegated":
            parent.status = "Assigned"

    _refresh_jobcard_process_status(jobcard_process)

    db.session.commit()

    remaining_after = parent_qty - new_total_delegated_qty
    if remaining_after < 0:
        remaining_after = Decimal("0")

    flash(
        f"Internal process task delegated successfully. Remaining quantity available: {remaining_after}",
        "success"
    )
    return redirect(url_for("operations.internal_process_task_detail", assignment_id=parent.id))

@operations_bp.route("/internal-tasks/<int:assignment_id>/status", methods=["POST"])
@login_required
@require_perm("operations.internal_tasks.update")
def update_internal_task_status(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if assignment.assigned_to_type != "INTERNAL" or assignment.internal_user_id != current_user.id:
        abort(403)

    svc = assignment.jobcard_service
    jobcard = svc.jobcard

    new_status = request.form.get("status")
    completion_remark = _clean(request.form.get("completion_remark"))
    now_ist = _now_ist()

    is_late_completion = bool(
        new_status == "Completed"
        and assignment.deadline
        and now_ist > assignment.deadline
    )

    if new_status not in ["Assigned", "In Progress", "Completed", "On Hold", "Rejected"]:
        flash("Invalid status selected.", "danger")
        return redirect(
            url_for(
                "operations.internal_task_detail",
                assignment_id=assignment.id
            )
        )

    if new_status == "Rejected":
        if assignment.status in ["Completed", "Rejected"]:
            flash("Completed or already rejected tasks cannot be rejected.", "danger")
            return redirect(url_for("operations.internal_task_detail", assignment_id=assignment.id))
        if not completion_remark:
            flash("Please enter a rejection reason.", "danger")
            return redirect(url_for("operations.internal_task_detail", assignment_id=assignment.id))

    if new_status == "Completed":
        if is_late_completion and not completion_remark:
            flash(
                "Completion remark is mandatory because this task is being closed after its deadline.",
                "danger"
            )
            return redirect(
                url_for(
                    "operations.internal_task_detail",
                    assignment_id=assignment.id
                )
            )

        if (
            svc.checklist_questions.count() > 0
            and assignment.checklist_status != "Submitted"
        ):
            flash(
                "Please submit the checklist before completing this task.",
                "danger"
            )
            return redirect(
                url_for(
                    "operations.internal_task_detail",
                    assignment_id=assignment.id
                )
            )

    assignment.status = new_status

    if new_status == "Rejected":
        assignment.completed_at = None
        assignment.completion_remark = completion_remark
        OperationsJobcardWorkloadEntry.query.filter_by(assignment_id=assignment.id, is_active=True).update(
            {"is_active": False, "updated_by_id": current_user.id, "updated_at": datetime.utcnow()},
            synchronize_session=False
        )
    elif new_status == "Completed":
        assignment.completed_at = now_ist
        assignment.completion_remark = (
            completion_remark if is_late_completion else None
        )
    else:
        assignment.completed_at = None
        assignment.completion_remark = None

    if assignment.parent_assignment_id:
        parent = OperationsJobcardAssignment.query.get(
            assignment.parent_assignment_id
        )
        if parent:
            _normalize_effective_service_assignment_status(parent)

    _refresh_service_status_after_change(svc)
    _refresh_jobcard_status(jobcard)

    db.session.commit()

    flash("Task status updated successfully.", "success")
    return redirect(
        url_for(
            "operations.internal_task_detail",
            assignment_id=assignment.id
        )
    )

@operations_bp.route("/internal-tasks/<int:assignment_id>", methods=["GET"])
@login_required
@require_perm("operations.internal_tasks.view")
def internal_task_detail(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if assignment.assigned_to_type != "INTERNAL" or assignment.internal_user_id != current_user.id:
        abort(403)

    svc = assignment.jobcard_service
    statuses = ["Assigned", "In Progress", "Completed", "On Hold", "Rejected"]

    checklist_questions = svc.checklist_questions.order_by(
        OperationsChecklistQuestion.sort_order.asc()
    ).all()

    internal_transfer_users = [
        u for u in _get_operations_users()
        if u.id != current_user.id
    ]

    delegation_summary = _delegation_summary_for_assignment(assignment)

    can_delegate_assignment = (
        assignment.parent_assignment_id is None
        and assignment.assignment_type in ["PRODUCTION", "QC"]
        and assignment.status not in ["Completed", "Rejected"]
        and delegation_summary["remaining_qty"] > 0
        and svc
        and svc.jobcard
        and svc.jobcard.status not in ["Ready For Billing", "Closure Approval Pending"]
    )

    now_ist = _now_ist()
    is_deadline_passed = bool(
        assignment.deadline
        and now_ist > assignment.deadline
    )

    return render_template(
        "operations/internal_task_detail.html",
        assignment=assignment,
        svc=svc,
        statuses=statuses,
        checklist_questions=checklist_questions,
        internal_transfer_users=internal_transfer_users,
        delegation_summary=delegation_summary,
        delegated_child_rows=delegation_summary["child_rows"],
        remaining_delegatable_qty=delegation_summary["remaining_qty"],
        delegated_qty=delegation_summary["delegated_qty"],
        completed_delegated_qty=delegation_summary["completed_qty"],
        can_delegate_assignment=can_delegate_assignment,
        is_deadline_passed=is_deadline_passed,
    )

@operations_bp.route("/qc-tasks", methods=["GET"])
@login_required
@require_perm("operations.internal_tasks.view")
def qc_tasks():
    q = _clean(request.args.get("q"))
    status = _clean(request.args.get("status"))
    page = request.args.get("page", 1, type=int)

    query = (
        OperationsJobcardAssignment.query
        .join(OperationsJobcardService, OperationsJobcardService.id == OperationsJobcardAssignment.jobcard_service_id)
        .join(OperationsJobcard, OperationsJobcard.id == OperationsJobcardService.jobcard_id)
        .outerjoin(Quote, Quote.id == OperationsJobcard.quote_id)
        .filter(OperationsJobcardAssignment.assignment_type == "QC")
        .filter(OperationsJobcardAssignment.assigned_to_type == "INTERNAL")
        .filter(OperationsJobcardAssignment.internal_user_id == current_user.id)
    )

    if q:
        like = f"%{q}%"
        query = query.filter(or_(
            OperationsJobcard.jobcard_code.ilike(like),
            Quote.quote_code.ilike(like),
            OperationsJobcardService.service_name.ilike(like),
        ))

    if status:
        query = query.filter(OperationsJobcardAssignment.status == status)

    pagination = (
        query
        .order_by(
            OperationsJobcardAssignment.assigned_at.desc(),
            OperationsJobcardAssignment.id.desc()
        )
        .paginate(page=page, per_page=20, error_out=False)
    )

    statuses = ["Assigned", "In Progress", "Completed", "On Hold", "Delegated"]
    today = _now_ist().date()

    internal_transfer_users = [
        u for u in _get_operations_users()
        if u.id != current_user.id
    ]

    return render_template(
        "operations/qc_tasks.html",
        pagination=pagination,
        q=q,
        status=status,
        statuses=statuses,
        today=today,
        internal_transfer_users=internal_transfer_users,
    )


@operations_bp.route("/qc-tasks/<int:assignment_id>", methods=["GET"])
@login_required
@require_perm("operations.internal_tasks.view")
def qc_task_detail(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if (
        assignment.assignment_type != "QC"
        or assignment.assigned_to_type != "INTERNAL"
        or assignment.internal_user_id != current_user.id
    ):
        abort(403)

    svc = assignment.jobcard_service
    statuses = ["Assigned", "In Progress", "Completed", "On Hold", "Rejected"]

    internal_transfer_users = [
        u for u in _get_operations_users()
        if u.id != current_user.id
    ]

    delegation_summary = _delegation_summary_for_assignment(assignment)

    can_delegate_assignment = (
        assignment.parent_assignment_id is None
        and assignment.assignment_type == "QC"
        and assignment.status not in ["Completed", "Rejected"]
        and delegation_summary["remaining_qty"] > 0
        and svc
        and svc.jobcard
        and svc.jobcard.status not in ["Ready For Billing", "Closure Approval Pending"]
    )

    translator_assignments = _active_translation_assignments(svc) if _is_translation_service(svc) else []

    xbench_reports = (
        XbenchReport.query
        .filter_by(qc_assignment_id=assignment.id)
        .order_by(XbenchReport.uploaded_at.desc(), XbenchReport.id.desc())
        .all()
    )
    latest_xbench_reports_by_translator = {}
    for report in xbench_reports:
        if report.production_assignment_id not in latest_xbench_reports_by_translator:
            latest_xbench_reports_by_translator[report.production_assignment_id] = report

    qc_checklist_questions = _ensure_qc_checklist_questions(assignment)
    if qc_checklist_questions:
        db.session.commit()
    qc_checklist_responses = {
        row.question_id: row
        for row in OperationsQCChecklistResponse.query.filter_by(assignment_id=assignment.id).all()
    }
    qc_checklist_categories = {}
    for question in qc_checklist_questions:
        qc_checklist_categories.setdefault(question.category or "General", []).append(question)

    return render_template(
        "operations/qc_task_detail.html",
        assignment=assignment,
        svc=svc,
        xbench_required=_is_translation_service(svc),
        translator_assignments=translator_assignments,
        xbench_reports=xbench_reports,
        latest_xbench_reports_by_translator=latest_xbench_reports_by_translator,
        is_deadline_passed=bool(assignment.deadline and _now_ist() > assignment.deadline),
        statuses=statuses,
        internal_transfer_users=internal_transfer_users,
        delegation_summary=delegation_summary,
        delegated_child_rows=delegation_summary["child_rows"],
        remaining_delegatable_qty=delegation_summary["remaining_qty"],
        delegated_qty=delegation_summary["delegated_qty"],
        completed_delegated_qty=delegation_summary["completed_qty"],
        can_delegate_assignment=can_delegate_assignment,
        qc_checklist_questions=qc_checklist_questions,
        qc_checklist_responses=qc_checklist_responses,
        qc_checklist_categories=qc_checklist_categories,
    )


@operations_bp.route("/qc-tasks/<int:assignment_id>/checklist", methods=["POST"])
@login_required
@require_perm("operations.internal_tasks.update")
def submit_qc_task_checklist(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)
    if (assignment.assignment_type != "QC" or assignment.assigned_to_type != "INTERNAL" or assignment.internal_user_id != current_user.id):
        abort(403)
    if assignment.status in {"Completed", "Delegated"}:
        flash("This QC checklist is locked for the current task status.", "warning")
        return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))

    questions = _ensure_qc_checklist_questions(assignment)
    errors = []
    now = _now_ist()

    for question in questions:
        field_name = f"qc_checklist_{question.id}"
        value = _clean(request.form.get(field_name))
        upload = request.files.get(field_name)
        existing = OperationsQCChecklistResponse.query.filter_by(question_id=question.id).first()

        if question.question_type == "checkbox":
            value = "yes" if request.form.get(field_name) == "1" else ""
        elif question.question_type == "file":
            if upload and upload.filename:
                try:
                    file_path = _save_qc_checklist_upload(upload, assignment.id, question.id)
                except ValueError as exc:
                    errors.append(f"{question.question_text}: {exc}")
                    continue
                if not existing:
                    existing = OperationsQCChecklistResponse(question_id=question.id, assignment_id=assignment.id)
                    db.session.add(existing)
                existing.file_path = file_path
                existing.response_value = upload.filename
                existing.submitted_by_id = current_user.id
                existing.submitted_at = now
                continue
            if existing and existing.file_path:
                continue
            value = ""

        if question.is_required and not str(value or "").strip():
            errors.append(f"Required: {question.question_text}")
            continue

        if not existing:
            existing = OperationsQCChecklistResponse(question_id=question.id, assignment_id=assignment.id)
            db.session.add(existing)
        existing.response_value = value or None
        existing.is_passed = None
        if question.question_type == "pass_fail":
            existing.is_passed = str(value or "").lower() == "pass"
        existing.score_awarded = (question.weight or 0) if existing.is_passed is not False else 0
        existing.submitted_by_id = current_user.id
        existing.submitted_at = now

    if errors:
        db.session.rollback()
        flash("Please complete the QC checklist: " + " | ".join(errors[:5]), "danger")
        return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))

    assignment.checklist_status = "Submitted"
    assignment.checklist_submitted_at = now
    db.session.commit()
    flash("QC checklist submitted successfully.", "success")
    return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))


@operations_bp.route("/qc-tasks/<int:assignment_id>/xbench/save", methods=["POST"])
@login_required
@require_perm("operations.internal_tasks.update")
def save_qc_xbench_evidence(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if (
        assignment.assignment_type != "QC"
        or assignment.assigned_to_type != "INTERNAL"
        or assignment.internal_user_id != current_user.id
    ):
        abort(403)

    if assignment.status == "Completed":
        flash("This QC task is already completed and its evidence is locked.", "warning")
        return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))

    success, error = _record_xbench_submission(assignment, require_all=False)
    if not success:
        db.session.rollback()
        flash(error, "danger")
        return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))

    db.session.commit()
    flash("Translator Xbench evidence saved successfully.", "success")
    return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))


@operations_bp.route("/qc-tasks/<int:assignment_id>/status", methods=["POST"])
@login_required
@require_perm("operations.internal_tasks.update")
def update_qc_task_status(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if (
        assignment.assignment_type != "QC"
        or assignment.assigned_to_type != "INTERNAL"
        or assignment.internal_user_id != current_user.id
    ):
        abort(403)

    if assignment.status == "Delegated":
        flash("This parent QC task is fully delegated. Complete delegated child QC tasks instead.", "danger")
        return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))

    new_status = request.form.get("status")
    completion_remark = _clean(request.form.get("completion_remark"))
    now_ist = _now_ist()
    is_late_completion = bool(
        new_status == "Completed"
        and assignment.deadline
        and now_ist > assignment.deadline
    )

    if new_status not in ["Assigned", "In Progress", "Completed", "On Hold", "Rejected"]:
        flash("Invalid status selected.", "danger")
        return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))

    svc = assignment.jobcard_service
    jobcard = svc.jobcard
    service_was_qc_pending = (svc.status == "QC Pending")

    if new_status == "Rejected":
        if assignment.status in ["Completed", "Rejected"]:
            flash("Completed or already rejected QC tasks cannot be rejected.", "danger")
            return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))
        if not completion_remark:
            flash("Please enter a rejection reason.", "danger")
            return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))

    if new_status == "Completed":
        qc_questions, qc_responses, missing_qc_items = _qc_checklist_completion_state(assignment)
        if qc_questions and (assignment.checklist_status != "Submitted" or missing_qc_items):
            flash("Submit all required QC checklist items before completing this QC task.", "danger")
            return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))

        if is_late_completion and not completion_remark:
            flash("Completion remark is mandatory because this QC task is being closed after its deadline.", "danger")
            return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))

        success, error = _record_xbench_submission(assignment, require_all=True)
        if not success:
            db.session.rollback()
            flash(error, "danger")
            return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))

    assignment.status = new_status

    if new_status == "Rejected":
        assignment.completed_at = None
        assignment.completion_remark = completion_remark
        OperationsJobcardWorkloadEntry.query.filter_by(assignment_id=assignment.id, is_active=True).update(
            {"is_active": False, "updated_by_id": current_user.id, "updated_at": datetime.utcnow()},
            synchronize_session=False
        )
    elif new_status == "Completed":
        assignment.completed_at = now_ist
        assignment.completion_remark = completion_remark if is_late_completion else None
    else:
        assignment.completed_at = None
        assignment.completion_remark = None

    if new_status in ["Completed", "Rejected"]:
        if new_status == "Rejected" and assignment.assignment_type == "QC" and service_was_qc_pending and not _has_pending_qc(svc):
            svc.status = "Completed"
            svc.completed_at = svc.completed_at or _now_ist()
        else:
            _refresh_service_status_after_change(svc)
        _refresh_jobcard_status(jobcard)

    db.session.commit()

    flash("QC task updated successfully.", "success")
    return redirect(url_for("operations.qc_task_detail", assignment_id=assignment.id))


@operations_bp.route("/xbench/categories", methods=["GET", "POST"])
@login_required
@require_perm("operations.vendor.assign")
def xbench_category_master():
    _ensure_xbench_severity_scale()

    if request.method == "POST":
        action = _clean(request.form.get("action")) or "single"
        severity_id = request.form.get("severity_id", type=int)
        severity_score = request.form.get("severity_score", type=int)

        severity = None
        if severity_id:
            severity = XbenchSeverityMaster.query.filter_by(
                id=severity_id,
                is_active=True,
            ).first()
        elif severity_score:
            severity = XbenchSeverityMaster.query.filter_by(
                severity_rank=severity_score,
                is_active=True,
            ).first()

        if severity_id or severity_score:
            if not severity or severity.severity_rank not in (1, 2, 3, 4, 5):
                flash("Please select a valid Xbench criticality score between 1 and 5.", "danger")
                db.session.rollback()
                return redirect(request.referrer or url_for("operations.xbench_category_master"))

        if action == "bulk":
            raw_ids = request.form.getlist("category_ids")
            category_ids = []
            for raw_id in raw_ids:
                try:
                    category_ids.append(int(raw_id))
                except (TypeError, ValueError):
                    continue

            category_ids = sorted(set(category_ids))
            if not category_ids:
                flash("Select at least one Xbench category for bulk mapping.", "warning")
                return redirect(request.referrer or url_for("operations.xbench_category_master"))

            categories_to_update = XbenchCategoryMaster.query.filter(
                XbenchCategoryMaster.id.in_(category_ids)
            ).all()

            now = _now_ist()
            for category in categories_to_update:
                category.severity_id = severity.id if severity else None
                category.updated_at = now

            db.session.commit()
            if severity:
                flash(
                    f"{len(categories_to_update)} categories mapped to "
                    f"{severity.severity_rank} - {severity.severity_name}.",
                    "success",
                )
            else:
                flash(f"Mapping removed from {len(categories_to_update)} categories.", "success")
            return redirect(request.referrer or url_for("operations.xbench_category_master"))

        category_id = request.form.get("category_id", type=int)
        category = XbenchCategoryMaster.query.get_or_404(category_id)
        category.severity_id = severity.id if severity else None
        category.updated_at = _now_ist()
        db.session.commit()

        if severity:
            flash(
                f"Xbench category mapped to {severity.severity_rank} - {severity.severity_name}.",
                "success",
            )
        else:
            flash("Xbench category mapping removed.", "success")

        return redirect(request.referrer or url_for("operations.xbench_category_master"))

    q = _clean(request.args.get("q"))
    severity_filter = _clean(request.args.get("severity"))
    mapping_filter = _clean(request.args.get("mapping"))

    query = XbenchCategoryMaster.query

    if q:
        like = f"%{q}%"
        query = query.filter(or_(
            XbenchCategoryMaster.category_name.ilike(like),
            XbenchCategoryMaster.category_group.ilike(like),
        ))

    if severity_filter:
        try:
            severity_value = int(severity_filter)
        except (TypeError, ValueError):
            severity_value = None

        if severity_value:
            query = query.join(
                XbenchSeverityMaster,
                XbenchCategoryMaster.severity_id == XbenchSeverityMaster.id,
            ).filter(or_(
                XbenchSeverityMaster.id == severity_value,
                XbenchSeverityMaster.severity_rank == severity_value,
            ))

    if mapping_filter == "mapped":
        query = query.filter(XbenchCategoryMaster.severity_id.isnot(None))
    elif mapping_filter == "unmapped":
        query = query.filter(XbenchCategoryMaster.severity_id.is_(None))

    categories = query.order_by(
        XbenchCategoryMaster.severity_id.is_(None).desc(),
        XbenchCategoryMaster.category_group.asc(),
        XbenchCategoryMaster.category_name.asc(),
    ).all()

    severities = XbenchSeverityMaster.query.filter(
        XbenchSeverityMaster.is_active.is_(True),
        XbenchSeverityMaster.severity_rank.in_([1, 2, 3, 4, 5]),
    ).order_by(
        XbenchSeverityMaster.severity_rank.desc(),
    ).all()

    db.session.commit()

    return render_template(
        "operations/xbench_category_master.html",
        categories=categories,
        severities=severities,
        severity_scale=XBENCH_SEVERITY_SCALE,
        q=q,
        severity_filter=severity_filter,
        mapping_filter=mapping_filter,
        unmapped_count=sum(1 for row in categories if not row.severity_id),
    )



@operations_bp.route("/xbench/translator-ratings", methods=["GET"])
@login_required
@require_perm("operations.vendor.assign")
def xbench_translator_ratings():
    """Show translator-wise Xbench criticality ratings.

    Each QC-task/production-assignment pair contributes only its latest saved
    report, so replacement uploads do not double-count the translator.
    """
    _ensure_xbench_severity_scale()

    q = _clean(request.args.get("q"))
    translator_type = _clean(request.args.get("translator_type")).upper()
    date_from_raw = _clean(request.args.get("date_from"))
    date_to_raw = _clean(request.args.get("date_to"))

    date_from = None
    date_to = None
    try:
        if date_from_raw:
            date_from = datetime.strptime(date_from_raw, "%Y-%m-%d")
    except ValueError:
        flash("Invalid From date ignored.", "warning")
    try:
        if date_to_raw:
            date_to = datetime.strptime(date_to_raw, "%Y-%m-%d") + timedelta(days=1)
    except ValueError:
        flash("Invalid To date ignored.", "warning")

    query = XbenchReport.query.filter(
        XbenchReport.is_uploaded.is_(True),
        XbenchReport.parsing_status == "Parsed",
    )

    if translator_type in {"VENDOR", "INTERNAL"}:
        query = query.filter(XbenchReport.translator_type_snapshot == translator_type)
    if date_from:
        query = query.filter(XbenchReport.uploaded_at >= date_from)
    if date_to:
        query = query.filter(XbenchReport.uploaded_at < date_to)
    if q:
        like = f"%{q}%"
        query = query.filter(XbenchReport.translator_name_snapshot.ilike(like))

    reports = query.order_by(
        XbenchReport.uploaded_at.desc(),
        XbenchReport.id.desc(),
    ).all()

    latest_reports = []
    seen_assignment_keys = set()
    for report in reports:
        key = (report.qc_assignment_id, report.production_assignment_id)
        if key in seen_assignment_keys:
            continue
        seen_assignment_keys.add(key)
        latest_reports.append(report)

    translator_rows = {}
    for report in latest_reports:
        if report.translator_type_snapshot == "VENDOR" and report.translator_vendor_id:
            translator_key = ("VENDOR", report.translator_vendor_id)
        elif report.translator_type_snapshot == "INTERNAL" and report.translator_internal_user_id:
            translator_key = ("INTERNAL", report.translator_internal_user_id)
        else:
            translator_key = (
                report.translator_type_snapshot or "UNKNOWN",
                (report.translator_name_snapshot or "").strip().lower(),
            )

        row = translator_rows.setdefault(translator_key, {
            "translator_key": translator_key,
            "translator_name": report.translator_name_snapshot,
            "translator_type": report.translator_type_snapshot or "UNKNOWN",
            "vendor_id": report.translator_vendor_id,
            "internal_user_id": report.translator_internal_user_id,
            "report_count": 0,
            "assignment_count": 0,
            "total_issues": 0,
            "mapped_issues": 0,
            "unmapped_issues": 0,
            "weighted_points": 0,
            "score_counts": {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
            "latest_report_at": None,
            "latest_jobcard_code": None,
            "reports": [],
        })

        row["report_count"] += 1
        row["assignment_count"] += 1
        row["latest_report_at"] = max(
            [dt for dt in [row["latest_report_at"], report.uploaded_at] if dt is not None],
            default=None,
        )
        if report.jobcard:
            row["latest_jobcard_code"] = report.jobcard.jobcard_code

        report_mapped = 0
        report_unmapped = 0
        report_weighted = 0
        for category_count in report.category_counts.all():
            issue_count = int(category_count.issue_count or 0)
            if issue_count <= 0:
                continue

            row["total_issues"] += issue_count
            severity_rank = None
            if category_count.category and category_count.category.severity:
                severity_rank = category_count.category.severity.severity_rank
            elif category_count.severity_snapshot:
                severity_rank = category_count.severity_snapshot.severity_rank

            if severity_rank in (1, 2, 3, 4, 5):
                row["mapped_issues"] += issue_count
                row["weighted_points"] += issue_count * severity_rank
                row["score_counts"][severity_rank] += issue_count
                report_mapped += issue_count
                report_weighted += issue_count * severity_rank
            else:
                row["unmapped_issues"] += issue_count
                report_unmapped += issue_count

        report_average = round(report_weighted / report_mapped, 2) if report_mapped else None
        row["reports"].append({
            "report": report,
            "average_rating": report_average,
            "mapped_issues": report_mapped,
            "unmapped_issues": report_unmapped,
        })

    rows = []
    for row in translator_rows.values():
        row["average_rating"] = (
            round(row["weighted_points"] / row["mapped_issues"], 2)
            if row["mapped_issues"] else None
        )
        row["mapping_coverage"] = (
            round((row["mapped_issues"] / row["total_issues"]) * 100, 1)
            if row["total_issues"] else 0
        )
        row["reports"] = sorted(
            row["reports"],
            key=lambda item: item["report"].uploaded_at or datetime.min,
            reverse=True,
        )
        rows.append(row)

    rows.sort(key=lambda row: (
        -(row["average_rating"] or 0),
        -row["total_issues"],
        row["translator_name"].lower(),
    ))

    total_translators = len(rows)
    total_reports = sum(row["report_count"] for row in rows)
    total_issues = sum(row["total_issues"] for row in rows)
    total_mapped_issues = sum(row["mapped_issues"] for row in rows)
    overall_weighted_points = sum(row["weighted_points"] for row in rows)
    overall_average_rating = (
        round(overall_weighted_points / total_mapped_issues, 2)
        if total_mapped_issues else None
    )

    return render_template(
        "operations/xbench_translator_ratings.html",
        rows=rows,
        q=q,
        translator_type=translator_type,
        date_from=date_from_raw,
        date_to=date_to_raw,
        total_translators=total_translators,
        total_reports=total_reports,
        total_issues=total_issues,
        overall_average_rating=overall_average_rating,
    )


@operations_bp.route("/xbench/severities", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def add_xbench_severity():
    _ensure_xbench_severity_scale()
    db.session.commit()

    flash(
        "Xbench criticality uses the fixed 1-5 scale: "
        "1 Minor, 2 Low, 3 Medium, 4 Critical and 5 Highly Critical.",
        "info",
    )
    return redirect(url_for("operations.xbench_category_master"))


@operations_bp.route("/jobcards/<int:jobcard_id>/deadline-extension/request", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def request_client_deadline_extension(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)
    quote = jobcard.quote

    if not quote:
        flash("This jobcard is not linked to a quote.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    current_deadline = jobcard.client_deadline or quote.client_deadline
    if not current_deadline:
        flash("Set the original client deadline before requesting an extension.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    pending = (
        OperationsClientDeadlineExtensionRequest.query
        .filter(
            OperationsClientDeadlineExtensionRequest.jobcard_id == jobcard.id,
            OperationsClientDeadlineExtensionRequest.status.in_(
                DEADLINE_EXTENSION_PENDING_STATUSES
            ),
        )
        .first()
    )
    if pending:
        flash("A deadline-extension request is already pending for this jobcard.", "warning")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    quote_owner = _deadline_extension_quote_owner(jobcard)
    if not quote_owner:
        flash(
            "The quote/opportunity owner is not configured. Assign a Sales owner before requesting an extension.",
            "danger",
        )
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    proposed_raw = _clean(request.form.get("proposed_deadline"))
    reason = _clean(request.form.get("reason"))

    if not proposed_raw or not reason:
        flash("Proposed deadline and extension reason are required.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    try:
        proposed_deadline = datetime.strptime(proposed_raw, "%Y-%m-%dT%H:%M")
    except (TypeError, ValueError):
        flash("Please enter a valid proposed deadline.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    if proposed_deadline <= current_deadline:
        flash("The proposed deadline must be later than the current client deadline.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    extension_minutes = int((proposed_deadline - current_deadline).total_seconds() // 60)
    requires_admin = extension_minutes > (48 * 60)

    row = OperationsClientDeadlineExtensionRequest(
        jobcard_id=jobcard.id,
        quote_id=quote.id,
        original_deadline=current_deadline,
        proposed_deadline=proposed_deadline,
        extension_minutes=extension_minutes,
        requires_admin_approval=requires_admin,
        reason=reason,
        status="Pending Sales",
        requested_by_id=current_user.id,
        requested_at=_now_ist(),
        quote_owner_id=quote_owner.id,
    )
    db.session.add(row)
    db.session.flush()
    _deadline_extension_history(
        row,
        "Requested",
        None,
        "Pending Sales",
        reason,
    )
    db.session.commit()

    flash(
        "Deadline-extension request submitted to {0}.{1}".format(
            quote_owner.name,
            " Admin approval will also be required." if requires_admin else "",
        ),
        "success",
    )
    return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))


@operations_bp.route("/deadline-extension-approvals")
@login_required
@require_perm(DEADLINE_EXTENSION_VIEW_PERMISSION)
def deadline_extension_approvals():
    status_filter = _clean(request.args.get("status")) or "pending"

    query = OperationsClientDeadlineExtensionRequest.query

    can_sales = current_user.has_perm(DEADLINE_EXTENSION_SALES_PERMISSION)
    can_admin = current_user.has_perm(DEADLINE_EXTENSION_ADMIN_PERMISSION)

    visibility = []
    if can_sales:
        visibility.append(
            and_(
                OperationsClientDeadlineExtensionRequest.quote_owner_id == current_user.id,
                OperationsClientDeadlineExtensionRequest.status == "Pending Sales",
            )
        )
    if can_admin:
        visibility.append(
            OperationsClientDeadlineExtensionRequest.status == "Pending Admin"
        )

    # History is visible to approvers for requests they participated in.
    if status_filter != "pending":
        history_visibility = []
        if can_sales:
            history_visibility.append(
                OperationsClientDeadlineExtensionRequest.quote_owner_id == current_user.id
            )
        if can_admin:
            history_visibility.append(
                OperationsClientDeadlineExtensionRequest.requires_admin_approval.is_(True)
            )
        if not history_visibility:
            abort(403)
        query = query.filter(or_(*history_visibility))
        if status_filter == "approved":
            query = query.filter(OperationsClientDeadlineExtensionRequest.status == "Approved")
        elif status_filter == "rejected":
            query = query.filter(OperationsClientDeadlineExtensionRequest.status == "Rejected")
    else:
        if not visibility:
            abort(403)
        query = query.filter(or_(*visibility))

    rows = query.order_by(
        OperationsClientDeadlineExtensionRequest.requested_at.desc()
    ).all()

    return render_template(
        "operations/deadline_extension_approvals.html",
        rows=rows,
        status_filter=status_filter,
        can_sales=can_sales,
        can_admin=can_admin,
    )


@operations_bp.route("/deadline-extension-requests/<int:request_id>/sales-decision", methods=["POST"])
@login_required
@require_perm(DEADLINE_EXTENSION_SALES_PERMISSION)
def deadline_extension_sales_decision(request_id):
    row = OperationsClientDeadlineExtensionRequest.query.get_or_404(request_id)

    if row.status != "Pending Sales":
        flash("This request is no longer awaiting Sales approval.", "warning")
        return redirect(url_for("operations.deadline_extension_approvals"))

    if row.quote_owner_id != current_user.id:
        abort(403)

    decision = _clean(request.form.get("decision")).lower()
    remark = _clean(request.form.get("remark"))

    if decision not in ("approve", "reject"):
        flash("Select Approve or Reject.", "danger")
        return redirect(url_for("operations.deadline_extension_approvals"))

    old_status = row.status
    now = _now_ist()

    if decision == "reject":
        if not remark:
            flash("Rejection remark is required.", "danger")
            return redirect(url_for("operations.deadline_extension_approvals"))
        row.status = "Rejected"
        row.rejected_by_id = current_user.id
        row.rejected_at = now
        row.rejection_remark = remark
        _deadline_extension_history(row, "Sales Rejected", old_status, "Rejected", remark)
    else:
        row.sales_approved_by_id = current_user.id
        row.sales_approved_at = now
        row.sales_remark = remark

        if row.requires_admin_approval:
            row.status = "Pending Admin"
            _deadline_extension_history(
                row,
                "Sales Approved",
                old_status,
                "Pending Admin",
                remark,
            )
        else:
            _deadline_extension_history(
                row,
                "Sales Approved",
                old_status,
                "Sales Approved",
                remark,
            )
            _complete_deadline_extension(row, remark)

    db.session.commit()
    flash("Sales decision saved successfully.", "success")
    return redirect(url_for("operations.deadline_extension_approvals"))


@operations_bp.route("/deadline-extension-requests/<int:request_id>/admin-decision", methods=["POST"])
@login_required
@require_perm(DEADLINE_EXTENSION_ADMIN_PERMISSION)
def deadline_extension_admin_decision(request_id):
    row = OperationsClientDeadlineExtensionRequest.query.get_or_404(request_id)

    if row.status != "Pending Admin" or not row.requires_admin_approval:
        flash("This request is not awaiting Admin approval.", "warning")
        return redirect(url_for("operations.deadline_extension_approvals"))

    decision = _clean(request.form.get("decision")).lower()
    remark = _clean(request.form.get("remark"))

    if decision not in ("approve", "reject"):
        flash("Select Approve or Reject.", "danger")
        return redirect(url_for("operations.deadline_extension_approvals"))

    old_status = row.status
    now = _now_ist()

    if decision == "reject":
        if not remark:
            flash("Rejection remark is required.", "danger")
            return redirect(url_for("operations.deadline_extension_approvals"))
        row.status = "Rejected"
        row.rejected_by_id = current_user.id
        row.rejected_at = now
        row.rejection_remark = remark
        _deadline_extension_history(row, "Admin Rejected", old_status, "Rejected", remark)
    else:
        row.admin_approved_by_id = current_user.id
        row.admin_approved_at = now
        row.admin_remark = remark
        _deadline_extension_history(
            row,
            "Admin Approved",
            old_status,
            "Admin Approved",
            remark,
        )
        _complete_deadline_extension(row, remark)

    db.session.commit()
    flash("Admin decision saved successfully.", "success")
    return redirect(url_for("operations.deadline_extension_approvals"))


@operations_bp.route("/jobcards/<int:jobcard_id>/set-client-deadline", methods=["POST"])
@login_required
@require_perm("operations.jobcard.view")
def set_jobcard_client_deadline(jobcard_id):
    """Set the client deadline once when it is missing.

    This endpoint deliberately refuses to overwrite an existing jobcard or
    quote deadline. It is available to the current PM/owner and users with
    operations.jobcard.view_all. The linked quote is updated at the same time
    so both records remain synchronized.
    """
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)
    quote = jobcard.quote

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id
    can_manage_jobcard = (
        owner_id == current_user.id
        or current_user.has_perm("operations.jobcard.view_all")
    )

    if not can_manage_jobcard:
        abort(403)

    # One-time only: do not permit overwriting either stored value.
    if jobcard.client_deadline or (quote and quote.client_deadline):
        flash(
            "Client deadline is already configured and cannot be changed from this page.",
            "warning",
        )
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    client_deadline_raw = _clean(request.form.get("client_deadline"))
    if not client_deadline_raw:
        flash("Please enter the client deadline.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    try:
        client_deadline = datetime.strptime(
            client_deadline_raw,
            "%Y-%m-%dT%H:%M",
        )
    except (TypeError, ValueError):
        flash("Please enter a valid client deadline.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    jobcard.client_deadline = client_deadline
    if quote:
        quote.client_deadline = client_deadline

    db.session.commit()

    flash(
        "Client deadline saved successfully. It will now be used for the PM on-time KPI.",
        "success",
    )
    return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))


@operations_bp.route("/quotes/<int:quote_id>/assign-ops", methods=["GET", "POST"])
@login_required
@require_perm("operations.jobcard.assign_ops")
def assign_ops_from_quote(quote_id):
    quote = Quote.query.get_or_404(quote_id)

    if not getattr(quote, "proposal_confirmed_at", None):
        flash("Ops assignment is allowed only after proposal confirmation.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=quote.id))

    existing = OperationsJobcard.query.filter_by(quote_id=quote.id).first()
    if existing:
        flash("Jobcard already created for this quote.", "info")
        return redirect(url_for("operations.view_jobcard", jobcard_id=existing.id))

    if request.method == "POST":
        ops_user_id = request.form.get("ops_user_id", type=int)
        ops_user = User.query.get(ops_user_id) if ops_user_id else None
        client_deadline_raw = _clean(request.form.get("client_deadline"))

        if not ops_user:
            flash("Please select operations user.", "danger")
            return redirect(url_for("operations.assign_ops_from_quote", quote_id=quote.id))

        if not client_deadline_raw:
            flash("Client deadline is required.", "danger")
            return redirect(url_for("operations.assign_ops_from_quote", quote_id=quote.id))

        try:
            client_deadline = datetime.strptime(
                client_deadline_raw,
                "%Y-%m-%dT%H:%M",
            )
        except (TypeError, ValueError):
            flash("Please enter a valid client deadline.", "danger")
            return redirect(url_for("operations.assign_ops_from_quote", quote_id=quote.id))

        quote.ops_assigned_to_id = ops_user.id
        quote.ops_assigned_by_id = current_user.id
        quote.ops_assigned_at = _now_ist()
        quote.client_deadline = client_deadline
        quote.ops_assignment_status = "Pending Jobcard"

        db.session.commit()

        flash("Proposal assigned to Operations successfully.", "success")
        return redirect(url_for("quotes.sent_proposals"))

    operation_users = _get_operations_users()

    return render_template(
        "operations/assign_ops.html",
        quote=quote,
        operation_users=operation_users,
    )

@operations_bp.route("/jobcard-requests")
@login_required
@require_perm("operations.jobcard.create")
def jobcard_requests():
    q = _clean(request.args.get("q"))
    page = request.args.get("page", 1, type=int)

    query = (
        Quote.query
        .filter(Quote.ops_assigned_to_id == current_user.id)
        .filter(Quote.ops_assignment_status == "Pending Jobcard")
        .filter(Quote.proposal_confirmed_at.isnot(None))
    )

    if q:
        like = f"%{q}%"
        query = query.filter(or_(
            Quote.quote_code.ilike(like),
            Quote.currency.ilike(like),
            Quote.billing_state.ilike(like),
            Quote.billing_gstin.ilike(like),
        ))

    query = query.order_by(
        Quote.ops_assigned_at.desc(),
        Quote.id.desc()
    )

    pagination = query.paginate(page=page, per_page=20, error_out=False)

    operation_users = [
        u for u in _get_operations_users()
        if u.id != current_user.id
    ]

    return render_template(
        "operations/jobcard_requests.html",
        pagination=pagination,
        q=q,
        operation_users=operation_users,
    )

@operations_bp.route("/jobcard-requests/<int:quote_id>/transfer", methods=["POST"])
@login_required
@require_perm("operations.jobcard.create")
def transfer_jobcard_request(quote_id):
    quote = Quote.query.get_or_404(quote_id)

    if quote.ops_assignment_status != "Pending Jobcard":
        flash("Only pending jobcard requests can be transferred.", "danger")
        return redirect(url_for("operations.jobcard_requests"))

    if quote.ops_assigned_to_id != current_user.id:
        flash("You can transfer only jobcard requests assigned to you.", "danger")
        return redirect(url_for("operations.jobcard_requests"))

    existing_jobcard = OperationsJobcard.query.filter_by(quote_id=quote.id).first()
    if existing_jobcard:
        flash("Jobcard already exists for this quote. Request cannot be transferred.", "danger")
        return redirect(url_for("operations.jobcard_requests"))

    new_user_id = request.form.get("new_ops_user_id", type=int)
    transfer_reason = _clean(request.form.get("transfer_reason"))

    if not new_user_id:
        flash("Please select a user to transfer this request.", "danger")
        return redirect(url_for("operations.jobcard_requests"))

    if new_user_id == current_user.id:
        flash("You cannot transfer the request to yourself.", "danger")
        return redirect(url_for("operations.jobcard_requests"))

    if not transfer_reason:
        flash("Transfer reason is required.", "danger")
        return redirect(url_for("operations.jobcard_requests"))

    eligible_users = _get_operations_users()
    eligible_user_ids = {u.id for u in eligible_users}

    if new_user_id not in eligible_user_ids:
        flash("Selected user is not eligible for jobcard request transfer.", "danger")
        return redirect(url_for("operations.jobcard_requests"))

    new_user = User.query.get(new_user_id)

    if not new_user or not new_user.is_active:
        flash("Invalid user selected.", "danger")
        return redirect(url_for("operations.jobcard_requests"))

    old_user = quote.ops_assigned_to

    quote.ops_assigned_to_id = new_user.id
    quote.ops_assigned_by_id = current_user.id
    quote.ops_assigned_at = _now_ist()
    quote.ops_assignment_status = "Pending Jobcard"

    db.session.add(AuditLog(
        entity="Quote",
        entity_id=quote.id,
        action="Jobcard Request Transfer",
        field="ops_assigned_to_id",
        old_value=str(old_user.name if old_user else quote.ops_assigned_to_id),
        new_value=str(new_user.name),
        performed_by_id=current_user.id,
        performed_at=_now_ist()
    ))

    db.session.commit()

    flash(
        f"Jobcard request transferred successfully to {new_user.name}.",
        "success"
    )
    return redirect(url_for("operations.jobcard_requests"))

@operations_bp.route("/jobcards/<int:jobcard_id>/transfer", methods=["POST"])
@login_required
@require_perm("operations.jobcard.transfer")
def transfer_jobcard(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

    if jobcard.status == "Ready For Billing":
        flash("Closed jobcards cannot be transferred.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    new_owner_id = request.form.get("new_owner_id", type=int)
    remark = _clean(request.form.get("remark"))

    new_owner = User.query.get(new_owner_id) if new_owner_id else None

    if not new_owner:
        flash("Please select new PM.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    if not remark:
        flash("Transfer remark is required.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    old_owner_id = jobcard.current_owner_id or jobcard.assigned_to_id

    db.session.add(OperationsJobcardTransferHistory(
        jobcard_id=jobcard.id,
        from_user_id=old_owner_id,
        to_user_id=new_owner.id,
        transferred_by_id=current_user.id,
        remark=remark,
        transferred_at=_now_ist()
    ))

    jobcard.current_owner_id = new_owner.id
    jobcard.assigned_to_id = new_owner.id

    db.session.commit()

    flash("Jobcard ownership transferred successfully.", "success")
    return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

def _operations_workload_visible_user_ids():
    """Return the Operations users visible to the logged-in user.

    Users with operations.jobcard.view_all can see all Operations data.
    Everyone else can see their own data and all recursive reportees.
    """
    if current_user.has_perm("operations.jobcard.view_all"):
        return [u.id for u in _operations_user_query().all()]

    hierarchy_ids = team_user_ids(
        current_user.id,
        include_self=True,
    )
    if not hierarchy_ids:
        return []

    return [
        u.id
        for u in _operations_user_query().filter(User.id.in_(hierarchy_ids)).all()
    ]


def _can_access_operations_workload_jobcard(jobcard):
    """
    Allow workload access solely through the standard jobcard-view permission.

    Workload entry must remain available after ownership transfers and must not
    depend on workforce group, reporting hierarchy, current owner, assigned
    user, or the operations.jobcard.view_all permission.

    The workload routes are already protected with:
        @require_perm("operations.jobcard.view")

    This helper deliberately mirrors that permission so transferred users,
    including Project Management users, can update workload when the permission
    has been assigned to their role/user.
    """
    return bool(current_user.has_perm("operations.jobcard.view"))


def _active_workload_standards_payload():
    rows = (
        OperationsWorkloadStandard.query
        .filter_by(is_active=True)
        .order_by(
            OperationsWorkloadStandard.application_name.asc(),
            OperationsWorkloadStandard.file_extension.asc(),
            OperationsWorkloadStandard.sow.asc(),
            OperationsWorkloadStandard.complexity.asc(),
        )
        .all()
    )
    return rows, [
        {
            "id": row.id,
            "application": row.application_name,
            "extension": row.file_extension or "__NONE__",
            "sow": row.sow,
            "service": row.service_name,
            "complexity": row.complexity,
        }
        for row in rows
    ]


@operations_bp.route("/jobcards/<int:jobcard_id>/workload")
@login_required
@require_perm("operations.jobcard.view")
def jobcard_workload(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)
    if not _can_access_operations_workload_jobcard(jobcard):
        abort(403)

    assignments = required_assignments_for_jobcard(jobcard)
    standards, standards_payload = _active_workload_standards_payload()

    entries_by_assignment = {}
    assignment_ids = [row.id for row in assignments]
    if assignment_ids:
        entries = (
            OperationsJobcardWorkloadEntry.query
            .filter(
                OperationsJobcardWorkloadEntry.assignment_id.in_(assignment_ids),
                OperationsJobcardWorkloadEntry.is_active.is_(True),
            )
            .order_by(OperationsJobcardWorkloadEntry.id.asc())
            .all()
        )
        for entry in entries:
            entries_by_assignment.setdefault(entry.assignment_id, []).append(entry)

    # Surface legacy service-mismatched workload rows so they can be corrected.
    # These rows are excluded from workload/KPI calculations by the service
    # layer and no longer satisfy workload completion.
    workload_mismatch_assignment_ids = set()
    for assignment in assignments:
        actual_service = str(assignment.jobcard_service.service_name or "").strip().lower()
        for entry in entries_by_assignment.get(assignment.id, []):
            if str(entry.service_snapshot or "").strip().lower() != actual_service:
                workload_mismatch_assignment_ids.add(assignment.id)
                break

    summary = workload_completion_summary(jobcard)
    locked = _jobcard_is_locked(jobcard) and not current_user.has_perm("operations.workload.history.update")

    return render_template(
        "operations/jobcard_workload.html",
        jobcard=jobcard,
        assignments=assignments,
        entries_by_assignment=entries_by_assignment,
        standards_payload=standards_payload,
        workload_summary=summary,
        workload_locked=locked,
        workload_mismatch_assignment_ids=workload_mismatch_assignment_ids,
    )


@operations_bp.route("/jobcards/<int:jobcard_id>/workload/bulk", methods=["POST"])
@login_required
@require_perm("operations.jobcard.view")
def add_bulk_assignment_workload(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)
    if not _can_access_operations_workload_jobcard(jobcard):
        abort(403)
    if _jobcard_is_locked(jobcard) and not current_user.has_perm("operations.workload.history.update"):
        flash("Workload cannot be changed because this jobcard is locked.", "danger")
        return redirect(url_for("operations.jobcard_workload", jobcard_id=jobcard.id))

    standard_id = request.form.get("workload_standard_id", type=int)
    standard = OperationsWorkloadStandard.query.get(standard_id) if standard_id else None
    selected_ids = request.form.getlist("assignment_ids[]")
    if not standard or not standard.is_active:
        flash("Please select a valid workload combination.", "danger")
        return redirect(url_for("operations.jobcard_workload", jobcard_id=jobcard.id))
    if not selected_ids:
        flash("Please select at least one internal Production or QC assignment.", "warning")
        return redirect(url_for("operations.jobcard_workload", jobcard_id=jobcard.id))

    eligible = {row.id: row for row in required_assignments_for_jobcard(jobcard)}
    saved = 0
    try:
        source = "HISTORICAL_ENTRY" if jobcard.status in {"Ready For Billing", "Completed"} else "LIVE_ENTRY"
        for raw_id in selected_ids:
            try:
                assignment_id = int(raw_id)
            except (TypeError, ValueError):
                continue
            assignment = eligible.get(assignment_id)
            quantity = request.form.get("workload_quantity_{}".format(assignment_id))
            if not assignment or not quantity:
                continue
            create_workload_entry(assignment, standard, quantity, current_user.id, source=source)
            saved += 1
        if not saved:
            raise ValueError("Enter a quantity for at least one selected assignment.")
        db.session.commit()
        flash("Workload classification applied to {} assignment(s).".format(saved), "success")
    except ValueError as exc:
        db.session.rollback(); flash(str(exc), "danger")
    except Exception:
        db.session.rollback()
        current_app.logger.exception("Failed to bulk save workload for jobcard %s", jobcard.id)
        flash("Workload details could not be saved.", "danger")
    return redirect(url_for("operations.jobcard_workload", jobcard_id=jobcard.id))


@operations_bp.route("/assignments/<int:assignment_id>/workload", methods=["POST"])
@login_required
@require_perm("operations.jobcard.view")
def add_assignment_workload(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)
    jobcard = assignment.jobcard_service.jobcard
    if not _can_access_operations_workload_jobcard(jobcard):
        abort(403)
    if _jobcard_is_locked(jobcard) and not current_user.has_perm("operations.workload.history.update"):
        flash("Workload cannot be changed because this jobcard is locked.", "danger")
        return redirect(url_for("operations.jobcard_workload", jobcard_id=jobcard.id))

    standard_id = request.form.get("workload_standard_id", type=int)
    quantity = request.form.get("workload_quantity")
    standard = OperationsWorkloadStandard.query.get(standard_id) if standard_id else None

    if not standard or not standard.is_active:
        flash("Please select a valid workload combination.", "danger")
        return redirect(url_for("operations.jobcard_workload", jobcard_id=jobcard.id))

    try:
        source = "HISTORICAL_ENTRY" if jobcard.status in {"Ready For Billing", "Completed"} else "LIVE_ENTRY"
        create_workload_entry(
            assignment=assignment,
            standard=standard,
            quantity=quantity,
            user_id=current_user.id,
            source=source,
        )
        db.session.commit()
        flash("Workload details saved.", "success")
    except ValueError as exc:
        db.session.rollback()
        flash(str(exc), "danger")
    except Exception:
        db.session.rollback()
        current_app.logger.exception("Failed to save workload for assignment %s", assignment.id)
        flash("Workload details could not be saved.", "danger")

    return redirect(url_for("operations.jobcard_workload", jobcard_id=jobcard.id))


@operations_bp.route("/workload/entries/<int:entry_id>/delete", methods=["POST"])
@login_required
@require_perm("operations.jobcard.view")
def delete_assignment_workload(entry_id):
    entry = OperationsJobcardWorkloadEntry.query.get_or_404(entry_id)
    assignment = entry.assignment
    jobcard = assignment.jobcard_service.jobcard
    if not _can_access_operations_workload_jobcard(jobcard):
        abort(403)
    if _jobcard_is_locked(jobcard) and not current_user.has_perm("operations.workload.history.update"):
        flash("Workload cannot be changed because this jobcard is locked.", "danger")
        return redirect(url_for("operations.jobcard_workload", jobcard_id=jobcard.id))

    entry.is_active = False
    entry.updated_by_id = current_user.id
    db.session.commit()
    flash("Workload row removed.", "success")
    return redirect(url_for("operations.jobcard_workload", jobcard_id=jobcard.id))


@operations_bp.route("/workload/history")
@login_required
@require_perm("operations.workload.history.update")
def historical_workload_update():
    """Paginated list of jobcards that still have missing workload entries.

    The previous implementation loaded up to 500 jobcards and calculated each
    jobcard in Python. This query lets MySQL first identify only jobcards that
    have at least one eligible Production/QC assignment without an active
    workload row, then paginates the result.
    """
    q = _clean(request.args.get("q"))
    status = _clean(request.args.get("status"))
    client_id = request.args.get("client_id", type=int)
    service_name = _clean(request.args.get("service_name"))
    assignment_type = _clean(request.args.get("assignment_type")).upper()
    date_from_raw = _clean(request.args.get("date_from"))
    date_to_raw = _clean(request.args.get("date_to"))
    page = max(request.args.get("page", 1, type=int) or 1, 1)
    per_page = 10

    date_from = None
    date_to = None
    try:
        if date_from_raw:
            date_from = datetime.strptime(date_from_raw, "%Y-%m-%d").date()
    except ValueError:
        flash("Invalid From Date ignored.", "warning")
        date_from_raw = ""

    try:
        if date_to_raw:
            date_to = datetime.strptime(date_to_raw, "%Y-%m-%d").date()
    except ValueError:
        flash("Invalid To Date ignored.", "warning")
        date_to_raw = ""

    if date_from and date_to and date_from > date_to:
        date_from, date_to = date_to, date_from
        date_from_raw = date_from.isoformat()
        date_to_raw = date_to.isoformat()

    active_workload_exists = (
        db.session.query(OperationsJobcardWorkloadEntry.id)
        .filter(
            OperationsJobcardWorkloadEntry.assignment_id
            == OperationsJobcardAssignment.id,
            OperationsJobcardWorkloadEntry.is_active.is_(True),
        )
        .exists()
    )

    delegated_child_exists = (
        db.session.query(OperationsJobcardAssignment.id)
        .filter(
            OperationsJobcardAssignment.parent_assignment_id
            == OperationsJobcardAssignment.id
        )
        .exists()
    )

    # Use a separate alias-safe child subquery through the table itself.
    child_assignment = OperationsJobcardAssignment.__table__.alias(
        "historical_workload_child_assignment"
    )
    delegated_child_exists = (
        db.session.query(child_assignment.c.id)
        .filter(
            child_assignment.c.parent_assignment_id
            == OperationsJobcardAssignment.id
        )
        .exists()
    )

    incomplete_jobcard_ids = (
        db.session.query(OperationsJobcardService.jobcard_id.label("jobcard_id"))
        .join(
            OperationsJobcardAssignment,
            OperationsJobcardAssignment.jobcard_service_id
            == OperationsJobcardService.id,
        )
        .filter(
            func.upper(OperationsJobcardAssignment.assignment_type).in_(
                ["PRODUCTION", "QC"]
            ),
            func.upper(OperationsJobcardAssignment.assigned_to_type).in_(
                ["VENDOR", "INTERNAL"]
            ),
            OperationsJobcardAssignment.replaced_at.is_(None),
            ~func.lower(
                func.coalesce(OperationsJobcardAssignment.status, "")
            ).in_(["cancelled", "replaced", "rejected"]),
            or_(
                func.lower(
                    func.coalesce(OperationsJobcardAssignment.status, "")
                ) != "delegated",
                ~delegated_child_exists,
            ),
            ~active_workload_exists,
        )
    )

    if service_name:
        incomplete_jobcard_ids = incomplete_jobcard_ids.filter(
            OperationsJobcardService.service_name == service_name
        )

    if assignment_type in {"PRODUCTION", "QC"}:
        incomplete_jobcard_ids = incomplete_jobcard_ids.filter(
            func.upper(OperationsJobcardAssignment.assignment_type)
            == assignment_type
        )

    incomplete_jobcard_ids = incomplete_jobcard_ids.distinct().subquery()

    # Apply the same self/team visibility used by the analytics dashboards.
    # A normal user sees only their own owned jobcards. A TL/manager sees their
    # own jobcards plus jobcards owned by all recursive reportees. Users with
    # operations.jobcard.view_all continue to see all jobcards.
    visible_user_ids = _operations_workload_visible_user_ids()

    visible_incomplete_jobcard_ids_query = (
        db.session.query(OperationsJobcard.id.label("jobcard_id"))
        .join(
            incomplete_jobcard_ids,
            incomplete_jobcard_ids.c.jobcard_id
            == OperationsJobcard.id,
        )
    )

    if visible_user_ids is not None:
        visible_incomplete_jobcard_ids_query = (
            visible_incomplete_jobcard_ids_query.filter(
                func.coalesce(
                    OperationsJobcard.current_owner_id,
                    OperationsJobcard.assigned_to_id,
                ).in_(visible_user_ids)
            )
        )

    visible_incomplete_jobcard_ids = (
        visible_incomplete_jobcard_ids_query
        .distinct()
        .subquery()
    )

    query = (
        OperationsJobcard.query
        .join(
            visible_incomplete_jobcard_ids,
            visible_incomplete_jobcard_ids.c.jobcard_id
            == OperationsJobcard.id,
        )
    )

    if q:
        like = "%{}%".format(q)
        query = query.outerjoin(Client, Client.id == OperationsJobcard.client_id)
        query = query.filter(
            or_(
                OperationsJobcard.jobcard_code.ilike(like),
                Client.company_name.ilike(like),
            )
        )

    if status:
        query = query.filter(OperationsJobcard.status == status)

    if client_id:
        query = query.filter(OperationsJobcard.client_id == client_id)

    if date_from:
        query = query.filter(
            OperationsJobcard.created_at >= datetime.combine(date_from, datetime.min.time())
        )

    if date_to:
        query = query.filter(
            OperationsJobcard.created_at
            < datetime.combine(date_to + timedelta(days=1), datetime.min.time())
        )

    pagination = query.order_by(
        OperationsJobcard.id.desc()
    ).paginate(
        page=page,
        per_page=per_page,
        error_out=False,
    )

    rows = []
    for jobcard in pagination.items:
        summary = workload_completion_summary(jobcard)
        rows.append({"jobcard": jobcard, "summary": summary})

    client_options = (
        db.session.query(Client.id, Client.company_name)
        .join(
            OperationsJobcard,
            OperationsJobcard.client_id == Client.id,
        )
        .join(
            visible_incomplete_jobcard_ids,
            visible_incomplete_jobcard_ids.c.jobcard_id
            == OperationsJobcard.id,
        )
        .filter(Client.company_name.isnot(None))
        .distinct()
        .order_by(Client.company_name.asc())
        .all()
    )

    service_options = [
        row[0]
        for row in (
            db.session.query(OperationsJobcardService.service_name)
            .join(
                visible_incomplete_jobcard_ids,
                visible_incomplete_jobcard_ids.c.jobcard_id
                == OperationsJobcardService.jobcard_id,
            )
            .filter(OperationsJobcardService.service_name.isnot(None))
            .distinct()
            .order_by(OperationsJobcardService.service_name.asc())
            .all()
        )
        if row[0]
    ]

    status_options = [
        row[0]
        for row in (
            db.session.query(OperationsJobcard.status)
            .join(
                incomplete_jobcard_ids,
                incomplete_jobcard_ids.c.jobcard_id == OperationsJobcard.id,
            )
            .filter(OperationsJobcard.status.isnot(None))
            .distinct()
            .order_by(OperationsJobcard.status.asc())
            .all()
        )
        if row[0]
    ]

    return render_template(
        "operations/historical_workload_update.html",
        rows=rows,
        pagination=pagination,
        q=q,
        status=status,
        client_id=client_id,
        service_name=service_name,
        assignment_type=assignment_type,
        date_from=date_from_raw,
        date_to=date_to_raw,
        client_options=client_options,
        service_options=service_options,
        status_options=status_options,
    )


@operations_bp.route("/workload/standards", methods=["GET", "POST"])
@login_required
@require_perm("operations.workload.master.manage")
def workload_standard_master():
    if request.method == "POST":
        standard_id = request.form.get("standard_id", type=int)
        row = OperationsWorkloadStandard.query.get(standard_id) if standard_id else OperationsWorkloadStandard()
        if not row:
            abort(404)

        row.application_name = _clean(request.form.get("application_name"))
        row.file_extension = _clean(request.form.get("file_extension"))
        row.sow = _clean(request.form.get("sow"))
        row.service_name = _clean(request.form.get("service_name"))
        row.complexity = _clean(request.form.get("complexity"))
        row.standard_minutes = request.form.get("standard_minutes", type=Decimal)
        row.unit_type = _clean(request.form.get("unit_type")) or "Quantity"
        row.base_quantity = request.form.get("base_quantity", type=Decimal) or Decimal("1")
        row.remarks = _clean(request.form.get("remarks"))
        row.is_active = bool(request.form.get("is_active"))
        row.updated_by_id = current_user.id

        if not standard_id:
            row.created_by_id = current_user.id
            db.session.add(row)

        if not all([row.application_name, row.sow, row.service_name, row.complexity]) or row.standard_minutes is None:
            flash("Application, SOW, service, complexity and standard minutes are required.", "danger")
            return redirect(url_for("operations.workload_standard_master"))

        try:
            db.session.commit()
            flash("Workload standard saved.", "success")
        except Exception:
            db.session.rollback()
            current_app.logger.exception("Failed to save workload standard")
            flash("The standard could not be saved. Check for a duplicate combination.", "danger")
        return redirect(url_for("operations.workload_standard_master"))

    q = _clean(request.args.get("q"))
    query = OperationsWorkloadStandard.query
    if q:
        like = f"%{q}%"
        query = query.filter(or_(
            OperationsWorkloadStandard.application_name.ilike(like),
            OperationsWorkloadStandard.file_extension.ilike(like),
            OperationsWorkloadStandard.sow.ilike(like),
            OperationsWorkloadStandard.service_name.ilike(like),
        ))
    rows = query.order_by(
        OperationsWorkloadStandard.application_name.asc(),
        OperationsWorkloadStandard.sow.asc(),
        OperationsWorkloadStandard.complexity.asc(),
    ).all()

    # Populate the Service dropdown from the existing Service Master.
    # Existing workload-standard service values are also included so legacy
    # rows remain editable even if a service has since been disabled/renamed.
    active_service_names = [
        service.name.strip()
        for service in LeadService.query.filter_by(is_active=True)
        .order_by(LeadService.sort_order.asc(), LeadService.name.asc())
        .all()
        if service.name and service.name.strip()
    ]
    existing_service_names = [
        value[0].strip()
        for value in db.session.query(OperationsWorkloadStandard.service_name)
        .filter(OperationsWorkloadStandard.service_name.isnot(None))
        .distinct()
        .all()
        if value[0] and value[0].strip()
    ]

    service_options = []
    seen_service_names = set()
    for service_name in active_service_names + existing_service_names:
        key = service_name.casefold()
        if key in seen_service_names:
            continue
        seen_service_names.add(key)
        service_options.append(service_name)

    return render_template(
        "operations/workload_standard_master.html",
        rows=rows,
        q=q,
        service_options=service_options,
    )


@operations_bp.route("/jobcards/<int:jobcard_id>/close", methods=["POST"])
@login_required
@require_perm("operations.jobcard.close")
def close_jobcard(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id
    if owner_id != current_user.id and not current_user.has_perm("operations.jobcard.view_all"):
        abort(403)

    missing_workload = missing_workload_assignments(jobcard)
    if missing_workload:
        labels = [assignment_display_name(row) for row in missing_workload[:5]]
        suffix = "" if len(missing_workload) <= 5 else f" and {len(missing_workload) - 5} more"
        flash(
            "Jobcard cannot be closed. Workload details are missing for: "
            + "; ".join(labels)
            + suffix
            + ".",
            "danger",
        )
        return redirect(url_for("operations.jobcard_workload", jobcard_id=jobcard.id))

    is_sample_job = request.form.get("is_sample_job") == "1"
    sample_reason = _clean(request.form.get("sample_reason"))
    billing_company_branch_id = request.form.get("billing_company_branch_id", type=int)
    closure_remark = _clean(request.form.get("closure_remark"))

    if not closure_remark:
        flash("Closure remark is required.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    if is_sample_job and not sample_reason:
        flash("Sample-job reason is required.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    billing_branch = None
    if not is_sample_job:
        if not billing_company_branch_id:
            flash("Please select billing branch for invoice.", "danger")
            return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

        billing_branch = CompanyBranch.query.get(billing_company_branch_id)
        if not billing_branch:
            flash("Invalid billing branch selected.", "danger")
            return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    existing_pending_approval = (
        OperationsJobcardClosureApprovalRequest.query
        .filter_by(jobcard_id=jobcard.id, status="Pending")
        .first()
    )

    if existing_pending_approval:
        flash("Closure approval is already pending for this jobcard.", "warning")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    closure_blocker = _jobcard_closure_blocker(jobcard)
    if closure_blocker:
        flash(closure_blocker, "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    commercial_overview = _jobcard_commercial_overview(jobcard)
    profit_margin_pct = commercial_overview["profit_margin_pct"]
    quote_amount_ex_tax = Decimal(str(commercial_overview.get("quote_amount_ex_tax") or 0))

    # ---------------------------------------------------------------
    # SAMPLE / NON-BILLABLE CLOSURE
    # ---------------------------------------------------------------
    if is_sample_job:
        # This path exists only for genuinely zero-value sample work. It must
        # never become a generic bypass for margin approval on billable jobs.
        if quote_amount_ex_tax != Decimal("0"):
            flash(
                "Sample Job can be selected only when quote amount excluding tax is zero.",
                "danger",
            )
            return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

        existing_pi = (
            ProformaInvoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(ProformaInvoice.status != "Cancelled")
            .first()
        )
        existing_invoice = (
            Invoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(Invoice.status != "Cancelled")
            .first()
        )

        if existing_pi or existing_invoice:
            flash(
                "This jobcard cannot be marked as Sample Job because a PI or Invoice already exists.",
                "danger",
            )
            return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

        now = _now_ist()
        jobcard.is_sample_job = True
        jobcard.sample_reason = sample_reason
        jobcard.sample_marked_at = now
        jobcard.sample_marked_by_id = current_user.id
        jobcard.billing_company_branch_id = None
        jobcard.closure_remark = closure_remark
        jobcard.closed_by_id = current_user.id
        jobcard.closed_at = now
        jobcard.ready_for_billing_at = None
        jobcard.ready_for_billing_by_id = None
        jobcard.status = "Sample Completed"

        db.session.commit()

        flash(
            "Sample Job closed successfully. Profit margin is not applicable and this jobcard is blocked from PI and Invoice generation.",
            "success",
        )
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    # ---------------------------------------------------------------
    # NORMAL BILLABLE CLOSURE (existing behaviour preserved)
    # ---------------------------------------------------------------
    if commercial_overview.get("missing_currency_rates"):
        flash(
            "Profit margin cannot be calculated. Missing INR currency rate for: "
            + ", ".join(commercial_overview["missing_currency_rates"]),
            "danger"
        )
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    if profit_margin_pct is None:
        flash(
            "Profit margin cannot be calculated because quote amount excluding tax is zero. "
            "If this is genuine sample work, select 'Sample / Non-Billable Job' in the closure window.",
            "danger",
        )
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    margin_approval_threshold = get_margin_threshold_percent()

    if profit_margin_pct < margin_approval_threshold:
        approval_request = OperationsJobcardClosureApprovalRequest(
            jobcard_id=jobcard.id,
            quote_id=jobcard.quote_id,
            billing_company_branch_id=billing_company_branch_id,
            requested_by_id=current_user.id,
            quote_amount_ex_tax=commercial_overview["quote_amount_ex_tax"],
            total_vendor_costs=commercial_overview["total_vendor_costs"],
            profit_amount=commercial_overview["profit_amount"],
            profit_margin_pct=profit_margin_pct,
            closure_remark=closure_remark,
            status="Pending",
            requested_at=_now_ist(),
        )

        db.session.add(approval_request)
        jobcard.status = "Closure Approval Pending"
        db.session.commit()

        flash(
            f"Profit margin is {profit_margin_pct:.2f}%, which is below the configured {margin_approval_threshold:.2f}% approval threshold. Closure approval request has been submitted.",
            "warning"
        )
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    jobcard.is_sample_job = False
    jobcard.sample_reason = None
    jobcard.sample_marked_at = None
    jobcard.sample_marked_by_id = None
    jobcard.billing_company_branch_id = billing_company_branch_id
    jobcard.closure_remark = closure_remark
    jobcard.closed_by_id = current_user.id
    jobcard.closed_at = _now_ist()
    jobcard.ready_for_billing_at = _now_ist()
    jobcard.ready_for_billing_by_id = current_user.id
    jobcard.status = "Ready For Billing"

    try:
        pms_result = update_pms_jobs_to_raise_invoice(jobcard)
    except Exception as e:
        db.session.rollback()
        flash(f"Jobcard closure failed while updating PMS status: {str(e)}", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    db.session.commit()

    message = "Jobcard closed and marked Ready For Billing."
    if pms_result["updated"] > 0:
        message += f" PMS updated: {pms_result['updated']} external job(s) moved to RaiseInvoice."
    else:
        message += " No PMS external job status was updated."

    if pms_result["errors"]:
        message += " PMS issues: " + " | ".join(pms_result["errors"][:5])

    flash(message, "success" if not pms_result["errors"] else "warning")
    return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

@operations_bp.route("/jobcards/<int:jobcard_id>/reopen-request", methods=["POST"])
@login_required
@require_perm("operations.jobcard.reopen_request")
def request_reopen_jobcard(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

    reason_category = _clean(request.form.get("reason_category"))
    reason_detail = _clean(request.form.get("reason_detail"))

    if not reason_category:
        flash("Please select a reopen reason.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    if reason_category not in REOPEN_REASON_OPTIONS:
        flash("Invalid reopen reason selected.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    if reason_category == "Other" and not reason_detail:
        flash("Please enter reopen reason details for Other.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    if reason_detail:
        reason = f"{reason_category} - {reason_detail}"
    else:
        reason = reason_category

    if jobcard.status not in {"Ready For Billing", "Sample Completed"}:
        flash("Only closed jobcards can be requested for reopening.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    latest_invoice = (
        Invoice.query
        .filter(
            or_(Invoice.jobcard_id == jobcard.id, Invoice.quote_id == jobcard.quote_id),
            Invoice.status != "Cancelled",
        )
        .order_by(Invoice.id.desc())
        .first()
    )
    if latest_invoice and not _jobcard_reopen_credit_note(jobcard):
        flash(
            "This invoiced jobcard can be reopened only after a Credit Note is generated against the latest invoice.",
            "danger",
        )
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    existing = (
        OperationsJobcardReopenRequest.query
        .filter_by(jobcard_id=jobcard.id, status="Pending")
        .first()
    )

    if existing:
        flash("A reopen request is already pending for this jobcard.", "warning")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    row = OperationsJobcardReopenRequest(
        jobcard_id=jobcard.id,
        quote_id=jobcard.quote_id,
        requested_by_id=current_user.id,
        reason=reason,
        status="Pending",
        requested_at=_now_ist()
    )

    db.session.add(row)
    db.session.commit()

    flash("Jobcard reopen request submitted successfully.", "success")
    return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

@operations_bp.route("/jobcard-reopen-requests")
@login_required
@require_perm("operations.jobcard.reopen_approve")
def jobcard_reopen_requests():
    # Keep the approval queue action-first: pending requests are loaded separately
    # and always rendered before processed history.
    pending_requests = (
        OperationsJobcardReopenRequest.query
        .filter(OperationsJobcardReopenRequest.status == "Pending")
        .order_by(OperationsJobcardReopenRequest.requested_at.desc())
        .all()
    )

    history_requests = (
        OperationsJobcardReopenRequest.query
        .filter(OperationsJobcardReopenRequest.status != "Pending")
        .order_by(
            func.coalesce(
                OperationsJobcardReopenRequest.approved_at,
                OperationsJobcardReopenRequest.rejected_at,
                OperationsJobcardReopenRequest.requested_at,
            ).desc()
        )
        .all()
    )

    today = _now_ist().date()

    pending_count = len(pending_requests)

    approved_today = (
        OperationsJobcardReopenRequest.query
        .filter(OperationsJobcardReopenRequest.status == "Approved")
        .filter(func.date(OperationsJobcardReopenRequest.approved_at) == today)
        .count()
    )

    rejected_today = (
        OperationsJobcardReopenRequest.query
        .filter(OperationsJobcardReopenRequest.status == "Rejected")
        .filter(func.date(OperationsJobcardReopenRequest.rejected_at) == today)
        .count()
    )

    return render_template(
        "operations/jobcard_reopen_requests.html",
        pending_requests=pending_requests,
        history_requests=history_requests,
        pending_count=pending_count,
        approved_today=approved_today,
        rejected_today=rejected_today,
    )

@operations_bp.route("/jobcard-reopen-requests/<int:request_id>/act", methods=["POST"])
@login_required
@require_perm("operations.jobcard.reopen_approve")
def act_jobcard_reopen_request(request_id):
    row = OperationsJobcardReopenRequest.query.get_or_404(request_id)

    if row.status != "Pending":
        flash("This reopen request is already processed.", "warning")
        return redirect(url_for("operations.jobcard_reopen_requests"))

    decision = request.form.get("decision")
    remark = _clean(request.form.get("approval_remark"))

    jobcard = row.jobcard

    if decision == "approve":
        latest_pi = (
            ProformaInvoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(ProformaInvoice.status != "Cancelled")
            .first()
        )

        latest_invoice = (
            Invoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(Invoice.status != "Cancelled")
            .first()
        )

        if latest_invoice:
            if not _jobcard_reopen_credit_note(jobcard):
                flash(
                    "This invoiced jobcard can be reopened only after a Credit Note is generated against the latest invoice.",
                    "danger",
                )
                return redirect(url_for("operations.jobcard_reopen_requests"))
        elif latest_pi:
            flash("This jobcard cannot be reopened because an active PI already exists and no invoice/Credit Note cycle is available.", "danger")
            return redirect(url_for("operations.jobcard_reopen_requests"))

        reopen_service_ids = request.form.getlist("reopen_service_ids", type=int)

        reopened_service_count = _apply_jobcard_reopen_approval(
            row=row,
            approval_remark=remark,
            reopen_service_ids=reopen_service_ids
        )

        db.session.commit()

        if reopened_service_count > 0:
            flash(
                f"Jobcard reopened successfully. {reopened_service_count} service line(s) reopened for rework.",
                "success"
            )
        else:
            flash("Jobcard reopened successfully.", "success")

        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    if decision == "reject":
        row.status = "Rejected"
        row.rejected_by_id = current_user.id
        row.rejected_at = _now_ist()
        row.approval_remark = remark

        db.session.commit()

        flash("Jobcard reopen request rejected.", "info")
        return redirect(url_for("operations.jobcard_reopen_requests"))

    flash("Invalid action.", "danger")
    return redirect(url_for("operations.jobcard_reopen_requests"))

@operations_bp.route("/jobcard-reopen-requests/<int:request_id>/approve", methods=["POST"])
@login_required
@require_perm("operations.jobcard.reopen_approve")
def approve_reopen_jobcard(request_id):
    row = OperationsJobcardReopenRequest.query.get_or_404(request_id)

    if row.status != "Pending":
        flash("This reopen request is already processed.", "warning")
        return redirect(url_for("operations.jobcard_reopen_requests"))

    jobcard = row.jobcard
    latest_pi = (
        ProformaInvoice.query
        .filter_by(quote_id=jobcard.quote_id)
        .filter(ProformaInvoice.status != "Cancelled")
        .first()
    )

    latest_invoice = (
        Invoice.query
        .filter_by(quote_id=jobcard.quote_id)
        .filter(Invoice.status != "Cancelled")
        .first()
    )

    if latest_invoice:
        if not _jobcard_reopen_credit_note(jobcard):
            flash(
                "This invoiced jobcard can be reopened only after a Credit Note is generated against the latest invoice.",
                "danger",
            )
            return redirect(url_for("operations.jobcard_reopen_requests"))
    elif latest_pi:
        flash("This jobcard cannot be reopened because an active PI already exists and no invoice/Credit Note cycle is available.", "danger")
        return redirect(url_for("operations.jobcard_reopen_requests"))

    reopen_service_ids = request.form.getlist("reopen_service_ids", type=int)

    reopened_service_count = _apply_jobcard_reopen_approval(
        row=row,
        approval_remark="Approved and jobcard reopened.",
        reopen_service_ids=reopen_service_ids
    )

    db.session.commit()

    if reopened_service_count > 0:
        flash(
            f"Jobcard reopened successfully. {reopened_service_count} service line(s) reopened for rework.",
            "success"
        )
    else:
        flash("Jobcard reopened successfully.", "success")

    return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))


@operations_bp.route("/jobcard-reopen-requests/<int:request_id>/reject", methods=["POST"])
@login_required
@require_perm("operations.jobcard.reopen_approve")
def reject_reopen_jobcard(request_id):
    row = OperationsJobcardReopenRequest.query.get_or_404(request_id)

    if row.status != "Pending":
        flash("This reopen request is already processed.", "warning")
        return redirect(url_for("operations.jobcard_reopen_requests"))

    remark = _clean(request.form.get("approval_remark"))

    if not remark:
        flash("Rejection remark is required.", "danger")
        return redirect(url_for("operations.jobcard_reopen_requests"))

    row.status = "Rejected"
    row.rejected_by_id = current_user.id
    row.rejected_at = _now_ist()
    row.approval_remark = remark

    db.session.commit()

    flash("Reopen request rejected.", "warning")
    return redirect(url_for("operations.jobcard_reopen_requests"))

@operations_bp.route("/services/<int:service_id>/assign-qc", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def assign_qc(service_id):
    svc = OperationsJobcardService.query.get_or_404(service_id)
    jobcard = svc.jobcard

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id
    if owner_id != current_user.id and not current_user.has_perm("operations.jobcard.view_all"):
        abort(403)

    if _jobcard_is_locked(jobcard):
        flash("QC assignment is not allowed because this jobcard is closed, billing exists, or closure approval is pending.", "danger")
        return redirect(_safe_operations_return_url("operations.view_jobcard", jobcard_id=jobcard.id))

    assigned_to_type = request.form.get("qc_assigned_to_type") or "INTERNAL"
    instruction = _clean(request.form.get("qc_instruction"))
    deadline_raw = request.form.get("qc_deadline") or None

    qc_file_title = _clean(request.form.get("qc_file_title"))
    qc_file_path = _save_jobcard_file(request.files.get("qc_file"))
    qc_additional_instruction = _clean(request.form.get("qc_additional_instruction"))

    deadline = None
    if deadline_raw:
        deadline = datetime.strptime(deadline_raw, "%Y-%m-%dT%H:%M")

    qty = Decimal(str(
        request.form.get("qc_assigned_qty")
        or getattr(svc, "total_quantity", None)
        or (svc.quote_item.qty if svc.quote_item else 1)
        or 1
    ))

    assignment = OperationsJobcardAssignment(
        jobcard_service_id=svc.id,
        assignment_type="QC",
        assigned_to_type=assigned_to_type,
        assigned_qty=qty,
        instruction=instruction or None,
        deadline=deadline,
        status="Assigned",
        file_title=qc_file_title or None,
        file_path=qc_file_path or None,
        additional_instruction=qc_additional_instruction or instruction or None,
        assigned_by_id=current_user.id,
        assigned_at=_now_ist()
    )

    if assigned_to_type == "INTERNAL":
        internal_user_id = request.form.get("qc_internal_user_id", type=int)
        internal_user = User.query.get(internal_user_id) if internal_user_id else None

        if not internal_user:
            flash("Please select internal QC user.", "danger")
            return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

        assignment.internal_user_id = internal_user.id

    elif assigned_to_type == "VENDOR":
        vendor_id = request.form.get("qc_vendor_id", type=int)
        vendor = VendorMaster.query.get(vendor_id) if vendor_id else None

        if not vendor:
            flash("Please select QC vendor.", "danger")
            return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))
        allowed, block_reason = _vendor_assignment_allowed(vendor)
        if not allowed:
            flash("{} cannot be assigned for QC: {}".format(vendor.name, block_reason or "vendor is not eligible"), "danger")
            return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

        assignment.vendor_id = vendor.id

    else:
        flash("Invalid QC assignment type.", "danger")
        return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

    db.session.add(assignment)
    db.session.flush()

    if assigned_to_type == "INTERNAL" and request.form.get("capture_qc_workload") == "1":
        standard_id = request.form.get("qc_workload_standard_id", type=int)
        standard = OperationsWorkloadStandard.query.get(standard_id) if standard_id else None
        workload_quantity = request.form.get("qc_workload_quantity") or qty
        if not standard or not standard.is_active:
            db.session.rollback()
            flash("Select a valid workload classification for QC workload.", "danger")
            return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))
        try:
            create_workload_entry(
                assignment=assignment,
                standard=standard,
                quantity=workload_quantity,
                user_id=current_user.id,
                source="ASSIGNMENT_ENTRY",
            )
        except ValueError as exc:
            db.session.rollback()
            flash(str(exc), "danger")
            return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

    if qty > Decimal(str(svc.total_quantity or 0)):
        svc.status = "Over Assigned"

    # QC can be assigned anytime.
    # Only move service to QC Pending if production is already completed.
    completed_qty = _completed_qty_for_service(svc)
    required_qty = Decimal(str(svc.total_quantity or 0))

    if completed_qty >= required_qty and required_qty > 0:
        svc.status = "QC Pending"
        svc.completed_at = None

    _refresh_jobcard_status_from_assignments(jobcard)

    db.session.commit()

    flash("QC assigned successfully.", "success")
    return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

@operations_bp.route("/jobcards/<int:jobcard_id>/bulk-qc-assign", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def bulk_assign_qc(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

    if not _can_pm_manage_jobcard(jobcard):
        abort(403)

    if _jobcard_is_locked(jobcard):
        flash("Bulk QC assignment is not allowed because this jobcard is closed, billing exists, or closure approval is pending.", "danger")
        return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

    service_ids = request.form.getlist("qc_service_ids[]", type=int)

    if not service_ids:
        flash("Please select at least one service line for QC assignment.", "danger")
        return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

    assigned_to_type = request.form.get("bulk_qc_assigned_to_type") or "INTERNAL"
    instruction = _clean(request.form.get("bulk_qc_instruction"))
    additional_instruction = _clean(request.form.get("bulk_qc_additional_instruction"))
    deadline_raw = request.form.get("bulk_qc_deadline") or None

    deadline = None
    if deadline_raw:
        deadline = datetime.strptime(deadline_raw, "%Y-%m-%dT%H:%M")

    internal_user = None
    vendor = None

    if assigned_to_type == "INTERNAL":
        internal_user_id = request.form.get("bulk_qc_internal_user_id", type=int)
        internal_user = User.query.get(internal_user_id) if internal_user_id else None

        if not internal_user:
            flash("Please select internal QC user.", "danger")
            return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))  

    elif assigned_to_type == "VENDOR":
        vendor_id = request.form.get("bulk_qc_vendor_id", type=int)
        vendor = VendorMaster.query.get(vendor_id) if vendor_id else None

        if not vendor:
            flash("Please select QC vendor.", "danger")
            return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))
        allowed, block_reason = _vendor_assignment_allowed(vendor)
        if not allowed:
            flash("{} cannot be assigned for QC: {}".format(vendor.name, block_reason or "vendor is not eligible"), "danger")
            return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

    else:
        flash("Invalid QC assignment type.", "danger")
        return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))
    assigned_count = 0

    try:
        services = (
            OperationsJobcardService.query
            .filter(OperationsJobcardService.jobcard_id == jobcard.id)
            .filter(OperationsJobcardService.id.in_(service_ids))
            .order_by(OperationsJobcardService.id.asc())
            .all()
        )

        for svc in services:
            qty = Decimal(str(
                request.form.get(f"bulk_qc_assigned_qty_{svc.id}")
                or request.form.get("bulk_qc_assigned_qty")
                or getattr(svc, "total_quantity", None)
                or (svc.quote_item.qty if svc.quote_item else 1)
                or 1
            ))

            assignment = OperationsJobcardAssignment(
                jobcard_service_id=svc.id,
                assignment_type="QC",
                assigned_to_type=assigned_to_type,
                assigned_qty=qty,
                instruction=instruction or None,
                additional_instruction=additional_instruction or instruction or None,
                deadline=deadline,
                status="Assigned",
                assigned_by_id=current_user.id,
                assigned_at=_now_ist()
            )

            if assigned_to_type == "INTERNAL":
                assignment.internal_user_id = internal_user.id
            else:
                assignment.vendor_id = vendor.id

            db.session.add(assignment)

            if qty > Decimal(str(svc.total_quantity or 0)):
                svc.status = "Over Assigned"

            completed_qty = _completed_qty_for_service(svc)
            required_qty = Decimal(str(svc.total_quantity or 0))

            if completed_qty >= required_qty and required_qty > 0:
                svc.status = "QC Pending"
                svc.completed_at = None

            assigned_count += 1

        if assigned_count > 0:
            _refresh_jobcard_status_from_assignments(jobcard)
            db.session.commit()
            flash(f"Bulk QC assignment completed. {assigned_count} QC task(s) assigned.", "success")
        else:
            db.session.rollback()
            flash("No valid service lines were selected for QC assignment.", "warning")

    except Exception as e:
        db.session.rollback()
        flash(f"Bulk QC assignment failed: {str(e)}", "danger")

    return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

@operations_bp.route("/assignments/<int:assignment_id>/pm-reject", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def pm_reject_internal_assignment(assignment_id):
    """Allow the PM/jobcard manager to reject an internal Production or QC task.

    Rejected assignments are retained for audit, but they are excluded from
    assigned quantity, workload, QC-pending and closure calculations.
    """
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)
    svc = assignment.jobcard_service
    jobcard = svc.jobcard
    service_was_qc_pending = (svc.status == "QC Pending")

    if not _can_pm_manage_jobcard(jobcard):
        abort(403)

    # PM may reject any QC assignment (internal or vendor), because any active
    # QC row can keep the service/jobcard open. Production rejection remains
    # restricted to INTERNAL assignments; vendor production uses replacement.
    is_rejectable_qc = assignment.assignment_type == "QC"
    is_rejectable_internal_production = (
        assignment.assignment_type == "PRODUCTION"
        and assignment.assigned_to_type == "INTERNAL"
    )

    if not (is_rejectable_qc or is_rejectable_internal_production):
        flash("PM rejection is available for all QC tasks and internally assigned Production tasks.", "danger")
        return redirect(_safe_operations_return_url("operations.view_jobcard", jobcard_id=jobcard.id))

    if assignment.status in ["Completed", "Cancelled", "Replaced", "Rejected"]:
        flash("This task is already completed, cancelled, replaced or rejected.", "warning")
        return redirect(_safe_operations_return_url("operations.view_jobcard", jobcard_id=jobcard.id))

    rejection_reason = _clean(request.form.get("rejection_reason"))
    if not rejection_reason:
        flash("Please enter a rejection reason.", "danger")
        return redirect(_safe_operations_return_url("operations.view_jobcard", jobcard_id=jobcard.id))

    assignment.status = "Rejected"
    assignment.completed_at = None
    assignment.completion_remark = rejection_reason

    # Rejected work must never contribute to workload/KPI calculations.
    OperationsJobcardWorkloadEntry.query.filter_by(
        assignment_id=assignment.id,
        is_active=True
    ).update(
        {
            "is_active": False,
            "updated_by_id": current_user.id,
            "updated_at": datetime.utcnow(),
        },
        synchronize_session=False,
    )

    if assignment.parent_assignment_id:
        parent = OperationsJobcardAssignment.query.get(assignment.parent_assignment_id)
        if parent:
            _normalize_effective_service_assignment_status(parent)

    # A rejected QC row closes that QC gate.  If it was the last active QC,
    # restore the service to Completed.  Production rejection instead releases
    # the quantity and recalculates the line normally.
    if assignment.assignment_type == "QC" and service_was_qc_pending and not _has_pending_qc(svc):
        svc.status = "Completed"
        svc.completed_at = svc.completed_at or _now_ist()
    else:
        _refresh_service_status_after_change(svc)
    _refresh_jobcard_status(jobcard)

    db.session.commit()

    if assignment.assignment_type == "QC":
        flash("QC task rejected. It will no longer block the service/jobcard and its workload will not be counted.", "success")
    else:
        flash("Internal Production task rejected. Its quantity/workload has been released and will not be counted.", "success")
    return redirect(_safe_operations_return_url("operations.view_jobcard", jobcard_id=jobcard.id))


@operations_bp.route("/assignments/<int:assignment_id>/complete-qc", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def complete_qc_assignment(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if assignment.assignment_type != "QC":
        flash("Invalid QC assignment.", "danger")
        return redirect(_safe_operations_return_url("operations.view_jobcard", jobcard_id=assignment.jobcard_service.jobcard_id))

    svc = assignment.jobcard_service
    jobcard = svc.jobcard

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id
    if owner_id != current_user.id and not current_user.has_perm("operations.jobcard.view_all"):
        abort(403)

    success, error = _record_xbench_submission(assignment, require_all=True)
    if not success:
        db.session.rollback()
        flash(error, "danger")
        return redirect(_safe_operations_return_url("operations.view_jobcard", jobcard_id=jobcard.id))

    assignment.status = "Completed"
    assignment.completed_at = _now_ist()

    if not _has_pending_qc(svc):
        completed_qty = _completed_qty_for_service(svc)
        required_qty = Decimal(str(svc.total_quantity or 0))

        if completed_qty >= required_qty:
            svc.status = "Completed"
            svc.completed_at = svc.completed_at or _now_ist()
    else:
        svc.status = "QC Pending"

    _refresh_jobcard_status(jobcard)
    db.session.commit()

    flash("QC marked completed.", "success")
    return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

@operations_bp.route("/internal-tasks/<int:assignment_id>/checklist", methods=["POST"])
@login_required
@require_perm("operations.internal_tasks.update")
def submit_internal_task_checklist(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if assignment.assigned_to_type != "INTERNAL" or assignment.internal_user_id != current_user.id:
        abort(403)

    svc = assignment.jobcard_service

    for question in svc.checklist_questions.order_by(OperationsChecklistQuestion.sort_order.asc()).all():
        input_name = f"checklist_{question.id}"

        file_path = None
        response_value = None

        if question.question_type == "file":
            file_path = _save_jobcard_file(request.files.get(input_name))
        elif question.question_type == "checkbox":
            response_value = "Yes" if request.form.get(input_name) == "1" else "No"
        else:
            response_value = _clean(request.form.get(input_name))

        if question.is_required and not response_value and not file_path:
            flash(f"Checklist required: {question.question_text}", "danger")
            return redirect(url_for("operations.internal_task_detail", assignment_id=assignment.id))

        existing = OperationsChecklistResponse.query.filter_by(
            checklist_question_id=question.id,
            jobcard_service_id=svc.id,
            assignment_id=assignment.id
        ).first()

        if not existing:
            existing = OperationsChecklistResponse(
                checklist_question_id=question.id,
                jobcard_service_id=svc.id,
                assignment_id=assignment.id,
                submitted_by_id=current_user.id
            )
            db.session.add(existing)

        existing.response_value = response_value
        existing.file_path = file_path or existing.file_path
        existing.submitted_at = _now_ist()

    assignment.checklist_status = "Submitted"
    assignment.checklist_submitted_at = _now_ist()

    all_production_assignments = (
        OperationsJobcardAssignment.query
        .filter_by(
            jobcard_service_id=svc.id,
            assignment_type="PRODUCTION"
        )
        .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"]))
        .all()
    )

    pending_checklist_rows = []

    for a in all_production_assignments:
        if a.parent_assignment_id is None and a.status == "Delegated":
            continue

        if a.checklist_status != "Submitted":
            pending_checklist_rows.append(a)

    if not pending_checklist_rows:
        svc.checklist_status = "Submitted"
        svc.checklist_submitted_at = _now_ist()
        
    db.session.commit()

    flash("Checklist submitted successfully.", "success")
    return redirect(url_for("operations.internal_task_detail", assignment_id=assignment.id))

@operations_bp.route("/external-checklist/<token>", methods=["GET", "POST"])
def external_checklist(token):
    assignment = OperationsJobcardAssignment.query.filter_by(
        external_checklist_token=token
    ).first_or_404()

    svc = assignment.jobcard_service

    questions = svc.checklist_questions.order_by(
        OperationsChecklistQuestion.sort_order.asc()
    ).all()

    if request.method == "POST":
        for question in questions:
            input_name = f"checklist_{question.id}"

            file_path = None
            response_value = None

            if question.question_type == "file":
                file_path = _save_jobcard_file(request.files.get(input_name))
            elif question.question_type == "checkbox":
                response_value = "Yes" if request.form.get(input_name) == "1" else "No"
            else:
                response_value = _clean(request.form.get(input_name))

            if question.is_required and not response_value and not file_path:
                flash(f"Checklist required: {question.question_text}", "danger")
                return redirect(url_for("operations.external_checklist", token=token))

            existing = OperationsChecklistResponse.query.filter_by(
                checklist_question_id=question.id,
                jobcard_service_id=svc.id,
                assignment_id=assignment.id
            ).first()

            if not existing:
                existing = OperationsChecklistResponse(
                    checklist_question_id=question.id,
                    jobcard_service_id=svc.id,
                    assignment_id=assignment.id,
                )
                db.session.add(existing)

            existing.response_value = response_value
            existing.file_path = file_path or existing.file_path
            existing.submitted_at = _now_ist()

        assignment.checklist_status = "Submitted"
        assignment.checklist_submitted_at = _now_ist()
        assignment.status = "Completed"
        assignment.completed_at = _now_ist()

        all_production_assignments = (
            OperationsJobcardAssignment.query
            .filter_by(
                jobcard_service_id=svc.id,
                assignment_type="PRODUCTION"
            )
            .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"]))
            .all()
        )

        pending_checklist_rows = []

        for a in all_production_assignments:
            if a.parent_assignment_id is None and a.status == "Delegated":
                continue

            if a.checklist_status != "Submitted":
                pending_checklist_rows.append(a)

        if not pending_checklist_rows:
            svc.checklist_status = "Submitted"
            svc.external_checklist_submitted_at = _now_ist()

        completed_qty = _completed_qty_for_service(svc)
        required_qty = Decimal(str(svc.total_quantity or 0))

        if completed_qty >= required_qty:
            if not _has_pending_qc(svc):
                svc.status = "Completed"
                svc.completed_at = svc.completed_at or _now_ist()
            else:
                svc.status = "QC Pending"
        else:
            _refresh_service_assignment_status(svc)

        _refresh_jobcard_status(svc.jobcard)

        db.session.commit()

        return render_template("operations/external_checklist_success.html")

    return render_template(
        "operations/external_checklist.html",
        svc=svc,
        questions=questions
    )

@operations_bp.route("/services/<int:service_id>/mark-completed", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def mark_service_completed(service_id):
    svc = OperationsJobcardService.query.get_or_404(service_id)
    jobcard = svc.jobcard

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id
    if owner_id != current_user.id and not current_user.has_perm("operations.jobcard.view_all"):
        abort(403)

    if _jobcard_is_locked(jobcard):
        flash(
            "Service cannot be marked completed because this jobcard is closed, billing exists, or closure approval is pending.",
            "danger"
        )
        return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))  

    production_assignments = (
        OperationsJobcardAssignment.query
        .filter_by(
            jobcard_service_id=svc.id,
            assignment_type="PRODUCTION"
        )
        .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"]))
        .all()
    )

    has_checklist = (
        OperationsChecklistQuestion.query
        .filter_by(jobcard_service_id=svc.id)
        .first()
        is not None
    )

    if has_checklist:
        pending_assignment_checklists = []

        for a in production_assignments:
            # Fully delegated parent should not block checklist.
            # Child checklist submission is checked separately.
            if a.parent_assignment_id is None and a.status == "Delegated":
                continue

            if a.checklist_status != "Submitted":
                pending_assignment_checklists.append(a)

        if pending_assignment_checklists:
            flash(
                "Checklist must be submitted for all production assignments before marking this service completed.",
                "danger"
            )
            return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

    # Mark active production assignments completed too.
    # This prevents later quantity-based refresh from treating this service as incomplete.
    for a in production_assignments:
        if a.status == "Completed":
            continue

        if a.parent_assignment_id is None and a.status == "Delegated":
            continue

        a.status = "Completed"
        a.completed_at = a.completed_at or _now_ist()

    # Important:
    # Do NOT call _refresh_jobcard_status_from_assignments(jobcard) here.
    # That function recalculates service status from assignment quantities
    # and can overwrite manual completion back to Submitted/Assigned.
    _mark_service_completed_manually(svc)

    db.session.commit()

    if svc.status == "QC Pending":
        flash("Service production marked completed. QC is pending for this service.", "warning")
    else:
        flash("Service marked completed.", "success")

    return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

@operations_bp.route("/assignments/<int:assignment_id>/submit-checklist", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def submit_assignment_checklist_by_pm(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)
    svc = assignment.jobcard_service
    jobcard = svc.jobcard

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id
    if owner_id != current_user.id and not current_user.has_perm("operations.jobcard.view_all"):
        abort(403)

    for question in svc.checklist_questions.order_by(OperationsChecklistQuestion.sort_order.asc()).all():
        input_name = f"checklist_{assignment.id}_{question.id}"

        file_path = None
        response_value = None

        if question.question_type == "file":
            file_path = _save_jobcard_file(request.files.get(input_name))
        elif question.question_type == "checkbox":
            response_value = "Yes" if request.form.get(input_name) == "1" else "No"
        else:
            response_value = _clean(request.form.get(input_name))

        if question.is_required and not response_value and not file_path:
            flash(f"Checklist required: {question.question_text}", "danger")
            return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

        existing = OperationsChecklistResponse.query.filter_by(
            checklist_question_id=question.id,
            jobcard_service_id=svc.id,
            assignment_id=assignment.id
        ).first()

        if not existing:
            existing = OperationsChecklistResponse(
                checklist_question_id=question.id,
                jobcard_service_id=svc.id,
                assignment_id=assignment.id,
                submitted_by_id=current_user.id
            )
            db.session.add(existing)

        existing.response_value = response_value
        existing.file_path = file_path or existing.file_path
        existing.submitted_by_id = current_user.id
        existing.submitted_at = _now_ist()

    assignment.checklist_status = "Submitted"
    assignment.checklist_submitted_at = _now_ist()

    all_production_assignments = (
        OperationsJobcardAssignment.query
        .filter_by(
            jobcard_service_id=svc.id,
            assignment_type="PRODUCTION"
        )
        .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"]))
        .all()
    )

    pending_checklist_rows = []

    for a in all_production_assignments:
        if a.parent_assignment_id is None and a.status == "Delegated":
            continue

        if a.checklist_status != "Submitted":
            pending_checklist_rows.append(a)

    if not pending_checklist_rows:
        svc.checklist_status = "Submitted"
        svc.checklist_submitted_at = _now_ist()
            
    db.session.commit()

    flash("Checklist submitted for this assignment only.", "success")
    return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))  

@operations_bp.route("/assignments/<int:assignment_id>/complete", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def complete_assignment(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if assignment.assignment_type != "PRODUCTION":
        flash("Invalid production assignment.", "danger")
        return redirect(url_for(
            "operations.view_jobcard",
            jobcard_id=assignment.jobcard_service.jobcard_id
        ))

    svc = assignment.jobcard_service
    jobcard = svc.jobcard

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id
    if owner_id != current_user.id and not current_user.has_perm("operations.jobcard.view_all"):
        abort(403)

    if svc.checklist_questions.count() > 0 and assignment.checklist_status != "Submitted":
        flash("Checklist must be submitted before completing this assignment.", "danger")
        return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

    assignment.status = "Completed"
    assignment.completed_at = _now_ist()

    # One bulk status refresh for the whole jobcard.  This replaces the old
    # per-service/per-child query chain while preserving the same status rules.
    _refresh_jobcard_status_from_assignments(jobcard)

    db.session.commit()

    flash("Assignment marked completed successfully.", "success")
    return redirect(_safe_operations_return_url("operations.vendor_assignment", jobcard_id=jobcard.id))

@operations_bp.route("/jobcards/<int:jobcard_id>/bulk-complete", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def bulk_complete_jobcard_assignments(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

    if not _can_pm_manage_jobcard(jobcard):
        abort(403)

    if _jobcard_is_locked(jobcard):
        flash("Bulk completion is not allowed because this jobcard is closed, billing exists, or closure approval is pending.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    production_assignment_ids = request.form.getlist("production_assignment_ids[]", type=int)
    qc_assignment_ids = request.form.getlist("qc_assignment_ids[]", type=int)

    if not production_assignment_ids and not qc_assignment_ids:
        flash("Please select at least one assignment to complete.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    completed_count = 0
    skipped_messages = []

    try:
        if production_assignment_ids:
            production_assignments = (
                OperationsJobcardAssignment.query
                .join(
                    OperationsJobcardService,
                    OperationsJobcardService.id == OperationsJobcardAssignment.jobcard_service_id
                )
                .filter(OperationsJobcardService.jobcard_id == jobcard.id)
                .filter(OperationsJobcardAssignment.id.in_(production_assignment_ids))
                .filter(OperationsJobcardAssignment.assignment_type == "PRODUCTION")
                .all()
            )

            for assignment in production_assignments:
                success, error = _complete_production_assignment_safely(assignment)

                if success:
                    completed_count += 1
                else:
                    label = assignment.jobcard_service.service_name if assignment.jobcard_service else f"Assignment {assignment.id}"
                    skipped_messages.append(f"{label}: {error}")

        if qc_assignment_ids:
            qc_assignments = (
                OperationsJobcardAssignment.query
                .join(
                    OperationsJobcardService,
                    OperationsJobcardService.id == OperationsJobcardAssignment.jobcard_service_id
                )
                .filter(OperationsJobcardService.jobcard_id == jobcard.id)
                .filter(OperationsJobcardAssignment.id.in_(qc_assignment_ids))
                .filter(OperationsJobcardAssignment.assignment_type == "QC")
                .all()
            )

            for assignment in qc_assignments:
                success, error = _complete_qc_assignment_safely(assignment)

                if success:
                    completed_count += 1
                else:
                    label = assignment.jobcard_service.service_name if assignment.jobcard_service else f"QC {assignment.id}"
                    skipped_messages.append(f"{label}: {error}")

        _refresh_jobcard_status(jobcard)
        db.session.commit()

        if completed_count > 0:
            msg = f"Bulk completion completed. {completed_count} assignment(s) marked completed."

            if skipped_messages:
                msg += " Some rows were skipped: " + " | ".join(skipped_messages[:5])

            flash(msg, "success" if not skipped_messages else "warning")
        else:
            flash("No assignments were completed. " + " | ".join(skipped_messages[:5]), "warning")

    except Exception as e:
        db.session.rollback()
        flash(f"Bulk completion failed: {str(e)}", "danger")

    return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

@operations_bp.route("/assignments/<int:assignment_id>/replace", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def replace_vendor_assignment(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if assignment.assignment_type != "PRODUCTION" or assignment.assigned_to_type != "VENDOR":
        flash("Only vendor production assignments can be replaced.", "danger")
        return redirect(url_for(
            "operations.vendor_assignment",
            jobcard_id=assignment.jobcard_service.jobcard_id
        ))

    svc = assignment.jobcard_service
    jobcard = svc.jobcard

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id
    if owner_id != current_user.id and not current_user.has_perm("operations.jobcard.view_all"):
        abort(403)

    if jobcard.status in ["Ready For Billing", "Closure Approval Pending"]:
        flash("Closed jobcards or closure approval pending jobcards cannot be modified.", "danger")
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

    latest_pi = (
        ProformaInvoice.query
        .filter_by(quote_id=jobcard.quote_id)
        .filter(ProformaInvoice.status != "Cancelled")
        .first()
    )

    latest_invoice = (
        Invoice.query
        .filter_by(quote_id=jobcard.quote_id)
        .filter(Invoice.status != "Cancelled")
        .first()
    )

    if latest_pi or latest_invoice:
        flash("Assignment cannot be replaced because PI or Invoice already exists.", "danger")
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

    reason = _clean(request.form.get("replacement_reason"))
    remark = _clean(request.form.get("replacement_remark"))

    if not reason:
        flash("Replacement reason is required.", "danger")
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

    jobcard_id = jobcard.id
    svc_id = svc.id

    # Store these before ending current local DB transaction.
    old_external_checklist_url = assignment.external_checklist_url
    old_assignment_id = assignment.id

    # Important:
    # End the current local MySQL transaction before calling external PMS.
    # This prevents local rows from staying locked while PMS update runs.
    db.session.rollback()

    pms_delete_result = {
        "deleted": 0,
        "skipped": 0,
        "message": "Not applicable."
    }

    try:
        # Recreate a lightweight object only for PMS delete matching.
        # We only need external_checklist_url for delete_pms_job_for_replaced_assignment().
        assignment_for_pms = OperationsJobcardAssignment(
            id=old_assignment_id,
            external_checklist_url=old_external_checklist_url
        )

        pms_delete_result = delete_pms_job_for_replaced_assignment(assignment_for_pms)

    except Exception as e:
        flash(f"Assignment replacement failed while deleting TransApp line item: {str(e)}", "danger")
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard_id))

    try:
        # Re-query fresh rows after external PMS update.
        assignment = OperationsJobcardAssignment.query.get_or_404(old_assignment_id)
        svc = OperationsJobcardService.query.get_or_404(svc_id)
        jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

        if assignment.status in ["Replaced", "Cancelled", "Rejected"]:
            flash("This assignment is already replaced or cancelled.", "warning")
            return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

        assignment.status = "Replaced"
        assignment.replacement_reason = reason
        assignment.replacement_remark = remark or None
        assignment.replaced_at = _now_ist()
        assignment.replaced_by_id = current_user.id

        assignment.external_checklist_token = None
        assignment.external_checklist_url = None

        svc.completed_at = None
        svc.checklist_status = "Pending"
        svc.checklist_submitted_at = None

        # Prevent SQLAlchemy from autoflushing the replacement update
        # while the status helper functions run SELECT queries.
        with db.session.no_autoflush:
            _refresh_service_assignment_status(svc)
            _refresh_jobcard_status_from_assignments(jobcard)

        db.session.commit()

    except Exception as e:
        db.session.rollback()
        flash(f"Assignment replacement failed while updating Nexus: {str(e)}", "danger")
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard_id))

    message = "Vendor assignment replaced. Quantity has been released for reassignment."

    if pms_delete_result.get("deleted", 0) > 0:
        message += f" TransApp updated: {pms_delete_result.get('deleted')} line item deleted."
    else:
        message += f" TransApp note: {pms_delete_result.get('message')}"

    flash(message, "success" if pms_delete_result.get("deleted", 0) > 0 else "warning")
    return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

@operations_bp.route("/jobcard-closure-approvals")
@login_required
@require_perm("operations.jobcard.margin_approve")
def jobcard_closure_approval_requests():
    requests = (
        OperationsJobcardClosureApprovalRequest.query
        .order_by(
            OperationsJobcardClosureApprovalRequest.status.asc(),
            OperationsJobcardClosureApprovalRequest.requested_at.desc()
        )
        .all()
    )

    today = _now_ist().date()

    pending_count = (
        OperationsJobcardClosureApprovalRequest.query
        .filter_by(status="Pending")
        .count()
    )

    approved_today = (
        OperationsJobcardClosureApprovalRequest.query
        .filter(OperationsJobcardClosureApprovalRequest.status == "Approved")
        .filter(func.date(OperationsJobcardClosureApprovalRequest.approved_at) == today)
        .count()
    )

    rejected_today = (
        OperationsJobcardClosureApprovalRequest.query
        .filter(OperationsJobcardClosureApprovalRequest.status == "Rejected")
        .filter(func.date(OperationsJobcardClosureApprovalRequest.rejected_at) == today)
        .count()
    )

    return render_template(
        "operations/jobcard_closure_approval_requests.html",
        requests=requests,
        pending_count=pending_count,
        approved_today=approved_today,
        rejected_today=rejected_today,
    )


@operations_bp.route("/jobcard-closure-approvals/<int:request_id>/act", methods=["POST"])
@login_required
@require_perm("operations.jobcard.margin_approve")
def act_jobcard_closure_approval_request(request_id):
    row = OperationsJobcardClosureApprovalRequest.query.get_or_404(request_id)

    if row.status != "Pending":
        flash("This closure approval request is already processed.", "warning")
        return redirect(url_for("operations.jobcard_closure_approval_requests"))

    decision = request.form.get("decision")
    remark = _clean(request.form.get("approval_remark"))

    jobcard = row.jobcard

    latest_pi = None
    latest_invoice = None

    if jobcard.quote_id:
        latest_pi = (
            ProformaInvoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(ProformaInvoice.status != "Cancelled")
            .first()
        )

        latest_invoice = (
            Invoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(Invoice.status != "Cancelled")
            .first()
        )

    if latest_pi or latest_invoice:
        flash("This jobcard cannot be approved for closure because PI or Invoice already exists.", "danger")
        return redirect(url_for("operations.jobcard_closure_approval_requests"))

    if decision == "approve":
        closure_blocker = _jobcard_closure_blocker(jobcard)

        if closure_blocker:
            flash(f"Cannot approve closure: {closure_blocker}", "danger")
            return redirect(url_for("operations.jobcard_closure_approval_requests"))

        row.status = "Approved"
        row.approved_by_id = current_user.id
        row.approved_at = _now_ist()
        row.approval_remark = remark or "Approved."

        jobcard.billing_company_branch_id = row.billing_company_branch_id
        jobcard.closure_remark = row.closure_remark
        jobcard.closed_by_id = row.requested_by_id
        jobcard.closed_at = _now_ist()
        jobcard.ready_for_billing_at = _now_ist()
        jobcard.ready_for_billing_by_id = current_user.id
        jobcard.status = "Ready For Billing"

        try:
            pms_result = update_pms_jobs_to_raise_invoice(jobcard)
        except Exception as e:
            db.session.rollback()
            flash(f"Closure approval failed while updating PMS status: {str(e)}", "danger")
            return redirect(url_for("operations.jobcard_closure_approval_requests"))

        db.session.commit()

        message = "Low margin closure approved. Jobcard has been marked Ready For Billing."

        if pms_result["updated"] > 0:
            message += f" PMS updated: {pms_result['updated']} external job(s) moved to RaiseInvoice."
        else:
            message += " No PMS external job status was updated."

        if pms_result["errors"]:
            message += " PMS issues: " + " | ".join(pms_result["errors"][:5])

        flash(message, "success" if not pms_result["errors"] else "warning")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id)) 

    if decision == "reject":
        if not remark:
            flash("Rejection remark is required.", "danger")
            return redirect(url_for("operations.jobcard_closure_approval_requests"))

        row.status = "Rejected"
        row.rejected_by_id = current_user.id
        row.rejected_at = _now_ist()
        row.approval_remark = remark

        if jobcard.status == "Closure Approval Pending":
            jobcard.status = "Completed"

        db.session.commit()

        flash("Low margin closure request rejected.", "warning")
        return redirect(url_for("operations.jobcard_closure_approval_requests"))

    flash("Invalid action.", "danger")
    return redirect(url_for("operations.jobcard_closure_approval_requests"))

@operations_bp.route("/internal-process-master", methods=["GET", "POST"])
@login_required
@require_perm("operations.internal_process.manage")
def internal_process_master():
    if request.method == "POST":
        action = request.form.get("action")

        if action == "create":
            name = _clean(request.form.get("name"))
            code = _clean(request.form.get("code")).lower().replace(" ", "_")
            description = _clean(request.form.get("description"))
            sort_order = request.form.get("sort_order", type=int) or 1
            is_active = True if request.form.get("is_active") == "1" else False

            if not name or not code:
                flash("Process name and code are required.", "danger")
                return redirect(url_for("operations.internal_process_master"))

            existing = (
                OperationsInternalProcessMaster.query
                .filter(
                    or_(
                        OperationsInternalProcessMaster.name == name,
                        OperationsInternalProcessMaster.code == code
                    )
                )
                .first()
            )

            if existing:
                flash("Process name or code already exists.", "danger")
                return redirect(url_for("operations.internal_process_master"))

            row = OperationsInternalProcessMaster(
                name=name,
                code=code,
                description=description or None,
                sort_order=sort_order,
                is_active=is_active,
                created_by_id=current_user.id,
            )

            db.session.add(row)
            db.session.commit()

            flash("Internal process added successfully.", "success")
            return redirect(url_for("operations.internal_process_master"))

        if action == "update":
            row = OperationsInternalProcessMaster.query.get_or_404(
                request.form.get("process_id", type=int)
            )

            name = _clean(request.form.get("name"))
            code = _clean(request.form.get("code")).lower().replace(" ", "_")
            description = _clean(request.form.get("description"))
            sort_order = request.form.get("sort_order", type=int) or 1
            is_active = True if request.form.get("is_active") == "1" else False

            if not name or not code:
                flash("Process name and code are required.", "danger")
                return redirect(url_for("operations.internal_process_master"))

            duplicate = (
                OperationsInternalProcessMaster.query
                .filter(OperationsInternalProcessMaster.id != row.id)
                .filter(
                    or_(
                        OperationsInternalProcessMaster.name == name,
                        OperationsInternalProcessMaster.code == code
                    )
                )
                .first()
            )

            if duplicate:
                flash("Another process with same name or code already exists.", "danger")
                return redirect(url_for("operations.internal_process_master"))

            row.name = name
            row.code = code
            row.description = description or None
            row.sort_order = sort_order
            row.is_active = is_active

            db.session.commit()

            flash("Internal process updated successfully.", "success")
            return redirect(url_for("operations.internal_process_master"))

        if action == "delete":
            row = OperationsInternalProcessMaster.query.get_or_404(
                request.form.get("process_id", type=int)
            )

            used_count = OperationsJobcardProcess.query.filter_by(
                process_master_id=row.id
            ).count()

            if used_count > 0:
                flash("This process is already used in jobcards. Please deactivate it instead of deleting.", "danger")
                return redirect(url_for("operations.internal_process_master"))

            db.session.delete(row)
            db.session.commit()

            flash("Internal process deleted successfully.", "success")
            return redirect(url_for("operations.internal_process_master"))

    rows = (
        OperationsInternalProcessMaster.query
        .order_by(
            OperationsInternalProcessMaster.sort_order.asc(),
            OperationsInternalProcessMaster.name.asc()
        )
        .all()
    )

    return render_template(
        "operations/internal_process_master.html",
        rows=rows
    )

@operations_bp.route("/jobcards/<int:jobcard_id>/internal-process-assign", methods=["POST"])
@login_required
@require_perm("operations.internal_process.assign")
def assign_internal_process(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id
    if owner_id != current_user.id and not current_user.has_perm("operations.jobcard.view_all"):
        abort(403)

    if jobcard.status in ["Ready For Billing", "Closure Approval Pending"]:
        flash("Internal process assignment is not allowed after closure or while closure approval is pending.", "danger")
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))  

    latest_pi = None
    latest_invoice = None

    if jobcard.quote_id:
        latest_pi = (
            ProformaInvoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(ProformaInvoice.status != "Cancelled")
            .first()
        )

        latest_invoice = (
            Invoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(Invoice.status != "Cancelled")
            .first()
        )

    if latest_pi or latest_invoice:
        flash("Internal process assignment cannot be modified because PI or Invoice already exists.", "danger")
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

    jobcard_process_id = request.form.get("jobcard_process_id", type=int)
    jobcard_service_id = request.form.get("jobcard_service_id", type=int)
    assigned_to_type = request.form.get("assigned_to_type") or "INTERNAL"

    assigned_qty = Decimal(str(request.form.get("assigned_qty") or 0))
    rate = Decimal(str(request.form.get("rate") or 0))
    flat_rate = True if request.form.get("flat_rate") == "1" else False

    deadline_raw = request.form.get("deadline") or None
    instruction = _clean(request.form.get("instruction"))

    file_title = _clean(request.form.get("file_title"))
    file_path = _save_jobcard_file(request.files.get("assignment_file"))

    if not jobcard_process_id or not jobcard_service_id:
        flash("Please select process and service line.", "danger")
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

    if assigned_qty <= 0:
        flash("Assigned quantity must be greater than zero.", "danger")
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))
    jobcard_process = OperationsJobcardProcess.query.get_or_404(jobcard_process_id)

    if jobcard_process.jobcard_id != jobcard.id:
        abort(403)

    svc = OperationsJobcardService.query.get_or_404(jobcard_service_id)

    if svc.jobcard_id != jobcard.id:
        abort(403)

    deadline = None
    if deadline_raw:
        deadline = datetime.strptime(deadline_raw, "%Y-%m-%dT%H:%M")

    assignment = OperationsJobcardProcessAssignment(
        jobcard_process_id=jobcard_process.id,
        jobcard_service_id=svc.id,
        assigned_to_type=assigned_to_type,
        assigned_qty=assigned_qty,
        rate=rate,
        flat_rate=flat_rate,
        deadline=deadline,
        instruction=instruction or None,
        status="Assigned",
        file_title=file_title or None,
        file_path=file_path or None,
        assigned_by_id=current_user.id,
        assigned_at=_now_ist()
    )

    if assigned_to_type == "INTERNAL":
        internal_user_id = request.form.get("internal_user_id", type=int)
        internal_user = User.query.get(internal_user_id) if internal_user_id else None

        if not internal_user:
            flash("Please select internal user.", "danger")
            return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

        assignment.internal_user_id = internal_user.id

    elif assigned_to_type == "VENDOR":
        vendor_id = request.form.get("vendor_id", type=int)
        vendor = VendorMaster.query.get(vendor_id) if vendor_id else None

        if not vendor:
            flash("Please select vendor.", "danger")
            return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))
        allowed, block_reason = _vendor_assignment_allowed(vendor)
        if not allowed:
            flash("{} cannot be assigned: {}".format(vendor.name, block_reason or "vendor is not eligible"), "danger")
            return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

        assignment.vendor_id = vendor.id

    else:
        flash("Invalid assignment type.", "danger")
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

    db.session.add(assignment)

    if jobcard_process.status in ["Pending", "Completed"]:
        jobcard_process.status = "Assigned"

    db.session.commit()

    flash("Internal process assignment added successfully.", "success")
    return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

@operations_bp.route("/internal-process-assignments/<int:assignment_id>/status", methods=["POST"])
@login_required
@require_perm("operations.internal_process.update")
def update_internal_process_assignment_status(assignment_id):
    assignment = OperationsJobcardProcessAssignment.query.get_or_404(assignment_id)

    jobcard = assignment.jobcard_process.jobcard

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id
    is_assignee = (
        assignment.assigned_to_type == "INTERNAL"
        and assignment.internal_user_id == current_user.id
    )

    if owner_id != current_user.id and not is_assignee and not current_user.has_perm("operations.jobcard.view_all"):
        abort(403)

    new_status = request.form.get("status")

    if new_status not in ["Assigned", "In Progress", "Completed", "On Hold", "Cancelled"]:
        flash("Invalid status selected.", "danger")
        return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))

    assignment.status = new_status

    if new_status == "Completed":
        assignment.completed_at = _now_ist()
    else:
        assignment.completed_at = None


    jobcard_process = assignment.jobcard_process
    _refresh_jobcard_process_status(jobcard_process)

    db.session.commit()

    flash("Internal process assignment status updated successfully.", "success")
    return redirect(url_for("operations.vendor_assignment", jobcard_id=jobcard.id))


def _format_workload_deadline(value):
    if not value:
        return ""

    try:
        return value.strftime("%d-%m-%Y %I:%M %p")
    except Exception:
        return str(value)

def _service_assignment_extra_details(row):
    svc = row.jobcard_service
    quote_item = svc.quote_item if svc and getattr(svc, "quote_item", None) else None

    description = ""
    if quote_item and quote_item.description:
        description = quote_item.description
    elif quote_item and quote_item.item_name:
        description = quote_item.item_name
    elif svc and svc.service_name:
        description = svc.service_name

    word_count = (
        row.assigned_qty
        or (svc.total_quantity if svc else 0)
        or (quote_item.qty if quote_item else 0)
        or 0
    )

    return description, word_count

def _assignment_title_from_service_assignment(row):
    svc = row.jobcard_service
    jobcard = svc.jobcard if svc else None

    description, word_count = _service_assignment_extra_details(row)

    title_parts = []

    if svc and svc.service_name:
        title_parts.append(svc.service_name)

    if row.instruction:
        title_parts.append(row.instruction)
    elif row.additional_instruction:
        title_parts.append(row.additional_instruction)

    title = " - ".join([str(x) for x in title_parts if x])

    if not title:
        title = "Service Assignment"

    assignment_type = (row.assignment_type or "PRODUCTION").strip().upper()

    if row.assigned_to_type == "INTERNAL":
        if assignment_type == "QC":
            task_url = url_for(
                "operations.qc_task_detail",
                assignment_id=row.id
            )
            action_label = "Open QC"
        else:
            task_url = url_for(
                "operations.internal_task_detail",
                assignment_id=row.id
            )
            action_label = "Open Task"
    else:
        task_url = (
            url_for("operations.view_jobcard", jobcard_id=jobcard.id)
            if jobcard else ""
        )
        action_label = "View Jobcard"

    return {
        "id": row.id,
        "type": assignment_type,
        "jobcard_no": jobcard.jobcard_code if jobcard else "",
        "assignment_title": title,
        "service_name": svc.service_name if svc else "",
        "description": description,
        "word_count": str(word_count or 0),
        "status": row.status or "Assigned",
        "deadline": _format_workload_deadline(row.deadline),
        "url": task_url,
        "action_label": action_label,
    }

def _assignment_title_from_process_assignment(row):
    jobcard_process = row.jobcard_process
    process_master = jobcard_process.process_master if jobcard_process else None
    jobcard = jobcard_process.jobcard if jobcard_process else None
    svc = row.jobcard_service

    title_parts = []

    if process_master and process_master.name:
        title_parts.append(process_master.name)

    if svc and svc.service_name:
        title_parts.append(svc.service_name)

    if row.instruction:
        title_parts.append(row.instruction)
    elif row.additional_instruction:
        title_parts.append(row.additional_instruction)

    title = " - ".join([str(x) for x in title_parts if x])

    if not title:
        title = "Internal Process Assignment"

    if row.assigned_to_type == "INTERNAL":
        task_url = url_for(
            "operations.internal_process_task_detail",
            assignment_id=row.id
        )
        action_label = "Open Task"
    else:
        task_url = (
            url_for("operations.view_jobcard", jobcard_id=jobcard.id)
            if jobcard else ""
        )
        action_label = "View Jobcard"

    return {
        "id": row.id,
        "type": "PROCESS",
        "jobcard_no": jobcard.jobcard_code if jobcard else "",
        "assignment_title": title,
        "service_name": svc.service_name if svc else "",
        "status": row.status or "Assigned",
        "deadline": _format_workload_deadline(row.deadline),
        "url": task_url,
        "action_label": action_label,
    }


def _jobcard_title_from_jobcard(row):
    title_parts = []

    if row.jobcard_code:
        title_parts.append(row.jobcard_code)

    if row.quote and row.quote.quote_code:
        title_parts.append(row.quote.quote_code)

    title = " - ".join([str(x) for x in title_parts if x])

    if not title:
        title = "PM Jobcard"

    return {
        "id": row.id,
        "type": "PM JOBCARD",
        "jobcard_no": row.jobcard_code or "",
        "assignment_title": title,
        "service_name": "",
        "status": row.status or "Submitted",
        "deadline": "",
        "url": url_for("operations.view_jobcard", jobcard_id=row.id)
    }

def _deadline_bucket(deadline):
    now = _now_ist()
    today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
    tomorrow_start = today_start + timedelta(days=1)
    day_after_start = today_start + timedelta(days=2)
    next_7_days = today_start + timedelta(days=7)

    if not deadline:
        return "no_deadline"

    if deadline < now:
        return "overdue"

    if today_start <= deadline < tomorrow_start:
        return "due_today"

    if tomorrow_start <= deadline < day_after_start:
        return "due_tomorrow"

    if deadline <= next_7_days:
        return "due_soon"

    return "later"


def _deadline_sort_value(deadline):
    if not deadline:
        return datetime.utcnow() + timedelta(days=3650)
    return deadline


def _workload_item_dict(row, source_type):
    description = ""
    word_count = 0

    if source_type == "PROCESS":
        jp = row.jobcard_process
        jobcard = jp.jobcard if jp else None
        process_name = jp.process_master.name if jp and jp.process_master else "Internal Process"
        service_name = row.jobcard_service.service_name if row.jobcard_service else ""

        svc = row.jobcard_service
        quote_item = svc.quote_item if svc and getattr(svc, "quote_item", None) else None

        if quote_item and quote_item.description:
            description = quote_item.description
        elif quote_item and quote_item.item_name:
            description = quote_item.item_name
        elif row.instruction:
            description = row.instruction
        elif row.additional_instruction:
            description = row.additional_instruction
        elif service_name:
            description = service_name

        word_count = (
            row.assigned_qty
            or (svc.total_quantity if svc else 0)
            or (quote_item.qty if quote_item else 0)
            or 0
        )

        title = process_name
        if service_name:
            title += " - " + service_name

    else:
        svc = row.jobcard_service
        jobcard = svc.jobcard if svc else None
        service_name = svc.service_name if svc else ""
        title = service_name or source_type

        description, word_count = _service_assignment_extra_details(row)

    return {
        "id": row.id,
        "source_type": source_type,
        "jobcard_no": jobcard.jobcard_code if jobcard else "",
        "jobcard_id": jobcard.id if jobcard else None,
        "title": title,
        "description": description,
        "word_count": str(word_count or 0),
        "status": row.status or "Assigned",
        "deadline": row.deadline,
        "deadline_text": _format_workload_deadline(row.deadline),
        "deadline_bucket": _deadline_bucket(row.deadline),
        "url": url_for("operations.view_jobcard", jobcard_id=jobcard.id) if jobcard else "",
    }

def _build_need_to_know_workload(user_ids):
    """
    PM planning view:
    shows only active work, deadline pressure and next aligned tasks.
    """
    users = (
        User.query
        .filter(User.id.in_(user_ids))
        .order_by(User.name.asc())
        .all()
    )

    rows = {}

    for user in users:
        rows[user.id] = {
            "user": user,
            "user_id": user.id,
            "active_total": 0,
            "production_active": 0,
            "qc_active": 0,
            "process_active": 0,
            "assigned": 0,
            "in_progress": 0,
            "on_hold": 0,
            "overdue": 0,
            "due_today": 0,
            "due_tomorrow": 0,
            "due_soon": 0,
            "later": 0,
            "no_deadline": 0,
            "next_deadline": None,
            "next_items": [],
        }

    if not user_ids:
        return []

    service_assignments = (
        OperationsJobcardAssignment.query
        .join(
            OperationsJobcardService,
            OperationsJobcardService.id == OperationsJobcardAssignment.jobcard_service_id
        )
        .join(
            OperationsJobcard,
            OperationsJobcard.id == OperationsJobcardService.jobcard_id
        )
        .filter(OperationsJobcardAssignment.assigned_to_type == "INTERNAL")
        .filter(OperationsJobcardAssignment.internal_user_id.in_(user_ids))
        .filter(OperationsJobcardAssignment.status.notin_(["Completed", "Cancelled", "Replaced", "Rejected"]))
        .order_by(
            OperationsJobcardAssignment.deadline.asc(),
            OperationsJobcardAssignment.id.desc()
        )
        .all()
    )

    for row in service_assignments:
        _normalize_effective_service_assignment_status(row)
        data = rows.get(row.internal_user_id)
        if not data:
            continue

        source_type = row.assignment_type or "PRODUCTION"
        item = _workload_item_dict(row, source_type)

        data["active_total"] += 1

        if source_type == "QC":
            data["qc_active"] += 1
        else:
            data["production_active"] += 1

        status = row.status or "Assigned"
        if status == "Assigned":
            data["assigned"] += 1
        elif status == "In Progress":
            data["in_progress"] += 1
        elif status == "On Hold":
            data["on_hold"] += 1

        bucket = item["deadline_bucket"]
        data[bucket] += 1

        if row.deadline and (not data["next_deadline"] or row.deadline < data["next_deadline"]):
            data["next_deadline"] = row.deadline

        data["next_items"].append(item)

    process_assignments = (
        OperationsJobcardProcessAssignment.query
        .join(
            OperationsJobcardProcess,
            OperationsJobcardProcess.id == OperationsJobcardProcessAssignment.jobcard_process_id
        )
        .join(
            OperationsJobcard,
            OperationsJobcard.id == OperationsJobcardProcess.jobcard_id
        )
        .filter(OperationsJobcardProcessAssignment.assigned_to_type == "INTERNAL")
        .filter(OperationsJobcardProcessAssignment.internal_user_id.in_(user_ids))
        .filter(OperationsJobcardProcessAssignment.status.notin_(["Completed", "Cancelled"]))
        .order_by(
            OperationsJobcardProcessAssignment.deadline.asc(),
            OperationsJobcardProcessAssignment.id.desc()
        )
        .all()
    )

    for row in process_assignments:
        _normalize_effective_process_assignment_status(row)
        data = rows.get(row.internal_user_id)
        if not data:
            continue

        item = _workload_item_dict(row, "PROCESS")

        data["active_total"] += 1
        data["process_active"] += 1

        status = row.status or "Assigned"
        if status == "Assigned":
            data["assigned"] += 1
        elif status == "In Progress":
            data["in_progress"] += 1
        elif status == "On Hold":
            data["on_hold"] += 1

        bucket = item["deadline_bucket"]
        data[bucket] += 1

        if row.deadline and (not data["next_deadline"] or row.deadline < data["next_deadline"]):
            data["next_deadline"] = row.deadline

        data["next_items"].append(item)

    final_rows = []

    for data in rows.values():
        data["next_items"] = sorted(
            data["next_items"],
            key=lambda x: _deadline_sort_value(x["deadline"])
        )[:5]

        data["next_deadline_text"] = _format_workload_deadline(data["next_deadline"])

        if data["overdue"] > 0:
            data["load_status"] = "Critical"
        elif data["due_today"] > 0:
            data["load_status"] = "Due Today"
        elif data["active_total"] >= 8:
            data["load_status"] = "Heavy"
        elif data["active_total"] >= 4:
            data["load_status"] = "Moderate"
        elif data["active_total"] > 0:
            data["load_status"] = "Light"
        else:
            data["load_status"] = "Available"

        final_rows.append(data)

    final_rows.sort(
        key=lambda r: (
            r["overdue"],
            r["due_today"],
            r["due_tomorrow"],
            r["active_total"]
        ),
        reverse=True
    )

    return final_rows

@operations_bp.route("/workload-dashboard")
@login_required
@require_perm("operations.workload.view")
def workload_dashboard():
    q = _clean(request.args.get("q"))
    status_filter = _clean(request.args.get("status"))
    view_scope = _clean(request.args.get("scope")) or "team"
    department_filter = _clean(request.args.get("department"))
    user_filter = request.args.get("user_id", type=int)

    allowed_user_ids = _get_workload_scope_user_ids()

    if not allowed_user_ids:
        flash("No workload data available.", "warning")
        return redirect(url_for("operations.dashboard"))

    users_query = (
        User.query
        .outerjoin(EmployeeProfile, EmployeeProfile.user_id == User.id)
        .filter(User.id.in_(allowed_user_ids))
    )

    if q:
        like = f"%{q}%"
        users_query = users_query.filter(or_(
            User.name.ilike(like),
            User.email.ilike(like)
        ))
    
    if department_filter:
        users_query = users_query.filter(EmployeeProfile.department == department_filter)

    if user_filter:
        users_query = users_query.filter(User.id == user_filter)

    filter_user_options = (
        User.query
        .outerjoin(EmployeeProfile, EmployeeProfile.user_id == User.id)
        .filter(User.id.in_(allowed_user_ids))
        .order_by(User.name.asc())
        .all()
    )

    department_options = (
        db.session.query(EmployeeProfile.department)
        .join(User, User.id == EmployeeProfile.user_id)
        .filter(User.id.in_(allowed_user_ids))
        .filter(EmployeeProfile.department.isnot(None))
        .filter(EmployeeProfile.department != "")
        .distinct()
        .order_by(EmployeeProfile.department.asc())
        .all()
    )

    department_options = [row[0] for row in department_options if row[0]]

    filtered_users = users_query.order_by(User.name.asc()).all()
    filtered_user_ids = [u.id for u in filtered_users]

    workload_summary = _build_user_workload_summary(filtered_user_ids)
    need_rows = _build_need_to_know_workload(filtered_user_ids)

    rows = list(workload_summary.values())

    if status_filter == "overdue":
        rows = [r for r in rows if r["overdue"] > 0]
    elif status_filter == "due_soon":
        rows = [r for r in rows if r["due_soon"] > 0]
    elif status_filter == "active":
        rows = [r for r in rows if r["active_total"] > 0]
    elif status_filter == "completed":
        rows = [r for r in rows if r["completed_total"] > 0]

    rows.sort(
        key=lambda r: (
            r["overdue"],
            r["active_total"],
            r["total_workload"]
        ),
        reverse=True
    )

    totals = {
        "users": len(rows),
        "active_total": sum(r["active_total"] for r in rows),
        "completed_total": sum(r["completed_total"] for r in rows),
        "total_workload": sum(r["total_workload"] for r in rows),
        "overdue": sum(r["overdue"] for r in rows),
        "due_soon": sum(r["due_soon"] for r in rows),

        "production_total": sum(r["production_total"] for r in rows),
        "qc_total": sum(r["qc_total"] for r in rows),
        "process_total": sum(r["process_total"] for r in rows),
        "jobcards_owned": sum(r["jobcards_owned"] for r in rows),

        "planning_active_total": sum(r["active_total"] for r in need_rows),
        "planning_overdue": sum(r["overdue"] for r in need_rows),
        "planning_due_today": sum(r["due_today"] for r in need_rows),
        "planning_due_tomorrow": sum(r["due_tomorrow"] for r in need_rows),
        "planning_due_soon": sum(r["due_soon"] for r in need_rows),
        "planning_no_deadline": sum(r["no_deadline"] for r in need_rows),
        "planning_available": len([r for r in need_rows if r["active_total"] == 0]),
    }

    can_view_all = current_user.has_perm("operations.jobcard.view_all")
    team_user_ids = _get_team_user_ids_for_manager(current_user.id)
    is_reporting_manager = True if team_user_ids else False

    return render_template(
        "operations/workload_dashboard.html",
        rows=rows,
        need_rows=need_rows,
        totals=totals,
        q=q,
        status_filter=status_filter,
        view_scope=view_scope,
        can_view_all=can_view_all,
        is_reporting_manager=is_reporting_manager,
        department_filter=department_filter,
        user_filter=user_filter,
        department_options=department_options,
        filter_user_options=filter_user_options,
    )

@operations_bp.route("/workload-dashboard/details/<int:user_id>/<string:bucket>")
@login_required
@require_perm("operations.workload.view")
def workload_dashboard_details(user_id, bucket):
    allowed_user_ids = _get_workload_scope_user_ids()

    if user_id not in allowed_user_ids:
        abort(403)

    today_start = _now_ist().replace(hour=0, minute=0, second=0, microsecond=0)
    next_7_days = today_start + timedelta(days=7)

    items = []

    # -----------------------------
    # Production / QC assignments
    # -----------------------------
    assignment_query = (
        OperationsJobcardAssignment.query
        .join(
            OperationsJobcardService,
            OperationsJobcardService.id == OperationsJobcardAssignment.jobcard_service_id
        )
        .join(
            OperationsJobcard,
            OperationsJobcard.id == OperationsJobcardService.jobcard_id
        )
        .filter(OperationsJobcardAssignment.assigned_to_type == "INTERNAL")
        .filter(OperationsJobcardAssignment.internal_user_id == user_id)
        .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"]))
    )

    if bucket == "production":
        rows = (
            assignment_query
            .filter(OperationsJobcardAssignment.assignment_type == "PRODUCTION")
            .order_by(OperationsJobcardAssignment.deadline.asc(), OperationsJobcardAssignment.id.desc())
            .all()
        )
        items.extend([_assignment_title_from_service_assignment(row) for row in rows])

    elif bucket == "qc":
        rows = (
            assignment_query
            .filter(OperationsJobcardAssignment.assignment_type == "QC")
            .order_by(OperationsJobcardAssignment.deadline.asc(), OperationsJobcardAssignment.id.desc())
            .all()
        )
        items.extend([_assignment_title_from_service_assignment(row) for row in rows])

    elif bucket == "active":
        rows = (
            assignment_query
            .filter(OperationsJobcardAssignment.status.notin_(["Completed", "Cancelled", "Replaced", "Rejected"]))
            .order_by(OperationsJobcardAssignment.deadline.asc(), OperationsJobcardAssignment.id.desc())
            .all()
        )
        items.extend([_assignment_title_from_service_assignment(row) for row in rows])

    elif bucket == "completed":
        rows = (
            assignment_query
            .filter(OperationsJobcardAssignment.status == "Completed")
            .order_by(OperationsJobcardAssignment.completed_at.desc(), OperationsJobcardAssignment.id.desc())
            .all()
        )
        items.extend([_assignment_title_from_service_assignment(row) for row in rows])

    elif bucket == "overdue":
        rows = (
            assignment_query
            .filter(OperationsJobcardAssignment.status.notin_(["Completed", "Cancelled", "Replaced", "Rejected"]))
            .filter(OperationsJobcardAssignment.deadline.isnot(None))
            .filter(OperationsJobcardAssignment.deadline < today_start)
            .order_by(OperationsJobcardAssignment.deadline.asc(), OperationsJobcardAssignment.id.desc())
            .all()
        )
        items.extend([_assignment_title_from_service_assignment(row) for row in rows])

    elif bucket == "due_soon":
        rows = (
            assignment_query
            .filter(OperationsJobcardAssignment.status.notin_(["Completed", "Cancelled", "Replaced", "Rejected"]))
            .filter(OperationsJobcardAssignment.deadline.isnot(None))
            .filter(OperationsJobcardAssignment.deadline >= today_start)
            .filter(OperationsJobcardAssignment.deadline <= next_7_days)
            .order_by(OperationsJobcardAssignment.deadline.asc(), OperationsJobcardAssignment.id.desc())
            .all()
        )
        items.extend([_assignment_title_from_service_assignment(row) for row in rows])

    # -----------------------------
    # Internal process assignments
    # -----------------------------
    process_query = (
        OperationsJobcardProcessAssignment.query
        .join(
            OperationsJobcardProcess,
            OperationsJobcardProcess.id == OperationsJobcardProcessAssignment.jobcard_process_id
        )
        .join(
            OperationsJobcard,
            OperationsJobcard.id == OperationsJobcardProcess.jobcard_id
        )
        .filter(OperationsJobcardProcessAssignment.assigned_to_type == "INTERNAL")
        .filter(OperationsJobcardProcessAssignment.internal_user_id == user_id)
        .filter(OperationsJobcardProcessAssignment.status != "Cancelled")
    )

    if bucket == "process":
        rows = (
            process_query
            .order_by(OperationsJobcardProcessAssignment.deadline.asc(), OperationsJobcardProcessAssignment.id.desc())
            .all()
        )
        items.extend([_assignment_title_from_process_assignment(row) for row in rows])

    elif bucket in ["active", "overdue", "due_soon", "completed"]:
        pq = process_query

        if bucket == "active":
            pq = pq.filter(OperationsJobcardProcessAssignment.status != "Completed")

        elif bucket == "completed":
            pq = pq.filter(OperationsJobcardProcessAssignment.status == "Completed")

        elif bucket == "overdue":
            pq = (
                pq
                .filter(OperationsJobcardProcessAssignment.status != "Completed")
                .filter(OperationsJobcardProcessAssignment.deadline.isnot(None))
                .filter(OperationsJobcardProcessAssignment.deadline < today_start)
            )

        elif bucket == "due_soon":
            pq = (
                pq
                .filter(OperationsJobcardProcessAssignment.status != "Completed")
                .filter(OperationsJobcardProcessAssignment.deadline.isnot(None))
                .filter(OperationsJobcardProcessAssignment.deadline >= today_start)
                .filter(OperationsJobcardProcessAssignment.deadline <= next_7_days)
            )

        rows = (
            pq
            .order_by(OperationsJobcardProcessAssignment.deadline.asc(), OperationsJobcardProcessAssignment.id.desc())
            .all()
        )
        items.extend([_assignment_title_from_process_assignment(row) for row in rows])

    # -----------------------------
    # PM owned jobcards
    # -----------------------------
    if bucket in ["pm_jobcards", "active", "completed"]:
        jq = OperationsJobcard.query.filter(OperationsJobcard.current_owner_id == user_id)

        if bucket == "completed":
            jq = jq.filter(OperationsJobcard.status == "Completed")
        elif bucket == "active":
            jq = jq.filter(OperationsJobcard.status != "Completed")

        rows = (
            jq
            .order_by(OperationsJobcard.created_at.desc(), OperationsJobcard.id.desc())
            .all()
        )

        items.extend([_jobcard_title_from_jobcard(row) for row in rows])

    user = User.query.get(user_id)

    return jsonify({
        "success": True,
        "user_name": user.name if user else "",
        "bucket": bucket,
        "count": len(items),
        "items": items
    })

@operations_bp.route("/dashboard")
@login_required
def operations_dashboard():
    """
    Operations dashboard.
    Shows cards, quick links and recent work based on logged-in user's permissions.
    """

    can_view_jobcards = current_user.has_perm("operations.jobcard.view")
    can_view_all_jobcards = current_user.has_perm("operations.jobcard.view_all")
    can_create_jobcard = current_user.has_perm("operations.jobcard.create")
    can_assign_vendor = current_user.has_perm("operations.vendor.assign")
    can_view_internal_tasks = current_user.has_perm("operations.internal_tasks.view")
    can_manage_checklist = current_user.has_perm("operations.checklist_master.manage")
    can_manage_jobcard_fields = current_user.has_perm("operations.jobcard.manage_fields")
    can_manage_internal_process = current_user.has_perm("operations.internal_process.manage")
    can_assign_internal_process = current_user.has_perm("operations.internal_process.assign")
    can_margin_approve = current_user.has_perm("operations.jobcard.margin_approve")
    can_reopen_approve = current_user.has_perm("operations.jobcard.reopen_approve")
    can_reopen_request = current_user.has_perm("operations.jobcard.reopen_request")

    permissions = {
        "can_view_jobcards": can_view_jobcards,
        "can_view_all_jobcards": can_view_all_jobcards,
        "can_create_jobcard": can_create_jobcard,
        "can_assign_vendor": can_assign_vendor,
        "can_view_internal_tasks": can_view_internal_tasks,
        "can_manage_checklist": can_manage_checklist,
        "can_manage_jobcard_fields": can_manage_jobcard_fields,
        "can_manage_internal_process": can_manage_internal_process,
        "can_assign_internal_process": can_assign_internal_process,
        "can_margin_approve": can_margin_approve,
        "can_reopen_approve": can_reopen_approve,
        "can_reopen_request": can_reopen_request,
    }

    # -----------------------------
    # Jobcard summary
    # -----------------------------
    jobcard_summary = {
        "total": 0,
        "submitted": 0,
        "assigned": 0,
        "in_progress": 0,
        "qc_pending": 0,
        "completed": 0,
        "closure_pending": 0,
        "ready_for_billing": 0,
    }

    recent_jobcards = []

    if can_view_jobcards or can_view_all_jobcards:
        jobcard_query = OperationsJobcard.query

        if not can_view_all_jobcards:
            jobcard_query = jobcard_query.filter(or_(
                OperationsJobcard.assigned_to_id == current_user.id,
                OperationsJobcard.current_owner_id == current_user.id
            ))

        jobcards_for_summary = jobcard_query.all()

        jobcard_summary = {
            "total": len(jobcards_for_summary),
            "submitted": sum(1 for j in jobcards_for_summary if j.status == "Submitted"),
            "assigned": sum(
                1 for j in jobcards_for_summary
                if j.status in ["Assigned", "Partially Assigned", "Over Assigned"]
            ),
            "in_progress": sum(1 for j in jobcards_for_summary if j.status == "In Progress"),
            "qc_pending": sum(1 for j in jobcards_for_summary if j.status == "QC Pending"),
            "completed": sum(1 for j in jobcards_for_summary if j.status == "Completed"),
            "closure_pending": sum(1 for j in jobcards_for_summary if j.status == "Closure Approval Pending"),
            "ready_for_billing": sum(1 for j in jobcards_for_summary if j.status == "Ready For Billing"),
        }

        recent_jobcards = (
            jobcard_query
            .order_by(
                OperationsJobcard.created_at.desc(),
                OperationsJobcard.id.desc()
            )
            .limit(8)
            .all()
        )

    # -----------------------------
    # Pending jobcard requests
    # -----------------------------
    pending_jobcard_requests_count = 0
    recent_jobcard_requests = []

    if can_create_jobcard:
        jobcard_request_query = (
            Quote.query
            .filter(Quote.ops_assigned_to_id == current_user.id)
            .filter(Quote.ops_assignment_status == "Pending Jobcard")
            .filter(Quote.proposal_confirmed_at.isnot(None))
        )

        pending_jobcard_requests_count = jobcard_request_query.count()

        recent_jobcard_requests = (
            jobcard_request_query
            .order_by(
                Quote.ops_assigned_at.desc(),
                Quote.id.desc()
            )
            .limit(6)
            .all()
        )

    # -----------------------------
    # Internal service task summary
    # -----------------------------
    internal_task_summary = {
        "total": 0,
        "assigned": 0,
        "in_progress": 0,
        "on_hold": 0,
        "completed": 0,
        "delegated": 0,
    }

    recent_internal_tasks = []

    if can_view_internal_tasks:
        internal_task_query = (
            OperationsJobcardAssignment.query
            .filter(OperationsJobcardAssignment.assignment_type == "PRODUCTION")
            .filter(OperationsJobcardAssignment.assigned_to_type == "INTERNAL")
            .filter(OperationsJobcardAssignment.internal_user_id == current_user.id)
        )

        internal_task_rows = internal_task_query.all()

        internal_task_summary = {
            "total": len(internal_task_rows),
            "assigned": sum(1 for a in internal_task_rows if a.status == "Assigned"),
            "in_progress": sum(1 for a in internal_task_rows if a.status == "In Progress"),
            "on_hold": sum(1 for a in internal_task_rows if a.status == "On Hold"),
            "completed": sum(1 for a in internal_task_rows if a.status == "Completed"),
            "delegated": sum(1 for a in internal_task_rows if a.status == "Delegated"),
        }

        recent_internal_tasks = (
            internal_task_query
            .order_by(
                OperationsJobcardAssignment.assigned_at.desc(),
                OperationsJobcardAssignment.id.desc()
            )
            .limit(6)
            .all()
        )

    # -----------------------------
    # QC task summary
    # -----------------------------
    qc_task_summary = {
        "total": 0,
        "assigned": 0,
        "in_progress": 0,
        "on_hold": 0,
        "completed": 0,
        "delegated": 0,
    }

    recent_qc_tasks = []

    if can_view_internal_tasks:
        qc_task_query = (
            OperationsJobcardAssignment.query
            .filter(OperationsJobcardAssignment.assignment_type == "QC")
            .filter(OperationsJobcardAssignment.assigned_to_type == "INTERNAL")
            .filter(OperationsJobcardAssignment.internal_user_id == current_user.id)
        )

        qc_task_rows = qc_task_query.all()

        qc_task_summary = {
            "total": len(qc_task_rows),
            "assigned": sum(1 for a in qc_task_rows if a.status == "Assigned"),
            "in_progress": sum(1 for a in qc_task_rows if a.status == "In Progress"),
            "on_hold": sum(1 for a in qc_task_rows if a.status == "On Hold"),
            "completed": sum(1 for a in qc_task_rows if a.status == "Completed"),
            "delegated": sum(1 for a in qc_task_rows if a.status == "Delegated"),
        }

        recent_qc_tasks = (
            qc_task_query
            .order_by(
                OperationsJobcardAssignment.assigned_at.desc(),
                OperationsJobcardAssignment.id.desc()
            )
            .limit(6)
            .all()
        )

    # -----------------------------
    # Internal process task summary
    # -----------------------------
    process_task_summary = {
        "total": 0,
        "assigned": 0,
        "in_progress": 0,
        "on_hold": 0,
        "completed": 0,
        "delegated": 0,
        "mtpe": 0,
    }

    recent_process_tasks = []

    if can_view_internal_tasks:
        process_task_query = (
            OperationsJobcardProcessAssignment.query
            .filter(OperationsJobcardProcessAssignment.assigned_to_type == "INTERNAL")
            .filter(OperationsJobcardProcessAssignment.internal_user_id == current_user.id)
        )

        process_task_rows = process_task_query.all()

        mtpe_count = 0
        for row in process_task_rows:
            process_master = row.jobcard_process.process_master if row.jobcard_process else None
            process_code = (process_master.code or "").lower() if process_master else ""
            process_name = (process_master.name or "").lower() if process_master else ""

            if "mtpe" in process_code or "mtpe" in process_name:
                mtpe_count += 1

        process_task_summary = {
            "total": len(process_task_rows),
            "assigned": sum(1 for a in process_task_rows if a.status == "Assigned"),
            "in_progress": sum(1 for a in process_task_rows if a.status == "In Progress"),
            "on_hold": sum(1 for a in process_task_rows if a.status == "On Hold"),
            "completed": sum(1 for a in process_task_rows if a.status == "Completed"),
            "delegated": sum(1 for a in process_task_rows if a.status == "Delegated"),
            "mtpe": mtpe_count,
        }

        recent_process_tasks = (
            process_task_query
            .order_by(
                OperationsJobcardProcessAssignment.assigned_at.desc(),
                OperationsJobcardProcessAssignment.id.desc()
            )
            .limit(6)
            .all()
        )

    # -----------------------------
    # Approval summary
    # -----------------------------
    approval_summary = {
        "closure_pending": 0,
        "reopen_pending": 0,
    }

    if can_margin_approve:
        approval_summary["closure_pending"] = (
            OperationsJobcardClosureApprovalRequest.query
            .filter_by(status="Pending")
            .count()
        )

    if can_reopen_approve:
        approval_summary["reopen_pending"] = (
            OperationsJobcardReopenRequest.query
            .filter_by(status="Pending")
            .count()
        )

    quick_links = []

    if can_create_jobcard:
        quick_links.append({
            "label": "Jobcard Requests",
            "url": url_for("operations.jobcard_requests"),
            "icon": "bi-inbox",
            "text": "Create jobcards from assigned confirmed proposals",
            "color": "primary",
            "count": pending_jobcard_requests_count,
        })

    if can_view_jobcards:
        quick_links.append({
            "label": "My Jobcards",
            "url": url_for("operations.my_jobcards"),
            "icon": "bi-kanban",
            "text": "View jobcards assigned to you",
            "color": "success",
            "count": jobcard_summary["total"],
        })

    if can_view_all_jobcards:
        quick_links.append({
            "label": "All Jobcards",
            "url": url_for("operations.all_jobcards"),
            "icon": "bi-grid-3x3-gap",
            "text": "View all operations jobcards",
            "color": "dark",
            "count": jobcard_summary["total"],
        })

    if can_view_internal_tasks:
        quick_links.append({
            "label": "Workload Dashboard",
            "url": url_for("operations.workload_dashboard"),
            "icon": "bi-speedometer2",
            "text": "View your workload and team workload",
            "color": "primary",
            "count": internal_task_summary["total"] + process_task_summary["total"] + qc_task_summary["total"],
        })

        quick_links.append({
            "label": "Internal Tasks",
            "url": url_for("operations.internal_tasks"),
            "icon": "bi-person-workspace",
            "text": "Production and internal process tasks assigned to you",
            "color": "info",
            "count": internal_task_summary["total"] + process_task_summary["total"],
        })

        quick_links.append({
            "label": "QC Tasks",
            "url": url_for("operations.qc_tasks"),
            "icon": "bi-check2-square",
            "text": "Quality check tasks assigned to you",
            "color": "warning",
            "count": qc_task_summary["total"],
        })

    if can_manage_jobcard_fields:
        quick_links.append({
            "label": "Jobcard Field Master",
            "url": url_for("operations.jobcard_field_master"),
            "icon": "bi-ui-checks-grid",
            "text": "Manage jobcard service fields",
            "color": "secondary",
            "count": None,
        })

    if can_manage_checklist:
        quick_links.append({
            "label": "Checklist Master",
            "url": url_for("operations.checklist_master"),
            "icon": "bi-card-checklist",
            "text": "Manage service checklist questions",
            "color": "secondary",
            "count": None,
        })

    if can_manage_internal_process:
        quick_links.append({
            "label": "Internal Process Master",
            "url": url_for("operations.internal_process_master"),
            "icon": "bi-diagram-3",
            "text": "Manage MTPE and other internal process masters",
            "color": "secondary",
            "count": None,
        })

    if can_margin_approve:
        quick_links.append({
            "label": "Closure Approvals",
            "url": url_for("operations.jobcard_closure_approval_requests"),
            "icon": "bi-shield-check",
            "text": "Approve low-margin jobcard closure requests",
            "color": "danger",
            "count": approval_summary["closure_pending"],
        })

    if can_reopen_approve:
        quick_links.append({
            "label": "Reopen Approvals",
            "url": url_for("operations.jobcard_reopen_requests"),
            "icon": "bi-arrow-counterclockwise",
            "text": "Approve or reject jobcard reopen requests",
            "color": "danger",
            "count": approval_summary["reopen_pending"],
        })

    return render_template(
        "operations/dashboard.html",
        permissions=permissions,
        jobcard_summary=jobcard_summary,
        internal_task_summary=internal_task_summary,
        qc_task_summary=qc_task_summary,
        process_task_summary=process_task_summary,
        approval_summary=approval_summary,
        quick_links=quick_links,
        recent_jobcards=recent_jobcards,
        recent_jobcard_requests=recent_jobcard_requests,
        recent_internal_tasks=recent_internal_tasks,
        recent_qc_tasks=recent_qc_tasks,
        recent_process_tasks=recent_process_tasks,
        pending_jobcard_requests_count=pending_jobcard_requests_count,
    )

@operations_bp.route("/jobcards/<int:jobcard_id>/mtpe-details", methods=["POST"])
@login_required
@require_perm("operations.jobcard.view")
def update_jobcard_mtpe_details(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

    owner_id = jobcard.current_owner_id or jobcard.assigned_to_id

    if owner_id != current_user.id and not current_user.has_perm("operations.jobcard.view_all"):
        abort(403)

    if jobcard.status in ["Ready For Billing", "Closure Approval Pending"]:
        flash("MTPE details cannot be updated after jobcard closure or while closure approval is pending.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    latest_pi = None
    latest_invoice = None

    if jobcard.quote_id:
        latest_pi = (
            ProformaInvoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(ProformaInvoice.status != "Cancelled")
            .first()
        )

        latest_invoice = (
            Invoice.query
            .filter_by(quote_id=jobcard.quote_id)
            .filter(Invoice.status != "Cancelled")
            .first()
        )

    if latest_pi or latest_invoice:
        flash("MTPE details cannot be updated because PI or Invoice already exists.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    language_pairs = request.form.getlist("mtpe_language_pair[]")
    mt_names = request.form.getlist("mtpe_mt_name[]")
    accuracies = request.form.getlist("mtpe_accuracy[]")
    feedbacks = request.form.getlist("mtpe_feedback[]")
    remarks_list = request.form.getlist("mtpe_remarks[]")

    if not language_pairs:
        flash("Please add at least one MTPE detail row.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    added_count = 0

    for idx, language_pair in enumerate(language_pairs):
        mtpe_language_pair = _clean(language_pair)
        mtpe_mt_name = _clean(mt_names[idx] if idx < len(mt_names) else "")
        mtpe_accuracy = _parse_mtpe_accuracy(accuracies[idx] if idx < len(accuracies) else "")
        mtpe_feedback = _clean(feedbacks[idx] if idx < len(feedbacks) else "")
        mtpe_remarks = _clean(remarks_list[idx] if idx < len(remarks_list) else "")

        # Skip completely blank rows
        if not mtpe_language_pair and not mtpe_mt_name and not mtpe_feedback and not mtpe_remarks:
            continue

        if mtpe_accuracy == "INVALID":
            flash("MTPE accuracy must be a valid number between 0 and 100.", "danger")
            return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

        missing_fields = []

        if not mtpe_language_pair:
            missing_fields.append(f"Row {idx + 1}: Language Pair")

        if not mtpe_mt_name:
            missing_fields.append(f"Row {idx + 1}: MT Name")

        if mtpe_accuracy is None:
            missing_fields.append(f"Row {idx + 1}: Accuracy")

        if not mtpe_feedback:
            missing_fields.append(f"Row {idx + 1}: Post Editor Feedback")

        if not mtpe_remarks:
            missing_fields.append(f"Row {idx + 1}: Remarks")

        if missing_fields:
            flash("Please fill MTPE details: " + ", ".join(missing_fields), "danger")
            return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

        entry = OperationsJobcardMTPEEntry(
            jobcard_id=jobcard.id,
            language_pair=mtpe_language_pair,
            mt_name=mtpe_mt_name,
            accuracy=mtpe_accuracy,
            feedback=mtpe_feedback,
            remarks=mtpe_remarks,
            created_by_id=current_user.id,
            created_at=_now_ist()
        )

        db.session.add(entry)
        added_count += 1

    if added_count <= 0:
        flash("Please add at least one valid MTPE detail row.", "danger")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    jobcard.mtpe_required = True
    jobcard.mtpe_updated_by_id = current_user.id
    jobcard.mtpe_updated_at = _now_ist()

    # Optional: also keep latest MTPE detail on old columns for backward compatibility
    latest_entry_data = {
        "language_pair": _clean(language_pairs[-1]),
        "mt_name": _clean(mt_names[-1] if mt_names else ""),
        "accuracy": _parse_mtpe_accuracy(accuracies[-1] if accuracies else ""),
        "feedback": _clean(feedbacks[-1] if feedbacks else ""),
        "remarks": _clean(remarks_list[-1] if remarks_list else ""),
    }

    if latest_entry_data["accuracy"] != "INVALID":
        jobcard.mtpe_language_pair = latest_entry_data["language_pair"] or None
        jobcard.mtpe_mt_name = latest_entry_data["mt_name"] or None
        jobcard.mtpe_accuracy = latest_entry_data["accuracy"]
        jobcard.mtpe_feedback = latest_entry_data["feedback"] or None
        jobcard.mtpe_remarks = latest_entry_data["remarks"] or None

    db.session.commit()

    flash(f"{added_count} MTPE detail row(s) added successfully.", "success")
    return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))


@operations_bp.route("/assignments/<int:assignment_id>/sync-pms-status", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def sync_assignment_pms_status(assignment_id):
    assignment = OperationsJobcardAssignment.query.get_or_404(assignment_id)

    if (
        assignment.assignment_type != "PRODUCTION"
        or assignment.assigned_to_type != "VENDOR"
    ):
        flash("Only external vendor production assignments can be synced from PMS.", "danger")
        return redirect(url_for(
            "operations.view_jobcard",
            jobcard_id=assignment.jobcard_service.jobcard_id
        ))

    svc = assignment.jobcard_service
    jobcard = svc.jobcard

    if not _can_pm_manage_jobcard(jobcard):
        abort(403)

    try:
        pms_row, error = _fetch_pms_status_for_assignment(assignment)

        if error:
            flash(error, "warning")
            return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

        pms_status = pms_row.get("jobstatus")
        updated, message = _apply_pms_status_to_assignment(assignment, pms_status)

        if updated:
            db.session.commit()
            flash(message, "success")
        else:
            db.session.rollback()
            flash(message, "info")

    except Exception as e:
        db.session.rollback()
        flash(f"PMS status sync failed: {str(e)}", "danger")

    return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

@operations_bp.route("/jobcards/<int:jobcard_id>/sync-pms-status", methods=["POST"])
@login_required
@require_perm("operations.vendor.assign")
def sync_jobcard_pms_status(jobcard_id):
    jobcard = OperationsJobcard.query.get_or_404(jobcard_id)

    if not _can_pm_manage_jobcard(jobcard):
        abort(403)

    vendor_assignments = (
        OperationsJobcardAssignment.query
        .join(
            OperationsJobcardService,
            OperationsJobcardService.id == OperationsJobcardAssignment.jobcard_service_id
        )
        .filter(OperationsJobcardService.jobcard_id == jobcard.id)
        .filter(OperationsJobcardAssignment.assignment_type == "PRODUCTION")
        .filter(OperationsJobcardAssignment.assigned_to_type == "VENDOR")
        .filter(OperationsJobcardAssignment.status.notin_(["Completed", "Cancelled", "Replaced", "Rejected"]))
        .filter(OperationsJobcardAssignment.external_checklist_url.isnot(None))
        .all()
    )

    if not vendor_assignments:
        flash("No active external vendor assignments found for PMS status sync.", "warning")
        return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

    checked_count = 0
    completed_count = 0
    skipped_count = 0
    errors = []

    try:
        for assignment in vendor_assignments:
            checked_count += 1

            pms_row, error = _fetch_pms_status_for_assignment(assignment)

            if error:
                skipped_count += 1
                errors.append(f"Assignment #{assignment.id}: {error}")
                continue

            pms_status = pms_row.get("jobstatus")
            updated, message = _apply_pms_status_to_assignment(assignment, pms_status)

            if updated:
                completed_count += 1
            else:
                skipped_count += 1

        _refresh_jobcard_status(jobcard)
        db.session.commit()

        message = (
            f"PMS status sync completed. "
            f"Checked: {checked_count}, "
            f"Completed in Nexus: {completed_count}, "
            f"No change/skipped: {skipped_count}."
        )

        if errors:
            message += " Some rows had issues: " + " | ".join(errors[:5])

        flash(message, "success" if completed_count > 0 else "info")

    except Exception as e:
        db.session.rollback()
        flash(f"PMS jobcard status sync failed: {str(e)}", "danger")

    return redirect(url_for("operations.view_jobcard", jobcard_id=jobcard.id))

#-----------------------------
# Utility route for one-time PMS data fix - updating currency type on PMS assignments based on vendor currency
#-----------------------------

@operations_bp.route("/vendors/update-pms-assignment-currency", methods=["POST"])
@login_required
@require_perm("operations.vendor.manage")
def update_pms_assignment_currency():
    try:
        engine = get_pms_engine()

        rows = (
            OperationsJobcardAssignment.query
            .join(VendorMaster, VendorMaster.id == OperationsJobcardAssignment.vendor_id)
            .filter(OperationsJobcardAssignment.assigned_to_type == "VENDOR")
            .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced", "Rejected"]))
            .filter(OperationsJobcardAssignment.external_checklist_url.isnot(None))
            .all()
        )

        updated = 0

        sql = text("""
            UPDATE jobs
            SET CurrencyType = :currency_type,
                ModifiedOn = :modified_on
            WHERE LTRIM(RTRIM(ISNULL(CheckListLinks, ''))) = :checklist_url
              AND ISNULL(IsDeleted, 0) = 0
        """)

        with engine.begin() as conn:
            for a in rows:
                if not a.vendor or not a.vendor.currency:
                    continue

                result = conn.execute(sql, {
                    "currency_type": str(a.vendor.currency).strip().upper()[:50],
                    "modified_on": _now_ist().replace(microsecond=0).strftime("%Y-%m-%d %H:%M:%S"),
                    "checklist_url": str(a.external_checklist_url).strip(),
                })

                updated += result.rowcount or 0

        flash(f"PMS assignment currency updated for {updated} old job(s).", "success")

    except Exception as e:
        db.session.rollback()
        flash(f"PMS currency update failed: {str(e)}", "danger")

    return redirect(url_for("operations.workload_dashboard"))


# ===========================================================================
# Operations workload analytics, capacity and KPI preview
# ===========================================================================

def _ops_dashboard_date(value, fallback=None):
    value = (value or "").strip()
    if not value:
        return fallback
    try:
        return datetime.strptime(value, "%Y-%m-%d").date()
    except (TypeError, ValueError):
        return fallback


def _ops_dashboard_scope_user_ids():
    """Self for users, self + recursive reportees for TLs/managers."""
    return _operations_workload_visible_user_ids()


def _ops_dashboard_selected_user_ids(scope_user_ids):
    raw_user_id = request.args.get("user_id", type=int)
    if not raw_user_id:
        return scope_user_ids
    if scope_user_ids is not None and raw_user_id not in scope_user_ids:
        abort(403)
    return [raw_user_id]


def _ops_dashboard_filter_context():
    today = datetime.utcnow().date()
    default_start = today.replace(day=1)
    start_date = _ops_dashboard_date(request.args.get("start_date"), default_start)
    end_date = _ops_dashboard_date(request.args.get("end_date"), today)
    if start_date > end_date:
        start_date, end_date = end_date, start_date

    scope_user_ids = _ops_dashboard_scope_user_ids()
    return {
        "start_date": start_date,
        "end_date": end_date,
        "scope_user_ids": scope_user_ids,
        "selected_user_ids": _ops_dashboard_selected_user_ids(scope_user_ids),
        "department": (request.args.get("department") or "").strip() or None,
        "service_name": (request.args.get("service_name") or "").strip() or None,
        "assignment_type": (request.args.get("assignment_type") or "").strip().upper() or None,
        "assigned_to_type": (request.args.get("assigned_to_type") or "").strip().upper() or None,
        "selected_user_id": request.args.get("user_id", type=int),
    }


def _ops_filtered_options(scope_user_ids):
    options = workload_filter_options()
    if scope_user_ids is not None:
        allowed = set(scope_user_ids)
        options["users"] = [u for u in options.get("users", []) if u.id in allowed]
    return options


@operations_bp.route("/workload/analytics")
@login_required
@require_perm("operations.jobcard.view")
def workload_analytics_dashboard():
    filters = _ops_dashboard_filter_context()
    dashboard = build_workload_dashboard(
        start_date=filters["start_date"],
        end_date=filters["end_date"],
        user_ids=filters["selected_user_ids"],
        department=filters["department"],
        service_name=filters["service_name"],
        assignment_type=filters["assignment_type"],
        assigned_to_type=filters["assigned_to_type"],
    )
    return render_template(
        "operations/workload_analytics_dashboard.html",
        dashboard=dashboard,
        options=_ops_filtered_options(filters["scope_user_ids"]),
        filters=filters,
    )


@operations_bp.route("/capacity")
@login_required
@require_perm("operations.capacity.view")
def capacity_dashboard():
    filters = _ops_dashboard_filter_context()
    dashboard = build_capacity_dashboard(
        start_date=filters["start_date"],
        end_date=filters["end_date"],
        user_ids=filters["selected_user_ids"],
        department=filters["department"],
    )
    return render_template(
        "operations/capacity_dashboard.html",
        dashboard=dashboard,
        options=_ops_filtered_options(filters["scope_user_ids"]),
        filters=filters,
    )


@operations_bp.route("/kpi")
@login_required
@require_perm("operations.kpi.dashboard.view")
def operations_kpi_dashboard():
    filters = _ops_dashboard_filter_context()
    dashboard = build_operations_kpi_dashboard(
        start_date=filters["start_date"],
        end_date=filters["end_date"],
        user_ids=filters["selected_user_ids"],
        department=filters["department"],
    )
    return render_template(
        "operations/operations_kpi_dashboard.html",
        dashboard=dashboard,
        options=_ops_filtered_options(filters["scope_user_ids"]),
        filters=filters,
    )

@operations_bp.route("/kpi/master", methods=["GET", "POST"])
@login_required
@require_perm("operations.kpi.master.manage")
def operations_kpi_master():
    if request.method == "POST":
        profile_id = request.form.get("profile_id", type=int)
        profile = OperationsKpiProfile.query.get(profile_id) if profile_id else OperationsKpiProfile()

        applies_to = (request.form.get("applies_to") or "designation").strip().lower()
        designation_id = request.form.get("designation_id", type=int)
        user_id = request.form.get("user_id", type=int)
        is_default = applies_to == "default"

        if applies_to == "default":
            designation_id = None
            user_id = None
        elif applies_to == "user":
            designation_id = None
            if not user_id:
                flash("Select a user for the user-wise KPI profile.", "danger")
                return redirect(url_for("operations.operations_kpi_master"))
        elif applies_to == "designation":
            user_id = None
            if not designation_id:
                flash("Select a designation for the designation-wise KPI profile.", "danger")
                return redirect(url_for("operations.operations_kpi_master"))
        else:
            flash("Invalid KPI profile assignment type.", "danger")
            return redirect(url_for("operations.operations_kpi_master"))

        existing = OperationsKpiProfile.query.filter(
            OperationsKpiProfile.id != (profile.id or 0),
            OperationsKpiProfile.is_active.is_(True),
        )
        if is_default:
            existing = existing.filter(
                OperationsKpiProfile.is_default.is_(True),
                OperationsKpiProfile.designation_id.is_(None),
                OperationsKpiProfile.user_id.is_(None),
            )
        elif user_id:
            existing = existing.filter(OperationsKpiProfile.user_id == user_id)
        else:
            existing = existing.filter(
                OperationsKpiProfile.designation_id == designation_id,
                OperationsKpiProfile.user_id.is_(None),
            )

        if existing.first():
            flash("An active KPI profile already exists for this selection.", "danger")
            return redirect(url_for("operations.operations_kpi_master"))

        metric_fields = {
            "workload_achievement_weight": "Workload Achievement",
            "on_time_completion_weight": "On-time Completion",
            "capacity_utilisation_weight": "Capacity Utilisation",
            "rework_control_weight": "Rework Control",
            "qc_compliance_weight": "QC Compliance",
        }
        metric_values = {}
        try:
            for field_name, label in metric_fields.items():
                value = Decimal(request.form.get(field_name) or "0")
                if value < 0:
                    flash(f"{label} weight cannot be negative.", "danger")
                    return redirect(url_for("operations.operations_kpi_master"))
                metric_values[field_name] = value

            manager_individual = Decimal(request.form.get("manager_individual_weight") or "0")
            manager_team = Decimal(request.form.get("manager_team_weight") or "0")
        except Exception:
            flash("Enter valid numeric KPI weightages.", "danger")
            return redirect(url_for("operations.operations_kpi_master"))

        metric_total = sum(metric_values.values(), Decimal("0"))
        if metric_total != Decimal("100"):
            flash(f"KPI component weights must total 100%. Current total: {metric_total}%", "danger")
            return redirect(url_for("operations.operations_kpi_master"))

        if manager_individual + manager_team != Decimal("100"):
            flash("Manager Individual and Team weights must total 100%.", "danger")
            return redirect(url_for("operations.operations_kpi_master"))

        profile_name = (request.form.get("profile_name") or "").strip()
        if not profile_name:
            flash("Profile name is required.", "danger")
            return redirect(url_for("operations.operations_kpi_master"))

        profile.profile_name = profile_name
        profile.designation_id = designation_id
        profile.user_id = user_id
        profile.is_default = is_default
        profile.is_active = True
        profile.include_indirect_reportees = bool(request.form.get("include_indirect_reportees"))
        profile.manager_individual_weight = manager_individual
        profile.manager_team_weight = manager_team
        for field_name, value in metric_values.items():
            setattr(profile, field_name, value)

        if not profile.id:
            profile.created_by_id = current_user.id
            db.session.add(profile)
        profile.updated_by_id = current_user.id
        db.session.commit()
        flash("Operations KPI profile saved successfully.", "success")
        return redirect(url_for("operations.operations_kpi_master"))

    rows = OperationsKpiProfile.query.order_by(
        OperationsKpiProfile.is_default.desc(),
        OperationsKpiProfile.user_id.is_(None),
        OperationsKpiProfile.profile_name.asc(),
    ).all()
    designations = Designation.query.filter_by(is_active=True).order_by(Designation.name.asc()).all()
    users = _operations_user_query().order_by(User.name.asc()).all()
    edit_id = request.args.get("edit_id", type=int)
    edit_row = OperationsKpiProfile.query.get(edit_id) if edit_id else None
    return render_template(
        "operations/operations_kpi_master.html",
        rows=rows,
        designations=designations,
        users=users,
        edit_row=edit_row,
    )


@operations_bp.route("/kpi/master/<int:profile_id>/toggle", methods=["POST"])
@login_required
@require_perm("operations.kpi.master.manage")
def toggle_operations_kpi_profile(profile_id):
    profile = OperationsKpiProfile.query.get_or_404(profile_id)
    profile.is_active = not bool(profile.is_active)
    profile.updated_by_id = current_user.id
    db.session.commit()
    flash("Operations KPI profile status updated.", "success")
    return redirect(url_for("operations.operations_kpi_master"))



# =========================================================
# Project Management workload, capacity and KPI dashboards
# =========================================================
def _pm_parse_date(value, fallback):
    try:
        return datetime.strptime(value, "%Y-%m-%d").date() if value else fallback
    except (TypeError, ValueError):
        return fallback


def _pm_dashboard_filters():
    today = datetime.utcnow().date()
    start = _pm_parse_date(request.args.get("start_date"), today.replace(day=1))
    end = _pm_parse_date(request.args.get("end_date"), today)
    if start > end:
        start, end = end, start
    visible = visible_pm_user_ids(current_user)
    selected = request.args.get("user_id", type=int)
    if selected and selected not in visible:
        abort(403)
    return {
        "start_date": start, "end_date": end, "visible_ids": visible,
        "user_ids": [selected] if selected else visible,
        "selected_user_id": selected,
        "department": (request.args.get("department") or "").strip() or None,
        "service_name": (request.args.get("service_name") or "").strip() or None,
    }


def _pm_invalid_workload_corrections(user_ids):
    """Return legacy workload rows whose saved service does not match the jobcard service.

    The result is scoped to the same PM visibility used by the PM dashboards.  A
    Team Lead therefore sees self + reportees, a PM sees only self, and Admin
    sees all PMs.  Rows are grouped by jobcard so the PM gets one clear action
    instead of one warning per workload row.
    """
    if not user_ids:
        return []

    rows = (
        db.session.query(
            OperationsJobcardWorkloadEntry,
            OperationsJobcardAssignment,
            OperationsJobcardService,
            OperationsJobcard,
        )
        .join(
            OperationsJobcardAssignment,
            OperationsJobcardAssignment.id == OperationsJobcardWorkloadEntry.assignment_id,
        )
        .join(
            OperationsJobcardService,
            OperationsJobcardService.id == OperationsJobcardWorkloadEntry.jobcard_service_id,
        )
        .join(
            OperationsJobcard,
            OperationsJobcard.id == OperationsJobcardService.jobcard_id,
        )
        .filter(
            OperationsJobcardWorkloadEntry.is_active.is_(True),
            OperationsJobcardAssignment.replaced_at.is_(None),
            OperationsJobcardAssignment.assigned_to_type == "INTERNAL",
            OperationsJobcardAssignment.assignment_type.in_(["PRODUCTION", "QC"]),
            or_(
                OperationsJobcard.current_owner_id.in_(list(user_ids)),
                OperationsJobcard.assigned_to_id.in_(list(user_ids)),
            ),
            func.lower(func.trim(func.coalesce(OperationsJobcardWorkloadEntry.service_snapshot, "")))
            != func.lower(func.trim(func.coalesce(OperationsJobcardService.service_name, ""))),
        )
        .order_by(OperationsJobcard.created_at.desc(), OperationsJobcard.id.desc())
        .all()
    )

    grouped = {}
    for entry, assignment, service, jobcard in rows:
        item = grouped.setdefault(jobcard.id, {
            "jobcard_id": jobcard.id,
            "jobcard_code": jobcard.jobcard_code,
            "status": jobcard.status or "",
            "pm_name": (jobcard.current_owner.name if jobcard.current_owner else
                        (jobcard.assigned_to.name if jobcard.assigned_to else "PM")),
            "issues": [],
            "assignment_ids": set(),
        })
        if assignment.id not in item["assignment_ids"]:
            item["assignment_ids"].add(assignment.id)
            item["issues"].append({
                "assignment_id": assignment.id,
                "assignment_type": assignment.assignment_type or "",
                "assigned_to": assignment.internal_user.name if assignment.internal_user else "Internal User",
                "actual_service": service.service_name or "Service",
                "saved_service": entry.service_snapshot or "Unspecified",
            })

    result = []
    for item in grouped.values():
        item["issue_count"] = len(item["issues"])
        item.pop("assignment_ids", None)
        result.append(item)
    return result


@operations_bp.route("/pm/workload-analytics")
@login_required
@require_perm("operations.jobcard.view")
def pm_workload_analytics_dashboard():
    f = _pm_dashboard_filters()
    dashboard = build_pm_workload_dashboard(
        f["start_date"],
        f["end_date"],
        f["user_ids"],
        f["service_name"],
        f["department"],
    )
    workload_corrections = _pm_invalid_workload_corrections(f["user_ids"])
    return render_template(
        "operations/pm_workload_analytics.html",
        dashboard=dashboard,
        options=pm_filter_options(f["visible_ids"]),
        filters=f,
        workload_corrections=workload_corrections,
    )


@operations_bp.route("/pm/capacity")
@login_required
@require_perm("operations.capacity.view")
def pm_capacity_dashboard():
    f = _pm_dashboard_filters()
    dashboard = build_pm_capacity_dashboard(
        f["start_date"],
        f["end_date"],
        f["user_ids"],
        f["service_name"],
        f["department"],
    )
    return render_template(
        "operations/pm_capacity_dashboard.html",
        dashboard=dashboard,
        options=pm_filter_options(f["visible_ids"]),
        filters=f,
    )


@operations_bp.route("/pm/kpi")
@login_required
@require_perm("operations.kpi.dashboard.view")
def pm_kpi_dashboard():
    f = _pm_dashboard_filters()
    return render_template("operations/pm_kpi_dashboard.html",
        dashboard=build_pm_kpi_dashboard(f["start_date"], f["end_date"], f["user_ids"], f["service_name"], f["department"]),
        options=pm_filter_options(f["visible_ids"]), filters=f)


@operations_bp.route("/pm/master", methods=["GET", "POST"])
@login_required
@require_perm("operations.kpi.master.manage")
def pm_kpi_master():
    if request.method == "POST":
        action = request.form.get("action")
        if action == "service":
            row_id = request.form.get("row_id", type=int)
            row = (
                PmServiceProductivityStandard.query.get(row_id)
                if row_id
                else PmServiceProductivityStandard()
            )

            service_id = request.form.get("service_id", type=int)
            lead_service = LeadService.query.get(service_id) if service_id else None

            if not lead_service:
                flash("Select a valid service from Lead Service Master.", "danger")
                return redirect(url_for("operations.pm_kpi_master"))

            # Keep the foreign key and the readable snapshot name together.
            # KPI calculations can therefore track the master record while
            # historical rows remain readable even if the master is renamed.
            row.service_id = lead_service.id
            row.service_name = lead_service.name.strip()
            row.quantity_unit = (
                request.form.get("quantity_unit") or "Project"
            ).strip()

            try:
                row.quantity_per_project = Decimal(
                    request.form.get("quantity_per_project") or "1"
                )
                row.projects_per_day = Decimal(
                    request.form.get("projects_per_day") or "1"
                )
                row.minutes_per_project = Decimal(
                    request.form.get("minutes_per_project") or "480"
                )
            except Exception:
                flash("Enter valid numeric service productivity values.", "danger")
                return redirect(url_for("operations.pm_kpi_master"))

            if (
                row.quantity_per_project <= 0
                or row.projects_per_day <= 0
                or row.minutes_per_project <= 0
            ):
                flash(
                    "All productivity values must be greater than zero.",
                    "danger",
                )
                return redirect(url_for("operations.pm_kpi_master"))

            row.effective_from = _pm_parse_date(
                request.form.get("effective_from"),
                None,
            )
            row.effective_to = _pm_parse_date(
                request.form.get("effective_to"),
                None,
            )
            row.is_active = bool(request.form.get("is_active"))
            row.updated_by_id = current_user.id

            if not row.id:
                row.created_by_id = current_user.id
                db.session.add(row)

            db.session.commit()
            flash("PM service productivity standard saved.", "success")
            return redirect(url_for("operations.pm_kpi_master"))
        if action == "profile":
            row_id=request.form.get("row_id",type=int); row=PmKpiProfile.query.get(row_id) if row_id else PmKpiProfile()
            applies=(request.form.get("applies_to") or "default").lower(); row.user_id=request.form.get("user_id",type=int) if applies=="user" else None; row.designation_id=request.form.get("designation_id",type=int) if applies=="designation" else None; row.is_default=applies=="default"
            row.profile_name=(request.form.get("profile_name") or "").strip()
            fields=['projects_executed_weight','revenue_generated_weight','profit_margin_weight','on_time_delivery_weight','rework_control_weight','revenue_ctc_multiplier','minimum_profit_margin_pct','on_time_target_pct','maximum_rework_pct','ticket_first_deduction','ticket_second_deduction','tl_individual_weight','tl_team_weight']
            try:
                for field in fields: setattr(row,field,Decimal(request.form.get(field) or '0'))
                row.ticket_first_threshold=int(request.form.get('ticket_first_threshold') or 1); row.ticket_second_threshold=int(request.form.get('ticket_second_threshold') or 6)
            except Exception:
                flash("Enter valid KPI configuration values.","danger"); return redirect(url_for("operations.pm_kpi_master"))
            if sum([row.projects_executed_weight,row.revenue_generated_weight,row.profit_margin_weight,row.on_time_delivery_weight,row.rework_control_weight],Decimal('0')) != Decimal('100'):
                flash("PM KPI component weights must total 100%.","danger"); return redirect(url_for("operations.pm_kpi_master"))
            if row.tl_individual_weight + row.tl_team_weight != Decimal('100'):
                flash("TL individual and team weights must total 100%.","danger"); return redirect(url_for("operations.pm_kpi_master"))
            row.include_indirect_reportees=bool(request.form.get('include_indirect_reportees')); row.is_active=bool(request.form.get('is_active')); row.updated_by_id=current_user.id
            if not row.id: row.created_by_id=current_user.id; db.session.add(row)
            db.session.commit(); flash("PM KPI profile saved.","success"); return redirect(url_for("operations.pm_kpi_master"))
    service_edit = (
        PmServiceProductivityStandard.query.get(
            request.args.get("service_edit", type=int)
        )
        if request.args.get("service_edit", type=int)
        else None
    )
    profile_edit = (
        PmKpiProfile.query.get(request.args.get("profile_edit", type=int))
        if request.args.get("profile_edit", type=int)
        else None
    )

    lead_services = (
        LeadService.query
        .order_by(LeadService.sort_order, LeadService.name)
        .all()
    )

    # Existing standards created before service_id was introduced are mapped
    # in the edit form by a normalized name comparison. Saving the form then
    # persists the actual LeadService foreign key and canonical name.
    service_selected_id = None
    if service_edit:
        service_selected_id = service_edit.service_id
        if not service_selected_id:
            legacy_name = re.sub(
                r"[^a-z0-9]+",
                "",
                (service_edit.service_name or "").strip().lower(),
            )
            legacy_aliases = {
                "proofreading": "proofread",
                "proofreader": "proofread",
                "multilingualstaffing": "multilingualstaffing",
                "dataservices": "dataannotation",
                "dataservice": "dataannotation",
            }
            legacy_name = legacy_aliases.get(legacy_name, legacy_name)

            for lead_service in lead_services:
                candidate = re.sub(
                    r"[^a-z0-9]+",
                    "",
                    (lead_service.name or "").strip().lower(),
                )
                candidate = legacy_aliases.get(candidate, candidate)
                if candidate == legacy_name:
                    service_selected_id = lead_service.id
                    break

    return render_template(
        "operations/pm_kpi_master.html",
        service_rows=(
            PmServiceProductivityStandard.query
            .order_by(PmServiceProductivityStandard.service_name)
            .all()
        ),
        profile_rows=(
            PmKpiProfile.query
            .order_by(
                PmKpiProfile.is_default.desc(),
                PmKpiProfile.profile_name,
            )
            .all()
        ),
        service_edit=service_edit,
        service_selected_id=service_selected_id,
        lead_services=lead_services,
        profile_edit=profile_edit,
        users=pm_user_query().order_by(User.name).all(),
        designations=(
            Designation.query
            .filter_by(is_active=True)
            .order_by(Designation.name)
            .all()
        ),
    )


@operations_bp.route("/pm/master/service/<int:row_id>/toggle", methods=["POST"])
@login_required
@require_perm("operations.kpi.master.manage")
def toggle_pm_service_standard(row_id):
    row=PmServiceProductivityStandard.query.get_or_404(row_id); row.is_active=not row.is_active; row.updated_by_id=current_user.id; db.session.commit(); return redirect(url_for("operations.pm_kpi_master"))


@operations_bp.route("/pm/master/profile/<int:row_id>/toggle", methods=["POST"])
@login_required
@require_perm("operations.kpi.master.manage")
def toggle_pm_kpi_profile(row_id):
    row=PmKpiProfile.query.get_or_404(row_id); row.is_active=not row.is_active; row.updated_by_id=current_user.id; db.session.commit(); return redirect(url_for("operations.pm_kpi_master"))
