const sequelize = require("../config/dbconnection")
const Sequelize = require('sequelize')
const fs = require('node:fs');
const moment = require('moment')
const util = require('node:util');
const { pipeline } = require('node:stream');
const { empty } = require("../Helpers/Common");
const { log } = require("node:console");
const pump = util.promisify(pipeline);
const Request = require("../models/request")

let includeLabourInstallService = true;
let laborInstallWhereCondition = includeLabourInstallService ? ' ' : ' ${laborInstallWhereCondition} '
let makeAsTaskCondition = true ? ` AND rss.makeInstallCard = 1 ` : ` AND (rqs.project_category = 11 OR (rqs.project_category != 11 AND rss.makeAsTask = 1)) `
// let makeAsTaskCondition = true ? ` AND rss.makeAsTask = 1 ` : ` AND (rqs.project_category = 11 OR (rqs.project_category != 11 AND rss.makeAsTask = 1)) `

const Projects = sequelize.define('projects', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    project_uid: { type: Sequelize.STRING, allowNull: false },
    name: { type: Sequelize.STRING, allowNull: false },
    short_code: { type: Sequelize.STRING, allowNull: false },
    request_id: { type: Sequelize.INTEGER, allowNull: false },
    tags: { type: Sequelize.TEXT, allowNull: false },
    start_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    due_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    installation_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    installation_start_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    installation_end_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    project_category: { type: Sequelize.INTEGER, allowNull: false },
    project_type: { type: Sequelize.INTEGER, allowNull: false },
    website_url: { type: Sequelize.TEXT, allowNull: false },
    state_id: { type: Sequelize.INTEGER, allowNull: false },
    city: { type: Sequelize.STRING, allowNull: false },
    cost: { type: Sequelize.DECIMAL(14,2), allowNull: true },
    description: { type: Sequelize.TEXT, allowNull: false },
    approved_image: { type: Sequelize.TEXT, allowNull: false },
    community: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    cover_image: { type: Sequelize.TEXT, allowNull: true, defaultValue: null },
    added_by: { type: Sequelize.INTEGER, allowNull: false },
    reason: { type: Sequelize.TEXT, allowNull: false },
    timestamp: { type: Sequelize.INTEGER, allowNull: false },
    noServiceNoTask: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0 },
    status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
    installation_status: { type: Sequelize.INTEGER, allowNull: false },
    completion: { type: Sequelize.TINYINT, allowNull: true, defaultValue: 0 },
    jobcost: { type: Sequelize.TINYINT, allowNull: true, defaultValue: 0 },
    notifyJobcost:{ type: Sequelize.TEXT, allowNull: true, defaultValue:null},
    hold: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0 },
    card_order: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
    is_estimate_job: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0 },
    change_order: { type: Sequelize.TINYINT, allowNull: true, defaultValue: null },
    qb_transaction_count: { type: Sequelize.INTEGER, allowNull: true, defaultValue: 0 },
}, { timestamps: false })
const ProjectTypes = sequelize.define('project_type', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    name: { type: Sequelize.STRING, allowNull: false },
    quickBookId: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    added_by: { type: Sequelize.INTEGER, allowNull: false },
    timestamp: { type: Sequelize.INTEGER, allowNull: false },
    status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
}, { timestamps: false })
const ProjectCategory = sequelize.define('project_categories', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    name: { type: Sequelize.STRING, allowNull: false },
    added_by: { type: Sequelize.INTEGER, allowNull: false },
    timestamp: { type: Sequelize.INTEGER, allowNull: false },
    status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
}, { timestamps: false })
const NoChargeType = sequelize.define('no_charge_type', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    name: { type: Sequelize.STRING, allowNull: false },
    added_by: { type: Sequelize.INTEGER, allowNull: false },
    timestamp: { type: Sequelize.INTEGER, allowNull: false },
    status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
}, { timestamps: false,tableName:"no_charge_type" })
const ProjectMembers = sequelize.define('project_members', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    project_id: { type: Sequelize.INTEGER, allowNull: false },
    staff_id: { type: Sequelize.INTEGER, allowNull: false },
    partner_id: { type: Sequelize.INTEGER, allowNull: true },
    contact_id: { type: Sequelize.INTEGER, allowNull: true, },
    lead_id: { type: Sequelize.INTEGER, allowNull: true, },
    collaboration :{ type: Sequelize.INTEGER, allowNull: true, defaultValue: 0 }, // 0 for internal member, 1 for collaborator
}, { timestamps: false })

const JobsTabCount=sequelize.define('jobs_tab_count',{
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    user_id: {type: Sequelize.INTEGER, allowNull: false},
    hold_count: {type: Sequelize.INTEGER, allowNull: false, defaultValue: 0},
    pre_production_count: {type: Sequelize.INTEGER, allowNull: false ,defaultValue: 0},
    production_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
    installs_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
    pickup_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
    shipping_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
    completed_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
    hold_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
    pre_production_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
    production_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
    installs_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
    pickup_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
    shipping_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
    completed_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
    previous_hold_tab: {type: Sequelize.STRING(50), allowNull: true,defaultValue: null},
    status: { type: Sequelize.TINYINT, defaultValue: 1 },
    timestamp: { type: Sequelize.INTEGER, allowNull: true },
  },{timestamps:false ,tableName: 'jobs_tab_count'})

const EstimateProjects = sequelize.define('estimate_projects', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    project_uid: { type: Sequelize.STRING, allowNull: false },
    name: { type: Sequelize.STRING, allowNull: false },
    short_code: { type: Sequelize.STRING, allowNull: false },
    request_id: { type: Sequelize.INTEGER, allowNull: false },
    tags: { type: Sequelize.TEXT, allowNull: false },
    start_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    due_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    installation_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    installation_start_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    installation_end_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    project_category: { type: Sequelize.INTEGER, allowNull: false },
    project_type: { type: Sequelize.INTEGER, allowNull: false },
    website_url: { type: Sequelize.TEXT, allowNull: false },
    state_id: { type: Sequelize.INTEGER, allowNull: false },
    city: { type: Sequelize.STRING, allowNull: false },
    cost: { type: Sequelize.DECIMAL(14,2), allowNull: true },
    description: { type: Sequelize.TEXT, allowNull: false },
    approved_image: { type: Sequelize.TEXT, allowNull: false },
    community: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    cover_image: { type: Sequelize.TEXT, allowNull: true, defaultValue: null },
    added_by: { type: Sequelize.INTEGER, allowNull: false },
    reason: { type: Sequelize.TEXT, allowNull: false },
    timestamp: { type: Sequelize.INTEGER, allowNull: false },
    noServiceNoTask: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0 },
    status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
    installation_status: { type: Sequelize.INTEGER, allowNull: false },
    completion: { type: Sequelize.TINYINT, allowNull: true, defaultValue: 0 },
    jobcost: { type: Sequelize.TINYINT, allowNull: true, defaultValue: 0 },
    notifyJobcost:{ type: Sequelize.TEXT, allowNull: true, defaultValue:null},
    hold: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0 },
    card_order: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
    is_estimate_job: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0 },
}, { tableName: 'estimate_projects', timestamps: false })

const EstimateProjectMembers = sequelize.define('estimate_project_members', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    project_id: { type: Sequelize.INTEGER, allowNull: false },
    staff_id: { type: Sequelize.INTEGER, allowNull: false },
    partner_id: { type: Sequelize.INTEGER, allowNull: true },
    contact_id: { type: Sequelize.INTEGER, allowNull: true, },
    lead_id: { type: Sequelize.INTEGER, allowNull: true, },
}, { tableName: 'estimate_project_members', timestamps: false })

const JobCost = require('../models/jobCost')

const parseDecimalFields = (order) => {
    order.cost = order.cost ? parseFloat(order.cost) : null;
    return order;
}

const getProjectById = async (id) => {
    try {
        let query = await sequelize.query(`SELECT p.*,pc.name AS job_category_name,
            r.syncWithQuickbooks, concat(u.first_name, ' ', u.last_name) as authorized_by,
             coalesce(pm.count, 0) as member_count, coalesce(pf.count, 0) as attachment_count,
              coalesce(pt.completed_count, 0) as completed_task_count, 
              coalesce(pt.pending_count, 0) as pending_task_count,c_ord.customer_id,
              r.isReview,r.installation_acceptance,r.is_split_order,r.facility_type,
              r.for_parent_facility,r.origin_facility_request_id,
              r.origin_facility_id,cop.product_notes,cop.product_id,
            coalesce(pt.all_task_completed, 0) AS allTaskCompleted,
            rs.delivery_type_id AS service_delivery_id 
              FROM projects p`
            + ` LEFT JOIN users u ON p.added_by=u.id `
            + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
             + ` LEFT JOIN requests r ON r.id=p.request_id `
             + ` LEFT JOIN request_services rs ON rs.request_id = r.id AND rs.makeAsTask = 0 AND rs.makeInstallCard = 1`
            + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
            + ` LEFT JOIN (select count(ID) as count, project_id from project_files group by project_id) pf ON pf.project_id=p.id `
            // + ` LEFT JOIN (select sum(case when status=3 then 1 else 0 end) as completed_count, sum(case when status!=3 then 1 else 0 end) as pending_count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
            + `  LEFT JOIN (SELECT 
                      COUNT(*) AS task_count, 
                      SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) AS completed_count, 
                      SUM(CASE WHEN status != 3 THEN 1 ELSE 0 END) AS pending_count, 
                      CASE 
                          WHEN COUNT(*) = 0 THEN 1  -- If no tasks, set all_task_completed to 1
                          WHEN SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) = COUNT(*) THEN 1  -- If all tasks are completed
                          ELSE 0  -- Otherwise, set all_task_completed to 0
                      END AS all_task_completed, 
                      project_id 
               FROM project_tasks 
               WHERE status != 0 
               GROUP BY project_id) pt ON pt.project_id = p.id`
            + ` LEFT JOIN customer_orders c_ord on c_ord.request_id = p.request_id `
            + ` LEFT JOIN customer_order_products cop on cop.order_id = p.request_id `
            + ` WHERE p.id = ${id}`

        );

        // if (query[0].length === 1) {
            if (query[0].length > 0) {
            // return query[0][0];
            let data = query[0][0];
            // return data?.map(record => parseDecimalFields(record));
            return parseDecimalFields(data);
        } else {
            return false;
        }

    } catch (error) {
        console.log("Server error1111" + error);
        throw new Error("Server error");
    }
}

const getProjectByRequestId = async (requestId) => {
    try {
      const [results] = await sequelize.query(`
        SELECT id 
        FROM projects 
        WHERE request_id = :requestId 
          AND status != 0 
        LIMIT 1
      `, {
        replacements: { requestId },
        type: sequelize.QueryTypes.SELECT
      });
  
      return results?.id || null;
  
    } catch (error) {
      console.error('Error fetching project by requestId:', error);
      throw new Error('Server error');
    }
  };
  

const getAllProjects = async (hasPermission, all = false, userType, userId, where = [],sort,fromDate,toDate,dueData, filterProjectType, currentTab, page = 1, limit = false, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = [], splitOrder = false) => {
    try {
        let estimateCondition = ' AND p.is_estimate_job=0'

        const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
        const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
        const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
        let limitCondition = ''
        if (limit){
            limitCondition = ` LIMIT ${limit} OFFSET ${(page - 1) * limit}`
        }
        let dateCondition = '';
        if (fromTimestamp && toTimestamp) {
          dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
        } else if (fromTimestamp) {
          dateCondition = ` p.installation_date >= ${fromTimestamp}`;
        } else if (toTimestamp) {
          dateCondition = ` p.installation_date <= ${toTimestamp}`;
        }
        // else if (dueTimestamp) {
        //     dateCondition = ` p.installation_date <= ${dueTimestamp}`;
        // }

        let createdAt = ''
        if (dueTimestamp) {
            // By Due: always order by installation date ascending
            createdAt = `ORDER BY p.installation_date ASC`
        } else {
            // Align semantics with OfficialRequest:
            // - "Newest": by creation (id DESC)
            // - "Oldest": by creation (id ASC)
            // - "Recently Updated": by last change (timestamp DESC)
            // - "Custom Order": by card_order
            if (sort === 'new') {
                createdAt = `ORDER BY p.id DESC `
            } else if (sort === 'old') {
                createdAt = `ORDER BY p.id ASC `
            } else if (sort === 'last_updated') {
                createdAt = `ORDER BY p.timestamp DESC`
            } else if (sort === 'custom_order') {
                createdAt = `ORDER BY p.card_order ASC`
            } else {
                // Default to newest if sort is unknown
                createdAt = `ORDER BY p.id DESC `
            }
        }

        let whereCondition;
        let query = ''
        if (all) {
            // For Production tab, allow status 2; for other tabs, exclude status 2
            if (currentTab === 'Production') {
                whereCondition = ` (p.status != 0 AND p.status != 1 AND p.status != 3 AND p.status != 6)`;
            }else if(currentTab === "Pre-Production") {
                whereCondition = ` (p.status = 1 )`;
            } else if(currentTab && currentTab === 'ALL') {
                whereCondition = ` p.status != 0`;
            } else if(currentTab && currentTab === 'Rejected') {
                whereCondition = ` p.status = 9`;
            } else{
                whereCondition = ` p.status != 999`;
            }
        } else {
            whereCondition = ` p.status = 1`;
        }
        if (!empty(where)) {

        }
        if (splitOrder === 1) {
            whereCondition += whereCondition ? ` AND req.is_split_order = 1 AND req.for_parent_facility != 2` : ` req.is_split_order = 1 AND req.for_parent_facility != 2`;
        } else if (splitOrder === 2) {
            whereCondition += whereCondition ? ` AND req.is_split_order = 0` : ` req.is_split_order = 0`;
        }

        let projectTypeCondition = '';
if (filterProjectType === 1) {
  projectTypeCondition = ` AND req.project_type = 1`;
} else if (filterProjectType === 2) {
  projectTypeCondition = ` AND req.project_type = 2`;
} else if (filterProjectType === 'NULL') {
  projectTypeCondition = ` AND req.project_type IS NULL`;
} else if (filterProjectType === 'ALL') {
  projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
} else {
  projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
}

        // Add job class filtering condition
        let jobClassCondition = '';
        if (jobClassFilter && jobClassFilter.length > 0) {
            const jobClassIds = jobClassFilter.join(',');
            jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
        }

        // Add job types filtering condition
        let jobTypesCondition = '';
        if (jobTypesFilter && jobTypesFilter.length > 0) {
            const jobTypesIds = jobTypesFilter.join(',');
            jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
        }

        // Add client filtering condition
        let clientCondition = '';
        if (clientFilter && clientFilter.length > 0) {
            const clientIds = clientFilter.join(',');
            clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
        }

        // Add user filtering condition
        let userCondition = '';
        if (userFilter && userFilter.length > 0) {
            const userIds = userFilter.join(',');
            userCondition = ` AND EXISTS (
                SELECT 1 FROM project_members pm 
                WHERE pm.project_id = p.id 
                AND pm.staff_id IN (${userIds})
            )`;
        }

        // Add project filtering condition
        let projectCondition = '';
        if (projectFilter && projectFilter.length > 0) {
            // Check if 'other' is included in the filter
            const hasOther = projectFilter.includes('other');
            const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
            if (hasOther && numericIds.length > 0) {
                // Include both specific communities and null/other communities
                projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
            } else if (hasOther) {
                // Only 'other' is selected
                projectCondition = ` AND p.community IS NULL`;
            } else {
                // Only specific communities are selected
                projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
            }
        }

        let departmentCondition = '';
        if (departmentFilter && departmentFilter.length > 0) {
            const departmentIds = departmentFilter.join(',');
          
        //     departmentCondition = `
        //     AND EXISTS (
        //       SELECT 1
        //       FROM project_members pm_dep
        //       INNER JOIN staff_members sm_dep ON pm_dep.staff_id = sm_dep.id
        //       INNER JOIN users u_dep ON sm_dep.user_id = u_dep.id
        //       WHERE pm_dep.project_id = p.id
        //       AND u_dep.department_id IN (${departmentIds})
        //     )
        //   `;

                        departmentCondition = `
            AND EXISTS (
                SELECT 1
                FROM project_members pm_dep
                INNER JOIN staff_members sm_dep 
                ON pm_dep.staff_id = sm_dep.id
                INNER JOIN services srv 
                ON FIND_IN_SET(srv.id, sm_dep.services)
                WHERE pm_dep.project_id = p.id
                AND srv.department_id IN (${departmentIds})
            )
            `;

           

          }

        // Add search condition
        let searchCondition = '';
        if (search && search.trim() !== '') {
            searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR req.doc_number LIKE '%${search}%' OR req.est_doc_number LIKE '%${search}%')`;
        }

        // Add currentTab filtering condition
        let tabCondition = '';
        if (currentTab === 'Hold') {
            tabCondition = ` p.hold = 1`;
        } else if (currentTab === 'Pre-Production') {
            tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0`;
        } else if (currentTab === 'Production') {
            tabCondition = ` p.hold = 0 AND p.status = 2`;
        }
        else if (currentTab === 'Rejected') {
            tabCondition = ` p.status = 9`;
        } else if (currentTab === 'Change Order') {
            tabCondition = ` p.hold = 0 AND p.change_order = 1`;
        }
        
        // Exclude change orders from all other tabs (including ALL)
        let changeOrderExclusion = '';
        if (currentTab !== 'Change Order' && currentTab !== 'Hold' && currentTab !== 'ALL') {
            changeOrderExclusion = ` (p.change_order IS NULL OR p.change_order = 0)`;
        }
        // else if (currentTab === 'Installs') {
        //     tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND req.status != 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
        // } else if (currentTab === 'Pickup') {
        //     tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
        // } else if (currentTab === 'Shipping') {
        //     tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
        // } else if (currentTab === 'Completed') {
        //     tabCondition = ` ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.isReview != 2 AND req.installation_acceptance = 1) OR (p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND req.isReview != 2 AND req.installation_acceptance = 1) OR req.status = 10`;
        // } else if (currentTab === 'T & M Review') {
        //     tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.installation_acceptance != 1 AND p.status = 3 AND p.project_category = 12 AND req.isReview = 2`;
        // } else if (currentTab === 'Cost Card') {
        //     tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.installation_acceptance != 1 AND p.status = 3 AND p.project_category != 12`;
        // }

        if (userType === 1 || userType == 8) {
            query = await sequelize.query(
                ` SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name,'project' As projectType,req.isFromDesignOrder,req.is_split_order,req.for_parent_facility,req.origin_facility_id, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count, com.name AS community_name,c_ord.customer_phone,c_ord.customer_name,c_ord.customer_id,c_ord.total,req.doc_number,req.est_doc_number,req.installation_acceptance,req.syncWithQuickbooks,req.design_order_id,COALESCE(p_dopm.name, CONCAT(s_dopm.first_name, ' ', COALESCE(s_dopm.last_name, ''))) AS design_order_member_name,COALESCE(s_dopm.first_name, '') AS design_order_member_first_name,COALESCE(s_dopm.last_name, '') AS design_order_member_last_name,COALESCE(u_dopm.email, u2_dopm.email, '') AS design_order_member_email,COALESCE(p_dopm.phone, s_dopm.phone, '') AS design_order_member_phone,GROUP_CONCAT(DISTINCT cop.product_name SEPARATOR ', ') AS product_name,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE ${whereCondition} ${dateCondition!= '' ? ' AND '+dateCondition : ''}  ${departmentCondition != '' ? departmentCondition : ''} ${projectTypeCondition} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} ${limitCondition} `
            );
        }
        else if (userType === 3) {
            query = await sequelize.query(
                ` SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name,req.isFromDesignOrder,req.is_split_order,req.for_parent_facility,req.origin_facility_id, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count, com.name AS community_name,c_ord.customer_phone, c_ord.customer_name,c_ord.customer_id,c_ord.total,req.doc_number,req.est_doc_number,req.installation_acceptance,req.syncWithQuickbooks,req.design_order_id,COALESCE(p_dopm.name, CONCAT(s_dopm.first_name, ' ', COALESCE(s_dopm.last_name, ''))) AS design_order_member_name,COALESCE(s_dopm.first_name, '') AS design_order_member_first_name,COALESCE(s_dopm.last_name, '') AS design_order_member_last_name,COALESCE(u_dopm.email, u2_dopm.email, '') AS design_order_member_email,COALESCE(p_dopm.phone, s_dopm.phone, '') AS design_order_member_phone,GROUP_CONCAT(DISTINCT cop.product_name SEPARATOR ', ') AS product_name,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` left join request_partners rp on rp.request_id=p.request_id`
                + ` left join partners pr on pr.id=rp.partner_id`
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE pr.user_id=${userId} ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} ${limitCondition} `
            );
        }
        else {
            query = await sequelize.query(`SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name,req.isFromDesignOrder,req.is_split_order,req.for_parent_facility,req.origin_facility_id, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count, com.name AS community_name,c_ord.customer_phone, c_ord.customer_name,c_ord.customer_id,c_ord.total,req.doc_number,req.est_doc_number,req.installation_acceptance,req.syncWithQuickbooks,req.design_order_id,COALESCE(p_dopm.name, CONCAT(s_dopm.first_name, ' ', COALESCE(s_dopm.last_name, ''))) AS design_order_member_name,COALESCE(s_dopm.first_name, '') AS design_order_member_first_name,COALESCE(s_dopm.last_name, '') AS design_order_member_last_name,COALESCE(u_dopm.email, u2_dopm.email, '') AS design_order_member_email,COALESCE(p_dopm.phone, s_dopm.phone, '') AS design_order_member_phone,GROUP_CONCAT(DISTINCT cop.product_name SEPARATOR ', ') AS product_name,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p `
                + ` LEFT JOIN staff_members s1 ON s1.id=p.project_lead  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN users u1 ON s1.user_id=u1.id `
                + ` LEFT JOIN staff_members s2 ON s2.id=p.default_assignee `
                + ` LEFT JOIN users u2 ON s2.user_id=u2.id `
                + ` LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id from project_members pm left join partners p on p.id=pm.partner_id left join users u on p.user_id=u.id left join staff_members s on s.id=pm.staff_id left join users u2 on s.user_id=u2.id) pmm ON pmm.project_id=p.id and pmm.user_id=${userId} `
                + ` LEFT JOIN users u ON p.added_by=u.id `
                + ` LEFT JOIN installations i ON p.id = i.project_id `
                + ` LEFT JOIN driver dr ON i.driver_id = dr.id `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id  `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` left join users ura on ura.id = req.id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) ins ON ins.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE (
                    u1.id = ${userId}
                    OR u2.id = ${userId}
                    OR pmm.user_id = ${userId}
                    OR (req.added_by = ${userId} AND ura.user_type <> 3)
                    OR FIND_IN_SET(${userId}, i.team_id)
                    OR FIND_IN_SET(${userId}, dr.user_id)
                    OR u_dopm.id = ${userId}
                    OR u2_dopm.id = ${userId}
                )
                ${dateCondition ? ' AND ' + dateCondition : ''}
                ${projectTypeCondition}
                ${departmentCondition ? ' ' + departmentCondition : ''}
                ${jobClassCondition}
                ${jobTypesCondition}
                ${clientCondition}
                ${userCondition}
                ${estimateCondition}
                ${projectCondition}
                ${tabCondition ? ' AND ' + tabCondition : ''}
                ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''}
                ${searchCondition ? ' AND ' + searchCondition : ''}
                GROUP BY p.id
                ${createdAt}
                ${limitCondition} `
                //  + ` WHERE (u1.id = ${userId} or u2.id = ${userId} or pmm.user_id =${userId} OR (req.added_by = ${userId} AND ura.user_type <> 3) OR FIND_IN_SET(${userId}, i.team_id) OR FIND_IN_SET(${userId}, dr.user_id) OR u_dopm.id = ${userId} OR u2_dopm.id = ${userId}) ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} ${limitCondition} `);
             );
             }
        let data;
        const isAdminUser = userType == 1 || userType == 8;
        const applyApprovedDesignFields = async (item) => {
            const image = await Request.FetchAllApprovedDesigns(item.request_id);
            const coverImage = image?.find((imageItem) => imageItem?.file_type?.startsWith('image/') || imageItem?.file_type === 'img');
            const firstItemWithLocationIds = image?.find((imageItem) => imageItem?.location_ids !== null);
            const approvedPdf = image?.[0];

            item.cover_image = coverImage?.name || "";
            item.approved_pdf = firstItemWithLocationIds?.name || approvedPdf?.name || "";

            return item;
        };

        const enrichProjectForAdmin = async (item) => {
            const [selectedMaterials, payout, services] = await Promise.all([
                JobCost.fetchAllJobCostProjectId(item.id),
                JobCost.fetchAllPayOutByProjectId(item.id, userId),
                Request.getAllServiceByRequest(item.request_id),
            ]);

            const price = selectedMaterials
                ?.filter((curr) => curr.taken === 1)
                ?.reduce((total, currentItem) => total + currentItem.total, 0) || 0;
            const serviceExpense = services
                ?.filter((curr) => curr.taken === 1)
                ?.reduce((total, currentItem) => total + (currentItem.qty * currentItem.originalCost), 0) || 0;
            const payoutPrice = (payout || []).reduce((total, currentItem) => total + currentItem.amount, 0);
            const expense = price + payoutPrice + Math.max(0, (serviceExpense - payoutPrice));
            const parsedCost = parseFloat(item.cost) || 0;

            if (Number(item.status) === 1 || parsedCost <= 0) {
                item.progressValue = 0;
            } else {
                item.progressValue = (expense / parsedCost) * 100;
                if (item.progressValue > 100) {
                    item.progressValue = 100;
                }
            }

            return applyApprovedDesignFields(item);
        };

        if (query.length > 0) {
            data = query[0];
            if (isAdminUser) {
                const results = await Promise.all(data.map(enrichProjectForAdmin));
                return results.map(record => parseDecimalFields(record));
            } else {
                const results = await Promise.all(data.map(applyApprovedDesignFields));
                return results?.map(record => parseDecimalFields(record));
            }


        } else {
            return false;
        }
    } catch (error) {
        console.log(error);
        throw new Error("Server error");
    }
}
// const getAllProjects = async (hasPermission, all = false, userType, userId, where = [],sort,fromDate,toDate,dueData, filterProjectType, currentTab, page = 1, limit = false, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = [], splitOrder = false) => {
//     try {
//         let estimateCondition = ' AND p.is_estimate_job=0'

//         const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
//         const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
//         const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
// console.log('toTimestamp',toTimestamp)
//         let limitCondition = ''
//         if (limit){
//             limitCondition = ` LIMIT ${limit} OFFSET ${(page - 1) * limit}`
//         }
//         let dateCondition = '';
//         if (fromTimestamp && toTimestamp) {
//           dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
//         } else if (fromTimestamp) {
//           dateCondition = ` p.installation_date >= ${fromTimestamp}`;
//         } else if (toTimestamp) {
//           dateCondition = ` p.installation_date <= ${toTimestamp}`;
//         }
//         // else if (dueTimestamp) {
//         //     dateCondition = ` p.installation_date <= ${dueTimestamp}`;
//         // }

//         let createdAt = ''
//         if (dueTimestamp) {
//             // By Due: always order by installation date ascending
//             createdAt = `ORDER BY p.installation_date ASC`
//         } else {
//             // Align semantics with OfficialRequest:
//             // - "Newest": by creation (id DESC)
//             // - "Oldest": by creation (id ASC)
//             // - "Recently Updated": by last change (timestamp DESC)
//             // - "Custom Order": by card_order
//             if (sort === 'new') {
//                 createdAt = `ORDER BY p.id DESC `
//             } else if (sort === 'old') {
//                 createdAt = `ORDER BY p.id ASC `
//             } else if (sort === 'last_updated') {
//                 createdAt = `ORDER BY p.timestamp DESC`
//             } else if (sort === 'custom_order') {
//                 createdAt = `ORDER BY p.card_order ASC`
//             } else {
//                 // Default to newest if sort is unknown
//                 createdAt = `ORDER BY p.id DESC `
//             }
//         }

//         let whereCondition;
//         let query = ''
//         if (all) {
//             // For Production tab, allow status 2; for other tabs, exclude status 2
//             if (currentTab === 'Production') {
//                 whereCondition = ` (p.status != 0 AND p.status != 1 AND p.status != 3 AND p.status != 6)`;
//             }else if(currentTab === "Pre-Production") {
//                 whereCondition = ` (p.status = 1 )`;
//             } else if(currentTab && currentTab === 'ALL') {
//                 whereCondition = ` p.status != 0`;
//             } else if(currentTab && currentTab === 'Rejected') {
//                 whereCondition = ` p.status = 9`;
//             } else{
//                 whereCondition = ` p.status != 999`;
//             }
//         } else {
//             whereCondition = ` p.status = 1`;
//         }
//         if (!empty(where)) {

//         }
//         if (splitOrder === 1) {
//             whereCondition += whereCondition ? ` AND req.is_split_order = 1 AND req.for_parent_facility != 2` : ` req.is_split_order = 1 AND req.for_parent_facility != 2`;
//         } else if (splitOrder === 2) {
//             whereCondition += whereCondition ? ` AND req.is_split_order = 0` : ` req.is_split_order = 0`;
//         }

//         let projectTypeCondition = '';
// if (filterProjectType === 1) {
//   projectTypeCondition = ` AND req.project_type = 1`;
// } else if (filterProjectType === 2) {
//   projectTypeCondition = ` AND req.project_type = 2`;
// } else if (filterProjectType === 'NULL') {
//   projectTypeCondition = ` AND req.project_type IS NULL`;
// } else if (filterProjectType === 'ALL') {
//   projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
// } else {
//   projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
// }

//         // Add job class filtering condition
//         let jobClassCondition = '';
//         if (jobClassFilter && jobClassFilter.length > 0) {
//             const jobClassIds = jobClassFilter.join(',');
//             jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
//         }

//         // Add job types filtering condition
//         let jobTypesCondition = '';
//         if (jobTypesFilter && jobTypesFilter.length > 0) {
//             const jobTypesIds = jobTypesFilter.join(',');
//             jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
//         }

//         // Add client filtering condition
//         let clientCondition = '';
//         if (clientFilter && clientFilter.length > 0) {
//             const clientIds = clientFilter.join(',');
//             clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
//         }

//         // Add user filtering condition
//         let userCondition = '';
//         if (userFilter && userFilter.length > 0) {
//             const userIds = userFilter.join(',');
//             userCondition = ` AND EXISTS (
//                 SELECT 1 FROM project_members pm 
//                 WHERE pm.project_id = p.id 
//                 AND pm.staff_id IN (${userIds})
//             )`;
//         }

//         // Add project filtering condition
//         let projectCondition = '';
//         if (projectFilter && projectFilter.length > 0) {
//             // Check if 'other' is included in the filter
//             const hasOther = projectFilter.includes('other');
//             const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
//             if (hasOther && numericIds.length > 0) {
//                 // Include both specific communities and null/other communities
//                 projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
//             } else if (hasOther) {
//                 // Only 'other' is selected
//                 projectCondition = ` AND p.community IS NULL`;
//             } else {
//                 // Only specific communities are selected
//                 projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
//             }
//         }

//         let departmentCondition = '';
//         if (departmentFilter && departmentFilter.length > 0) {
//             const departmentIds = departmentFilter.join(',');
          
//         //     departmentCondition = `
//         //     AND EXISTS (
//         //       SELECT 1
//         //       FROM project_members pm_dep
//         //       INNER JOIN staff_members sm_dep ON pm_dep.staff_id = sm_dep.id
//         //       INNER JOIN users u_dep ON sm_dep.user_id = u_dep.id
//         //       WHERE pm_dep.project_id = p.id
//         //       AND u_dep.department_id IN (${departmentIds})
//         //     )
//         //   `;

//                         departmentCondition = `
//             AND EXISTS (
//                 SELECT 1
//                 FROM project_members pm_dep
//                 INNER JOIN staff_members sm_dep 
//                 ON pm_dep.staff_id = sm_dep.id
//                 INNER JOIN services srv 
//                 ON FIND_IN_SET(srv.id, sm_dep.services)
//                 WHERE pm_dep.project_id = p.id
//                 AND srv.department_id IN (${departmentIds})
//             )
//             `;

           

//           }

//         // Add search condition
//         let searchCondition = '';
//         if (search && search.trim() !== '') {
//             searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR req.doc_number LIKE '%${search}%' OR req.est_doc_number LIKE '%${search}%')`;
//         }

//         // Add currentTab filtering condition
//         let tabCondition = '';
//         if (currentTab === 'Hold') {
//             tabCondition = ` p.hold = 1`;
//         } else if (currentTab === 'Pre-Production') {
//             tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0`;
//         } else if (currentTab === 'Production') {
//             tabCondition = ` p.hold = 0 AND p.status = 2`;
//         }
//         else if (currentTab === 'Rejected') {
//             tabCondition = ` p.status = 9`;
//         } else if (currentTab === 'Change Order') {
//             tabCondition = ` p.hold = 0 AND p.change_order = 1`;
//         }
        
//         // Exclude change orders from all other tabs (including ALL)
//         let changeOrderExclusion = '';
//         if (currentTab !== 'Change Order' && currentTab !== 'Hold' && currentTab !== 'ALL') {
//             changeOrderExclusion = ` (p.change_order IS NULL OR p.change_order = 0)`;
//         }
//         // else if (currentTab === 'Installs') {
//         //     tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND req.status != 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
//         // } else if (currentTab === 'Pickup') {
//         //     tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
//         // } else if (currentTab === 'Shipping') {
//         //     tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
//         // } else if (currentTab === 'Completed') {
//         //     tabCondition = ` ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.isReview != 2 AND req.installation_acceptance = 1) OR (p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND req.isReview != 2 AND req.installation_acceptance = 1) OR req.status = 10`;
//         // } else if (currentTab === 'T & M Review') {
//         //     tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.installation_acceptance != 1 AND p.status = 3 AND p.project_category = 12 AND req.isReview = 2`;
//         // } else if (currentTab === 'Cost Card') {
//         //     tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.installation_acceptance != 1 AND p.status = 3 AND p.project_category != 12`;
//         // }

//         if (userType === 1 || userType == 8) {
//             query = await sequelize.query(
//                 ` SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name,'project' As projectType,req.isFromDesignOrder,req.is_split_order,req.for_parent_facility,req.origin_facility_id, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count, com.name AS community_name,c_ord.customer_phone,c_ord.customer_name,c_ord.customer_id,c_ord.total,req.doc_number,req.est_doc_number,req.installation_acceptance,req.syncWithQuickbooks,req.design_order_id,COALESCE(p_dopm.name, CONCAT(s_dopm.first_name, ' ', COALESCE(s_dopm.last_name, ''))) AS design_order_member_name,COALESCE(s_dopm.first_name, '') AS design_order_member_first_name,COALESCE(s_dopm.last_name, '') AS design_order_member_last_name,COALESCE(u_dopm.email, u2_dopm.email, '') AS design_order_member_email,COALESCE(p_dopm.phone, s_dopm.phone, '') AS design_order_member_phone,GROUP_CONCAT(DISTINCT cop.product_name SEPARATOR ', ') AS product_name,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p `
//                 + ` LEFT JOIN users u ON p.added_by=u.id  `
//                 + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
//                 + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
//                 + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
//                 + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
//                 + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
//                 + ` INNER JOIN requests req on req.id = p.request_id `
//                 + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
//                 + ` LEFT JOIN products prod ON prod.id = cop.product_id `
//                 + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
//                 + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
//                 + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
//                 + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
//                 + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
//                 + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
//                 + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//                 + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
//                 + ` WHERE ${whereCondition} ${dateCondition!= '' ? ' AND '+dateCondition : ''}  ${departmentCondition != '' ? departmentCondition : ''} ${projectTypeCondition} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} ${limitCondition} `
//             );
//         }
//         else if (userType === 3) {
//             query = await sequelize.query(
//                 ` SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name,req.isFromDesignOrder,req.is_split_order,req.for_parent_facility,req.origin_facility_id, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count, com.name AS community_name,c_ord.customer_phone, c_ord.customer_name,c_ord.customer_id,c_ord.total,req.doc_number,req.est_doc_number,req.installation_acceptance,req.syncWithQuickbooks,req.design_order_id,COALESCE(p_dopm.name, CONCAT(s_dopm.first_name, ' ', COALESCE(s_dopm.last_name, ''))) AS design_order_member_name,COALESCE(s_dopm.first_name, '') AS design_order_member_first_name,COALESCE(s_dopm.last_name, '') AS design_order_member_last_name,COALESCE(u_dopm.email, u2_dopm.email, '') AS design_order_member_email,COALESCE(p_dopm.phone, s_dopm.phone, '') AS design_order_member_phone,GROUP_CONCAT(DISTINCT cop.product_name SEPARATOR ', ') AS product_name,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p `
//                 + ` LEFT JOIN users u ON p.added_by=u.id  `
//                 + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
//                 + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
//                 + ` left join request_partners rp on rp.request_id=p.request_id`
//                 + ` left join partners pr on pr.id=rp.partner_id`
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
//                 + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
//                 + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
//                 + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
//                 + ` INNER JOIN requests req on req.id = p.request_id `
//                 + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
//                 + ` LEFT JOIN products prod ON prod.id = cop.product_id `
//                 + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
//                 + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
//                 + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
//                 + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
//                 + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
//                 + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
//                 + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//                 + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
//                 + ` WHERE pr.user_id=${userId} ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} ${limitCondition} `
//             );
//         }
//         else {
//             query = await sequelize.query(`SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name,req.isFromDesignOrder,req.is_split_order,req.for_parent_facility,req.origin_facility_id, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count, com.name AS community_name,c_ord.customer_phone, c_ord.customer_name,c_ord.customer_id,c_ord.total,req.doc_number,req.est_doc_number,req.installation_acceptance,req.syncWithQuickbooks,req.design_order_id,COALESCE(p_dopm.name, CONCAT(s_dopm.first_name, ' ', COALESCE(s_dopm.last_name, ''))) AS design_order_member_name,COALESCE(s_dopm.first_name, '') AS design_order_member_first_name,COALESCE(s_dopm.last_name, '') AS design_order_member_last_name,COALESCE(u_dopm.email, u2_dopm.email, '') AS design_order_member_email,COALESCE(p_dopm.phone, s_dopm.phone, '') AS design_order_member_phone,GROUP_CONCAT(DISTINCT cop.product_name SEPARATOR ', ') AS product_name,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p `
//                 + ` LEFT JOIN staff_members s1 ON s1.id=p.project_lead  `
//                 + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
//                 + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
//                 + ` LEFT JOIN users u1 ON s1.user_id=u1.id `
//                 + ` LEFT JOIN staff_members s2 ON s2.id=p.default_assignee `
//                 + ` LEFT JOIN users u2 ON s2.user_id=u2.id `
//                 + ` LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id from project_members pm left join partners p on p.id=pm.partner_id left join users u on p.user_id=u.id left join staff_members s on s.id=pm.staff_id left join users u2 on s.user_id=u2.id) pmm ON pmm.project_id=p.id and pmm.user_id=${userId} `
//                 + ` LEFT JOIN users u ON p.added_by=u.id `
//                 + ` LEFT JOIN installations i ON p.id = i.project_id `
//                 + ` LEFT JOIN driver dr ON i.driver_id = dr.id `
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  `
//                 + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  `
//                 + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id  `
//                 + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
//                 + ` INNER JOIN requests req on req.id = p.request_id `
//                 + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
//                 + ` LEFT JOIN products prod ON prod.id = cop.product_id `
//                 + ` left join users ura on ura.id = req.id `
//                 + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
//                 + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
//                 + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
//                 + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
//                 + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
//                 + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
//                 + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//                 + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) ins ON ins.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
//                 + ` WHERE (
//                     u1.id = ${userId}
//                     OR u2.id = ${userId}
//                     OR pmm.user_id = ${userId}
//                     OR (req.added_by = ${userId} AND ura.user_type <> 3)
//                     OR FIND_IN_SET(${userId}, i.team_id)
//                     OR FIND_IN_SET(${userId}, dr.user_id)
//                     OR u_dopm.id = ${userId}
//                     OR u2_dopm.id = ${userId}
//                 )
//                 ${dateCondition ? ' AND ' + dateCondition : ''}
//                 ${projectTypeCondition}
//                 ${departmentCondition ? ' ' + departmentCondition : ''}
//                 ${jobClassCondition}
//                 ${jobTypesCondition}
//                 ${clientCondition}
//                 ${userCondition}
//                 ${estimateCondition}
//                 ${projectCondition}
//                 ${tabCondition ? ' AND ' + tabCondition : ''}
//                 ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''}
//                 ${searchCondition ? ' AND ' + searchCondition : ''}
//                 GROUP BY p.id
//                 ${createdAt}
//                 ${limitCondition} `
//                 //  + ` WHERE (u1.id = ${userId} or u2.id = ${userId} or pmm.user_id =${userId} OR (req.added_by = ${userId} AND ura.user_type <> 3) OR FIND_IN_SET(${userId}, i.team_id) OR FIND_IN_SET(${userId}, dr.user_id) OR u_dopm.id = ${userId} OR u2_dopm.id = ${userId}) ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} ${limitCondition} `);
//              );
//              }
//         console.log("$$#################hifiiiiiiiiiiiiii");
//         let data;
//         if (query.length > 0) {
//             data = query[0];
//             if (userType == 1 || userType == 8) {
//                 const results = await Promise.all(data.map(async (item) => {

//                     let selectedMaterials = await JobCost.fetchAllJobCostProjectId(item.id);
//                     let price = selectedMaterials?.filter(curr => curr.taken === 1)?.reduce((total, currentItem) => { return total + currentItem.total }, 0);
//                     let payout = await JobCost.fetchAllPayOutByProjectId(item.id, userId);
//                     let services = await Request.getAllServiceByRequest(item.request_id);
//                     let serviceExpense = services?.filter(curr => curr.taken === 1)?.reduce((total, currentItem) => { return total + (currentItem.qty * currentItem.originalCost) }, 0);
//                     let payoutPrice = payout.reduce((total, currentItem) => total + currentItem.amount, 0);

//                     let expense = price + payoutPrice + Math.max(0, (serviceExpense - payoutPrice))
//                     const parsedCost = parseFloat(item.cost) || 0;
//                     if (Number(item.status) === 1 || parsedCost <= 0) {
//                         item.progressValue = 0;
//                     } else {
//                         item.progressValue = (expense / parsedCost) * 100
//                         if (item.progressValue > 100) {
//                             item.progressValue = 100
//                         }
//                     }
//                     let image = await Request.FetchAllApprovedDesigns(item.request_id);
//                     let coverImage = image?.filter((imageItem)=>imageItem?.file_type?.startsWith('image/') || imageItem?.file_type ==='img')
//                     let linkedItems = image?.find((imageItem) => imageItem?.location_ids !== null);
//                     console.log("###########linkedItems",linkedItems)
//                     let firstItemWithLocationIds = linkedItems
//                     let ApprovedPdf = image[0]
//                     if (!empty(coverImage[0])) {
//                         item.cover_image = coverImage[0]?.name ? coverImage[0]?.name : ""
//                     }
//                     else {
//                         item.cover_image = ""
//                     }
//                     if (!empty(firstItemWithLocationIds)) {
//                         item.approved_pdf = firstItemWithLocationIds.name ? firstItemWithLocationIds.name : ""
//                     }
//                     else {
//                         item.approved_pdf = ApprovedPdf?.name ? ApprovedPdf?.name : ""
//                     }

//                     return item;
//                 }));
//                 // return results;
//                 return results.map(record => parseDecimalFields(record));
//             } else {
//                 const results = await Promise.all(data.map(async (item) => {
//                     let image = await Request.FetchAllApprovedDesigns(item.request_id);
//                     let coverImage = image?.filter((imageItem)=>imageItem?.file_type?.startsWith('image/') || imageItem?.file_type ==='img')
//                     let linkedItems = image?.find((imageItem) => imageItem?.location_ids !== null);
//                     let firstItemWithLocationIds = linkedItems
//                     let ApprovedPdf = image[0]
//                     if (!empty(coverImage[0])) {
//                         item.cover_image = coverImage[0]?.name ? coverImage[0]?.name : ""
//                     }
//                     else {
//                         item.cover_image = ""
//                     }
//                     if (!empty(firstItemWithLocationIds)) {
//                         item.approved_pdf = firstItemWithLocationIds?.name ? firstItemWithLocationIds?.name : ""
//                     }
//                     else {
//                         item.approved_pdf = ApprovedPdf?.name ? ApprovedPdf?.name : ""
//                     }
//                     return item;
//                 }));
//                 return results?.map(record => parseDecimalFields(record));
//             }


//         } else {
//             return false;
//         }
//     } catch (error) {
//         console.log(error);
//         throw new Error("Server error");
//     }
// }
const getAllProjectsForCommunityCount = async (hasPermission, all = false, userType, userId, where = [],sort,fromDate,toDate,dueData, filterProjectType, currentTab, page = 1, limit = false, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = [], splitOrder = false) => {
    try {
        let estimateCondition = ' AND p.is_estimate_job=0'

        const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
        const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
        const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
        console.log('toTimestamp',toTimestamp)
        let limitCondition = ''
        // if (limit){
        //     limitCondition = ` LIMIT ${limit} OFFSET ${(page - 1) * limit}`
        // }
        let dateCondition = '';
        if (fromTimestamp && toTimestamp) {
          dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
        } else if (fromTimestamp) {
          dateCondition = ` p.installation_date >= ${fromTimestamp}`;
        } else if (toTimestamp) {
          dateCondition = ` p.installation_date <= ${toTimestamp}`;
        }
        // else if (dueTimestamp) {
        //     dateCondition = ` p.installation_date <= ${dueTimestamp}`;
        // }

        let createdAt = ''
        if (dueTimestamp) {
            createdAt=`ORDER BY p.installation_date ASC`
        }else{
            if(sort==='new'){
                createdAt = `ORDER BY p.id DESC `
            }else if(sort==='old'){
                createdAt = `ORDER BY p.id ASC `
            }else if(sort === 'custom_order'){
                createdAt=`ORDER BY p.card_order ASC`
            }else{
                createdAt=`ORDER BY p.timestamp DESC`
            }
        }

        let whereCondition;
        let query = ''
        if (all) {
            // For Production tab, allow status 2; for other tabs, exclude status 2
            if (currentTab === 'Production') {
                whereCondition = ` (p.status != 0 AND p.status != 1 AND p.status != 3 AND p.status != 6)`;
            }else if(currentTab === "Pre-Production") {
                whereCondition = ` (p.status = 1 )`;
            } else if(currentTab && currentTab === 'ALL') {
                whereCondition = ` p.status != 0`;
            } else if(currentTab && currentTab === 'Rejected') {
                whereCondition = ` p.status = 9`;
            } else{
                whereCondition = ` p.status != 999`;
            }
        } else {
            whereCondition = ` p.status = 1`;
        }
        if (!empty(where)) {

        }
        if (splitOrder === 1) {
            whereCondition += whereCondition ? ` AND req.is_split_order = 1 AND req.for_parent_facility != 2` : ` req.is_split_order = 1 AND req.for_parent_facility != 2`;
        } else if (splitOrder === 2) {
            whereCondition += whereCondition ? ` AND req.is_split_order = 0` : ` req.is_split_order = 0`;
        }

        let projectTypeCondition = '';
if (filterProjectType === 1) {
  projectTypeCondition = ` AND req.project_type = 1`;
} else if (filterProjectType === 2) {
  projectTypeCondition = ` AND req.project_type = 2`;
} else if (filterProjectType === 'NULL') {
  projectTypeCondition = ` AND req.project_type IS NULL`;
} else if (filterProjectType === 'ALL') {
  projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
} else {
  projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
}

        // Add job class filtering condition
        let jobClassCondition = '';
        if (jobClassFilter && jobClassFilter.length > 0) {
            const jobClassIds = jobClassFilter.join(',');
            jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
        }

        // Add job types filtering condition
        let jobTypesCondition = '';
        if (jobTypesFilter && jobTypesFilter.length > 0) {
            const jobTypesIds = jobTypesFilter.join(',');
            jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
        }

        // Add client filtering condition
        let clientCondition = '';
        if (clientFilter && clientFilter.length > 0) {
            const clientIds = clientFilter.join(',');
            clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
        }

        // Add user filtering condition
        let userCondition = '';
        if (userFilter && userFilter.length > 0) {
            const userIds = userFilter.join(',');
            userCondition = ` AND EXISTS (
                SELECT 1 FROM project_members pm 
                WHERE pm.project_id = p.id 
                AND pm.staff_id IN (${userIds})
            )`;
        }

        // Add project filtering condition
        let projectCondition = '';
        if (projectFilter && projectFilter.length > 0) {
            // Check if 'other' is included in the filter
            const hasOther = projectFilter.includes('other');
            const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
            if (hasOther && numericIds.length > 0) {
                // Include both specific communities and null/other communities
                projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
            } else if (hasOther) {
                // Only 'other' is selected
                projectCondition = ` AND p.community IS NULL`;
            } else {
                // Only specific communities are selected
                projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
            }
        }

        let departmentCondition = '';
        if (departmentFilter && departmentFilter.length > 0) {
            const departmentIds = departmentFilter.join(',');
          
        //     departmentCondition = `
        //     AND EXISTS (
        //       SELECT 1
        //       FROM project_members pm_dep
        //       INNER JOIN staff_members sm_dep ON pm_dep.staff_id = sm_dep.id
        //       INNER JOIN users u_dep ON sm_dep.user_id = u_dep.id
        //       WHERE pm_dep.project_id = p.id
        //       AND u_dep.department_id IN (${departmentIds})
        //     )
        //   `;

                        departmentCondition = `
            AND EXISTS (
                SELECT 1
                FROM project_members pm_dep
                INNER JOIN staff_members sm_dep 
                ON pm_dep.staff_id = sm_dep.id
                INNER JOIN services srv 
                ON FIND_IN_SET(srv.id, sm_dep.services)
                WHERE pm_dep.project_id = p.id
                AND srv.department_id IN (${departmentIds})
            )
            `;

           

          }

        // Add search condition
        let searchCondition = '';
        if (search && search.trim() !== '') {
            searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR req.doc_number LIKE '%${search}%' OR req.est_doc_number LIKE '%${search}%')`;
        }

        // Add currentTab filtering condition
        let tabCondition = '';
        if (currentTab === 'Hold') {
            tabCondition = ` p.hold = 1`;
        } else if (currentTab === 'Pre-Production') {
            tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0`;
        } else if (currentTab === 'Production') {
            tabCondition = ` p.hold = 0 AND p.status = 2`;
        } else if (currentTab === 'Rejected') {
            tabCondition = ` p.status = 9`;
        } else if (currentTab === 'Change Order') {
            tabCondition = ` p.hold = 0 AND p.change_order = 1`;
        }

        // Exclude change orders from all other tabs (including ALL)
        let changeOrderExclusion = '';
        if (currentTab !== 'Change Order' && currentTab !== 'Hold' && currentTab !== 'ALL') {
            changeOrderExclusion = ` (p.change_order IS NULL OR p.change_order = 0)`;
        }
        // else if (currentTab === 'Installs') {
        //     tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND req.status != 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
        // } else if (currentTab === 'Pickup') {
        //     tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
        // } else if (currentTab === 'Shipping') {
        //     tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
        // } else if (currentTab === 'Completed') {
        //     tabCondition = ` ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.isReview != 2 AND req.installation_acceptance = 1) OR (p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND req.isReview != 2 AND req.installation_acceptance = 1) OR req.status = 10`;
        // } else if (currentTab === 'T & M Review') {
        //     tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.installation_acceptance != 1 AND p.status = 3 AND p.project_category = 12 AND req.isReview = 2`;
        // } else if (currentTab === 'Cost Card') {
        //     tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.installation_acceptance != 1 AND p.status = 3 AND p.project_category != 12`;
        // }

        if (userType === 1 || userType == 8) {
            query = await sequelize.query(
                ` SELECT p.* FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE ${whereCondition} ${dateCondition!= '' ? ' AND '+dateCondition : ''}  ${departmentCondition != '' ? departmentCondition : ''} ${projectTypeCondition} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} `
            );
        }
        else if (userType === 3) {
            query = await sequelize.query(
                ` SELECT p.* FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` left join request_partners rp on rp.request_id=p.request_id`
                + ` left join partners pr on pr.id=rp.partner_id`
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE pr.user_id=${userId} ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} `
            );
        }
        else {
            query = await sequelize.query(`SELECT p.* FROM projects p `
                + ` LEFT JOIN staff_members s1 ON s1.id=p.project_lead  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN users u1 ON s1.user_id=u1.id `
                + ` LEFT JOIN staff_members s2 ON s2.id=p.default_assignee `
                + ` LEFT JOIN users u2 ON s2.user_id=u2.id `
                + ` LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id from project_members pm left join partners p on p.id=pm.partner_id left join users u on p.user_id=u.id left join staff_members s on s.id=pm.staff_id left join users u2 on s.user_id=u2.id) pmm ON pmm.project_id=p.id and pmm.user_id=${userId} `
                + ` LEFT JOIN users u ON p.added_by=u.id `
                + ` LEFT JOIN installations i ON p.id = i.project_id `
                + ` LEFT JOIN driver dr ON i.driver_id = dr.id `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id  `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` left join users ura on ura.id = req.id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) ins ON ins.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE (
                    u1.id = ${userId}
                    OR u2.id = ${userId}
                    OR pmm.user_id = ${userId}
                    OR (req.added_by = ${userId} AND ura.user_type <> 3)
                    OR FIND_IN_SET(${userId}, i.team_id)
                    OR FIND_IN_SET(${userId}, dr.user_id)
                    OR u_dopm.id = ${userId}
                    OR u2_dopm.id = ${userId}
                )
                ${dateCondition ? ' AND ' + dateCondition : ''}
                ${projectTypeCondition}
                ${departmentCondition ? ' ' + departmentCondition : ''}
                ${jobClassCondition}
                ${jobTypesCondition}
                ${clientCondition}
                ${userCondition}
                ${estimateCondition}
                ${projectCondition}
                ${tabCondition ? ' AND ' + tabCondition : ''}
                ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''}
                ${searchCondition ? ' AND ' + searchCondition : ''}
                GROUP BY p.id
                ${createdAt}`
                //  + ` WHERE (u1.id = ${userId} or u2.id = ${userId} or pmm.user_id =${userId} OR (req.added_by = ${userId} AND ura.user_type <> 3) OR FIND_IN_SET(${userId}, i.team_id) OR FIND_IN_SET(${userId}, dr.user_id) OR u_dopm.id = ${userId} OR u2_dopm.id = ${userId}) ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} ${limitCondition} `);
             );
             }
        console.log("$$#################hifiiiiiiiiiiiiii");
        return query?.length > 0 ? query?.[0] : [];
    }
catch (error) {
        console.log(error);
        return [];
    }
}

const getAllEstimateProjects = async (hasPermission, all = false, userType, userId, where = [],sort,fromDate,toDate,dueData, filterProjectType, currentTab, page = 1, limit = false, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = []) => {
    try {
        let estimateCondition = ' AND p.is_estimate_job=1'

        const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
        const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
        const dueTimestamp = dueData ? moment().endOf('day').unix() : null;

        let limitCondition = ''
        if (limit){
            limitCondition = ` LIMIT ${limit} OFFSET ${(page - 1) * limit}`
        }
        let dateCondition = '';
        if (fromTimestamp && toTimestamp) {
          dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
        } else if (fromTimestamp) {
          dateCondition = ` p.installation_date >= ${fromTimestamp}`;
        } else if (toTimestamp) {
          dateCondition = ` p.installation_date <= ${toTimestamp}`;
        }
        // else if (dueTimestamp) {
        //     dateCondition = ` p.installation_date <= ${dueTimestamp}`;
        // }

        let createdAt = ''
        if (dueTimestamp) {
            createdAt=`ORDER BY p.installation_date ASC`
        }else{
            if(sort==='new'){
                createdAt = `ORDER BY p.id DESC `
            }else if(sort==='old'){
                createdAt = `ORDER BY p.id ASC `
            }else if(sort === 'custom_order'){
                createdAt=`ORDER BY p.card_order ASC`
            }else{
                createdAt=`ORDER BY p.timestamp DESC`
            }
        }

        let whereCondition;
        let query = ''
        if (currentTab === 'Drafts') {
            whereCondition = ` req.is_draft = 1`;
        } else if (all) {
            // For Production tab, allow status 2; for other tabs, exclude status 2
            if (currentTab === 'In Progress') {
                whereCondition = ` (p.status != 0 AND p.status != 1 AND p.status != 3 AND p.hold = 0)`;
            }else if(currentTab === "New") {
                whereCondition = ` (p.status = 1  AND p.hold = 0)`;
            } else if(currentTab === 'Hold') {
                whereCondition = ` p.hold = 1`;
            } else{
                whereCondition = ` p.status = 3 AND p.hold = 0`;
            }
        } else {
            whereCondition = ` p.status = 1`;
        }


        let projectTypeCondition = '';
        if (filterProjectType === 1) {
            projectTypeCondition = ` AND req.project_type = 1`;
        } else if (filterProjectType === 2) {
            projectTypeCondition = ` AND req.project_type = 2`;
        } else if (filterProjectType === 'NULL') {
            projectTypeCondition = ` AND req.project_type IS NULL`;
        } else if (filterProjectType === 'ALL') {
            projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
        } else {
            projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
        }

        // Add job class filtering condition
        let jobClassCondition = '';
        if (jobClassFilter && jobClassFilter.length > 0) {
            const jobClassIds = jobClassFilter.join(',');
            jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
        }

        // Add job types filtering condition
        let jobTypesCondition = '';
        if (jobTypesFilter && jobTypesFilter.length > 0) {
            const jobTypesIds = jobTypesFilter.join(',');
            jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
        }

        // Add client filtering condition
        let clientCondition = '';
        if (clientFilter && clientFilter.length > 0) {
            const clientIds = clientFilter.join(',');
            clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
        }

        // Add user filtering condition
        let userCondition = '';
        if (userFilter && userFilter.length > 0) {
            const userIds = userFilter.join(',');
            userCondition = ` AND EXISTS (
                SELECT 1 FROM project_members pm 
                WHERE pm.project_id = p.id 
                AND pm.staff_id IN (${userIds})
            )`;
        }

        // Add project filtering condition
        let projectCondition = '';
        if (projectFilter && projectFilter.length > 0) {
            // Check if 'other' is included in the filter
            const hasOther = projectFilter.includes('other');
            const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
            if (hasOther && numericIds.length > 0) {
                // Include both specific communities and null/other communities
                projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
            } else if (hasOther) {
                // Only 'other' is selected
                projectCondition = ` AND p.community IS NULL`;
            } else {
                // Only specific communities are selected
                projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
            }
        }

        let departmentCondition = '';
        if (departmentFilter && departmentFilter.length > 0) {
            const departmentIds = departmentFilter.join(',');
          
            departmentCondition = `
            AND EXISTS (
              SELECT 1
              FROM project_members pm_dep
              INNER JOIN staff_members sm_dep ON pm_dep.staff_id = sm_dep.id
              INNER JOIN users u_dep ON sm_dep.user_id = u_dep.id
              WHERE pm_dep.project_id = p.id
              AND u_dep.department_id IN (${departmentIds})
            )
          `;
          }

        // Add search condition
        let searchCondition = '';
        if (search && search.trim() !== '') {
            searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR req.doc_number LIKE '%${search}%' OR req.est_doc_number LIKE '%${search}%')`;
        }

        // Add currentTab filtering condition
        let tabCondition = '';
        if (currentTab === 'Hold') {
            tabCondition = ` p.hold = 1`;
        } else if (currentTab === 'New') {
            tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0`;
        } else if (currentTab === 'In Progress') {
            tabCondition = ` p.hold = 0 AND p.status = 2 `;
        } else if (currentTab === 'Drafts') {
            tabCondition = ` req.is_draft = 1`;
        } else {
            tabCondition = ` p.hold = 0 AND p.status = 3 `;
        }

        if (userType === 1 || userType == 8) {
            query = await sequelize.query(
                ` SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name,'project' As projectType,req.isFromDesignOrder,req.is_split_order,req.for_parent_facility,req.origin_facility_id, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count, req.is_draft, com.name AS community_name,c_ord.customer_phone,c_ord.customer_name,c_ord.customer_id,c_ord.total,req.doc_number,req.est_doc_number,req.installation_acceptance,req.syncWithQuickbooks,req.design_order_id,COALESCE(p_dopm.name, CONCAT(s_dopm.first_name, ' ', COALESCE(s_dopm.last_name, ''))) AS design_order_member_name,COALESCE(s_dopm.first_name, '') AS design_order_member_first_name,COALESCE(s_dopm.last_name, '') AS design_order_member_last_name,COALESCE(u_dopm.email, u2_dopm.email, '') AS design_order_member_email,COALESCE(p_dopm.phone, s_dopm.phone, '') AS design_order_member_phone,GROUP_CONCAT(DISTINCT cop.product_name SEPARATOR ', ') AS product_name,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE ${whereCondition} ${dateCondition!= '' ? ' AND '+dateCondition : ''}  ${departmentCondition != '' ? departmentCondition : ''} ${projectTypeCondition} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} ${limitCondition} `
            );
        }
        else if (userType === 3) {
            query = await sequelize.query(
                ` SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name,req.isFromDesignOrder,req.is_split_order,req.for_parent_facility,req.origin_facility_id, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count, req.is_draft, com.name AS community_name,c_ord.customer_phone, c_ord.customer_name,c_ord.customer_id,c_ord.total,req.doc_number,req.est_doc_number,req.installation_acceptance,req.syncWithQuickbooks,req.design_order_id,COALESCE(p_dopm.name, CONCAT(s_dopm.first_name, ' ', COALESCE(s_dopm.last_name, ''))) AS design_order_member_name,COALESCE(s_dopm.first_name, '') AS design_order_member_first_name,COALESCE(s_dopm.last_name, '') AS design_order_member_last_name,COALESCE(u_dopm.email, u2_dopm.email, '') AS design_order_member_email,COALESCE(p_dopm.phone, s_dopm.phone, '') AS design_order_member_phone,GROUP_CONCAT(DISTINCT cop.product_name SEPARATOR ', ') AS product_name,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` left join request_partners rp on rp.request_id=p.request_id`
                + ` left join partners pr on pr.id=rp.partner_id`
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE pr.user_id=${userId} ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} ${limitCondition} `
            );
        }
        else {
            query = await sequelize.query(`SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name,req.isFromDesignOrder,req.is_split_order,req.for_parent_facility,req.origin_facility_id, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count, req.is_draft, com.name AS community_name,c_ord.customer_phone, c_ord.customer_name,c_ord.customer_id,c_ord.total,req.doc_number,req.est_doc_number,req.installation_acceptance,req.syncWithQuickbooks,req.design_order_id,COALESCE(p_dopm.name, CONCAT(s_dopm.first_name, ' ', COALESCE(s_dopm.last_name, ''))) AS design_order_member_name,COALESCE(s_dopm.first_name, '') AS design_order_member_first_name,COALESCE(s_dopm.last_name, '') AS design_order_member_last_name,COALESCE(u_dopm.email, u2_dopm.email, '') AS design_order_member_email,COALESCE(p_dopm.phone, s_dopm.phone, '') AS design_order_member_phone,GROUP_CONCAT(DISTINCT cop.product_name SEPARATOR ', ') AS product_name,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p `
                + ` LEFT JOIN staff_members s1 ON s1.id=p.project_lead  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN users u1 ON s1.user_id=u1.id `
                + ` LEFT JOIN staff_members s2 ON s2.id=p.default_assignee `
                + ` LEFT JOIN users u2 ON s2.user_id=u2.id `
                + ` LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id from project_members pm left join partners p on p.id=pm.partner_id left join users u on p.user_id=u.id left join staff_members s on s.id=pm.staff_id left join users u2 on s.user_id=u2.id) pmm ON pmm.project_id=p.id and pmm.user_id=${userId} `
                + ` LEFT JOIN users u ON p.added_by=u.id `
                + ` LEFT JOIN installations i ON p.id = i.project_id `
                + ` LEFT JOIN driver dr ON i.driver_id = dr.id `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id  `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` left join users ura on ura.id = req.id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) ins ON ins.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE (
                    u1.id = ${userId}
                    OR u2.id = ${userId}
                    OR pmm.user_id = ${userId}
                    OR (req.added_by = ${userId} AND ura.user_type <> 3)
                    OR FIND_IN_SET(${userId}, i.team_id)
                    OR FIND_IN_SET(${userId}, dr.user_id)
                    OR u_dopm.id = ${userId}
                    OR u2_dopm.id = ${userId}
                )
                ${dateCondition ? ' AND ' + dateCondition : ''}
                ${projectTypeCondition}
                ${departmentCondition ? ' ' + departmentCondition : ''}
                ${jobClassCondition}
                ${jobTypesCondition}
                ${clientCondition}
                ${userCondition}
                ${estimateCondition}
                ${projectCondition}
                ${tabCondition ? ' AND ' + tabCondition : ''}
                ${searchCondition ? ' AND ' + searchCondition : ''}
                GROUP BY p.id
                ${createdAt}
                ${limitCondition} `
                //  + ` WHERE (u1.id = ${userId} or u2.id = ${userId} or pmm.user_id =${userId} OR (req.added_by = ${userId} AND ura.user_type <> 3) OR FIND_IN_SET(${userId}, i.team_id) OR FIND_IN_SET(${userId}, dr.user_id) OR u_dopm.id = ${userId} OR u2_dopm.id = ${userId}) ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} GROUP BY p.id ${createdAt} ${limitCondition} `);
             );
             }
        console.log("$$#################hifiiiiiiiiiiiiii");
        let data;
        if (query.length > 0) {
            data = query[0];
            if (userType == 1 || userType == 8) {
                const results = await Promise.all(data.map(async (item) => {

                    let selectedMaterials = await JobCost.fetchAllJobCostProjectId(item.id);
                    let price = selectedMaterials?.filter(curr => curr.taken === 1)?.reduce((total, currentItem) => { return total + currentItem.total }, 0);
                    let payout = await JobCost.fetchAllPayOutByProjectId(item.id, userId);
                    let services = await Request.getAllServiceByRequest(item.request_id);
                    let serviceExpense = services?.filter(curr => curr.taken === 1)?.reduce((total, currentItem) => { return total + (currentItem.qty * currentItem.originalCost) }, 0);
                    let payoutPrice = payout.reduce((total, currentItem) => total + currentItem.amount, 0);

                    let expense = price + payoutPrice + Math.max(0, (serviceExpense - payoutPrice))
                    const parsedCost = parseFloat(item.cost) || 0;
                    if (Number(item.status) === 1 || parsedCost <= 0) {
                        item.progressValue = 0;
                    } else {
                        item.progressValue = (expense / parsedCost) * 100
                        if (item.progressValue > 100) {
                            item.progressValue = 100
                        }
                    }
                    let image = await Request.FetchAllApprovedDesigns(item.request_id);
                    image = image?.filter((imageItem)=>imageItem?.file_type?.startsWith('image/') || imageItem?.file_type ==='img')
                    if (!empty(image[0])) {
                        item.cover_image = image[0].name ? image[0].name : ""
                    }
                    else {
                        item.cover_image = ""
                    }

                    return item;
                }));
                // return results;
                return results.map(record => parseDecimalFields(record));
            } else {
                const results = await Promise.all(data.map(async (item) => {
                    let image = await Request.FetchAllApprovedDesigns(item.request_id);
                    image = image?.filter((imageItem)=>imageItem?.file_type?.startsWith('image/') || imageItem?.file_type ==='img')
                    if (!empty(image[0])) {
                        item.cover_image = image[0].name ? image[0].name : ""
                    }
                    else {
                        item.cover_image = ""
                    }

                    return item;
                }));
                return results?.map(record => parseDecimalFields(record));
            }


        } else {
            return false;
        }
    } catch (error) {
        console.log("getAllEstimateProjects error",error);
        throw new Error("Server error");
    }
}

const getTotalEstimateProjectsCount = async (hasPermission, all = false, userType, userId, where = [], sort, fromDate, toDate, dueData, filterProjectType, currentTab, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = []) => {
    try {
        let estimateCondition = ' AND p.is_estimate_job=1'

        const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
        const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
        const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
        
        let dateCondition = '';
        if (fromTimestamp && toTimestamp) {
          dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
        } else if (fromTimestamp) {
          dateCondition = ` p.installation_date >= ${fromTimestamp}`;
        } else if (toTimestamp) {
          dateCondition = ` p.installation_date <= ${toTimestamp}`;
        }

        let whereCondition;
        if (currentTab === 'Drafts') {
            whereCondition = ` req.is_draft = 1 AND p.hold = 0`;
        } else if (all) {
            if (currentTab === 'In Progress') {
                whereCondition = ` (p.status != 0 AND p.status != 1 AND p.status != 3 AND p.hold = 0 AND req.is_draft = 0)`;
            }else if(currentTab === "New") {
                whereCondition = ` (p.status = 1  AND p.hold = 0 AND req.is_draft = 0)`;
            } else if(currentTab === 'Hold') {
                whereCondition = ` p.hold = 1`;
            } else{
                whereCondition = ` p.status = 3 AND p.hold = 0`;
            }
        } else {
            whereCondition = ` p.status = 1`;
        }

        let projectTypeCondition = '';
        if (filterProjectType === 1) {
          projectTypeCondition = ` AND req.project_type = 1`;
        } else if (filterProjectType === 2) {
          projectTypeCondition = ` AND req.project_type = 2`;
        } else if (filterProjectType === 'NULL') {
          projectTypeCondition = ` AND req.project_type IS NULL`;
        } else if (filterProjectType === 'ALL') {
          projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
        } else {
          projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
        }

        // Add job class filtering condition
        let jobClassCondition = '';
        if (jobClassFilter && jobClassFilter.length > 0) {
            const jobClassIds = jobClassFilter.join(',');
            jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
        }

        // Add job types filtering condition
        let jobTypesCondition = '';
        if (jobTypesFilter && jobTypesFilter.length > 0) {
            const jobTypesIds = jobTypesFilter.join(',');
            jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
        }

        // Add client filtering condition
        let clientCondition = '';
        if (clientFilter && clientFilter.length > 0) {
            const clientIds = clientFilter.join(',');
            clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
        }

        // Add user filtering condition
        let userCondition = '';
        if (userFilter && userFilter.length > 0) {
            const userIds = userFilter.join(',');
            userCondition = ` AND EXISTS (
                SELECT 1 FROM project_members pm 
                WHERE pm.project_id = p.id 
                AND pm.staff_id IN (${userIds})
            )`;
        }

        // Add project filtering condition
        let projectCondition = '';
        if (projectFilter && projectFilter.length > 0) {
            // Check if 'other' is included in the filter
            const hasOther = projectFilter.includes('other');
            const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
            if (hasOther && numericIds.length > 0) {
                // Include both specific communities and null/other communities
                projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
            } else if (hasOther) {
                // Only 'other' is selected
                projectCondition = ` AND p.community IS NULL`;
            } else {
                // Only specific communities are selected
                projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
            }
        }

        let departmentCondition = '';
        if (departmentFilter && departmentFilter.length > 0) {
            const departmentIds = departmentFilter.join(',');
          
            departmentCondition = `
            AND EXISTS (
               SELECT 1
               FROM project_members pmm
               INNER JOIN staff_members smm ON pmm.staff_id = smm.id
               INNER JOIN users uu ON smm.user_id = uu.id
               WHERE pmm.project_id = p.id
               AND uu.department_id IN (${departmentIds})
             )
           `; 
          }


        // Add search condition
        let searchCondition = '';
        if (search && search.trim() !== '') {
            searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR req.doc_number LIKE '%${search}%' OR req.est_doc_number LIKE '%${search}%')`;
        }

        // Add currentTab filtering condition
        let tabCondition = '';
        if (currentTab === 'Hold') {
            tabCondition = ` p.hold = 1`;
        } else if (currentTab === 'New') {
            tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0`;
        } else if (currentTab === 'In Progress') {
            tabCondition = ` p.hold = 0 AND p.status = 2 `;
        } else if (currentTab === 'Drafts') {
            tabCondition = ` req.is_draft = 1`;
        } else {
            tabCondition = ` p.hold = 0 AND p.status = 3 `;
        }

        let query = '';
        if (userType === 1 || userType == 8) {
            query = await sequelize.query(
                ` SELECT COUNT(DISTINCT p.id) as count FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE ${whereCondition} ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition}  ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${estimateCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} `
            );
        }
        else if (userType === 3) {
            query = await sequelize.query(
                ` SELECT COUNT(DISTINCT p.id) as count FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` left join request_partners rp on rp.request_id=p.request_id`
                + ` left join partners pr on pr.id=rp.partner_id`
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE pr.user_id=${userId} ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${estimateCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} `
            );
        }
        else {
            query = await sequelize.query(`SELECT COUNT(DISTINCT p.id) as count FROM projects p `
                + ` LEFT JOIN staff_members s1 ON s1.id=p.project_lead  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN users u1 ON s1.user_id=u1.id `
                + ` LEFT JOIN staff_members s2 ON s2.id=p.default_assignee `
                + ` LEFT JOIN users u2 ON s2.user_id=u2.id `
                + ` LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id from project_members pm left join partners p on p.id=pm.partner_id left join users u on p.user_id=u.id left join staff_members s on s.id=pm.staff_id left join users u2 on s.user_id=u2.id) pmm ON pmm.project_id=p.id and pmm.user_id=${userId} `
                + ` LEFT JOIN users u ON p.added_by=u.id `
                + ` LEFT JOIN installations i ON p.id = i.project_id `
                + ` LEFT JOIN driver dr ON i.driver_id = dr.id `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id  `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` left join users ura on ura.id = req.id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) ins ON ins.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE (u1.id = ${userId} or u2.id = ${userId} or pmm.user_id =${userId} OR (req.added_by = ${userId} AND ura.user_type <> 3) OR FIND_IN_SET(${userId}, i.team_id) OR FIND_IN_SET(${userId}, dr.user_id) OR u_dopm.id = ${userId} OR u2_dopm.id = ${userId}) ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${estimateCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} `);
        }
        
        return query[0][0].count;
    } catch (error) {
        console.log("Error getting total projects count:", error);
        throw new Error("Server error");
    }
};

const   getAllProjectsProgress = async (hasPermission, all = false, userType, userId, where = [],sort,fromDate,toDate,dueData,selectedTab) => {
    try {
        const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
        const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
        const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
        console.log('toTimestamp',toTimestamp)
        let dateCondition = '';
        if (fromTimestamp && toTimestamp) {
          dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
        } else if (fromTimestamp) {
          dateCondition = ` p.installation_date >= ${fromTimestamp}`;
        } else if (toTimestamp) {
          dateCondition = ` p.installation_date <= ${toTimestamp}`;
        }
        // else if (dueTimestamp) {
        //     dateCondition = ` p.installation_date <= ${dueTimestamp}`;
        // }

        let createdAt = ''
        if (dueTimestamp) {
            createdAt=`ORDER BY p.installation_date ASC`
        }else{
            if(sort==='new'){
                createdAt = `ORDER BY p.id DESC `
            }else if(sort==='old'){
                createdAt = `ORDER BY p.id ASC `
            }else if(sort === 'custom_order'){
                createdAt=`ORDER BY p.card_order ASC`
            }else{
                createdAt=`ORDER BY p.timestamp DESC`
            }
        }
        let whereCondition;
        let query = ''
        // if (all) {
        //     // For Production tab, allow status 2; for other tabs, exclude status 2
        //     if (currentTab === 'Production') {
        //         whereCondition = ` (p.status != 0 AND p.status != 1 AND p.status != 3)`;
        //     } else if (currentTab === 'ALL') {
        //         whereCondition = ` p.status != 0`;
        //     }
        //     else {
        //         whereCondition = ` p.status != 2`;
        //     }
        // } else {
        //     whereCondition = ` p.status = 1`;
        // }
        if (!empty(where)) {

        }

        let tabCondition = '';
if (selectedTab === 'movedToInstalls') {
  tabCondition = ` AND p.status = 3 `;
} else if (selectedTab === 'inProduction') {
  tabCondition = ` AND p.status != 3 `;
}
        if (userType === 1 || userType == 8) {
            // query = await sequelize.query(
            //     ` SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count,com.name AS community_name,c_ord.customer_phone,c_ord.customer_name,c_ord.total FROM projects p `
            //     + ` LEFT JOIN users u ON p.added_by=u.id  `
            //     + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
            //     + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
            //     + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
            //     + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
            //     + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
            //     + ` left join requests req on req.id = p.request_id `
            //     + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
            //     + ` WHERE p.status!=0 AND req.installation_acceptance IS NULL ${dateCondition ? ` AND ${dateCondition}` : ''} ${createdAt} `
            // );
            query = await sequelize.query(
                ` SELECT p.*, 
                         pc.name AS job_category_name, 
                         ptp.name AS job_class_name, 
                         CONCAT(u.first_name, ' ', u.last_name) AS authorized_by, 
                         COALESCE(pm.count, 0) AS member_count, 
                         COALESCE(pt.count, 0) AS task_count, 
                         com.name AS community_name, 
                         c_ord.customer_phone, 
                         c_ord.customer_name, 
                         c_ord.total,
                         inst_counts.installation_count, 
                         total_inst_counts.total_installation_count,
                         cop.product_count, 
                         cop.product_names,
                         rss.service_count,
                         sm.first_name AS sales_rep_first_name,
                         sm.last_name AS sales_rep_last_name,
                         req.est_doc_number,
                         req.doc_number,
                         req.installation_acceptance,
                        CASE 
                            WHEN p.project_category = 12 THEN 
                            CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END
                            WHEN p.project_category = 11 THEN 
                            CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                            WHEN p.project_category = 14 THEN 
                            CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                            ELSE 
                            CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) THEN 1 ELSE 0 END 
                        END AS oldallInstallationCompleted,
                        CASE 
                            WHEN 
                        (
                            (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0))
                            AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)
                        ) OR (
                            COALESCE(total_inst_counts.total_installation_count, 0) <= 0
                            AND p.status = 3 AND p.noServiceNoTask = 0
                        )
                            THEN 1
                            ELSE 0
                        END AS allInstallationCompleted,
                        CASE 
                            WHEN inst_counts.installation_count >= cop.product_count 
                                OR inst_counts.installation_count >= rss.service_count 
                            THEN 1 
                            ELSE 0 
                        END AS veryoldallInstallationCompleted


                  FROM projects p 
                  
                  LEFT JOIN users u ON p.added_by = u.id  
                  LEFT JOIN project_categories pc ON pc.id = p.project_category  
                  LEFT JOIN project_types ptp ON ptp.id = p.project_type  
                  LEFT JOIN (SELECT COUNT(id) AS count, project_id FROM project_members GROUP BY project_id) pm 
                            ON pm.project_id = p.id  
                  LEFT JOIN (SELECT COUNT(ID) AS count, project_id FROM project_tasks WHERE status != 0 GROUP BY project_id) pt 
                            ON pt.project_id = p.id  
                  LEFT JOIN customer_orders c_ord ON c_ord.request_id = p.request_id  
                  LEFT JOIN requests req ON req.id = p.request_id  
                  LEFT JOIN community com ON com.id = p.community 
                                          AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 
                                          AND com.status = 1 
                  
                  -- Join installations to check installation counts
                  LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count 
                             FROM installations WHERE status = 4 GROUP BY request_id) inst_counts 
                            ON inst_counts.request_id = p.request_id  
                  LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count 
                    FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = p.request_id
                  -- Join to get product count for comparison
                  LEFT JOIN (
                      SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, 
                       SUM(
                            CASE
                            WHEN cop.is_single_card = 1 THEN 1
                            ELSE cop.location_quantity
                            END
                        ) AS product_count,
                         GROUP_CONCAT(DISTINCT cop.product_name SEPARATOR ', ') AS product_names
                      FROM customer_orders co
                      JOIN customer_order_products cop ON co.id = cop.order_id
                      JOIN requests req ON co.request_id = req.id
                      WHERE cop.material = 0
                      GROUP BY co.request_id
                  ) cop ON p.request_id = cop.request_id  
            
                  -- Join to get service count for comparison
                  LEFT JOIN (
                      SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                      FROM customer_orders co
                      JOIN  requests rqs ON co.request_id = rqs.id
                      JOIN request_services rss ON co.request_id = rss.request_id
                      JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                      WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                      GROUP BY co.request_id
                  ) rss ON p.request_id = rss.request_id  

                  LEFT JOIN staff_members sm ON sm.id = req.sales_rep_ids
            
                  -- Fetch only projects where installations are NOT complete
                  WHERE p.status != 0 ${tabCondition}
                        AND req.installation_acceptance IS NULL AND req.status !=0 AND p.is_estimate_job=0
                        ${dateCondition ? ` AND ${dateCondition}` : ''} 
                        ${createdAt} `
            );
            
        }
        else if (userType === 3) {
            // query = await sequelize.query(
            //     ` SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count,com.name AS community_name,c_ord.customer_phone, c_ord.customer_name,c_ord.total FROM projects p `
            //     + ` LEFT JOIN users u ON p.added_by=u.id  `
            //     + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
            //     + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
            //     + ` left join request_partners rp on rp.request_id=p.request_id`
            //     + ` left join partners pr on pr.id=rp.partner_id`
            //     + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
            //     + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
            //     + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
            //     + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
            //     + ` where p.status!=0 AND pr.user_id=${userId} ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${createdAt} `
            // );
            query = await sequelize.query(
                ` SELECT p.*, 
                         pc.name AS job_category_name, 
                         ptp.name AS job_class_name, 
                         CONCAT(u.first_name, ' ', u.last_name) AS authorized_by, 
                         COALESCE(pm.count, 0) AS member_count, 
                         COALESCE(pt.count, 0) AS task_count, 
                         com.name AS community_name, 
                         c_ord.customer_phone, 
                         c_ord.customer_name, 
                         c_ord.total,
                         inst_counts.installation_count, 
                         total_inst_counts.total_installation_count,
                         cop.product_count, 
                         cop.product_names,
                         rss.service_count,
                         sm.first_name AS sales_rep_first_name,
                         sm.last_name AS sales_rep_last_name,
                         req.est_doc_number,
                         req.doc_number,
                         req.installation_acceptance,
                        CASE 
                            WHEN p.project_category = 12 THEN 
                            CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END
                            WHEN p.project_category = 11 THEN 
                            CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                            WHEN p.project_category = 14 THEN 
                            CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                            ELSE 
                            CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) THEN 1 ELSE 0 END 
                        END AS oldallInstallationCompleted,
                        CASE 
                            WHEN 
                        (
                            (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0))
                            AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)
                        ) OR (
                            COALESCE(total_inst_counts.total_installation_count, 0) <= 0
                            AND p.status = 3 AND p.noServiceNoTask = 0
                        )
                            THEN 1
                            ELSE 0
                        END AS allInstallationCompleted,
                         CASE 
                             WHEN inst_counts.installation_count >= cop.product_count 
                                  OR inst_counts.installation_count >= rss.service_count 
                             THEN 1 
                             ELSE 0 
                         END AS veryoldallInstallationCompleted
                  FROM projects p 
                  
                  LEFT JOIN users u ON p.added_by = u.id  
                  LEFT JOIN project_categories pc ON pc.id = p.project_category  
                  LEFT JOIN project_types ptp ON ptp.id = p.project_type  
                  LEFT JOIN (SELECT COUNT(id) AS count, project_id FROM project_members GROUP BY project_id) pm 
                            ON pm.project_id = p.id  
                  LEFT JOIN (SELECT COUNT(ID) AS count, project_id FROM project_tasks WHERE status != 0 GROUP BY project_id) pt 
                            ON pt.project_id = p.id  
                  LEFT JOIN customer_orders c_ord ON c_ord.request_id = p.request_id  
                  LEFT JOIN requests req ON req.id = p.request_id  
                  LEFT JOIN community com ON com.id = p.community 
                                          AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 
                                          AND com.status = 1 
            
                  -- Join request_partners and partners to get user_id filter
                  LEFT JOIN request_partners rp ON rp.request_id = p.request_id
                  LEFT JOIN partners pr ON pr.id = rp.partner_id
            
                  -- Join installations to check installation counts
                  LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count 
                             FROM installations WHERE status = 4 GROUP BY request_id) inst_counts 
                            ON inst_counts.request_id = p.request_id  
                LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count 
                    FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = p.request_id
                  -- Join to get product count for comparison
                  LEFT JOIN (
                      SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity,
                       SUM(
                            CASE
                            WHEN cop.is_single_card = 1 THEN 1
                            ELSE cop.location_quantity
                            END
                        ) AS product_count,
                         GROUP_CONCAT(DISTINCT cop.product_name SEPARATOR ', ') AS product_names
                      FROM customer_orders co
                      JOIN customer_order_products cop ON co.id = cop.order_id
                      JOIN requests req ON co.request_id = req.id
                      WHERE cop.material = 0
                      GROUP BY co.request_id
                  ) cop ON p.request_id = cop.request_id  
            
                  -- Join to get service count for comparison
                  LEFT JOIN (
                      SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                      FROM customer_orders co
                      JOIN  requests rqs ON co.request_id = rqs.id
                      JOIN request_services rss ON co.request_id = rss.request_id
                      JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                      WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                      GROUP BY co.request_id
                  ) rss ON p.request_id = rss.request_id  

                  -- Fetch only projects where installations are NOT complete
                  WHERE p.status != 0 ${tabCondition} 
                        AND pr.user_id = ${userId}
                        AND req.installation_acceptance IS NULL AND p.is_estimate_job=0
                        ${dateCondition ? ` AND ${dateCondition}` : ''} 
                        ${createdAt} `
            );
            
        }
        else {
            // query = await sequelize.query(`SELECT p.*,pc.name AS job_category_name,ptp.name AS job_class_name, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count,com.name AS community_name,c_ord.customer_phone, c_ord.customer_name,c_ord.total FROM projects p `
            //     + ` LEFT JOIN staff_members s1 ON s1.id=p.project_lead  `
            //     + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
            //     + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
            //     + ` LEFT JOIN users u1 ON s1.user_id=u1.id `
            //     + ` LEFT JOIN staff_members s2 ON s2.id=p.default_assignee `
            //     + ` LEFT JOIN users u2 ON s2.user_id=u2.id `
            //     + ` LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id from project_members pm left join partners p on p.id=pm.partner_id left join users u on p.user_id=u.id left join staff_members s on s.id=pm.staff_id left join users u2 on s.user_id=u2.id) pmm ON pmm.project_id=p.id and pmm.user_id=${userId} `
            //     + ` LEFT JOIN users u ON p.added_by=u.id `
            //     + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  `
            //     + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  `
            //     + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
            //     + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
            //     + ` WHERE p.status!=0 AND (u1.id = ${userId} or u2.id = ${userId} or pmm.user_id =${userId} ) ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${createdAt} `);
           
            // query = await sequelize.query(
            //     ` SELECT p.*, 
            //              pc.name AS job_category_name, 
            //              ptp.name AS job_class_name, 
            //              CONCAT(u.first_name, ' ', u.last_name) AS authorized_by, 
            //              COALESCE(pm.count, 0) AS member_count, 
            //              COALESCE(pt.count, 0) AS task_count, 
            //              com.name AS community_name, 
            //              c_ord.customer_phone, 
            //              c_ord.customer_name, 
            //              c_ord.total,
            //              inst_counts.installation_count, 
            //              COALESCE(cop.product_count, 0) AS product_count, 
            //              COALESCE(rss.service_count, 0) AS service_count,
            //              CASE 
            //                  WHEN COALESCE(inst_counts.installation_count, 0) >= COALESCE(cop.product_count, 0) 
            //                       OR COALESCE(inst_counts.installation_count, 0) >= COALESCE(rss.service_count, 0) 
            //                  THEN 1 
            //                  ELSE 0 
            //              END AS allInstallationCompleted
            //       FROM projects p 
                  
            //       -- User Information
            //       LEFT JOIN users u ON p.added_by = u.id  
            //       LEFT JOIN staff_members s1 ON s1.id = p.project_lead  
            //       LEFT JOIN users u1 ON s1.user_id = u1.id  
            //       LEFT JOIN staff_members s2 ON s2.id = p.default_assignee  
            //       LEFT JOIN users u2 ON s2.user_id = u2.id  
            
            //       -- Project Categories & Types
            //       LEFT JOIN project_categories pc ON pc.id = p.project_category  
            //       LEFT JOIN project_types ptp ON ptp.id = p.project_type  
            
            //       -- Project Members (Including Staff & Partners)
            //       LEFT JOIN (SELECT pm.project_id, COALESCE(u.id, u2.id) AS user_id 
            //                  FROM project_members pm 
            //                  LEFT JOIN partners p ON p.id = pm.partner_id 
            //                  LEFT JOIN users u ON p.user_id = u.id 
            //                  LEFT JOIN staff_members s ON s.id = pm.staff_id 
            //                  LEFT JOIN users u2 ON s.user_id = u2.id) pmm 
            //                  ON pmm.project_id = p.id AND pmm.user_id = ${userId}  
            
            //       -- Project Counts
            //       LEFT JOIN (SELECT COUNT(id) AS count, project_id FROM project_members GROUP BY project_id) pm 
            //                 ON pm.project_id = p.id  
            //       LEFT JOIN (SELECT COUNT(ID) AS count, project_id FROM project_tasks WHERE status != 0 GROUP BY project_id) pt 
            //                 ON pt.project_id = p.id  
            
            //       -- Customer Orders & Requests
            //       LEFT JOIN customer_orders c_ord ON c_ord.request_id = p.request_id  
            //       LEFT JOIN requests req ON req.id = p.request_id  
            
            //       -- Community
            //       LEFT JOIN community com ON com.id = p.community 
            //                               AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 
            //                               AND com.status = 1  
            
            //       -- Join request_partners and partners to get user_id filter
            //       LEFT JOIN request_partners rp ON rp.request_id = p.request_id
            //       LEFT JOIN partners pr ON pr.id = rp.partner_id
            
            //       -- Join installations to check installation counts
            //       LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count 
            //                  FROM installations WHERE status = 4 GROUP BY request_id) inst_counts 
            //                 ON inst_counts.request_id = p.request_id  
            
            //       -- Join to get product count for comparison
            //       LEFT JOIN (
            //           SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, COUNT(cop.location_quantity) AS product_count
            //           FROM customer_orders co
            //           JOIN customer_order_products cop ON co.id = cop.order_id
            //           WHERE cop.material = 0
            //           GROUP BY co.request_id
            //       ) cop ON p.request_id = cop.request_id  
            
            //       -- Join to get service count for comparison
            //       LEFT JOIN (
            //           SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
            //           FROM customer_orders co
            //           JOIN request_services rss ON co.request_id = rss.request_id
            //           GROUP BY co.request_id
            //       ) rss ON p.request_id = rss.request_id  
            
            //       -- Fetch only projects where installations are NOT complete
            //       WHERE p.status != 0  
            //             AND (pr.user_id = ${userId} OR u1.id = ${userId} OR u2.id = ${userId} OR pmm.user_id = ${userId})  
            //             AND req.installation_acceptance IS NULL
            //             ${dateCondition != '' ? ' AND ' + dateCondition : ''} 
            //             ${createdAt} `
            // );
            
            query = await sequelize.query(`
                SELECT p.*, 
                       pc.name AS job_category_name, 
                       ptp.name AS job_class_name, 
                       CONCAT(u.first_name, ' ', u.last_name) AS authorized_by, 
                       COALESCE(pm.count, 0) AS member_count, 
                       COALESCE(pt.count, 0) AS task_count, 
                       com.name AS community_name, 
                       c_ord.customer_phone, 
                       c_ord.customer_name, 
                       c_ord.total,
                       inst_counts.installation_count, 
                       total_inst_counts.total_installation_count,
                       cop.product_count, 
                       rss.service_count,
                        CASE 
                            WHEN p.project_category = 12 THEN 
                            CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END
                            WHEN p.project_category = 11 THEN 
                            CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                            WHEN p.project_category = 14 THEN 
                            CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                            ELSE 
                            CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) THEN 1 ELSE 0 END 
                        END AS oldallInstallationCompleted,
                        CASE 
                            WHEN 
                            (
                            (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0))
                            AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)
                            ) OR (
                            COALESCE(total_inst_counts.total_installation_count, 0) <= 0
                            AND p.status = 3 AND p.noServiceNoTask = 0
                            )
                            THEN 1
                            ELSE 0
                        END AS allInstallationCompleted,
                       CASE 
                           WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) 
                                OR inst_counts.installation_count >= COALESCE(rss.service_count, 0) 
                           THEN 1 
                           ELSE 0 
                       END AS veryoldallInstallationCompleted
                FROM projects p 
                LEFT JOIN staff_members s1 ON s1.id = p.project_lead  
                LEFT JOIN project_categories pc ON pc.id = p.project_category 
                LEFT JOIN project_types ptp ON ptp.id = p.project_type 
                LEFT JOIN users u1 ON s1.user_id = u1.id 
                LEFT JOIN staff_members s2 ON s2.id = p.default_assignee 
                LEFT JOIN users u2 ON s2.user_id = u2.id 
                LEFT JOIN (SELECT pm.project_id, COALESCE(u.id, u2.id) AS user_id 
                           FROM project_members pm 
                           LEFT JOIN partners p ON p.id = pm.partner_id 
                           LEFT JOIN users u ON p.user_id = u.id 
                           LEFT JOIN staff_members s ON s.id = pm.staff_id 
                           LEFT JOIN users u2 ON s.user_id = u2.id) pmm 
                       ON pmm.project_id = p.id AND pmm.user_id = ${userId} 
                LEFT JOIN users u ON p.added_by = u.id 
                LEFT JOIN (SELECT COUNT(id) AS count, project_id FROM project_members GROUP BY project_id) pm 
                       ON pm.project_id = p.id  
                LEFT JOIN (SELECT COUNT(ID) AS count, project_id FROM project_tasks WHERE status != 0 GROUP BY project_id) pt 
                       ON pt.project_id = p.id  
                LEFT JOIN customer_orders c_ord ON c_ord.request_id = p.request_id 
                LEFT JOIN community com ON com.id = p.community 
                                         AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 
                                         AND com.status = 1
            
                -- Join to check installation counts
                LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count 
                           FROM installations WHERE status = 4 GROUP BY request_id) inst_counts 
                       ON inst_counts.request_id = p.request_id  
                LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count 
                    FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = p.request_id
                -- Join to get product count for comparison
                LEFT JOIN (SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, 
                            SUM(
                                    CASE
                                    WHEN cop.is_single_card = 1 THEN 1
                                    ELSE cop.location_quantity
                                    END
                                ) AS product_count
                           FROM customer_orders co
                           JOIN customer_order_products cop ON co.id = cop.order_id
                           JOIN requests req ON co.request_id = req.id
                           WHERE cop.material = 0
                           GROUP BY co.request_id) cop 
                       ON p.request_id = cop.request_id  
            
                -- Join to get service count for comparison
                LEFT JOIN (SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                           FROM customer_orders co
                           JOIN  requests rqs ON co.request_id = rqs.id
                           JOIN request_services rss ON co.request_id = rss.request_id
                           JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                           WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                           GROUP BY co.request_id) rss 
                       ON p.request_id = rss.request_id  
            
                WHERE p.status != 0 ${tabCondition} AND p.is_estimate_job=0
                      AND (u1.id = ${userId} OR u2.id = ${userId} OR pmm.user_id = ${userId}) 
                      ${dateCondition !== '' ? ` AND ${dateCondition}` : ''} 
                      ${createdAt}
            `);
            
            
            
        }
        console.log("$$#################hifiiiiiiiiiiiiii");
        let data;
        if (query.length > 0) {
            data = query[0];
            if (userType == 1 || userType == 8) {
                const results = await Promise.all(data.map(async (item) => {

                    let selectedMaterials = await JobCost.fetchAllJobCostProjectId(item.id);
                    let price = selectedMaterials?.filter(curr => curr.taken === 1)?.reduce((total, currentItem) => { return total + currentItem.total }, 0);
                    let payout = await JobCost.fetchAllPayOutByProjectId(item.id, userId);
                    let services = await Request.getAllServiceByRequest(item.request_id);
                    let serviceExpense = services?.filter(curr => curr.taken === 1)?.reduce((total, currentItem) => { return total + (currentItem.qty * currentItem.originalCost) }, 0);
                    let payoutPrice = payout.reduce((total, currentItem) => total + currentItem.amount, 0);

                    let expense = price + payoutPrice + Math.max(0, (serviceExpense - payoutPrice))
                    const parsedCost = parseFloat(item.cost) || 0;
                    if (Number(item.status) === 1 || parsedCost <= 0) {
                        item.progressValue = 0;
                    } else {
                        item.progressValue = (expense / parsedCost) * 100
                        if (item.progressValue > 100) {
                            item.progressValue = 100
                        }
                    }
                    let image = await Request.FetchAllApprovedDesigns(item.request_id);
                    image = image?.filter((imageItem)=>imageItem?.file_type?.startsWith('image/') || imageItem?.file_type ==='img')
                    if (!empty(image[0])) {
                        item.cover_image = image[0].name ? image[0].name : ""
                    }
                    else {
                        item.cover_image = ""
                    }

                    return item;
                }));
                // return results;
                return results.map(record => parseDecimalFields(record));
            } else {
                const results = await Promise.all(data.map(async (item) => {
                    let image = await Request.FetchAllApprovedDesigns(item.request_id);
                    image = image?.filter((imageItem)=>imageItem?.file_type?.startsWith('image/') || imageItem?.file_type ==='img')
                    if (!empty(image[0])) {
                        item.cover_image = image[0].name ? image[0].name : ""
                    }
                    else {
                        item.cover_image = ""
                    }

                    return item;
                }));
                return results?.map(record => parseDecimalFields(record));
            }


        } else {
            return false;
        }
    } catch (error) {
        console.log(error);
        throw new Error("Server error");
    }
}

const addProject = async (data) => {
    try {
        let results = await Projects.create(data)
        if (results) {
            return results;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.error("Error adding the projects ", error);
        return false;
    }
}
const addEstimateProject = async (data) => {
    try {
        let results = await EstimateProjects.create(data)
        if (results) {
            return results;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.error("Error adding the estimate projects ", error);
        return false;
    }
}

// const isProjectNameExist = async (name, projectId = 0) => {
//     let whereCondition = "";
//     if (projectId !== 0) {
//         whereCondition = `  and p.id!=${projectId}`
//     }
//     let query = await sequelize.query(`select id,p.name from projects p  where p.name like "${name}" ${whereCondition}`);

//     if (query[0]?.length >= 1) {
//         return true;
//     } else {
//         return false;
//     }
// }

const isProjectNameExist = async (name, projectId = 0) => {
    try {
      let whereCondition = '';
      const replacements = { nameLike: name };
  
      if (projectId !== 0) {
        whereCondition = 'AND p.id != :projectId';
        replacements.projectId = projectId;
      }
  
      const query = `
        SELECT id, p.name
        FROM projects p
        WHERE p.name = :nameLike ${whereCondition}
      `;
  
      const result = await sequelize.query(query, {
        replacements,
        type: sequelize.QueryTypes.SELECT,
      });
  
      return result.length >= 1;
    } catch (error) {
      console.error('Error checking project name existence:', error);
      return false;
    }
  };
  

const doUpload = async (file, filename) => {
    await pump(file, fs.createWriteStream(`./build/images/projects/${filename}`));
    return true
}

const updateProject = async (projId, data) => {
    try {
        // Refresh timestamp on every project update so
        // "Recently updated" sorting reflects status changes.
        const nowTs = Math.floor(Date.now() / 1000);
        const updatePayload = {
            ...data,
            timestamp: nowTs,
        };

        const updatedRows = await Projects.update(updatePayload, {
            where: {
                id: projId
            },
            returning: true,
        });
        if (updatedRows) {
            if (updatedRows[1] > 0) {
                return true;
            }
            else {
                return false;
            }
        }
    }
    catch (error) {
        console.error("Error updating job:", error);
        return false;
    }
}
const updateEstimateProject = async (projId, data) => {
    try {
        const updatedRows = await EstimateProjects.update(data, {
            where: {
                id: projId
            },
            returning: true,
        });
        if (updatedRows) {
            if (updatedRows[1] > 0) {
                return true;
            }
            else {
                return false;
            }
        }
    }
    catch (error) {
        console.error("Error updating job:", error);
        return false;
    }
}

const updateProjectByRequestId = async (requestId, data) => {
  try {
    const [affectedCount] = await Projects.update(data, {
      where: { request_id: requestId }
    });
    return affectedCount > 0;
  } catch (error) {
    console.error("Error updating project by request_id:", error);
    return false;
  }
};

/** Update only the estimate job row (projects.is_estimate_job = 1) for a request */
const updateEstimateJobProjectByRequestId = async (requestId, data) => {
  try {
    const [affectedCount] = await Projects.update(data, {
      where: { request_id: requestId, is_estimate_job: 1 }
    });
    return affectedCount > 0;
  } catch (error) {
    console.error("Error updating estimate job project by request_id:", error);
    return false;
  }
};

/** Update hold status of the estimate job project (projects table, is_estimate_job=1) for a request */
const updateEstimateJobHoldByRequestId = async (requestId, hold) => {
  try {
    const [affectedCount] = await Projects.update(
      { hold: hold ? 1 : 0 },
      { where: { request_id: requestId, is_estimate_job: 1 } }
    );
    return affectedCount > 0;
  } catch (error) {
    console.error("Error updating estimate job hold by request_id:", error);
    return false;
  }
};

const updateEstimateProjectByRequestId = async (requestId, data) => {
  try {
    const [affectedCount] = await EstimateProjects.update(data, {
      where: { request_id: requestId }
    });
    return affectedCount > 0;
  } catch (error) {
    console.error("Error updating project by request_id:", error);
    return false;
  }
};

const getAllMemberUserIdsByProjectId = async (projectId) => {
    try {
      const result = await sequelize.query(`
        SELECT sm.user_id
        FROM project_members pm
        LEFT JOIN staff_members sm ON pm.staff_id = sm.id
        WHERE pm.project_id = ${projectId} AND sm.user_id IS NOT NULL
      `);
  
      if (result[0].length >= 1) {
        const userIds = result[0].map(row => row.user_id.toString());
        return userIds;
      } else {
        return [];
      }
    } catch (error) {
      console.error("Error fetching user_ids from project_members:", error);
      return [];
    }
  };
  
  

const deleteProject = async (projId, projStatus = 0) => {
    try {
        const deleted = await Projects.destroy({
            where: {
                id: projId
            },
        });
        if (deleted) {
            return true;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
        return false;
    }
}
const deleteEstimateProject = async (projId, projStatus = 0) => {
    try {
        const deleted = await EstimateProjects.destroy({
            where: {
                id: projId
            },
        });
        if (deleted) {
            return true;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
        return false;
    }
}
const deleteProjectMember = async (id, projStatus = 0) => {
    try {
        const deleted = await ProjectMembers.destroy({
            where: {
                id: id
            },
        });

        if (deleted) {
            return deleted;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
    }
}
const deleteAllProjectMember = async (id, projStatus = 0) => {
    try {
        const deleted = await ProjectMembers.destroy({
            where: {
                project_id: id
            },
        });

        if (deleted) {
            return deleted;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
    }
}
const deleteEstimateProjectMember = async (id, projStatus = 0) => {
    try {
        const deleted = await EstimateProjectMembers.destroy({
            where: {
                id: id
            },
        });

        if (deleted) {
            return deleted;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
    }
}
const deleteAllEstimateProjectMember = async (id, projStatus = 0) => {
    try {
        const deleted = await EstimateProjectMembers.destroy({
            where: {
                project_id: id
            },
        });

        if (deleted) {
            return deleted;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
    }
}
const getAllProjectCategories = async (all = false, where = []) => {
    let whereCondition = "";
    if (all) {
        whereCondition = " where p.status!=2";
    }
    else {
        whereCondition = " where p.status=1";
    }
    let query = await sequelize.query(`select p.*, concat(u.first_name,' ',u.last_name) as authorized_by from project_categories p `
        + ` left join users u on p.added_by=u.id `
        + ` ${whereCondition} order by p.name asc`)
    let data;
    if (query[0].length > 0) {
        data = query[0];
        return data;
    } else {
        return [];
    }
}
const getAllNoChargeTypes = async (all = false, where = []) => {
    let whereCondition = "";
    if (all) {
        whereCondition = " where p.status!=2";
    }
    else {
        whereCondition = " where p.status=1";
    }
    let query = await sequelize.query(`select p.*, concat(u.first_name,' ',u.last_name) as authorized_by from no_charge_type p `
        + ` left join users u on p.added_by=u.id `
        + ` ${whereCondition} order by p.name asc`)
    let data;
    if (query[0].length > 0) {
        data = query[0];
        return data;
    } else {
        return [];
    }
}
const getAllProjectTypes = async (all = false, where = []) => {
    let whereCondition = "";
    if (all) {
        whereCondition = " where p.status!=2";
    }
    else {
        whereCondition = " where p.status=1";
    }
    let query = await sequelize.query(`select p.*, concat(u.first_name,' ',u.last_name) as authorized_by from project_types p `
        + ` left join users u on p.added_by=u.id `
        + ` ${whereCondition} order by p.name asc`)
    let data = [];

    if (query[0].length > 0) {
        data = query[0];

    }

    return data;
}
const getAllStates = async (all = false, where = []) => {
    let whereCondition = "";
    if (all) {
        whereCondition = " where s.status!=2";
    }
    else {
        whereCondition = " where s.status=1";
    }
    let query = await sequelize.query(`select s.* from states s `
        + ` ${whereCondition} order by s.id asc`)
    let data = [];

    if (query[0].length > 0) {
        data = query[0];

    }

    return data;
}
const acceptedRequests = async (id = null) => {
    let query = await sequelize.query(`SELECT r.*,rp.id as rt_partner_id FROM requests r
    LEFT JOIN projects p ON r.id = p.request_id
    JOIN request_partners rp ON rp.request_id=r.id
    WHERE p.request_id IS NULL and r.status=3 or r.id=${id}`);
    let data = [];

    if (query[0].length > 0) {
        data = query[0];

    }

    return data;
}
const isProjectTypeExist = async (name, projectId = 0) => {
    let whereCondition = "";
    if (projectId !== 0) {
        whereCondition = `  and p.id!=${projectId}`
    }
    let query = await sequelize.query(`select id,p.name from project_types p  where p.name like '${name}' ${whereCondition}`);

    if (query[0].length >= 1) {
        return true;
    } else {
        return false;
    }
}
const addProjectType = async (data) => {

    try {

        let results = await ProjectTypes.create(data)
        if (results) {
            return results.id;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.error("Error adding the projects ", error);
        return false;
    }
}
const getProjectTypeById = async (id) => {
    try {
        let query = await sequelize.query(`SELECT p.*, concat(u.first_name,' ',u.last_name) as authorized_by FROM project_types p`
            + ` LEFT JOIN users u ON p.added_by=u.id `
            + ` WHERE p.id = ${id} and p.status!=2`

        );

        if (query[0].length === 1) {
            return query[0][0];
        } else {
            return false;
        }

    } catch (error) {
        console.log(error);
        throw new Error("Server error");
    }
}
const updateProjectType = async (data, id) => {
    let res = await ProjectTypes.update(data, { where: { id: id } });
    return res[0] ? true : false;
}
const deleteProjectType = async (id, status = 0) => {

    try {
        const deleted = await ProjectTypes.destroy({
            where: {
                id: id
            },
        });

        if (deleted) {
            return deleted;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
    }
}
const isProjectCategoryExist = async (name, projectId = 0) => {
    let whereCondition = "";
    if (projectId !== 0) {
        whereCondition = `  and p.id!=${projectId}`
    }
    let query = await sequelize.query(`select id,p.name from project_categories p  where p.name like '${name}' ${whereCondition}`);

    if (query[0].length >= 1) {
        return true;
    } else {
        return false;
    }
}
const isNoChargeTypeExist = async (name, projectId = 0) => {
    let whereCondition = "";
    if (projectId !== 0) {
        whereCondition = `  and p.id!=${projectId}`
    }
    let query = await sequelize.query(`select id,p.name from no_charge_type p  where p.name like '${name}' ${whereCondition}`);

    if (query[0].length >= 1) {
        return true;
    } else {
        return false;
    }
}
const addProjectCategory = async (data) => {

    try {

        let results = await ProjectCategory.create(data)
        if (results) {
            return results.id;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.error("Error adding the projects ", error);
        return false;
    }
}
const addNoChargeType = async (data) => {

    try {

        let results = await NoChargeType.create(data)
        if (results) {
            return results.id;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.error("Error adding the projects ", error);
        return false;
    }
}
const getProjectCategoryById = async (id) => {
    try {
        let query = await sequelize.query(`SELECT p.*, concat(u.first_name,' ',u.last_name) as authorized_by FROM  project_categories p`
            + ` LEFT JOIN users u ON p.added_by=u.id `
            + ` WHERE p.id = ${id} and p.status!=2`

        );

        if (query[0].length === 1) {
            return query[0][0];
        } else {
            return false;
        }

    } catch (error) {
        console.log(error);
        throw new Error("Server error");
    }
}
const getNoChargeTypeById = async (id) => {
    try {
        let query = await sequelize.query(`SELECT p.*, concat(u.first_name,' ',u.last_name) as authorized_by FROM  no_charge_type p`
            + ` LEFT JOIN users u ON p.added_by=u.id `
            + ` WHERE p.id = ${id} and p.status!=2`

        );

        if (query[0].length === 1) {
            return query[0][0];
        } else {
            return false;
        }

    } catch (error) {
        console.log(error);
        throw new Error("Server error");
    }
}
const updateProjectCategory = async (data, id) => {
    let res = await ProjectCategory.update(data, { where: { id: id } });
    return res[0] ? true : false;
}
const updateNoChargeType = async (data, id) => {
    let res = await NoChargeType.update(data, { where: { id: id } });
    return res[0] ? true : false;
}
const deleteProjectCategory = async (id, status = 0) => {

    try {
        const deleted = await ProjectCategory.destroy({
            where: {
                id: id
            },
        });

        if (deleted) {
            return deleted;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
    }
}
const deleteNoChargeType = async (id, status = 0) => {

    try {
        const deleted = await NoChargeType.destroy({
            where: {
                id: id
            },
        });

        if (deleted) {
            return deleted;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
    }
}
const getAllTeam = async (id) => {
    let query = await sequelize.query("SELECT pm.*, coalesce(p.name, concat(s.first_name, ' ', coalesce(s.last_name, ''))) as name, coalesce(u.profile_pic, u2.profile_pic) as profile_pic, coalesce(u.email, u2.email) as email, coalesce(u.id, u2.id) as userid, (case when pm.partner_id is not null then 'Client' else 'Team' end) as user_role_name, ur.name as user_role, coalesce(pt.count, 0) as task_count FROM project_members pm "
        + " LEFT JOIN partners p ON p.id=pm.partner_id "
        + " LEFT JOIN users u ON p.user_id=u.id "
        + " LEFT JOIN staff_members s ON s.id=pm.staff_id "
        + " LEFT JOIN users u2 ON s.user_id=u2.id "
        + " LEFT JOIN user_roles ur ON ur.id=u2.user_type"
        + " LEFT JOIN (select count(ptm.ID) as count, ptm.partner_id, ptm.staff_id from project_task_members ptm "
        + " left join project_tasks pt on pt.ID=ptm.task_id "
        + ` where pt.status!=0 and pt.project_id=${id} group by ptm.partner_id, ptm.staff_id) pt ON pt.partner_id=pm.partner_id or pt.staff_id=pm.staff_id`
        + ` WHERE pm.project_id =${id} ORDER BY pm.id DESC`)
    let data = []
    if (query[0].length > 0) {
        data = query[0].filter(row => !empty(row.name))
    }
    return data;
}
const getTeamMembers = async (userType, all = false) => {
    let whereCondition = ""
    if (all) {
        whereCondition = "sm.status!=2";
    }
    else {
        whereCondition = "sm.status=1";
    }
    let query = await sequelize.query(`select sm.id,u.id as user_id,concat(sm.first_name,' ',coalesce(sm.last_name,'')) as name,ur.name AS role from staff_members sm `
        + ` left join users u on u.id=sm.user_id`
        + ` left join user_roles ur on ur.id=u.user_type`
        + ` where u.user_type=${userType} order by sm.id DESC`)
    let data = [];

    if (query[0].length > 0) {
        data = query[0];

    }

    return data;
}
const getTeamMembersBasedOnSkills = async (skills, userType, all = false) => {
    let whereCondition = ""
    if (all) {
        whereCondition = "sm.status!=2";
    }
    else {
        whereCondition = "sm.status=1";
    }
    if (skills) {
        // whereCondition += ` and sm.services in (${skills}) or u.user_type=${userType}`
        let skillsCondition = skills.split(',').map(skill => `FIND_IN_SET(${skill}, sm.services)`).join(' OR ');
        whereCondition += ` AND (${skillsCondition}) `;
        // whereCondition += ` AND (${skillsCondition}) or u.user_type = ${userType}`;
    }
    else {
        // whereCondition += ` and u.user_type=${userType}`
        
    }

    let query = await sequelize.query(`select sm.id,u.id as user_id,concat(sm.first_name,' ',coalesce(sm.last_name,'')) as name from staff_members sm `
        + ` left join users u on u.id=sm.user_id`
        + ` where ${whereCondition} order by sm.id DESC`)
    let data = [];

    if (query[0].length > 0) {
        data = query[0];

    }
    console.log("##############", data);
    return data;
}

const getDesignTeamMembersBasedOnSkills = async (skills) => {
    if (!skills) {
      return []; 
    }
  
    const skillsCondition = skills
      .split(',')
      .map(skill => `FIND_IN_SET(${skill}, sm.services)`)
      .join(' OR ');
  
        const query = await sequelize.query(
            `SELECT sm.id, 
                    u.id AS user_id, 
                    sm.email, 
                    sm.phone,
                    sm.phone_country_code, 
                    u.smsEnabled, 
                    u.emailEnabled, 
                    CONCAT(sm.first_name, ' ', COALESCE(sm.last_name, '')) AS name,
                    CASE WHEN FIND_IN_SET(14, u.pcb_item_order) > 0 THEN 1 ELSE 0 END AS pcb_new_design_jobs,
                    COALESCE((SELECT pcb_email_enabled FROM user_pcb_preferences WHERE user_id = sm.user_id AND pcb_item_id = 14 AND status != 0 LIMIT 1), 0) AS pcb_new_design_jobs_email,
                    COALESCE((SELECT pcb_sms_enabled FROM user_pcb_preferences WHERE user_id = sm.user_id AND pcb_item_id = 14 AND status != 0 LIMIT 1), 0) AS pcb_new_design_jobs_sms,
                    CASE WHEN FIND_IN_SET(17, u.pcb_item_order) > 0 THEN 1 ELSE 0 END AS view_design_permission
            FROM staff_members sm
            LEFT JOIN users u ON u.id = sm.user_id
            LEFT JOIN user_roles ur ON ur.id = u.user_type
            WHERE sm.status = 1 
                AND (${skillsCondition}) 
                AND u.user_type = 11
            ORDER BY sm.id DESC`
        );
            
    return query[0] || [];
  };

    const getEstimators = async (estimator_id, all = false) => {
        try{
            let whereCondition = "";

            // Determine status condition based on 'all' flag
            if (all) {
                whereCondition = "sm.status != 2";
            } else {
                whereCondition = "sm.status = 1";
            }

            // If estimator_id is provided, construct the condition for filtering estimators
            if (estimator_id) {
                const estimatorIds = estimator_id.split(',').map(est => `'${est.trim()}'`); // Ensure IDs are treated as strings
                let estimatorCondition = `sm.id IN (${estimatorIds.join(',')})`; // Use 'IN' for better readability
                whereCondition += ` AND (${estimatorCondition})`;
            }

            // Build the query
            const query = await sequelize.query(`
                SELECT sm.id, u.id AS user_id, CONCAT(sm.first_name, ' ', COALESCE(sm.last_name, '')) AS name 
                FROM staff_members sm
                LEFT JOIN users u ON u.id = sm.user_id
                WHERE ${whereCondition}
                ORDER BY sm.id DESC
            `);

            // Return the result
            return query[0] || []; // Return an empty array if no results found
        }catch(error){
            console.log('getEstimators error', error)
            throw error; // Optional: Re-throw the error or handle accordingly
        }
    };

    const getAllDesignTeamMembers = async () => {
    const query = await sequelize.query(
        `SELECT 
            sm.id, 
            u.id AS user_id,
            sm.phone, 
            u.smsEnabled, 
            u.emailEnabled, 
            u.email,
            CONCAT(sm.first_name, ' ', COALESCE(sm.last_name, '')) AS name,
            CASE WHEN FIND_IN_SET(14, u.pcb_item_order) > 0 THEN 1 ELSE 0 END AS pcb_new_design_jobs,
            COALESCE((SELECT pcb_email_enabled FROM user_pcb_preferences WHERE user_id = sm.user_id AND pcb_item_id = 14 AND status != 0 LIMIT 1), 0)           AS pcb_new_design_jobs_email,
            COALESCE((SELECT pcb_sms_enabled FROM user_pcb_preferences WHERE user_id = sm.user_id AND pcb_item_id = 14 AND status != 0 LIMIT 1), 0)             AS pcb_new_design_jobs_sms,
            CASE WHEN FIND_IN_SET(17, u.pcb_item_order) > 0 THEN 1 ELSE 0 END AS view_design_permission
        FROM staff_members sm
        LEFT JOIN users u ON u.id = sm.user_id
        LEFT JOIN user_roles ur ON ur.id = u.user_type
        WHERE sm.status = 1 
        AND u.user_type = 11
        ORDER BY sm.id DESC`
    );

    return query[0] || [];
    };
    const getAllEstimateTeamMembers = async () => {
    const query = await sequelize.query(
        `SELECT 
            sm.id, 
            u.id AS user_id,
            sm.phone, 
            u.smsEnabled, 
            u.emailEnabled, 
            u.email,
            CONCAT(sm.first_name, ' ', COALESCE(sm.last_name, '')) AS name,
            CASE WHEN FIND_IN_SET(14, u.pcb_item_order) > 0 THEN 1 ELSE 0 END AS pcb_new_design_jobs,
            COALESCE((SELECT pcb_email_enabled FROM user_pcb_preferences WHERE user_id = sm.user_id AND pcb_item_id = 14 AND status != 0 LIMIT 1), 0)           AS pcb_new_design_jobs_email,
            COALESCE((SELECT pcb_sms_enabled FROM user_pcb_preferences WHERE user_id = sm.user_id AND pcb_item_id = 14 AND status != 0 LIMIT 1), 0)             AS pcb_new_design_jobs_sms,
            CASE WHEN FIND_IN_SET(17, u.pcb_item_order) > 0 THEN 1 ELSE 0 END AS view_design_permission
        FROM staff_members sm
        LEFT JOIN users u ON u.id = sm.user_id
        LEFT JOIN user_roles ur ON ur.id = u.user_type
        WHERE sm.status = 1 
        AND u.user_type = 18
        ORDER BY sm.id DESC`
    );

    return query[0] || [];
    };

    const getAllTeamMembersForEmail = async () => {
        const query = await sequelize.query(
            `SELECT 
                sm.id, 
                u.id AS user_id,
                u.profile_pic,
                sm.first_name,
                sm.last_name,
                sm.phone, 
                u.smsEnabled, 
                u.emailEnabled, 
                u.email,
                CONCAT(sm.first_name, ' ', COALESCE(sm.last_name, '')) AS name
            FROM staff_members sm
            LEFT JOIN users u ON u.id = sm.user_id
            LEFT JOIN user_roles ur ON ur.id = u.user_type
            WHERE sm.status = 1 
            AND u.user_type != 3
            AND u.email IS NOT NULL
            AND u.email != ''
            ORDER BY sm.id DESC`
        );

        return query[0] || [];
    };
  
  
const addProjectMember = async (data) => {
    try {
        console.log("$$$$$$$$$$$nnn", data);
        let results = await ProjectMembers.create(data)
        if (results) {
            return results;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.error("Error adding the projects ", error);
        return false;
    }
}
const getAllProjectMembers = async (id) => {
    let query = await sequelize.query(`SELECT pm.*, coalesce(p.name, concat(s.first_name, ' ', coalesce(s.last_name, ''))) as name,s.first_name,s.last_name, coalesce(u.profile_pic, u2.profile_pic) as profile_pic, `
        + ` coalesce(u.email, u2.email) as email,u2.id as userId,s.hourly_rate, coalesce(u.id, u2.id) as userid, (case when pm.partner_id is not null then 'Client' else 'Team' end) as user_role_name, ur.name as user_role,`
        + ` coalesce(pt.count, 0) as task_count FROM project_members pm `
        + ` LEFT JOIN partners p ON p.id=pm.partner_id `
        + ` LEFT JOIN users u ON p.user_id=u.id `
        + ` LEFT JOIN staff_members s ON s.id=pm.staff_id `
        + ` LEFT JOIN users u2 ON s.user_id=u2.id `
        + ` LEFT JOIN user_roles ur ON ur.id=u2.user_type `
        + ` LEFT JOIN (select count(ptm.ID) as count, ptm.partner_id, ptm.staff_id from project_task_members ptm left join project_tasks pt on pt.ID=ptm.task_id where pt.status!=0 and pt.project_id=50 group by ptm.partner_id, ptm.staff_id) pt ON pt.partner_id=pm.partner_id or pt.staff_id=pm.staff_id `
        + ` WHERE pm.project_id =${id} GROUP BY pm.staff_id ORDER BY pm.id DESC `)
    let data = [];

    if (query[0].length > 0) {
        data = query[0];

    }

    return data;
}
const addEstimateProjectMember = async (data) => {
    try {
        console.log("$$$$$$$$$$$nnn", data);
        let results = await EstimateProjectMembers.create(data)
        if (results) {
            return results;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.error("Error adding the projects ", error);
        return false;
    }
}
const getAllEstimateProjectMembers = async (id) => {
    let query = await sequelize.query(`SELECT pm.*, coalesce(p.name, concat(s.first_name, ' ', coalesce(s.last_name, ''))) as name,s.first_name,s.last_name, coalesce(u.profile_pic, u2.profile_pic) as profile_pic, `
        + ` coalesce(u.email, u2.email) as email,u2.id as userId,s.hourly_rate, coalesce(u.id, u2.id) as userid, (case when pm.partner_id is not null then 'Client' else 'Team' end) as user_role_name, ur.name as user_role,`
        + ` coalesce(pt.count, 0) as task_count FROM estimate_project_members pm `
        + ` LEFT JOIN partners p ON p.id=pm.partner_id `
        + ` LEFT JOIN users u ON p.user_id=u.id `
        + ` LEFT JOIN staff_members s ON s.id=pm.staff_id `
        + ` LEFT JOIN users u2 ON s.user_id=u2.id `
        + ` LEFT JOIN user_roles ur ON ur.id=u2.user_type `
        + ` LEFT JOIN (select count(ptm.ID) as count, ptm.partner_id, ptm.staff_id from estimate_project_task_members ptm left join estimate_project_tasks pt on pt.ID=ptm.task_id where pt.status!=0 and pt.project_id=50 group by ptm.partner_id, ptm.staff_id) pt ON pt.partner_id=pm.partner_id or pt.staff_id=pm.staff_id `
        + ` WHERE pm.project_id =${id} GROUP BY pm.staff_id ORDER BY pm.id DESC `)
    let data = [];

    if (query[0].length > 0) {
        data = query[0];

    }

    return data;
}

const projectMembersForMessaging = async (requestId) => {
  const query = await sequelize.query(`
    SELECT 
      s.id,
      CONCAT(s.first_name, ' ', COALESCE(s.last_name, '')) AS name,
      0 AS isVendor, 
      s.user_id,
      NULL AS accept_status,
      u2.profile_pic,
      u2.user_type,
      'Y' AS active,
      0 AS rating,
      0 AS no_of_reviews
    FROM project_members pm
    LEFT JOIN projects p ON p.id = pm.project_id
    LEFT JOIN staff_members s ON s.id = pm.staff_id
    LEFT JOIN users u2 ON s.user_id = u2.id
    WHERE p.request_id = ${requestId}
  `);

  return query[0] || [];
};

const DriverForMessaging = async (requestId) => {
  const query = await sequelize.query(`
    SELECT 
      d.id,
      d.name,
      0 AS isVendor,
      d.user_id,
      NULL AS accept_status,
      u.profile_pic,
      u.user_type,
      'Y' AS active,
      0 AS rating,
      0 AS no_of_reviews
    FROM installations i
    LEFT JOIN driver d ON d.id = i.driver_id
    LEFT JOIN users u ON d.user_id = u.id
    WHERE i.request_id = ${requestId}
    GROUP BY d.id
  `);

  return query[0] || [];
};

const InstallersForMessaging = async (requestId) => {
  const query = await sequelize.query(`
    SELECT 
      s.id,
      CONCAT(u.first_name, ' ', COALESCE(u.last_name, '')) AS name,
      0 AS isVendor,
      u.id AS user_id,
      NULL AS accept_status,
      u.profile_pic,
      u.user_type,
      'Y' AS active,
      0 AS rating,
      0 AS no_of_reviews
    FROM installations i
    LEFT JOIN users u ON u.id = i.team_id
    LEFT JOIN staff_members s ON s.user_id = u.id
    WHERE i.request_id = ${requestId}
    GROUP BY u.id
  `);

  return query[0] || [];
};
const AdminsForMessaging = async (excludeUserId) => {
  const query = await sequelize.query(`
    SELECT 
      s.id,
      CONCAT(u.first_name, ' ', COALESCE(u.last_name, '')) AS name,
      0 AS isVendor,
      u.id AS user_id,
      NULL AS accept_status,
      u.profile_pic,
      u.user_type,
      'Y' AS active,
      0 AS rating,
      0 AS no_of_reviews
    FROM users u
    LEFT JOIN staff_members s ON s.user_id = u.id
    WHERE u.user_type IN (1, 8)
    GROUP BY u.id
  `);

  return query[0] || [];
};
const AdminsForMessagingNew = async (excludeUserId = null) => {
    let whereCondition = '';
    const replacements = {};
  
    // if (excludeUserId) {
    //   whereCondition = ' AND u.id != :excludeUserId';
    //   replacements.excludeUserId = excludeUserId;
    // }
  
    const query = await sequelize.query(`
      SELECT 
        s.id,
        CONCAT(u.first_name, ' ', COALESCE(u.last_name, '')) AS name,
        0 AS isVendor,
        u.id AS user_id,
        NULL AS accept_status,
        u.profile_pic,
        u.user_type,
        'Y' AS active,
        0 AS rating,
        0 AS no_of_reviews
      FROM users u
      LEFT JOIN staff_members s ON s.user_id = u.id
      WHERE u.user_type IN (1, 8)
        ${whereCondition}
      GROUP BY u.id
    `, {
      replacements,
      type: sequelize.QueryTypes.SELECT
    });
  
    return query || [];
  };
  

const fetchAllAttachments = async (id) => {
    let query = await sequelize.query(`select p.*, concat(u.first_name,' ',u.last_name) as authorized_by from project_files p`
        + ` left join users u on p.userid=u.id`
        + ` where p.project_id=${id} order by p.id DESC`)
    let data = [];

    if (query[0].length > 0) {
        data = query[0];

    }

    return data;
}
const fetchAllTeamMembers = async (all = false) => {
    let whereCondition = ""
    if (all) {
        whereCondition = "p.status!=2";
    }
    else {
        whereCondition = "p.status=1";
    }
    let query = await sequelize.query(`SELECT DISTINCT p.id, concat(p.first_name, ' ', coalesce(p.last_name, '')) as name FROM staff_members p`
        + ` where ${whereCondition} order by p.id DESC`)
    let data = [];

    if (query[0].length > 0) {
        data = query[0];

    }

    return data;
}
const fetchprojectsByClientId = async (id) => {
    let result = await sequelize.query(`
    select p.id as id ,p.name as name, p.request_id as request_id from projects as p
    left join request_partners rp on rp.request_id = p.request_id WHERE rp.partner_id = ${id}`)

    if (result[0].length > 0) {
        return result[0]
    } else {
        return []
    }
}

const fetchprojectsByTeamId = async (id) => {
    let result = await sequelize.query(`
    select p.*, pc.name AS project_category_name from projects p
    left join project_members pm on pm.project_id = p.id
    LEFT JOIN project_categories pc ON pc.id=p.project_category
    join requests r on r.id = p.request_id
    WHERE pm.staff_id = ${id}`)

    if (result[0].length > 0) {
        return result[0]
    } else {
        return []
    }
}
const fetchDesignOrdersByTeamId = async (staffId) => {
  const result = await sequelize.query(`
    SELECT do.*, 
           do.name AS design_order_name
    FROM design_orders do
    LEFT JOIN design_order_project_members dop ON dop.design_order_id = do.id
    WHERE dop.staff_id = ${staffId}
  `);

  return result[0].length > 0 ? result[0] : [];
};

const projectMemberExist = async (data) => {
    let query = await sequelize.query(` select staff_id from project_members where staff_id=${data.staff_id} and project_id=${data.project_id}`)
    console.log("HIIIIIIIIIIIIIII", query[0].length);
    if (query[0].length > 0) {
        return true
    } else {
        return false
    }
}
// const completedInstallations = async () => {
//     let query = await sequelize.query(` 
//     SELECT p.*, i.*, r.*, co.*, cp.*
//     FROM projects p
//     LEFT JOIN requests r ON p.request_id = r.id
//     LEFT JOIN installations i ON r.id = i.request_id
//     LEFT JOIN customer_orders co ON co.request_id = r.id
//     LEFT JOIN customer_order_products cp ON cp.order_id = co.id
//     WHERE i.status = 4
//     AND cp.product_id = i.product_id`)
// }
// const getAllcompletedInstallations = async (hasPermission, all = false, userType, userId, where = []) => {
//     try {
//         let whereCondition;
//         let query = ''
//         if (all) {
//             whereCondition = ` p.status != 2`;
//         } else {
//             whereCondition = ` p.status = 1`;
//         }
//         if (!empty(where)) {

//         }
//         if (userType === 1) {
//             query = await sequelize.query(
//                 ` SELECT DISTINCT p.*, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count FROM projects p `
//                 + ` LEFT JOIN users u ON p.added_by=u.id  `
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
//                 + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
//                 + `  LEFT JOIN requests r ON p.request_id = r.id `
//                 + ` LEFT JOIN installations i ON r.id = i.request_id`
//                 + ` LEFT JOIN customer_orders co ON co.request_id = r.id`
//                 + ` LEFT JOIN customer_order_products cp ON cp.order_id = co.id`
//                 +  ` WHERE NOT EXISTS (SELECT 1 
//                     FROM customer_order_products cop
//                     LEFT JOIN customer_orders co2 ON co2.id = cop.order_id
//                     LEFT JOIN installations ii ON cop.product_id = ii.product_id AND ii.request_id = co2.request_id
//                     WHERE co2.request_id = r.id
//                     AND (ii.product_id IS NULL OR ii.status <> 4)
//                     )
//                 ORDER BY p.id DESC`
//             );
//         }
//         else if (userType === 3) {
//             // query = await sequelize.query(
//             //     ` SELECT p.*, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count FROM projects p `
//             //     + ` LEFT JOIN users u ON p.added_by=u.id  `
//             //     + ` left join request_partners rp on rp.request_id=p.request_id`
//             //     + ` left join partners pr on pr.id=rp.partner_id`
//             //     + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
//             //     + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
//             //     + ` where pr.user_id=${userId} ORDER BY p.id DESC`
//             // );
//             return []
//         }
//         else {
//             // query = await sequelize.query(`SELECT p.*, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count FROM projects p `
//             //     + ` LEFT JOIN staff_members s1 ON s1.id=p.project_lead  `
//             //     + ` LEFT JOIN users u1 ON s1.user_id=u1.id `
//             //     + ` LEFT JOIN staff_members s2 ON s2.id=p.default_assignee `
//             //     + ` LEFT JOIN users u2 ON s2.user_id=u2.id `
//             //     + ` LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id from project_members pm left join partners p on p.id=pm.partner_id left join users u on p.user_id=u.id left join staff_members s on s.id=pm.staff_id left join users u2 on s.user_id=u2.id) pmm ON pmm.project_id=p.id and pmm.user_id=${userId} `
//             //     + ` LEFT JOIN users u ON p.added_by=u.id `
//             //     + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  `
//             //     + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  `
//             //     + ` WHERE (u1.id = ${userId} or u2.id = ${userId} or pmm.user_id =${userId} ) ORDER BY p.id DESC`);
//             return []
//         }
//         console.log("$$#################hifiiiiiiiiiiiiii");
//         let data;
//         if (query.length > 0) {
//             data = query[0];
//             if (userType == 1) {
//                 const results = await Promise.all(data.map(async (item) => {

//                     let selectedMaterials = await JobCost.fetchAllJobCostProjectId(item.id);
//                     let price = selectedMaterials.reduce((total, currentItem) => total + currentItem.total, 0);
//                     let payout = await JobCost.fetchAllPayOutByProjectId(item.id, userId);
//                     let services = await Request.getAllServiceByRequest(item.request_id);
//                     let serviceExpense = services.reduce((total, currentItem) => total + (currentItem.qty * currentItem.originalCost), 0);
//                     let payoutPrice = payout.reduce((total, currentItem) => total + currentItem.amount, 0);

//                     let expense = price + payoutPrice + Math.max(0, (serviceExpense - payoutPrice))
//                     item.progressValue = (expense / parseFloat(item.cost)) * 100
//                     if (item.progressValue > 100) {
//                         item.progressValue = 100
//                     }
//                     let image = await Request.FetchAllApprovedDesigns(item.request_id);
//                     image = image?.filter((imageItem)=>imageItem?.file_type?.startsWith('image/') || imageItem?.file_type ==='img')
//                     if (!empty(image[0])) {
//                         item.cover_image = image[0].name ? image[0].name : ""
//                     }
//                     else {
//                         item.cover_image = ""
//                     }

//                     return item;
//                 }));
//                 return results;
//             } else {
//                 return data;
//             }


//         } else {
//             return false;
//         }
//     } catch (error) {
//         console.log("#####################Error", error);
//         throw new Error("Server error");
//     }
// }
const getAllcompletedInstallations = async (hasPermission, all = false, userType, userId, sort, where = [], fromDate, toDate,dueData,filterProjectType, currentTab, page = 1, limit = 6, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = [], splitOrder = false, forAllTab = false) => {
    try {
        let estimateCondition = ' AND p.is_estimate_job=0';
        let whereCondition;
        const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
        const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
        const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
        let dateCondition = '';
        if (fromTimestamp && toTimestamp) {
          dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
        } else if (fromTimestamp) {
          dateCondition = ` p.installation_date >= ${fromTimestamp}`;
        } else if (toTimestamp) {
          dateCondition = ` p.installation_date <= ${toTimestamp}`;
        }
        // else if (dueTimestamp) {
        //     dateCondition = ` p.installation_date <= ${dueTimestamp}`;
        // }
        let query = ''
        if (all) {
            whereCondition = ` p.status != 2`;
        } else {
            whereCondition = ` p.status = 1`;
        }
        if (!empty(where)) {

        }
        // if (splitOrder === 1) {
        //     whereCondition += whereCondition ? ` AND r.is_split_order = 1` : ` r.is_split_order = 1`;
        // } else if (splitOrder === 2) {
        //     whereCondition += whereCondition ? ` AND r.is_split_order = 0` : ` r.is_split_order = 0`;
        // }

        let createdAt = ''
        if (dueTimestamp) {
            createdAt=`ORDER BY p.installation_date ASC`
        }else{
            if(sort==='new'){
                createdAt = `ORDER BY p.id DESC `
            }else if(sort==='old'){
                createdAt = `ORDER BY p.id ASC `
            }else if(sort === 'custom_order'){
                createdAt=`ORDER BY p.card_order ASC`
            }else{
                createdAt=`ORDER BY p.timestamp DESC`
            }
        }

        let projectTypeCondition = '';
if (filterProjectType === 1) {
  projectTypeCondition = ` p.project_type = 1`;
} else if (filterProjectType === 2) {
  projectTypeCondition = ` p.project_type = 2`;
} else if (filterProjectType === 'NULL') {
  projectTypeCondition = ` p.project_type IS NULL`;
} else {
  projectTypeCondition = ` (p.project_type IS NULL OR p.project_type IS NOT NULL)`;
}

        // Add job class filtering condition
        let jobClassCondition = '';
        if (jobClassFilter && jobClassFilter.length > 0) {
            const jobClassIds = jobClassFilter.join(',');
            jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
        }

        // Add job types filtering condition
        let jobTypesCondition = '';
        if (jobTypesFilter && jobTypesFilter.length > 0) {
            const jobTypesIds = jobTypesFilter.join(',');
            jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
        }

        // Add client filtering condition
        let clientCondition = '';
        if (clientFilter && clientFilter.length > 0) {
            const clientIds = clientFilter.join(',');
            clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
        }

        // Add user filtering condition
        let userCondition = '';
        if (userFilter && userFilter.length > 0) {
            const userIds = userFilter.join(',');
            userCondition = ` AND EXISTS (
                SELECT 1 FROM project_members pm 
                WHERE pm.project_id = p.id 
                AND pm.staff_id IN (${userIds})
            )`;
        }

        // Add project filtering condition
        let projectCondition = '';
        if (projectFilter && projectFilter.length > 0) {
            // Check if 'other' is included in the filter
            const hasOther = projectFilter.includes('other');
            const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
            if (hasOther && numericIds.length > 0) {
                // Include both specific communities and null/other communities
                projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
            } else if (hasOther) {
                // Only 'other' is selected
                projectCondition = ` AND p.community IS NULL`;
            } else {
                // Only specific communities are selected
                projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
            }
        }

        let departmentCondition = '';
        if (departmentFilter && departmentFilter.length > 0) {
            const departmentIds = departmentFilter.join(',');
          
            // departmentCondition = `
            //     AND EXISTS (
            //       SELECT 1
            //       FROM project_members pm
            //       INNER JOIN staff_members sm ON pm.staff_id = sm.id
            //       INNER JOIN users u ON sm.user_id = u.id
            //       WHERE pm.project_id = p.id
            //       AND u.department_id IN (${departmentIds})
            //     )
            //   `;
            departmentCondition = `
            AND EXISTS (
              SELECT 1
              FROM project_members pm_dep
              INNER JOIN staff_members sm_dep ON pm_dep.staff_id = sm_dep.id
              INNER JOIN users u_dep ON sm_dep.user_id = u_dep.id
              WHERE pm_dep.project_id = p.id
              AND u_dep.department_id IN (${departmentIds})
            )
          `;
          }
        // Add search condition
        let searchCondition = '';
        if (search && search.trim() !== '') {
            searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR r.doc_number LIKE '%${search}%' OR r.est_doc_number LIKE '%${search}%')`;
        }

        // Add currentTab filtering condition for remaining tabs
        let tabCondition = '';
        let splitMirrorCondition = '';
        // Keep Change Order behavior consistent with getAllProjects:
        // - Show only change orders on "Change Order" tab
        // - Hide change orders from all other tabs (except Hold)
        let changeOrderBaseCondition = '';
        let changeOrderExclusion = '';
        if (currentTab === 'Hold') {
            tabCondition = ` p.hold = 1`;
        } else if (currentTab === 'Pre-Production') {
            tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0`;
        } else if (currentTab === 'Production') {
            tabCondition = ` p.hold = 0 AND p.status = 2 `;
        } else if (currentTab === 'Change Order') {
            tabCondition = ` p.hold = 0 AND p.change_order = 1`;
        } else if (currentTab === 'Installs') {
            // Include installation_pending_review. For ALL tab (forAllTab), skip EXISTS to avoid duplicates.
            tabCondition = forAllTab
                ? ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND r.status != 3 AND p.status = 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1) OR ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND COALESCE(i.pending_review, 0) = 1)) OR (COALESCE(i.pending_review, 0) = 2) `
                : ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND r.status != 3 AND p.status = 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (EXISTS (SELECT 1 FROM installations inst_tab WHERE inst_tab.request_id = r.id AND inst_tab.status IS NOT NULL AND inst_tab.status != 5 AND inst_tab.complete_status = 1 AND inst_tab.status != 0) AND r.status != 3 AND p.status = 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1) OR ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND COALESCE(i.pending_review, 0) = 1)) OR (COALESCE(i.pending_review, 0) = 2)`;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1)`;
        } else if (currentTab === 'Pickup') {
            tabCondition = forAllTab
                ? ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2))`
                : ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (EXISTS (SELECT 1 FROM installations inst_tab WHERE inst_tab.request_id = r.id AND inst_tab.status IS NOT NULL AND inst_tab.status != 5 AND inst_tab.complete_status = 2) AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2))`;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2)`;
        } else if (currentTab === 'Shipping') {
            tabCondition = forAllTab
                ? ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3))`
                : ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (EXISTS (SELECT 1 FROM installations inst_tab WHERE inst_tab.request_id = r.id AND inst_tab.status IS NOT NULL AND inst_tab.status != 5 AND inst_tab.complete_status = 3) AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3))`;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3)`;
        } else if (currentTab === 'Completed') {
            // Exclude installation_pending_review (show those in Installs tab instead)
            tabCondition = ` (((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND r.isReview != 2 AND r.installation_acceptance = 1) OR (p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND r.isReview != 2 AND r.installation_acceptance = 1) OR r.status = 10 OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)) AND (COALESCE(i.pending_review, 0) != 1) AND (COALESCE(i.pending_review, 0) != 2)`;
         splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)`;
        } else if (currentTab === 'T & M Review') {
            // Original frontend condition: (item.allInstallationCompleted === 1 && item?.installation_acceptance !==1 && item.project_status == 3 && item.project_category == 12 && item.isReview ==2)
            tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)  AND p.status = 3 AND p.project_category = 12 AND r.isReview = 2`;
        } else if (currentTab === 'Cost Card') {
            // Original frontend condition: (item.allInstallationCompleted === 1 && item?.installation_acceptance !==1 && item.project_status == 3 && item.project_category !== 12 )
            tabCondition = ` ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) OR (total_inst_counts.total_installation_count IS NULL))  AND p.status = 3 AND p.project_category != 12 AND r.installation_acceptance IS NULL AND (COALESCE(i.pending_review, 0) NOT IN (1, 2)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4) `;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4)`;
        }

        if (currentTab === 'Change Order') {
            changeOrderBaseCondition = ` OR (p.change_order = 1)`;
        }
        if (currentTab !== 'Change Order' && currentTab !== 'Hold' && currentTab !== 'ALL') {
            changeOrderExclusion = ` (p.change_order IS NULL OR p.change_order = 0)`;
        }
        if (userType === 1 || userType == 8) {
            // query = await sequelize.query(
            //     ` SELECT DISTINCT p.*, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count FROM projects p `
            //     + ` LEFT JOIN users u ON p.added_by=u.id  `
            //     + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
            //     + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
            //     + `  LEFT JOIN requests r ON p.request_id = r.id `
            //     + ` LEFT JOIN installations i ON r.id = i.request_id`
            //     + ` LEFT JOIN customer_orders co ON co.request_id = r.id`
            //     + ` LEFT JOIN customer_order_products cp ON cp.order_id = co.id`
            //     +  ` WHERE NOT EXISTS (SELECT 1 
            //         FROM customer_order_products cop
            //         LEFT JOIN customer_orders co2 ON co2.id = cop.order_id
            //         LEFT JOIN installations ii ON cop.product_id = ii.product_id AND ii.request_id = co2.request_id
            //         WHERE co2.request_id = r.id
            //         AND (ii.product_id IS NULL OR ii.status <> 4)
            //         )
            //     ORDER BY p.id DESC`
            // );
            query = await sequelize.query(
                ` SELECT p.*,p.status AS project_status,pc.name AS job_category_name,r.status AS request_status,r.origin_facility_id,r.is_split_order,r.for_parent_facility,ptp.name AS job_class_name,cop.location_quantity,inst_counts.installation_count, total_inst_counts.total_installation_count, cop.product_count,rss.service_count, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count, i.status as installationStatus,r.doc_number,r.est_doc_number,r.installation_acceptance,r.isReview,r.syncWithQuickbooks,i.complete_status as InstallCompleteStatus,COALESCE(i.pending_review, 0) AS installation_pending_review,`
                + ` CASE `
                + ` WHEN inst_counts.installation_count >= cop.product_count OR inst_counts.installation_count >= rss.service_count `
                + ` THEN 1 `
                + ` ELSE 0 `
                + ` END AS veryoldallInstallationCompleted,`
                + ` CASE 
                        WHEN p.project_category = 12 THEN 
                        CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END
                        WHEN p.project_category = 11 THEN 
                        CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                        WHEN p.project_category = 14 THEN 
                        CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                        ELSE 
                        CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) THEN 1 ELSE 0 END 
                    END AS oldallInstallationCompleted, `
                + `CASE 
                        WHEN 
                        (
                        (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0))
                        AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)
                        ) OR (
                        COALESCE(total_inst_counts.total_installation_count, 0) <= 0
                        AND p.status = 3 AND p.noServiceNoTask = 0
                        )
                        THEN 1
                        ELSE 0
                    END AS allInstallationCompleted,`
                + ` com.name AS community_name,r.isFromDesignOrder,c_ord.customer_phone, c_ord.customer_name,c_ord.customer_id,c_ord.total,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p ` 
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
                + ` INNER JOIN requests r ON p.request_id = r.id `
                + ` LEFT JOIN (
                        SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, 
                         SUM(
                                CASE
                                WHEN cop.is_single_card = 1 THEN 1
                                ELSE cop.location_quantity
                                END
                            ) AS product_count
                        FROM customer_orders co
                        JOIN customer_order_products cop ON co.id = cop.order_id
                        JOIN requests req ON co.request_id = req.id
                        WHERE cop.material = 0
                        GROUP BY co.request_id
                    ) cop ON r.id = cop.request_id `

                + ` LEFT JOIN (
                        SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                        FROM customer_orders co
                        JOIN  requests rqs ON co.request_id = rqs.id
                        JOIN  request_services rss ON co.request_id = rss.request_id
                        JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                        WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                        GROUP BY co.request_id
                    ) rss ON r.id = rss.request_id `

                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id`
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id`
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` left join partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` where (((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
                        r.noServiceNoTask = 0 AND r.status=4) OR (i.status IS NOT NULL)${changeOrderBaseCondition}) ${splitMirrorCondition})  
                         ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
                         ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
                         ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
                         ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} GROUP BY p.id ${createdAt} 
                          LIMIT ${limit} OFFSET ${(page - 1) * limit}`
                        // ${dateCondition!= '' ? ' AND '+dateCondition : ''} AND ${projectTypeCondition} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${departmentCondition != '' ? departmentCondition : ''} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} ${createdAt} LIMIT ${limit} OFFSET ${(page - 1) * limit}`
            );

        }
        else if (userType === 3) {
            query = await sequelize.query(
                ` SELECT p.*,p.status AS project_status,pc.name AS job_category_name,ptp.name AS job_class_name,r.status AS request_status,r.origin_facility_id,r.is_split_order,r.for_parent_facility, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, inst_counts.installation_count, total_inst_counts.total_installation_count, cop.product_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count,i.status as installationStatus,r.doc_number,r.est_doc_number,r.installation_acceptance,r.isReview,r.syncWithQuickbooks,i.complete_status as InstallCompleteStatus,COALESCE(i.pending_review, 0) AS installation_pending_review,`
                + ` CASE `
                + ` WHEN inst_counts.installation_count >= cop.product_count OR inst_counts.installation_count >= rss.service_count`
                + ` THEN 1 `
                + ` ELSE 0 `
                + ` END AS veryoldallInstallationCompleted,`
                + ` CASE 
                        WHEN p.project_category = 12 THEN 
                        CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END
                        WHEN p.project_category = 11 THEN 
                        CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                        WHEN p.project_category = 14 THEN 
                        CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                        ELSE 
                        CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) THEN 1 ELSE 0 END 
                    END AS oldallInstallationCompleted, `
                + `CASE 
                        WHEN 
                        (
                        (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0))
                        AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)
                        ) OR (
                        COALESCE(total_inst_counts.total_installation_count, 0) <= 0
                        AND p.status = 3 AND p.noServiceNoTask = 0
                        )
                        THEN 1
                        ELSE 0
                    END AS allInstallationCompleted,`
                + ` com.name AS community_name,r.isFromDesignOrder,c_ord.customer_phone, c_ord.customer_name,c_ord.customer_id,c_ord.total,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` left join request_partners rp on rp.request_id=p.request_id`
                + ` left join partners pr on pr.id=rp.partner_id`
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
                + ` INNER JOIN requests r ON p.request_id = r.id `
                + ` LEFT JOIN (
                    SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity,
                     SUM(
                            CASE
                            WHEN cop.is_single_card = 1 THEN 1
                            ELSE cop.location_quantity
                            END
                        ) AS product_count
                    FROM customer_orders co
                    JOIN customer_order_products cop ON co.id = cop.order_id
                    JOIN requests req ON co.request_id = req.id
                    WHERE cop.material = 0
                    GROUP BY co.request_id
                ) cop ON r.id = cop.request_id `

                + ` LEFT JOIN (
                    SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                    FROM customer_orders co
                    JOIN  requests rqs ON co.request_id = rqs.id
                    JOIN  request_services rss ON co.request_id = rss.request_id
                    JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                    WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                    GROUP BY co.request_id
                ) rss ON r.id = rss.request_id `

                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id`
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` left join partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` where pr.user_id=${userId} and ((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
                        r.noServiceNoTask = 0 AND r.status=4) OR  (i.status IS NOT NULL)${changeOrderBaseCondition}) 
                          ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
                         ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
                         ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
                         ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} GROUP BY p.id ${createdAt} 
                          LIMIT ${limit} OFFSET ${(page - 1) * limit}`
                        // ${dateCondition!= '' ? ' AND '+dateCondition : ''} AND ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${createdAt}`
            );
        }
        else {
            query = await sequelize.query(
                `SELECT p.*,p.status AS project_status,pc.name AS job_category_name,ptp.name AS job_class_name,r.status AS request_status,r.origin_facility_id,r.is_split_order,r.for_parent_facility,inst_counts.installation_count,total_inst_counts.total_installation_count, cop.product_count,r.doc_number,r.est_doc_number,r.installation_acceptance,r.isReview,r.syncWithQuickbooks, 
                    concat(u.first_name, ' ', u.last_name) as authorized_by, 
                    coalesce(pm.count, 0) as member_count, 
                    coalesce(pt.count, 0) as task_count,
                    coalesce(jnm.count, 0) as job_note_count,
                    i.status as installationStatus, 
                    i.complete_status as InstallCompleteStatus,  -- ✅ Ensure this is included
                    CASE 
                        WHEN inst_counts.installation_count >= cop.product_count OR inst_counts.installation_count >= rss.service_count
                        THEN 1 
                        ELSE 0 
                    END AS veryoldallInstallationCompleted, 
                    CASE 
                        WHEN p.project_category = 12 THEN 
                        CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END
                        WHEN p.project_category = 11 THEN 
                        CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                        WHEN p.project_category = 14 THEN 
                        CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                        ELSE 
                        CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) THEN 1 ELSE 0 END 
                    END AS oldallInstallationCompleted,
                    CASE 
                        WHEN 
                        (
                        (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0))
                        AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)
                        ) OR (
                        COALESCE(total_inst_counts.total_installation_count, 0) <= 0
                        AND p.status = 3 AND p.noServiceNoTask = 0
                        )
                        THEN 1
                        ELSE 0
                    END AS allInstallationCompleted,
                    com.name AS community_name, 
                    c_ord.customer_phone, 
                    r.isFromDesignOrder, 
                    c_ord.customer_name, 
                    c_ord.customer_id,
                    c_ord.total ,
                    part.thumbnail AS customer_logo
                FROM projects p 
                LEFT JOIN staff_members s1 ON s1.id=p.project_lead  
                LEFT JOIN users u1 ON s1.user_id=u1.id 
                LEFT JOIN project_categories pc ON pc.id=p.project_category 
                LEFT JOIN project_types ptp ON ptp.id=p.project_type 
                LEFT JOIN staff_members s2 ON s2.id=p.default_assignee 
                LEFT JOIN users u2 ON s2.user_id=u2.id 
                LEFT JOIN installations i2 ON p.id=i2.project_id 
                LEFT JOIN driver dr ON i2.driver_id=dr.id 
                LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id 
                    from project_members pm 
                    left join partners p on p.id=pm.partner_id 
                    left join users u on p.user_id=u.id 
                    left join staff_members s on s.id=pm.staff_id 
                    left join users u2 on s.user_id=u2.id) pmm 
                    ON pmm.project_id=p.id and pmm.user_id=${userId} 
                LEFT JOIN users u ON p.added_by=u.id 
                LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  
                LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  
                INNER JOIN requests r ON p.request_id = r.id 
                LEFT JOIN users ura ON r.added_by=ura.id 
                LEFT JOIN (
                    SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, 
                     SUM(
                    CASE
                      WHEN cop.is_single_card = 1 THEN 1
                      ELSE cop.location_quantity
                    END
                  ) AS product_count
                    FROM customer_orders co
                    JOIN customer_order_products cop ON co.id = cop.order_id
                    JOIN requests req ON co.request_id = req.id
                    WHERE cop.material = 0
                    GROUP BY co.request_id
                ) cop ON r.id = cop.request_id 
                LEFT JOIN (
                    SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                    FROM customer_orders co
                    JOIN  requests rqs ON co.request_id = rqs.id
                    JOIN  request_services rss ON co.request_id = rss.request_id
                    JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                    WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                    GROUP BY co.request_id
                ) rss ON r.id = rss.request_id 
                -- ✅ FIX: Include complete_status in installations join
                LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id 
                LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id 
                LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id
                LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id
                LEFT JOIN customer_orders c_ord ON c_ord.request_id = p.request_id 
                LEFT JOIN partners part ON part.id = c_ord.customer_id 
                LEFT JOIN community com ON com.id=p.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1 
                WHERE (u1.id = ${userId} OR u2.id = ${userId} OR pmm.user_id =${userId} OR (r.added_by = ${userId} AND ura.user_type <> 3) OR FIND_IN_SET(${userId}, i2.team_id) OR FIND_IN_SET(${userId}, dr.user_id)) 
                AND ((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
                        r.noServiceNoTask = 0 AND r.status=4) OR  (i.status IS NOT NULL)${changeOrderBaseCondition}) 
                         ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
                         ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
                         ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
                         ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} GROUP BY p.id ${createdAt} 
                          LIMIT ${limit} OFFSET ${(page - 1) * limit}`
                        // ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition != '' ? ' AND ' + tabCondition : ''} GROUP BY p.id ${createdAt}`
            );
            
        }
        let data;
        const isAdminUser = userType == 1 || userType == 8;
        const applyApprovedDesignFields = async (item) => {
            const image = await Request.FetchAllApprovedDesigns(item.request_id);
            const coverImage = image?.find((imageItem) => imageItem?.file_type?.startsWith('image/') || imageItem?.file_type === 'img');
            const firstItemWithLocationIds = image?.find((imageItem) => imageItem?.location_ids !== null);
            const approvedPdf = image?.[0];

            item.cover_image = coverImage?.name || "";
            item.approved_pdf = firstItemWithLocationIds?.name || approvedPdf?.name || "";

            return item;
        };

        const enrichCompletedInstallationForAdmin = async (item) => {
            const [selectedMaterials, payout, services] = await Promise.all([
                JobCost.fetchAllJobCostProjectId(item.id),
                JobCost.fetchAllPayOutByProjectId(item.id, userId),
                Request.getAllServiceByRequest(item.request_id),
            ]);

            const price = (selectedMaterials || []).reduce((total, currentItem) => {
                if (currentItem.taken === 1) {
                    return total + currentItem.total;
                }
                return total;
            }, 0);

            const serviceExpense = (services || []).reduce((total, currentItem) => {
                if (currentItem.taken === 1) {
                    return total + (currentItem.qty * currentItem.originalCost);
                }
                return total;
            }, 0);

            const payoutPrice = (payout || []).reduce((total, currentItem) => total + currentItem.amount, 0);
            const expense = price + payoutPrice + Math.max(0, (serviceExpense - payoutPrice));
            const parsedCost = parseFloat(item.cost) || 0;

            if (Number(item.status) === 1 || parsedCost <= 0) {
                item.progressValue = 0;
            } else {
                item.progressValue = (expense / parsedCost) * 100;
                if (item.progressValue > 100) {
                    item.progressValue = 100;
                }
            }

            return applyApprovedDesignFields(item);
        };

        if (query.length > 0) {
            data = query[0];
            if (isAdminUser) {
                const results = await Promise.all(data.map(enrichCompletedInstallationForAdmin));
                return results?.map(record => parseDecimalFields(record));
            } else {
                const results = await Promise.all(data.map(applyApprovedDesignFields));
                return results?.map(record => parseDecimalFields(record));
            }


        } else {
            return false;
        }
    } catch (error) {
        console.log("#####################Error", error);
        throw new Error("Server error");
    }
}
// const getAllcompletedInstallations = async (hasPermission, all = false, userType, userId, sort, where = [], fromDate, toDate,dueData,filterProjectType, currentTab, page = 1, limit = 6, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = [], splitOrder = false, forAllTab = false) => {
//     try {
//         let estimateCondition = ' AND p.is_estimate_job=0';
//         let whereCondition;
//         const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
//         const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
//         const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
//         let dateCondition = '';
//         if (fromTimestamp && toTimestamp) {
//           dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
//         } else if (fromTimestamp) {
//           dateCondition = ` p.installation_date >= ${fromTimestamp}`;
//         } else if (toTimestamp) {
//           dateCondition = ` p.installation_date <= ${toTimestamp}`;
//         }
//         // else if (dueTimestamp) {
//         //     dateCondition = ` p.installation_date <= ${dueTimestamp}`;
//         // }
//         let query = ''
//         if (all) {
//             whereCondition = ` p.status != 2`;
//         } else {
//             whereCondition = ` p.status = 1`;
//         }
//         if (!empty(where)) {

//         }
//         // if (splitOrder === 1) {
//         //     whereCondition += whereCondition ? ` AND r.is_split_order = 1` : ` r.is_split_order = 1`;
//         // } else if (splitOrder === 2) {
//         //     whereCondition += whereCondition ? ` AND r.is_split_order = 0` : ` r.is_split_order = 0`;
//         // }

//         let createdAt = ''
//         if (dueTimestamp) {
//             createdAt=`ORDER BY p.installation_date ASC`
//         }else{
//             if(sort==='new'){
//                 createdAt = `ORDER BY p.id DESC `
//             }else if(sort==='old'){
//                 createdAt = `ORDER BY p.id ASC `
//             }else if(sort === 'custom_order'){
//                 createdAt=`ORDER BY p.card_order ASC`
//             }else{
//                 createdAt=`ORDER BY p.timestamp DESC`
//             }
//         }

//         let projectTypeCondition = '';
// if (filterProjectType === 1) {
//   projectTypeCondition = ` p.project_type = 1`;
// } else if (filterProjectType === 2) {
//   projectTypeCondition = ` p.project_type = 2`;
// } else if (filterProjectType === 'NULL') {
//   projectTypeCondition = ` p.project_type IS NULL`;
// } else {
//   projectTypeCondition = ` (p.project_type IS NULL OR p.project_type IS NOT NULL)`;
// }

//         // Add job class filtering condition
//         let jobClassCondition = '';
//         if (jobClassFilter && jobClassFilter.length > 0) {
//             const jobClassIds = jobClassFilter.join(',');
//             jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
//         }

//         // Add job types filtering condition
//         let jobTypesCondition = '';
//         if (jobTypesFilter && jobTypesFilter.length > 0) {
//             const jobTypesIds = jobTypesFilter.join(',');
//             jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
//         }

//         // Add client filtering condition
//         let clientCondition = '';
//         if (clientFilter && clientFilter.length > 0) {
//             const clientIds = clientFilter.join(',');
//             clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
//         }

//         // Add user filtering condition
//         let userCondition = '';
//         if (userFilter && userFilter.length > 0) {
//             const userIds = userFilter.join(',');
//             userCondition = ` AND EXISTS (
//                 SELECT 1 FROM project_members pm 
//                 WHERE pm.project_id = p.id 
//                 AND pm.staff_id IN (${userIds})
//             )`;
//         }

//         // Add project filtering condition
//         let projectCondition = '';
//         if (projectFilter && projectFilter.length > 0) {
//             // Check if 'other' is included in the filter
//             const hasOther = projectFilter.includes('other');
//             const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
//             if (hasOther && numericIds.length > 0) {
//                 // Include both specific communities and null/other communities
//                 projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
//             } else if (hasOther) {
//                 // Only 'other' is selected
//                 projectCondition = ` AND p.community IS NULL`;
//             } else {
//                 // Only specific communities are selected
//                 projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
//             }
//         }

//         let departmentCondition = '';
//         if (departmentFilter && departmentFilter.length > 0) {
//             const departmentIds = departmentFilter.join(',');
          
//             // departmentCondition = `
//             //     AND EXISTS (
//             //       SELECT 1
//             //       FROM project_members pm
//             //       INNER JOIN staff_members sm ON pm.staff_id = sm.id
//             //       INNER JOIN users u ON sm.user_id = u.id
//             //       WHERE pm.project_id = p.id
//             //       AND u.department_id IN (${departmentIds})
//             //     )
//             //   `;
//             departmentCondition = `
//             AND EXISTS (
//               SELECT 1
//               FROM project_members pm_dep
//               INNER JOIN staff_members sm_dep ON pm_dep.staff_id = sm_dep.id
//               INNER JOIN users u_dep ON sm_dep.user_id = u_dep.id
//               WHERE pm_dep.project_id = p.id
//               AND u_dep.department_id IN (${departmentIds})
//             )
//           `;
//           }
//         // Add search condition
//         let searchCondition = '';
//         if (search && search.trim() !== '') {
//             searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR r.doc_number LIKE '%${search}%' OR r.est_doc_number LIKE '%${search}%')`;
//         }

//         // Add currentTab filtering condition for remaining tabs
//         let tabCondition = '';
//         let splitMirrorCondition = '';
//         // Keep Change Order behavior consistent with getAllProjects:
//         // - Show only change orders on "Change Order" tab
//         // - Hide change orders from all other tabs (except Hold)
//         let changeOrderBaseCondition = '';
//         let changeOrderExclusion = '';
//         if (currentTab === 'Hold') {
//             tabCondition = ` p.hold = 1`;
//         } else if (currentTab === 'Pre-Production') {
//             tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0`;
//         } else if (currentTab === 'Production') {
//             tabCondition = ` p.hold = 0 AND p.status = 2 `;
//         } else if (currentTab === 'Change Order') {
//             tabCondition = ` p.hold = 0 AND p.change_order = 1`;
//         } else if (currentTab === 'Installs') {
//             // Include installation_pending_review. For ALL tab (forAllTab), skip EXISTS to avoid duplicates.
//             tabCondition = forAllTab
//                 ? ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND r.status != 3 AND p.status = 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1) OR ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND COALESCE(i.pending_review, 0) = 1)) OR (COALESCE(i.pending_review, 0) = 2) `
//                 : ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND r.status != 3 AND p.status = 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (EXISTS (SELECT 1 FROM installations inst_tab WHERE inst_tab.request_id = r.id AND inst_tab.status IS NOT NULL AND inst_tab.status != 5 AND inst_tab.complete_status = 1 AND inst_tab.status != 0) AND r.status != 3 AND p.status = 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1) OR ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND COALESCE(i.pending_review, 0) = 1)) OR (COALESCE(i.pending_review, 0) = 2)`;
//             splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1)`;
//         } else if (currentTab === 'Pickup') {
//             tabCondition = forAllTab
//                 ? ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2))`
//                 : ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (EXISTS (SELECT 1 FROM installations inst_tab WHERE inst_tab.request_id = r.id AND inst_tab.status IS NOT NULL AND inst_tab.status != 5 AND inst_tab.complete_status = 2) AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2))`;
//             splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2)`;
//         } else if (currentTab === 'Shipping') {
//             tabCondition = forAllTab
//                 ? ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3))`
//                 : ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (EXISTS (SELECT 1 FROM installations inst_tab WHERE inst_tab.request_id = r.id AND inst_tab.status IS NOT NULL AND inst_tab.status != 5 AND inst_tab.complete_status = 3) AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3))`;
//             splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3)`;
//         } else if (currentTab === 'Completed') {
//             // Exclude installation_pending_review (show those in Installs tab instead)
//             tabCondition = ` (((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND r.isReview != 2 AND r.installation_acceptance = 1) OR (p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND r.isReview != 2 AND r.installation_acceptance = 1) OR r.status = 10 OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)) AND (COALESCE(i.pending_review, 0) != 1) AND (COALESCE(i.pending_review, 0) != 2)`;
//          splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)`;
//         } else if (currentTab === 'T & M Review') {
//             // Original frontend condition: (item.allInstallationCompleted === 1 && item?.installation_acceptance !==1 && item.project_status == 3 && item.project_category == 12 && item.isReview ==2)
//             tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)  AND p.status = 3 AND p.project_category = 12 AND r.isReview = 2`;
//         } else if (currentTab === 'Cost Card') {
//             // Original frontend condition: (item.allInstallationCompleted === 1 && item?.installation_acceptance !==1 && item.project_status == 3 && item.project_category !== 12 )
//             tabCondition = ` ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) OR (total_inst_counts.total_installation_count IS NULL))  AND p.status = 3 AND p.project_category != 12 AND r.installation_acceptance IS NULL AND (COALESCE(i.pending_review, 0) NOT IN (1, 2)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4) `;
//             splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4)`;
//             console.log('tabCondition+++++++', tabCondition)
//         }

//         if (currentTab === 'Change Order') {
//             changeOrderBaseCondition = ` OR (p.change_order = 1)`;
//         }
//         if (currentTab !== 'Change Order' && currentTab !== 'Hold' && currentTab !== 'ALL') {
//             changeOrderExclusion = ` (p.change_order IS NULL OR p.change_order = 0)`;
//         }
// console.log('testtttttttttt');

//         if (userType === 1 || userType == 8) {
//             // query = await sequelize.query(
//             //     ` SELECT DISTINCT p.*, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count FROM projects p `
//             //     + ` LEFT JOIN users u ON p.added_by=u.id  `
//             //     + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
//             //     + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
//             //     + `  LEFT JOIN requests r ON p.request_id = r.id `
//             //     + ` LEFT JOIN installations i ON r.id = i.request_id`
//             //     + ` LEFT JOIN customer_orders co ON co.request_id = r.id`
//             //     + ` LEFT JOIN customer_order_products cp ON cp.order_id = co.id`
//             //     +  ` WHERE NOT EXISTS (SELECT 1 
//             //         FROM customer_order_products cop
//             //         LEFT JOIN customer_orders co2 ON co2.id = cop.order_id
//             //         LEFT JOIN installations ii ON cop.product_id = ii.product_id AND ii.request_id = co2.request_id
//             //         WHERE co2.request_id = r.id
//             //         AND (ii.product_id IS NULL OR ii.status <> 4)
//             //         )
//             //     ORDER BY p.id DESC`
//             // );
//             query = await sequelize.query(
//                 ` SELECT p.*,p.status AS project_status,pc.name AS job_category_name,r.status AS request_status,r.origin_facility_id,r.is_split_order,r.for_parent_facility,ptp.name AS job_class_name,cop.location_quantity,inst_counts.installation_count, total_inst_counts.total_installation_count, cop.product_count,rss.service_count, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count, i.status as installationStatus,r.doc_number,r.est_doc_number,r.installation_acceptance,r.isReview,r.syncWithQuickbooks,i.complete_status as InstallCompleteStatus,COALESCE(i.pending_review, 0) AS installation_pending_review,`
//                 + ` CASE `
//                 + ` WHEN inst_counts.installation_count >= cop.product_count OR inst_counts.installation_count >= rss.service_count `
//                 + ` THEN 1 `
//                 + ` ELSE 0 `
//                 + ` END AS veryoldallInstallationCompleted,`
//                 + ` CASE 
//                         WHEN p.project_category = 12 THEN 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END
//                         WHEN p.project_category = 11 THEN 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
//                         WHEN p.project_category = 14 THEN 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
//                         ELSE 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) THEN 1 ELSE 0 END 
//                     END AS oldallInstallationCompleted, `
//                 + `CASE 
//                         WHEN 
//                         (
//                         (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0))
//                         AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)
//                         ) OR (
//                         COALESCE(total_inst_counts.total_installation_count, 0) <= 0
//                         AND p.status = 3 AND p.noServiceNoTask = 0
//                         )
//                         THEN 1
//                         ELSE 0
//                     END AS allInstallationCompleted,`
//                 + ` com.name AS community_name,r.isFromDesignOrder,c_ord.customer_phone, c_ord.customer_name,c_ord.customer_id,c_ord.total,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p ` 
//                 + ` LEFT JOIN users u ON p.added_by=u.id  `
//                 + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
//                 + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
//                 + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
//                 + ` INNER JOIN requests r ON p.request_id = r.id `
//                 + ` LEFT JOIN (
//                         SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, 
//                          SUM(
//                                 CASE
//                                 WHEN cop.is_single_card = 1 THEN 1
//                                 ELSE cop.location_quantity
//                                 END
//                             ) AS product_count
//                         FROM customer_orders co
//                         JOIN customer_order_products cop ON co.id = cop.order_id
//                         JOIN requests req ON co.request_id = req.id
//                         WHERE cop.material = 0
//                         GROUP BY co.request_id
//                     ) cop ON r.id = cop.request_id `

//                 + ` LEFT JOIN (
//                         SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
//                         FROM customer_orders co
//                         JOIN  requests rqs ON co.request_id = rqs.id
//                         JOIN  request_services rss ON co.request_id = rss.request_id
//                         JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
//                         WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
//                         GROUP BY co.request_id
//                     ) rss ON r.id = rss.request_id `

//                 + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id`
//                 + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id`
//                 + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
//                 + ` left join partners part ON part.id = c_ord.customer_id `
//                 + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//                 + ` where (((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
//                         r.noServiceNoTask = 0 AND r.status=4) OR (i.status IS NOT NULL)${changeOrderBaseCondition}) ${splitMirrorCondition})  
//                          ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
//                          ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
//                          ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
//                          ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} GROUP BY p.id ${createdAt} 
//                           LIMIT ${limit} OFFSET ${(page - 1) * limit}`
//                         // ${dateCondition!= '' ? ' AND '+dateCondition : ''} AND ${projectTypeCondition} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${departmentCondition != '' ? departmentCondition : ''} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} ${createdAt} LIMIT ${limit} OFFSET ${(page - 1) * limit}`
//             );

//         }
//         else if (userType === 3) {
//             query = await sequelize.query(
//                 ` SELECT p.*,p.status AS project_status,pc.name AS job_category_name,ptp.name AS job_class_name,r.status AS request_status,r.origin_facility_id,r.is_split_order,r.for_parent_facility, concat(u.first_name, ' ', u.last_name) as authorized_by, coalesce(pm.count, 0) as member_count, inst_counts.installation_count, total_inst_counts.total_installation_count, cop.product_count, coalesce(pt.count, 0) as task_count, coalesce(jnm.count, 0) as job_note_count,i.status as installationStatus,r.doc_number,r.est_doc_number,r.installation_acceptance,r.isReview,r.syncWithQuickbooks,i.complete_status as InstallCompleteStatus,COALESCE(i.pending_review, 0) AS installation_pending_review,`
//                 + ` CASE `
//                 + ` WHEN inst_counts.installation_count >= cop.product_count OR inst_counts.installation_count >= rss.service_count`
//                 + ` THEN 1 `
//                 + ` ELSE 0 `
//                 + ` END AS veryoldallInstallationCompleted,`
//                 + ` CASE 
//                         WHEN p.project_category = 12 THEN 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END
//                         WHEN p.project_category = 11 THEN 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
//                         WHEN p.project_category = 14 THEN 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
//                         ELSE 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) THEN 1 ELSE 0 END 
//                     END AS oldallInstallationCompleted, `
//                 + `CASE 
//                         WHEN 
//                         (
//                         (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0))
//                         AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)
//                         ) OR (
//                         COALESCE(total_inst_counts.total_installation_count, 0) <= 0
//                         AND p.status = 3 AND p.noServiceNoTask = 0
//                         )
//                         THEN 1
//                         ELSE 0
//                     END AS allInstallationCompleted,`
//                 + ` com.name AS community_name,r.isFromDesignOrder,c_ord.customer_phone, c_ord.customer_name,c_ord.customer_id,c_ord.total,CONCAT(COALESCE(c_ord.customer_address, ''), ', ', COALESCE(c_ord.customer_phone, ''), ', ', COALESCE(com.name, ''), ', ', COALESCE(c_ord.customer_name, '')) AS description,part.thumbnail AS customer_logo FROM projects p `
//                 + ` LEFT JOIN users u ON p.added_by=u.id  `
//                 + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
//                 + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
//                 + ` left join request_partners rp on rp.request_id=p.request_id`
//                 + ` left join partners pr on pr.id=rp.partner_id`
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
//                 + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
//                 + ` INNER JOIN requests r ON p.request_id = r.id `
//                 + ` LEFT JOIN (
//                     SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity,
//                      SUM(
//                             CASE
//                             WHEN cop.is_single_card = 1 THEN 1
//                             ELSE cop.location_quantity
//                             END
//                         ) AS product_count
//                     FROM customer_orders co
//                     JOIN customer_order_products cop ON co.id = cop.order_id
//                     JOIN requests req ON co.request_id = req.id
//                     WHERE cop.material = 0
//                     GROUP BY co.request_id
//                 ) cop ON r.id = cop.request_id `

//                 + ` LEFT JOIN (
//                     SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
//                     FROM customer_orders co
//                     JOIN  requests rqs ON co.request_id = rqs.id
//                     JOIN  request_services rss ON co.request_id = rss.request_id
//                     JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
//                     WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
//                     GROUP BY co.request_id
//                 ) rss ON r.id = rss.request_id `

//                 + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id `
//                 + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id`
//                 + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
//                 + ` left join partners part ON part.id = c_ord.customer_id `
//                 + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//                 + ` where pr.user_id=${userId} and ((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
//                         r.noServiceNoTask = 0 AND r.status=4) OR  (i.status IS NOT NULL)${changeOrderBaseCondition}) 
//                           ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
//                          ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
//                          ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
//                          ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} GROUP BY p.id ${createdAt} 
//                           LIMIT ${limit} OFFSET ${(page - 1) * limit}`
//                         // ${dateCondition!= '' ? ' AND '+dateCondition : ''} AND ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${createdAt}`
//             );
//         }
//         else {
//             query = await sequelize.query(
//                 `SELECT p.*,p.status AS project_status,pc.name AS job_category_name,ptp.name AS job_class_name,r.status AS request_status,r.origin_facility_id,r.is_split_order,r.for_parent_facility,inst_counts.installation_count,total_inst_counts.total_installation_count, cop.product_count,r.doc_number,r.est_doc_number,r.installation_acceptance,r.isReview,r.syncWithQuickbooks, 
//                     concat(u.first_name, ' ', u.last_name) as authorized_by, 
//                     coalesce(pm.count, 0) as member_count, 
//                     coalesce(pt.count, 0) as task_count,
//                     coalesce(jnm.count, 0) as job_note_count,
//                     i.status as installationStatus, 
//                     i.complete_status as InstallCompleteStatus,  -- ✅ Ensure this is included
//                     CASE 
//                         WHEN inst_counts.installation_count >= cop.product_count OR inst_counts.installation_count >= rss.service_count
//                         THEN 1 
//                         ELSE 0 
//                     END AS veryoldallInstallationCompleted, 
//                     CASE 
//                         WHEN p.project_category = 12 THEN 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END
//                         WHEN p.project_category = 11 THEN 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
//                         WHEN p.project_category = 14 THEN 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) + COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
//                         ELSE 
//                         CASE WHEN inst_counts.installation_count >= COALESCE(cop.product_count, 0) THEN 1 ELSE 0 END 
//                     END AS oldallInstallationCompleted,
//                     CASE 
//                         WHEN 
//                         (
//                         (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0))
//                         AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)
//                         ) OR (
//                         COALESCE(total_inst_counts.total_installation_count, 0) <= 0
//                         AND p.status = 3 AND p.noServiceNoTask = 0
//                         )
//                         THEN 1
//                         ELSE 0
//                     END AS allInstallationCompleted,
//                     com.name AS community_name, 
//                     c_ord.customer_phone, 
//                     r.isFromDesignOrder, 
//                     c_ord.customer_name, 
//                     c_ord.customer_id,
//                     c_ord.total ,
//                     part.thumbnail AS customer_logo
//                 FROM projects p 
//                 LEFT JOIN staff_members s1 ON s1.id=p.project_lead  
//                 LEFT JOIN users u1 ON s1.user_id=u1.id 
//                 LEFT JOIN project_categories pc ON pc.id=p.project_category 
//                 LEFT JOIN project_types ptp ON ptp.id=p.project_type 
//                 LEFT JOIN staff_members s2 ON s2.id=p.default_assignee 
//                 LEFT JOIN users u2 ON s2.user_id=u2.id 
//                 LEFT JOIN installations i2 ON p.id=i2.project_id 
//                 LEFT JOIN driver dr ON i2.driver_id=dr.id 
//                 LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id 
//                     from project_members pm 
//                     left join partners p on p.id=pm.partner_id 
//                     left join users u on p.user_id=u.id 
//                     left join staff_members s on s.id=pm.staff_id 
//                     left join users u2 on s.user_id=u2.id) pmm 
//                     ON pmm.project_id=p.id and pmm.user_id=${userId} 
//                 LEFT JOIN users u ON p.added_by=u.id 
//                 LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  
//                 LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  
//                 INNER JOIN requests r ON p.request_id = r.id 
//                 LEFT JOIN users ura ON r.added_by=ura.id 
//                 LEFT JOIN (
//                     SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, 
//                      SUM(
//                     CASE
//                       WHEN cop.is_single_card = 1 THEN 1
//                       ELSE cop.location_quantity
//                     END
//                   ) AS product_count
//                     FROM customer_orders co
//                     JOIN customer_order_products cop ON co.id = cop.order_id
//                     JOIN requests req ON co.request_id = req.id
//                     WHERE cop.material = 0
//                     GROUP BY co.request_id
//                 ) cop ON r.id = cop.request_id 
//                 LEFT JOIN (
//                     SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
//                     FROM customer_orders co
//                     JOIN  requests rqs ON co.request_id = rqs.id
//                     JOIN  request_services rss ON co.request_id = rss.request_id
//                     JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
//                     WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
//                     GROUP BY co.request_id
//                 ) rss ON r.id = rss.request_id 
//                 -- ✅ FIX: Include complete_status in installations join
//                 LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id 
//                 LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id 
//                 LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id
//                 LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id
//                 LEFT JOIN customer_orders c_ord ON c_ord.request_id = p.request_id 
//                 LEFT JOIN partners part ON part.id = c_ord.customer_id 
//                 LEFT JOIN community com ON com.id=p.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1 
//                 WHERE (u1.id = ${userId} OR u2.id = ${userId} OR pmm.user_id =${userId} OR (r.added_by = ${userId} AND ura.user_type <> 3) OR FIND_IN_SET(${userId}, i2.team_id) OR FIND_IN_SET(${userId}, dr.user_id)) 
//                 AND ((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
//                         r.noServiceNoTask = 0 AND r.status=4) OR  (i.status IS NOT NULL)${changeOrderBaseCondition}) 
//                          ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
//                          ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
//                          ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
//                          ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} GROUP BY p.id ${createdAt} 
//                           LIMIT ${limit} OFFSET ${(page - 1) * limit}`
//                         // ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition != '' ? ' AND ' + tabCondition : ''} GROUP BY p.id ${createdAt}`
//             );
            
//         }
//         let data;
//         if (query.length > 0) {
//             data = query[0];
//             if (userType == 1 || userType == 8) {
//                 const results = await Promise.all(data.map(async (item) => {

//                     // let selectedMaterials = await JobCost.fetchAllJobCostProjectId(item.id);
//                     // let price = selectedMaterials.reduce((total, currentItem) => total + currentItem.total, 0);
//                     // let payout = await JobCost.fetchAllPayOutByProjectId(item.id, userId);
//                     // let services = await Request.getAllServiceByRequest(item.request_id);
//                     // let serviceExpense = services.reduce((total, currentItem) => total + (currentItem.qty * currentItem.originalCost), 0);
//                     // let payoutPrice = payout.reduce((total, currentItem) => total + currentItem.amount, 0);

//                     // let expense = price + payoutPrice + Math.max(0, (serviceExpense - payoutPrice))
//                     // item.progressValue = (expense / parseFloat(item.cost)) * 100
//                     // if (item.progressValue > 100) {
//                     //     item.progressValue = 100
//                     // }
//                     let selectedMaterials = await JobCost.fetchAllJobCostProjectId(item.id);
//                     let price = selectedMaterials.reduce((total, currentItem) => {
//                     if (currentItem.taken === 1) {
//                         return total + currentItem.total;
//                     }
//                     return total;
//                     }, 0);

//                     let payout = await JobCost.fetchAllPayOutByProjectId(item.id, userId);
//                     let services = await Request.getAllServiceByRequest(item.request_id);

//                     let serviceExpense = services.reduce((total, currentItem) => {
//                     if (currentItem.taken === 1) {
//                         return total + (currentItem.qty * currentItem.originalCost);
//                     }
//                     return total;
//                     }, 0);

//                     let payoutPrice = payout.reduce((total, currentItem) => total + currentItem.amount, 0);

//                     let expense = price + payoutPrice + Math.max(0, (serviceExpense - payoutPrice));

//                     const parsedCost = parseFloat(item.cost) || 0;
//                     if (Number(item.status) === 1 || parsedCost <= 0) {
//                         item.progressValue = 0;
//                     } else {
//                         item.progressValue = (expense / parsedCost) * 100;
//                         if (item.progressValue > 100) {
//                             item.progressValue = 100;
//                         }
//                     }

//                     let image = await Request.FetchAllApprovedDesigns(item.request_id);
//                     let coverImage = image?.filter((imageItem)=>imageItem?.file_type?.startsWith('image/') || imageItem?.file_type ==='img')
//                     let linkedItems = image?.find((imageItem) => imageItem?.location_ids !== null);
//                     let firstItemWithLocationIds = linkedItems
//                     let ApprovedPdf = image[0]
//                     if (!empty(coverImage[0])) {
//                         item.cover_image = coverImage[0].name ? coverImage[0].name : ""
//                     }
//                     else {
//                         item.cover_image = ""
//                     }
//                     if (!empty(firstItemWithLocationIds)) {
//                         item.approved_pdf = firstItemWithLocationIds?.name ? firstItemWithLocationIds?.name : ""
//                     }
//                     else {
//                         item.approved_pdf = ApprovedPdf?.name ? ApprovedPdf?.name : ""
//                     }

//                     return item;
//                 }));
//                 return results?.map(record => parseDecimalFields(record));
//             } else {
//                 // return data;
//                 const results = await Promise.all(data.map(async (item) => {
//                     let image = await Request.FetchAllApprovedDesigns(item.request_id);
//                     let coverImage = image?.filter((imageItem)=>imageItem?.file_type?.startsWith('image/') || imageItem?.file_type ==='img')
//                     let linkedItems = image?.find((imageItem) => imageItem?.location_ids !== null);
//                     let firstItemWithLocationIds = linkedItems
//                     let ApprovedPdf = image[0]
//                     if (!empty(coverImage[0])) {
//                         item.cover_image = coverImage[0]?.name ? coverImage[0]?.name : ""
//                     }
//                     else {
//                         item.cover_image = ""
//                     }
//                     if (!empty(firstItemWithLocationIds)) {
//                         item.approved_pdf = firstItemWithLocationIds?.name ? firstItemWithLocationIds?.name : ""
//                     }
//                     else {
//                         item.approved_pdf = ApprovedPdf?.name ? ApprovedPdf?.name : ""
//                     }
//                     return item;
//                 }));
//                 return results?.map(record => parseDecimalFields(record));
//                 // return data?.map(record => parseDecimalFields(record));
//             }


//         } else {
//             return false;
//         }
//     } catch (error) {
//         console.log("#####################Error", error);
//         throw new Error("Server error");
//     }
// }

const getAllcompletedInstallationsForCommunityCount = async (hasPermission, all = false, userType, userId, sort, where = [], fromDate, toDate,dueData,filterProjectType, currentTab, page = 1, limit = 6, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = [], splitOrder = false) => {
    try {
        let estimateCondition = ' AND p.is_estimate_job=0';
        let whereCondition;
        const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
        const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
        const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
        let dateCondition = '';
        if (fromTimestamp && toTimestamp) {
          dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
        } else if (fromTimestamp) {
          dateCondition = ` p.installation_date >= ${fromTimestamp}`;
        } else if (toTimestamp) {
          dateCondition = ` p.installation_date <= ${toTimestamp}`;
        }
        // else if (dueTimestamp) {
        //     dateCondition = ` p.installation_date <= ${dueTimestamp}`;
        // }
        let query = ''
        if (all) {
            whereCondition = ` p.status != 2`;
        } else {
            whereCondition = ` p.status = 1`;
        }
        if (!empty(where)) {

        }
        // if (splitOrder === 1) {
        //     whereCondition += whereCondition ? ` AND r.is_split_order = 1` : ` r.is_split_order = 1`;
        // } else if (splitOrder === 2) {
        //     whereCondition += whereCondition ? ` AND r.is_split_order = 0` : ` r.is_split_order = 0`;
        // }

        let createdAt = ''
        if (dueTimestamp) {
            createdAt=`ORDER BY p.installation_date ASC`
        }else{
            if(sort==='new'){
                createdAt = `ORDER BY p.id DESC `
            }else if(sort==='old'){
                createdAt = `ORDER BY p.id ASC `
            }else if(sort === 'custom_order'){
                createdAt=`ORDER BY p.card_order ASC`
            }else{
                createdAt=`ORDER BY p.timestamp DESC`
            }
        }

        let projectTypeCondition = '';
if (filterProjectType === 1) {
  projectTypeCondition = ` p.project_type = 1`;
} else if (filterProjectType === 2) {
  projectTypeCondition = ` p.project_type = 2`;
} else if (filterProjectType === 'NULL') {
  projectTypeCondition = ` p.project_type IS NULL`;
} else {
  projectTypeCondition = ` (p.project_type IS NULL OR p.project_type IS NOT NULL)`;
}

        // Add job class filtering condition
        let jobClassCondition = '';
        if (jobClassFilter && jobClassFilter.length > 0) {
            const jobClassIds = jobClassFilter.join(',');
            jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
        }

        // Add job types filtering condition
        let jobTypesCondition = '';
        if (jobTypesFilter && jobTypesFilter.length > 0) {
            const jobTypesIds = jobTypesFilter.join(',');
            jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
        }

        // Add client filtering condition
        let clientCondition = '';
        if (clientFilter && clientFilter.length > 0) {
            const clientIds = clientFilter.join(',');
            clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
        }

        // Add user filtering condition
        let userCondition = '';
        if (userFilter && userFilter.length > 0) {
            const userIds = userFilter.join(',');
            userCondition = ` AND EXISTS (
                SELECT 1 FROM project_members pm 
                WHERE pm.project_id = p.id 
                AND pm.staff_id IN (${userIds})
            )`;
        }

        // Add project filtering condition
        let projectCondition = '';
        if (projectFilter && projectFilter.length > 0) {
            // Check if 'other' is included in the filter
            const hasOther = projectFilter.includes('other');
            const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
            if (hasOther && numericIds.length > 0) {
                // Include both specific communities and null/other communities
                projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
            } else if (hasOther) {
                // Only 'other' is selected
                projectCondition = ` AND p.community IS NULL`;
            } else {
                // Only specific communities are selected
                projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
            }
        }

        let departmentCondition = '';
        if (departmentFilter && departmentFilter.length > 0) {
            const departmentIds = departmentFilter.join(',');
          
            // departmentCondition = `
            //     AND EXISTS (
            //       SELECT 1
            //       FROM project_members pm
            //       INNER JOIN staff_members sm ON pm.staff_id = sm.id
            //       INNER JOIN users u ON sm.user_id = u.id
            //       WHERE pm.project_id = p.id
            //       AND u.department_id IN (${departmentIds})
            //     )
            //   `;
            departmentCondition = `
            AND EXISTS (
              SELECT 1
              FROM project_members pm_dep
              INNER JOIN staff_members sm_dep ON pm_dep.staff_id = sm_dep.id
              INNER JOIN users u_dep ON sm_dep.user_id = u_dep.id
              WHERE pm_dep.project_id = p.id
              AND u_dep.department_id IN (${departmentIds})
            )
          `;
          }
        // Add search condition
        let searchCondition = '';
        if (search && search.trim() !== '') {
            searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR r.doc_number LIKE '%${search}%' OR r.est_doc_number LIKE '%${search}%')`;
        }

        // Add currentTab filtering condition for remaining tabs
        let tabCondition = '';
        let splitMirrorCondition = '';
        // Keep Change Order behavior consistent with getAllProjects:
        // - Show only change orders on "Change Order" tab
        // - Hide change orders from all other tabs (except Hold)
        let changeOrderBaseCondition = '';
        let changeOrderExclusion = '';
        if (currentTab === 'Hold') {
            tabCondition = ` p.hold = 1`;
        } else if (currentTab === 'Pre-Production') {
            tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0`;
        } else if (currentTab === 'Production') {
            tabCondition = ` p.hold = 0 AND p.status = 2 `;
        } else if (currentTab === 'Change Order') {
            tabCondition = ` p.hold = 0 AND p.change_order = 1`;
        } else if (currentTab === 'Installs') {
            // Include installation_pending_review (all done, awaiting review) in Installs tab, not Completed
            tabCondition = ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND r.status != 3 AND p.status = 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1) OR ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND COALESCE(i.pending_review, 0) = 1)) OR (COALESCE(i.pending_review, 0) = 2) `;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1)`;
        } else if (currentTab === 'Pickup') {
            tabCondition = ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2))`;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2)`;
        } else if (currentTab === 'Shipping') {
            tabCondition = ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3))`;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3)`;
        } else if (currentTab === 'Completed') {
            // Exclude installation_pending_review (show those in Installs tab instead)
            tabCondition = ` (((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND r.isReview != 2 AND r.installation_acceptance = 1) OR (p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND r.isReview != 2 AND r.installation_acceptance = 1) OR r.status = 10 OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)) AND (COALESCE(i.pending_review, 0) != 1) AND (COALESCE(i.pending_review, 0) != 2)`;
         splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)`;
        } else if (currentTab === 'T & M Review') {
            // Original frontend condition: (item.allInstallationCompleted === 1 && item?.installation_acceptance !==1 && item.project_status == 3 && item.project_category == 12 && item.isReview ==2)
            tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)  AND p.status = 3 AND p.project_category = 12 AND r.isReview = 2`;
        } else if (currentTab === 'Cost Card') {
            // Original frontend condition: (item.allInstallationCompleted === 1 && item?.installation_acceptance !==1 && item.project_status == 3 && item.project_category !== 12 )
            tabCondition = ` ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) OR (total_inst_counts.total_installation_count IS NULL))  AND p.status = 3 AND p.project_category != 12 AND r.installation_acceptance IS NULL AND (COALESCE(i.pending_review, 0) NOT IN (1, 2)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4) `;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4)`;
            console.log('tabCondition+++++++', tabCondition)
        }

        if (currentTab === 'Change Order') {
            changeOrderBaseCondition = ` OR (p.change_order = 1)`;
        }
        if (currentTab !== 'Change Order' && currentTab !== 'Hold' && currentTab !== 'ALL') {
            changeOrderExclusion = ` (p.change_order IS NULL OR p.change_order = 0)`;
        }
console.log('testtttttttttt');

        if (userType === 1 || userType == 8) {
            query = await sequelize.query(
                ` SELECT p.* FROM projects p ` 
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
                + ` INNER JOIN requests r ON p.request_id = r.id `
                + ` LEFT JOIN (
                        SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, 
                         SUM(
                                CASE
                                WHEN cop.is_single_card = 1 THEN 1
                                ELSE cop.location_quantity
                                END
                            ) AS product_count
                        FROM customer_orders co
                        JOIN customer_order_products cop ON co.id = cop.order_id
                        JOIN requests req ON co.request_id = req.id
                        WHERE cop.material = 0
                        GROUP BY co.request_id
                    ) cop ON r.id = cop.request_id `

                + ` LEFT JOIN (
                        SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                        FROM customer_orders co
                        JOIN  requests rqs ON co.request_id = rqs.id
                        JOIN  request_services rss ON co.request_id = rss.request_id
                        JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                        WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                        GROUP BY co.request_id
                    ) rss ON r.id = rss.request_id `

                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id`
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id`
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` left join partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` where (((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
                        r.noServiceNoTask = 0 AND r.status=4) OR (i.status IS NOT NULL)${changeOrderBaseCondition}) ${splitMirrorCondition})  
                         ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
                         ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
                         ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
                         ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} GROUP BY p.id ${createdAt}`
                        // ${dateCondition!= '' ? ' AND '+dateCondition : ''} AND ${projectTypeCondition} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${departmentCondition != '' ? departmentCondition : ''} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} ${createdAt} LIMIT ${limit} OFFSET ${(page - 1) * limit}`
            );

        }
        else if (userType === 3) {
            query = await sequelize.query(
                ` SELECT p.* FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` left join request_partners rp on rp.request_id=p.request_id`
                + ` left join partners pr on pr.id=rp.partner_id`
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
                + ` INNER JOIN requests r ON p.request_id = r.id `
                + ` LEFT JOIN (
                    SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity,
                     SUM(
                            CASE
                            WHEN cop.is_single_card = 1 THEN 1
                            ELSE cop.location_quantity
                            END
                        ) AS product_count
                    FROM customer_orders co
                    JOIN customer_order_products cop ON co.id = cop.order_id
                    JOIN requests req ON co.request_id = req.id
                    WHERE cop.material = 0
                    GROUP BY co.request_id
                ) cop ON r.id = cop.request_id `

                + ` LEFT JOIN (
                    SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                    FROM customer_orders co
                    JOIN  requests rqs ON co.request_id = rqs.id
                    JOIN  request_services rss ON co.request_id = rss.request_id
                    JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                    WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                    GROUP BY co.request_id
                ) rss ON r.id = rss.request_id `

                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id`
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` left join partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` where pr.user_id=${userId} and ((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
                        r.noServiceNoTask = 0 AND r.status=4) OR  (i.status IS NOT NULL)${changeOrderBaseCondition}) 
                          ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
                         ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
                         ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
                         ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} GROUP BY p.id ${createdAt} `
                        // ${dateCondition!= '' ? ' AND '+dateCondition : ''} AND ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${createdAt}`
            );
        }
        else {
            query = await sequelize.query(
                `SELECT p.* FROM projects p 
                LEFT JOIN staff_members s1 ON s1.id=p.project_lead  
                LEFT JOIN users u1 ON s1.user_id=u1.id 
                LEFT JOIN project_categories pc ON pc.id=p.project_category 
                LEFT JOIN project_types ptp ON ptp.id=p.project_type 
                LEFT JOIN staff_members s2 ON s2.id=p.default_assignee 
                LEFT JOIN users u2 ON s2.user_id=u2.id 
                LEFT JOIN installations i2 ON p.id=i2.project_id 
                LEFT JOIN driver dr ON i2.driver_id=dr.id 
                LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id 
                    from project_members pm 
                    left join partners p on p.id=pm.partner_id 
                    left join users u on p.user_id=u.id 
                    left join staff_members s on s.id=pm.staff_id 
                    left join users u2 on s.user_id=u2.id) pmm 
                    ON pmm.project_id=p.id and pmm.user_id=${userId} 
                LEFT JOIN users u ON p.added_by=u.id 
                LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  
                LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  
                INNER JOIN requests r ON p.request_id = r.id 
                LEFT JOIN users ura ON r.added_by=ura.id 
                LEFT JOIN (
                    SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, 
                     SUM(
                    CASE
                      WHEN cop.is_single_card = 1 THEN 1
                      ELSE cop.location_quantity
                    END
                  ) AS product_count
                    FROM customer_orders co
                    JOIN customer_order_products cop ON co.id = cop.order_id
                    JOIN requests req ON co.request_id = req.id
                    WHERE cop.material = 0
                    GROUP BY co.request_id
                ) cop ON r.id = cop.request_id 
                LEFT JOIN (
                    SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                    FROM customer_orders co
                    JOIN  requests rqs ON co.request_id = rqs.id
                    JOIN  request_services rss ON co.request_id = rss.request_id
                    JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                    WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                    GROUP BY co.request_id
                ) rss ON r.id = rss.request_id 
                -- ✅ FIX: Include complete_status in installations join
                LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id 
                LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id 
                LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id
                LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id
                LEFT JOIN customer_orders c_ord ON c_ord.request_id = p.request_id 
                LEFT JOIN partners part ON part.id = c_ord.customer_id 
                LEFT JOIN community com ON com.id=p.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1 
                WHERE (u1.id = ${userId} OR u2.id = ${userId} OR pmm.user_id =${userId} OR (r.added_by = ${userId} AND ura.user_type <> 3) OR FIND_IN_SET(${userId}, i2.team_id) OR FIND_IN_SET(${userId}, dr.user_id)) 
                AND ((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
                        r.noServiceNoTask = 0 AND r.status=4) OR  (i.status IS NOT NULL)${changeOrderBaseCondition}) 
                         ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
                         ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
                         ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
                         ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} GROUP BY p.id ${createdAt} `
                        // ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition != '' ? ' AND ' + tabCondition : ''} GROUP BY p.id ${createdAt}`
            );
            
        }
        let data;
        if (query.length > 0) {
            data = query[0];
            return data;
        } else {
            return [];
        }
    } catch (error) {
        console.log("#####################Error", error);
        return [];
    }
}

const updateCardOrder = async (cards) => {
    if (!cards || !cards.length) {
      return false;
    }
    try {
      const updatePromises = cards.map((card, index) => {
        return Projects.update(
          { card_order: index },
          { where: { id: card.id } }
        );
      });
  
      await Promise.all(updatePromises);
  
      return true;
    } catch (error) {
      console.log("Error updating card order:", error);
      throw new Error("Error updating card order");
    }
  };
const updateEstimateCardOrder = async (cards) => {
    if (!cards || !cards.length) {
      return false;
    }
    try {
      const updatePromises = cards.map((card, index) => {
        return EstimateProjects.update(
          { card_order: index },
          { where: { id: card.id } }
        );
      });
  
      await Promise.all(updatePromises);
  
      return true;
    } catch (error) {
      console.log("Error updating card order:", error);
      throw new Error("Error updating card order");
    }
  };

  const findProjectById = async (id,request) => {
    try {
        let results =null
        if(request){
            results = await sequelize.query(
                ' SELECT p.*,r.map_service AS map_service_id,co.id as order_id,c.name as community_name,r.doc_number,r.is_single_card,CONCAT(u.first_name, " ", u.last_name) AS client_name,r.origin_facility_id,r.origin_facility_request_id,r.is_split_order,r.for_parent_facility FROM projects p'
                +' left join customer_orders co on co.request_id=p.request_id'
                +' left join requests r on r.id=p.request_id'
                +' left join request_partners rpt on r.id=rpt.request_id'
                +' left join partners pt on rpt.partner_id=pt.id'
                +' left join users u on pt.user_id=u.id'
                +' left join community c on r.community=c.id'
                +' WHERE p.request_id = :id',
                {
                    replacements: { id },  
                    type: sequelize.QueryTypes.SELECT,  
                }
            );
        }else{
            results = await sequelize.query(
                ' SELECT p.*,r.map_service AS map_service_id,co.id as order_id,c.name as community_name,r.doc_number,r.is_single_card,CONCAT(u.first_name, " ", u.last_name) AS client_name,r.origin_facility_id,r.origin_facility_request_id,r.is_split_order,r.for_parent_facility FROM projects p'
                +' left join customer_orders co on co.request_id=p.request_id'
                +' left join requests r on r.id=p.request_id'
                +' left join request_partners rpt on r.id=rpt.request_id'
                +' left join partners pt on rpt.partner_id=pt.id'
                +' left join users u on pt.user_id=u.id'
                +' left join community c on r.community=c.id'
                +' WHERE p.id = :id',
                {
                    replacements: { id },  
                    type: sequelize.QueryTypes.SELECT,  
                }
            );
        }
        if (results && results.length > 0) {
            return results[0];  
        } else {
            return false; 
        }
    } catch (error) {
        console.error("Error finding the project by ID: ", error);
        return false;
    }
};


const getAllDesignOrderJobs = async (hasPermission, all = false, userType, userId, where = [],sort,fromDate,toDate,dueData,currentTab,filterClient, fromCalendar, page = 1, limit = false, search) => {
    try {
        const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
        const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
        const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
  
        let limitCondition = ''
        if (limit){
            limitCondition = ` LIMIT ${limit} OFFSET ${(page - 1) * limit}`
        }

        let dateCondition = '';
        if (!fromCalendar) {
        if (fromTimestamp && toTimestamp) {
          dateCondition = ` AND do.due_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
        } else if (fromTimestamp) {
          dateCondition = ` AND do.due_date >= ${fromTimestamp}`;
        } else if (toTimestamp) {
          dateCondition = ` AND do.due_date <= ${toTimestamp}`;
        }
          // else if (dueTimestamp) {
          //     dateCondition = ` p.installation_date <= ${dueTimestamp}`;
          // }
        }
  
        let createdAt = ''
        if (dueTimestamp) {
            createdAt=`ORDER BY do.due_date ASC`
        }else{
            if(sort==='new'){
                createdAt = `ORDER BY do.id DESC `
            }else if(sort==='old'){
                createdAt = `ORDER BY do.id ASC `
            }else if(sort === 'custom_order'){
                createdAt=`ORDER BY do.card_order ASC`
            }else{
                createdAt=`ORDER BY do.timestamp DESC`
            }
        }
        let whereCondition;
        let query = ''
        if (all) {
            // For Production tab, allow status 2; for other tabs, exclude status 2
            if (currentTab === 'Production') {
                whereCondition = ` (p.status != 0 AND p.status != 1 AND p.status != 3)`;
            } else if (currentTab === 'ALL') {
                whereCondition = ` p.status != 0`;
            }
            else {
                whereCondition = ` p.status != 2`;
            }
        } else {
            whereCondition = ` p.status = 1`;
        }
        if (!empty(where)) {
  
        }
        let condition = ''
        if (currentTab) {
            if (currentTab === "New") {
              condition = "AND do.design_order_job_status = 1 AND do.hold=0";
            } else if (currentTab === "In-Progress") {
              condition = "AND do.design_order_job_status = 2 AND do.hold=0";
            } else if (currentTab === "Completed") {
              condition = "AND do.design_order_job_status = 3 AND do.hold=0";
            } else if (currentTab === "Rejected") {
              condition = "AND do.design_order_job_status = 4 AND do.hold=0";
            } else {
              condition = "AND do.hold=1";
            }
          }
        const designerCondition = ` AND (do.working_designer_id IS NULL OR do.working_designer_id = ${userId}) `;

        let clientFilterCondition = '';
        if (filterClient && Array.isArray(filterClient) && filterClient.length > 0) {
            const clientIds = filterClient.map(id => parseInt(id)).filter(id => !isNaN(id));
            if (clientIds.length > 0) {
                clientFilterCondition = ` AND do.client IN (${clientIds.join(',')})`;
            }
        }
        let searchCondition = ''
        if (search) {
            const escapedSearch = search.replace(/'/g, "''").trim();
            const normalizedSearch = escapedSearch.toLowerCase();
            const searchNoHash = normalizedSearch.replace(/^#/, ''); 
            searchCondition = `AND (
                CAST(do.id AS CHAR) LIKE '%${searchNoHash}%'
                OR LOWER(COALESCE(do.name, '')) LIKE '%${normalizedSearch}%'
                OR LOWER(COALESCE(do.description, '')) LIKE '%${normalizedSearch}%'
                OR LOWER(COALESCE(p.name, '')) LIKE '%${normalizedSearch}%'
            `;
            
            // if (userType !== 3 && !isClient) {
            if (userType !== 3) {
                searchCondition += ` OR LOWER(COALESCE(com.name, '')) LIKE '%${normalizedSearch}%'`;
            }
            
            searchCondition += `)`;
        }

        if (userType === 1 || userType == 8) {
            query = await sequelize.query(`
                SELECT DISTINCT do.*,com.name AS community_name,'designJob' As projectType,p.name As customer_name,p.id As customer_id FROM design_orders do
                INNER JOIN design_order_services dos ON do.id = dos.design_order_id
                LEFT JOIN community com ON do.community = com.id 
                LEFT JOIN partners p ON do.client = p.id
                WHERE do.status NOT IN (0, 3, 4) ${condition} ${searchCondition} ${dateCondition} ${clientFilterCondition} ${createdAt} ${limitCondition}`
            );
        } else if (userType === 3) {
            query = await sequelize.query(`
                SELECT DISTINCT do.*,com.name AS community_name,'designJob' As projectType ,p.name As customer_name,p.id As customer_id FROM design_orders do
                INNER JOIN design_order_services dos ON do.id = dos.design_order_id
                LEFT JOIN community com ON do.community = com.id 
                LEFT JOIN partners p ON do.client = p.id
                WHERE p.user_id=${userId} AND do.status NOT IN (0, 3,4) ${condition} ${searchCondition} ${dateCondition} ${clientFilterCondition} ${createdAt} ${limitCondition}`
            );
        // }else {
        //     query = await sequelize.query(`
        //         SELECT DISTINCT do.*,com.name AS community_name,p.name As customer_name,p.id As customer_id, concat(sm.first_name, ' ', sm.last_name) as staff_name FROM design_orders do
        //         INNER JOIN design_order_services dos ON do.id = dos.design_order_id
        //         LEFT JOIN community com ON do.community = com.id 
        //         LEFT JOIN partners p ON do.client = p.id
        //         LEFT JOIN design_order_project_members pm ON do.id = pm.design_order_id
        //         LEFT JOIN staff_members sm ON pm.staff_id = sm.id
        //         WHERE (sm.user_id=${userId} OR do.added_by = ${userId})
        //         AND do.status NOT IN (0, 3) 
        //         ${condition} 
        //         ${designerCondition}
        //         ${createdAt}`
        //     );
        // }
        }else {
            query = await sequelize.query(`
                SELECT DISTINCT do.*,com.name AS community_name,p.name As customer_name,p.id As customer_id FROM design_orders do
                INNER JOIN design_order_services dos ON do.id = dos.design_order_id
                LEFT JOIN community com ON do.community = com.id 
                LEFT JOIN partners p ON do.client = p.id
                WHERE (do.id IN (SELECT pm.design_order_id FROM design_order_project_members pm 
                       INNER JOIN staff_members sm ON pm.staff_id = sm.id 
                       WHERE sm.user_id = ${userId}) OR do.added_by = ${userId}) 
                AND do.status NOT IN (0, 3, 4) 
                ${condition} ${searchCondition}
                ${designerCondition}
                ${dateCondition} ${clientFilterCondition} ${createdAt} ${limitCondition}`
            );
        }
        // }else {
        //     query = await sequelize.query(`
        //         SELECT DISTINCT do.*,com.name AS community_name,p.name As customer_name,p.id As customer_id, concat(sm.first_name, ' ', sm.last_name) as staff_name FROM design_orders do
        //         INNER JOIN design_order_services dos ON do.id = dos.design_order_id
        //         LEFT JOIN community com ON do.community = com.id 
        //         LEFT JOIN partners p ON do.client = p.id
        //         LEFT JOIN design_order_project_members pm ON do.id = pm.design_order_id
        //         LEFT JOIN staff_members sm ON pm.staff_id = sm.id
        //         WHERE (sm.user_id=${userId} OR do.added_by = ${userId}) AND do.status NOT IN (0, 3) ${condition} ${createdAt}`
        //     );
        // }
        let data;
        if (query.length > 0) {
            data = query[0];
            if (userType == 1 || userType == 8) {
                const results = await Promise.all(data.map(async (item) => {
                    let taskData = await Request.getDesignOrderById(item.id)
                    item.taskData = taskData || [];
                    item.task_count =taskData?.length || 0

                    let attachment = await Request.getAllDesignOrderAttachments(item.id)
                    // item.attachment=attachment || []
                    item.attachment=item?.status == 2 ? (attachment?.filter(imageItem=>(imageItem?.file_type?.startsWith("image") || imageItem?.file_type === "img")) || []) : []
  
                    let reference_attachment = await Request.getAllDesignOrderReferenceAttachments(item.id)
                    item.reference_attachment=item?.status == 2 ? (reference_attachment?.filter(imageItem=>(imageItem?.file_type?.startsWith("image") || imageItem?.file_type === "img")) || []) : []
  
                    // let selectedMaterials = await JobCost.fetchAllJobCostProjectId(item.id);
                    // let price = selectedMaterials?.filter(curr => curr.taken === 1)?.reduce((total, currentItem) => { return total + currentItem.total }, 0);
                  
                    // let payout = await JobCost.fetchAllPayOutByProjectId(item.id, userId);

                    // let services = await Request.getAllServiceByRequest(item.request_id);
                    // let services = await Request.getAllServiceByDesignOrder(item.id);
                    // let serviceExpense = services?.filter(curr => curr.taken === 1)?.reduce((total, currentItem) => { return total + (currentItem.qty * currentItem.originalCost) }, 0);
                    // let payoutPrice = payout.reduce((total, currentItem) => total + currentItem.amount, 0);
  
                    // let expense = price + payoutPrice + Math.max(0, (serviceExpense - payoutPrice))
                    // item.progressValue = (expense / parseFloat(item.cost)) * 100
                    // if (item.progressValue > 100) {
                    //     item.progressValue = 100
                    // }
                    // let image = await Request.FetchAllApprovedDesigns(item.request_id);
                    // image = image?.filter((imageItem)=>imageItem?.file_type?.startsWith('image/') || imageItem?.file_type ==='img')
                    // if (!empty(image[0])) {
                    //     item.cover_image = image[0].name ? image[0].name : ""
                    // }
                    // else {
                    //     item.cover_image = ""
                    // }
  
                    return item;
                }));
                // return results;
                return results.map(record => parseDecimalFields(record));
            } else {
                const results = await Promise.all(data.map(async (item) => {
                    let taskData = await Request.getDesignOrderById(item.id)
                    item.taskData = taskData || [];
                    item.task_count =taskData?.length || 0

                    let attachment = await Request.getAllDesignOrderAttachments(item.id)
                    // item.attachment=attachment || []
                    item.attachment=item?.status == 2 ? (attachment?.filter(imageItem=>(imageItem?.file_type?.startsWith("image") || imageItem?.file_type === "img")) || []) : []
                    
                    let reference_attachment = await Request.getAllDesignOrderReferenceAttachments(item.id)
                    item.reference_attachment=item?.status == 2 ? (reference_attachment?.filter(imageItem=>(imageItem?.file_type?.startsWith("image") || imageItem?.file_type === "img")) || []) : []

                    // Fetch staff names for this design order
                    let staffQuery = await sequelize.query(`
                        SELECT CONCAT(sm.first_name, ' ', sm.last_name) as staff_name 
                        FROM design_order_project_members pm 
                        INNER JOIN staff_members sm ON pm.staff_id = sm.id 
                        WHERE pm.design_order_id = ${item.id}
                    `);
                    item.staff_name = staffQuery[0]?.map(staff => staff.staff_name).join(', ') || '';
  
                //     let image = await Request.FetchAllApprovedDesigns(item.id);
                //     image = image?.filter((imageItem)=>imageItem?.file_type?.startsWith('image/') || imageItem?.file_type ==='img')
                //     if (!empty(image[0])) {
                //         item.cover_image = image[0].name ? image[0].name : ""
                //     }
                //     else {
                //         item.cover_image = ""
                //     }
  
                    return item;
                }));
                return results?.map(record => parseDecimalFields(record));
            }

        } else {
            return false;
        }
    } catch (error) {
        console.log(error);
        throw new Error("Server error");
    }
  }

const getTotalDesignOrderJobsCount = async (hasPermission, all = false, userType, userId, where = [], sort, fromDate, toDate, dueData, currentTab, filterClient, search) => {
    try {
        const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
        const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
        const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
  
        let dateCondition = '';
        if (fromTimestamp && toTimestamp) {
          dateCondition = ` AND do.due_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
        } else if (fromTimestamp) {
          dateCondition = ` AND do.due_date >= ${fromTimestamp}`;
        } else if (toTimestamp) {
          dateCondition = ` AND do.due_date <= ${toTimestamp}`;
        }

        let condition = ''
        if (currentTab) {
            if (currentTab === "New") {
              condition = "AND do.design_order_job_status = 1 AND do.hold=0";
            } else if (currentTab === "In-Progress") {
              condition = "AND do.design_order_job_status = 2 AND do.hold=0";
            } else if (currentTab === "Completed") {
              condition = "AND do.design_order_job_status = 3 AND do.hold=0";
            } else if (currentTab === "Rejected") {
              condition = "AND do.design_order_job_status = 4 AND do.hold=0";
            } else {
              condition = "AND do.hold=1";
            }
          }
        const designerCondition = ` AND (do.working_designer_id IS NULL OR do.working_designer_id = ${userId}) `;
        
        let clientFilterCondition = '';
        if (filterClient && Array.isArray(filterClient) && filterClient.length > 0) {
            const clientIds = filterClient.map(id => parseInt(id)).filter(id => !isNaN(id));
            if (clientIds.length > 0) {
                clientFilterCondition = ` AND do.client IN (${clientIds.join(',')})`;
            }
        }

        let searchCondition = ''
        if (search) {
            const escapedSearch = search.replace(/'/g, "''").trim();
            const normalizedSearch = escapedSearch.toLowerCase();
            const searchNoHash = normalizedSearch.replace(/^#/, ''); 
            searchCondition = `AND (
                CAST(do.id AS CHAR) LIKE '%${searchNoHash}%'
                OR LOWER(COALESCE(do.name, '')) LIKE '%${normalizedSearch}%'
                OR LOWER(COALESCE(do.description, '')) LIKE '%${normalizedSearch}%'
                OR LOWER(COALESCE(p.name, '')) LIKE '%${normalizedSearch}%'
            `;
            
            // if (userType !== 3 && !isClient) {
            if (userType !== 3) {
                searchCondition += ` OR LOWER(COALESCE(com.name, '')) LIKE '%${normalizedSearch}%'`;
            }
            
            searchCondition += `)`;
        }

        let countQuery;
        if (userType === 1 || userType == 8) {
            countQuery = await sequelize.query(`
                SELECT COUNT(DISTINCT do.id) as totalCount FROM design_orders do
                INNER JOIN design_order_services dos ON do.id = dos.design_order_id
                LEFT JOIN community com ON do.community = com.id 
                LEFT JOIN partners p ON do.client = p.id
                WHERE do.status NOT IN (0, 3,4) ${condition} ${searchCondition} ${dateCondition} ${clientFilterCondition}`
            );
        } else if (userType === 3) {
            countQuery = await sequelize.query(`
                SELECT COUNT(DISTINCT do.id) as totalCount FROM design_orders do
                INNER JOIN design_order_services dos ON do.id = dos.design_order_id
                LEFT JOIN community com ON do.community = com.id 
                LEFT JOIN partners p ON do.client = p.id
                WHERE p.user_id=${userId} AND do.status NOT IN (0, 3,4) ${condition} ${searchCondition} ${dateCondition} ${clientFilterCondition}`
            );
        } else {
            countQuery = await sequelize.query(`
                SELECT COUNT(DISTINCT do.id) as totalCount FROM design_orders do
                INNER JOIN design_order_services dos ON do.id = dos.design_order_id
                LEFT JOIN community com ON do.community = com.id 
                LEFT JOIN partners p ON do.client = p.id
                WHERE (do.id IN (SELECT pm.design_order_id FROM design_order_project_members pm 
                       INNER JOIN staff_members sm ON pm.staff_id = sm.id 
                       WHERE sm.user_id = ${userId}) OR do.added_by = ${userId}) 
                AND do.status NOT IN (0, 3, 4) 
                ${condition} ${searchCondition}
                ${designerCondition}
                ${dateCondition} ${clientFilterCondition}`
            );
        }

        if (countQuery && countQuery[0] && countQuery[0][0]) {
            return countQuery[0][0].totalCount || 0;
        }
        return 0;
    } catch (error) {
        console.log(error);
        throw new Error("Server error");
    }
  }

  const getDesignOrderProjectById = async (id) => {
    try {
        let query = await sequelize.query(`
            SELECT do.*, coalesce(pm.count, 0) as member_count, coalesce(pf.count, 0) as attachment_count, coalesce(pfr.count, 0) as reference_attachment_count, coalesce(pt.completed_count, 0) as completed_task_count, coalesce(pt.pending_count, 0) as pending_task_count FROM design_orders do
            LEFT JOIN (select count(id) as count, design_order_id from design_order_project_members group by design_order_id) pm ON pm.design_order_id=do.id 
            LEFT JOIN (select count(id) as count, is_reference, design_order_id from design_order_attachments group by design_order_id, is_reference) pf ON pf.design_order_id=do.id AND pf.is_reference = 0
            LEFT JOIN (select count(id) as count, is_reference, design_order_id from design_order_attachments group by design_order_id, is_reference) pfr ON pfr.design_order_id=do.id AND pfr.is_reference = 1
            LEFT JOIN (select sum(case when status=3 then 1 else 0 end) as completed_count, sum(case when status!=3 then 1 else 0 end) as pending_count, design_order_id from design_order_services where status!=0 group by design_order_id) pt ON pt.design_order_id=do.id 
            WHERE do.id =${id}`
        );
        if (query[0].length === 1) {
            // return query[0][0];
            let data = query[0][0];
            // return data?.map(record => parseDecimalFields(record));
            return parseDecimalFields(data);
        } else {
            return false;
        }

    } catch (error) {
        console.log("Server error1111" + error);
        throw new Error("Server error");
    }
}

const addJobsTabCount = async (data) => {
    try {
      console.log('jobs order adding')
      const [newOrderCount, created] = await JobsTabCount.findOrCreate({
        where: { user_id: data.user_id },
        defaults: { 
          hold_count: 0,
          pre_production_count: 0,
          production_count: 0,
          installs_count: 0,
          pickup_count: 0,
          shipping_count: 0,
          completed_count: 0,
          timestamp: data.timestamp
        }
      });
      console.log("Jobs order count added")
  
      return newOrderCount.id;
    } catch (error) {
      console.error('Failed to add jobs tab count:', error);
      throw error;
    }
  };

  const updateJobsTabCount = async (userId, data) => {
    try{
      let result = await JobsTabCount.update(data, {
        where: { user_id: userId }
      })
      if (result[0] > 0) {
        return true;
      } else {
        return false;
      }
    }catch(error){
      console.log('Error : ',error);
      return error
    }
  }

  const getJobsTabByUserId = async (userId) => {
    try {
      const orderCount = await JobsTabCount.findOne({
        where: { user_id: userId },
        attributes: ['id']
      });
  
      if (orderCount) {
        return orderCount;
      } else {
        return "No record found";
      }
    } catch (error) {
      console.error('Error retrieving jobs count:', error);
      return error;
    }
  }

  const getJobsTabByUserData = async (userId) => {
    try {
      const orderCount = await JobsTabCount.findOne({
        where: { user_id: userId },
      });
  
      if (orderCount) {
        return orderCount;
      } else {
        return "No record found";
      }
    } catch (error) {
      console.error('Error retrieving Jobs count:', error);
      return error;
    }
  }

  const jobTabIncrementField = async (userId, field, amount, fieldIds, projectId, increase = true) => {
    try {
      const userCount = await JobsTabCount.findOne({ where: { user_id: userId } });
  
      if (!userCount) {
        console.warn(`No record found for userId: ${userId}`);
        return false;
      }
  
      let currentIds = userCount[fieldIds] ? userCount[fieldIds].split(',') : [];
      if (!increase) {
        if (!currentIds.includes(projectId.toString())) {
          console.warn(`Job ID not found in ${fieldIds}, cannot reduce count.`);
          return false;
        }
      }
      if (increase) {
        if (!currentIds.includes(projectId.toString())) {
          currentIds.push(projectId.toString());
          amount = 1;
        } else {
          console.warn(`Job ID ${projectId} already exists in ${fieldIds}, count remains the same.`);
          amount = 0;
        }
      } else {
  
        currentIds = currentIds.filter(id => id !== projectId.toString());
      }
      const fieldUpdate = sequelize.literal(`GREATEST(${field} + (${amount}), 0)`);
      
      const result = await JobsTabCount.update(
        {
          [field]: fieldUpdate, //sequelize.literal(`${field} + ${amount}`),
          [fieldIds]: currentIds.length > 0 ? currentIds.join(',') : null
        },
        { where: { user_id: userId } }
      );
  
      if (result[0]) {
        return true;
      } else {
        console.warn(`No rows were updated for userId: ${userId}`);
        return false;
      }
    } catch (error) {
      console.error("Error updating count and IDs:", error.message);
      console.error(error);
    }
  };
  const getJobsTabCountByUser = async (userId) => {
    let res = await JobsTabCount.findOne({
      where: { user_id: userId, status: 1 }
    })
    return res;
  }

const getOptimizedProductionOverviewCounts = async (queryParams = {}, hasJobPermission = false) => {
  const {
    userType,
    userId,
    sort,
    fromDate,
    toDate,
    dueData,
  } = queryParams;

  const commonArgs = [
    hasJobPermission,
    true,
    userType,
    userId,
    null,
    sort || 'new',
    fromDate,
    toDate,
    dueData,
    'ALL',
  ];

  const projectCountByTab = (tab) =>
    getTotalProjectsCount(
      ...commonArgs,
      tab,
      '',
      [],
      [],
      [],
      [],
      [],
      [],
      2
    );

  const completedCountByTab = (tab) =>
    getTotalCompletedInstallationsCount(
      hasJobPermission,
      true,
      userType,
      userId,
      sort || 'new',
      false,
      fromDate,
      toDate,
      dueData,
      'ALL',
      tab,
      '',
      [],
      [],
      [],
      [],
      [],
      [],
      2
    );

  try {
    const jobsTabCount = await getJobsTabCountByUser(userId);

    const [changeOrder, tmReview, costCard] = await Promise.all([
      projectCountByTab('Change Order'),
      completedCountByTab('T & M Review'),
      completedCountByTab('Cost Card'),
    ]);

    if (jobsTabCount) {
      return {
        jobsHold: Number(jobsTabCount.hold_count) || 0,
        changeOrder: Number(changeOrder) || 0,
        preProductionJobs: Number(jobsTabCount.pre_production_count) || 0,
        productionJobs: Number(jobsTabCount.production_count) || 0,
        jobInstalls: Number(jobsTabCount.installs_count) || 0,
        jobPickup: Number(jobsTabCount.pickup_count) || 0,
        jobShipping: Number(jobsTabCount.shipping_count) || 0,
        tmReview: Number(tmReview) || 0,
        costCard: Number(costCard) || 0,
        completedJobs: Number(jobsTabCount.completed_count) || 0,
      };
    }

    // Fallback for users with no tab-count row yet.
    const [
      jobsHold,
      preProductionJobs,
      productionJobs,
      jobInstalls,
      jobPickup,
      jobShipping,
      completedJobs,
    ] = await Promise.all([
      projectCountByTab('Hold'),
      projectCountByTab('Pre-Production'),
      projectCountByTab('Production'),
      completedCountByTab('Installs'),
      completedCountByTab('Pickup'),
      completedCountByTab('Shipping'),
      completedCountByTab('Completed'),
    ]);

    return {
      jobsHold: Number(jobsHold) || 0,
      changeOrder: Number(changeOrder) || 0,
      preProductionJobs: Number(preProductionJobs) || 0,
      productionJobs: Number(productionJobs) || 0,
      jobInstalls: Number(jobInstalls) || 0,
      jobPickup: Number(jobPickup) || 0,
      jobShipping: Number(jobShipping) || 0,
      tmReview: Number(tmReview) || 0,
      costCard: Number(costCard) || 0,
      completedJobs: Number(completedJobs) || 0,
    };
  } catch (error) {
    console.error('Error in getOptimizedProductionOverviewCounts:', error);
    throw error;
  }
}


const  updateProjectById = async(projectId, updateData)=> {
    try {
      // Find the project
      const project = await Projects.findByPk(projectId);
  
      if (!project) {
        console.log('Project not found');
        return null;
      }
  
      // Update project with the provided data
      await project.update(updateData);
  
      console.log('Project updated successfully');
      return project;
    } catch (error) {
      console.error('Error updating project:', error);
      throw error;
    }
  }

const  updateEstimateProjectById = async(projectId, updateData)=> {
    try {
      // Find the project
      const project = await EstimateProjects.findByPk(projectId);
  
      if (!project) {
        console.log('Project not found');
        return null;
      }
  
      // Update project with the provided data
      await project.update(updateData);
  
      console.log('Project updated successfully');
      return project;
    } catch (error) {
      console.error('Error updating project:', error);
      throw error;
    }
  }
  

 const fetchProjectStatusById = async(projectId, options = {}) =>{
  const rows = await sequelize.query(
    `
      SELECT projects.*, cop.product_notes,cop.product_id, r.is_split_order,r.facility_type,r.for_parent_facility,r.origin_facility_request_id,r.origin_facility_id
        FROM projects
        Left join requests r on r.id = projects.request_id
        LEFT JOIN customer_order_products cop ON cop.order_id = projects.request_id
       WHERE projects.id = ${projectId}
       LIMIT 1;
    `,
    
  );

  if (rows.length === 0) {
    throw new Error(`Project with id ${projectId} not found`);
  }
  return rows[0];
}

const fetchAllUsersByTaskModel = async (projectId) => {
    try {
        const query = `
            SELECT 
                -- Project Table
                p.id AS project_id,
                p.name AS project_name,
                p.short_code AS project_short_code,
                p.city AS project_city,
                
                -- Project Task Table
                pt.id AS task_id,
                pt.name AS task_name,
                pt.customer_order_product_id,
                pt.service_id,
                
                -- Project Subtasks Table
                pst.id AS subtask_id,
                pst.name AS subtask_name,
                
                -- Project Subtask Members Table
                psm.id AS subtask_member_id,
                
                -- Staff Members Table
                sm.first_name AS staff_first_name,
                sm.last_name AS staff_last_name,
                sm.hourly_rate,
                concat(sm.first_name, ' ', sm.last_name) as staff_name,
                sm.id AS staff_id,
                sm.user_id AS staff_user_id,
                sm.email AS staff_email,
                
                -- Users Table (for profile pic)
                u.profile_pic AS user_profile_pic
                
            FROM projects p
            LEFT JOIN project_tasks pt ON pt.project_id = p.id
            LEFT JOIN project_subtasks pst ON pst.task_id = pt.id
            LEFT JOIN project_subtask_members psm ON psm.subtask_id = pst.id
            LEFT JOIN staff_members sm ON sm.id = psm.staff_id
            LEFT JOIN users u ON u.id = sm.user_id
            WHERE p.status != 0
            AND p.id = :projectId -- Filter by project_id
        `; // AND pst.status != 0

        const [results] = await sequelize.query(query, {
            replacements: { projectId }, 
        });

        if (results.length > 0) {
            return results;
        } else {
            return null; // Or handle as needed
        }
    } catch (error) {
        console.error("Error fetching users by task:", error);
        throw new Error("Server error while fetching users by task");
    }
};

// const fetchAllInstallerDriver = async (projectId) => {
//     try {
//         // Query to handle both team_id (installers/staff) and driver_id (drivers)
//         // Using UNION to combine results from both team_id and driver_id
//         // Also includes service_id from request_services where labour_cost_service_id = 10
//         const query = `
//             SELECT 
//                 -- Staff Members Table (from team_id)
//                 sm.first_name AS staff_first_name,
//                 sm.last_name AS staff_last_name,
//                 sm.hourly_rate,
//                 concat(sm.first_name, ' ', sm.last_name) as staff_name,
//                 sm.id AS staff_id,
//                 sm.user_id AS staff_user_id,
//                 sm.email AS staff_email,
//                 u.profile_pic AS user_profile_pic,
//                 rs.id AS service_id,
//                 TRUE AS is_driver,
//                 i.id AS installation_id,
//                 COALESCE(pr.name, lcs.name) AS installation_name
//             FROM installations i
//             LEFT JOIN staff_members sm ON FIND_IN_SET(sm.user_id, i.team_id) > 0
//             LEFT JOIN users u ON u.id = sm.user_id
//             LEFT JOIN projects p ON p.id = i.project_id
//             LEFT JOIN (
//             SELECT MIN(id) AS id, request_id
//             FROM request_services
//             WHERE labour_cost_service_id = 10
//             GROUP BY request_id
//             ) rs_ref ON rs_ref.request_id = p.request_id
//             LEFT JOIN request_services rs ON rs.id = rs_ref.id
//             LEFT JOIN products pr ON pr.id = i.product_id
//             LEFT JOIN labour_cost_services lcs ON lcs.id = i.labour_cost_service_id
//             WHERE i.project_id = :projectId
//             AND i.team_id IS NOT NULL 
//             AND i.team_id != ''
//             AND sm.user_id IS NOT NULL
//             GROUP BY sm.user_id, i.id
//             UNION
            
//             SELECT 
//                 -- Driver Table (from driver_id)
//                 u.first_name AS staff_first_name,
//                 u.last_name AS staff_last_name,
//                 d.hourly_rate,
//                 d.name as staff_name,
//                 d.id AS staff_id,
//                 d.user_id AS staff_user_id,
//                 d.email AS staff_email,
//                 u.profile_pic AS user_profile_pic,
//                 rs.id AS service_id,
//                 TRUE AS is_driver,
//                 i.id AS installation_id,
//                 COALESCE(pr.name, lcs.name) AS installation_name
//             FROM installations i
//             LEFT JOIN driver d ON FIND_IN_SET(d.id, i.driver_id) > 0
//             LEFT JOIN users u ON u.id = d.user_id
//             LEFT JOIN projects p ON p.id = i.project_id
//             LEFT JOIN (
//             SELECT MIN(id) AS id, request_id
//             FROM request_services
//             WHERE labour_cost_service_id = 10
//             GROUP BY request_id
//             ) rs_ref ON rs_ref.request_id = p.request_id
//             LEFT JOIN request_services rs ON rs.id = rs_ref.id
//             LEFT JOIN products pr ON pr.id = i.product_id
//             LEFT JOIN labour_cost_services lcs ON lcs.id = i.labour_cost_service_id
//             WHERE i.project_id = :projectId
//             AND i.driver_id IS NOT NULL 
//             AND i.driver_id != ''
//             AND d.user_id IS NOT NULL
//             GROUP BY d.user_id, i.id
//         `;

//         const [results] = await sequelize.query(query, {
//             replacements: { projectId },
//         });

//         if (results.length > 0) {
//             return results;
//         } else {
//             return null; // No data found
//         }
//     } catch (error) {
//         console.error("Error fetching installers/drivers:", error);
//         throw new Error("Server error while fetching installers/drivers");
//     }
// };

const fetchAllInstallerDriver = async (projectId) => {
    try {
        const query = `
            SELECT 
                sm.first_name AS staff_first_name,
                sm.last_name AS staff_last_name,
                sm.hourly_rate,
                CONCAT(sm.first_name, ' ', sm.last_name) AS staff_name,
                sm.id AS staff_id,
                sm.user_id AS staff_user_id,
                sm.email AS staff_email,
                u.profile_pic AS user_profile_pic,
                rs.id AS service_id,
                TRUE AS is_driver,
                i.id AS installation_id,
                COALESCE(pr.name, lcs.name) AS installation_name
            FROM installations i
            LEFT JOIN staff_members sm ON FIND_IN_SET(sm.user_id, i.team_id) > 0
            LEFT JOIN users u ON u.id = sm.user_id
            LEFT JOIN projects p ON p.id = i.project_id
            LEFT JOIN (
                SELECT MIN(id) AS id, request_id
                FROM request_services
                WHERE labour_cost_service_id = 10
                GROUP BY request_id
            ) rs_ref ON rs_ref.request_id = p.request_id
            LEFT JOIN request_services rs ON rs.id = rs_ref.id
            LEFT JOIN products pr ON pr.id = i.product_id
            LEFT JOIN labour_cost_services lcs ON lcs.id = i.labour_cost_service_id
            WHERE i.project_id = :projectId
            AND i.team_id IS NOT NULL 
            AND i.team_id != ''
            AND sm.user_id IS NOT NULL
            GROUP BY sm.user_id, i.id

            UNION

            SELECT 
                u.first_name AS staff_first_name,
                u.last_name AS staff_last_name,
                d.hourly_rate,
                d.name AS staff_name,
                d.id AS staff_id,
                d.user_id AS staff_user_id,
                d.email AS staff_email,
                u.profile_pic AS user_profile_pic,
                rs.id AS service_id,
                TRUE AS is_driver,
                i.id AS installation_id,
                COALESCE(pr.name, lcs.name) AS installation_name
            FROM installations i
            LEFT JOIN driver d ON FIND_IN_SET(d.id, i.driver_id) > 0
            LEFT JOIN users u ON u.id = d.user_id
            LEFT JOIN projects p ON p.id = i.project_id
            LEFT JOIN (
                SELECT MIN(id) AS id, request_id
                FROM request_services
                WHERE labour_cost_service_id = 10
                GROUP BY request_id
            ) rs_ref ON rs_ref.request_id = p.request_id
            LEFT JOIN request_services rs ON rs.id = rs_ref.id
            LEFT JOIN products pr ON pr.id = i.product_id
            LEFT JOIN labour_cost_services lcs ON lcs.id = i.labour_cost_service_id
            WHERE i.project_id = :projectId
            AND i.driver_id IS NOT NULL 
            AND i.driver_id != ''
            AND d.user_id IS NOT NULL
            GROUP BY d.user_id, i.id
        `;

        const [results] = await sequelize.query(query, {
            replacements: { projectId },
        });

        // If results exist, return unique data
        if (results.length > 0) {
            // Remove duplicate entries based on combination of staff_user_id and installation_id
            const uniqueResults = [];
            const seen = new Set();

            for (const result of results) {
                const uniqueKey = `${result.staff_user_id}-${result.installation_id}`;
                if (!seen.has(uniqueKey)) {
                    seen.add(uniqueKey);
                    uniqueResults.push(result);
                }
            }

            return uniqueResults;
        } else {
            return null; // No data found
        }
    } catch (error) {
        console.error("Error fetching installers/drivers:", error);
        throw new Error("Server error while fetching installers/drivers");
    }
};

const fetchAllUsersByTimeAndMaterialModel = async (projectId) => {
    try {
        const query = `
                SELECT *
                FROM (
                    -- Staff members (existing)
                    SELECT 
                        p.id AS project_id,
                        p.name AS project_name,
                        p.short_code AS project_short_code,
                        p.city AS project_city,

                        pm.id AS project_member_id,

                        sm.first_name AS staff_first_name,
                        sm.last_name AS staff_last_name,
                        sm.hourly_rate,
                        concat(sm.first_name, ' ', sm.last_name) as staff_name,
                        sm.id AS staff_id,
                        sm.user_id AS staff_user_id,
                        sm.email AS staff_email,

                        u.profile_pic AS user_profile_pic

                    FROM projects p
                    LEFT JOIN project_members pm ON pm.project_id = p.id
                    LEFT JOIN staff_members sm ON sm.id = pm.staff_id
                    LEFT JOIN users u ON u.id = sm.user_id
                    WHERE p.status != 0
                    AND p.id = :projectId
                    AND pm.staff_id IS NOT NULL

                    UNION ALL

                    -- Driver members (new)
                    SELECT 
                        p.id AS project_id,
                        p.name AS project_name,
                        p.short_code AS project_short_code,
                        p.city AS project_city,

                        NULL AS project_member_id,

                        NULL AS staff_first_name,
                        NULL AS staff_last_name,
                        d.hourly_rate,
                        d.name AS staff_name,
                        d.id AS staff_id,
                        d.user_id AS staff_user_id,
                        d.email AS staff_email,

                        NULL AS user_profile_pic

                    FROM projects p
                    LEFT JOIN installations i ON i.project_id = p.id
                    LEFT JOIN driver d ON FIND_IN_SET(d.id, i.driver_id)
                    WHERE p.status != 0
                    AND p.id = :projectId
                ) AS combined
                WHERE combined.staff_id IS NOT NULL;
                `;

    //     const query = `
    //     -- Staff members (existing)
    //     SELECT 
    //         p.id AS project_id,
    //         p.name AS project_name,
    //         p.short_code AS project_short_code,
    //         p.city AS project_city,
    
    //         pm.id AS project_member_id,
    
    //         sm.first_name AS staff_first_name,
    //         sm.last_name AS staff_last_name,
    //         sm.hourly_rate,
    //         concat(sm.first_name, ' ', sm.last_name) as staff_name,
    //         sm.id AS staff_id,
    //         sm.user_id AS staff_user_id,
    //         sm.email AS staff_email,
    
    //         u.profile_pic AS user_profile_pic
    
    //     FROM projects p
    //     LEFT JOIN project_members pm ON pm.project_id = p.id
    //     LEFT JOIN staff_members sm ON sm.id = pm.staff_id
    //     LEFT JOIN users u ON u.id = sm.user_id
    //     WHERE p.status != 0
    //       AND p.id = :projectId
    //       AND pm.staff_id IS NOT NULL
    
    //     UNION ALL
    
    //     -- Driver members (new)
    //     SELECT 
    //         p.id AS project_id,
    //         p.name AS project_name,
    //         p.short_code AS project_short_code,
    //         p.city AS project_city,
    
    //         NULL AS project_member_id,
    
    //         NULL AS staff_first_name,
    //         NULL AS staff_last_name,
    //         d.hourly_rate,
    //         d.name AS staff_name,
    //         d.id AS staff_id,
    //         d.user_id AS staff_user_id,
    //         d.email AS staff_email,
    
    //         NULL AS user_profile_pic
    
    //     FROM projects p
    //     LEFT JOIN installations i ON i.project_id = p.id
    //     LEFT JOIN driver d ON FIND_IN_SET(d.id, i.driver_id)
    //     WHERE p.status != 0
    //       AND p.id = :projectId
    // `;
    
        const [results] = await sequelize.query(query, {
            replacements: { projectId }, 
        });

        if (results.length > 0) {
            return results;
        } else {
            return [];
        }
    } catch (error) {
        console.error("Error fetching users by time and material:", error);
        throw new Error("Server error while fetching users by time and material");
    }
};

const projectIdFromRequestId = async (requestId) => {
    const project = await Projects.findOne({ where: { request_id: requestId } });
  
    if (!project) {
      return null; 
    }
  
    
    return project.id;
  
  
  };
const estimateProjectIdFromRequestId = async (requestId) => {
    const project = await EstimateProjects.findOne({ where: { request_id: requestId } });
  
    if (!project) {
      return null; 
    }
  
    
    return project.id;
  
  
  };

// Count methods for pagination
// const getTotalProjectsCount = async (hasPermission, all = false, userType, userId, where = [], sort, fromDate, toDate, dueData, filterProjectType, currentTab, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = [], splitOrder = false) => {
//     try {
//         const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
//         const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
//         const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
        
//         let dateCondition = '';
//         if (fromTimestamp && toTimestamp) {
//           dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
//         } else if (fromTimestamp) {
//           dateCondition = ` p.installation_date >= ${fromTimestamp}`;
//         } else if (toTimestamp) {
//           dateCondition = ` p.installation_date <= ${toTimestamp}`;
//         }

//         let whereCondition;
//         if (all) {
//             // For Production tab, allow status 2; for other tabs, exclude status 2
//             if (currentTab === 'Production') {
//                 whereCondition = ` (p.status != 0 AND p.status != 1 AND p.status != 3)`;
//             } else if (currentTab === 'ALL') {
//                 whereCondition = ` p.status != 0`;
//             }
//             else {
//                 whereCondition = ` p.status != 2`;
//             }
//         } else {
//             whereCondition = ` p.status = 1`;
//         }
//         if (splitOrder === 1) {
//             whereCondition += whereCondition ? ` AND req.is_split_order = 1 AND req.for_parent_facility != 2` : ` req.is_split_order = 1 AND req.for_parent_facility != 2`;
//         } else if (splitOrder === 2) {
//             whereCondition += whereCondition ? ` AND req.is_split_order = 0` : ` req.is_split_order = 0`;
//         }
//         let projectTypeCondition = '';
//         if (filterProjectType === 1) {
//           projectTypeCondition = ` AND req.project_type = 1`;
//         } else if (filterProjectType === 2) {
//           projectTypeCondition = ` AND req.project_type = 2`;
//         } else if (filterProjectType === 'NULL') {
//           projectTypeCondition = ` AND req.project_type IS NULL`;
//         } else if (filterProjectType === 'ALL') {
//           projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
//         } else {
//           projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
//         }

//         // Add job class filtering condition
//         let jobClassCondition = '';
//         if (jobClassFilter && jobClassFilter.length > 0) {
//             const jobClassIds = jobClassFilter.join(',');
//             jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
//         }

//         // Add job types filtering condition
//         let jobTypesCondition = '';
//         if (jobTypesFilter && jobTypesFilter.length > 0) {
//             const jobTypesIds = jobTypesFilter.join(',');
//             jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
//         }

//         // Add client filtering condition
//         let clientCondition = '';
//         if (clientFilter && clientFilter.length > 0) {
//             const clientIds = clientFilter.join(',');
//             clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
//         }

//         // Add user filtering condition
//         let userCondition = '';
//         if (userFilter && userFilter.length > 0) {
//             const userIds = userFilter.join(',');
//             userCondition = ` AND EXISTS (
//                 SELECT 1 FROM project_members pm 
//                 WHERE pm.project_id = p.id 
//                 AND pm.staff_id IN (${userIds})
//             )`;
//         }

//         // Add project filtering condition
//         let projectCondition = '';
//         if (projectFilter && projectFilter.length > 0) {
//             // Check if 'other' is included in the filter
//             const hasOther = projectFilter.includes('other');
//             const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
//             if (hasOther && numericIds.length > 0) {
//                 // Include both specific communities and null/other communities
//                 projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
//             } else if (hasOther) {
//                 // Only 'other' is selected
//                 projectCondition = ` AND p.community IS NULL`;
//             } else {
//                 // Only specific communities are selected
//                 projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
//             }
//         }

//         let departmentCondition = '';
//         if (departmentFilter && departmentFilter.length > 0) {
//             const departmentIds = departmentFilter.join(',');
          
//             // departmentCondition = `
//             //     AND EXISTS (
//             //       SELECT 1
//             //       FROM project_members pm
//             //       INNER JOIN staff_members sm ON pm.staff_id = sm.id
//             //       INNER JOIN users u ON sm.user_id = u.id
//             //       WHERE pm.project_id = p.id
//             //       AND u.department_id IN (${departmentIds})
//             //     )
//             //   `;
//             departmentCondition = `
//             AND EXISTS (
//                SELECT 1
//                FROM project_members pmm
//                INNER JOIN staff_members smm ON pmm.staff_id = smm.id
//                INNER JOIN users uu ON smm.user_id = uu.id
//                WHERE pmm.project_id = p.id
//                AND uu.department_id IN (${departmentIds})
//              )
//            `; 
//           }


//         // Add search condition
//         let searchCondition = '';
//         if (search && search.trim() !== '') {
//             searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR req.doc_number LIKE '%${search}%' OR req.est_doc_number LIKE '%${search}%')`;
//         }

//         // Add currentTab filtering condition
//         let tabCondition = '';
//         if (currentTab === 'Hold') {
//             tabCondition = ` p.hold = 1`;
//         } else if (currentTab === 'Pre-Production') {
//             tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0`;
//         } else if (currentTab === 'Production') {
//             tabCondition = ` p.hold = 0 AND p.status = 2`;
//         } else if (currentTab === 'Installs') {
//             tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND req.status != 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
//         } else if (currentTab === 'Pickup') {
//             tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
//         } else if (currentTab === 'Shipping') {
//             tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
//         } else if (currentTab === 'Completed') {
//             tabCondition = ` ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.isReview != 2 AND req.installation_acceptance = 1) OR (p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND req.isReview != 2 AND req.installation_acceptance = 1) OR req.status = 10`;
//         } else if (currentTab === 'T & M Review') {
//             tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.installation_acceptance != 1 AND p.status = 3 AND p.project_category = 12 AND req.isReview = 2`;
//         } else if (currentTab === 'Cost Card') {
//             tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.installation_acceptance != 1 AND p.status = 3 AND p.project_category != 12`;
//         } else if (currentTab === 'Change Order') {
//             tabCondition = ` p.hold = 0 AND p.change_order = 1`;
//         }

//         // Exclude change orders from other tabs (including ALL)
//         let changeOrderExclusion = '';
//         if (currentTab !== 'Change Order' && currentTab !== 'Hold') {
//             changeOrderExclusion = ` (p.change_order IS NULL OR p.change_order = 0)`;
//         }

//         let query = '';
//         if (userType === 1 || userType == 8) {
//             query = await sequelize.query(
//                 ` SELECT COUNT(DISTINCT p.id) as count FROM projects p `
//                 + ` LEFT JOIN users u ON p.added_by=u.id  `
//                 + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
//                 + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
//                 + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
//                 + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
//                 + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
//                 + ` INNER JOIN requests req on req.id = p.request_id `
//                 + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
//                 + ` LEFT JOIN products prod ON prod.id = cop.product_id `
//                 + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
//                 + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
//                 + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
//                 + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
//                 + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
//                 + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//                 + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
//                 + ` WHERE ${whereCondition} ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition}  ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} `
//             );
//         }
//         else if (userType === 3) {
//             query = await sequelize.query(
//                 ` SELECT COUNT(DISTINCT p.id) as count FROM projects p `
//                 + ` LEFT JOIN users u ON p.added_by=u.id  `
//                 + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
//                 + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
//                 + ` left join request_partners rp on rp.request_id=p.request_id`
//                 + ` left join partners pr on pr.id=rp.partner_id`
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
//                 + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
//                 + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
//                 + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
//                 + ` INNER JOIN requests req on req.id = p.request_id `
//                 + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
//                 + ` LEFT JOIN products prod ON prod.id = cop.product_id `
//                 + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
//                 + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
//                 + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
//                 + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
//                 + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
//                 + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//                 + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
//                 + ` WHERE pr.user_id=${userId} ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} `
//             );
//         }
//         else {
//             query = await sequelize.query(`SELECT COUNT(DISTINCT p.id) as count FROM projects p `
//                 + ` LEFT JOIN staff_members s1 ON s1.id=p.project_lead  `
//                 + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
//                 + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
//                 + ` LEFT JOIN users u1 ON s1.user_id=u1.id `
//                 + ` LEFT JOIN staff_members s2 ON s2.id=p.default_assignee `
//                 + ` LEFT JOIN users u2 ON s2.user_id=u2.id `
//                 + ` LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id from project_members pm left join partners p on p.id=pm.partner_id left join users u on p.user_id=u.id left join staff_members s on s.id=pm.staff_id left join users u2 on s.user_id=u2.id) pmm ON pmm.project_id=p.id and pmm.user_id=${userId} `
//                 + ` LEFT JOIN users u ON p.added_by=u.id `
//                 + ` LEFT JOIN installations i ON p.id = i.project_id `
//                 + ` LEFT JOIN driver dr ON i.driver_id = dr.id `
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  `
//                 + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  `
//                 + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id  `
//                 + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
//                 + ` INNER JOIN requests req on req.id = p.request_id `
//                 + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
//                 + ` LEFT JOIN products prod ON prod.id = cop.product_id `
//                 + ` left join users ura on ura.id = req.added_by `
//                 + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
//                 + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
//                 + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
//                 + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
//                 + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
//                 + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//                 + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) ins ON ins.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
//                 + ` WHERE (u1.id = ${userId} or u2.id = ${userId} or pmm.user_id =${userId} OR (req.added_by = ${userId} AND ura.user_type <> 3) OR FIND_IN_SET(${userId}, i.team_id) OR FIND_IN_SET(${userId}, dr.user_id) OR u_dopm.id = ${userId} OR u2_dopm.id = ${userId}) ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} `);
//         }
        
//         return query[0][0].count;
//     } catch (error) {
//         console.log("Error getting total projects count:", error);
//         throw new Error("Server error");
//     }
// };

const getTotalProjectsCount = async (hasPermission, all = false, userType, userId, where = [],sort,fromDate,toDate,dueData, filterProjectType, currentTab, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = [], splitOrder = false) => {
    try {
        let estimateCondition = ' AND p.is_estimate_job=0'

        const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
        const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
        const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
        let dateCondition = '';
        if (fromTimestamp && toTimestamp) {
          dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
        } else if (fromTimestamp) {
          dateCondition = ` p.installation_date >= ${fromTimestamp}`;
        } else if (toTimestamp) {
          dateCondition = ` p.installation_date <= ${toTimestamp}`;
        }


        let createdAt = ''
        if (dueTimestamp) {
            createdAt=`ORDER BY p.installation_date ASC`
        }else{
            if(sort==='new'){
                createdAt = `ORDER BY p.id DESC `
            }else if(sort==='old'){
                createdAt = `ORDER BY p.id ASC `
            }else if(sort === 'custom_order'){
                createdAt=`ORDER BY p.card_order ASC`
            }else{
                createdAt=`ORDER BY p.timestamp DESC`
            }
        }

        let whereCondition;
        let query = ''
        if (all) {
            // For Production tab, allow status 2; for other tabs, exclude status 2
            if (currentTab === 'Production') {
                whereCondition = ` (p.status != 0 AND p.status != 1 AND p.status != 3 AND p.status != 9)`;
            }else if(currentTab === "Pre-Production") {
                whereCondition = ` (p.status = 1 )`;
            } else if (currentTab === 'Rejected') {
                whereCondition = ` p.status = 9`;
            } else if(currentTab && currentTab === 'ALL') {
                whereCondition = ` p.status != 0`;
            }else{
                whereCondition = ` p.status != 999`;
            }
        } else {
            whereCondition = ` p.status = 1`;
        }
        if (!empty(where)) {

        }
        if (splitOrder === 1) {
            whereCondition += whereCondition ? ` AND req.is_split_order = 1 AND req.for_parent_facility != 2` : ` req.is_split_order = 1 AND req.for_parent_facility != 2`;
        } else if (splitOrder === 2) {
            whereCondition += whereCondition ? ` AND req.is_split_order = 0` : ` req.is_split_order = 0`;
        }

        let projectTypeCondition = '';
        if (filterProjectType === 1) {
        projectTypeCondition = ` AND req.project_type = 1`;
        } else if (filterProjectType === 2) {
        projectTypeCondition = ` AND req.project_type = 2`;
        } else if (filterProjectType === 'NULL') {
        projectTypeCondition = ` AND req.project_type IS NULL`;
        } else if (filterProjectType === 'ALL') {
        projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
        } else {
        projectTypeCondition = ` AND (req.project_type IS NULL OR req.project_type IS NOT NULL)`;
        }

        // Add job class filtering condition
        let jobClassCondition = '';
        if (jobClassFilter && jobClassFilter.length > 0) {
            const jobClassIds = jobClassFilter.join(',');
            jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
        }

        // Add job types filtering condition
        let jobTypesCondition = '';
        if (jobTypesFilter && jobTypesFilter.length > 0) {
            const jobTypesIds = jobTypesFilter.join(',');
            jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
        }

        // Add client filtering condition
        let clientCondition = '';
        if (clientFilter && clientFilter.length > 0) {
            const clientIds = clientFilter.join(',');
            clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
        }

        // Add user filtering condition
        let userCondition = '';
        if (userFilter && userFilter.length > 0) {
            const userIds = userFilter.join(',');
            userCondition = ` AND EXISTS (
                SELECT 1 FROM project_members pm 
                WHERE pm.project_id = p.id 
                AND pm.staff_id IN (${userIds})
            )`;
        }

        // Add project filtering condition
        let projectCondition = '';
        if (projectFilter && projectFilter.length > 0) {
            // Check if 'other' is included in the filter
            const hasOther = projectFilter.includes('other');
            const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
            if (hasOther && numericIds.length > 0) {
                // Include both specific communities and null/other communities
                projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
            } else if (hasOther) {
                // Only 'other' is selected
                projectCondition = ` AND p.community IS NULL`;
            } else {
                // Only specific communities are selected
                projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
            }
        }

        let departmentCondition = '';
        if (departmentFilter && departmentFilter.length > 0) {
            const departmentIds = departmentFilter.join(',');
          
            departmentCondition = `
                AND EXISTS (
                    SELECT 1
                    FROM project_members pm_dep
                    INNER JOIN staff_members sm_dep 
                    ON pm_dep.staff_id = sm_dep.id
                    INNER JOIN services srv 
                    ON FIND_IN_SET(srv.id, sm_dep.services)
                    WHERE pm_dep.project_id = p.id
                    AND srv.department_id IN (${departmentIds})
                )
            `;
          }

        // Add search condition
        let searchCondition = '';
        if (search && search.trim() !== '') {
            searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR req.doc_number LIKE '%${search}%' OR req.est_doc_number LIKE '%${search}%')`;
        }

        // Add currentTab filtering condition
        let tabCondition = '';
        if (currentTab === 'Hold') {
            tabCondition = ` p.hold = 1`;
        } else if (currentTab === 'Pre-Production') {
            tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0`;
        } else if (currentTab === 'Production') {
            tabCondition = ` p.hold = 0 AND p.status = 2`;

        } else if (currentTab === 'Rejected') {
            tabCondition = ` p.status = 9`;
        } else if (currentTab === 'Installs') {
            tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND req.status != 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
        } else if (currentTab === 'Pickup') {
            tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
        } else if (currentTab === 'Shipping') {
            tabCondition = ` i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)`;
        } else if (currentTab === 'Completed') {
            tabCondition = ` ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.isReview != 2 AND req.installation_acceptance = 1) OR (p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND req.isReview != 2 AND req.installation_acceptance = 1) OR req.status = 10`;
        } else if (currentTab === 'T & M Review') {
            tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.installation_acceptance != 1 AND p.status = 3 AND p.project_category = 12 AND req.isReview = 2`;
        } else if (currentTab === 'Cost Card') {
            tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND req.installation_acceptance != 1 AND p.status = 3 AND p.project_category != 12`;
        } else if (currentTab === 'Change Order') {
            tabCondition = ` p.hold = 0 AND p.change_order = 1`;
        }
        
        // Exclude change orders from all other tabs (including ALL)
        let changeOrderExclusion = '';
        if (currentTab !== 'Change Order' && currentTab !== 'Hold' && currentTab !== 'ALL') {
            changeOrderExclusion = ` (p.change_order IS NULL OR p.change_order = 0)`;
        }

        if (userType === 1 || userType == 8) {
            query = await sequelize.query(
                ` SELECT  COUNT(DISTINCT p.id) as count  FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE ${whereCondition} ${dateCondition!= '' ? ' AND '+dateCondition : ''}  ${departmentCondition != '' ? departmentCondition : ''} ${projectTypeCondition} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} ${createdAt}`
            );
        } else if (userType === 3) {
            query = await sequelize.query(
                ` SELECT  COUNT(DISTINCT p.id) as count FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` left join request_partners rp on rp.request_id=p.request_id`
                + ` left join partners pr on pr.id=rp.partner_id`
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) i ON i.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE pr.user_id=${userId} ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} ${createdAt} `
            );
        } else {
            query = await sequelize.query(`SELECT  COUNT(DISTINCT p.id) as count FROM projects p `
                + ` LEFT JOIN staff_members s1 ON s1.id=p.project_lead  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN users u1 ON s1.user_id=u1.id `
                + ` LEFT JOIN staff_members s2 ON s2.id=p.default_assignee `
                + ` LEFT JOIN users u2 ON s2.user_id=u2.id `
                + ` LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id from project_members pm left join partners p on p.id=pm.partner_id left join users u on p.user_id=u.id left join staff_members s on s.id=pm.staff_id left join users u2 on s.user_id=u2.id) pmm ON pmm.project_id=p.id and pmm.user_id=${userId} `
                + ` LEFT JOIN users u ON p.added_by=u.id `
                + ` LEFT JOIN installations i ON p.id = i.project_id `
                + ` LEFT JOIN driver dr ON i.driver_id = dr.id `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id  `
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` INNER JOIN requests req on req.id = p.request_id `
                + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
                + ` LEFT JOIN products prod ON prod.id = cop.product_id `
                + ` left join users ura on ura.id = req.id `
                + ` LEFT JOIN design_order_project_members dopm ON req.design_order_id = dopm.design_order_id `
                + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
                + ` LEFT JOIN partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
                + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
                + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) ins ON ins.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = req.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = req.id`
                + ` WHERE (
                    u1.id = ${userId}
                    OR u2.id = ${userId}
                    OR pmm.user_id = ${userId}
                    OR (req.added_by = ${userId} AND ura.user_type <> 3)
                    OR FIND_IN_SET(${userId}, i.team_id)
                    OR FIND_IN_SET(${userId}, dr.user_id)
                    OR u_dopm.id = ${userId}
                    OR u2_dopm.id = ${userId}
                )
                ${dateCondition ? ' AND ' + dateCondition : ''}
                ${projectTypeCondition}
                ${departmentCondition ? ' ' + departmentCondition : ''}
                ${jobClassCondition}
                ${jobTypesCondition}
                ${clientCondition}
                ${userCondition}
                ${estimateCondition}
                ${projectCondition}
                ${tabCondition ? ' AND ' + tabCondition : ''}
                ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''}
                ${searchCondition ? ' AND ' + searchCondition : ''}
                ${createdAt} `
             );
        }
        if (query.length > 0) {
            return query?.[0]?.[0]?.count || 0;
        } else {
            return 0;
        }
    } catch (error) {
        console.log(error);
        throw new Error("Server error");
    }
}


// const getTotalCompletedInstallationsCount = async (hasPermission, all = false, userType, userId, sort, where = [], fromDate, toDate, dueData, filterProjectType, currentTab, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = [], splitOrder = false) => {
//     try {
//         const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
//         const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
//         const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
        
//         let dateCondition = '';
//         if (fromTimestamp && toTimestamp) {
//           dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
//         } else if (fromTimestamp) {
//           dateCondition = ` p.installation_date >= ${fromTimestamp}`;
//         } else if (toTimestamp) {
//           dateCondition = ` p.installation_date <= ${toTimestamp}`;
//         }

//         let whereCondition;
//         if (all) {
//             // For Production tab, allow status 2; for other tabs, exclude status 2
//             if (currentTab === 'Production') {
//                 whereCondition = ` (p.status != 0 AND p.status != 1 AND p.status != 3)`;
//             } else if (currentTab === 'ALL') {
//                 whereCondition = ` p.status != 0`;
//             }
//             else {
//                 whereCondition = ` p.status != 2`;
//             }
//         } else {
//             whereCondition = ` p.status = 1`;
//         }
//         if (splitOrder === 1) {
//             whereCondition += whereCondition ? ` AND req.is_split_order = 1 AND req.for_parent_facility != 2` : ` req.is_split_order = 1 AND req.for_parent_facility != 2`;
//         } else if (splitOrder === 2) {
//             whereCondition += whereCondition ? ` AND req.is_split_order = 0` : ` req.is_split_order = 0`;
//         }

//         let projectTypeCondition = '';
//         if (filterProjectType === 1) {
//           projectTypeCondition = ` p.project_type = 1`;
//         } else if (filterProjectType === 2) {
//           projectTypeCondition = ` p.project_type = 2`;
//         } else if (filterProjectType === 'NULL') {
//           projectTypeCondition = ` p.project_type IS NULL`;
//         } else {
//           projectTypeCondition = ` (p.project_type IS NULL OR p.project_type IS NOT NULL)`;
//         }

//         // Add job class filtering condition
//         let jobClassCondition = '';
//         if (jobClassFilter && jobClassFilter.length > 0) {
//             const jobClassIds = jobClassFilter.join(',');
//             jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
//         }

//         // Add job types filtering condition
//         let jobTypesCondition = '';
//         if (jobTypesFilter && jobTypesFilter.length > 0) {
//             const jobTypesIds = jobTypesFilter.join(',');
//             jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
//         }

//         // Add client filtering condition
//         let clientCondition = '';
//         if (clientFilter && clientFilter.length > 0) {
//             const clientIds = clientFilter.join(',');
//             clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
//         }

//         // Add user filtering condition
//         let userCondition = '';
//         if (userFilter && userFilter.length > 0) {
//             const userIds = userFilter.join(',');
//             userCondition = ` AND EXISTS (
//                 SELECT 1 FROM project_members pm 
//                 WHERE pm.project_id = p.id 
//                 AND pm.staff_id IN (${userIds})
//             )`;
//         }

//         // Add project filtering condition
//         let projectCondition = '';
//         if (projectFilter && projectFilter.length > 0) {
//             // Check if 'other' is included in the filter
//             const hasOther = projectFilter.includes('other');
//             const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
//             if (hasOther && numericIds.length > 0) {
//                 // Include both specific communities and null/other communities
//                 projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
//             } else if (hasOther) {
//                 // Only 'other' is selected
//                 projectCondition = ` AND p.community IS NULL`;
//             } else {
//                 // Only specific communities are selected
//                 projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
//             }
//         }

//         let departmentCondition = '';
//         if (departmentFilter && departmentFilter.length > 0) {
//             const departmentIds = departmentFilter.join(',');
          
//             // departmentCondition = `
//             //     AND EXISTS (
//             //       SELECT 1
//             //       FROM project_members pm_dep
//             //       INNER JOIN staff_members sm_dep ON pm_dep.staff_id = sm_dep.id
//             //       INNER JOIN users u_dep ON sm_dep.user_id = u_dep.id
//             //       WHERE pm_dep.project_id = p.id
//             //       AND u_dep.department_id IN (${departmentIds})
//             //     )
//             //   `;
//             departmentCondition = `
//             AND EXISTS (
//               SELECT 1
//               FROM project_members pm_dep
//               INNER JOIN staff_members sm_dep ON pm_dep.staff_id = sm_dep.id
//               INNER JOIN users u_dep ON sm_dep.user_id = u_dep.id
//               WHERE pm_dep.project_id = p.id
//               AND u_dep.department_id IN (${departmentIds})
//             )
//           `;
//           }

//         // Add search condition
//         let searchCondition = '';
//         if (search && search.trim() !== '') {
//             searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR r.doc_number LIKE '%${search}%' OR r.est_doc_number LIKE '%${search}%')`;
//         }

//         // Add currentTab filtering condition for remaining tabs
//         let tabCondition = '';
//         let splitMirrorCondition = '';
//         let changeOrderBaseCondition = '';
//         let changeOrderExclusion = '';
//         if (currentTab === 'Hold') {
//             tabCondition = ` p.hold = 1`;
//         } else if (currentTab === 'Pre-Production') {
//             tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0 `;
//         } else if (currentTab === 'Production') {
//             tabCondition = ` p.hold = 0 AND p.status = 2 `;
//         } else if (currentTab === 'Change Order') {
//             tabCondition = ` p.hold = 0 AND p.change_order = 1`;
//         } else if (currentTab === 'Installs') {
//             tabCondition = ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND r.status != 3 AND p.status = 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1))`;
//             splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1)`;
//         } else if (currentTab === 'Pickup') {
//             tabCondition = ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2))`;
//             splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2)`;
//         } else if (currentTab === 'Shipping') {
//             tabCondition = ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3))`;
//             splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3)`;
//         } else if (currentTab === 'Completed') {
//             // Original frontend condition: (item.allInstallationCompleted === 1 && item.isReview !==2 && item?.installation_acceptance ==1) || (item.project_status == 3 && !item.total_installation_count && item.isReview !==2 && item?.installation_acceptance ==1)|| item.request_status ==10
//             tabCondition = ` ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND r.isReview != 2 AND r.installation_acceptance = 1) OR (p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND r.isReview != 2 AND r.installation_acceptance = 1) OR r.status = 10 OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)`;
//          splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)`;
//         } else if (currentTab === 'T & M Review') {
//             // Original frontend condition: (item.allInstallationCompleted === 1 && item?.installation_acceptance !==1 && item.project_status == 3 && item.project_category == 12 && item.isReview ==2)
//             tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)  AND p.status = 3 AND p.project_category = 12 AND r.isReview = 2`;
//         } else if (currentTab === 'Cost Card') {
//             // Original frontend condition: (item.allInstallationCompleted === 1 && item?.installation_acceptance !==1 && item.project_status == 3 && item.project_category !== 12 )
//             tabCondition = ` ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) OR (total_inst_counts.total_installation_count IS NULL))  AND p.status = 3 AND p.project_category != 12 AND r.installation_acceptance IS NULL OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4)`;
//             splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4)`;
//             console.log('tabCondition+++++++', tabCondition)
//         }

//         if (currentTab === 'Change Order') {
//             changeOrderBaseCondition = ` OR (p.change_order = 1)`;
//         }
//         if (currentTab !== 'Change Order' && currentTab !== 'Hold') {
//             changeOrderExclusion = ` (p.change_order IS NULL OR p.change_order = 0)`;
//         }

//         let query = '';
//         if (userType === 1 || userType == 8) {
//             query = await sequelize.query(
//                 ` SELECT COUNT(DISTINCT p.id) as count FROM projects p `
//                 + ` LEFT JOIN users u ON p.added_by=u.id  `
//                 + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
//                 + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
//                 + ` INNER JOIN requests r ON p.request_id = r.id `
//                 + ` LEFT JOIN (
//                         SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, 
//                          SUM(
//                                 CASE
//                                 WHEN cop.is_single_card = 1 THEN 1
//                                 ELSE cop.location_quantity
//                                 END
//                             ) AS product_count
//                         FROM customer_orders co
//                         JOIN customer_order_products cop ON co.id = cop.order_id
//                         JOIN requests req ON co.request_id = req.id
//                         WHERE cop.material = 0
//                         GROUP BY co.request_id
//                     ) cop ON r.id = cop.request_id `

//                 + ` LEFT JOIN (
//                         SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
//                         FROM customer_orders co
//                         JOIN  requests rqs ON co.request_id = rqs.id
//                         JOIN  request_services rss ON co.request_id = rss.request_id
//                         JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
//                         WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
//                         GROUP BY co.request_id
//                     ) rss ON r.id = rss.request_id `

//                 + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id`
//                 + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id`
//                 + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
//                 + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//                 + ` where (((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
//                         r.noServiceNoTask = 0 AND r.status=4) OR (i.status IS NOT NULL)${changeOrderBaseCondition}) ${splitMirrorCondition}) ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition!= '' ? ' AND '+dateCondition : ''} AND ${projectTypeCondition} ${jobClassCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND ('+tabCondition+')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} `
//             );
//         }
//         else if (userType === 3) {
//             query = await sequelize.query(
//                 ` SELECT COUNT(DISTINCT p.id) as count FROM projects p `
//                 + ` LEFT JOIN users u ON p.added_by=u.id  `
//                 + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
//                 + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
//                 + ` left join request_partners rp on rp.request_id=p.request_id`
//                 + ` left join partners pr on pr.id=rp.partner_id`
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
//                 + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
//                 + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id `
//                 + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
//                 + ` INNER JOIN requests r on r.id = p.request_id `
//                 + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
//                 + ` LEFT JOIN products prod ON prod.id = cop.product_id `
//                 + ` LEFT JOIN design_order_project_members dopm ON r.design_order_id = dopm.design_order_id `
//                 + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
//                 + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
//                 + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
//                 + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
//                 + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//                 + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = rr.id`
//                 + ` WHERE pr.user_id=${userId} ${dateCondition!= '' ? ' AND '+dateCondition : ''} ${projectTypeCondition} ${departmentCondition != '' ? departmentCondition : ''} ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${projectCondition} ${tabCondition!= '' ? ' AND '+tabCondition : ''} ${changeOrderExclusion!= '' ? ' AND '+changeOrderExclusion : ''} ${searchCondition!= '' ? ' AND '+searchCondition : ''} `
//             );
//         }
//         else {
//             query = await sequelize.query(`SELECT COUNT(DISTINCT p.id) as count FROM projects p `
//                 + ` LEFT JOIN staff_members s1 ON s1.id=p.project_lead  `
//                 + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
//                 + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
//                 + ` LEFT JOIN users u1 ON s1.user_id=u1.id `
//                 + ` LEFT JOIN staff_members s2 ON s2.id=p.default_assignee `
//                 + ` LEFT JOIN users u2 ON s2.user_id=u2.id `
//                 + ` LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id from project_members pm left join partners p on p.id=pm.partner_id left join users u on p.user_id=u.id left join staff_members s on s.id=pm.staff_id left join users u2 on s.user_id=u2.id) pmm ON pmm.project_id=p.id and pmm.user_id=${userId} `
//                 + ` LEFT JOIN users u ON p.added_by=u.id `
//                 + ` LEFT JOIN installations i ON p.id = i.project_id `
//                 + ` LEFT JOIN driver dr ON i.driver_id = dr.id `
//                 + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  `
//                 + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  `
//                 + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id  `
//                 + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
//                 + ` INNER JOIN requests r on r.id = p.request_id `
//                 + ` LEFT JOIN customer_order_products cop ON cop.order_id = c_ord.id `
//                 + ` LEFT JOIN products prod ON prod.id = cop.product_id `
//                 + ` left join users ura on ura.id = r.added_by `
//                 + ` LEFT JOIN design_order_project_members dopm ON r.design_order_id = dopm.design_order_id `
//                 + ` LEFT JOIN partners p_dopm ON p_dopm.id = dopm.partner_id `
//                 + ` LEFT JOIN users u_dopm ON p_dopm.user_id = u_dopm.id `
//                 + ` LEFT JOIN staff_members s_dopm ON s_dopm.id = dopm.staff_id `
//                 + ` LEFT JOIN users u2_dopm ON s_dopm.user_id = u2_dopm.id `
//                 + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//                 + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status FROM installations GROUP BY request_id) ins ON ins.request_id = r.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id `
//                 + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id`
//                 + ` WHERE (u1.id = ${userId} or u2.id = ${userId} or pmm.user_id =${userId} 
//                 OR (r.added_by = ${userId} AND ura.user_type <> 3) 
//                 OR FIND_IN_SET(${userId}, i.team_id) 
//                 OR FIND_IN_SET(${userId}, dr.user_id) 
//                 OR u_dopm.id = ${userId} 
//                 OR u2_dopm.id = ${userId})`
//              + `${dateCondition ? ' AND ' + dateCondition : ''}`
//              + `${projectTypeCondition ? ' AND ' + projectTypeCondition : ''}`
//              + `${departmentCondition ? ' AND ' + departmentCondition : ''}`
//              + `${jobClassCondition ? ' AND ' + jobClassCondition : ''}`
//              + `${jobTypesCondition ? ' AND ' + jobTypesCondition : ''}`
//              + `${clientCondition ? ' AND ' + clientCondition : ''}`
//              + `${userCondition ? ' AND ' + userCondition : ''}`
//              + `${projectCondition ? ' AND ' + projectCondition : ''}`
//              + `${tabCondition ? ' AND ' + tabCondition : ''}`
//              + `${changeOrderExclusion ? ' AND ' + changeOrderExclusion : ''}`
//              + `${searchCondition ? ' AND ' + searchCondition : ''}`
//             );
//         }
        
//         return query?.[0]?.[0]?.count;
//     } catch (error) {
//         console.log("Error getting total completed installations count:", error);
//         throw new Error("Server error");
//     }
// };

const getTotalCompletedInstallationsCount = async (hasPermission, all = false, userType, userId, sort, where = [], fromDate, toDate,dueData,filterProjectType, currentTab, search = '', jobClassFilter = [], jobTypesFilter = [], clientFilter = [], userFilter = [], projectFilter = [], departmentFilter = [], splitOrder = false, forAllTab = false) => {
    try {
        let estimateCondition = ' AND p.is_estimate_job=0';
        let whereCondition;
        const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
        const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
        const dueTimestamp = dueData ? moment().endOf('day').unix() : null;
        let dateCondition = '';
        if (fromTimestamp && toTimestamp) {
          dateCondition = ` p.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
        } else if (fromTimestamp) {
          dateCondition = ` p.installation_date >= ${fromTimestamp}`;
        } else if (toTimestamp) {
          dateCondition = ` p.installation_date <= ${toTimestamp}`;
        }
        // else if (dueTimestamp) {
        //     dateCondition = ` p.installation_date <= ${dueTimestamp}`;
        // }
        let query = ''
        if (all) {
            whereCondition = ` p.status != 2`;
        } else {
            whereCondition = ` p.status = 1`;
        }
        if (!empty(where)) {

        }
        // if (splitOrder === 1) {
        //     whereCondition += whereCondition ? ` AND r.is_split_order = 1` : ` r.is_split_order = 1`;
        // } else if (splitOrder === 2) {
        //     whereCondition += whereCondition ? ` AND r.is_split_order = 0` : ` r.is_split_order = 0`;
        // }

        let createdAt = ''
        if (dueTimestamp) {
            createdAt=`ORDER BY p.installation_date ASC`
        }else{
            if(sort==='new'){
                createdAt = `ORDER BY p.id DESC `
            }else if(sort==='old'){
                createdAt = `ORDER BY p.id ASC `
            }else if(sort === 'custom_order'){
                createdAt=`ORDER BY p.card_order ASC`
            }else{
                createdAt=`ORDER BY p.timestamp DESC`
            }
        }

        let projectTypeCondition = '';
if (filterProjectType === 1) {
  projectTypeCondition = ` p.project_type = 1`;
} else if (filterProjectType === 2) {
  projectTypeCondition = ` p.project_type = 2`;
} else if (filterProjectType === 'NULL') {
  projectTypeCondition = ` p.project_type IS NULL`;
} else {
  projectTypeCondition = ` (p.project_type IS NULL OR p.project_type IS NOT NULL)`;
}

        // Add job class filtering condition
        let jobClassCondition = '';
        if (jobClassFilter && jobClassFilter.length > 0) {
            const jobClassIds = jobClassFilter.join(',');
            jobClassCondition = ` AND p.project_type IN (${jobClassIds})`;
        }

        // Add job types filtering condition
        let jobTypesCondition = '';
        if (jobTypesFilter && jobTypesFilter.length > 0) {
            const jobTypesIds = jobTypesFilter.join(',');
            jobTypesCondition = ` AND p.project_category IN (${jobTypesIds})`;
        }

        // Add client filtering condition
        let clientCondition = '';
        if (clientFilter && clientFilter.length > 0) {
            const clientIds = clientFilter.join(',');
            clientCondition = ` AND c_ord.customer_id IN (${clientIds})`;
        }

        // Add user filtering condition
        let userCondition = '';
        if (userFilter && userFilter.length > 0) {
            const userIds = userFilter.join(',');
            userCondition = ` AND EXISTS (
                SELECT 1 FROM project_members pm 
                WHERE pm.project_id = p.id 
                AND pm.staff_id IN (${userIds})
            )`;
        }

        // Add project filtering condition
        let projectCondition = '';
        if (projectFilter && projectFilter.length > 0) {
            // Check if 'other' is included in the filter
            const hasOther = projectFilter.includes('other');
            const numericIds = projectFilter.filter(id => id !== 'other').map(id => parseInt(id));
            
            if (hasOther && numericIds.length > 0) {
                // Include both specific communities and null/other communities
                projectCondition = ` AND (p.community IN (${numericIds.join(',')}) OR p.community IS NULL)`;
            } else if (hasOther) {
                // Only 'other' is selected
                projectCondition = ` AND p.community IS NULL`;
            } else {
                // Only specific communities are selected
                projectCondition = ` AND p.community IN (${numericIds.join(',')})`;
            }
        }

        let departmentCondition = '';
        if (departmentFilter && departmentFilter.length > 0) {
            const departmentIds = departmentFilter.join(',');
          
            // departmentCondition = `
            //     AND EXISTS (
            //       SELECT 1
            //       FROM project_members pm
            //       INNER JOIN staff_members sm ON pm.staff_id = sm.id
            //       INNER JOIN users u ON sm.user_id = u.id
            //       WHERE pm.project_id = p.id
            //       AND u.department_id IN (${departmentIds})
            //     )
            //   `;
            departmentCondition = `
            AND EXISTS (
              SELECT 1
              FROM project_members pm_dep
              INNER JOIN staff_members sm_dep ON pm_dep.staff_id = sm_dep.id
              INNER JOIN users u_dep ON sm_dep.user_id = u_dep.id
              WHERE pm_dep.project_id = p.id
              AND u_dep.department_id IN (${departmentIds})
            )
          `;
          }
        // Add search condition
        let searchCondition = '';
        if (search && search.trim() !== '') {
            searchCondition = ` (p.name LIKE '%${search}%' OR p.project_uid LIKE '%${search}%' OR c_ord.customer_name LIKE '%${search}%' OR r.doc_number LIKE '%${search}%' OR r.est_doc_number LIKE '%${search}%')`;
        }

        // Add currentTab filtering condition for remaining tabs
        let tabCondition = '';
        let splitMirrorCondition = '';
        // Keep Change Order behavior consistent with getAllProjects:
        // - Show only change orders on "Change Order" tab
        // - Hide change orders from all other tabs (except Hold)
        let changeOrderBaseCondition = '';
        let changeOrderExclusion = '';
        if (currentTab === 'Hold') {
            tabCondition = ` p.hold = 1`;
        } else if (currentTab === 'Pre-Production') {
            tabCondition = ` (p.status = 1 OR p.status = 0) AND p.hold = 0`;
        } else if (currentTab === 'Production') {
            tabCondition = ` p.hold = 0 AND p.status = 2 `;
        } else if (currentTab === 'Change Order') {
            tabCondition = ` p.hold = 0 AND p.change_order = 1`;
        } else if (currentTab === 'Installs') {
            // Include installation_pending_review. For ALL tab (forAllTab), skip EXISTS to avoid duplicates.
            tabCondition = forAllTab
                ? ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND r.status != 3 AND p.status = 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1) OR ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND COALESCE(i.pending_review, 0) = 1)) OR (COALESCE(i.pending_review, 0) = 2) `
                : ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND r.status != 3 AND p.status = 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (EXISTS (SELECT 1 FROM installations inst_tab WHERE inst_tab.request_id = r.id AND inst_tab.status IS NOT NULL AND inst_tab.status != 5 AND inst_tab.complete_status = 1 AND inst_tab.status != 0) AND r.status != 3 AND p.status = 3 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1) OR ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND COALESCE(i.pending_review, 0) = 1)) OR (COALESCE(i.pending_review, 0) = 2) `;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1)`;
        } else if (currentTab === 'Pickup') {
            tabCondition = forAllTab
                ? ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2))`
                : ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 2 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (EXISTS (SELECT 1 FROM installations inst_tab WHERE inst_tab.request_id = r.id AND inst_tab.status IS NOT NULL AND inst_tab.status != 5 AND inst_tab.complete_status = 2) AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2))`;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2)`;
        } else if (currentTab === 'Shipping') {
            tabCondition = forAllTab
                ? ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3))`
                : ` ((i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 3 AND i.status != 5 AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (EXISTS (SELECT 1 FROM installations inst_tab WHERE inst_tab.request_id = r.id AND inst_tab.status IS NOT NULL AND inst_tab.status != 5 AND inst_tab.complete_status = 3) AND (COALESCE(inst_counts.installation_count, 0) < COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3))`;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3)`;
        } else if (currentTab === 'Completed') {
            // Exclude installation_pending_review (show those in Installs tab instead)
            tabCondition = ` (((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) AND r.isReview != 2 AND r.installation_acceptance = 1) OR (p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND r.isReview != 2 AND r.installation_acceptance = 1) OR r.status = 10 OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)) AND (COALESCE(i.pending_review, 0) != 1) AND (COALESCE(i.pending_review, 0) != 2)`;
         splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)`;
        } else if (currentTab === 'T & M Review') {
            // Original frontend condition: (item.allInstallationCompleted === 1 && item?.installation_acceptance !==1 && item.project_status == 3 && item.project_category == 12 && item.isReview ==2)
            tabCondition = ` (COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0)  AND p.status = 3 AND p.project_category = 12 AND r.isReview = 2`;
        } else if (currentTab === 'Cost Card') {
            // Original frontend condition: (item.allInstallationCompleted === 1 && item?.installation_acceptance !==1 && item.project_status == 3 && item.project_category !== 12 )
            tabCondition = ` ((COALESCE(inst_counts.installation_count, 0) >= COALESCE(total_inst_counts.total_installation_count, 0)) AND (COALESCE(total_inst_counts.total_installation_count, 0) > 0) OR (total_inst_counts.total_installation_count IS NULL))  AND p.status = 3 AND p.project_category != 12 AND r.installation_acceptance IS NULL AND (COALESCE(i.pending_review, 0) NOT IN (1, 2)) OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4) `;
            splitMirrorCondition = ` OR (r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4)`;
            console.log('tabCondition+++++++', tabCondition)
        }

        if (currentTab === 'Change Order') {
            changeOrderBaseCondition = ` OR (p.change_order = 1)`;
        }
        if (currentTab !== 'Change Order' && currentTab !== 'Hold' && currentTab !== 'ALL') {
            changeOrderExclusion = ` (p.change_order IS NULL OR p.change_order = 0)`;
        }
console.log('testtttttttttt');

        if (userType === 1 || userType == 8) {
            query = await sequelize.query(
                ` SELECT  COUNT(DISTINCT p.id) as count  FROM projects p ` 
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id `
                + ` INNER JOIN requests r ON p.request_id = r.id `
                + ` LEFT JOIN (
                        SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, 
                         SUM(
                                CASE
                                WHEN cop.is_single_card = 1 THEN 1
                                ELSE cop.location_quantity
                                END
                            ) AS product_count
                        FROM customer_orders co
                        JOIN customer_order_products cop ON co.id = cop.order_id
                        JOIN requests req ON co.request_id = req.id
                        WHERE cop.material = 0
                        GROUP BY co.request_id
                    ) cop ON r.id = cop.request_id `

                + ` LEFT JOIN (
                        SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                        FROM customer_orders co
                        JOIN  requests rqs ON co.request_id = rqs.id
                        JOIN  request_services rss ON co.request_id = rss.request_id
                        JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                        WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                        GROUP BY co.request_id
                    ) rss ON r.id = rss.request_id `

                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id`
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id`
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` left join partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` where (((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
                        r.noServiceNoTask = 0 AND r.status=4) OR (i.status IS NOT NULL)${changeOrderBaseCondition}) ${splitMirrorCondition})  
                         ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
                         ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
                         ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
                         ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} ${createdAt}`
            );
        }
        else if (userType === 3) {
            query = await sequelize.query(
                ` SELECT  COUNT(DISTINCT p.id) as count  FROM projects p `
                + ` LEFT JOIN users u ON p.added_by=u.id  `
                + ` LEFT JOIN project_categories pc ON pc.id=p.project_category `
                + ` LEFT JOIN project_types ptp ON ptp.id=p.project_type `
                + ` left join request_partners rp on rp.request_id=p.request_id`
                + ` left join partners pr on pr.id=rp.partner_id`
                + ` LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id `
                + ` LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id`
                + ` INNER JOIN requests r ON p.request_id = r.id `
                + ` LEFT JOIN (
                    SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity,
                     SUM(
                            CASE
                            WHEN cop.is_single_card = 1 THEN 1
                            ELSE cop.location_quantity
                            END
                        ) AS product_count
                    FROM customer_orders co
                    JOIN customer_order_products cop ON co.id = cop.order_id
                    JOIN requests req ON co.request_id = req.id
                    WHERE cop.material = 0
                    GROUP BY co.request_id
                ) cop ON r.id = cop.request_id `

                + ` LEFT JOIN (
                    SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                    FROM customer_orders co
                    JOIN  requests rqs ON co.request_id = rqs.id
                    JOIN  request_services rss ON co.request_id = rss.request_id
                    JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                    WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                    GROUP BY co.request_id
                ) rss ON r.id = rss.request_id `

                + ` LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id `
                + ` LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id `
                + ` LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id`
                + ` left join customer_orders c_ord on c_ord.request_id = p.request_id `
                + ` left join partners part ON part.id = c_ord.customer_id `
                + ` LEFT JOIN community com ON com.id=p.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
                + ` where pr.user_id=${userId} and ((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
                        r.noServiceNoTask = 0 AND r.status=4) OR  (i.status IS NOT NULL)${changeOrderBaseCondition}) 
                          ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
                         ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
                         ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
                         ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} ${createdAt}`
            );
        }
        else {
            query = await sequelize.query(
                `SELECT  COUNT(DISTINCT p.id) as count  FROM projects p 
                LEFT JOIN staff_members s1 ON s1.id=p.project_lead  
                LEFT JOIN users u1 ON s1.user_id=u1.id 
                LEFT JOIN project_categories pc ON pc.id=p.project_category 
                LEFT JOIN project_types ptp ON ptp.id=p.project_type 
                LEFT JOIN staff_members s2 ON s2.id=p.default_assignee 
                LEFT JOIN users u2 ON s2.user_id=u2.id 
                LEFT JOIN installations i2 ON p.id=i2.project_id 
                LEFT JOIN driver dr ON i2.driver_id=dr.id 
                LEFT JOIN (select pm.project_id, COALESCE(u.id,u2.id) as user_id 
                    from project_members pm 
                    left join partners p on p.id=pm.partner_id 
                    left join users u on p.user_id=u.id 
                    left join staff_members s on s.id=pm.staff_id 
                    left join users u2 on s.user_id=u2.id) pmm 
                    ON pmm.project_id=p.id and pmm.user_id=${userId} 
                LEFT JOIN users u ON p.added_by=u.id 
                LEFT JOIN (select count(id) as count, project_id from project_members group by project_id) pm ON pm.project_id=p.id  
                LEFT JOIN (select count(ID) as count, project_id from project_tasks where status!=0 group by project_id) pt ON pt.project_id=p.id  
                INNER JOIN requests r ON p.request_id = r.id 
                LEFT JOIN users ura ON r.added_by=ura.id 
                LEFT JOIN (
                    SELECT co.request_id, SUM(cop.location_quantity) AS location_quantity, 
                     SUM(
                    CASE
                      WHEN cop.is_single_card = 1 THEN 1
                      ELSE cop.location_quantity
                    END
                  ) AS product_count
                    FROM customer_orders co
                    JOIN customer_order_products cop ON co.id = cop.order_id
                    JOIN requests req ON co.request_id = req.id
                    WHERE cop.material = 0
                    GROUP BY co.request_id
                ) cop ON r.id = cop.request_id 
                LEFT JOIN (
                    SELECT co.request_id, SUM(rss.qty) AS location_quantity, COUNT(rss.qty) AS service_count
                    FROM customer_orders co
                    JOIN  requests rqs ON co.request_id = rqs.id
                    JOIN  request_services rss ON co.request_id = rss.request_id
                    JOIN  labour_cost_services lcs ON rss.labour_cost_service_id = lcs.id
                    WHERE rss.recipe_id IS NULL ${laborInstallWhereCondition} ${makeAsTaskCondition}
                    GROUP BY co.request_id
                ) rss ON r.id = rss.request_id 
                -- ✅ FIX: Include complete_status in installations join
                LEFT JOIN (SELECT request_id, MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review FROM installations GROUP BY request_id) i ON i.request_id = r.id 
                LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 4 GROUP BY request_id) inst_counts ON inst_counts.request_id = r.id 
                LEFT JOIN (SELECT request_id, COUNT(*) AS total_installation_count FROM installations GROUP BY request_id) total_inst_counts ON total_inst_counts.request_id = r.id
                LEFT JOIN (select count(id) as count, request_id from job_note_messages group by request_id) jnm ON jnm.request_id=p.request_id
                LEFT JOIN customer_orders c_ord ON c_ord.request_id = p.request_id 
                LEFT JOIN partners part ON part.id = c_ord.customer_id 
                LEFT JOIN community com ON com.id=p.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1 
                WHERE (u1.id = ${userId} OR u2.id = ${userId} OR pmm.user_id =${userId} OR (r.added_by = ${userId} AND ura.user_type <> 3) OR FIND_IN_SET(${userId}, i2.team_id) OR FIND_IN_SET(${userId}, dr.user_id)) 
                AND ((p.status = 3 AND total_inst_counts.total_installation_count IS NULL AND 
                        r.noServiceNoTask = 0 AND r.status=4) OR  (i.status IS NOT NULL)${changeOrderBaseCondition}) 
                         ${splitOrder === 1 ? ' AND r.is_split_order = 1 AND r.for_parent_facility != 2' : splitOrder === 2 ? ' AND r.is_split_order = 0' : ''} ${dateCondition != '' ? ' AND ' + dateCondition : ''} AND ${projectTypeCondition}
                         ${jobClassCondition} ${jobTypesCondition} ${clientCondition} ${userCondition} ${estimateCondition} ${projectCondition}
                         ${searchCondition != '' ? ' AND ' + searchCondition : ''} ${departmentCondition != '' ? departmentCondition : ''}  
                         ${tabCondition != '' ? ' AND (' + tabCondition + ')' : ''} ${changeOrderExclusion != '' ? ' AND ' + changeOrderExclusion : ''} ${createdAt}`
            );
            
        }
        if (query.length > 0) {
            return query?.[0]?.[0]?.count || 0;
        } else {
            return 0;
        }
    } catch (error) {
        console.log("#####################Error", error);
        throw new Error("Server error");
    }
}

  const deleteProjectMembersBySubtaskIdForUpdate = async (id, status = 0) => {

    try {
        const deleted = await ProjectMembers.destroy({
            where: {
                sub_task_id: id
            },
        });

        if (deleted) {
            return deleted;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
    }
}
const deleteEstimateProjectMembersBySubtaskIdForUpdate = async (id, status = 0) => {
    try {
        const deleted = await EstimateProjectMembers.destroy({
            where: {
                sub_task_id: id
            },
        });

        if (deleted) {
            return deleted;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
    }
}

  const getSubtaskMembersByProjectId = async (projectId) => {
    try {
        const result = await sequelize.query(`
            SELECT DISTINCT
                psm.id as subtask_member_id,
                psm.subtask_id,
                psm.staff_id,
                psm.partner_id,
                psm.contact_id,
                psm.lead_id,
                ps.name as subtask_name,
                ps.description as subtask_description,
                ps.status as subtask_status,
                ps.complete as subtask_complete,
                ps.start_date as subtask_start_date,
                ps.due_date as subtask_due_date,
                ps.priority as subtask_priority,
                pt.ID as task_id,
                pt.name as task_name,
                pt.project_id,
                -- Staff member data
                sm.first_name,
                sm.last_name,
                sm.email as staff_email,
                sm.phone as staff_phone,
                sm.hourly_rate,
                sm.services,
                sm.status as staff_status,
                sm.city,
                sm.state_id,
                sm.contact_tags,
                sm.workflows,
                sm.permissions,
                sm.personal_timezone,
                sm.date_format,
                sm.time_format,
                CONCAT(sm.first_name, ' ', COALESCE(sm.last_name, '')) AS staff_name,
                -- User data
                u.id as staff_user_id,
                u.username,
                u.email as user_email,
                u.profile_pic as staff_profile_pic,
                u.company_name,
                u.user_type,
                u.status as user_status,
                u.timestamp as user_timestamp,
                u.last_login,
                u.timezone,
                u.language,
                u.date_format as user_date_format,
                u.time_format as user_time_format,
                u.currency,
                u.noti_count,
                u.is_online,
                u.last_seen,
                -- User role data
                ur.name as staff_role,
                ur.user_permissions,
                ur.staff_permission,
                ur.is_added_by_client,
                ur.isClientUserRole,
                -- Partner data (if applicable)
                p.name as partner_name,
                p.user_id as partner_user_id,
                p.partner_type,
                p.rank_id,
                p.state_id as partner_state_id,
                p.city as partner_city,
                p.onboard_complete,
                p.card_order,
                p.isVendor,
                p.customerTypeId,
                -- Partner user data
                u3.profile_pic as partner_profile_pic,
                u3.email as partner_email,
                u3.id as partner_user_id_from_users,
                -- Partner type data
                pt_type.name as partner_type_name,
                pt_type.bg_color,
                -- Rank data
                r.name as rank_name,
                r.rank_image,
                -- State data
                s.short_name as state_name,
                s.name as state_full_name,
                -- Customer type data
                ct.name as customer_type_name,
                ct.billing_type,
                -- User role for partner
                ur2.name as partner_user_role
            FROM project_subtask_members psm
            JOIN project_subtasks ps ON ps.ID = psm.subtask_id
            LEFT JOIN project_tasks pt ON pt.ID = ps.task_id
            LEFT JOIN staff_members sm ON sm.id = psm.staff_id
            LEFT JOIN users u ON u.id = sm.user_id
            LEFT JOIN user_roles ur ON ur.id = u.user_type
            LEFT JOIN partners p ON p.id = psm.partner_id
            LEFT JOIN users u3 ON p.user_id = u3.id
            LEFT JOIN partner_types pt_type ON p.partner_type = pt_type.id
            LEFT JOIN ranks r ON p.rank_id = r.id
            LEFT JOIN states s ON p.state_id = s.id
            LEFT JOIN customer_type ct ON p.customerTypeId = ct.id
            LEFT JOIN user_roles ur2 ON u3.user_type = ur2.id
            WHERE pt.project_id = ${projectId}
            AND ps.status != 0
            ORDER BY pt.ID DESC, ps.ID DESC, psm.id DESC
        `);

        if (!empty(result)) {
            if (result[0].length > 0) {
                return result[0];
            }
        }
        return [];
    } catch (error) {
        console.log("Error in getSubtaskMembersByProjectId:", error);
        return [];
    }
}

const getTransactionCountByProjectId = async (projectId,requestId) => {
  try {
    if(requestId){
      const result = await sequelize.query(`SELECT qb_transaction_count FROM projects WHERE request_id = ${requestId}`);
      return result[0][0].qb_transaction_count;
    }
    else{
      const result = await sequelize.query(`SELECT qb_transaction_count FROM projects WHERE id = ${projectId}`);
      return result[0][0].qb_transaction_count;
    }
  }
  catch (error) {
    console.log("Error in getTransactionCountByProjectId:", error);
    return 0;
  }
}

// --- Project member sync helpers (job members shown in ViewTask) ---
// Rules:
// - Add anyone assigned to any subtask in this project (union across all tasks).
// - Remove ONLY workflow-skill-based members if they are no longer assigned to any subtask in the project.
// - Never remove clients/collaborators/protected roles.
const getDistinctSubtaskStaffIdsByProjectId = async (projectId) => {
  try {
    const [rows] = await sequelize.query(
      `
      SELECT DISTINCT psm.staff_id
      FROM project_subtask_members psm
      JOIN project_subtasks ps ON ps.ID = psm.subtask_id
      JOIN project_tasks pt ON pt.ID = ps.task_id
      WHERE pt.project_id = :projectId
        AND ps.status != 0
        AND psm.staff_id IS NOT NULL
      `,
      { replacements: { projectId: Number(projectId) } }
    );

    return (rows || [])
      .map((r) => Number(r?.staff_id))
      .filter((n) => Number.isFinite(n) && n > 0);
  } catch (error) {
    console.error("Error in getDistinctSubtaskStaffIdsByProjectId:", error);
    return [];
  }
};

const getDistinctWorkflowSkillIdsByProjectId = async (projectId) => {
  try {
    // Product tasks: pt.customer_order_product_id -> customer_order_products.id
    // Service tasks: pt.customer_order_product_id -> request_services.id
    const [workflowRows] = await sequelize.query(
      `
      SELECT DISTINCT cp.workflow AS workflow_id
      FROM project_tasks pt
      JOIN customer_order_products cp ON cp.id = pt.customer_order_product_id
      WHERE pt.project_id = :projectId
        AND pt.status != 0
        AND pt.product_id IS NOT NULL
        AND pt.service_id IS NULL
        AND cp.workflow IS NOT NULL

      UNION

      SELECT DISTINCT rs.workflow AS workflow_id
      FROM project_tasks pt
      JOIN request_services rs ON rs.id = pt.customer_order_product_id
      WHERE pt.project_id = :projectId
        AND pt.status != 0
        AND pt.service_id IS NOT NULL
        AND pt.product_id IS NULL
        AND rs.workflow IS NOT NULL
      `,
      { replacements: { projectId: Number(projectId) } }
    );

    const workflowIds = (workflowRows || [])
      .map((r) => Number(r?.workflow_id))
      .filter((n) => Number.isFinite(n) && n > 0);

    if (!workflowIds.length) return [];

    const [stageRows] = await sequelize.query(`
      SELECT ows.skill_ids
      FROM onboard_workflow_stages ows
      WHERE ows.status = 1
        AND ows.workflow_id IN (${workflowIds.join(",")})
    `);

    const skillIds = new Set();
    for (const row of stageRows || []) {
      const raw = row?.skill_ids;
      if (!raw) continue;
      const found = String(raw).match(/\d+/g) || [];
      for (const s of found) {
        const n = Number(s);
        if (Number.isFinite(n) && n > 0) skillIds.add(n);
      }
    }

    return Array.from(skillIds);
  } catch (error) {
    console.error("Error in getDistinctWorkflowSkillIdsByProjectId:", error);
    return [];
  }
};

const syncSkillBasedProjectMembersBySubtasks = async (projectId, opts = {}) => {
  const protectedUserTypes = Array.isArray(opts.protectedUserTypes)
    ? opts.protectedUserTypes
    : [1]; // default: superadmin

  try {
    const unionSubtaskStaffIds = new Set(
      await getDistinctSubtaskStaffIdsByProjectId(projectId)
    );

    // Skill-based staff derived from workflows across all tasks in this project
    const skillIds = await getDistinctWorkflowSkillIdsByProjectId(projectId);
    const skillCsv = (skillIds || []).join(",");
    const workflowStaffIds = new Set();
    if (skillCsv) {
      const members = await getTeamMembersBasedOnSkills(skillCsv, 14);
      for (const m of members || []) {
        const staffId = Number(m?.id);
        if (Number.isFinite(staffId) && staffId > 0) workflowStaffIds.add(staffId);
      }
    }

    const [existingRows] = await sequelize.query(
      `
      SELECT pm.id, pm.staff_id, pm.partner_id, pm.collaboration, u.user_type
      FROM project_members pm
      LEFT JOIN staff_members sm ON sm.id = pm.staff_id
      LEFT JOIN users u ON u.id = sm.user_id
      WHERE pm.project_id = :projectId
      `,
      { replacements: { projectId: Number(projectId) } }
    );

    const existingStaffIds = new Set();
    for (const row of existingRows || []) {
      const staffId = Number(row?.staff_id);
      if (Number.isFinite(staffId) && staffId > 0) existingStaffIds.add(staffId);
    }

    // Add: ensure union subtask members exist as project members (add-only)
    for (const staffId of unionSubtaskStaffIds) {
      if (existingStaffIds.has(staffId)) continue;
      await ProjectMembers.create({
        project_id: Number(projectId),
        staff_id: Number(staffId),
        partner_id: null,
        contact_id: null,
        lead_id: null,
        collaboration: 0,
      });
    }

    // Remove: only workflow-skill-based members not assigned to any subtask
    for (const row of existingRows || []) {
      const pmId = Number(row?.id);
      const staffId = Number(row?.staff_id);
      if (!Number.isFinite(pmId) || pmId <= 0) continue;
      if (!Number.isFinite(staffId) || staffId <= 0) continue;

      const isClient = row?.partner_id != null;
      const isCollaborator = Number(row?.collaboration) === 1;
      const isProtectedRole = protectedUserTypes.includes(Number(row?.user_type));
      if (isClient || isCollaborator || isProtectedRole) continue;

      const isWorkflowSkillBased = workflowStaffIds.has(staffId);
      const isOnAnySubtask = unionSubtaskStaffIds.has(staffId);
      if (isWorkflowSkillBased && !isOnAnySubtask) {
        await ProjectMembers.destroy({ where: { id: pmId } });
      }
    }

    return { status: 1 };
  } catch (error) {
    console.error("Error in syncSkillBasedProjectMembersBySubtasks:", error);
    return { status: 0, message: String(error) };
  }
};

const getAllJobsProjectTableData = async () => {
  try {
    const result = await sequelize.query(`SELECT * FROM projects WHERE status in (1,2)`);
    return result[0];
  }
  catch (error) {
    console.log("Error in getAllProjectTableData:", error);
    return [];
  }
}

module.exports = {
    Projects, getProjectById, getAllProjects,getAllProjectsProgress, addProject, isProjectNameExist, doUpload, updateProject,updateProjectByRequestId, updateEstimateJobProjectByRequestId, deleteProject,
    getAllProjectCategories,getAllNoChargeTypes, getAllProjectTypes, getAllStates, acceptedRequests, isProjectTypeExist, addProjectType,
    getProjectTypeById, updateProjectType, deleteProjectType, getAllTeam, getTeamMembers, addProjectMember, getAllProjectMembers,
    fetchAllAttachments, fetchAllTeamMembers, deleteProjectMember, addNoChargeType,isNoChargeTypeExist,addProjectCategory, getProjectCategoryById, updateProjectCategory,getNoChargeTypeById,
    deleteProjectCategory,deleteNoChargeType,updateNoChargeType, isProjectCategoryExist, getTeamMembersBasedOnSkills,
    fetchprojectsByClientId, fetchprojectsByTeamId,
    projectMemberExist,
    getAllcompletedInstallations, getAllcompletedInstallationsForCommunityCount, deleteAllProjectMember, updateCardOrder,
    findProjectById,
    getAllDesignOrderJobs,
    getAllEstimateTeamMembers, getEstimators,
    getDesignOrderProjectById,updateProjectById,getDesignTeamMembersBasedOnSkills,getAllDesignTeamMembers,getAllTeamMembersForEmail,
    getAllMemberUserIdsByProjectId,getJobsTabByUserData,jobTabIncrementField,getJobsTabCountByUser,addJobsTabCount ,updateJobsTabCount ,getJobsTabByUserId,getProjectByRequestId,fetchDesignOrdersByTeamId,projectMembersForMessaging,DriverForMessaging,InstallersForMessaging,
    AdminsForMessaging,fetchProjectStatusById, fetchAllUsersByTaskModel,
    fetchAllInstallerDriver,fetchAllUsersByTimeAndMaterialModel,projectIdFromRequestId,
    getSubtaskMembersByProjectId,
    deleteProjectMembersBySubtaskIdForUpdate,
    getDistinctSubtaskStaffIdsByProjectId,
    getDistinctWorkflowSkillIdsByProjectId,
    syncSkillBasedProjectMembersBySubtasks,
    getTotalEstimateProjectsCount, getAllEstimateProjects, getAllProjectsForCommunityCount,
    getTotalProjectsCount, getTotalCompletedInstallationsCount,
    getOptimizedProductionOverviewCounts,
    getTotalDesignOrderJobsCount,
    AdminsForMessagingNew,getTransactionCountByProjectId,
    updateEstimateJobHoldByRequestId,getAllJobsProjectTableData,
}