const { INTEGER, STRING, TEXT, FLOAT, TINYINT, CHAR, DECIMAL, Sequelize, Op } = require("sequelize");
const sequelize = require("../config/dbconnection");
const { empty } = require("../Helpers/Common");
const moment = require('moment')
const { fetchPartners, getRequestPartnerByIds, getRequestPartnersBulk } = require("./requestPartners");
const { FACILITY_ID, getOtherInstallationDatabases } = require("../config/SplitManagementDb");

let includeLabourInstallService = true;
let laborInstallWhereCondition = includeLabourInstallService ? '' : ' AND rss.labour_cost_service_id != 10'
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 Requests = sequelize.define('request', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  name: { type: STRING, allowNull: false },
  catalog_type: { type: STRING, allowNull: true, defaultValue: null  },
  description: { type: TEXT, allowNull: false },
  thumbnail: { type: STRING(2000), allowNull: true, defaultValue: null },
  services: { type: INTEGER, allowNull: true },
  workflows: { type: INTEGER, allowNull: true },
  reason: { type: TEXT, allowNull: true, defaultValue: null },
  edit_reason: { type: TEXT, allowNull: true, defaultValue: null },
  reject_file: { type: TEXT, allowNull: true, defaultValue: null },
  reject_file_type: { type: TEXT, allowNull: true, defaultValue: null },
  project_type: { type: INTEGER, allowNull: true, defaultValue: null },
  project_category: { type: TINYINT, allowNull: true, defaultValue: null },
  no_charge_type: { type: TINYINT, allowNull: true, defaultValue: null },
  no_charge_reason: { type: TEXT, allowNull: true},
  community: { type: INTEGER, allowNull: true, defaultValue: null },
  map_service: { type: INTEGER, allowNull: true, defaultValue: null },
  submission_deadline: { type: STRING, defaultValue: null, allowNull: true },
  participation_ends: { type: STRING, defaultValue: null, allowNull: true },
  installation_start_date: { type: INTEGER, allowNull: true, defaultValue: null },
  installation_end_date: { type: INTEGER, allowNull: true, defaultValue: null },
  start_date: { type: STRING, defaultValue: null, allowNull: true },
  subject: { type: TEXT, defaultValue: null },
  closed_for_proposal: { type: INTEGER, defaultValue: 0 },
  email_content: { type: TEXT, allowNull: true },
  type: { type: TINYINT, defaultValue: null, },
  welcome_message: { type: TINYINT, defaultValue: null, },
  markup_type: { type: INTEGER, allowNull: false, defaultValue: 1 },
  status: { type: TINYINT, defaultValue: 1 },
  added_by: { type: INTEGER, defaultValue: null },
  edited_by: { type: INTEGER, defaultValue: null },
  onboard_complete: { type: INTEGER, defaultValue: 0 },
  timestamp: { type: INTEGER, allowNull: false },
  noServiceNoTask: { type: TINYINT, allowNull: false, defaultValue: 0 },
  labour_cost_services: { type: TEXT, allowNull: true, defaultValue: null },
  labour_cost: { type: INTEGER, allowNull: false, defaultValue: 0 },
  is_location: { type: INTEGER, allowNull: false, defaultValue: 0 },
  is_service_location: { type: INTEGER, allowNull: false, defaultValue: 0 },
  is_rfp_service_location: { type: INTEGER, allowNull: false, defaultValue: 0 },
  is_rfp_product_location: { type: INTEGER, allowNull: false, defaultValue: 0 },
  notes: { type: TEXT, allowNull: false },
  quotation: { type: TINYINT, defaultValue: 0 },
  is_request_estimate: { type: TINYINT, defaultValue: 0 },
  estimator_ids: { type: STRING(250), allowNull: true, defaultValue: null },
  is_create_estimate: { type: TINYINT, defaultValue: 0 },
  new_order: { type: TINYINT, allowNull: false, defaultValue: 0 },
  quotation_status: { type: TINYINT, defaultValue: 2 },
  estimate_id: { type: INTEGER, allowNull: true },
  syncWithQuickbooks: { type: INTEGER, allowNull: true },
  is_production_qb: { type: INTEGER, allowNull: true, defaultValue: 1 },
  reasonWithQb: { type: STRING(3000), allowNull: true },
  card_order: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
  doc_number: { type: STRING(200), allowNull: true , defaultValue: null},
  est_doc_number: { type: TEXT, allowNull: true , defaultValue: null},
  po_number: { type: STRING(200), allowNull: true, defaultValue: null },
  isReview: { type: INTEGER, allowNull: true, defaultValue: 0 },
  installation_acceptance: { type: INTEGER, allowNull: true, defaultValue: null },
  min_payment_status:{ type: INTEGER, allowNull: false, defaultValue: 0 },
  client_approve: { type: INTEGER, allowNull: false, defaultValue: 0  },
  isFromDesignOrder: { type: INTEGER, allowNull: false, defaultValue: 0  },
  isFromEstimate: { type: INTEGER, allowNull: false, defaultValue: 0  },
  design_order_id: { type: INTEGER, allowNull: true, defaultValue: null },
  is_single_card: { type: INTEGER, allowNull: false, defaultValue: 0  },
  send_to_client: { type: INTEGER, allowNull: false, defaultValue: 1  },
  duplicated_from: { type: INTEGER, allowNull: true, defaultValue: null },
  hold: {type:INTEGER,allowNull:false,defaultValue:0},
  hold_reason: { type: TEXT, allowNull: true, defaultValue: null },
  avalara_transaction_id: { type: TEXT, allowNull: true, defaultValue: null },
  avalara_code: { type: TEXT, allowNull: true, defaultValue: null },
  created_at: { type: INTEGER, allowNull: false, defaultValue: 0 },
  facility_type: { type: TEXT, allowNull: true, defaultValue: null },
  origin_facility_id: { type: INTEGER, allowNull: true, defaultValue: null },
  origin_facility_request_id: { type: INTEGER, allowNull: true, defaultValue: null },
  is_split_order: { type: INTEGER, allowNull: false, defaultValue: 0 },
  for_parent_facility: { type: INTEGER, allowNull: false, defaultValue: 0 },
  new_order: { type: TINYINT, allowNull: false, defaultValue: 0 },
  split_mirror_status: { type: INTEGER, allowNull: false, defaultValue: 0 },
  mirror_approve_status: { type: TEXT, allowNull: true, defaultValue: null },
  received_status: { type: INTEGER, allowNull: false, defaultValue: 0 },
  sales_rep_ids: { type: TEXT, allowNull: true, defaultValue: null },
  collaborators: { type: TEXT, allowNull: true, defaultValue: null },
  sign_agreement: { type: TEXT, allowNull: true, defaultValue: null },
  is_draft: { type: TINYINT, allowNull: false, defaultValue: 0 },
  show_install_price: { type: TINYINT, allowNull: true, defaultValue: 1 },
  bill_to: { type: TEXT, allowNull: true },
  ship_to: { type: TEXT, allowNull: true },
}, { timestamps: false, tableName: 'requests' })
// when you adding any new row in the table also need to add in splitmanagement model

const RequestAttachments = sequelize.define('request_attachments', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  name: { type: TEXT, allowNull: false },
  request_id: { type: STRING, allowNull: false },
  extension: { type: STRING, allowNull: false, defaultValue: "img" },
  file_size: { type: INTEGER, allowNull: false, defaultValue: 2 },
  file_type: { type: String, allowNull: false, defaultValue: "img" },
  approved: { type: TINYINT, allowNull: false, defaultValue: 0 },
  approved_by: { type: INTEGER, allowNull: true, defaultValue: null },
  product_id: { type: INTEGER, allowNull: true, defaultValue: null },
  product_ids: { type: STRING, allowNull: true, defaultValue: null },
  location_ids: { type: STRING, allowNull: true, defaultValue: null },
  reason: { type: TEXT, allowNull: true, defaultValue: null },
  status: { type: TINYINT, defaultValue: 1 },
  added_by: { type: INTEGER, defaultValue: null },
  isDesign: { type: TINYINT, defaultValue: 2 },
  timestamp: { type: INTEGER, allowNull: false }
}, { timestamps: false })
const RequestPayments = sequelize.define('request_payments', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  request_id: { type: INTEGER, allowNull: false },
  title: { type: STRING, allowNull: false, },
  amount: { type: FLOAT, allowNull: false, defaultValue: 2 },
  added_by: { type: INTEGER, defaultValue: null },
  timestamp: { type: INTEGER, allowNull: false },
  updated_by: { type: INTEGER, allowNull: true },
  status: { type: TINYINT, defaultValue: 1 },
  paymentMode: { type: STRING, allowNull: true, },
  source: { type: INTEGER, allowNull: false,defaultValue: 1 }

}, { timestamps: false })
const RequestLocation = sequelize.define('request_locations', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  order_id: { type: INTEGER, allowNull: false },
  product_id: { type: INTEGER, allowNull: true, defaultValue: null },
  route_location_id: {type: INTEGER, allowNull: true, defaultValue: null },
  address: { type: STRING, allowNull: true, },
  city: { type: STRING, allowNull: true, },
  state: { type: STRING, allowNull: true, },
  zip: { type: STRING, allowNull: true, },
  lng: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
  lat: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
  added_by: { type: INTEGER, defaultValue: null },
  timestamp: { type: INTEGER, allowNull: false },
  updated_by: { type: INTEGER, allowNull: true },
  status: { type: TINYINT, defaultValue: 1 },
  starting_point: { type: INTEGER, allowNull: true, defaultValue: null },
  ending_point: { type: INTEGER, allowNull: true, defaultValue: null },
  color: { type: TEXT, allowNull: true, defaultValue: null },
  isLinkedAll: { type: INTEGER, allowNull: false, defaultValue: 0 },
}, { timestamps: false })
const RequestServiceLocations = sequelize.define('request_service_locations', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  request_id: { type: INTEGER, allowNull: false },
  service_id: { type: INTEGER, allowNull: false },
  address: { type: STRING, allowNull: true, },
  city: { type: STRING, allowNull: true, },
  state: { type: STRING, allowNull: true, },
  zip: { type: STRING, allowNull: true, },
  lng: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
  lat: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
  added_by: { type: INTEGER, defaultValue: null },
  timestamp: { type: INTEGER, allowNull: false },
  updated_by: { type: INTEGER, allowNull: true },
  status: { type: TINYINT, defaultValue: 1 },
  starting_point: { type: INTEGER, allowNull: true, defaultValue: null },
  ending_point: { type: INTEGER, allowNull: true, defaultValue: null },
  color: { type: TEXT, allowNull: true, defaultValue: null },
}, { timestamps: false })
const RequestServices = sequelize.define('request_services', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  product_index: { type: INTEGER, allowNull: false, defaultValue: 0 },
  request_id: { type: INTEGER, allowNull: false },
  labour_cost_service_id: { type: INTEGER, allowNull: true, defaultValue: null },
  recipe_id: { type: INTEGER, allowNull: true, defaultValue: null },
  product_id: { type: INTEGER, allowNull: true, defaultValue: null },
  qty: { type: FLOAT(12, 2), allowNull: false },
  markup: { type: FLOAT(12, 2), allowNull: true, defaultValue: null },
  unit_cost: { type: FLOAT(12, 2), allowNull: false },
  total_cost: { type: FLOAT(12, 2), allowNull: false },
  job_cost: { type: INTEGER, allowNull: true, defaultValue: 0 },
  taken: { type: TINYINT, allowNull: false, defaultValue: 0 },
  rfp: { type: TINYINT, allowNull: false, defaultValue: 0 },
  map_service: { type: TINYINT, allowNull: false, defaultValue: 0 },
  jobcost_unit_cost: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0 },
  jobcost_quantity: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0 },
  jobcost_total_cost: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0 },
  is_dos: { type:INTEGER, allowNull: false, defaultValue: 0 },
  isAdditionalProduct: { type:INTEGER, allowNull: false, defaultValue: 0 },
  makeAsTask: { type:TINYINT(4), allowNull: false, defaultValue: 0 },
  makeInstallCard: { type:TINYINT(4), allowNull: false, defaultValue: 0 },
  from_job: { type:INTEGER, allowNull: false, defaultValue: 0 },
  fixed_service_cost: { type:INTEGER, allowNull: false, defaultValue: 0 },
  is_addition_service: { type:INTEGER, allowNull: true, defaultValue: 0 },
  service_notes: { type: TEXT(2000), allowNull: true, defaultValue: null },
  status: { type: TINYINT, allowNull: false, defaultValue: 1 },
  service_name : { type: STRING, allowNull: true, defaultValue: null },
  workflow:{type:INTEGER,allowNull:true,defaultValue:null},
  facility_id:{type:INTEGER,allowNull:true,defaultValue:null},
  split_percentage: { type: FLOAT, allowNull: true,defaultValue:0 },
  incoming_split_percentage: { type: FLOAT, allowNull: true,defaultValue:0 },
  delivery_type_id: { type: INTEGER, allowNull: true,defaultValue:null },
  installer_facility_id: { type: INTEGER, allowNull: true,defaultValue:null },
  service_desc:{type:TEXT,allowNull:true, defaultValue:null}, 
  is_service_row: { type: INTEGER, allowNull: true, defaultValue: null },
  is_existing_service: { type: INTEGER, allowNull: true, defaultValue: 0 },
}, { timestamps: false, tableName: 'request_services' })

const emails = sequelize.define('emails', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  email: { type: STRING, allowNull: false },
}, { timestamps: false, tableName: 'emails' });

const DesignOrders = sequelize.define('design_orders', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  name: { type: STRING(200), allowNull: false },
  total_cost: { type: FLOAT, allowNull: false ,defaultValue:0.00},
  description: { type: TEXT, allowNull: false },
  client: { type: INTEGER, allowNull: false },
  community: { type: INTEGER, allowNull: true },
  start_date: { type: INTEGER, allowNull: true, defaultValue:null },
  due_date: { type: INTEGER, allowNull: true, defaultValue:null },
  requested_due_date:{ type: INTEGER, allowNull: true, defaultValue:null },
  subject: { type: STRING(200), allowNull: true, defaultValue: null },
  email_content: { type: TEXT, allowNull: true, defaultValue: null },
  welcome_message: { type: TINYINT, allowNull: true, defaultValue: null },
  notes: { type: TEXT, allowNull: true, defaultValue: null },
  estimate_id:{type: INTEGER(100), allowNull: true, defaultValue: null },
  syncWithQuickbooks:{type: INTEGER, allowNull: true, defaultValue: null },
  reasonWithQb:{type: TEXT, allowNull: true, defaultValue: null},
  card_order: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 1 },
  status: { type: TINYINT, allowNull: false, defaultValue: 1 },
  completion: { type: INTEGER, allowNull: false, defaultValue: 1 },
  design_order_job_status: { type: INTEGER, allowNull: false, defaultValue: 1 },
  reason: { type: TEXT, allowNull: true, defaultValue: null },
  reject_type: { type: INTEGER, allowNull: true, defaultValue: null },
  reject_file: { type: TEXT, allowNull: true, defaultValue: null },
  reject_file_type: { type: TEXT, allowNull: true, defaultValue: null },
  hold_reason: { type: TEXT, allowNull: true, defaultValue: null },
  added_by: { type: INTEGER, allowNull: false },
  designer_email_sent: { type: TINYINT, allowNull: false, defaultValue: 0 },
  designer_sms_sent: { type: TINYINT, allowNull: false, defaultValue: 0 },
  timestamp: { type: INTEGER, allowNull: false },
  created_at: { type: INTEGER, allowNull: true, defaultValue: null },
  hold: { type: INTEGER, allowNull: false, defaultValue: 0 },
  client_approve: { type: INTEGER, allowNull: false, defaultValue: 1  },
  send_client_app_req: { type: INTEGER, allowNull: false, defaultValue: 0  },
  edited_by: { type: INTEGER, allowNull: true, defaultValue: null },
  working_designer_id: { type: INTEGER, allowNull: true, defaultValue: null },
  is_from_client: { type: TINYINT, allowNull: false, defaultValue: 0 },
  is_in_queue: { type: TINYINT, allowNull: false, defaultValue: 0 },
  collaborators: { type: TEXT, allowNull: true, defaultValue: null },
  request_id: { type: INTEGER, allowNull: true, defaultValue: null },
  old_design_order_id: { type: INTEGER, allowNull: true, defaultValue: null },
}, { timestamps: false, tableName:'design_orders' })

const DesignOrderAttachments = sequelize.define('design_order_attachments', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  name: { type: TEXT, allowNull: false },
  design_order_id: { type: INTEGER, allowNull: false },
  extension: { type: STRING(10), allowNull: false,defaultValue:"img" },
  file_size: { type: INTEGER, allowNull: false,defaultValue:2 },
  file_type: { type:STRING(200), allowNull: false,defaultValue:"img" },
  approved: { type: TINYINT,allowNull: false, defaultValue: 0 },
  approved_by: { type: INTEGER,allowNull:true, defaultValue: null },
  added_by: { type: INTEGER, defaultValue: null },
  reason: { type: TEXT, allowNull: true, defaultValue: null },
  timestamp: { type: INTEGER, allowNull: false },
  isChat: { type: TINYINT, defaultValue: 0 },
  status: { type: TINYINT, defaultValue: 1 },
  isDesign: { type: TINYINT, defaultValue: 1 },
  isNew: { type: INTEGER, defaultValue: 1 },
  is_reference: { type: TINYINT,allowNull: false, defaultValue: 0 },
}, { timestamps: false, tableName:'design_order_attachments' })

const DesignOrdersServices = sequelize.define('design_order_services', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  labour_cost_service_id:{ type: INTEGER, allowNull: false },
  quantity:{ type: FLOAT(14,2), allowNull: false },
  total:{ type: FLOAT(12,2), allowNull: false },
  unit_cost:{ type: FLOAT(14,2), allowNull: false },
  taken:{ type: INTEGER, allowNull: false,defaultValue:0 },
  job_cost:{ type: INTEGER, allowNull: false,defaultValue:0 },
  jobcost_quantity:{ type: FLOAT(14,2), allowNull: false,defaultValue:0.00 },
  jobcost_total_cost:{ type: FLOAT(14,2), allowNull: false,defaultValue:0.00 },
  design_order_id:{ type: INTEGER, allowNull: false },
  complete:{ type: INTEGER, allowNull: false, defaultValue: 0 },
  status:{ type: INTEGER, allowNull: false, defaultValue: 1 },
}, { timestamps: false, tableName:'design_order_services' })

const DesignOrderProducts = sequelize.define('design_order_products', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  product_index:{type:INTEGER,allowNull:false,defaultValue:0},
  design_order_id: { type: INTEGER, allowNull: false },
  name: { type: TEXT, allowNull: false },
  description: { type: TEXT, allowNull: true, defaultValue: null },
  status: { type: INTEGER, allowNull: false, defaultValue: 1 },
}, { timestamps: false, tableName: 'design_order_products' })

const DesignOrdersSubTask = sequelize.define('design_order_sub_task', {
  id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  design_order_id: { type: Sequelize.INTEGER, allowNull: false, },
  task_id: { type: Sequelize.INTEGER, allowNull: false, },
  skill_ids :{type:Sequelize.STRING,allowNull:true},
  name: { type: Sequelize.STRING, allowNull: false },
  task_uid: { type: Sequelize.INTEGER, allowNull: false, },
  description: { type: Sequelize.STRING, allowNull: false },
  start_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  due_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  reporter_id: { type: Sequelize.INTEGER, allowNull: false,defaultValue:1 },
  priority: { type: Sequelize.INTEGER, allowNull: false, },
  status: { type: Sequelize.INTEGER, allowNull: false },
  userid: { type: Sequelize.INTEGER, allowNull: false, },
  timestamp: { type: Sequelize.INTEGER, allowNull: false },
  complete: { type: Sequelize.INTEGER, allowNull: false, },
  complete_sync: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 1 },
}, { timestamps: false,tableName:"design_order_sub_task" })

const DesignOrderProjectMembers = sequelize.define('design_order_project_members', {
  id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  design_order_id: { type: Sequelize.INTEGER, allowNull: false },
  staff_id: { type: Sequelize.INTEGER, allowNull: false },
  partner_id: { type: Sequelize.INTEGER, allowNull: true,defaultValue:null },
  contact_id: { type: Sequelize.INTEGER, allowNull: true,defaultValue:null },
  lead_id: { type: Sequelize.INTEGER, allowNull: true, defaultValue:null},
}, { timestamps: false })

const DesignOrderProjectSubtaskMembers = sequelize.define('design_order_project_subtask_members', {
  id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  subtask_id: { type: Sequelize.INTEGER, allowNull: false },
  staff_id: { type: Sequelize.INTEGER, allowNull: false },
  partner_id: { type: Sequelize.INTEGER, allowNull: true,defaultValue:null },
  contact_id: { type: Sequelize.INTEGER, allowNull: true,defaultValue:null },
  lead_id: { type: Sequelize.INTEGER, allowNull: true, defaultValue:null},
}, { timestamps: false })

const designOrderStaffTaskTimelogs = sequelize.define('design_order_staff_task_timelogs',{
  id: {type: Sequelize.INTEGER, allowNull: false,primaryKey:true ,autoIncrement:true},
  user_id: {type: Sequelize.INTEGER, allowNull: false},
  design_order_id: {type: Sequelize.INTEGER, allowNull: true, defaultValue:null},
  task_id: {type: Sequelize.INTEGER, allowNull: true, defaultValue:null},
  sub_task_id: {type: Sequelize.STRING, allowNull: true, defaultValue:null},
  start_time: {type: Sequelize.INTEGER, allowNull: false},
  end_time: {type: Sequelize.INTEGER, allowNull: true, defaultValue:null},
  status: {type: Sequelize.INTEGER, allowNull: false},
  noSubTask: {type: Sequelize.INTEGER, allowNull: false, defaultValue:0},
},{timestamps:false})

const DesignOrderRejectedFiles = sequelize.define('design_order_rejected_files', {
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  design_order_id: { type: INTEGER, allowNull: false },
  file_url: { type: STRING, allowNull: false },
  file_type: { type: STRING, allowNull: false },
  file_name: { type: STRING, allowNull: false },
  timestamp: { type: INTEGER, allowNull: false },
}, { timestamps: false, tableName: 'design_order_rejected_files' })

const designOrderPayOut=sequelize.define('design_order_payouts',{
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  design_order_id: { type: INTEGER,allowNull:true, defaultValue: null },
  task_id : { type: INTEGER,allowNull:true, defaultValue: null },
  log_id: { type: STRING, allowNull:true, defaultValue: null },
  timelog_id: { type: INTEGER, allowNull:true, defaultValue: null },
  paid_at: { type: INTEGER, defaultValue: null },
  end_date: { type: INTEGER, allowNull:true, defaultValue: null },
  is_time_tracking: { type: INTEGER, allowNull:false, defaultValue: 0 },
  amount: { type: FLOAT, defaultValue: null },
  hours: { type: FLOAT, defaultValue: null },
  description: { type: STRING, defaultValue: null },
  team:{ type: INTEGER, defaultValue: null},
  status: { type: TINYINT, defaultValue: 1 },
  added_by: { type: INTEGER, defaultValue: null },
  timestamp: { type: INTEGER, allowNull: false },
  cover: { type: TEXT, defaultValue: null },
  description: { type: STRING, defaultValue: null },
  is_auto_pay: { type: INTEGER, defaultValue: 0 },
},{timestamps:false})

const DesignOrderCount=sequelize.define('design_order_count',{
  id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  user_id: {type: Sequelize.INTEGER, allowNull: false},
  open_count: {type: Sequelize.INTEGER, allowNull: false, defaultValue: 0},
  approved_count: {type: Sequelize.INTEGER, allowNull: false ,defaultValue: 0},
  rejected_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
  hold_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
  new_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
  in_progress_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
  completed_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
  job_hold_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
  open_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  approved_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  rejected_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  hold_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  new_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  in_progress_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  completed_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  job_hold_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  status: { type: TINYINT, defaultValue: 1 },
  timestamp: { type: INTEGER, allowNull: true },
},{timestamps:false ,tableName: 'design_order_count'})

const EstimateTabCount=sequelize.define('estimate_tab_count',{
  id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  user_id: {type: Sequelize.INTEGER, allowNull: false},
  open_count: {type: Sequelize.INTEGER, allowNull: false, defaultValue: 0},
  approved_count: {type: Sequelize.INTEGER, allowNull: false ,defaultValue: 0},
  archive_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
  open_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  approved_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  archive_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  status: { type: Sequelize.TINYINT, defaultValue: 1 },
  timestamp: { type: Sequelize.INTEGER, allowNull: true },
},{timestamps:false ,tableName: 'estimate_tab_count'})

const SalesOrderTabCount=sequelize.define('sales_order_tab_count',{
  id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  user_id: {type: Sequelize.INTEGER, allowNull: false},
  open_count: {type: Sequelize.INTEGER, allowNull: false, defaultValue: 0},
  approved_count: {type: Sequelize.INTEGER, allowNull: false ,defaultValue: 0},
  in_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},
  invoicing_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
  completed_count: {type: Sequelize.INTEGER, allowNull: false,defaultValue: 0},
  open_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  approved_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  in_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},
  invoicing_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  completed_count_ids: {type: Sequelize.TEXT, allowNull: true,defaultValue: null},
  status: { type: Sequelize.TINYINT, defaultValue: 1 },
  timestamp: { type: Sequelize.INTEGER, allowNull: true },
},{timestamps:false ,tableName: 'sales_order_tab_count'})


const parseDecimalFields = (order) => {
  order.total = order.total ? parseFloat(order.total) : null;
  order.invoice_total = order.invoice_total ? parseFloat(order.invoice_total) : null;
  order.budget = order.budget ? parseFloat(order.budget) : null;
  order.sub_total = order.sub_total ? parseFloat(order.sub_total) : null;
  order.tax = order.tax ? parseFloat(order.tax) : null;
  order.extra_discount = order.extra_discount ? parseFloat(order.extra_discount) : null;
  order.cost = order.cost ? parseFloat(order.cost) : null;
  return order;
}

const addRequest = async (data) => {

  let res = await Requests.create(data)
  return res.id;
}
const addRequestPayment = async (data) => {

  let res = await RequestPayments.create(data)
  return res.id;
}
const addLocation = async (data) => {
  let res = await RequestLocation.create(data)
  return res.id;
}

const updateLocation = async (data, id) => {
  let res = await RequestLocation.update(data, {
    where: { id: id }
  })
  if (res) {
    return true
  } else {
    return false
  }
}

const updateLocationProducts = async (data, order_id) => {
  let res = await RequestLocation.update(data, {
    where: { order_id: order_id }
  })
  if (res) {
    return true
  } else {
    return false
  }
}

const updateLocationIsLinkedAll = async (productIds) => {
  try {
    // Handle comma-separated string or array
    let productIdArray = [];
    console.log('productIds', productIds)
    if (typeof productIds === 'string') {
      productIdArray = productIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
    } else if (Array.isArray(productIds)) {
      productIdArray = productIds.map(id => parseInt(id)).filter(id => !isNaN(id));
    }
    
    if (productIdArray.length === 0) {
      return false;
    }
    
    let res = await RequestLocation.update(
      { isLinkedAll: 1 },
      {
        where: {
          id: {
            [Sequelize.Op.in]: productIdArray
          }
        }
      }
    );
    
    return res ? true : false;
  } catch (error) {
    console.error("Error updating location isLinkedAll:", error);
    return false;
  }
}

const getRequestLocationsByRequestIdWhereIsLinkedAllZero = async (request_id) => {
  try {
    const query = `
      SELECT rl.id,rl.isLinkedAll,rl.product_id 
      FROM request_locations rl
      INNER JOIN customer_order_products cop ON rl.order_id = cop.id
      INNER JOIN customer_orders co ON cop.order_id = co.id
      LEFT JOIN products p ON cop.product_id = p.id
      WHERE co.request_id = :request_id 
        AND (rl.isLinkedAll = 0 OR rl.isLinkedAll IS NULL)
        AND cop.rfp = 0
        AND (p.meterial = 0 OR p.meterial IS NULL)
    `;
    
    const result = await sequelize.query(query, {
      replacements: { request_id },
      type: sequelize.QueryTypes.SELECT
    });
    
    return result || [];
  } catch (error) {
    console.error("Error fetching request locations where isLinkedAll = 0:", error);
    return [];
  }
}

const updateLocationIsLinkedAllByLocationId = async (locationId, requestId) => {
  try {
    // Check if location still has any linked attachments
    const linkedAttachments = await sequelize.query(
      `SELECT COUNT(*) as count 
       FROM request_attachments 
       WHERE request_id = :requestId 
       AND status = 1 
       AND approved = 1 
       AND location_ids IS NOT NULL 
       AND FIND_IN_SET(:locationId, location_ids) > 0`,
      {
        type: sequelize.QueryTypes.SELECT,
        replacements: { requestId, locationId: parseInt(locationId) }
      }
    );
    
    const hasLinkedAttachments = linkedAttachments[0]?.count > 0;
    
    // Update isLinkedAll: 1 if has linked attachments, 0 if not
    // Verify location belongs to the request by joining through customer_order_products and customer_orders
    const res = await sequelize.query(
      `UPDATE request_locations rl
       INNER JOIN customer_order_products cop ON rl.order_id = cop.id
       INNER JOIN customer_orders co ON cop.order_id = co.id
       SET rl.isLinkedAll = :isLinkedAll
       WHERE rl.id = :locationId AND co.request_id = :requestId`,
      {
        type: sequelize.QueryTypes.UPDATE,
        replacements: {
          isLinkedAll: hasLinkedAttachments ? 1 : 0,
          locationId: parseInt(locationId),
          requestId
        }
      }
    );
    
    return res ? true : false;
  } catch (error) {
    console.error("Error updating location isLinkedAll:", error);
    return false;
  }
}

const getLocationProductsById = async (order_id) => {
  try {
    let res = await RequestLocation.findOne({
      where: { order_id: order_id }
    });

    return res ? res.dataValues : null;
  } catch (error) {
    console.error("Error fetching product location:", error);
    return null;
  }
};

const getAllLocationProductsById = async (order_id) => {
  try {
    const res = await RequestLocation.findAll({
      where: { order_id }
    });
    return res.map(r => r.get({ plain: true }));
  } catch (error) {
    console.error("Error fetching product location:", error);
    return [];
  }
};

const getAllServiceByRequestId = async (request_id) => {
  try {
    const res = await RequestServices.findAll({
      where: { request_id }
    });
    return res.map(r => r.get({ plain: true }));
  } catch (error) {
    console.error("Error fetching service location:", error);
    return [];
  }
};

const getAllLocationServiceByRequestId = async (request_id) => {
  try {
    const res = await RequestServiceLocations.findAll({
      where: { request_id }
    });
    return res.map(r => r.get({ plain: true }));
  } catch (error) {
    console.error("Error fetching service location:", error);
    return [];
  }
};

const getLocationProductsByLocId = async (loc_id) => {
  try {
    let res = await RequestLocation.findOne({
      where: { id: loc_id }
    });

    return res ? res.dataValues : null;
  } catch (error) {
    console.error("Error fetching product location:", error);
    return null;
  }
};
const addServiceLocation = async (data) => {
  let res = await RequestServiceLocations.create(data)
  return res.id;
}

const updateServiceLocation = async (data, id) => {
  let res = await RequestServiceLocations.update(data, {
    where: { id: id }
  })
  if (res) {
    return true
  } else {
    return false
  }
}
const getRouteServiceLocationById = async (service_id) => {
  try {
    let res = await RequestServiceLocations.findOne({
      where: { service_id: service_id }
    });

    return res ? res.dataValues : null;

  } catch (error) {
    console.error("Error fetching product location:", error);
    return null;
  }
};

const updateRouteServiceLocation = async (data, service_id) => {
  let res = await RequestServiceLocations.update(data, {
    where: { service_id: service_id }
  })
  if (res) {
    return true
  } else {
    return false
  }
}

const deleteServiceLocation = async (id) => {
  let res = await RequestServiceLocations.destroy({
    where: { request_id: id }
  })
  if (res) {
    return true
  } else {
    return false
  }
}

const deleteServiceLocationByServiceId = async (serviceId) => {
  try {
    const result = await RequestServiceLocations.destroy({
      where: { service_id: serviceId }
    });
    return result > 0;
  } catch (error) {
    console.error('Error deleting service location by service_id:', error);
    return false;
  }
}

const updateRequestPayment = async (data, id) => {
  let result = await RequestPayments.update(data, {

    where: { id: id }
  })
  console.log("#######Result", result);
  if (result) {
    return result;
  } else {
    return false;
  }
}
const updateRequets = async (request_id, data) => {
  try{
    let result = await Requests.update(data, {
      where: { id: request_id }
    })
    if (result[0] > 0) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.log('Error : ', error);
    return false;
  }
}

const getAllRequests = async (requestId, userId, userType, page, rowPerpage, search, where = '', sort, fromDate, toDate, filterCommunity, dueData,clientFilter, filterProjectType, filterUser, filterProjectCategory) => {
  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 r.participation_ends BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
    } else if (fromTimestamp) {
      dateCondition = `AND r.participation_ends >= ${fromTimestamp}`;
    } else if (toTimestamp) {
      dateCondition = `AND r.participation_ends <= ${toTimestamp}`;
    }

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

    let offset = null
    if (rowPerpage && page) {
      offset = (page - 1) * rowPerpage;
    }
    let totalCount = 0
    let allCount=0
    let openCount=0
    let acceptedCount=0
    let inProductionCount=0
    let completedCount=0
    let installsCount=0
    let totalCompletedCount = 0
    let partnerWhere = '';
    let query = '';
    let countQuery = '';
    let content = ''

    if (search) {
      const escapedSearch = search.replace(/'/g, "''").trim();
      const normalizedSearch = escapedSearch.toLowerCase();
    
      content = `AND (
        LOWER(COALESCE(r.name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.description, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(pc.name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(c_ord.customer_name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.doc_number, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.est_doc_number, '')) LIKE '%${normalizedSearch}%'`
      
      // Include com.name only if userType is not 3 (com is joined only in that case)
      if (userType !== 3) {
        content += ` OR LOWER(COALESCE(com.name, '')) LIKE '%${normalizedSearch}%'`;
      }
    
      content += `)`;
    }   

    let WhereCondition = ''
    let CountwhereCondition = ''
    if (requestId) {
      WhereCondition = ` r.id=${requestId}`
      CountwhereCondition = ` r.id=${requestId}`
    }
    else {
      WhereCondition = ` r.status <>0  and r.status<>8 ${dateCondition}`
      CountwhereCondition = ` r.status <>0  and r.status<>8 ${dateCondition}`
      if (!empty(where)) {
        WhereCondition = ` r.status != 0  and r.status<>8 AND ${where} ${dateCondition}`
        CountwhereCondition = ` r.status != 0  and r.status<>8 ${dateCondition}`
      }
    }

    if (!WhereCondition.trim()) {
      WhereCondition = '1=1'; 
    }
    if (!CountwhereCondition.trim()) {
      CountwhereCondition = '1=1'; 
    }
    let community=''
    let communityConditionNew=''
    if (filterCommunity && filterCommunity.length > 0) {
      const communityCondition = ` AND r.community IN (${filterCommunity.join(',')}) `;
      communityConditionNew = ` WHERE r.community IN (${filterCommunity.join(',')}) `;
      WhereCondition += ` ${communityCondition}`;
      CountwhereCondition += ` ${communityCondition}`;
      community += ` ${communityCondition}`;
    }
    let clientCondition = '';
    let clientConditionNew = '';
    if (clientFilter && clientFilter.length > 0) {
      const clientFilterCondition = ` AND c_ord.customer_id IN (${clientFilter.join(',')}) `;
      clientConditionNew = ` WHERE c_ord.customer_id IN (${clientFilter.join(',')}) `;
      WhereCondition += ` ${clientFilterCondition}`;
      CountwhereCondition += ` ${clientFilterCondition}`;
      clientCondition += ` ${clientFilterCondition}`;
    }

    let userCondition = '';
    let userConditionNew = '';
    if (filterUser && filterUser.length > 0) {
      const projectMemberExists = `EXISTS (SELECT 1 FROM projects p JOIN project_members pm ON pm.project_id = p.id WHERE p.request_id = r.id AND p.is_estimate_job=0 AND pm.staff_id IN (${filterUser.join(',')}))`;
      const collaboratorChecks = filterUser.map((id) => `FIND_IN_SET(${parseInt(id, 10)}, REPLACE(TRIM(COALESCE(r.collaborators,'')), ' ', '')) > 0`).join(' OR ');
      const userFilterCondition = ` AND ( ${projectMemberExists} OR (TRIM(COALESCE(r.collaborators,'')) != '' AND (${collaboratorChecks})) ) `;
      userConditionNew = ` WHERE ( ${projectMemberExists} OR (TRIM(COALESCE(r.collaborators,'')) != '' AND (${collaboratorChecks})) ) `;
      WhereCondition += ` ${userFilterCondition}`;
      CountwhereCondition += ` ${userFilterCondition}`;
      userCondition += ` ${userFilterCondition}`;
    }

    if (filterProjectType === 1) {
      WhereCondition += ` AND r.project_type = 1`;
    } else if (filterProjectType === 2) {
      WhereCondition += ` AND r.project_type = 2`;
    }else if (filterProjectType === 3) {
      WhereCondition += ` AND r.is_split_order = 1`;
    }else if (filterProjectType === 'NULL'){
      WhereCondition += ` AND r.project_type IS NULL`;
    } else {
      WhereCondition += ` AND (r.project_type IS NULL OR r.project_type IS NOT NULL)`;
    }

    if(filterProjectCategory == 1){
      WhereCondition += ` AND r.project_category = 15`;
    }else if(filterProjectCategory == 2){
      WhereCondition += ` AND r.project_category = 9`;
    }

    let limit = ''
    if (rowPerpage) {
      limit = `LIMIT ${rowPerpage} OFFSET ${offset}`
    }

    if (userType != 3) {
      
      query = await sequelize.query("SELECT `r`.*,  est_prj.status AS estimate_job_status, proj.noServiceNoTask AS proj_noServiceNoTask,proj.status AS proj_status,proj.id AS isProject,rp.id as rt_partner_id ,c_ord.total as invoice_total,CONCAT(u.first_name, ' ', u.last_name) as added_by_name, u.user_type as added_by_user_type, c_ord.grandTotal as invoice_grand_total,u2.profile_pic AS customer_pic,com.name AS community_name, com.phone AS community_phone, COALESCE((SELECT GROUP_CONCAT(pd.po_number ORDER BY pd.id SEPARATOR ', ') FROM po_details pd WHERE pd.community_id = com.id AND pd.status = 1), '') AS community_po_number,com.address AS community_address, com.city AS community_city, com.state AS community_state, com.zip AS community_zipcode, COALESCE((SELECT GROUP_CONCAT(DISTINCT CONCAT(sm.first_name,' ',COALESCE(sm.last_name,'')) ORDER BY sm.id SEPARATOR ' ') FROM staff_members sm WHERE r.sales_rep_ids IS NOT NULL AND r.sales_rep_ids != '' AND FIND_IN_SET(sm.id, r.sales_rep_ids) > 0), '') AS sales_rep_names, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count,i.status as installationStatus,i.complete_status AS installationCompleteStatus, COALESCE(i.pending_review, 0) AS installation_pending_review,c_ord.customer_name,c_ord.customer_id,ct.billing_type, "
        + ` CASE WHEN ur.isClientUserRole = 1 THEN 1 ELSE 0 END as isAddedByClient, `
        + ` 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,`
        + ` CASE 
                WHEN r.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 r.project_category = 11 THEN 
                CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                WHEN r.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 proj.status = 3 AND proj.noServiceNoTask = 0
            )
            THEN 1
            ELSE 0
          END AS allInstallationCompleted,`
          + `CASE 
            WHEN 
            (
              (COALESCE(inst_non_edit.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
            )
            THEN 1
            ELSE 0
          END AS enableEditOnStaged,`
        + ` COALESCE(reqPay.totalAmount, 0) AS totalPaidAmount,`
        + ` (COALESCE(c_ord.total, 0) - COALESCE(reqPay.totalAmount, 0)) AS dueAmount,`
        + ` inst_counts.installation_count, inst_non_edit.installation_count AS staged_installation_count, total_inst_counts.total_installation_count, cop.product_count, rss.service_count, `
        + ` CASE WHEN COALESCE(partial_inst.partial_installation_count, 0) > 0 THEN 1 ELSE 0 END AS partial_install, `
        + ` COALESCE(mixed_inst.mixed_installation, 0) AS mixed_installation, `
        + " pc.name AS job_category_name FROM `requests` `r` "
        + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
        + " LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c "
        + " left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id LIMIT 1),0) and c.user_id!=1 group by c.request_id) rm ON `r`.`id`=`rm`.`request_id` "
        + " LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM `request_proposals` where status=1 group by request_id) rps ON `rps`.`request_id`=`r`.`id` "
        // + ` LEFT JOIN community com ON com.id = r.community`
        + ` left join customer_orders c_ord on c_ord.request_id = r.id `
        + ` left join projects proj on proj.request_id = r.id AND proj.is_estimate_job = 0`
        + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
        + ` LEFT JOIN request_partners rp ON rp.request_id=r.id`
        + ` left join partners p2 on p2.id = c_ord.customer_id `
        + ` left join projects est_prj on est_prj.request_id = r.id AND est_prj.is_estimate_job = 1 AND r.quotation = 1`
        + ` left join customer_type ct on p2.customerTypeId = ct.id `
        + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
        + ` left join users u2 on u2.id = p2.user_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 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, 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 installation_count FROM installations WHERE status = 1 GROUP BY request_id) inst_non_edit ON inst_non_edit.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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id) partial_inst ON partial_inst.request_id = r.id `
        + ` LEFT JOIN (SELECT request_id, CASE WHEN COUNT(DISTINCT COALESCE(complete_status, -1)) > 1 THEN 1 ELSE 0 END AS mixed_installation FROM installations GROUP BY request_id) mixed_inst ON mixed_inst.request_id = r.id `
        + ` LEFT JOIN users u ON r.added_by=u.id `
        + ` LEFT JOIN user_roles ur ON ur.id = u.user_type `
        + ` WHERE ${WhereCondition} ${content} ${createdAt} ${limit}`)

      totalCount = await sequelize.query(`SELECT COUNT(r.id) as totalCount FROM requests r `
        + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
        + " LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c "
        + " left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id LIMIT 1),0) and c.user_id!=1 group by c.request_id) rm ON `r`.`id`=`rm`.`request_id` "
        + " LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM `request_proposals` where status=1 group by request_id) rps ON `rps`.`request_id`=`r`.`id` "
        + ` left join customer_orders c_ord on c_ord.request_id = r.id `
        + ` left join projects proj on proj.request_id = r.id AND proj.is_estimate_job = 0`
        + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
        + ` LEFT JOIN request_partners rp ON rp.request_id=r.id`
        + ` left join partners p2 on p2.id = c_ord.customer_id `
        + ` left join customer_type ct on p2.customerTypeId = ct.id `
        + ` left join projects est_prj on est_prj.request_id = r.id AND est_prj.is_estimate_job = 1 AND r.quotation = 1`
        + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
        + ` left join users u2 on u2.id = p2.user_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 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, 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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id) partial_inst ON partial_inst.request_id = r.id `
        + ` LEFT JOIN users u ON r.added_by=u.id WHERE ${WhereCondition} ${content}`);
    }
    if (userType == 3) {
      query = await sequelize.query(`SELECT rp.id as rt_partner_id,  est_prj.status AS estimate_job_status, proj.noServiceNoTask AS proj_noServiceNoTask,proj.status AS proj_status,proj.id AS isProject, u2.profile_pic AS customer_pic, com.name AS community_name, COALESCE((SELECT GROUP_CONCAT(DISTINCT CONCAT(sm.first_name,' ',COALESCE(sm.last_name,'')) ORDER BY sm.id SEPARATOR ' ') FROM staff_members sm WHERE r.sales_rep_ids IS NOT NULL AND r.sales_rep_ids != '' AND FIND_IN_SET(sm.id, r.sales_rep_ids) > 0), '') AS sales_rep_names, rp.accept_status, i.status as installationStatus,CONCAT(u.first_name, ' ', u.last_name) as added_by_name, u.user_type as added_by_user_type, i.complete_status AS installationCompleteStatus, COALESCE(i.pending_review, 0) AS installation_pending_review, p.user_id as partner_user_id, trps.proposal_added_by, trps.proposal_status, r.*, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count, CONCAT(u.first_name, " ", u.last_name) as send_to, u.id as sender_id, u.profile_pic as pic, c_ord.customer_name,c_ord.customer_id, ct.billing_type,
        CASE WHEN ur.isClientUserRole = 1 THEN 1 ELSE 0 END as isAddedByClient, 
        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, 
        CASE 
          WHEN r.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 r.project_category = 11 THEN 
          CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
          WHEN r.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 proj.status = 3 AND proj.noServiceNoTask = 0
            )
            THEN 1
            ELSE 0
          END AS allInstallationCompleted,
          CASE 
            WHEN 
              (
                (COALESCE(inst_non_edit.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
              )
              THEN 1
              ELSE 0
          END AS enableEditOnStaged,
        COALESCE(reqPay.totalAmount, 0) AS totalPaidAmount, 
        (COALESCE(c_ord.total, 0) - COALESCE(reqPay.totalAmount, 0)) AS dueAmount, 
        inst_counts.installation_count,inst_non_edit.installation_count AS staged_installation_count, total_inst_counts.total_installation_count, cop.product_count, rss.service_count, 
        CASE WHEN COALESCE(partial_inst.partial_installation_count, 0) > 0 THEN 1 ELSE 0 END AS partial_install,
        COALESCE(mixed_inst.mixed_installation, 0) AS mixed_installation,
        pc.name AS job_category_name
        FROM requests r 
      LEFT JOIN project_categories pc ON pc.id = r.project_category 
      LEFT JOIN (SELECT COUNT(c.id) AS cnt, c.request_id FROM request_messages c 
          LEFT JOIN partners p ON p.id = c.partner_id WHERE c.timestamp >= COALESCE((SELECT rml.timestamp FROM request_message_last_seen rml WHERE rml.request_id = c.request_id AND rml.user_id = ${userId} AND rml.partner_id = c.partner_id LIMIT 1), 0) AND c.user_id != ${userId} AND p.user_id = ${userId} GROUP BY c.request_id) rm ON r.id = rm.request_id 
      LEFT JOIN (SELECT COUNT(id) AS cnt, request_id FROM request_proposals WHERE status = 1 GROUP BY request_id) rps ON rps.request_id = r.id 
      LEFT JOIN users u ON r.added_by = u.id
      LEFT JOIN user_roles ur ON ur.id = u.user_type
      LEFT JOIN request_partners rp ON rp.request_id = r.id 
      JOIN partners p ON p.id = rp.partner_id 
      LEFT JOIN customer_orders c_ord ON c_ord.request_id = r.id 
      left join projects proj on proj.request_id = r.id AND proj.is_estimate_job = 0
      LEFT JOIN partners p2 ON p2.id = c_ord.customer_id 
      LEFT JOIN customer_type ct ON p2.customerTypeId = ct.id 
      LEFT JOIN users u2 ON u2.id = p2.user_id 
      left join projects est_prj on est_prj.request_id = r.id AND est_prj.is_estimate_job = 1 AND r.quotation = 1
      LEFT JOIN community com ON com.id = r.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1 
      LEFT JOIN (SELECT request_id AS rid, added_by AS proposal_added_by, COALESCE(status, 'NA') AS proposal_status FROM request_proposals WHERE added_by = ${userId}) trps ON trps.rid = r.id 
    
      LEFT JOIN (SELECT MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review, request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id
    
      LEFT JOIN (SELECT SUM(amount) AS totalAmount, request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay ON reqPay.request_id = r.id 
      LEFT JOIN (
        SELECT request_id, COUNT(*) AS installation_count 
        FROM installations 
        WHERE status = 1 
        GROUP BY request_id
      ) inst_non_edit ON inst_non_edit.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, 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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id) partial_inst ON partial_inst.request_id = r.id
      LEFT JOIN (SELECT request_id, CASE WHEN COUNT(DISTINCT COALESCE(complete_status, -1)) > 1 THEN 1 ELSE 0 END AS mixed_installation FROM installations GROUP BY request_id) mixed_inst ON mixed_inst.request_id = r.id
      WHERE p.user_id = ${userId} AND ${WhereCondition} AND r.status != 1 ${content} ${createdAt} ${limit}`);
    
          totalCount = await sequelize.query(`select count(r.id) as totalCount from requests r
            LEFT JOIN project_categories pc ON pc.id = r.project_category 
            LEFT JOIN (SELECT COUNT(c.id) AS cnt, c.request_id FROM request_messages c 
            LEFT JOIN partners p ON p.id = c.partner_id WHERE c.timestamp >= COALESCE((SELECT rml.timestamp FROM request_message_last_seen rml WHERE rml.request_id = c.request_id AND rml.user_id = ${userId} AND rml.partner_id = c.partner_id LIMIT 1), 0) AND c.user_id != ${userId} AND p.user_id = ${userId} GROUP BY c.request_id) rm ON r.id = rm.request_id 
            LEFT JOIN (SELECT COUNT(id) AS cnt, request_id FROM request_proposals WHERE status = 1 GROUP BY request_id) rps ON rps.request_id = r.id 
            LEFT JOIN users u ON r.added_by = u.id 
            LEFT JOIN request_partners rp ON rp.request_id = r.id 
            JOIN partners p ON p.id = rp.partner_id 
            LEFT JOIN customer_orders c_ord ON c_ord.request_id = r.id 
            left join projects proj on proj.request_id = r.id AND proj.is_estimate_job = 0
            LEFT JOIN partners p2 ON p2.id = c_ord.customer_id 
            LEFT JOIN customer_type ct ON p2.customerTypeId = ct.id 
            LEFT JOIN users u2 ON u2.id = p2.user_id 
            LEFT JOIN community com ON com.id = r.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1 
            LEFT JOIN (SELECT request_id AS rid, added_by AS proposal_added_by, COALESCE(status, 'NA') AS proposal_status FROM request_proposals WHERE added_by = ${userId}) trps ON trps.rid = r.id 
          
            LEFT JOIN (SELECT MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review, request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id
          
            LEFT JOIN (SELECT SUM(amount) AS totalAmount, request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay ON reqPay.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, 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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id
            ) partial_inst ON partial_inst.request_id = r.id 
            left join projects est_prj on est_prj.request_id = r.id AND est_prj.is_estimate_job = 1 AND r.quotation = 1
            WHERE p.user_id = ${userId} AND ${WhereCondition} AND r.status != 1 ${content} `
          )
    }
    let result = query[0]
    // const counts = countQuery[0][0];

    if (result.length >= 1) {
      
      const allRequestIds = result.map((row) => row.id);
      // Fetch all designs and partners in bulk
      const allDesigns = await FetchAllApprovedDesignsBulk(allRequestIds); // Assume this function handles bulk fetching
      const allPartners = await getRequestPartnersBulk(false,allRequestIds); // Assume this function handles bulk fetching

      // Create a map for fast lookup
      const designsMap = {};
      allDesigns.forEach((design) => {
        if (!designsMap[design.request_id]) designsMap[design.request_id] = [];
        designsMap[design.request_id].push(design);
      });

      const partnersMap = {};
      allPartners.forEach((partner) => {
        if (!partnersMap[partner.request_id]) partnersMap[partner.request_id] = [];
        partnersMap[partner.request_id].push(partner);
      });

      // Process each row with mapped data
      const newData = result.map((row) => {
        // Fetch designs for the row
        const designs = designsMap[row.id] || [];
        const filteredDesigns = designs.filter(
          (imageItem) => imageItem?.file_type?.startsWith("image/") || imageItem?.file_type === "img"
        );
        row.thumbnail = filteredDesigns[0]?.name || "";

        // Fetch partners for the row
        row.partners = partnersMap[row.id] || [];

        return parseDecimalFields(row); // Assume this is a utility function
      });

      return {
        data: newData,
        totalCount: totalCount[0][0].totalCount,
        // totalCount: counts.totalCount,
        allCount: 0, // counts.allCount,
        openCount: 0, // counts.openCount,
        acceptedCount: 0, // counts.acceptedCount,
        inProductionCount: 0, // counts.inProductionCount,
        completedCount: 0, // counts.completedCount,
        installsCount: 0, // counts.installsCount,
        pickupCount: 0, // counts.pickupCount,
        shippingCount: 0, // counts.shippingCount
       };
    }
    else {
      return { data:[], 
        totalCount: totalCount[0][0].totalCount,
        // totalCount: counts.totalCount,
        allCount: 0, // counts.allCount,
        openCount: 0, // counts.openCount,
        acceptedCount: 0, // counts.acceptedCount,
        inProductionCount: 0, // counts.inProductionCount,
        completedCount: 0, // counts.completedCount,
        installsCount: 0, // counts.installsCount,
        pickupCount: 0, // counts.pickupCount,
        shippingCount: 0, // counts.shippingCount
       };
    }
  } catch (error) {
    console.error(error);
    return error;
  }
};
const getAllRequestsForUser = async ({
  requestId,
  userId,
  userType
}) => {
  try {
    // Initialize conditions for requestId, userId, and userType
    let WhereCondition = '';
    let CountwhereCondition = '';
    
    // If a specific requestId is provided, set the condition for it
    if (requestId) {
      WhereCondition = `r.id = ${requestId}`;
      CountwhereCondition = `r.id = ${requestId}`;
    } else {
      // Otherwise, exclude requests that are closed (status 0) and cancelled (status 8)
      WhereCondition = `r.status <> 0 AND r.status <> 8`;
      CountwhereCondition = `r.status <> 0 AND r.status <> 8`;
    }

    // If userType is not 3, we include more information in the query
    let communityCondition = '';
    let clientCondition = '';
    let userCondition = '';

    if (userType !== 3) {
      // Include condition to join community, client, and user-related information
      communityCondition = 'LEFT JOIN community com ON com.id = r.community';
      clientCondition = 'LEFT JOIN customer_orders c_ord ON c_ord.request_id = r.id';
      userCondition = 'LEFT JOIN users u ON r.added_by = u.id';
    }

    // Build the query
    const query = await sequelize.query(`
      SELECT r.*, 
        CONCAT(u.first_name, ' ', u.last_name) as added_by_name, 
        u.user_type as added_by_user_type,
        c_ord.total as invoice_total,
        com.name AS community_name,
        com.phone AS community_phone,
        c_ord.customer_name, 
        c_ord.customer_id 
      FROM requests r
      ${communityCondition}
      ${clientCondition}
      ${userCondition}
      WHERE ${WhereCondition}
      ORDER BY r.timestamp DESC
    `);

    // Count the total number of records matching the conditions
    const totalCountQuery = await sequelize.query(`
      SELECT COUNT(r.id) AS totalCount 
      FROM requests r
      ${communityCondition}
      ${clientCondition}
      ${userCondition}
      WHERE ${CountwhereCondition}
    `);

    // Return the results with the total count
    return {
      data: query[0],
      totalCount: totalCountQuery[0][0].totalCount
    };
  } catch (error) {
    console.error('Error in getAllRequestsForUser:', error);
    return { data: [], totalCount: 0 };
  }
};




// New function to return total counts using the exact previously commented SQL (no changes)
const getAllRequestsTotalCount = async (requestId, userId, userType, page, rowPerpage, search, where = '', sort, fromDate, toDate, filterCommunity, dueData, clientFilter, filterProjectType, filterUser, filterProjectCategory) => {
  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 r.participation_ends BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
    } else if (fromTimestamp) {
      dateCondition = `AND r.participation_ends >= ${fromTimestamp}`;
    } else if (toTimestamp) {
      dateCondition = `AND r.participation_ends <= ${toTimestamp}`;
    }

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

    let offset = null
    if (rowPerpage && page) {
      offset = (page - 1) * rowPerpage;
    }
    let totalCount = 0
    let content = ''

    if (search) {
      const escapedSearch = search.replace(/'/g, "''").trim();
      const normalizedSearch = escapedSearch.toLowerCase();

      content = `AND (
        LOWER(COALESCE(r.name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.description, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(pc.name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(c_ord.customer_name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.doc_number, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.est_doc_number, '')) LIKE '%${normalizedSearch}%'`

      if (userType !== 3) {
        content += ` OR LOWER(COALESCE(com.name, '')) LIKE '%${normalizedSearch}%'`;
      }

      content += `)`;
    }

    let WhereCondition = ''
    if (requestId) {
      WhereCondition = ` r.id=${requestId}`
    } else {
      WhereCondition = ` r.status <>0  and r.status<>8 ${dateCondition}`
      if (!empty(where)) {
        WhereCondition = ` r.status != 0  and r.status<>8 AND ${where} ${dateCondition}`
      }
    }

    if (!WhereCondition.trim()) {
      WhereCondition = '1=1';
    }

    let community = ''
    if (filterCommunity && filterCommunity.length > 0) {
      const communityCondition = ` AND r.community IN (${filterCommunity.join(',')}) `;
      WhereCondition += ` ${communityCondition}`;
      community += ` ${communityCondition}`;
    }

    if (clientFilter && clientFilter.length > 0) {
      const clientFilterCondition = ` AND c_ord.customer_id IN (${clientFilter.join(',')}) `;
      WhereCondition += ` ${clientFilterCondition}`;
    }

    if (filterUser && filterUser.length > 0) {
      const projectMemberExists = `EXISTS (SELECT 1 FROM projects p JOIN project_members pm ON pm.project_id = p.id WHERE p.request_id = r.id AND p.is_estimate_job=0 AND pm.staff_id IN (${filterUser.join(',')}))`;
      const collaboratorChecks = filterUser.map((id) => `FIND_IN_SET(${parseInt(id, 10)}, REPLACE(TRIM(COALESCE(r.collaborators,'')), ' ', '')) > 0`).join(' OR ');
      const userFilterCondition = ` AND ( ${projectMemberExists} OR (TRIM(COALESCE(r.collaborators,'')) != '' AND (${collaboratorChecks})) ) `;
      WhereCondition += ` ${userFilterCondition}`;
    }

    if (filterProjectType === 1) {
      WhereCondition += ` AND r.project_type = 1`;
    } else if (filterProjectType === 2) {
      WhereCondition += ` AND r.project_type = 2`;
    }else if (filterProjectType === 3) {
      WhereCondition += ` AND r.is_split_order = 1`;
    } else if (filterProjectType === 'NULL'){
      WhereCondition += ` AND r.project_type IS NULL`;
    } else {
      WhereCondition += ` AND (r.project_type IS NULL OR r.project_type IS NOT NULL)`;
    }

    if(filterProjectCategory == 1){
      WhereCondition += ` AND r.project_category = 15`;
    }else if(filterProjectCategory == 2){
      WhereCondition += ` AND r.project_category = 9`;
    }

    if (userType != 3) {
      // exact commented SQL for totalCount (no modifications)
      totalCount = await sequelize.query(`SELECT COUNT(r.id) as totalCount FROM requests r `
        + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
        + " LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c "
        + " left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id LIMIT 1),0) and c.user_id!=1 group by c.request_id) rm ON `r`.`id`=`rm`.`request_id` "
        + " LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM `request_proposals` where status=1 group by request_id) rps ON `rps`.`request_id`=`r`.`id` "
        + ` left join customer_orders c_ord on c_ord.request_id = r.id `
        + ` left join projects proj on proj.request_id = r.id  AND proj.is_estimate_job = 0`
        + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
        + ` LEFT JOIN request_partners rp ON rp.request_id=r.id`
        + ` left join partners p2 on p2.id = c_ord.customer_id `
        + ` left join customer_type ct on p2.customerTypeId = ct.id `
        + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
        + ` left join users u2 on u2.id = p2.user_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 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, 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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id) partial_inst ON partial_inst.request_id = r.id `
        + ` LEFT JOIN users u ON r.added_by=u.id WHERE ${WhereCondition} ${content}`);
    }
    if (userType == 3) {
      // exact commented SQL for totalCount (no modifications)
      totalCount = await sequelize.query(
        'select count(r.id) as totalCount from requests r' +
        '   LEFT JOIN project_categories pc ON pc.id = r.project_category ' +
        '   LEFT JOIN (SELECT COUNT(c.id) AS cnt, c.request_id FROM request_messages c ' +
        '   LEFT JOIN partners p ON p.id = c.partner_id WHERE c.timestamp >= COALESCE((SELECT rml.timestamp FROM request_message_last_seen rml WHERE rml.request_id = c.request_id AND rml.user_id = ' + userId + ' AND rml.partner_id = c.partner_id LIMIT 1), 0) AND c.user_id != ' + userId + ' AND p.user_id = ' + userId + ' GROUP BY c.request_id) rm ON r.id = rm.request_id ' +
        '   LEFT JOIN (SELECT COUNT(id) AS cnt, request_id FROM request_proposals WHERE status = 1 GROUP BY request_id) rps ON rps.request_id = r.id ' +
        '   LEFT JOIN users u ON r.added_by = u.id ' +
        '   LEFT JOIN request_partners rp ON rp.request_id = r.id ' +
        '   JOIN partners p ON p.id = rp.partner_id ' +
        '   LEFT JOIN customer_orders c_ord ON c_ord.request_id = r.id ' +
        '   left join projects proj on proj.request_id = r.id AND proj.is_estimate_job = 0' +
        '   LEFT JOIN partners p2 ON p2.id = c_ord.customer_id ' +
        '   LEFT JOIN customer_type ct ON p2.customerTypeId = ct.id ' +
        '   LEFT JOIN users u2 ON u2.id = p2.user_id ' +
        '   LEFT JOIN community com ON com.id = r.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1 ' +
        '   LEFT JOIN (SELECT request_id AS rid, added_by AS proposal_added_by, COALESCE(status, \"NA\") AS proposal_status FROM request_proposals WHERE added_by = ' + userId + ') trps ON trps.rid = r.id ' +
        '   LEFT JOIN (SELECT MAX(status) AS status, MAX(complete_status) AS complete_status, MAX(COALESCE(pending_review, 0)) AS pending_review, request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id' +
        '   LEFT JOIN (SELECT SUM(amount) AS totalAmount, request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay ON reqPay.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, 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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id) partial_inst ON partial_inst.request_id = r.id ' +
        '   WHERE p.user_id = ' + userId + ' AND ' + WhereCondition + ' AND r.status != 1 ' + content
      );
    }

    const countValue = Array.isArray(totalCount) && totalCount[0] && totalCount[0][0] ? (totalCount[0][0].totalCount || 0) : 0;
    return { totalCount: countValue };
  } catch (error) {
    console.error(error);
    return error;
  }
}

// const getAllRequests = async (requestId, userId, userType, page, rowPerpage, search, where = '', sort, fromDate, toDate, filterCommunity, dueData) => {
//   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 r.participation_ends BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
//     } else if (fromTimestamp) {
//       dateCondition = `AND r.participation_ends >= ${fromTimestamp}`;
//     } else if (toTimestamp) {
//       dateCondition = `AND r.participation_ends <= ${toTimestamp}`;
//     }

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

//     let offset = null
//     if (rowPerpage && page) {
//       offset = (page - 1) * rowPerpage;
//     }
//     let totalCount = 0
//     let allCount=0
//     let openCount=0
//     let acceptedCount=0
//     let inProductionCount=0
//     let completedCount=0
//     let installsCount=0
//     let totalCompletedCount = 0
//     let partnerWhere = '';
//     let query = '';
//     let content = ''
//     if (search) {
//       content = `and r.name LIKE '%${search}%'`
//     }
//     let WhereCondition = ''
//     if (requestId) {
//       WhereCondition = ` r.id=${requestId}`
//     }
//     else {
//       WhereCondition = ` r.status <>0  and r.status<>8 ${dateCondition}`
//       if (!empty(where)) {
//         WhereCondition = ` r.status != 0 AND ${where} ${dateCondition}`
//       }
//     }

//     if (!WhereCondition.trim()) {
//       WhereCondition = '1=1'; 
//     }
//     let community=''
//     if (filterCommunity && filterCommunity.length > 0) {
//       const communityCondition = ` AND r.community IN (${filterCommunity.join(',')}) `;
//       WhereCondition += ` ${communityCondition}`;
//       community += ` ${communityCondition}`;
//     }
//     let limit = ''
//     if (rowPerpage) {
//       limit = `LIMIT ${rowPerpage} OFFSET ${offset}`
//     }

//     if (userType != 3) {
//       query = await sequelize.query("SELECT `r`.*,rp.id as rt_partner_id ,c_ord.total as invoice_total, c_ord.grandTotal as invoice_grand_total,u2.profile_pic AS customer_pic,com.name AS community_name, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count,i.status as installationStatus,i.complete_status AS installationCompleteStatus,c_ord.customer_name,ct.billing_type, "
//         + ` CASE `
//         + ` WHEN inst_counts.installation_count >= cop.product_count OR inst_counts.installation_count >= rss.service_count `
//         + ` THEN 1 `
//         + ` ELSE 0 `
//         + ` END AS allInstallationCompleted,`
//         + ` COALESCE(reqPay.totalAmount, 0) AS totalPaidAmount,`
//         + ` (COALESCE(c_ord.total, 0) - COALESCE(reqPay.totalAmount, 0)) AS dueAmount,`
//         + ` inst_counts.installation_count, cop.product_count, rss.service_count, `
//         + " pc.name AS job_category_name FROM `requests` `r` "
//         + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
//         + " LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c "
//         + " left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id),0) and c.user_id!=1 group by c.request_id) rm ON `r`.`id`=`rm`.`request_id` "
//         + " LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM `request_proposals` where status=1 group by request_id) rps ON `rps`.`request_id`=`r`.`id` "
//         // + ` LEFT JOIN community com ON com.id = r.community`
//         + ` left join customer_orders c_ord on c_ord.request_id = r.id `
//         + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//         + ` JOIN request_partners rp ON rp.request_id=r.id`
//         + ` left join partners p2 on p2.id = c_ord.customer_id `
//         + ` left join customer_type ct on p2.customerTypeId = ct.id `
//         + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
//         + ` left join users u2 on u2.id = p2.user_id `
//         + ` 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 = r.id `
//         + ` 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 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  request_services rss ON co.request_id = rss.request_id
//               WHERE rss.labour_cost_service_id != 10
//               GROUP BY co.request_id
//             ) rss ON r.id = rss.request_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 `
//         + ` JOIN users u ON r.added_by=u.id WHERE ${WhereCondition} ${content} ${createdAt} ${limit}`)

//       totalCount = await sequelize.query(`
//         SELECT COUNT(r.id) as totalCount FROM requests r
//         LEFT JOIN project_categories pc ON pc.id = r.project_category 
//         LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c 
//         left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id),0) and c.user_id!=1 group by c.request_id) rm ON r.id=rm.request_id
//         LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals where status=1 group by request_id) rps ON rps.request_id=r.id 
//         left join customer_orders c_ord on c_ord.request_id = r.id 
//         LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1
//         JOIN request_partners rp ON rp.request_id=r.id
//         left join partners p2 on p2.id = c_ord.customer_id 
//         left join customer_type ct on p2.customerTypeId = ct.id 
//         left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id 
//         left join users u2 on u2.id = p2.user_id 
//         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 = r.id 
//         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 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  request_services rss ON co.request_id = rss.request_id
//           GROUP BY co.request_id
//         ) rss ON r.id = rss.request_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 
//         JOIN users u ON r.added_by=u.id 
//         WHERE ${WhereCondition} ${content}  `);
        
//         allCount = await sequelize.query(`
//           SELECT COUNT(r.id) AS allCount FROM requests r
//           LEFT JOIN project_categories pc ON pc.id = r.project_category 
//           LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c 
//           left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id),0) and c.user_id!=1 group by c.request_id) rm ON r.id=rm.request_id
//           LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals where status=1 group by request_id) rps ON rps.request_id=r.id 
//           left join customer_orders c_ord on c_ord.request_id = r.id 
//           LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1
//           JOIN request_partners rp ON rp.request_id=r.id
//           left join partners p2 on p2.id = c_ord.customer_id 
//           left join customer_type ct on p2.customerTypeId = ct.id 
//           left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id 
//           left join users u2 on u2.id = p2.user_id 
//           LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY 
//           request_id) i ON i.request_id = r.id 
//           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 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  request_services rss ON co.request_id = rss.request_id
//             GROUP BY co.request_id
//           ) rss ON r.id = rss.request_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 
//           JOIN users u ON r.added_by=u.id 
//           WHERE r.status <>0  and r.status<>8 ${community}
//         `);
        
//         openCount = await sequelize.query(`
//           select count(r.id) as openCount
//           FROM requests r
//           LEFT JOIN project_categories pc ON pc.id = r.project_category 
//           LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c 
//           left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id),0) and c.user_id!=1 group by c.request_id) rm ON r.id=rm.request_id
//           LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals where status=1 group by request_id) rps ON rps.request_id=r.id 
//           left join customer_orders c_ord on c_ord.request_id = r.id 
//           LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1
//           JOIN request_partners rp ON rp.request_id=r.id
//           left join partners p2 on p2.id = c_ord.customer_id 
//           left join customer_type ct on p2.customerTypeId = ct.id 
//           left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id 
//           left join users u2 on u2.id = p2.user_id 
//           LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY 
//           request_id) i ON i.request_id = r.id 
//           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 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  request_services rss ON co.request_id = rss.request_id
//             GROUP BY co.request_id
//           ) rss ON r.id = rss.request_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 
//           JOIN users u ON r.added_by=u.id 
//           where  r.status != 0 AND ((r.status=2) OR (r.status=3 AND r.min_payment_status=0)) 
//           ${community}`)

//         acceptedCount = await sequelize.query(`
//           select count(r.id) as acceptedCount
//           FROM requests r
//           LEFT JOIN project_categories pc ON pc.id = r.project_category 
//           LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c 
//           left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id),0) and c.user_id!=1 group by c.request_id) rm ON r.id=rm.request_id
//           LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals where status=1 group by request_id) rps ON rps.request_id=r.id 
//           left join customer_orders c_ord on c_ord.request_id = r.id 
//           LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1
//           JOIN request_partners rp ON rp.request_id=r.id
//           left join partners p2 on p2.id = c_ord.customer_id 
//           left join customer_type ct on p2.customerTypeId = ct.id 
//           left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id 
//           left join users u2 on u2.id = p2.user_id 
//           LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY 
//           request_id) i ON i.request_id = r.id 
//           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 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  request_services rss ON co.request_id = rss.request_id
//             GROUP BY co.request_id
//           ) rss ON r.id = rss.request_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 
//           JOIN users u ON r.added_by=u.id 
//           where r.status != 0 AND (r.status=3 AND r.min_payment_status =1)
//           ${community}`)

//          inProductionCount = await sequelize.query(`
//          select count(r.id) as inProductionCount
//           FROM requests r
//           LEFT JOIN project_categories pc ON pc.id = r.project_category 
//           LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c 
//           left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id),0) and c.user_id!=1 group by c.request_id) rm ON r.id=rm.request_id
//           LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals where status=1 group by request_id) rps ON rps.request_id=r.id 
//           left join customer_orders c_ord on c_ord.request_id = r.id 
//           LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1
//           JOIN request_partners rp ON rp.request_id=r.id
//           left join partners p2 on p2.id = c_ord.customer_id 
//           left join customer_type ct on p2.customerTypeId = ct.id 
//           left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id 
//           left join users u2 on u2.id = p2.user_id 
//           LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY 
//           request_id) i ON i.request_id = r.id 
//           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 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  request_services rss ON co.request_id = rss.request_id
//             GROUP BY co.request_id
//           ) rss ON r.id = rss.request_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 
//           JOIN users u ON r.added_by=u.id 
//           where  r.status != 0 AND r.status=4 and i.status IS NULL 
//           ${community}`)

//          completedCount = await sequelize.query(`
//           select count(r.id) as completedCount from requests r 
//           LEFT JOIN project_categories pc ON pc.id = r.project_category 
//            LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY 
//          request_id) i ON i.request_id = r.id `
//         + ` 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 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  request_services rss ON co.request_id = rss.request_id
//               GROUP BY co.request_id
//             ) rss ON r.id = rss.request_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 
//          where  r.status != 0 AND i.status IS NOT NULL AND ( inst_counts.installation_count >= cop.product_count OR inst_counts.installation_count >= rss.service_count ) 
//          AND (cop.request_id IS NOT NULL OR rss.request_id IS NOT NULL) ${community}`)
//          installsCount = await sequelize.query(`
//          SELECT 
//     COUNT(CASE WHEN i.complete_status = 1 THEN 1 END) AS installsCount,
//     COUNT(CASE WHEN i.complete_status = 2 THEN 1 END) AS pickupCount,
//     COUNT(CASE WHEN (i.complete_status = 3 AND i.status != 5 ) THEN 1 END) AS shippingCount
//   FROM requests r
//           LEFT JOIN project_categories pc ON pc.id = r.project_category 
//            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 = r.id `
//         + ` 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 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  request_services rss ON co.request_id = rss.request_id
//               GROUP BY co.request_id
//             ) rss ON r.id = rss.request_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 
//          where  r.status != 0 AND i.status IS NOT NULL   AND ( COALESCE(inst_counts.installation_count, 0) < COALESCE(cop.product_count, 0) \n          OR (pc.name = 'Service Only' AND COALESCE(inst_counts.installation_count, 0) < COALESCE(rss.service_count, 0))\n          OR (COALESCE(cop.product_count, 0) = 0 AND COALESCE(rss.service_count, 0) > 0 AND COALESCE(inst_counts.installation_count, 0) < COALESCE(rss.service_count, 0))\n        ) 
//          AND (cop.request_id IS NOT NULL OR rss.request_id IS NOT NULL) ${community}`)
//     }
//     if (userType == 3) {
//       query = await sequelize.query(` SELECT  rp . id  as  rt_partner_id ,u2.profile_pic AS customer_pic,com.name AS community_name,  rp . accept_status ,i.status as installationStatus,i.complete_status AS installationCompleteStatus,  p . user_id  as  partner_user_id ,  trps . proposal_added_by ,  trps . proposal_status ,  r .*, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count,concat(u.first_name," ", u.last_name) as send_to,u.id as sender_id,u.profile_pic as pic,c_ord.customer_name,ct.billing_type,`
//         + ` CASE `
//         + ` WHEN inst_counts.installation_count >= cop.product_count OR inst_counts.installation_count >= rss.service_count `
//         + ` THEN 1 `
//         + ` ELSE 0 `
//         + ` END AS allInstallationCompleted,`
//         + ` COALESCE(reqPay.totalAmount, 0) AS totalPaidAmount,`
//         + ` (COALESCE(c_ord.total, 0) - COALESCE(reqPay.totalAmount, 0)) AS dueAmount,`
//         + ` inst_counts.installation_count, cop.product_count, rss.service_count, `
//         + ` pc.name AS job_category_name  FROM  requests   r  `
//         + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
//         + ` LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c `
//         + ` left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=${userId} and rml.partner_id=c.partner_id),0) and c.user_id!=${userId} and p.user_id=${userId} group by c.request_id) rm ON  r.id = rm.request_id `
//         + ` LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals`
//         + ` where status=1 group by request_id) rps ON rps.request_id=r.id`
//         + ` JOIN users u ON r.added_by=u.id`
//         + ` JOIN request_partners rp ON rp.request_id=r.id`
//         + `  JOIN partners p ON p.id=rp.partner_id `
//         + ` left join customer_orders c_ord on c_ord.request_id = r.id `
//         + ` left join partners p2 on p2.id = c_ord.customer_id `
//         + ` left join customer_type ct on p2.customerTypeId = ct.id `
//         + ` left join users u2 on u2.id = p2.user_id `
//         + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//         + ` LEFT JOIN (select request_id as rid, added_by as proposal_added_by,COALESCE(status,'NA') as proposal_status from request_proposals where added_by=184) trps ON trps.rid=r.id `
//         + ` 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 = r.id `
//         + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
//         + ` 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 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  request_services rss ON co.request_id = rss.request_id
//               WHERE rss.labour_cost_service_id != 10
//               GROUP BY co.request_id
//             ) rss ON r.id = rss.request_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 `
//         + ` WHERE p.user_id = ${userId} AND  ${WhereCondition} and r.status!=1 ${content} ${createdAt} ${limit}`)

//       totalCount = await sequelize.query(`select count(r.id) as totalCount from requests r`
//         + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
//         + ` LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c `
//         + ` left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=${userId} and rml.partner_id=c.partner_id),0) and c.user_id!=${userId} and p.user_id=${userId} group by c.request_id) rm ON  r.id = rm.request_id `
//         + ` LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals`
//         + ` where status=1 group by request_id) rps ON rps.request_id=r.id`
//         + ` JOIN users u ON r.added_by=u.id`
//         + ` JOIN request_partners rp ON rp.request_id=r.id`
//         + `  JOIN partners p ON p.id=rp.partner_id `
//         + ` left join customer_orders c_ord on c_ord.request_id = r.id `
//         + ` left join partners p2 on p2.id = c_ord.customer_id `
//         + ` left join customer_type ct on p2.customerTypeId = ct.id `
//         + ` left join users u2 on u2.id = p2.user_id `
//         + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//         + ` LEFT JOIN (select request_id as rid, added_by as proposal_added_by,COALESCE(status,'NA') as proposal_status from request_proposals where added_by=184) trps ON trps.rid=r.id `
//         + ` LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY 
//          request_id) i ON i.request_id = r.id `
//         + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
//         + ` 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 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  request_services rss ON co.request_id = rss.request_id
//               GROUP BY co.request_id
//             ) rss ON r.id = rss.request_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 `
//         + ` WHERE p.user_id = ${userId} ${content} and ${WhereCondition} and r.status!=1  `
//       )
      
//       allCount = await sequelize.query(` SELECT COUNT(r.id) AS allCount  from requests r `
//         + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
//         + ` LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c `
//         + ` left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=${userId} and rml.partner_id=c.partner_id),0) and c.user_id!=${userId} and p.user_id=${userId} group by c.request_id) rm ON  r.id = rm.request_id `
//         + ` LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals`
//         + ` where status=1 group by request_id) rps ON rps.request_id=r.id`
//         + ` JOIN users u ON r.added_by=u.id`
//         + ` JOIN request_partners rp ON rp.request_id=r.id`
//         + `  JOIN partners p ON p.id=rp.partner_id `
//         + ` left join customer_orders c_ord on c_ord.request_id = r.id `
//         + ` left join partners p2 on p2.id = c_ord.customer_id `
//         + ` left join customer_type ct on p2.customerTypeId = ct.id `
//         + ` left join users u2 on u2.id = p2.user_id `
//         + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//         + ` LEFT JOIN (select request_id as rid, added_by as proposal_added_by,COALESCE(status,'NA') as proposal_status from request_proposals where added_by=184) trps ON trps.rid=r.id `
//         + ` LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY 
//          request_id) i ON i.request_id = r.id `
//         + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
//         + ` 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 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  request_services rss ON co.request_id = rss.request_id
//               GROUP BY co.request_id
//             ) rss ON r.id = rss.request_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 `
//         + ` WHERE p.user_id = ${userId} AND r.status NOT IN (0, 1, 8) ${community} `);
      
//       openCount = await sequelize.query(`select count(r.id) as openCount from requests r`
//         + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
//         + ` LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c `
//         + ` left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=${userId} and rml.partner_id=c.partner_id),0) and c.user_id!=${userId} and p.user_id=${userId} group by c.request_id) rm ON  r.id = rm.request_id `
//         + ` LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals`
//         + ` where status=1 group by request_id) rps ON rps.request_id=r.id`
//         + ` JOIN users u ON r.added_by=u.id`
//         + ` JOIN request_partners rp ON rp.request_id=r.id`
//         + `  JOIN partners p ON p.id=rp.partner_id `
//         + ` left join customer_orders c_ord on c_ord.request_id = r.id `
//         + ` left join partners p2 on p2.id = c_ord.customer_id `
//         + ` left join customer_type ct on p2.customerTypeId = ct.id `
//         + ` left join users u2 on u2.id = p2.user_id `
//         + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//         + ` LEFT JOIN (select request_id as rid, added_by as proposal_added_by,COALESCE(status,'NA') as proposal_status from request_proposals where added_by=184) trps ON trps.rid=r.id `
//         + ` LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY 
//          request_id) i ON i.request_id = r.id `
//         + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
//         + ` 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 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  request_services rss ON co.request_id = rss.request_id
//               GROUP BY co.request_id
//             ) rss ON r.id = rss.request_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 `
//         + ` WHERE p.user_id = ${userId} and r.status!=1 and r.status != 0 AND ((r.status=2) OR (r.status=3 AND r.min_payment_status=0)) 
//          ${community}`
//       )

//       acceptedCount = await sequelize.query(`select count(r.id) as acceptedCount from requests r`
//         + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
//         + ` LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c `
//         + ` left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=${userId} and rml.partner_id=c.partner_id),0) and c.user_id!=${userId} and p.user_id=${userId} group by c.request_id) rm ON  r.id = rm.request_id `
//         + ` LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals`
//         + ` where status=1 group by request_id) rps ON rps.request_id=r.id`
//         + ` JOIN users u ON r.added_by=u.id`
//         + ` JOIN request_partners rp ON rp.request_id=r.id`
//         + `  JOIN partners p ON p.id=rp.partner_id `
//         + ` left join customer_orders c_ord on c_ord.request_id = r.id `
//         + ` left join partners p2 on p2.id = c_ord.customer_id `
//         + ` left join customer_type ct on p2.customerTypeId = ct.id `
//         + ` left join users u2 on u2.id = p2.user_id `
//         + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//         + ` LEFT JOIN (select request_id as rid, added_by as proposal_added_by,COALESCE(status,'NA') as proposal_status from request_proposals where added_by=184) trps ON trps.rid=r.id `
//         + ` LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY 
//          request_id) i ON i.request_id = r.id `
//         + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
//         + ` 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 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  request_services rss ON co.request_id = rss.request_id
//               GROUP BY co.request_id
//             ) rss ON r.id = rss.request_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 `
//         + ` WHERE p.user_id = ${userId} and r.status!=1 and r.status != 0 AND  (r.status=3 AND r.min_payment_status =1) 
//           ${community}`
//       )

//       inProductionCount = await sequelize.query(`select count(r.id) as inProductionCount from requests r`
//         + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
//         + ` LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c `
//         + ` left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=${userId} and rml.partner_id=c.partner_id),0) and c.user_id!=${userId} and p.user_id=${userId} group by c.request_id) rm ON  r.id = rm.request_id `
//         + ` LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals`
//         + ` where status=1 group by request_id) rps ON rps.request_id=r.id`
//         + ` JOIN users u ON r.added_by=u.id`
//         + ` JOIN request_partners rp ON rp.request_id=r.id`
//         + `  JOIN partners p ON p.id=rp.partner_id `
//         + ` left join customer_orders c_ord on c_ord.request_id = r.id `
//         + ` left join partners p2 on p2.id = c_ord.customer_id `
//         + ` left join customer_type ct on p2.customerTypeId = ct.id `
//         + ` left join users u2 on u2.id = p2.user_id `
//         + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
//         + ` LEFT JOIN (select request_id as rid, added_by as proposal_added_by,COALESCE(status,'NA') as proposal_status from request_proposals where added_by=184) trps ON trps.rid=r.id `
//         + ` LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY 
//          request_id) i ON i.request_id = r.id `
//         + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
//         + ` 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 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  request_services rss ON co.request_id = rss.request_id
//               GROUP BY co.request_id
//             ) rss ON r.id = rss.request_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 `
//         + ` WHERE p.user_id = ${userId} and r.status=4 and r.status != 0 AND  i.status IS NULL 
//          ${community}`
//       )
//       completedCount = await sequelize.query(`select count(r.id) as completedCount from requests r`
//         + ` JOIN request_partners rp ON rp.request_id=r.id`
//         + `  JOIN partners p ON p.id=rp.partner_id `
//         + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
//         + `  LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY 
//          request_id) i ON i.request_id = r.id `
//         + ` 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 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  request_services rss ON co.request_id = rss.request_id
//           GROUP BY co.request_id
//         ) rss ON r.id = rss.request_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 `
//         + ` WHERE p.user_id = ${userId} and r.status!=1 and r.status != 0 AND  i.status IS NOT NULL AND ( inst_counts.installation_count >= cop.product_count OR inst_counts.installation_count >= rss.service_count ) 
//         AND (cop.request_id IS NOT NULL OR rss.request_id IS NOT NULL) ${community}`
//       )
//       installsCount = await sequelize.query(`  SELECT 
//         COUNT(CASE WHEN i.complete_status = 1 THEN 1 END) AS installsCount,
//     COUNT(CASE WHEN i.complete_status = 2 THEN 1 END) AS pickupCount,
//     COUNT(CASE WHEN i.complete_status = 3 THEN 1 END) AS shippingCount from requests r`
//         + ` JOIN request_partners rp ON rp.request_id=r.id`
//         + `  JOIN partners p ON p.id=rp.partner_id `
//         + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
//         + `  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 = r.id `
//         + ` 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 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  request_services rss ON co.request_id = rss.request_id
//           GROUP BY co.request_id
//         ) rss ON r.id = rss.request_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 `
//         + ` WHERE p.user_id = ${userId} and r.status!=1 and r.status != 0 AND  i.status IS NOT NULL AND ( COALESCE(inst_counts.installation_count, 0) < COALESCE(cop.product_count, 0) OR (pc.name = 'Service Only' AND COALESCE(inst_counts.installation_count, 0) < COALESCE(rss.service_count, 0)) OR (COALESCE(cop.product_count, 0) = 0 AND COALESCE(rss.service_count, 0) > 0 AND COALESCE(inst_counts.installation_count, 0) < COALESCE(rss.service_count, 0))) 
//         AND (cop.request_id IS NOT NULL OR rss.request_id IS NOT NULL)  ${community}`
//       )
//     }
//     let result = query[0]
// console.log("bsdfisfidgidfgi333333",acceptedCount);

//     if (result.length >= 1) {
//       const newData = await Promise.all(result.map(async (row) => {
//         let image = await FetchAllApprovedDesigns(row.id);
//         image = image?.filter((imageItem) => imageItem?.file_type?.startsWith('image/') || imageItem?.file_type === 'img')
//         let partners = await getRequestPartnerByIds(false, row.id);
//         if (!empty(image[0])) {
//           row.thumbnail = image[0].name ? image[0].name : ""
//         }
//         else {
//           row.thumbnail = ""
//         }
//         if (partners?.length > 0) {
//           row.partners = partners
//         } else {
//           row.partners = []
//         }
//         return row;
//       }));
//       const data = newData?.map(record => parseDecimalFields(record));
//       return { data, 
//         totalCount: totalCount[0][0].totalCount,
//         allCount: allCount[0][0].allCount,
//         openCount: openCount[0][0].openCount,
//         acceptedCount: acceptedCount[0][0].acceptedCount,
//         inProductionCount: inProductionCount[0][0].inProductionCount,
//         completedCount: completedCount[0][0].completedCount,
//         installsCount: installsCount[0][0].installsCount,
//         pickupCount: installsCount[0][0].pickupCount,
//         shippingCount: installsCount[0][0].shippingCount,
//        };
//     }
//     else {
//       return { data:[], 
//         totalCount: totalCount[0][0].totalCount,
//         allCount: allCount[0][0].allCount,
//         openCount: openCount[0][0].openCount,
//         acceptedCount: acceptedCount[0][0].acceptedCount,
//         inProductionCount: inProductionCount[0][0].inProductionCount,
//         completedCount: completedCount[0][0].completedCount,
//         installsCount: installsCount[0][0].installsCount,
//         pickupCount: installsCount[0][0].pickupCount,
//         shippingCount: installsCount[0][0].shippingCount,
//        };
//     }
//   } catch (error) {
//     console.error(error);
//     return error;
//   }
// };

const getAllQuotations = async (requestId, userId, userType, page, rowPerpage, search, where = '', sort, fromDate, toDate,filterClient, filterProjectType, filterUser, dueData, filterCommunity,projectEstimate=false ) => {
  try {
    let createdAt = '';
    // If dueData is true, sort by participation_ends (due date) ascending
    if (dueData === true) {
      createdAt = ` ORDER BY r.participation_ends ASC `;
    } else if (sort === 'new') {
      createdAt = ` ORDER BY r.id DESC `;
    } else if (sort === 'old') {
      createdAt = ` ORDER BY r.id ASC `;
    } else if (sort === 'custom_order') {
      createdAt = `ORDER BY r.card_order ASC`
    } else {
      createdAt = ` ORDER BY r.timestamp DESC`;
    }

    let offset = null;
    if (rowPerpage && page) {
      offset = (page - 1) * rowPerpage;
    }
    let totalCount = 0;
    let partnerWhere = '';
    let query = '';
    let content = '';
    // if (search) {
    //   // content = ` and r.name LIKE '%${search}%' OR r.description LIKE '%${search}%'`;
    //   content = `AND (LOWER(r.name) LIKE LOWER('%${search}%') OR LOWER(r.description) LIKE LOWER('%${search}%'))`;
    // }
    if (search) {
      const escapedSearch = search.replace(/'/g, "''").trim();
      const normalizedSearch = escapedSearch.toLowerCase();
    
      content = `AND (
        LOWER(COALESCE(r.name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.description, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(c_ord.customer_name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.doc_number, '')) LIKE '%${normalizedSearch}%'`
      
      // Include com.name only if userType is not 3 (com is joined only in that case)
      if (userType !== 3) {
        content += ` OR LOWER(COALESCE(com.name, '')) LIKE '%${normalizedSearch}%'`;
      }
    
      content += `)`;
    }    

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

    let dateCondition = '';
    if (fromTimestamp && toTimestamp) {
      dateCondition = `AND r.participation_ends BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
    } else if (fromTimestamp) {
      dateCondition = `AND r.participation_ends >= ${fromTimestamp}`;
    } else if (toTimestamp) {
      dateCondition = `AND r.participation_ends <= ${toTimestamp}`;
    }

    let WhereCondition = '';
    if (requestId) {
      WhereCondition = ` r.id=${requestId}`;
    } else {
      WhereCondition = ` r.status = 8 ${dateCondition}`;
      if (!empty(where)) {
        WhereCondition = ` ${where} ${dateCondition}`;
      }
    }
    if (userType === 3) {
      WhereCondition += ` AND (r.send_to_client = 1 OR r.added_by = ${userId})`;
    }

    if (filterProjectType === 1) {
      WhereCondition += ` AND r.project_type = 1`;
    } else if (filterProjectType === 2) {
      WhereCondition += ` AND r.project_type = 2`;
    } else if (filterProjectType === 3) {
      WhereCondition += ` AND r.is_split_order = 1`;
    } else if (filterProjectType === 'NULL'){
      WhereCondition += ` AND r.project_type IS NULL`;
    } else {
      WhereCondition += ` AND (r.project_type IS NULL OR r.project_type IS NOT NULL)`;
    }

    let clientCondition = '';
    if (filterClient && filterClient.length > 0) {
      clientCondition = ` AND c_ord.customer_id IN (${filterClient.join(',')}) `;
    }    

    let userCondition = '';
    if (filterUser && filterUser.length > 0) {
      userCondition = ` AND r.added_by IN (${filterUser.join(',')}) `;
    }

    let communityCondition = '';
    if (filterCommunity && filterCommunity.length > 0) {
      // Check if 'other' is in the filter (for null communities)
      const hasOther = filterCommunity.includes('other');
      const communityIds = filterCommunity.filter(id => id !== 'other');
      
      if (hasOther && communityIds.length > 0) {
        // Filter by community IDs OR null
        communityCondition = ` AND (r.community IN (${communityIds.join(',')}) OR r.community IS NULL) `;
      } else if (hasOther) {
        // Only 'other' selected - filter for null communities
        communityCondition = ` AND r.community IS NULL `;
      } else {
        // Only specific community IDs selected
        communityCondition = ` AND r.community IN (${communityIds.join(',')}) `;
      }
    }

    let limit = '';
    if (rowPerpage) {
      limit = `LIMIT ${rowPerpage} OFFSET ${offset}`;
    }     
    let designOrderCondition = '';
    if(projectEstimate){
      designOrderCondition = ` LEFT JOIN design_orders d_ord ON d_ord.request_id = r.id `;
      
    }

    if (userType != 3) {
      query = await sequelize.query("SELECT `r`.*, est_prj.status AS estimate_job_status, c_ord.total as invoice_total,c_ord.grandTotal as invoice_grand_total,u2.profile_pic AS customer_pic,com.name AS community_name, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count,i.status as installationStatus,i.complete_status AS installationCompleteStatus, c_ord.customer_name,pc.name AS job_category_name FROM `requests` `r` "
        + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
        + " LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c "
        + " left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id LIMIT 1),0) and c.user_id!=1 group by c.request_id) rm ON `r`.`id`=`rm`.`request_id` "
        + " LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM `request_proposals` where status=1 group by request_id) rps ON `rps`.`request_id`=`r`.`id` "
        + ` left join customer_orders c_ord on c_ord.request_id = r.id `
        + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
        + ` left join partners p2 on p2.id = c_ord.customer_id `
        + ` left join users u2 on u2.id = p2.user_id `
        + ` ${designOrderCondition}`
        + ` left join projects est_prj on est_prj.request_id = r.id AND est_prj.is_estimate_job = 1 AND r.quotation = 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 = r.id `
        + ` LEFT JOIN users u ON r.added_by=u.id WHERE ${WhereCondition} ${clientCondition} ${userCondition} ${communityCondition} ${content} ${createdAt} ${limit}`);

        totalCount = await sequelize.query(`
          select count(r.id) as totalCount from requests r 
          LEFT JOIN customer_orders c_ord on c_ord.request_id = r.id
          left join projects est_prj on est_prj.request_id = r.id AND est_prj.is_estimate_job = 1 AND r.quotation = 1
          ${designOrderCondition}
          LEFT JOIN community com ON com.id = r.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1
          LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id 
          WHERE ${WhereCondition} ${clientCondition} ${userCondition} ${communityCondition} ${content}`);
        
    }

    if (userType == 3) {
      query = await sequelize.query(` SELECT  rp . id  as  rt_partner_id ,  est_prj.status AS estimate_job_status, i.status as installationStatus,i.complete_status AS installationCompleteStatus, u2.profile_pic AS customer_pic,com.name AS community_name,  rp . accept_status ,  p . user_id  as  partner_user_id ,  trps . proposal_added_by ,  trps . proposal_status ,  r .*, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count,concat(u.first_name," ", u.last_name) as send_to,u.id as sender_id,u.profile_pic as pic,c_ord.customer_name,pc.name AS job_category_name  FROM  requests   r  `
        + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
        + ` LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c `
        + ` left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=${userId} and rml.partner_id=c.partner_id LIMIT 1),0) and c.user_id!=${userId} and p.user_id=${userId} group by c.request_id) rm ON  r.id = rm.request_id `
        + ` LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals`
        + ` where status=1 group by request_id) rps ON rps.request_id=r.id`
        + ` LEFT JOIN users u ON r.added_by=u.id`
        + ` LEFT JOIN request_partners rp ON rp.request_id=r.id`
        + `  LEFT JOIN partners p ON p.id=rp.partner_id `
        + ` left join customer_orders c_ord on c_ord.request_id = r.id `
        + ` left join partners p2 on p2.id = c_ord.customer_id `
        + ` left join users u2 on u2.id = p2.user_id `
        + ` ${designOrderCondition}`
        + ` left join projects est_prj on est_prj.request_id = r.id AND est_prj.is_estimate_job = 1 AND r.quotation = 1`
        + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
        + ` LEFT JOIN (select request_id as rid, added_by as proposal_added_by,COALESCE(status,'NA') as proposal_status from request_proposals where added_by=184) trps ON trps.rid=r.id `
        + ` 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 = r.id `
        + ` WHERE p.user_id = ${userId} AND ${WhereCondition} ${userCondition} ${communityCondition} and r.status!=1 ${content} ${createdAt} ${limit}`);

      totalCount = await sequelize.query(`select count(r.id) as totalCount from requests r`
        + ` LEFT JOIN request_partners rp ON rp.request_id=r.id`
        + ` ${designOrderCondition}`
        + ` left join projects est_prj on est_prj.request_id = r.id AND est_prj.is_estimate_job = 1 AND r.quotation = 1`
        + `  JOIN partners p ON p.id=rp.partner_id `
        + `  LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id `
        + ` WHERE p.user_id = ${userId} ${content} ${userCondition} ${communityCondition} and ${WhereCondition} and r.status!=1`);
    }

    let result = query[0];

    if (result.length >= 1) {
      const newData = await Promise.all(result.map(async (row) => {
        let image = await FetchAllApprovedDesigns(row.id);
        image = image?.filter((imageItem) => imageItem?.file_type?.startsWith('image/') || imageItem?.file_type === 'img')
        let partners = await getRequestPartnerByIds(false, row.id);
        if (!empty(image[0])) {
          row.thumbnail = image[0].name ? image[0].name : "";
        } else {
          row.thumbnail = "";
        }
        if (partners?.length > 0) {
          row.partners = partners;
        } else {
          row.partners = [];
        }
        return row;
      }));
      const data = newData?.map(record => parseDecimalFields(record));
      // return { data, totalCount: totalCount[0]?.[0]?.totalCount || 0 };
      return { data, totalCount: totalCount[0][0].totalCount || 0 };
    } else {
      return [];
    }
  } catch (error) {
    console.error(error);
    return null;
  }
};

const getAllQuotationsCountForOverview = async (requestId, userId, userType, page, rowPerpage, search, where = '', sort, fromDate, toDate,filterClient, filterProjectType, filterUser, dueData, filterCommunity,projectEstimate=false ) => {
  try {
    let createdAt = '';
    // If dueData is true, sort by participation_ends (due date) ascending
    if (dueData === true) {
      createdAt = ` ORDER BY r.participation_ends ASC `;
    } else if (sort === 'new') {
      createdAt = ` ORDER BY r.id DESC `;
    } else if (sort === 'old') {
      createdAt = ` ORDER BY r.id ASC `;
    } else if (sort === 'custom_order') {
      createdAt = `ORDER BY r.card_order ASC`
    } else {
      createdAt = ` ORDER BY r.timestamp DESC`;
    }

    let offset = null;
    if (rowPerpage && page) {
      offset = (page - 1) * rowPerpage;
    }
    let totalCount = 0;
    let partnerWhere = '';
    let query = '';
    let content = '';
    // if (search) {
    //   // content = ` and r.name LIKE '%${search}%' OR r.description LIKE '%${search}%'`;
    //   content = `AND (LOWER(r.name) LIKE LOWER('%${search}%') OR LOWER(r.description) LIKE LOWER('%${search}%'))`;
    // }
    if (search) {
      const escapedSearch = search.replace(/'/g, "''").trim();
      const normalizedSearch = escapedSearch.toLowerCase();
    
      content = `AND (
        LOWER(COALESCE(r.name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.description, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(c_ord.customer_name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.doc_number, '')) LIKE '%${normalizedSearch}%'`
      
      // Include com.name only if userType is not 3 (com is joined only in that case)
      if (userType !== 3) {
        content += ` OR LOWER(COALESCE(com.name, '')) LIKE '%${normalizedSearch}%'`;
      }
    
      content += `)`;
    }    

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

    let dateCondition = '';
    if (fromTimestamp && toTimestamp) {
      dateCondition = `AND r.participation_ends BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
    } else if (fromTimestamp) {
      dateCondition = `AND r.participation_ends >= ${fromTimestamp}`;
    } else if (toTimestamp) {
      dateCondition = `AND r.participation_ends <= ${toTimestamp}`;
    }

    let WhereCondition = '';
    if (requestId) {
      WhereCondition = ` r.id=${requestId}`;
    } else {
      WhereCondition = ` r.status = 8 ${dateCondition}`;
      if (!empty(where)) {
        WhereCondition = ` ${where} ${dateCondition}`;
      }
    }
    if (userType === 3) {
      WhereCondition += ` AND (r.send_to_client = 1 OR r.added_by = ${userId})`;
    }

    if (filterProjectType === 1) {
      WhereCondition += ` AND r.project_type = 1`;
    } else if (filterProjectType === 2) {
      WhereCondition += ` AND r.project_type = 2`;
    } else if (filterProjectType === 3) {
      WhereCondition += ` AND r.is_split_order = 1`;
    } else if (filterProjectType === 'NULL'){
      WhereCondition += ` AND r.project_type IS NULL`;
    } else {
      WhereCondition += ` AND (r.project_type IS NULL OR r.project_type IS NOT NULL)`;
    }

    let clientCondition = '';
    if (filterClient && filterClient.length > 0) {
      clientCondition = ` AND c_ord.customer_id IN (${filterClient.join(',')}) `;
    }    

    let userCondition = '';
    if (filterUser && filterUser.length > 0) {
      userCondition = ` AND r.added_by IN (${filterUser.join(',')}) `;
    }

    let communityCondition = '';
    if (filterCommunity && filterCommunity.length > 0) {
      // Check if 'other' is in the filter (for null communities)
      const hasOther = filterCommunity.includes('other');
      const communityIds = filterCommunity.filter(id => id !== 'other');
      
      if (hasOther && communityIds.length > 0) {
        // Filter by community IDs OR null
        communityCondition = ` AND (r.community IN (${communityIds.join(',')}) OR r.community IS NULL) `;
      } else if (hasOther) {
        // Only 'other' selected - filter for null communities
        communityCondition = ` AND r.community IS NULL `;
      } else {
        // Only specific community IDs selected
        communityCondition = ` AND r.community IN (${communityIds.join(',')}) `;
      }
    }

    let limit = '';
    if (rowPerpage) {
      limit = `LIMIT ${rowPerpage} OFFSET ${offset}`;
    }     
    let designOrderCondition = '';
    if(projectEstimate){
      designOrderCondition = ` LEFT JOIN design_orders d_ord ON d_ord.request_id = r.id `;
      
    }

    if (userType != 3) {
      
        totalCount = await sequelize.query(`
          select count(r.id) as totalCount from requests r 
          LEFT JOIN customer_orders c_ord on c_ord.request_id = r.id
          left join projects est_prj on est_prj.request_id = r.id AND est_prj.is_estimate_job = 1 AND r.quotation = 1
          ${designOrderCondition}
          LEFT JOIN community com ON com.id = r.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1
          LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id 
          WHERE ${WhereCondition} ${clientCondition} ${userCondition} ${communityCondition} ${content}`);
        
    }

    if (userType == 3) {
     
      totalCount = await sequelize.query(`select count(r.id) as totalCount from requests r`
        + ` LEFT JOIN request_partners rp ON rp.request_id=r.id`
        + ` ${designOrderCondition}`
        + ` left join projects est_prj on est_prj.request_id = r.id AND est_prj.is_estimate_job = 1 AND r.quotation = 1`
        + `  JOIN partners p ON p.id=rp.partner_id `
        + `  LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id `
        + ` WHERE p.user_id = ${userId} ${content} ${userCondition} ${communityCondition} and ${WhereCondition} and r.status!=1`);
    }
     
    return {  totalCount: totalCount[0][0].totalCount || 0 };
    
  } catch (error) {
    console.error(error);
    return 0;
  }
};

const getAllQuotationsCount = async (requestId, userId, userType, page, rowPerpage, search, where = '', sort, fromDate, toDate) => {
  try {
    let createdAt = '';
    if (sort === 'new') {
      createdAt = ` ORDER BY r.id DESC `;
    } else if (sort === 'old') {
      createdAt = ` ORDER BY r.id ASC `;
    } else if (sort === 'custom_order') {
      createdAt = `ORDER BY r.card_order ASC`
    } else {
      createdAt = ` ORDER BY r.timestamp DESC`;
    }

    let offset = null;
    if (rowPerpage && page) {
      offset = (page - 1) * rowPerpage;
    }
    let totalCount = 0;
    let partnerWhere = '';
    let query = '';
    let content = '';
    if (search) {
      content = ` and r.name LIKE '%${search}%'`;
    }

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

    let dateCondition = '';
    if (fromTimestamp && toTimestamp) {
      dateCondition = `AND r.participation_ends BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
    } else if (fromTimestamp) {
      dateCondition = `AND r.participation_ends >= ${fromTimestamp}`;
    } else if (toTimestamp) {
      dateCondition = `AND r.participation_ends <= ${toTimestamp}`;
    }

    let WhereCondition = '';
    if (requestId) {
      WhereCondition = ` r.id=${requestId}`;
    } else {
      WhereCondition = ` r.status = 8 ${dateCondition}`;
      if (!empty(where)) {
        WhereCondition = ` ${where} ${dateCondition}`;
      }
    }
    if (userType === 3) {
      WhereCondition += ` AND (r.send_to_client = 1 OR r.added_by = ${userId})`;
    }

    let limit = '';
    if (rowPerpage) {
      limit = `LIMIT ${rowPerpage} OFFSET ${offset}`;
    }

    if (userType != 3) {
      totalCount = await sequelize.query(`
         select count(r.id) as totalCount from requests r 
           LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id 
           WHERE ${WhereCondition} ${content}`);
    }

    if (userType == 3) {
      totalCount = await sequelize.query(`select count(r.id) as totalCount from requests r`
        + ` LEFT JOIN request_partners rp ON rp.request_id=r.id`
        + `  JOIN partners p ON p.id=rp.partner_id `
        + `  LEFT JOIN (SELECT MAX(status) AS status,request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id `
        + ` WHERE p.user_id = ${userId} ${content} and ${WhereCondition} and r.status!=1 ${userCondition}`);
    }

    if (totalCount?.length >= 1) {
      
      return { totalCount: totalCount[0][0].totalCount };
    } else {
      return [];
    }
  } catch (error) {
    console.error(error);
    return null;
  }
};

const getAllTeamBatch = async () => {
  try {
    let query = ` SELECT rt.*, CONCAT(sm.first_name, ' ', sm.last_name) as member_name, u.profile_pic
      FROM request_teams rt
      JOIN staff_members sm ON sm.id = rt.team_user_id
      JOIN users u ON u.id = sm.user_id
      WHERE rt.status = 1 AND sm.status = 1`
    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT,
    })
    if (result.length >= 1) {
      const request_team = {}
      result.forEach(row => {
        if (!request_team[row.request_id]) {
          return request_team[row.request_id] = []
        } else {
          request_team[row.request_id].push(row)
          return request_team;

        }
      })
    } else {
      return false
    }
    return result
  } catch (error) {
    console.log(error, 'Error in fetching all request team members')
  }
}
const getServices = async (serviceId) => {
  try {
    let query = '';

    if (serviceId) {
      query = `SELECT sr.*
                     FROM services as sr
                     WHERE sr.id = :serviceId`;
    } else {
      query = `SELECT sr.*
                     FROM services as sr
                     WHERE sr.status = 1`;
    }

    const result = await sequelize.query(query, {
      replacements: { serviceId },
      type: sequelize.QueryTypes.SELECT,
    });

    if (result.length >= 1) {
      const data = result.map((row) => row);
      return data;
    } else {
      return false;
    }
  } catch (error) {
    console.error('Error in fetching services:', error);
    throw error;
  }
};

const getRequestById = async (request_id) => {
  if (!empty(request_id)) {
    let query = `SELECT rt.*, co.id AS cust_order_id, co.total,p.id as project_id,co.budget,pc.name AS job_category_name,cusTyp.billing_type,cusTyp.quickbookId AS paymentTermQuickbookId,part.name AS customer_name,part.email AS customer_email,co.customer_id FROM requests rt `
      + ` LEFT JOIN customer_orders co ON co.request_id = rt.id `
      + ` LEFT JOIN project_categories pc ON pc.id = rt.project_category `
      + ` LEFT JOIN projects p ON p.request_id = rt.id AND p.is_estimate_job = 0 `
      + ` LEFT JOIN partners part ON part.id = co.customer_id `
      + ` LEFT JOIN customer_type cusTyp ON cusTyp.id = part.customerTypeId `
      + ` WHERE rt.id = ${request_id}`;

    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT,
    });

    if (result.length === 1) {
      const data = result.map((row) => row);
      return data.map(record => parseDecimalFields(record));
    } else {
      return false;
    }
  } else {
    return false;
  }
};

const getSalesOrderRequestByDesignOrderId = async (design_order_id) => {
  try {
    if (empty(design_order_id)) return false;
    const result = await sequelize.query(
      `SELECT r.* FROM requests r
       WHERE r.design_order_id = :design_order_id
         AND r.quotation = 0
         AND r.status != 0
       ORDER BY r.id DESC
       LIMIT 1`,
      {
        replacements: { design_order_id },
        type: sequelize.QueryTypes.SELECT,
      }
    );
    return result?.length ? result[0] : false;
  } catch (error) {
    console.log('Error : ', error);
    return false;
  }
}
const getEstimateRequestByDesignOrderId = async (design_order_id) => {
  try {
    if (empty(design_order_id)) return false;
    const result = await sequelize.query(
      `SELECT r.* FROM requests r
       WHERE r.design_order_id = :design_order_id
         AND r.quotation = 1
         AND r.status != 0
       ORDER BY r.id DESC
       LIMIT 1`,
      {
        replacements: { design_order_id },
        type: sequelize.QueryTypes.SELECT,
      }
    );
    return result?.length ? result[0] : false;
  } catch (error) {
    console.log('Error : ', error);
    return false;
  }
}
const getRequestEstimateByDesignOrderId = async (design_order_id) => {
  try {
    if (empty(design_order_id)) return false;
    const result = await sequelize.query(
      `SELECT r.* FROM requests r
       WHERE r.design_order_id = :design_order_id
         AND r.quotation = 1
         AND r.is_request_estimate = 1
         AND r.status != 0
       ORDER BY r.id DESC
       LIMIT 1`,
      {
        replacements: { design_order_id },
        type: sequelize.QueryTypes.SELECT,
      }
    );
    return result?.length ? result[0] : false;
  } catch (error) {
    console.log('Error : ', error);
    return false;
  }
}
const getRequestByProductId = async (product_id) => {
  if (!empty(product_id)) {
    let query = `SELECT rt.*, co.total,co.budget FROM requests rt `
      + `LEFT JOIN customer_orders co ON co.request_id = rt.id `
      + `WHERE rt.id = ${product_id}`;

    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT,
    });

    if (result.length === 1) {
      const data = result.map((row) => row);
      return data.map(record => parseDecimalFields(record));
    } else {
      return false;
    }
  } else {
    return false;
  }
};
const editRequest = async (request_id, values) => {
  if (!empty(request_id && values)) {
    let query = `UPDATE rt.* FROM requests rt WHERE id=${request_id}`
    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.UPDATE,
    });
  }
}
const deleteRequestById = async (request_id) => {
  if (!empty(request_id)) {
    let query = `
    UPDATE requests
    SET status = 0
    WHERE id = ${request_id}`;
    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.UPDATE,
    });

    if (result) {
      return true
    } else {
      return false
    }
  }
}
const destroyRequestById = async (request_id, transaction = null) => {
  try {
    if (!request_id) return false;

    const result = await Requests.destroy({
      where: { id: request_id },
      transaction
    });

    return result > 0; // true if deleted
  } catch (error) {
    console.error('Error destroying request by id:', error);
    return false;
  }
};
const addRequestClients = async (table_name, data) => {
  let res = await Requests.create(data)
  return res.id;
}
const getRequestPartnersByIds = async (partner_ids = [], request_id = 0) => {
  let query = '';
  let clients = partner_ids.join(',')

  if (!empty(partner_ids)) {
    query = `SELECT u.id, CONCAT(u.first_name, ' ', u.last_name) as name FROM partners t
             LEFT JOIN users u ON t.user_id = u.id 
             WHERE u.status = 1 AND t.id in ( ${clients} )
             ORDER BY u.id DESC`;

  } else {
    query = `SELECT u.id, CONCAT(u.first_name, ' ', u.last_name) as name 
             FROM request_partners r 
             LEFT JOIN partners t ON r.partner_id = t.id 
             LEFT JOIN users u ON t.user_id = u.id 
             WHERE u.status = 1 AND r.request_id = ${request_id}
             ORDER BY u.id DESC`;
  }

  const result = await sequelize.query(query, {
    type: sequelize.QueryTypes.SELECT,
  });

  if (result.length >= 1) {

    return result;
  } else {
    return [];
  }
};

const getRequestTeamUserIds = async (request_id) => {

  let query = `SELECT u.id FROM request_teams r LEFT JOIN staff_members t on r.team_user_id=t.id
    LEFT JOIN users u on t.user_id=u.id WHERE u.status=1 and r.request_id=${request_id}
    ORDER BY u.id DESC`;

  try {
    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT,
    });

    if (result.length >= 1) {
      return result;
    } else {
      return [];
    }
  } catch (error) {
    console.error('Error executing query:', error);
    return [];
  }
};
const searchRequests = async (requestId, userType, userId, content) => {
  try {
    let partnerWhere = '';
    let query = '';
    let WhereCondition = '';

    if (requestId) {
      WhereCondition = ` AND r.id=${requestId}`;
    } else {
      WhereCondition = '';
    }

    let contentCondition = '';
    if (content) {
      contentCondition = ` AND (r.name LIKE '%${content}%' OR r.description LIKE '%${content}%')`;
    }

    if (userType != 3) {
      query = await sequelize.query(
        "SELECT `r`.*, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count FROM `requests` `r` "
        + " LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c "
        + " left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id LIMIT 1),0) and c.user_id!=1 group by c.request_id) rm ON `r`.`id`=`rm`.`request_id` "
        + " LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM `request_proposals` where status=1 group by request_id) rps ON `rps`.`request_id`=`r`.`id` "
        + ` JOIN users u ON r.added_by=u.id WHERE r.status <>0 ${WhereCondition} ${contentCondition} ORDER BY r.id DESC`
      );
    }

    if (userType == 3) {
      query = await sequelize.query(
        `SELECT rp.id as rt_partner_id, rp.accept_status, p.user_id as partner_user_id, trps.proposal_added_by, trps.proposal_status, r.*, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count, concat(u.first_name," ", u.last_name) as send_to, u.profile_pic as pic FROM requests r `
        + ` LEFT JOIN (select count(c.id) as cnt, c.request_id from request_messages c `
        + ` left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=${userId} and rml.partner_id=c.partner_id LIMIT 1),0) and c.user_id!=${userId} and p.user_id=${userId} group by c.request_id) rm ON r.id = rm.request_id `
        + ` LEFT JOIN (SELECT COUNT(id) as cnt, request_id FROM request_proposals`
        + ` where status=1 group by request_id) rps ON rps.request_id=r.id`
        + ` JOIN users u ON r.added_by=u.id`
        + ` JOIN request_partners rp ON rp.request_id=r.id`
        + ` JOIN partners p ON p.id=rp.partner_id `
        + ` LEFT JOIN (select request_id as rid, added_by as proposal_added_by, COALESCE(status,'NA') as proposal_status from request_proposals where added_by=184) trps ON trps.rid=r.id `
        + ` WHERE p.user_id = ${userId} AND r.status <>0 ${WhereCondition} ${contentCondition} ORDER BY r.id DESC`
      );
    }

    let result = query[0];

    if (result.length >= 1) {
      // const data = result.map((row) => row);
      const data = await Promise.all(result.map(async (row) => {
        let image = await FetchAllApprovedDesigns(row.id);
        image = image?.filter((imageItem) => imageItem?.file_type?.startsWith('image/') || imageItem?.file_type === 'img')
        if (!empty(image[0])) {
          row.thumbnail = image[0].name ? image[0].name : ""
        }
        else {
          row.thumbnail = ""
        }

        return row;
      }));
      return data;
    } else {
      return [];
    }
  } catch (error) {
    console.error(error);
    return null;
  }

}

const getAllClientRequestId = async (id) => {
  let query = await sequelize.query(`SELECT DISTINCT p.*, u.username, u.company_name, u.user_type, u.profile_pic, u.status FROM partners p`
    + ` JOIN users u ON p.user_id=u.id `
    + ` WHERE u.user_type = 3 AND u.status = 1 AND p.status = 1 AND p.id not in(select partner_id from request_partners where request_id=${id}) ORDER BY p.id DESC`)
  let data = [];

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

  }

  return data;
}
const addRequestAttachments = async (data) => {

  let res = await RequestAttachments.create(data)
  return res.id;
}
const updateRequestAttachments = async (requestId, data) => {

  let res = await RequestAttachments.update(data, {
    where: { id: data.id, request_id: requestId }
  })
  return res;
}
const getAllRequestAttachments = async (requestId) => {
  let res = await RequestAttachments.findAll({
    where: { request_id: requestId, status: 1 },
    order: [['id', 'DESC']] // Order by 'id' in descending order
  })
  return res;
}
const getRequestAttachmentById = async (id) => {
  let res = await RequestAttachments.findOne({
    where: { id: id, status: 1 }
  })
  return res?.dataValues;
}
const getRequestAttachmentsByLocationId = async (requestId) => {
  try {
    const query = `
      SELECT id, name, location_ids, status, request_id
      FROM request_attachments 
      WHERE request_id = :requestId
      ORDER BY id DESC
    `;
    
    const result = await sequelize.query(query, {
      replacements: { requestId },
      type: sequelize.QueryTypes.SELECT
    });
    
    return result || [];
  } catch (error) {
    console.error("Error fetching request attachments by location ID:", error);
    return [];
  }
}

const deleteExistingAttachments = async (requestId) => {
  try {
    const query = `
    DELETE FROM request_attachments WHERE request_id = :requestId AND location_ids is not null and location_ids != ''
  `;
    const result = await sequelize.query(query, {
      replacements: { requestId },
      type: sequelize.QueryTypes.DELETE
    });
    return result;
  } catch (error) {
    console.error("Error deleting existing attachments:", error);
    return null;
  }
}
const deletePayment = async (id) => {
  try {
    const deleted = await RequestPayments.destroy({
      where: {
        id: id
      },
    });

    if (deleted) {
      return deleted;
    }
    else {
      return false;
    }
  }
  catch (error) {
    console.log("Delete error......", error)
  }
}
const deleteLocation = async (id) => {
  let deleted = await sequelize.query(`DELETE rl FROM request_locations rl`
    + ` left join customer_order_products cp on cp.id=rl.order_id`
    + ` left join customer_orders co on co.id=cp.order_id`
    + ` left join requests r on r.id=co.request_id`
    + ` WHERE rl.order_id=${id}`)
  if (deleted) {
    return deleted;
  }
  else {
    return false;
  }

}
const deleteMaterialLocationByOrderId = async (id) => {
  let deleted = await sequelize.query(`DELETE rl FROM request_locations rl`
    + ` left join customer_order_products cp on cp.id=rl.order_id`
    + ` WHERE cp.order_id=${id} and material=1`)
  if (deleted) {
    return deleted;
  }
  else {
    return false;
  }
}
const FetchAllApprovedDesigns = async (id) => {
  let query = `SELECT * FROM request_attachments WHERE request_id=${id} AND status=1 and approved=1 ORDER BY timestamp ASC`
  const result = sequelize.query(query, {
    type: sequelize.QueryTypes.SELECT,
  })
  return result
}

const FetchAllApprovedDesignsBulk = async (ids) => {
  if (!ids || ids.length === 0) {
    return [];
  }

  // Use a single query with WHERE IN to fetch designs for all provided IDs
  const query = `
    SELECT * 
    FROM request_attachments 
    WHERE request_id IN (${ids.join(",")}) 
      AND status=1 
      AND approved=1
  `;

  const result = await sequelize.query(query, {
    type: sequelize.QueryTypes.SELECT,
  });

  return result;
};


const getRequestByCommunityId = async (communityId, userId, userType, hasPermission = false, client) => {
  if (!empty(communityId)) {
    console.log("#################Communityyyyyyyyyy", client);
    let query = `SELECT rt.*,u2.profile_pic AS customer_pic,r.name as community_name FROM requests rt `
      + ` left join customer_orders c_ord on c_ord.request_id = rt.id `
      + ` left join partners p2 on p2.id = c_ord.customer_id `
      + ` left join users u2 on u2.id = p2.user_id `
      + ` LEFT JOIN community r on rt.community = r.id `
      + ` WHERE r.id=${communityId} and rt.status!=0  and FIND_IN_SET(c_ord.customer_id, r.clients) > 0 AND r.status = 1 `;
    if (userType !== 1 && hasPermission == false) {
      query = `SELECT rt.*,rp.partner_id AS request_partner_id,pt.user_id,u2.profile_pic AS customer_pic,r.name as community_name FROM requests rt `
        + ` LEFT JOIN request_partners rp on rt.id = rp.request_id `
        + ` LEFT JOIN partners pt on pt.id = rp.partner_id `
        + ` left join customer_orders c_ord on c_ord.request_id = rt.id `
        + ` left join partners p2 on p2.id = c_ord.customer_id `
        + ` left join users u2 on u2.id = p2.user_id `
        + ` LEFT JOIN community r on rt.community = r.id`
        + ` WHERE rt.community=${communityId} AND pt.user_id = ${userId}  and rt.status!=0 and FIND_IN_SET(${client}, r.clients) > 0 and r.status=1`;
    }

    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT,
    });

    if (result.length > 0) {
      const data = result.map((row) => row);
      return data;
    } else {
      return [];
    }
  } else {
    return false;
  }
};

// const getCompletedInstallsByCommunityId = async (communityId, userId, userType, hasPermission = false, client) => {
//   if (!empty(communityId)) {
//     console.log("#################Communityyyyyyyyyy", client);
//     let query = `SELECT rt.*,u2.profile_pic AS customer_pic,r.name as community_name FROM requests rt `
//       + ` left join customer_orders c_ord on c_ord.request_id = rt.id `
//       + ` left join partners p2 on p2.id = c_ord.customer_id `
//       + ` left join users u2 on u2.id = p2.user_id `
//       + ` LEFT JOIN community r on rt.community = r.id `
//       + ` LEFT JOIN installations inst ON inst.request_id = rt.id `
//       + ` WHERE r.id=${communityId} and 
//           rt.installation_acceptance IS NOT NULL and rt.status!=0  
//           and FIND_IN_SET(c_ord.customer_id, r.clients) > 0 AND r.status = 1 `
//       + ` AND inst.complete_status = 1 `
//       + ` GROUP BY rt.id`;
//     if (userType !== 1 && hasPermission == false) {
//       query = `SELECT rt.*,rp.partner_id AS request_partner_id,pt.user_id,u2.profile_pic AS customer_pic,r.name as community_name FROM requests rt `
//         + ` LEFT JOIN request_partners rp on rt.id = rp.request_id `
//         + ` LEFT JOIN partners pt on pt.id = rp.partner_id `
//         + ` left join customer_orders c_ord on c_ord.request_id = rt.id `
//         + ` left join partners p2 on p2.id = c_ord.customer_id `
//         + ` left join users u2 on u2.id = p2.user_id `
//         + ` LEFT JOIN community r on rt.community = r.id`
//         +  ` LEFT JOIN installations inst ON inst.request_id = rt.id `
//         + ` WHERE rt.community=${communityId} AND rt.installation_acceptance IS NOT NULL AND pt.user_id = ${userId}  and rt.status!=0 and FIND_IN_SET(${client}, r.clients) > 0 and r.status=1`
//         + ` AND inst.complete_status = 1 `
//         + ` GROUP BY rt.id`;
//     }

//     const result = await sequelize.query(query, {
//       type: sequelize.QueryTypes.SELECT,
//     });

//     if (result.length > 0) {
//       const data = result.map((row) => row);
//       return data;
//     } else {
//       return [];
//     }
//   } else {
//     return false;
//   }
// };

// const getCompletedInstallsByCommunityId = async (communityId, userId, userType, hasPermission = false, client, page = 1, rowsPerPage = 10, sort = 'new', fromDate, toDate, dueDate, search) => {
//   if (!empty(communityId)) {
//     console.log("#################Communityyyyyyyyyy", client);

//     // Pagination
//     let offset = (page - 1) * rowsPerPage;
//     let limitQuery = `LIMIT ${rowsPerPage} OFFSET ${offset}`;

//     // Sorting
//     let createdAt = '';
//     if (dueDate) {
//         createdAt = `ORDER BY inst.installation_date ASC`;  // Ordering by due date if provided
//     } else if (sort === 'new') {
//         createdAt = `ORDER BY rt.id DESC`;  // Newest First
//     } else if (sort === 'old') {
//         createdAt = `ORDER BY rt.id ASC`;  // Oldest First
//     } else {
//         createdAt = `ORDER BY rt.timestamp DESC`; // Default Sorting
//     }

//     // Date Filters (From Date, To Date, Due Date)
//     const fromTimestamp = fromDate ? moment(fromDate).startOf('day').unix() : null;
//     const toTimestamp = toDate ? moment(toDate).endOf('day').unix() : null;
//     const dueTimestamp = dueDate ? moment(dueDate).endOf('day').unix() : null;

//     let dateCondition = '';
//     if (fromTimestamp && toTimestamp) {
//         dateCondition = ` inst.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
//     } else if (fromTimestamp) {
//         dateCondition = ` inst.installation_date >= ${fromTimestamp}`;
//     } else if (toTimestamp) {
//         dateCondition = ` inst.installation_date <= ${toTimestamp}`;
//     }

//     let dueDateCondition = '';
//     // if (dueTimestamp) {
//     //     dueDateCondition = ` inst.due_date <= ${dueTimestamp}`;
//     // }

//     // Search Filter
//     let searchCondition = '';
//     if (search) {
//         search = search.toLowerCase();
//         searchCondition = ` (LOWER(rt.name) LIKE '%${search}%' OR LOWER(r.name) LIKE '%${search}%') `;
//     }

//     // Base Query Conditions
//     let whereCondition = `WHERE r.id=${communityId} 
//                           AND rt.installation_acceptance IS NOT NULL 
//                           AND rt.status!=0 
//                           AND FIND_IN_SET(c_ord.customer_id, r.clients) > 0 
//                           AND r.status = 1 
//                           AND inst.complete_status = 1`;

//     if (userType !== 1 && !hasPermission) {
//         whereCondition = `WHERE rt.community=${communityId} 
//                           AND rt.installation_acceptance IS NOT NULL 
//                           AND pt.user_id = ${userId} 
//                           AND rt.status!=0 
//                           AND FIND_IN_SET(${client}, r.clients) > 0 
//                           AND r.status=1 
//                           AND inst.complete_status = 1`;
//     }

//     let filters = [];
//     if (dateCondition) filters.push(dateCondition);
//     // if (dueDateCondition) filters.push(dueDateCondition);
//     if (searchCondition) filters.push(searchCondition);

//     if (filters.length > 0) {
//         whereCondition += ` AND ${filters.join(' AND ')}`;
//     }

//     // Main Query
//     let query = `SELECT rt.*, u2.profile_pic AS customer_pic, r.name AS community_name, inst.due_date ,inst.installation_date
//                  FROM requests rt
//                  LEFT JOIN customer_orders c_ord ON c_ord.request_id = rt.id
//                  LEFT JOIN partners p2 ON p2.id = c_ord.customer_id
//                  LEFT JOIN users u2 ON u2.id = p2.user_id
//                  LEFT JOIN community r ON rt.community = r.id
//                  LEFT JOIN installations inst ON inst.request_id = rt.id
//                  ${whereCondition}
//                  GROUP BY rt.id
//                  ${createdAt}
//                  ${limitQuery}`;

//     // Execute Query
//     const result = await sequelize.query(query, { type: sequelize.QueryTypes.SELECT });

//     return result.length > 0 ? result.map(row => row) : [];
//   } else {
//     return false;
//   }
// };

// const getCompletedInstallsByCommunityId = async (
//   communityId, userId, userType, hasPermission = false, client, 
//   page = 1, rowsPerPage = 10, sort = 'new', fromDate, toDate, dueData, search
// ) => {
//   if (!communityId) return false;

//   console.log("Community:", communityId, "Client:", client, "Due Data:", dueData);

//   let offset = (page - 1) * rowsPerPage;
//   let limitQuery = `LIMIT ${rowsPerPage} OFFSET ${offset}`;

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

//   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 = ` inst.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
//   } else if (fromTimestamp) {
//       dateCondition = ` inst.installation_date >= ${fromTimestamp}`;
//   } else if (toTimestamp) {
//       dateCondition = ` inst.installation_date <= ${toTimestamp}`;
//   }

//   let dueDateCondition = '';
//   if (dueData) {
//       dueDateCondition = ` inst.installation_date <= ${dueTimestamp}`;
//   }


//   let searchCondition = '';
//   if (search) {
//       search = search.toLowerCase();
//       searchCondition = ` (LOWER(rt.name) LIKE '%${search}%' OR LOWER(r.name) LIKE '%${search}%') `;
//   }

//   let whereCondition = `WHERE r.id=${communityId} 
//                         AND rt.installation_acceptance IS NOT NULL 
//                         AND rt.status!=0 
//                         AND FIND_IN_SET(c_ord.customer_id, r.clients) > 0 
//                         AND r.status = 1 
//                         AND inst.complete_status = 1`;

//   if (userType !== 1 && !hasPermission) {
//       whereCondition = `WHERE rt.community=${communityId} 
//                         AND rt.installation_acceptance IS NOT NULL 
//                         AND pt.user_id = ${userId} 
//                         AND rt.status!=0 
//                         AND FIND_IN_SET(${client}, r.clients) > 0 
//                         AND r.status=1 
//                         AND inst.complete_status = 1`;
//   }


//   let filters = [];
//   if (dateCondition) filters.push(dateCondition);
//   if (dueDateCondition) filters.push(dueDateCondition);
//   if (searchCondition) filters.push(searchCondition);

//   if (filters.length > 0) {
//       whereCondition += ` AND ${filters.join(' AND ')}`;
//   }


//   let query = `
//       SELECT rt.*, u2.profile_pic AS customer_pic, r.name AS community_name, inst.due_date, inst.installation_date
//       FROM requests rt
//       LEFT JOIN customer_orders c_ord ON c_ord.request_id = rt.id
//       LEFT JOIN partners p2 ON p2.id = c_ord.customer_id
//       LEFT JOIN users u2 ON u2.id = p2.user_id
//       LEFT JOIN community r ON rt.community = r.id
//       LEFT JOIN installations inst ON inst.request_id = rt.id
//       ${whereCondition}
//       GROUP BY rt.id
//       ${createdAt}  -- ✅ Fix: Sorting applied after filtering
//       ${limitQuery}`;

//   console.log("Final SQL Query:", query);


//   const result = await sequelize.query(query, { type: sequelize.QueryTypes.SELECT });

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

const getCompletedInstallsByCommunityId = async (
  communityId, userId, userType, hasPermission = false, client, 
  page = 1, rowsPerPage = 10, sort = 'new', fromDate, toDate, dueData, search,filterValue,filterClient, filterProjectType
) => {
  if (!communityId) return false;

  console.log("Community:", communityId, "Client:", client, "Due Data:", dueData);

  let offset = (page - 1) * rowsPerPage;
  let limitQuery = `LIMIT ${rowsPerPage} OFFSET ${offset}`;

  let orderByCondition = '';
  if (dueData) {
    orderByCondition = `ORDER BY inst.installation_date ASC`;  
  } else if (sort === 'new') {
    orderByCondition = `ORDER BY inst.id DESC`;  
  } else if (sort === 'old') {
    orderByCondition = `ORDER BY inst.id ASC`;  
  } else if (sort === 'custom_order') {
    orderByCondition = `ORDER BY inst.card_order ASC`;  
  } else {
    orderByCondition = `ORDER BY inst.timestamp DESC`;  
  }

  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 inst.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
  } else if (fromTimestamp) {
      dateCondition = ` AND inst.installation_date >= ${fromTimestamp}`;
  } else if (toTimestamp) {
      dateCondition = ` AND inst.installation_date <= ${toTimestamp}`;
  }

  // let dueDateCondition = '';
  // if (dueData) {
  //     dueDateCondition = ` AND inst.installation_date <= ${dueTimestamp}`;
  // }

  let searchCondition = '';
  // if (search) {
  //     search = search.toLowerCase();
  //     searchCondition = ` AND (LOWER(rt.name) LIKE '%${search}%' OR LOWER(r.name) LIKE '%${search}%' OR LOWER(r.description) LIKE '%${search}%') `;
  // }
  if (search) {
    search = search.toLowerCase();
        searchCondition = ` AND LOWER(rt.description) LIKE '%${search}%' `;
  }
  
  let filterCondition = '';
  if (filterValue) {
      filterCondition = ` AND rt.id = ${filterValue}`;
  }
  let clientCondition = '';
  if (Array.isArray(filterClient) && filterClient.length > 0) {
      clientCondition = ` AND c_ord.customer_id IN (${filterClient.join(',')})`;
}

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

  let baseQuery = `
      FROM requests rt
      LEFT JOIN customer_orders c_ord ON c_ord.request_id = rt.id
      LEFT JOIN partners p2 ON p2.id = c_ord.customer_id
      LEFT JOIN users u2 ON u2.id = p2.user_id
      LEFT JOIN community r ON rt.community = r.id
      LEFT JOIN installations inst ON inst.request_id = rt.id
      WHERE r.id = ${communityId}
      AND rt.installation_acceptance IS NOT NULL 
      AND rt.status != 0 
      AND FIND_IN_SET(c_ord.customer_id, r.clients) > 0 
      AND r.status = 1 
      AND inst.complete_status = 1
      ${filterCondition} ${dateCondition} ${searchCondition} ${clientCondition} ${projectTypeCondition}
  `;

  // if (userType !== 1 && !hasPermission) {
  if (userType == 3 && !hasPermission) {
      baseQuery = `
        FROM requests rt
        LEFT JOIN customer_orders c_ord ON c_ord.request_id = rt.id
        LEFT JOIN partners p2 ON p2.id = c_ord.customer_id
        LEFT JOIN users u2 ON u2.id = p2.user_id
        LEFT JOIN community r ON rt.community = r.id
        LEFT JOIN installations inst ON inst.request_id = rt.id
        WHERE rt.community = ${communityId}
        AND rt.installation_acceptance IS NOT NULL 
        AND p2.user_id = ${userId} 
        AND rt.status != 0 
        AND FIND_IN_SET(${client}, r.clients) > 0 
        AND r.status = 1 
        AND inst.complete_status = 1
        ${filterCondition} ${dateCondition} ${searchCondition}  ${clientCondition} ${projectTypeCondition}
      `;
  }

  let dataQuery = `
      SELECT rt.*, u2.profile_pic AS customer_pic, r.name AS community_name, inst.due_date, inst.installation_date
      ${baseQuery}
      GROUP BY rt.id
      ${orderByCondition}  
      ${limitQuery}
  `;

  let countQuery = `
      SELECT COUNT(DISTINCT rt.id) AS totalCount
      ${baseQuery}
  `;

  try {
    const dataResult = await sequelize.query(dataQuery, { type: sequelize.QueryTypes.SELECT });
    const countResult = await sequelize.query(countQuery, { type: sequelize.QueryTypes.SELECT });
    const totalCount = countResult[0]?.totalCount || 0;
    return {
      data: dataResult,
      totalCount: totalCount
    };
  } catch (error) {
    console.error("Error fetching completed installs:", error);
    return { data: [], totalCount: 0 };
  }
};

const getCompletedInstallsByCommunityIdForFilter = async (communityId, userId = 0, userType = 0, hasPermission = false, sort, fromDate, toDate ,filterClient) => {
  try {
      let orderByCondition = '';
      if (sort === 'new') {
          orderByCondition = `ORDER BY I.id DESC`;
      } else if (sort === 'old') {
          orderByCondition = `ORDER BY I.id ASC`;
      } else if (sort === 'custom_order') {
          orderByCondition = `ORDER BY I.card_order ASC`;
      } else {
          orderByCondition = `ORDER BY I.timestamp DESC`;
      }

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

      let dateCondition = '';
      if (fromTimestamp && toTimestamp) {
          dateCondition = ` AND I.installation_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
      } else if (fromTimestamp) {
          dateCondition = ` AND I.installation_date >= ${fromTimestamp}`;
      } else if (toTimestamp) {
          dateCondition = ` AND I.installation_date <= ${toTimestamp}`;
      }
      let clientCondition = '';
      if (Array.isArray(filterClient) && filterClient.length > 0) {
        clientCondition = ` AND c.customer_id IN (${filterClient.map(id => `'${id}'`).join(',')})`;
    }

      let whereCondition = `AND I.complete_status = 1
                            AND r.status != 0  
                            AND FIND_IN_SET(c.customer_id, com.clients) > 0
                            AND com.status = 1
                            AND com.id = ${communityId}`;

      if (userType !== 1 && userType !== 8 && userType !== 0 && !hasPermission) {
          whereCondition += ` AND (
    ${userType} = 1 OR ${userType} = 8 OR ${hasPermission} = true 
    OR EXISTS (
        SELECT 1 FROM project_members pm
        JOIN staff_members sm ON sm.id = pm.staff_id
        WHERE pm.project_id = I.project_id AND sm.user_id = ${userId}
    )
    OR EXISTS (
        SELECT 1 FROM customer_orders co
        JOIN partners p ON p.id = co.customer_id
        JOIN users u ON u.id = p.user_id
        WHERE co.request_id = I.request_id AND u.id = ${userId}
    )
)
`;
      }

      let query = `
          SELECT I.*, ptp.name AS job_class_name, pc.name AS job_category_name, 
          p.cover_image, p.start_date, p.name AS Project_name, 
          CONCAT(u.first_name, ' ', COALESCE(u.last_name, '')) AS implementation_manager, 
          u.profile_pic AS manager_profile_photo, dr.name AS driver_name, com.name AS community_name,
          COALESCE(MAX(CASE WHEN ra.approved = 1 THEN ra.name END), MAX(ra.name)) AS attachmentUrl, 
          COALESCE(MAX(CASE WHEN ra.approved = 1 THEN 1 END), MAX(ra.approved)) AS approved 
          FROM installations I
          LEFT JOIN staff_members sm ON sm.id = I.team_id
          LEFT JOIN project_members pm ON pm.project_id = I.project_id
          LEFT JOIN users u ON u.id = I.team_id
          LEFT JOIN projects p ON p.id = I.project_id AND p.is_estimate_job = 0
          LEFT JOIN project_types ptp ON ptp.id = p.project_type
          LEFT JOIN project_categories pc ON pc.id = p.project_category
          LEFT JOIN requests r ON r.id = I.request_id
          LEFT JOIN request_attachments ra ON ra.request_id = I.request_id AND (ra.file_type LIKE 'image/%' OR ra.file_type = 'img')
          LEFT JOIN customer_orders c ON c.request_id = r.id
          LEFT JOIN community com ON com.id = p.community 
          LEFT JOIN driver dr ON dr.id = I.driver_id
          WHERE r.installation_acceptance IS NOT NULL ${whereCondition} ${dateCondition} ${clientCondition}
          GROUP BY r.id 
          ${orderByCondition}
      `;

      const dataResult = await sequelize.query(query, { type: sequelize.QueryTypes.SELECT });

      return dataResult;

  } catch (error) {
      console.error("Error fetching installations by community:", error);
      return [];
  }
};

const getProjectByCommunityId = async (communityId, userId, userType, hasPermission = false, client) => {
  if (!empty(communityId)) {
    console.log('result----------------22222222222222222');
    // let query = `SELECT rt.* FROM projects rt WHERE community=${communityId}`;
    // if(userType !== 1 && hasPermission == false){
    //   query = `SELECT p.*,rp.partner_id AS request_partner_id,pt.user_id FROM projects p `
    //     +` LEFT JOIN installations i on p.id = i.project_id `
    //     +` LEFT JOIN request_partners rp on p.request_id = rp.request_id `
    //     +` LEFT JOIN partners pt on pt.id = rp.partner_id `
    //     +` WHERE p.community=${communityId} AND i.project_id IS NULL AND pt.user_id = ${userId}`;
    let query = `SELECT rt.* FROM projects rt `
      + ` LEFT JOIN requests r on r.id=rt.request_id`
      + ` left join customer_orders c_ord on c_ord.request_id = r.id `
      + ` left join community c on c.id=r.community WHERE rt.community=${communityId} AND rt.is_estimate_job=0 and FIND_IN_SET(c_ord.customer_id, c.clients) > 0 and c.status=1`
    if (userType !== 1 && hasPermission == false) {
      query = `SELECT p.*,rp.partner_id AS request_partner_id,pt.user_id FROM projects p `

        + ` LEFT JOIN request_partners rp on p.request_id = rp.request_id `
        + ` LEFT JOIN partners pt on pt.id = rp.partner_id `
        + ` LEFT JOIN requests r on r.id=p.request_id`
        + ` left join community c on c.id=r.community`
        + ` WHERE r.community=${communityId} AND p.is_estimate_job=0 AND pt.user_id = ${userId} and FIND_IN_SET(${client},c.clients) > 0 and c.status=1`;
    }
    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT,
    });
    console.log('result----------------');
    if (result?.length > 0) {
      const data = result.map((row) => row);
      // return data;
      return data?.map(record => parseDecimalFields(record));
    } else {
      return [];
    }
  } else {
    return false;
  }
};

const getCompleteDesignByCommunityId = async (communityId, userId, userType, hasPermission = false, client) => {
  if (!empty(communityId)) {
    let query = `SELECT rt.*,u2.profile_pic AS customer_pic,r.name as community_name FROM requests rt `
      + ` left join customer_orders c_ord on c_ord.request_id = rt.id `
      + ` left join partners p2 on p2.id = c_ord.customer_id `
      + ` left join users u2 on u2.id = p2.user_id `
      + ` LEFT JOIN community r on rt.community = r.id `
      + ` WHERE r.id=${communityId} and rt.status!=0 and rt.isFromDesignOrder=1  and FIND_IN_SET(c_ord.customer_id, r.clients) > 0 AND r.status = 1 `;
    if (userType !== 1 && hasPermission == false) {
      query = `SELECT rt.*,rp.partner_id AS request_partner_id,pt.user_id,u2.profile_pic AS customer_pic,r.name as community_name FROM requests rt `
        + ` LEFT JOIN request_partners rp on rt.id = rp.request_id `
        + ` LEFT JOIN partners pt on pt.id = rp.partner_id `
        + ` left join customer_orders c_ord on c_ord.request_id = rt.id `
        + ` left join partners p2 on p2.id = c_ord.customer_id `
        + ` left join users u2 on u2.id = p2.user_id `
        + ` LEFT JOIN community r on rt.community = r.id`
        + ` WHERE rt.community=${communityId} AND rt.isFromDesignOrder=1 AND pt.user_id = ${userId}  and rt.status!=0 and FIND_IN_SET(${client}, r.clients) > 0 and r.status=1`;
    }

    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT,
    });

    if (result.length > 0) {
      const data = result.map((row) => row);
      return data;
    } else {
      return [];
    }
  } else {
    return false;
  }
};

// const getCompleteDesignOrdersByCommunityId = async (communityId, userId, userType, hasPermission = false, client) => {
//   if (!communityId) {
//     return false;
//   }

//   let query = `
//     SELECT do.*, u2.profile_pic AS customer_pic, c.name AS community_name 
//     FROM design_orders do
//     LEFT JOIN partners p ON p.id = do.client
//     LEFT JOIN users u2 ON u2.id = p.user_id
//     LEFT JOIN community c ON do.community = c.id
//     WHERE do.community = ${communityId}
//     AND do.status = 3 
//     AND c.status = 1
//     AND FIND_IN_SET(do.client, c.clients) > 0
//   `;

//   if (userType !== 1 && !hasPermission) {
//     query = `
//         SELECT do.*, u2.profile_pic AS customer_pic, c.name AS community_name 
//         FROM design_orders do
//         LEFT JOIN partners p ON p.id = do.client
//         LEFT JOIN users u2 ON u2.id = p.user_id
//         LEFT JOIN community c ON do.community = c.id
//         WHERE do.community = ${communityId}
//         AND do.status = 3 
//         AND c.status = 1
//         AND p.user_id = ${userId}
//         AND FIND_IN_SET(${client}, c.clients) > 0
//     `;
//   }

//   try {
//     const result = await sequelize.query(query, {
//       type: sequelize.QueryTypes.SELECT,
//     });

//     return result.length > 0 ? result : [];
//   } catch (error) {
//     console.error("Error fetching design orders:", error);
//     throw error;
//   }
// };

// const getCompleteDesignOrdersByCommunityId = async (communityId, userId, userType, hasPermission = false, client, page = 1, rowPerpage = 10, search = '', sort = 'default', fromDate = null, toDate = null, dueData = false) => {
//   if (!communityId) {
//     return false;
//   }
//   const fromTimestamp = fromDate ? moment(fromDate, 'YYYY-MM-DD HH:mm:ss').startOf('day').unix() : null;
//   const toTimestamp = toDate ? moment(toDate, 'YYYY-MM-DD HH:mm:ss').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}`;
//   }
  
//   if (dueData) {
//     createdAt = `ORDER BY UNIX_TIMESTAMP(do.due_date) ASC`;
//   }

//   let searchCondition = '';
//   if (search) {
//     searchCondition = `AND do.name LIKE '%${search}%'`;
//   }

//   let orderByCondition = '';
//   if (dueTimestamp) {
//     orderByCondition = `ORDER BY do.due_date ASC`;
//   } else {
//     if (sort === 'new') {
//       orderByCondition = `ORDER BY do.id DESC`;
//     } else if (sort === 'old') {
//       orderByCondition = `ORDER BY do.id ASC`;
//     } else if (sort === 'custom_order') {
//       orderByCondition = `ORDER BY do.card_order ASC`;
//     } else {
//       orderByCondition = `ORDER BY do.timestamp DESC`;
//     }
//   }

//   let offset = (page - 1) * rowPerpage;
//   let limitCondition = `LIMIT ${rowPerpage} OFFSET ${offset}`;

//   let query = `
//     SELECT do.*, u2.profile_pic AS customer_pic, c.name AS community_name 
//     FROM design_orders do
//     LEFT JOIN partners p ON p.id = do.client
//     LEFT JOIN users u2 ON u2.id = p.user_id
//     LEFT JOIN community c ON do.community = c.id
//     WHERE do.community = ${communityId}
//     AND do.status = 3 
//     AND c.status = 1
//     AND FIND_IN_SET(do.client, c.clients) > 0
//     ${dateCondition} ${searchCondition} ${orderByCondition} ${limitCondition}
//   `;

//   if (userType !== 1 && !hasPermission) {
//     query = `
//       SELECT do.*, u2.profile_pic AS customer_pic, c.name AS community_name 
//       FROM design_orders do
//       LEFT JOIN partners p ON p.id = do.client
//       LEFT JOIN users u2 ON u2.id = p.user_id
//       LEFT JOIN community c ON do.community = c.id
//       WHERE do.community = ${communityId}
//       AND do.status = 3 
//       AND c.status = 1
//       AND p.user_id = ${userId}
//       AND FIND_IN_SET(${client}, c.clients) > 0
//       ${dateCondition} ${searchCondition} ${orderByCondition} ${limitCondition}
//     `;
//   }

//   try {
//     const result = await sequelize.query(query, {
//       type: sequelize.QueryTypes.SELECT,
//     });

//     return result.length > 0 ? result : [];
//   } catch (error) {
//     console.error("Error fetching design orders:", error);
//     throw error;
//   }
// };
const getCompleteDesignOrdersByCommunityId = async (communityId, userId, userType, hasPermission = false, client, page = 1, rowPerpage = 10, search = '', sort = 'default', fromDate = null, toDate = null, dueData = false, filterClient) => {
  if (!communityId) {
    return [];
  }

  const fromTimestamp = fromDate ? moment(fromDate, 'YYYY-MM-DD HH:mm:ss').startOf('day').unix() : null;
  const toTimestamp = toDate ? moment(toDate, 'YYYY-MM-DD HH:mm:ss').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 searchCondition = '';
  if (search) {
    searchCondition = `AND do.description LIKE '%${search}%'`;
  }
  let clientCondition = '';
  if (filterClient && filterClient.length > 0) {
      clientCondition = `AND do.client IN (${filterClient.join(',')})`;
  }


  let orderByCondition = '';
  if (dueTimestamp) {
    orderByCondition = `ORDER BY do.due_date ASC`;
  } else {
    if (sort === 'new') {
      orderByCondition = `ORDER BY do.id DESC`;
    } else if (sort === 'old') {
      orderByCondition = `ORDER BY do.id ASC`;
    } else if (sort === 'custom_order') {
      orderByCondition = `ORDER BY do.card_order ASC`;
    } else {
      orderByCondition = `ORDER BY do.timestamp DESC`;
    }
  }

  let offset = (page - 1) * rowPerpage;
  let limitCondition = `LIMIT ${rowPerpage} OFFSET ${offset}`;

  let baseQuery = `
    FROM design_orders do
    LEFT JOIN design_orders odo ON odo.id = do.old_design_order_id
    LEFT JOIN partners p ON p.id = do.client
    LEFT JOIN users u2 ON u2.id = p.user_id
    LEFT JOIN community c ON do.community = c.id
    WHERE do.community = ${communityId}
    AND do.status = 3 
    AND c.status = 1
    AND FIND_IN_SET(do.client, c.clients) > 0
    ${dateCondition} ${searchCondition} ${clientCondition}
  `;

  let dataQuery = `
    SELECT do.*, u2.profile_pic AS customer_pic, c.name AS community_name, odo.name AS old_design_order_name
    ${baseQuery}
    ${orderByCondition} ${limitCondition}
  `;

  let countQuery = `
    SELECT COUNT(do.id) AS totalCount ${baseQuery}
  `;

  // if (userType !== 1 && !hasPermission) {
  if (userType == 3 && !hasPermission) {
    baseQuery = `
      FROM design_orders do
      LEFT JOIN design_orders odo ON odo.id = do.old_design_order_id
      LEFT JOIN partners p ON p.id = do.client
      LEFT JOIN users u2 ON u2.id = p.user_id
      LEFT JOIN community c ON do.community = c.id
      WHERE do.community = ${communityId}
      AND do.status = 3 
      AND c.status = 1
      AND p.user_id = ${userId}
      AND FIND_IN_SET(${client}, c.clients) > 0
      ${dateCondition} ${searchCondition} ${clientCondition}
    `;

    dataQuery = `
      SELECT do.*, u2.profile_pic AS customer_pic, c.name AS community_name, odo.name AS old_design_order_name
      ${baseQuery}
      ${orderByCondition} ${limitCondition}
    `;

    countQuery = `
      SELECT COUNT(do.id) AS totalCount ${baseQuery}
    `;
  }

  try {
    const [dataResult, countResult] = await Promise.all([
      sequelize.query(dataQuery, { type: sequelize.QueryTypes.SELECT }),
      sequelize.query(countQuery, { type: sequelize.QueryTypes.SELECT })
    ]);

    const totalCount = countResult[0]?.totalCount || 0;

    // Returning both data and totalCount as a single array
    return [...dataResult, { totalCount }];
  } catch (error) {
    console.error("Error fetching design orders:", error);
    return [];
  }
};

const getJobsByClientId = async (clientId, userId, userType, id, isEstimateJob = false) => {
  let whereCondition = ''
  if (id) {
    whereCondition = ` AND r.community=${id} `
  }
  let estimateJobCondition = ' AND rt.is_estimate_job=0'
  if(isEstimateJob){
    estimateJobCondition = ' AND rt.is_estimate_job=1'
  }
  if (!empty(clientId)) {
    let query = `SELECT rt.* FROM projects rt 
      LEFT JOIN requests r on r.id = rt.request_id
      LEFT JOIN request_partners rp on rp.request_id = rt.request_id
      LEFT JOIN partners pt on pt.id = rp.partner_id
      WHERE pt.user_id=${clientId} ${whereCondition} ${estimateJobCondition} AND rp.accept_status != 2`;
    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT,
    });
    console.log("#######################dataaaaaaaaa");
    if (result?.length > 0) {
      const data = result.map((row) => row);
      // return data;
      return data?.map(record => parseDecimalFields(record));
    } else {
      return [];
    }
  } else {
    return false;
  }
};

const getProjectByClientId = async (clientId, userId, userType, client) => {
  if (!empty(clientId)) {
    let query = `SELECT DISTINCT rt.* FROM community rt 
      LEFT JOIN requests r on r.community = rt.id
      LEFT JOIN request_partners rp on rp.request_id = r.id
      LEFT JOIN partners pt on pt.id = rp.partner_id
      WHERE FIND_IN_SET(${client}, rt.clients) > 0 and rt.status!=2`;
    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT,
    });
    console.log("##########nushhhhhhhhhhhhhh");
    if (result?.length > 0) {
      const data = result.map((row) => row);
      return data;
    } else {
      return [];
    }
  } else {
    return false;
  }
};

// Optimized function for fetching single request by ID (used in production inner page)
const getRequestByIdOptimized = async (requestId, userId, userType) => {
  try {
    // Use simpler query structure for single request fetch
    const baseQuery = userType == 3 
      ? `SELECT rp.id as rt_partner_id,proj.noServiceNoTask AS proj_noServiceNoTask,proj.status AS proj_status,proj.id AS isProject, u2.profile_pic AS customer_pic, com.name AS community_name, rp.accept_status, i.status as installationStatus,CONCAT(u.first_name, ' ', u.last_name) as added_by_name, u.user_type as added_by_user_type, i.complete_status AS installationCompleteStatus, p.user_id as partner_user_id, trps.proposal_added_by, trps.proposal_status, r.*, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count, CONCAT(u.first_name, " ", u.last_name) as send_to, u.id as sender_id, u.profile_pic as pic, c_ord.customer_name,c_ord.customer_id, ct.billing_type, 
        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, 
        CASE 
          WHEN r.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 r.project_category = 11 THEN 
          CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
          WHEN r.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 proj.status = 3 AND proj.noServiceNoTask = 0
            )
            THEN 1
            ELSE 0
          END AS allInstallationCompleted,
          CASE 
            WHEN 
              (
                (COALESCE(inst_non_edit.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
              )
              THEN 1
              ELSE 0
          END AS enableEditOnStaged,
        COALESCE(reqPay.totalAmount, 0) AS totalPaidAmount, 
        (COALESCE(c_ord.total, 0) - COALESCE(reqPay.totalAmount, 0)) AS dueAmount, 
        COALESCE((SELECT GROUP_CONCAT(DISTINCT CONCAT(sm.first_name,' ',COALESCE(sm.last_name,'')) ORDER BY sm.id SEPARATOR ' ') FROM staff_members sm WHERE r.sales_rep_ids IS NOT NULL AND r.sales_rep_ids != '' AND FIND_IN_SET(sm.id, r.sales_rep_ids) > 0), '') AS sales_rep_names,
        inst_counts.installation_count,inst_non_edit.installation_count AS staged_installation_count, total_inst_counts.total_installation_count, cop.product_count, rss.service_count, 
        CASE WHEN COALESCE(partial_inst.partial_installation_count, 0) > 0 THEN 1 ELSE 0 END AS partial_install,
        pc.name AS job_category_name
        FROM requests r 
      LEFT JOIN project_categories pc ON pc.id = r.project_category 
      LEFT JOIN (SELECT COUNT(c.id) AS cnt, c.request_id FROM request_messages c 
          LEFT JOIN partners p ON p.id = c.partner_id WHERE c.timestamp >= COALESCE((SELECT rml.timestamp FROM request_message_last_seen rml WHERE rml.request_id = c.request_id AND rml.user_id = ${userId} AND rml.partner_id = c.partner_id LIMIT 1), 0) AND c.user_id != ${userId} AND p.user_id = ${userId} GROUP BY c.request_id) rm ON r.id = rm.request_id 
      LEFT JOIN (SELECT COUNT(id) AS cnt, request_id FROM request_proposals WHERE status = 1 GROUP BY request_id) rps ON rps.request_id = r.id 
      JOIN users u ON r.added_by = u.id 
      LEFT JOIN request_partners rp ON rp.request_id = r.id 
      JOIN partners p ON p.id = rp.partner_id 
      LEFT JOIN customer_orders c_ord ON c_ord.request_id = r.id 
      left join projects proj on proj.request_id = r.id AND proj.is_estimate_job = 0
      LEFT JOIN partners p2 ON p2.id = c_ord.customer_id 
      LEFT JOIN customer_type ct ON p2.customerTypeId = ct.id 
      LEFT JOIN users u2 ON u2.id = p2.user_id 
      LEFT JOIN community com ON com.id = r.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1 
      LEFT JOIN (SELECT request_id AS rid, added_by AS proposal_added_by, COALESCE(status, 'NA') AS proposal_status FROM request_proposals WHERE added_by = ${userId}) trps ON trps.rid = r.id 
      LEFT JOIN (SELECT MAX(status) AS status, MAX(complete_status) AS complete_status, request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id
      LEFT JOIN (SELECT SUM(amount) AS totalAmount, request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay ON reqPay.request_id = r.id 
      LEFT JOIN (SELECT request_id, COUNT(*) AS installation_count FROM installations WHERE status = 1 GROUP BY request_id) inst_non_edit ON inst_non_edit.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
        GROUP BY co.request_id
      ) rss ON r.id = rss.request_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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id) partial_inst ON partial_inst.request_id = r.id
      WHERE p.user_id = ${userId} AND r.id = ${requestId} AND r.status != 1`
      : `SELECT r.*,proj.noServiceNoTask AS proj_noServiceNoTask,proj.status AS proj_status,proj.id AS isProject,rp.id as rt_partner_id ,c_ord.total as invoice_total,CONCAT(u.first_name, ' ', u.last_name) as added_by_name, u.user_type as added_by_user_type, c_ord.grandTotal as invoice_grand_total,u2.profile_pic AS customer_pic,com.name AS community_name, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count,i.status as installationStatus,i.complete_status AS installationCompleteStatus,c_ord.customer_name,c_ord.customer_id,ct.billing_type, 
        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,
        CASE 
                WHEN r.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 r.project_category = 11 THEN 
                CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                WHEN r.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 proj.status = 3 AND proj.noServiceNoTask = 0
            )
            THEN 1
            ELSE 0
          END AS allInstallationCompleted,
          CASE 
            WHEN 
            (
              (COALESCE(inst_non_edit.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
            )
            THEN 1
            ELSE 0
          END AS enableEditOnStaged,
        COALESCE(reqPay.totalAmount, 0) AS totalPaidAmount,
        (COALESCE(c_ord.total, 0) - COALESCE(reqPay.totalAmount, 0)) AS dueAmount,
        COALESCE((SELECT GROUP_CONCAT(DISTINCT CONCAT(sm.first_name,' ',COALESCE(sm.last_name,'')) ORDER BY sm.id SEPARATOR ' ') FROM staff_members sm WHERE r.sales_rep_ids IS NOT NULL AND r.sales_rep_ids != '' AND FIND_IN_SET(sm.id, r.sales_rep_ids) > 0), '') AS sales_rep_names,
        inst_counts.installation_count, inst_non_edit.installation_count AS staged_installation_count, total_inst_counts.total_installation_count, cop.product_count, rss.service_count, 
        CASE WHEN COALESCE(partial_inst.partial_installation_count, 0) > 0 THEN 1 ELSE 0 END AS partial_install, 
        pc.name AS job_category_name FROM requests r 
        LEFT JOIN project_categories pc ON pc.id = r.project_category 
        LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c 
        left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=${userId} and rml.partner_id=c.partner_id LIMIT 1),0) and c.user_id!=${userId} group by c.request_id) rm ON r.id = rm.request_id 
        LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM request_proposals where status=1 group by request_id) rps ON rps.request_id = r.id 
        left join customer_orders c_ord on c_ord.request_id = r.id 
        left join projects proj on proj.request_id = r.id  AND proj.is_estimate_job = 0
        LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1
        LEFT JOIN request_partners rp ON rp.request_id=r.id
        left join partners p2 on p2.id = c_ord.customer_id 
        left join customer_type ct on p2.customerTypeId = ct.id 
        left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id 
        left join users u2 on u2.id = p2.user_id 
        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 = 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
              GROUP BY co.request_id
            ) rss ON r.id = rss.request_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 installation_count FROM installations WHERE status = 1 GROUP BY request_id) inst_non_edit ON inst_non_edit.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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id) partial_inst ON partial_inst.request_id = r.id 
        LEFT JOIN users u ON r.added_by=u.id WHERE r.id = ${requestId}`;

    const query = await sequelize.query(baseQuery);
    let result = query[0];

    if (result.length >= 1) {
      // Fetch designs and partners in bulk (only for the single request)
      const allDesigns = await FetchAllApprovedDesignsBulk([requestId]);
      const allPartners = await getRequestPartnersBulk(false, [requestId]);

      // Process the result
      const newData = result.map((row) => {
        const designs = allDesigns.filter(d => d.request_id === row.id) || [];
        const filteredDesigns = designs.filter(
          (imageItem) => imageItem?.file_type?.startsWith("image/") || imageItem?.file_type === "img"
        );
        row.thumbnail = filteredDesigns[0]?.name || "";
        row.partners = allPartners.filter(p => p.request_id === row.id) || [];
        return parseDecimalFields(row);
      });

      return {
        data: newData
      };
    } else {
      return { data: [] };
    }
  } catch (error) {
    console.error('Error in getRequestByIdOptimized:', error);
    return { data: [] };
  }
};

const checkExistingProject = async (requestId, is_estimate_job=false) => {
  let whereCondition = ' AND p.is_estimate_job = 0'
  if (is_estimate_job){
    whereCondition = ' AND p.is_estimate_job = 1'
  }
  let query = await sequelize.query(`select p.id from projects p where p.request_id=${requestId} ${whereCondition}`)

  if (query[0].length > 0) {
    return query[0][0].id;
  }
  else {
    return false;
  }
}


// const checkExistingProject = async (requestId, is_estimate_job = false) => {
//   try {
//     // Construct the condition dynamically
//     const condition = {
//       request_id: requestId,
//       is_estimate_job: {
//         [Op.eq]: is_estimate_job ? 1 : 0 // Using Op.eq for equality check
//       }
//     };

//     // Use Sequelize's 'findOne' to execute the query and get the result safely
//     const project = await sequelize.models.Project.findOne({
//       attributes: ['id'],
//       where: condition
//     });

//     // If a project is found, return its id, otherwise return false
//     return project ? project.id : false;
//   } catch (error) {
//     console.error("Error in checkExistingProject:", error);
//     return false;
//   }
// };

const checkExistingEstimateProject = async (requestId) => {
  let query = await sequelize.query(`select p.id from estimate_projects p where p.request_id=${requestId}`)

  if (query[0].length > 0) {
    return query[0][0].id;
  }
  else {
    return false;
  }
}

const checkExistingTask = async (name, project, indexId) => {
  try {

    const query = await sequelize.query(
      'SELECT p.id FROM project_tasks p WHERE p.name LIKE :name AND p.order_id = :indexId AND p.project_id = :project and status!=0',
      {
        replacements: {
          name: `%${name}%`,
          project: project,
          indexId: indexId
        },
        type: sequelize.QueryTypes.SELECT
      }
    );


    if (query.length > 0) {
      return query[0].id;
    } else {
      return false;
    }
  } catch (error) {
    console.error(error);
    return false;
  }
};


const checkExistingSubTask = async (name, project) => {
  try {

    const query = await sequelize.query(
      `SELECT p.id FROM project_subtasks p 
      LEFT JOIN project_tasks pt ON pt.id = p.task_id 
      WHERE p.name = :name  and p.task_id= :project and p.status!=0`,
      {
        replacements: {
          name: name,
          project: project

        },
        type: sequelize.QueryTypes.SELECT
      }
    );

    if (query.length > 0) {
      return query[0].id;
    } else {
      return false;
    }
  } catch (error) {
    console.error(error);
    return false;
  }
};
const getRequestServiceByServiceId = async (requestId, labourCostServiceId) => {
  try {
    const result = await RequestServices.findOne({
      where: { request_id: requestId, labour_cost_service_id: labourCostServiceId, status: 1 }
    });
    return result ? result.get({ plain: true }) : null;
  } catch (error) {
    console.log(error, 'error in getRequestServiceByServiceId');
    return null;
  }
};

const addRequestServices = async (data) => {
  try {
    const result = await RequestServices.create(data)
    if (result) {
      return result.dataValues?.id
    } else {
      return false
    }
  } catch (error) {
    console.log(error, 'error in addRequestServices')
    return false
  }
}
const updateRequestServices = async (data, id, requestId) => {
  console.log('dataaaaaaaaaaaa', data)
  try {
    const result = RequestServices.update(data, {
      where: { id: id, request_id: requestId }
    })
    if (result) {
      return true
    } else {
      return false
    }
  } catch (error) {
    console.log(error, 'error in updateRequestServices')
    return false
  }
}

// Update the service workflow for a specific row in `request_services`.
// This is used by the "Change Workflow" feature for service tasks.
const updateRequestServiceWorkflowById = async (requestServiceId, workflowId) => {
  try {
    const [affectedCount] = await RequestServices.update(
      { workflow: Number(workflowId) },
      { where: { id: Number(requestServiceId) } }
    );
    return affectedCount > 0;
  } catch (error) {
    console.log(error, 'error in updateRequestServiceWorkflowById')
    return false
  }
}

const updateProductRequestServiceStatus = async (request_id) => {
  try {
    const result = await RequestServices.update({status: 0}, {
      where: { request_id: request_id, product_id: { [Sequelize.Op.ne]: null }, labour_cost_service_id: { [Sequelize.Op.ne]: 10 } }
    });
    return true; // Return true if rows were affected
  } catch (error) {
    console.log(error, 'error in updateProductRequestServiceStatus');
    return false;
  }
}

const updateRequestServiceStatus = async (id, status) => {
  try {
    const result = await RequestServices.update({status: 0}, {
      where: { id: id }
    });
    return true; // Return true if rows were affected
  } catch (error) {
    console.log(error, 'error in updateRequestServiceStatus');
    return false;
  }
}

const deleteRequestServicesById = async (id) => {
  try {
    const result = await RequestServices.destroy({
      where: { id: id }
    });
    return true; // Return true if rows were affected
  } catch (error) {
    console.log(error, 'error in deleteRequestServicesById');
    return false;
  }
}
const deleteRequestServices = async (id) => {
  try {
    const result = RequestServices.destroy({
      where: { request_id: id }
    })
    console.log("#####################RRRRR", result);
    if (result) {
      return true
    } else {
      return false
    }
  } catch (error) {
    console.log(error, 'error in deleteRequestServices')
    return false
  }
}
const deleteRequestServicesWithoutRecipe = async (id) => {
  try {
    const result = RequestServices.destroy({
      where: { request_id: id, recipe_id: null, job_cost: 1 }
    })
    console.log("#####################RRRRR", result);
    if (result) {
      return true
    } else {
      return false
    }
  } catch (error) {
    console.log(error, 'error in deleteRequestServices')
    return false
  }
}

const deleteRequestServicesWithRequestId = async (id) => {
  try {
    const result =await RequestServices.destroy({
      where: { request_id: id }
    })
    console.log("djhjdhsdjsdhkhdsh", result);
    if (result) {
      return true
    } else {
      return false
    }
  } catch (error) {
    console.log(error, 'error in deleteRequestServices')
    return false
  }
}

const getRequestServices = async (id, serviceId = false, productId = false, productIndex = false,projectCategory) => {
  try {
    let whereCondition = ''
    if (serviceId) {
      whereCondition += ` AND rs.labour_cost_service_id=${serviceId} `
    }
    if (productId) {
      whereCondition += ` AND rs.product_id=${productId} `
    }
    if (productIndex) {
      whereCondition += ` AND rs.product_index='${productIndex}' `
    }
    if (projectCategory == 12) {
      whereCondition += ``
    }else{
      whereCondition += ` AND rs.from_job = 0 `
    }
    whereCondition += ` AND (rs.recipe_id IS NULL) `
    
    const result = await sequelize.query(`SELECT DISTINCT rs.*,ls.inhouse,ls.taxCode,ls.makeAsTask AS makeAsTask_lcs,ls.makeInstallCard AS makeInstallCard_lcs,i.id AS installation_id,ls.quickbookId,it.status AS published_status,i.installation_temp_id,ct.name as installation_temp_name,i.location_id,sr.quantity AS prQty,rs.qty AS quantity,ls.name,ls.quickbookId, ls.avatarUrl AS service_image, ls.cost,ls.total_cost AS service_original_cost,ls.markup as originalMarkup,ls.service_type, rsl.city, rsl.address, rsl.state, rsl.zip , rsl.lat, rsl.lng,rsl.id AS req_loc_id,
      rsl.starting_point, rsl.ending_point,rsl.color,ls.syncWithQuickbooks,i.complete_status as installation_status
      FROM request_services rs 
      LEFT JOIN labour_cost_services ls ON ls.id = rs.labour_cost_service_id
      LEFT JOIN request_service_locations rsl ON rsl.service_id = rs.id
      left join installations i on i.location_id = rsl.id and i.labour_cost_service_id IS NOT NULL
      LEFT JOIN custom_field_templates ct on ct.id = i.installation_temp_id
      LEFT JOIN installation_temp_fields it on it.template_id=i.installation_temp_id and it.installation_id = i.id
      left JOIN services_recipe sr ON sr.recipe_id = rs.recipe_id and sr.service_id = rs.labour_cost_service_id 
       WHERE rs.request_id=${id} ${whereCondition} GROUP BY rs.id, rsl.id ORDER BY rs.id ASC`)
    if (result[0]?.length > 0) {
      return result[0]
    } else {
      return []
    }
  } catch (error) {
    console.log(error, 'error in getRequestServices')
    return false
  }
}

const getRequestServiceById = async (id) => {
  try {
    const result = await RequestServices.findOne({ where: { id: id } });
    console.log("result", result);
    return result;
  } catch (error) {
    console.log(error, 'error in getRequestServiceById');
    return false;
  }
}
const getRequestServicesNew = async (_id_, _serviceId_ = false, _productId_ = false, _productIndex_ = false, _projectCategory_) => {
  try {
  let whereCondition = '';
  const replacements = { requestId: _id_ };
   
  if (_serviceId_) {
  whereCondition += ' AND rs.labour_cost_service_id = :serviceId';
  replacements.serviceId = _serviceId_;
  }
  if (_productId_) {
  whereCondition += ' AND rs.product_id = :productId';
  replacements.productId = _productId_;
  }
  if (_productIndex_) {
  whereCondition += ' AND rs.product_index = :productIndex';
  replacements.productIndex = _productIndex_;
  }
  if (_projectCategory_ != 12) {
  whereCondition += ' AND rs.from_job = 0';
  }
   
  const query = `
  SELECT DISTINCT
  rs.*,
  ls.inhouse,
  ls.taxCode,
  ls.makeAsTask AS makeAsTask_lcs,
  ls.makeInstallCard AS makeInstallCard_lcs,
  i.id AS installation_id,
  ls.quickbookId,
  it.status AS published_status,
  i.installation_temp_id,
  ct.name AS installation_temp_name,
  i.location_id,
  sr.quantity AS prQty,
  rs.qty AS quantity,
  ls.name,
  ls.quickbookId,
  ls.avatarUrl AS service_image,
  ls.cost,
  ls.total_cost AS service_original_cost,
  ls.markup AS originalMarkup,
  ls.service_type,
  rsl.city,
  rsl.address,
  rsl.state,
  rsl.zip,
  rsl.lat,
  rsl.lng,
  rsl.id AS req_loc_id,
  rsl.starting_point,
  rsl.ending_point,
  rsl.color
  FROM request_services rs
  LEFT JOIN labour_cost_services ls ON ls.id = rs.labour_cost_service_id
  LEFT JOIN request_service_locations rsl ON rsl.service_id = rs.id
  LEFT JOIN installations i ON i.location_id = rsl.id
  LEFT JOIN custom_field_templates ct ON ct.id = i.installation_temp_id
  LEFT JOIN installation_temp_fields it ON it.template_id = i.installation_temp_id AND it.installation_id = i.id
  LEFT JOIN services_recipe sr ON sr.recipe_id = rs.recipe_id AND sr.service_id = rs.labour_cost_service_id
  WHERE rs.request_id = :requestId
  ${whereCondition}
  ORDER BY rs.id ASC
  `;
   
  const result = await sequelize.query(query, {
  replacements,
  type: sequelize.QueryTypes.SELECT,
  });
   
  return result.length ? result : [];
  } catch (error) {
  console.error(error, 'error in getRequestServices');
  return false;
  }
};

const getSplitRequestServices = async (id, serviceId = false, productId = false, productIndex = false,projectCategory) => {
  try {
    let whereCondition = ''
    if (serviceId) {
      whereCondition += ` AND rs.labour_cost_service_id=${serviceId} `
    }
    if (productId) {
      whereCondition += ` AND rs.product_id=${productId} `
    }
    if (productIndex) {
      whereCondition += ` AND rs.product_index='${productIndex}' `
    }
    if (projectCategory == 12) {
      whereCondition += ``
    }else{
      whereCondition += ` AND rs.from_job = 0 `
    }
    
    const currentFacility = FACILITY_ID;
    const installations = getOtherInstallationDatabases();
    
    // Helper functions
    const getDbByFacilityId = (fid) => installations.find((db) => Number(db.id) === Number(fid));
    const getDbNameByWhich = (whichDb) => {
      if (whichDb === 'local') return '';
      const db = installations.find((d) => d.name === whichDb);
      return db?.database_name || '';
    };
    
    // Build whereCondition for initial query (without rs. prefix)
    let initialWhereCondition = '';
    if (serviceId) {
      initialWhereCondition += ` AND labour_cost_service_id=${serviceId} `
    }
    if (productId) {
      initialWhereCondition += ` AND product_id=${productId} `
    }
    if (productIndex) {
      initialWhereCondition += ` AND product_index='${productIndex}' `
    }
    if (projectCategory == 12) {
      initialWhereCondition += ``
    }else{
      initialWhereCondition += ` AND from_job = 0 `
    }
    
    // 1) Get all request_services with facility_id
    const rsRowsResult = await sequelize.query(
      `SELECT id, facility_id FROM request_services WHERE request_id = ${id} ${initialWhereCondition}`,
      { type: sequelize.QueryTypes.SELECT }
    );
    
    if (!rsRowsResult || rsRowsResult.length === 0) return [];
    
    // Helper to normalize facility_id (treat null/0 as current)
    const norm = (fid) => (fid == null || fid === 0 ? currentFacility : Number(fid));
    
    // 2) Partition rows into groups by where the labour_cost_services data should be read from
    const groupMap = new Map(); // whichDb => [ids]
    
    for (const r of rsRowsResult) {
      const fid = norm(r.facility_id);
      const whichDb = (fid === currentFacility)
        ? 'local'
        : (getDbByFacilityId(fid)?.name || 'local');
      if (!groupMap.has(whichDb)) groupMap.set(whichDb, []);
      groupMap.get(whichDb).push(r.id);
    }
    
    // 3) Build a reusable group query with the right cross-DB joins
    const runGroupQuery = async (ids, whichDb) => {
      if (!ids.length) return [];
      
      const placeholders = ids.map(() => '?').join(',');
      
      // First get request_services data with all local joins
      const baseSql = `SELECT DISTINCT rs.*, rsl.city, rsl.address, rsl.state, rsl.zip , rsl.lat, rsl.lng, rsl.id AS req_loc_id,
        rsl.starting_point, rsl.ending_point, rsl.color, i.id AS installation_id, i.installation_temp_id, i.location_id,
        ct.name as installation_temp_name, it.status AS published_status
        FROM request_services rs 
        LEFT JOIN request_service_locations rsl ON rsl.service_id = rs.id
        left join installations i on i.location_id = rsl.id
        LEFT JOIN custom_field_templates ct on ct.id = i.installation_temp_id
        LEFT JOIN installation_temp_fields it on it.template_id=i.installation_temp_id and it.installation_id = i.id
         WHERE rs.id IN (${placeholders}) GROUP BY rs.id, rsl.id ORDER BY rs.id ASC`;
      
      const baseResult = await sequelize.query(baseSql, {
        type: sequelize.QueryTypes.SELECT,
        replacements: ids
      });
      
      if (!baseResult || baseResult.length === 0) return [];
      
      // Get unique labour_cost_service_ids and recipe_ids
      const labourCostServiceIds = [...new Set(baseResult.map(r => r.labour_cost_service_id).filter(Boolean))];
      const recipeServicePairs = baseResult
        .filter(r => r.labour_cost_service_id && r.recipe_id)
        .map(r => ({ recipe_id: r.recipe_id, service_id: r.labour_cost_service_id }));
      
      // Fetch labour_cost_services and services_recipe from appropriate database
      let labourCostMap = {};
      let recipeMap = {};
      
      if (whichDb === 'local') {
        // Use current database
        if (labourCostServiceIds.length > 0) {
          const lcsSql = `SELECT * FROM labour_cost_services WHERE id IN (${labourCostServiceIds.join(',')})`;
          const lcsResult = await sequelize.query(lcsSql, { type: sequelize.QueryTypes.SELECT });
          labourCostMap = {};
          for (const lcs of lcsResult) {
            labourCostMap[lcs.id] = lcs;
          }
        }
        
        if (recipeServicePairs.length > 0) {
          const recipeConditions = recipeServicePairs.map(
            p => `(recipe_id = ${p.recipe_id} AND service_id = ${p.service_id})`
          ).join(' OR ');
          const recipeSql = `SELECT recipe_id, service_id, quantity AS prQty FROM services_recipe WHERE ${recipeConditions}`;
          const recipeResult = await sequelize.query(recipeSql, { type: sequelize.QueryTypes.SELECT });
          recipeMap = {};
          for (const recipe of recipeResult) {
            const key = `${recipe.recipe_id}_${recipe.service_id}`;
            recipeMap[key] = recipe.prQty;
          }
        }
      } else {
        // Use other facility database connection
        const targetDb = installations.find(d => d.name === whichDb);
        if (targetDb && targetDb.connection) {
          if (labourCostServiceIds.length > 0) {
            const lcsSql = `SELECT * FROM labour_cost_services WHERE id IN (${labourCostServiceIds.join(',')})`;
            const lcsQueryResult = await targetDb.connection.query(lcsSql);
            const lcsResult = lcsQueryResult[0] || [];
            labourCostMap = {};
            for (const lcs of lcsResult) {
              labourCostMap[lcs.id] = lcs;
            }
          }
          
          if (recipeServicePairs.length > 0) {
            const recipeConditions = recipeServicePairs.map(
              p => `(recipe_id = ${p.recipe_id} AND service_id = ${p.service_id})`
            ).join(' OR ');
            const recipeSql = `SELECT recipe_id, service_id, quantity AS prQty FROM services_recipe WHERE ${recipeConditions}`;
            const recipeQueryResult = await targetDb.connection.query(recipeSql);
            const recipeResult = recipeQueryResult[0] || [];
            recipeMap = {};
            for (const recipe of recipeResult) {
              const key = `${recipe.recipe_id}_${recipe.service_id}`;
              recipeMap[key] = recipe.prQty;
            }
          }
        }
      }
      
      // Merge labour_cost_services data with request_services
      const mergedResults = baseResult.map(rs => {
        const lcs = labourCostMap[rs.labour_cost_service_id];
        const recipeKey = rs.recipe_id && rs.labour_cost_service_id 
          ? `${rs.recipe_id}_${rs.labour_cost_service_id}` 
          : null;
        const prQty = recipeKey ? (recipeMap[recipeKey] || null) : null;

        const costWithOutgoing = lcs?.cost + (lcs?.cost * (rs?.split_percentage / 100))
        
        return {
          ...rs,
          inhouse: lcs?.inhouse || null,
          taxCode: lcs?.taxCode || null,
          makeAsTask_lcs: lcs?.makeAsTask || null,
          makeInstallCard_lcs: lcs?.makeInstallCard || null,
          quickbookId: lcs?.quickbookId || null,
          name: lcs?.name || null,
          service_image: lcs?.avatarUrl || null,
          cost: lcs?.cost || null,
          service_original_cost: lcs?.total_cost || null,
          originalMarkup: lcs?.markup || null,
          service_type: lcs?.service_type || null,
          quantity: rs.qty || null,
          prQty: prQty,
          costWithOutgoing : costWithOutgoing
        };
      });
      
      return mergedResults;
    };
    
    // 4) Run queries for each group and combine results
    const allResults = [];
    for (const [whichDb, ids] of groupMap.entries()) {
      const groupResults = await runGroupQuery(ids, whichDb);
      allResults.push(...groupResults);
    }
    
    // Sort by id to maintain original order
    allResults.sort((a, b) => a.id - b.id);
    
    return allResults;
  } catch (error) {
    console.log(error, 'error in getRequestServices')
    return false
  }
}

const getSingleRequestService10 = async (requestId) => {
  try {
    const [rows] = await sequelize.query(
      `
      SELECT DISTINCT
        rs.*, ls.inhouse, ls.taxCode, ls.makeAsTask AS makeAsTask_lcs,
        ls.makeInstallCard AS makeInstallCard_lcs, i.id AS installation_id,
        ls.quickbookId, it.status AS published_status, i.installation_temp_id,
        ct.name as installation_temp_name, i.location_id, sr.quantity AS prQty,
        rs.qty AS quantity, ls.name, ls.quickbookId, ls.avatarUrl AS service_image,
        ls.cost, ls.total_cost AS service_original_cost, ls.markup as originalMarkup,
        ls.service_type, rsl.city, rsl.address, rsl.state, rsl.zip, rsl.lat, rsl.lng,
        rsl.id AS req_loc_id, rsl.starting_point, rsl.ending_point, rsl.color
      FROM request_services rs
      LEFT JOIN labour_cost_services ls ON ls.id = rs.labour_cost_service_id
      LEFT JOIN request_service_locations rsl ON rsl.service_id = rs.id
      LEFT JOIN installations i ON i.location_id = rsl.id
      LEFT JOIN custom_field_templates ct ON ct.id = i.installation_temp_id
      LEFT JOIN installation_temp_fields it ON it.template_id = i.installation_temp_id
                                           AND it.installation_id = i.id
      LEFT JOIN services_recipe sr ON sr.recipe_id = rs.recipe_id
                                   AND sr.service_id = rs.labour_cost_service_id
      WHERE rs.request_id = :requestId
        AND rs.labour_cost_service_id = 10
      ORDER BY rs.id ASC
      LIMIT 1
      `,
      { replacements: { requestId } }
    );

    return rows?.[0] || null; 
  } catch (error) {
    console.error('error in getSingleRequestService10:', error);
    return null;
  }
};


const getAllRecipeRequestServices = async (id, serviceId = false, productId = false, productIndex = false) => {
  try {
    let whereCondition = 'AND rs.recipe_id IS NOT NULL AND rs.labour_cost_service_id != 10'; // 👈 Add this line
    if (serviceId) {
      whereCondition += ` AND rs.labour_cost_service_id=${serviceId} `;
    }
    if (productId) {
      whereCondition += ` AND rs.product_id=${productId} `;
    }
    if (productIndex) {
      whereCondition += ` AND rs.product_index='${productIndex}' `;
    }

    const result = await sequelize.query(`
      SELECT DISTINCT rs.*, ls.makeAsTask AS makeAsTask_lcs, ls.makeInstallCard AS makeInstallCard_lcs,
        i.id AS installation_id, ls.quickbookId, it.status AS published_status, i.installation_temp_id,
        ct.name as installation_temp_name, i.location_id, sr.quantity AS prQty, rs.qty AS quantity,
        ls.name, ls.quickbookId, ls.avatarUrl AS service_image, ls.cost, ls.total_cost AS service_original_cost,
        ls.markup as originalMarkup, ls.service_type, rsl.city, rsl.address, rsl.state, rsl.zip, rsl.lat, rsl.lng,
        rsl.id AS req_loc_id, rsl.starting_point, rsl.ending_point, rsl.color
      FROM request_services rs 
      LEFT JOIN labour_cost_services ls ON ls.id = rs.labour_cost_service_id
      LEFT JOIN request_service_locations rsl ON rsl.service_id = rs.id
      LEFT JOIN installations i ON i.location_id = rsl.id
      LEFT JOIN custom_field_templates ct ON ct.id = i.installation_temp_id
      LEFT JOIN installation_temp_fields it ON it.template_id = i.installation_temp_id AND it.installation_id = i.id
      LEFT JOIN services_recipe sr ON sr.recipe_id = rs.recipe_id AND sr.service_id = rs.labour_cost_service_id 
      WHERE rs.request_id = ${id} ${whereCondition}
    `);

    return result[0]?.length > 0 ? result[0] : [];
  } catch (error) {
    console.log(error, 'error in getRequestServices');
    return false;
  }
};

const updateAllRecipesTakenByRequestId = async (requestId) => {
  try {
    const result = await sequelize.query(
      `UPDATE request_services 
        SET taken = 1 
        WHERE request_id = :requestId AND recipe_id IS NOT NULL AND labour_cost_service_id != 10`,
      {
        replacements: { requestId },
        type: sequelize.QueryTypes.UPDATE
      }
    );
    return result;
  } catch (error) {
    console.error('❌ Error updating all recipes to taken=1:', error);
    return false;
  }
}

const getAllServiceByRequest = async (requestId) => {
  let query = await sequelize.query(`select rs.*,l.name,l.cost as originalCost,l.service_type from request_services rs`
    + ` left join labour_cost_services l on l.id=rs.labour_cost_service_id `
    + ` where rs.request_id=${requestId}`
  )
  let data = [];
  if (query[0].length > 0) {
    data = query[0]
  }
  return data;
}
const getProjectExisting = async (request_id, isEstimateJob = false) => {
  let whereCondition = ' AND is_estimate_job=0'
  if (isEstimateJob){
    whereCondition = ' AND is_estimate_job=1'
  }
  let query = await sequelize.query(` select * from projects  where request_id=${request_id} ${whereCondition}`)

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


const updateCardOrder = async (cards) => {
  if (!cards || !cards.length) {
    return false;
  }
  try {
    const updatePromises = cards.map((card, index) => {
      return Requests.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 findTotalPaidAmount = async (requestId) => {
  try {
    const query = `
      SELECT SUM(amount) AS totalAmount
      FROM request_payments
      WHERE request_id = :requestId AND status = 1;
    `;

    const [results] = await sequelize.query(query, {
      replacements: { requestId },
      type: sequelize.QueryTypes.SELECT,
    });

    return results.totalAmount || 0; // Default to 0 if no result or totalAmount is null
  } catch (error) {
    console.error('Error fetching total paid amount:', error);
    return false;
  }
};


const editRequestTable = async (id, updatedData) => {
  try {
    const result = await Requests.update(updatedData, {
      where: { id },
    });

    if (result[0] === 1) {
      return { message: 'Requests  updated successfully' };
    } else {
      return { message: 'Requests not found or no changes made' };
    }
  } catch (error) {
    console.error('Error editing customer type:', error);
    throw error;
  }
};

const addDesignOrders = async (data) => {
  try{
    let res = await DesignOrders.create(data);
    return res.id;
  }catch(error){
    console.log('Error : ',error);
    return error
  }
}

const addEmail = async (data) => {
  try{
    let res = await emails.create(data);
    return res.id;
  }catch(error){
    console.log('Error : ',error);
    return error
  }
}
const getEmails = async () => {
  try{
    let res = await emails.findAll();
    return res;
  }catch(error){
    console.log('Error : ',error);
    return error
  }
}
const updateDesignOrders = async (id, data) => {
  try{
    let result = await DesignOrders.update(data, {
      where: { id: id }
    })
    if (result[0] > 0) {
      return true;
    } else {
      return false;
    }
  }catch(error){
    console.log('Error : ',error);
    return error
  }
}
// const addDesignOrderCount = async (data) => {
//   try {
//     const newOrderCount = await DesignOrderCount.create(data);
//     return newOrderCount.id;
//   } catch (error) {
//     console.error('Failed to add design order count:', error);
//     throw error;
//   }
// }
const addDesignOrderCount = async (data) => {
  try {
    const [newOrderCount, created] = await DesignOrderCount.findOrCreate({
      where: { user_id: data.user_id },
      defaults: { 
        open_count: 0,
        approved_count: 0,
        rejected_count: 0,
        hold_count: 0,
        open_count_ids: data.open_count_ids,
        approved_count_ids: null,
        rejected_ids: null,
        hold_count_ids: null,
        timestamp: data.timestamp
      }
    });

    return newOrderCount.id;
  } catch (error) {
    console.error('Failed to add design order count:', error);
    throw error;
  }
};

const updateDesignOrderCount = async (userId, data) => {
  try{
    let result = await DesignOrderCount.update(data, {
      where: { user_id: userId }
    })
    if (result[0] > 0) {
      return true;
    } else {
      return false;
    }
  }catch(error){
    console.log('Error : ',error);
    return error
  }
}
const getDesignOrderCountByUserId = async (userId) => {
  try {
    const orderCount = await DesignOrderCount.findOne({
      where: { user_id: userId },
      attributes: ['id']
    });

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

    if (orderCount) {
      return orderCount;
    } else {
      return "No record found";
    }
  } catch (error) {
    console.error('Error retrieving design order count:', error);
    return error;
  }
}
// const designCountIncrementField = async (userId, field, amount) => {
//   try {
//     const result = await DesignOrderCount.update(
//       { [field]: sequelize.literal(`${field} + ${amount}`) },
//       { 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 incrementing field:", error.message);
//     console.error("Error updating field:", error);
//   }
// };
const designCountIncrementField = async (userId, field, amount, fieldIds, designOrderId, increase = true) => {
  console.log("designCountIncrementField")
  try {
    const userCount = await DesignOrderCount.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(designOrderId.toString())) {
        console.warn(`Design order ID not found in ${fieldIds}, cannot reduce count.`);
        return false;
      }
    }

    // if (increase) {
    //   if (!currentIds.includes(designOrderId.toString())) {
    //     currentIds.push(designOrderId.toString());
    //   }
    // } else {

    //   currentIds = currentIds.filter(id => id !== designOrderId.toString());
    // }
    if (increase) {
      if (!currentIds.includes(designOrderId.toString())) {
        currentIds.push(designOrderId.toString());
        amount = 1;
      } else {
        console.warn(`Design order ID ${designOrderId} already exists in ${fieldIds}, count remains the same.`);
        amount = 0;
      }
    } else {

      currentIds = currentIds.filter(id => id !== designOrderId.toString());
    }
    const fieldUpdate = sequelize.literal(`GREATEST(${field} + (${amount}), 0)`);
    
    const result = await DesignOrderCount.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 getDesignCountByUser = async (userId) => {
  let res = await DesignOrderCount.findOne({
    where: { user_id: userId, status: 1 }
  })
  return res;
}

const addDesignOrderAttachments = async (data) => {
  try{
    let res = await DesignOrderAttachments.create(data);
    return res.id;
  }catch(error){
    console.log('Error : ',error);
    return error
  }
}

const addDesignOrderRejectedFiles = async (data) => {
  try {
    const res = await DesignOrderRejectedFiles.bulkCreate(data);
    return res.map(r => r.id); // returns inserted IDs
  } catch (error) {
    console.log('Error : ', error);
    throw error;
  }
};

const deleteDesignOrderAttachment = async (id) => {
  try {
    const deleted = await DesignOrderAttachments.destroy({
      where: { id }
    });

    if (deleted === 0) {
      console.log(`No attachment found with id ${id}`);
      return false;
    }

    return true;
  } catch (error) {
    console.log('Error while deleting attachment:', error);
    return error;
  }
};

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

const updateMultipleDesignOrderAttachments = async (idArray, data) => {
  try {
    if (!Array.isArray(idArray) || idArray.length === 0) {
      console.warn('No design IDs provided for bulk update.');
      return false;
    }    
    const result = await DesignOrderAttachments.update(data, {
      where: {
        id: { [Sequelize.Op.in]: idArray }
      }
    });
    if (result[0] > 0) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.log('Error:', error);
    return error;
  }
};

const deleteDesignOrderAttachments = async (design_order_id) => {
  try{
    let result = await DesignOrderAttachments.destroy({
      where: { design_order_id: design_order_id }
    })
    if (result[0] > 0) {
      return true;
    } else {
      return false;
    }
  }catch(error){
    console.log('Error : ',error);
    return error
  }
}

const deleteDesignOrderAttachmentsBulk=async(ids)=>{
  let deleted=await sequelize.query(`delete from design_order_attachments where id in (${ids.join()})`)
  if (deleted) {
      return deleted;
  }
  else {
      return false;
  }
}

const updateDesignOrderCardOrder = async (cards) => {
  if (!cards || !cards.length) {
    return false;
  }
  try {
    const updatePromises = cards.map((card, index) => {
      return DesignOrders.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 checkIfUserIsClient = async (userType) => {
  try {
    if (!userType) return false;

    const [results] = await sequelize.query(
      "SELECT isClientUserRole FROM user_roles WHERE id = :userType",
      { replacements: { userType }, type: sequelize.QueryTypes.SELECT }
    );

    return results?.isClientUserRole === 1;
  } catch (error) {
    console.error("Error checkIfUserIsClient:", error);
    throw new Error("Error checking if user is client");
  }
};

const getAllDesignOrders = async (orderId, userId, userType,isClient,page,rowPerpage,search,where='',sort,fromDate,toDate, dueData,filterClient,filterProject) => {
  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 d.due_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
    } else if (fromTimestamp) {
      dateCondition = `AND d.due_date >= ${fromTimestamp}`;
    } else if (toTimestamp) {
      dateCondition = `AND d.due_date <= ${toTimestamp}`;
    }
    
    let createdAt = ''
    if (dueTimestamp) {
      createdAt=`ORDER BY d.due_date ASC`
    }else{
      if(sort==='new'){
        createdAt = `ORDER BY d.id DESC `
      }else if(sort==='old'){
          createdAt = `ORDER BY d.id ASC `
      }else if(sort === 'custom_order'){
      createdAt=`ORDER BY d.card_order ASC`
      }else{
        createdAt=`ORDER BY d.timestamp DESC`
      }
    }

    let offset = null
    if(rowPerpage && page){
     offset = (page - 1) * rowPerpage;
    }
    let totalCount=0
    let openCount=0
    let acceptedCount=0
    let rejectedCount=0
    let holdCount=0
    let allCount=0

    let query = '';
    let content = ''
    // if(search){
    //     content=`and d.name LIKE '%${search}%'`
    // }
    //previos one 09/09/25
    // if (search) {
    //   const escapedSearch = search.replace(/'/g, "''").trim();
    //   const normalizedSearch = escapedSearch.toLowerCase();
    
    //   content = `AND (
    //        CAST(d.id AS CHAR) LIKE '%${escapedSearch}%'
    //     OR LOWER(COALESCE(d.name, '')) LIKE '%${normalizedSearch}%'
    //     OR LOWER(COALESCE(d.description, '')) LIKE '%${normalizedSearch}%'
    //     OR LOWER(COALESCE(pt.name, '')) LIKE '%${normalizedSearch}%`;
    
    //   if (userType !== 3 && !isClient) {
    //     content += ` OR LOWER(COALESCE(com.name, '')) LIKE '%${normalizedSearch}%'`;
    //   }
    
    //   content += `)`;
    // }    
    if (search) {
      const escapedSearch = search.replace(/'/g, "''").trim();
      const normalizedSearch = escapedSearch.toLowerCase();
      const searchNoHash = normalizedSearch.replace(/^#/, ''); 
      content = `AND (
           CAST(d.id AS CHAR) LIKE '%${searchNoHash}%'
        OR LOWER(COALESCE(d.name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(d.description, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(pt.name, '')) LIKE '%${normalizedSearch}%'
      `;
    
      if (userType !== 3 && !isClient) {
        content += ` OR LOWER(COALESCE(com.name, '')) LIKE '%${normalizedSearch}%'`;
      }
    
      content += `)`;
    }
    
    // if (search) {
    //   const escapedSearch = search.replace(/'/g, "''").trim();
    //   const normalizedSearch = escapedSearch.toLowerCase().replace(/["'/\-]/g, '').replace(/\s+/g, '');
    
    //   // Constructing the match condition
    //   content = `AND (REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LOWER(d.description), '"', ''), '/', ''), '-', ''), ' ', ''), '''', '') LIKE '%${normalizedSearch}%')`;
      
    //   // content = `AND (REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LOWER(d.name), '"', ''), '/', ''), '-', ''), ' ', ''), '''', '') LIKE '%${normalizedSearch}%' 
    //   //           OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LOWER(d.description), '"', ''), '/', ''), '-', ''), ' ', ''), '''', '') LIKE '%${normalizedSearch}%')`;
    // }
    let WhereCondition = ''
    if (orderId) {
      WhereCondition = ` d.id=${orderId}`
    }
    else {
      // WhereCondition = ` d.status <>0  and d.status<>8 ${dateCondition}`
      WhereCondition = ` d.status NOT IN (0, 3, 8) ${dateCondition}`
      if(!empty(where)){
        WhereCondition=` ${where} ${dateCondition}`
      }
    }
    let clientCondition = '';
    if (filterClient && filterClient.length > 0) {
      clientCondition = ` AND d.client IN (${filterClient.join(',')}) `;
    }

    let projectCondition = '';
    if (filterProject && filterProject.length > 0) {
      if (filterProject.includes('other')) {
        // Filter for projects with null community or specific project IDs
        const projectIds = filterProject.filter(id => id !== 'other');
        if (projectIds.length > 0) {
          projectCondition = ` AND (d.community IS NULL OR d.community IN (${projectIds.join(',')})) `;
        } else {
          projectCondition = ` AND d.community IS NULL `;
        }
      } else {
        projectCondition = ` AND d.community IN (${filterProject.join(',')}) `;
      }
    }

    let limit = ''
    if(rowPerpage){
      limit = `LIMIT ${rowPerpage} OFFSET ${offset}`
    }
    const designerCondition = ` AND (d.working_designer_id IS NULL OR d.working_designer_id = ${userId} OR d.added_by = ${userId}) `;
    const collaboratorCondition = ` AND (d.collaborators IS NULL OR d.collaborators LIKE '%${userId}%' OR d.added_by = ${userId}) `;

    if (userType == 1 || userType == 8) {
      query = await sequelize.query(`SELECT d.*, d.created_at, com.name AS community_name,d.added_by AS added_by, `
        + ` CONCAT(u1.first_name," ", u1.last_name) as customer_name, `
        + ` CONCAT(
              IFNULL(pt.address, ''), 
              IFNULL(CONCAT(', ', pt.city), ''), 
              IFNULL(CONCAT(', ', st.name), ''), 
              IFNULL(CONCAT(', ', pt.zip_code), '')
            ) AS customer_address, `
        + ` pt.phone AS customer_phone, `
        + ` CONCAT(u.first_name," ", u.last_name) as added_by_name,u.user_type AS added_by_user_type, u1.profile_pic AS added_by_profile_pic,u1.profile_pic AS customer_pic, COALESCE(COUNT(doa.id), 0) AS attachment_count,
             COALESCE(COUNT(doar.id), 0) AS reference_attachment_count,
             MIN(CASE WHEN doa.isNew = 1 THEN 1 ELSE 2 END) AS isNewDesigns, r.id AS converted_design_request_id, odo.name AS old_design_order_name, ro.quotation AS quotation, ro.is_request_estimate AS is_request_estimate FROM design_orders d `
        + ` JOIN partners pt ON d.client = pt.id `
        + ` LEFT JOIN states st ON pt.state_id = st.id `
        + ` JOIN users u1 ON pt.user_id = u1.id `
        + ` JOIN users u ON d.added_by = u.id `
        + ` LEFT JOIN community com ON com.id = d.community `
        + ` LEFT JOIN design_order_attachments doa ON doa.design_order_id = d.id AND doa.is_reference = 0`
        + ` LEFT JOIN design_order_attachments doar ON doar.design_order_id = d.id AND doar.is_reference = 1`
        + ` LEFT JOIN design_orders odo ON odo.id = d.old_design_order_id`
        + ` LEFT JOIN requests r ON r.design_order_id = d.id`
        + ` LEFT JOIN requests ro on ro.design_order_id = d.old_design_order_id`
        + ` WHERE ${WhereCondition} ${clientCondition} ${projectCondition} ${content} GROUP BY d.id ${createdAt} ${limit}`)
         
        totalCount = await sequelize.query(`SELECT count(DISTINCT d.id) AS totalCount FROM design_orders d 
          JOIN partners pt ON d.client = pt.id 
          LEFT JOIN states st ON pt.state_id = st.id 
          JOIN users u1 ON pt.user_id = u1.id 
          JOIN users u ON d.added_by = u.id 
          LEFT JOIN community com ON com.id = d.community 
          LEFT JOIN design_order_attachments doa ON doa.design_order_id = d.id AND doa.is_reference = 0
          WHERE ${WhereCondition} ${clientCondition} ${projectCondition} ${content}`);
        
      // acceptedCount = await sequelize.query(`SELECT count(d.id) AS acceptedCount FROM design_orders d `
      //   + ` WHERE d.status=2 AND d.hold=0`)
      // openCount = await sequelize.query(`SELECT count(d.id) AS openCount FROM design_orders d `
      //   + ` WHERE d.status=1 AND d.hold=0`)
      // rejectedCount = await sequelize.query(`SELECT count(d.id) AS rejectedCount FROM design_orders d `
      //   + ` WHERE d.status=6 AND d.hold=0 ${clientCondition}`)
      rejectedCount = await sequelize.query(`SELECT count(d.id) AS rejectedCount FROM design_orders d 
        JOIN partners pt ON d.client = pt.id 
        LEFT JOIN states st ON pt.state_id = st.id 
        JOIN users u1 ON pt.user_id = u1.id 
        JOIN users u ON d.added_by = u.id 
        LEFT JOIN community com ON com.id = d.community 
        WHERE d.status=6 AND d.hold=0 ${clientCondition} ${projectCondition}`)
      // holdCount = await sequelize.query(`SELECT count(d.id) AS holdCount FROM design_orders d `
      //   + ` WHERE d.hold=1`)
      // allCount = await sequelize.query(`SELECT count(d.id) AS allCount FROM design_orders d `
      //   + ` WHERE  d.status NOT IN (0, 3, 8)`)
    }else if (userType == 3 || isClient) {
      query = await sequelize.query(`SELECT d.*, d.created_at, `
        + ` CONCAT(u1.first_name," ", u1.last_name) as customer_name,com.name AS community_name,u1.profile_pic AS added_by_profile_pic,u1.profile_pic AS customer_pic,d.added_by AS added_by_id, `
        + ` CONCAT(
              IFNULL(pt.address, ''), 
              IFNULL(CONCAT(', ', pt.city), ''), 
              IFNULL(CONCAT(', ', st.name), ''), 
              IFNULL(CONCAT(', ', pt.zip_code), '')
            ) AS customer_address, `
        + ` pt.phone AS customer_phone, `
        + ` COALESCE(COUNT(doar.id), 0) AS reference_attachment_count, `
        + ` CONCAT(u.first_name," ", u.last_name) as added_by,u.user_type AS added_by_user_type, COALESCE(COUNT(doa.id), 0) AS attachment_count, r.id AS converted_design_request_id, odo.name AS old_design_order_name, ro.quotation AS old_design_order_request_quotation, ro.is_request_estimate AS old_design_order_request_is_request_estimate FROM design_orders d `
        + ` JOIN partners pt ON d.client = pt.id `
        + ` LEFT JOIN states st ON pt.state_id = st.id `
        + ` JOIN users u1 ON pt.user_id = u1.id `
        + ` JOIN users u ON d.added_by = u.id `
        + ` LEFT JOIN community com ON com.id = d.community`
        + ` LEFT JOIN design_order_attachments doa ON doa.design_order_id = d.id AND doa.is_reference = 0`
        + ` LEFT JOIN design_order_attachments doar ON doar.design_order_id = d.id AND doar.is_reference = 1`
        + ` LEFT JOIN design_orders odo ON odo.id = d.old_design_order_id`
        + ` LEFT JOIN requests r ON r.design_order_id = d.id`
        + ` LEFT JOIN requests ro ON ro.design_order_id = d.old_design_order_id`
        + ` WHERE u1.id=${userId} AND ${WhereCondition} ${clientCondition} ${projectCondition} ${content} GROUP BY d.id ${createdAt} ${limit}`)
         
      totalCount = await sequelize.query(`SELECT count(DISTINCT d.id) AS totalCount FROM design_orders d `
        + ` JOIN partners pt ON d.client = pt.id `
        + ` JOIN users u1 ON pt.user_id = u1.id `
        + ` LEFT JOIN design_order_attachments doa ON doa.design_order_id = d.id AND doa.is_reference = 0`
        + ` WHERE u1.id=${userId} AND ${WhereCondition} ${clientCondition} ${projectCondition} ${content}`)
      // acceptedCount = await sequelize.query(`SELECT count(d.id) AS acceptedCount FROM design_orders d `
      //   + ` JOIN partners pt ON d.client = pt.id `
      //   + ` JOIN users u1 ON pt.user_id = u1.id `
      //   + ` WHERE u1.id=${userId} AND d.status=2 AND d.hold=0`)
      // openCount = await sequelize.query(`SELECT count(d.id) AS openCount FROM design_orders d `
      //   + ` JOIN partners pt ON d.client = pt.id `
      //   + ` JOIN users u1 ON pt.user_id = u1.id `
      //   + ` WHERE u1.id=${userId} AND d.status=1 AND d.hold=0`)
      // rejectedCount = await sequelize.query(`SELECT count(d.id) AS rejectedCount FROM design_orders d `
      //   + ` JOIN partners pt ON d.client = pt.id `
      //   + ` JOIN users u1 ON pt.user_id = u1.id `
      //   + ` WHERE u1.id=${userId} AND d.status=6 AND d.hold=0`)
      rejectedCount = await sequelize.query(`SELECT count(d.id) AS rejectedCount FROM design_orders d 
        JOIN partners pt ON d.client = pt.id 
        LEFT JOIN states st ON pt.state_id = st.id 
        JOIN users u1 ON pt.user_id = u1.id 
        JOIN users u ON d.added_by = u.id 
        LEFT JOIN community com ON com.id = d.community 
        WHERE u1.id=${userId} AND d.status=6 AND d.hold=0`)
      // holdCount = await sequelize.query(`SELECT count(d.id) AS holdCount FROM design_orders d `
      //   + ` JOIN partners pt ON d.client = pt.id `
      //   + ` JOIN users u1 ON pt.user_id = u1.id `
      //   + ` WHERE u1.id=${userId} AND d.hold=1`)
      // allCount = await sequelize.query(`SELECT count(d.id) AS allCount FROM design_orders d `
      //   + ` JOIN partners pt ON d.client = pt.id `
      //   + ` JOIN users u1 ON pt.user_id = u1.id `
      //   + ` WHERE u1.id=${userId} AND  d.status NOT IN (0, 3, 8)`)
    }
    else {
      // query = await sequelize.query(`
      //   SELECT DISTINCT d.*, 
      //     CONCAT(u1.first_name," ", u1.last_name) AS customer_name,
      //     com.name AS community_name,
      //     d.added_by AS added_by,
      //     CONCAT(
      //       IFNULL(pt.address, ''), 
      //       IFNULL(CONCAT(', ', pt.city), ''), 
      //       IFNULL(CONCAT(', ', st.name), ''), 
      //       IFNULL(CONCAT(', ', pt.zip_code), '')
      //     ) AS customer_address,
      //     pt.phone AS customer_phone, COALESCE(COUNT(doa.id), 0) AS attachment_count,
      //     CONCAT(u.first_name," ", u.last_name) AS added_by_name,u.user_type AS added_by_user_type,u1.profile_pic AS added_by_profile_pic,u1.profile_pic AS customer_pic
      //   FROM design_orders d
      //   LEFT JOIN design_order_project_members pm ON d.id = pm.design_order_id
      //   LEFT JOIN staff_members sm ON pm.staff_id = sm.id
      //   LEFT JOIN partners p ON pm.partner_id = p.id
      //   LEFT JOIN users u_sm ON sm.user_id = u_sm.id
      //   LEFT JOIN users u_p ON p.user_id = u_p.id
      //   JOIN partners pt ON d.client = pt.id
      //   LEFT JOIN states st ON pt.state_id = st.id
      //   JOIN users u1 ON pt.user_id = u1.id
      //   JOIN users u ON d.added_by = u.id
      //   LEFT JOIN community com ON com.id = d.community
      //   LEFT JOIN design_order_attachments doa ON doa.design_order_id = d.id
      //   WHERE (u_sm.id = ${userId} OR u_p.id = ${userId} OR d.added_by = ${userId})
      //     AND ${WhereCondition} ${clientCondition} ${content} GROUP BY d.id ${createdAt} ${limit}
      // `);
      query = await sequelize.query(`
        SELECT DISTINCT d.*, d.created_at,
          CONCAT(u1.first_name," ", u1.last_name) AS customer_name,
          com.name AS community_name,
          d.added_by AS added_by,
          CONCAT(
            IFNULL(pt.address, ''), 
            IFNULL(CONCAT(', ', pt.city), ''), 
            IFNULL(CONCAT(', ', st.name), ''), 
            IFNULL(CONCAT(', ', pt.zip_code), '')
          ) AS customer_address,
          pt.phone AS customer_phone, COALESCE(COUNT(doa.id), 0) AS attachment_count,
          COALESCE(COUNT(doar.id), 0) AS reference_attachment_count,
          CONCAT(u.first_name," ", u.last_name) AS added_by_name,u.user_type AS added_by_user_type,u1.profile_pic AS added_by_profile_pic,u1.profile_pic AS customer_pic,
          r.id AS converted_design_request_id,
          odo.name AS old_design_order_name,
          ro.quotation AS old_design_order_request_quotation,
          ro.is_request_estimate AS old_design_order_request_is_request_estimate
        FROM design_orders d
        LEFT JOIN design_order_project_members pm ON d.id = pm.design_order_id
        LEFT JOIN staff_members sm ON pm.staff_id = sm.id
        LEFT JOIN partners p ON pm.partner_id = p.id
        LEFT JOIN users u_sm ON sm.user_id = u_sm.id
        LEFT JOIN users u_p ON p.user_id = u_p.id
        JOIN partners pt ON d.client = pt.id
        LEFT JOIN states st ON pt.state_id = st.id
        JOIN users u1 ON pt.user_id = u1.id
        JOIN users u ON d.added_by = u.id
        LEFT JOIN community com ON com.id = d.community
        LEFT JOIN design_order_attachments doa ON doa.design_order_id = d.id AND doa.is_reference = 0
        LEFT JOIN design_order_attachments doar ON doar.design_order_id = d.id AND doar.is_reference = 1
        LEFT JOIN design_orders odo ON odo.id = d.old_design_order_id
        LEFT JOIN requests r ON r.design_order_id = d.id
        LEFT JOIN requests ro ON ro.design_order_id = d.old_design_order_id
        LEFT JOIN staff_members sm_self ON sm_self.user_id = ${userId}
        WHERE (
          u_sm.id = ${userId}
          OR u_p.id = ${userId}
          OR d.added_by = ${userId}
          OR FIND_IN_SET(sm_self.id, REPLACE(d.collaborators,' ',''))
        )
          AND ${WhereCondition} ${clientCondition} ${projectCondition} ${content} ${designerCondition}
        GROUP BY d.id ${createdAt} ${limit}
      `);
    
      totalCount = await sequelize.query(`
        SELECT COUNT(DISTINCT d.id) AS totalCount
        FROM design_orders d
        JOIN partners pt ON d.client = pt.id
        LEFT JOIN community com ON com.id = d.community
        LEFT JOIN design_order_project_members pm ON d.id = pm.design_order_id
        LEFT JOIN staff_members sm ON pm.staff_id = sm.id
        LEFT JOIN partners p ON pm.partner_id = p.id
        LEFT JOIN users u_sm ON sm.user_id = u_sm.id
        LEFT JOIN users u_p ON p.user_id = u_p.id
        LEFT JOIN staff_members sm_self ON sm_self.user_id = ${userId}
        LEFT JOIN design_order_attachments doa ON doa.design_order_id = d.id AND doa.is_reference = 0
        WHERE (
          u_sm.id = ${userId}
          OR u_p.id = ${userId}
          OR d.added_by = ${userId}
          OR FIND_IN_SET(sm_self.id, REPLACE(d.collaborators,' ',''))
        )
          AND ${WhereCondition} ${clientCondition} ${projectCondition} ${content} ${designerCondition}
      `);
    
      rejectedCount = await sequelize.query(`
        SELECT COUNT(DISTINCT d.id) AS rejectedCount
        FROM design_orders d
        JOIN partners pt ON d.client = pt.id
        LEFT JOIN community com ON com.id = d.community
        LEFT JOIN design_order_project_members pm ON d.id = pm.design_order_id
        LEFT JOIN staff_members sm ON pm.staff_id = sm.id
        LEFT JOIN partners p ON pm.partner_id = p.id
        LEFT JOIN users u_sm ON sm.user_id = u_sm.id
        LEFT JOIN users u_p ON p.user_id = u_p.id
        LEFT JOIN staff_members sm_self ON sm_self.user_id = ${userId}
        WHERE (u_sm.id = ${userId}
          OR u_p.id = ${userId}
          OR d.added_by = ${userId}
          OR FIND_IN_SET(sm_self.id, REPLACE(d.collaborators,' ',''))
      )
          AND d.status = 6 AND d.hold = 0 ${designerCondition}
      `);
      // totalCount = await sequelize.query(`
      //   SELECT COUNT(DISTINCT d.id) AS totalCount
      //   FROM design_orders d
      //   LEFT JOIN design_order_project_members pm ON d.id = pm.design_order_id
      //   LEFT JOIN staff_members sm ON pm.staff_id = sm.id
      //   LEFT JOIN partners p ON pm.partner_id = p.id
      //   LEFT JOIN users u_sm ON sm.user_id = u_sm.id
      //   LEFT JOIN users u_p ON p.user_id = u_p.id
      //   WHERE (u_sm.id = ${userId} OR u_p.id = ${userId} OR d.added_by = ${userId})
      //     AND ${WhereCondition} ${clientCondition} ${content}
      // `);
    
      // rejectedCount = await sequelize.query(`
      //   SELECT COUNT(DISTINCT d.id) AS rejectedCount
      //   FROM design_orders d
      //   LEFT JOIN design_order_project_members pm ON d.id = pm.design_order_id
      //   LEFT JOIN staff_members sm ON pm.staff_id = sm.id
      //   LEFT JOIN partners p ON pm.partner_id = p.id
      //   LEFT JOIN users u_sm ON sm.user_id = u_sm.id
      //   LEFT JOIN users u_p ON p.user_id = u_p.id
      //   WHERE (u_sm.id = ${userId} OR u_p.id = ${userId} OR d.added_by = ${userId})
      //     AND d.status = 6 AND d.hold = 0
      // `);
    }
    
    let result = query[0]
    // console.log('totalCount===1',totalCount)
    // console.log('allCount===2',allCount)
    if (result.length >= 1) {
      const newData = await Promise.all(result.map(async (row) => {
        return row;
      }));
      const data = newData?.map(record => parseDecimalFields(record));
      // console.log('allCount===3',allCount[0][0].allCount)
      // console.log('allCount===4',totalCount[0][0].totalCount)
      return {data,
        // totalCount:totalCount[0][0].totalCount,
        // acceptedCount:acceptedCount[0][0].acceptedCount,
        // openCount:openCount[0][0].openCount,
        // rejectedCount:rejectedCount[0][0].rejectedCount,
        // holdCount:holdCount[0][0].holdCount,
        // allCount:allCount[0][0].allCount
        totalCount:totalCount[0][0].totalCount,
        acceptedCount:0,
        openCount:0,
        rejectedCount:rejectedCount[0][0]?.rejectedCount || 0,
        holdCount:0,
        allCount:0
      };

    }
    else {
      return {data:[],
        totalCount:totalCount[0][0].totalCount,
        acceptedCount:0,
        openCount:0,
        rejectedCount:0,
        holdCount:0,
        allCount:0,
      };
    }
  } catch (error) {
    console.error(error);
    return null;
  }
};
const getDesignOrderRejectedAttachments = async (design_order_id) => {
  try {
    const result = await sequelize.query(
      `
      SELECT 
        id,
        design_order_id,
        file_url,
        file_type,
        file_name,
        timestamp
      FROM design_order_rejected_files
      WHERE design_order_id = :design_order_id
      ORDER BY id DESC
      `,
      {
        replacements: { design_order_id },
        type: sequelize.QueryTypes.SELECT
      }
    );

    return result;
  } catch (error) {
    console.log('Error fetching rejected attachments:', error);
    return [];
  }
};

const getAllDesignOrdersCount = async (orderId, userId, userType,page,rowPerpage,search,where='',sort,fromDate,toDate, dueData,filterClient,filterProject) => {
  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 d.due_date BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
    } else if (fromTimestamp) {
      dateCondition = `AND d.due_date >= ${fromTimestamp}`;
    } else if (toTimestamp) {
      dateCondition = `AND d.due_date <= ${toTimestamp}`;
    }

    const isClient = await checkIfUserIsClient(userType);
    
    let createdAt = ''
    if (dueTimestamp) {
      createdAt=`ORDER BY d.due_date ASC`
    }else{
      if(sort==='new'){
        createdAt = `ORDER BY d.id DESC `
      }else if(sort==='old'){
          createdAt = `ORDER BY d.id ASC `
      }else if(sort === 'custom_order'){
      createdAt=`ORDER BY d.card_order ASC`
      }else{
        createdAt=`ORDER BY d.timestamp DESC`
      }
    }

    let offset = null
    if(rowPerpage && page){
     offset = (page - 1) * rowPerpage;
    }
    let totalCount=0
    let openCount=0
    let acceptedCount=0
    let rejectedCount=0
    let holdCount=0
    let allCount=0

    let query = '';
    let content = ''
    if(search){
        content=`and d.name LIKE '%${search}%'`
    }
    let WhereCondition = ''
    if (orderId) {
      WhereCondition = ` d.id=${orderId}`
    }
    else {
      // WhereCondition = ` d.status <>0  and d.status<>8 ${dateCondition}`
      WhereCondition = ` d.status NOT IN (0, 3, 8) ${dateCondition}`
      if(!empty(where)){
        WhereCondition=` ${where} ${dateCondition}`
      }
    }
    let clientCondition = '';
    if (filterClient && filterClient.length > 0) {
      clientCondition = ` AND d.client IN (${filterClient.join(',')}) `;
    }

    let projectCondition = '';
    if (filterProject && filterProject.length > 0) {
      if (filterProject.includes('other')) {
        // Filter for projects with null community or specific project IDs
        const projectIds = filterProject.filter(id => id !== 'other');
        if (projectIds.length > 0) {
          projectCondition = ` AND (d.community IS NULL OR d.community IN (${projectIds.join(',')})) `;
        } else {
          projectCondition = ` AND d.community IS NULL `;
        }
      } else {
        projectCondition = ` AND d.community IN (${filterProject.join(',')}) `;
      }
    }
    
    let limit = ''
    if(rowPerpage){
      limit = `LIMIT ${rowPerpage} OFFSET ${offset}`
    }
    let joinCondition = ''
    let designerCondition = ''
    if (userType == 1 || userType == 8) {
      joinCondition = ''
      designerCondition = '';
    }else{
      joinCondition = ` JOIN partners pt ON d.client = pt.id 
                        LEFT JOIN community com ON com.id = d.community 
                        LEFT JOIN design_order_project_members pm ON d.id = pm.design_order_id 
                        LEFT JOIN staff_members sm ON pm.staff_id = sm.id 
                        LEFT JOIN partners p ON pm.partner_id = p.id 
                        LEFT JOIN users u_sm ON sm.user_id = u_sm.id 
                        LEFT JOIN users u_p ON p.user_id = u_p.id `

      designerCondition = ` AND (u_sm.id = ${userId} OR u_p.id = ${userId} OR d.added_by = ${userId}) 
                            AND (d.working_designer_id IS NULL OR d.working_designer_id = ${userId} OR d.added_by = ${userId}) `;
    }



    if (userType !=3 && !isClient) {
      // totalCount = await sequelize.query(`SELECT count(DISTINCT d.id) AS totalCount FROM design_orders d `
      //   + joinCondition
      //   + ` LEFT JOIN design_order_attachments doa ON doa.design_order_id = d.id AND doa.is_reference = 0`
      //   + ` WHERE ${WhereCondition} ${clientCondition} ${projectCondition} ${content} ${designerCondition}`)
      totalCount = await sequelize.query(`SELECT count(DISTINCT d.id) AS totalCount FROM design_orders d 
        JOIN partners pt ON d.client = pt.id 
        LEFT JOIN states st ON pt.state_id = st.id 
        JOIN users u1 ON pt.user_id = u1.id 
        JOIN users u ON d.added_by = u.id 
        LEFT JOIN community com ON com.id = d.community 
        LEFT JOIN design_order_attachments doa ON doa.design_order_id = d.id AND doa.is_reference = 0
        WHERE ${WhereCondition} ${clientCondition} ${projectCondition} ${content}`);
      acceptedCount = await sequelize.query(`SELECT count(d.id) AS acceptedCount FROM design_orders d `
        + joinCondition
        + ` WHERE d.status=2 AND d.hold=0 ${clientCondition} ${projectCondition} ${designerCondition}`)
      openCount = await sequelize.query(`SELECT count(d.id) AS openCount FROM design_orders d `
        + joinCondition
        + ` WHERE d.status=1 AND d.hold=0 ${clientCondition} ${projectCondition} ${designerCondition}`)
      rejectedCount = await sequelize.query(`SELECT count(d.id) AS rejectedCount FROM design_orders d `
        + joinCondition
        + ` WHERE d.status=6 AND d.hold=0 ${clientCondition} ${projectCondition} ${designerCondition}`)
      holdCount = await sequelize.query(`SELECT count(d.id) AS holdCount FROM design_orders d `
        + joinCondition
        + ` WHERE d.hold=1 ${clientCondition} ${projectCondition} ${designerCondition}`)
      allCount = await sequelize.query(`SELECT count(d.id) AS allCount FROM design_orders d `
        + joinCondition
        + ` WHERE  d.status NOT IN (0, 3, 8) ${clientCondition} ${projectCondition} ${designerCondition}`)
    }
    if (userType == 3 || isClient) {
      totalCount = await sequelize.query(`SELECT count(DISTINCT d.id) AS totalCount FROM design_orders d `
        + ` JOIN partners pt ON d.client = pt.id `
        + ` JOIN users u1 ON pt.user_id = u1.id `
        + ` LEFT JOIN design_order_attachments doa ON doa.design_order_id = d.id AND doa.is_reference = 0 `
        + ` WHERE u1.id=${userId} AND ${WhereCondition} ${clientCondition} ${projectCondition} ${content}`)
      acceptedCount = await sequelize.query(`SELECT count(d.id) AS acceptedCount FROM design_orders d `
        + ` JOIN partners pt ON d.client = pt.id `
        + ` JOIN users u1 ON pt.user_id = u1.id `
        + ` WHERE u1.id=${userId} AND d.client = pt.id AND d.status=2 AND d.hold=0 ${clientCondition} ${projectCondition}`)
      openCount = await sequelize.query(`SELECT count(d.id) AS openCount FROM design_orders d `
        + ` JOIN partners pt ON d.client = pt.id `
        + ` JOIN users u1 ON pt.user_id = u1.id `
        + ` WHERE u1.id=${userId} AND d.status=1 AND d.hold=0 ${clientCondition} ${projectCondition}`)
      rejectedCount = await sequelize.query(`SELECT count(d.id) AS rejectedCount FROM design_orders d `
        + ` JOIN partners pt ON d.client = pt.id `
        + ` JOIN users u1 ON pt.user_id = u1.id `
        + ` WHERE u1.id=${userId} AND d.status=6 AND d.hold=0 ${clientCondition} ${projectCondition}`)
      holdCount = await sequelize.query(`SELECT count(d.id) AS holdCount FROM design_orders d `
        + ` JOIN partners pt ON d.client = pt.id `
        + ` JOIN users u1 ON pt.user_id = u1.id `
        + ` WHERE u1.id=${userId} AND d.hold=1 ${clientCondition} ${projectCondition}`)
      allCount = await sequelize.query(`SELECT count(d.id) AS allCount FROM design_orders d `
        + ` JOIN partners pt ON d.client = pt.id `
        + ` JOIN users u1 ON pt.user_id = u1.id `
        + ` WHERE u1.id=${userId} AND  d.status NOT IN (0, 3, 8) ${clientCondition} ${projectCondition}`)
    }
    if (totalCount.length >= 1) {
      return {
        totalCount:totalCount[0][0].totalCount,
        acceptedCount:acceptedCount[0][0].acceptedCount,
        openCount:openCount[0][0].openCount,
        rejectedCount:rejectedCount[0][0].rejectedCount,
        holdCount:holdCount[0][0].holdCount,
        allCount:allCount[0][0].allCount
      };
    }
    else {
      return {
        totalCount:totalCount[0][0].totalCount,
        acceptedCount:acceptedCount[0][0].acceptedCount,
        openCount:openCount[0][0].openCount,
        rejectedCount:rejectedCount[0][0].rejectedCount,
        holdCount:holdCount[0][0].holdCount,
        allCount:allCount[0][0].allCount
      };
    }
  } catch (error) {
    console.error(error);
    return null;
  }
};

const deleteDesignOrderById = async (order_id) => {
  if (!empty(order_id)) {
    let query = `UPDATE design_orders SET status = 0 WHERE id = ${order_id}`;
    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.UPDATE,
    });
    if (result) {
      return true
    } else {
      return false
    }
  }
}

const fetchAllDesignOrderAttachments=async(orderId)=>{
  let query = await sequelize.query(`select d.*,d.id AS ID, d.name AS file_url,concat(u.first_name," ", u.last_name) as updated_by,u.profile_pic as pic,concat(s.first_name," ", s.last_name) as approved_by, d.approved_by AS approved_by_id from design_order_attachments d
  left join users u on u.id=d.added_by
  left join users s on s.id=d.approved_by
  where d.design_order_id=${orderId} AND d.is_reference = 0 ORDER BY d.approved DESC `) 
  let data = [];

  if (query[0]?.length > 0) {
      data = query[0];
  }
  return data;
}
const fetchAllDesignOrderReferenceAttachments=async(orderId)=>{
  let query = await sequelize.query(`select d.*,d.id AS ID, d.name AS file_url,concat(u.first_name," ", u.last_name) as updated_by,u.profile_pic as pic,concat(s.first_name," ", s.last_name) as approved_by, d.approved_by AS approved_by_id from design_order_attachments d
  left join users u on u.id=d.added_by
  left join users s on s.id=d.approved_by
  where d.design_order_id=${orderId} AND d.is_reference = 1 ORDER BY d.approved DESC `) 
  let data = [];

  if (query[0]?.length > 0) {
      data = query[0];
  }
  return data;
}
const fetchAllDesignOrderAttachmentsForConvert=async(orderId)=>{
  let query = await sequelize.query(`select d.*,d.id AS ID, d.name AS file_url,concat(u.first_name," ", u.last_name) as updated_by,u.profile_pic as pic,concat(s.first_name," ", s.last_name) as approved_by from design_order_attachments d
  left join users u on u.id=d.added_by
  left join users s on s.id=d.approved_by
  where d.design_order_id=${orderId} AND d.is_reference = 0 and d.isChat = 0 ORDER BY d.approved DESC `) 
  let data = [];

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

const getDesignOrderPartnersByIds = async (partner_ids = [], design_order_id = 0) => {
  let query = '';
  let clients = partner_ids.join(',')

  if (!empty(partner_ids)) {
    query = `SELECT u.id, CONCAT(u.first_name, ' ', u.last_name) as name FROM partners t
             LEFT JOIN users u ON t.user_id = u.id 
             WHERE u.status = 1 AND t.id in ( ${clients} )
             ORDER BY u.id DESC`;

  } else {
    query = `SELECT u.id, CONCAT(u.first_name, ' ', u.last_name) as name 
             FROM design_orders r 
             LEFT JOIN partners t ON r.client = t.id 
             LEFT JOIN users u ON t.user_id = u.id 
             WHERE u.status = 1 AND r.id = ${design_order_id}
             ORDER BY u.id DESC`;
  }

  const result = await sequelize.query(query, {
    type: sequelize.QueryTypes.SELECT,
  });

  if (result.length >= 1) {
    return result;
  } else {
    return [];
  }
};

const findRequestAndPaymentById = async(id) => {
  let query = `
    SELECT  r.*, 
  COALESCE(SUM(rp.amount), 0) AS totalPaymentAmount,
  co.total AS totalCustomerOrders
  FROM requests r
LEFT JOIN request_payments rp ON r.id = rp.request_id AND rp.status = 1
LEFT JOIN customer_orders co ON r.id = co.request_id
WHERE r.id = ${id} GROUP BY  r.id
  `;

  const result = await sequelize.query(query, {
    type: sequelize.QueryTypes.SELECT,
  });
  if (result.length >= 1) {
    return result[0];
  } else {
    return [];
  }
}

const addDesignOrderServices = async (data) => {

  let res = await DesignOrdersServices.create(data)
  return res.id;
}

const addDesignOrderProducts = async (data) => {
  try {
    let res = await DesignOrderProducts.create(data)
    return res.id;
  } catch (error) {
    console.log('Error : ', error)
    return error
  }
}

const getDesignOrderProductsByDesignOrderId = async (designOrderId) => {
  try {
    return await DesignOrderProducts.findAll({
      where: { design_order_id: designOrderId, status: 1 },
      order: [['id', 'ASC']],
    })
  } catch (error) {
    console.log('Error : ', error)
    return []
  }
}

const deleteDesignOrderProductsByDesignOrderId = async (designOrderId) => {
  try {
    return await DesignOrderProducts.destroy({
      where: { design_order_id: designOrderId },
    })
  } catch (error) {
    console.log('Error : ', error)
    return error
  }
}


const getDesignOrderById = async (id) => {
  let res = await DesignOrdersServices.findAll( {
    where: { design_order_id: id }
  })
  if (res) {
    return res
  } else {
    return false
  }
}
const getDesignOrderServicesByDesignOrderId = async (id) => {
  let res = await sequelize.query(
    `SELECT dos.*, lcs.name AS name,lcs.syncWithQuickbooks,lcs.quickbookId 
     FROM design_order_services dos
     LEFT JOIN labour_cost_services lcs ON dos.labour_cost_service_id = lcs.id
     WHERE dos.design_order_id = :id`,
    {
      replacements: { id },
      type: sequelize.QueryTypes.SELECT,
    }
  );

  return res.length ? res : false;
};

const updateDesignOrderService = async (data, id) => {
  let res = await DesignOrdersServices.update(data, {
    where: { id: id }
  })
  console.log('resresres',res)
  if (res) {
    return true
  } else {
    return false
  }
}


const getAllServiceByDesignOrder = async (requestId) => {
  let query = await sequelize.query(`select dos.*,l.name,l.cost as originalCost from design_order_services dos`
    + ` left join labour_cost_services l on l.id=dos.labour_cost_service_id `
    + ` where dos.design_order_id=${requestId}`
  )
  let data = [];
  if (query[0].length > 0) {
    data = query[0]
  }
  return data;
}

const addDesignOrdersSubTask = async (data) => {
  try{
    let res = await DesignOrdersSubTask.create(data)
    if(res){
      return res.id;
    }else{
      return false
    }
  }catch(error){
    console.log('Error : ',error);
    return false
  }
}

const getDesignOrdersSubTaskByTask = async (id) => {
  let res = await DesignOrdersServices.findAll( {
    where: { task_id: id }
  })
  if (res) {
    return res
  } else {
    return false
  }
}

const getDesignOrdersSubTaskByDesignOrder = async (id) => {
  let res = await sequelize.query(`select * from design_order_sub_task where design_order_id=${id}`);
  if (res[0]?.length) {
    return res[0]
  } else {
    return []
  }
}

const deleteDesignOrdersSubTask = async (id) => {
  let res = await DesignOrdersSubTask.destroy({
    where: { design_order_id: id }
  })
  if (res) {
    return true
  } else {
    return false
  }
}

const updateDesignOrdersSubTask = async (data, id) => {
  try {
    const updatedRows = await DesignOrdersSubTask.update(data, {
        where: {
            id: id
        },
        returning: true,
    });
    if (updatedRows) {
      if (updatedRows[1] > 0) {
        return true;
      }
      else {
        return false;
      }
    }
  }catch (error) {
    console.error("Error updating design order sub task:", error);
    return false;
  }
}

const deleteDesignOrderServices = async (id) => {
  let res = await DesignOrdersServices.destroy({
    where: { design_order_id: id }
  })
  if (res) {
    return true
  } else {
    return false
  }
}

const getAllDesignOrderTasks = async (id, userId, userType, hasPermission,taskId=false) => {
  try {
    let query = '';
    let whereCondition = ''
    if(taskId){
      whereCondition = ` AND dos.id = ${taskId} `
    }
    // if (userType === 1 || userType === 8 || hasPermission) {
    if (userType !=3) {
      query = await sequelize.query(
        `SELECT DISTINCT dos.*, 
              lcs.name AS service_name,
              lcs.name AS name,
              do.name AS design_order_name, 
              do.total_cost, 
              do.status AS design_order_status, 
              do.timestamp AS design_order_timestamp,
              doar.id AS reference_attachment_id, 
              doar.name AS reference_attachment_name, 
              doar.file_type AS reference_attachment_file_type, 
              doar.approved AS reference_attachment_approved, 
              doa.id AS attachment_id, 
              doa.name AS attachment_name, 
              doa.file_type AS attachment_file_type, 
              doa.approved AS attachment_approved, 
              dost.name AS sub_task_name,
              dost.description AS sub_task_description,
              dost.priority AS sub_task_priority, 
              dost.status AS sub_task_status, 
              COALESCE(tm.count, 0) AS member_count, 
              COALESCE(da.count, 0) AS attachment_count,
              COALESCE(dar.count, 0) AS reference_attachment_count,
              COALESCE(st.count, 0) AS subtask_count
        FROM design_order_services dos
        LEFT JOIN design_orders do ON dos.design_order_id = do.id
        LEFT JOIN labour_cost_services lcs ON dos.labour_cost_service_id = lcs.id
        LEFT JOIN design_order_attachments doa ON doa.design_order_id = dos.design_order_id AND doa.is_reference = 0
        LEFT JOIN design_order_attachments doar ON doar.design_order_id = dos.design_order_id AND doar.is_reference = 1
        LEFT JOIN design_order_sub_task dost 
            ON dost.design_order_id = dos.design_order_id 
            AND dost.task_id = dos.id  -- Ensures subtask is linked to the correct service
        LEFT JOIN (
            SELECT task_id, COUNT(id) AS count 
            FROM design_order_sub_task 
            GROUP BY task_id
        ) tm ON tm.task_id = dos.id
        LEFT JOIN (
            SELECT design_order_id, COUNT(id) AS count 
            FROM design_order_attachments WHERE is_reference = 0
            GROUP BY design_order_id
        ) da ON da.design_order_id = do.id
        LEFT JOIN (
            SELECT design_order_id, COUNT(id) AS count 
            FROM design_order_attachments WHERE is_reference = 1
            GROUP BY design_order_id
        ) dar ON dar.design_order_id = do.id
        LEFT JOIN (
            SELECT design_order_id, task_id, COUNT(id) AS count 
            FROM design_order_sub_task
            GROUP BY design_order_id, task_id
        ) st ON st.design_order_id = dos.design_order_id 
            AND st.task_id = dos.id
        WHERE dos.design_order_id = ${id} ${whereCondition}
        GROUP BY dos.id, lcs.name, do.name, do.total_cost, do.status, do.timestamp, doa.id, doa.name, doa.file_type, doa.approved, 
                dost.name, dost.description, dost.priority, dost.status
        ORDER BY dos.id DESC`
      );
    } else {
      query = await sequelize.query(
        `SELECT DISTINCT dos.*, 
              lcs.name AS service_name,
              lcs.name AS name,
              do.name AS design_order_name, 
              do.total_cost, 
              do.status AS design_order_status, 
              do.timestamp AS design_order_timestamp,
              doar.id AS reference_attachment_id, 
              doar.name AS reference_attachment_name, 
              doar.file_type AS reference_attachment_file_type, 
              doar.approved AS reference_attachment_approved, 
              doa.id AS attachment_id, 
              doa.name AS attachment_name, 
              doa.file_type AS attachment_file_type, 
              doa.approved AS attachment_approved, 
              dost.name AS sub_task_name,
              dost.description AS sub_task_description,
              dost.priority AS sub_task_priority, 
              dost.status AS sub_task_status, 
              COALESCE(tm.count, 0) AS member_count, 
              COALESCE(da.count, 0) AS attachment_count,
              COALESCE(dar.count, 0) AS reference_attachment_count,
              COALESCE(st.count, 0) AS subtask_count
        FROM design_order_services dos
        LEFT JOIN design_orders do ON dos.design_order_id = do.id
        LEFT JOIN labour_cost_services lcs ON dos.labour_cost_service_id = lcs.id
        LEFT JOIN design_order_attachments doa ON doa.design_order_id = dos.design_order_id AND doa.is_reference = 0
        LEFT JOIN design_order_attachments doar ON doar.design_order_id = dos.design_order_id AND doar.is_reference = 1
        LEFT JOIN design_order_sub_task dost 
            ON dost.design_order_id = dos.design_order_id 
            AND dost.task_id = dos.id  -- Ensures subtask is linked to the correct service
        LEFT JOIN (
            SELECT task_id, COUNT(id) AS count 
            FROM design_order_sub_task 
            GROUP BY task_id
        ) tm ON tm.task_id = dos.id
        LEFT JOIN (
            SELECT design_order_id, COUNT(id) AS count 
            FROM design_order_attachments WHERE is_reference = 0
            GROUP BY design_order_id
        ) da ON da.design_order_id = do.id
        LEFT JOIN (
            SELECT design_order_id, COUNT(id) AS count 
            FROM design_order_attachments WHERE is_reference = 1
            GROUP BY design_order_id
        ) dar ON dar.design_order_id = do.id
        LEFT JOIN (
            SELECT design_order_id, task_id, COUNT(id) AS count 
            FROM design_order_sub_task
            GROUP BY design_order_id, task_id
        ) st ON st.design_order_id = dos.design_order_id 
            AND st.task_id = dos.id
         WHERE dos.design_order_id = ${id} AND dos.taken != 0  ${whereCondition}
          GROUP BY dos.id, lcs.name, do.name, do.total_cost, do.status, do.timestamp, doa.id, doa.name, doa.file_type, doa.approved, 
                  dost.name, dost.description, dost.priority, dost.status
          ORDER BY dos.id DESC`
      );
    }

    let data = [];

    if (query[0]?.length > 0) {
      data = await Promise.all(
        query[0]?.map(async (row) => {
          if (row?.attachment_id) {
            const attachmentDetails = await sequelize.query(
              `SELECT * FROM design_order_attachments WHERE design_order_id = ${row.design_order_id} AND is_reference = 0`
            );
            row.attachments = attachmentDetails[0]?.length > 0 ? attachmentDetails[0] : [];
          } else {
            row.attachments = [];
          }
          if (row?.reference_attachment_id) {
            const attachmentDetails = await sequelize.query(
              `SELECT * FROM design_order_attachments WHERE design_order_id = ${row.design_order_id} AND is_reference = 1`
            );
            row.reference_attachments = attachmentDetails[0]?.length > 0 ? attachmentDetails[0] : [];
          } else {
            row.reference_attachments = [];
          }
          return row;
        })
      );
    }
    if (!Array.isArray(data) || data.length === 0) {
      return [];
    }
    data = Array.from(new Map(data.map((item) => [item.id, item])).values());
    return data;    
  } catch (error) {
    console.error(error);
    throw new Error("Server error");
  }
};

// const getAllDesignOrderTasks = async (id, userId, userType, hasPermission, taskId = false) => {
//   try {
//     let whereCondition = '';
//     if (taskId) {
//       whereCondition = ` AND dos.id = ${taskId} `;
//     }

//     let query = await sequelize.query(
//       `SELECT DISTINCT dos.*, 
//             lcs.name AS service_name,
//             do.name AS design_order_name, 
//             do.total_cost, 
//             do.status AS design_order_status, 
//             do.timestamp AS design_order_timestamp,
//             doa.id AS attachment_id, 
//             doa.name AS attachment_name, 
//             doa.file_type AS attachment_file_type, 
//             doa.approved AS attachment_approved, 
//             COALESCE(tm.count, 0) AS member_count, 
//             COALESCE(da.count, 0) AS attachment_count
//       FROM design_order_services dos
//       LEFT JOIN design_orders do ON dos.design_order_id = do.id
//       LEFT JOIN labour_cost_services lcs ON dos.labour_cost_service_id = lcs.id
//       LEFT JOIN design_order_attachments doa ON doa.design_order_id = dos.design_order_id
//       LEFT JOIN (
//           SELECT task_id, COUNT(id) AS count 
//           FROM design_order_sub_task 
//           GROUP BY task_id
//       ) tm ON tm.task_id = dos.id
//       LEFT JOIN (
//           SELECT design_order_id, COUNT(id) AS count 
//           FROM design_order_attachments 
//           GROUP BY design_order_id
//       ) da ON da.design_order_id = do.id
//       WHERE dos.design_order_id = ${id} ${whereCondition}
//       GROUP BY dos.id, lcs.name, do.name, do.total_cost, do.status, do.timestamp, doa.id, doa.name, doa.file_type, doa.approved
//       ORDER BY dos.id DESC`
//     );

//     let services = query[0] || [];

//     // ✅ Step 2: Fetch Subtasks in a Separate Query
//     const subtaskQuery = await sequelize.query(
//       `SELECT dost.task_id, dost.name AS sub_task_name, dost.description AS sub_task_description, 
//               dost.priority AS sub_task_priority, dost.status AS sub_task_status
//        FROM design_order_sub_task dost
//        WHERE dost.design_order_id = ${id};`
//     );

//     const subtasks = subtaskQuery[0] || [];

//     // ✅ Step 3: Merge Subtasks into Services
//     const serviceMap = {};
//     services.forEach(service => {
//       serviceMap[service.id] = { ...service, subtasks: [] };
//     });

//     subtasks.forEach(subtask => {
//       if (serviceMap[subtask.task_id]) {
//         serviceMap[subtask.task_id].subtasks.push({
//           name: subtask.sub_task_name,
//           description: subtask.sub_task_description,
//           priority: subtask.sub_task_priority,
//           status: subtask.sub_task_status
//         });
//       }
//     });

//     return Object.values(serviceMap);

//   } catch (error) {
//     console.error(error);
//     throw new Error("Server error");
//   }
// };

const addDesignOrdersProjectMember = async (data) => {

  let res = await DesignOrderProjectMembers.create(data)
  if(res){

    return res.id;
  }else{
    return false
  }
}

const deleteDesignOrdersProjectMember = async (id) => {
  let res = await DesignOrderProjectMembers.destroy({
    where: { design_order_id: id }
  })
  if (res) {
    return true
  } else {
    return false
  }
}
const deleteDesignOrdersProjectMemberById = async (id) => {
  let res = await DesignOrderProjectMembers.destroy({
    where: { id: id }
  })
  if (res) {
    return true
  } else {
    return false
  }
}


const projectMemberExist = async (data) => {
  let query = await sequelize.query(` select staff_id from design_order_project_members where staff_id=${data.staff_id} and design_order_id=${data.design_order_id}`)
  console.log("HIIIIIIIIIIIIIII", query[0].length);
  if (query[0].length > 0) {
      return true
  } else {
      return false
  }
}

const getAllDesignOrderProjectMembers = async (id, memberId = false) => {
  let whereCondition = '';
  if (memberId) {
    whereCondition = ` AND pm.id = ${memberId} `;
  }

  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,
      s.phone, 
      COALESCE(u.profile_pic, u2.profile_pic) AS profile_pic,
      u2.user_type,
      u2.id AS user_id, 
      COALESCE(u.email, u2.email) AS email,
      COALESCE(u.id, u2.id) AS userid,
      u2.smsEnabled,
      u2.emailEnabled,
      (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,
      CASE WHEN FIND_IN_SET(251, ur.user_permissions) > 0 THEN 1 ELSE 0 END AS pcb_new_design_jobs,
      COALESCE((SELECT pcb_email_enabled FROM user_pcb_preferences WHERE user_id = COALESCE(u.id, u2.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 = COALESCE(u.id, u2.id) AND pcb_item_id = 14 AND status != 0 LIMIT 1), 0) AS pcb_new_design_jobs_sms,
      CASE WHEN FIND_IN_SET(254, ur.user_permissions) > 0 THEN 1 ELSE 0 END AS view_design_permission
    FROM design_order_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.design_order_id = ${id} ${whereCondition}
    ORDER BY pm.id DESC
  `);

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

  return data;
};
const getAllDesignOrderProjectMembersNew = async (id, memberId = false) => {
  let whereCondition = '';
  if (memberId) {
    whereCondition = ` AND pm.id = :memberId `;
  }

  const 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,
      s.phone, 
      COALESCE(u.profile_pic, u2.profile_pic) AS profile_pic,
      u2.user_type,
      u2.id AS user_id, 
      COALESCE(u.email, u2.email) AS email,
      COALESCE(u.id, u2.id) AS userid,
      u2.smsEnabled,
      u2.emailEnabled,
      CASE 
        WHEN pm.partner_id IS NOT NULL THEN 'Client' 
        ELSE 'Team' 
      END AS user_role_name,
      ur.name AS user_role,
      COALESCE(pt_partner.count, pt_staff.count, 0) AS task_count,
      CASE 
        WHEN FIND_IN_SET(251, ur.user_permissions) > 0 THEN 1 
        ELSE 0 
      END AS pcb_new_design_jobs,
      COALESCE(pcb_prefs.pcb_email_enabled, 0) AS pcb_new_design_jobs_email,
      COALESCE(pcb_prefs.pcb_sms_enabled, 0) AS pcb_new_design_jobs_sms,
      CASE 
        WHEN FIND_IN_SET(254, ur.user_permissions) > 0 THEN 1 
        ELSE 0 
      END AS view_design_permission
    FROM design_order_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

    -- Task count for partners
    LEFT JOIN (
      SELECT 
        ptm.partner_id,
        COUNT(ptm.ID) AS count
      FROM project_task_members ptm
      JOIN project_tasks pt ON pt.ID = ptm.task_id
      WHERE pt.status != 0 AND pt.project_id = 50
      GROUP BY ptm.partner_id
    ) pt_partner ON pt_partner.partner_id = pm.partner_id

    -- Task count for staff
    LEFT JOIN (
      SELECT 
        ptm.staff_id,
        COUNT(ptm.ID) AS count
      FROM project_task_members ptm
      JOIN project_tasks pt ON pt.ID = ptm.task_id
      WHERE pt.status != 0 AND pt.project_id = 50
      GROUP BY ptm.staff_id
    ) pt_staff ON pt_staff.staff_id = pm.staff_id

    -- PCB preferences (grouped, no duplicates)
    LEFT JOIN (
      SELECT 
        user_id,
        MAX(pcb_email_enabled) AS pcb_email_enabled,
        MAX(pcb_sms_enabled) AS pcb_sms_enabled
      FROM user_pcb_preferences
      WHERE pcb_item_id = 14 AND status != 0
      GROUP BY user_id
    ) pcb_prefs ON pcb_prefs.user_id = COALESCE(u.id, u2.id)

    WHERE pm.design_order_id = :designOrderId ${whereCondition}
    ORDER BY pm.id DESC
  `, {
    replacements: { 
      designOrderId: id,
      memberId: memberId
    },
    type: sequelize.QueryTypes.SELECT
  });

  return query.length ? query : [];
};


const addDesignOrdersProjectSubtaskMember = async (data) => {
  let res = await DesignOrderProjectSubtaskMembers.create(data)
  if(res){
    return res.id;
  }else{
    return false
  }
}

const deleteDesignOrdersProjectSubtaskMember = async (id) => {
  let res = await DesignOrderProjectSubtaskMembers.destroy({
    where: { subtask_id: id }
  })
  if(res){
    return res.id;
  }else{
    return false
  }
}

const projectSubtaskMemberExist = async (data,subtask_id) => {
  let query = await sequelize.query(` select staff_id,subtask_id from design_order_project_subtask_members where subtask_id=${subtask_id} and staff_id=${data.staff_id}`)
  if (query[0].length > 0) {
      return true
  } else {
      return false
  }
}

const getAllDesignOrderProjectSubTaskBytaskId = async (id, userType, userId) => {
  let query = ""
  console.log("###########UserType",userType);
  if (userType != 1 && userType != 8 && userType !=3) {
      query = await sequelize.query(`SELECT pt.* FROM design_order_sub_task pt `
          + ` LEFT JOIN design_order_project_members s ON s.id=pt.reporter_id `
          + ` LEFT JOIN staff_members s1 ON s1.id=pt.reporter_id `
          + ` LEFT JOIN users u1 ON s1.user_id=u1.id`
          + ` LEFT JOIN (select pm.subtask_id, COALESCE(u.id,u2.id) as user_id from design_order_project_subtask_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.subtask_id=pt.id and pmm.user_id=${userId}   `
          + ` WHERE (u1.id = ${userId} or pmm.user_id = ${userId} ) AND pt.task_id = ${id} AND pt.status !=0 ORDER BY pt.id DESC`)
          // + ` WHERE  pt.task_id = ${id} AND pt.status !=0 ORDER BY pt.ID DESC`)
      console.log("############PRoject Sub task");
      }
  else {
      query = await sequelize.query(`SELECT pt.* FROM design_order_sub_task pt 
      WHERE pt.task_id = ${id} AND pt.status !=0 ORDER BY pt.ID DESC`)
  }
  let data = [];
  console.log('query[0]=====',query[0])
  if (query[0].length > 0) {
      data= await Promise.all(query[0].map(async row=>{
          console.log("################PM",row);
          row.teamMembers=[]
          let query2=await sequelize.query(`select pm.*,u.profile_pic as profile_pic,concat(s.first_name, ' ', coalesce(s.last_name, '')) as name,s.hourly_rate as hourly_rate,u.id as user_id,u.user_type as user_type from design_order_project_subtask_members pm  
          left join staff_members s on s.id=pm.staff_id
          left join users u on u.id=s.user_id
          where pm.subtask_id=${row.id}`)
        if(query2.length>0){
          row.teamMembers=query2[0]
        }
        return row
      }))
      

  }
  return data;
}

const designOrderProjectSubTaskSkills = async (taskId) => {
  try {
    // Query to get skill_ids
    let result = await sequelize.query(`SELECT pst.skill_ids FROM design_order_sub_task AS pst WHERE pst.task_id = ${taskId}`);
    
    // Map and split skill_ids
    let skillIdsArray = result[0].map(item => {
      if (!item.skill_ids) {
        return [];
      }
      // Ensure skill_ids is treated as a string before splitting
      return item.skill_ids.toString().split(',').map(id => parseInt(id, 10));
    });

    // Combine all skill_ids into a single array
    let combinedSkillIds = [].concat(...skillIdsArray);

    let data = [];
    if (combinedSkillIds.length > 0) {
      // Query to get data from services table
      data = await sequelize.query(`SELECT s.* FROM services AS s WHERE s.id IN (${combinedSkillIds.join(',')})`);
      return data[0];
    } else {
      return [];
    }
  } catch (error) {
    console.error("designOrderProjectSubTaskSkills error:", error);
    throw error;
  }
};


const fetchDesignOrderStaffTaskTimelog = async(id=null,userId=null,taskId=null,projectId=null,logIdArray=null, installationId=null)=>{
  try{
      let whereCondition='';
      if(logIdArray?.length > 0){
          whereCondition += ` AND st.id IN (${logIdArray.join(',')}) `
      }else{
          whereCondition += ` AND st.status=1 `
      }
      if(id){
          whereCondition += ` AND st.id = ${id} `
      }
      if(userId){
          whereCondition += ` AND st.user_id = ${userId} `
      }
      if(projectId){
          whereCondition += ` AND st.job_id = ${projectId} `
      }

      let baseCondition = '';
      if (installationId) {
          baseCondition = `st.installation_id = ${installationId}`;
      }else if (taskId) {
          baseCondition = `st.task_id = ${taskId}`;
      }


      const results = await sequelize.query(`SELECT st.*,CONCAT(u.first_name,' ',u.last_name) AS staff_name `
      +` FROM design_order_staff_task_timelogs st `
      +` LEFT JOIN users u ON u.id = st.user_id `
      +` WHERE ${baseCondition} ${whereCondition}`)
      // +` WHERE st.status=1 ${whereCondition} `)
      if (results[0]?.length) {
          return results[0];
      }
      else {
          return false;
      }
  }catch(error){
      console.error("Error fetching the staff job timelog ", error);
      return false;
  }
}


const fetchAllServicesByDesignOrderId = async (requestId) => {
  let query = await sequelize.query(`
    SELECT rs.*, l.name, 
      CASE 
        WHEN l.cost = 0 THEN rs.unit_cost 
        ELSE COALESCE(l.cost, rs.unit_cost) 
      END AS originalCost
    FROM design_order_services rs
    LEFT JOIN labour_cost_services l ON l.id = rs.labour_cost_service_id
    WHERE rs.design_order_id = ${requestId} AND rs.job_cost = 0
  `);

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


const fetchAllAdditionalServicesByDesignOrderId=async(requestId)=>{
  let query=await sequelize.query(`select rs.*,l.name,l.cost as originalCost from design_order_services rs`
      +` left join labour_cost_services l on l.id=rs.labour_cost_service_id `
      +` where rs.design_order_id=${requestId} and rs.job_cost=1`
  )
  let data=[];
    if (query[0].length > 0){
      data=query[0]
    }
    return data;
}




const getAllDesignOrderStaffTaskTimelogs = async (newUserId, id) => {
  try {
    // Base query with the correct alias for design_order_staff_task_timelogs
    let query = `SELECT dostt.*,sm.hourly_rate, lcs.name as task_name,   COALESCE(CONCAT(sm.first_name, ' ', sm.last_name), 'Signwise Admin') AS staff_name
                 FROM design_order_staff_task_timelogs dostt
                 LEFT JOIN design_order_services dos ON dos.id = dostt.task_id
                 LEFT JOIN labour_cost_services lcs ON lcs.id = dos.labour_cost_service_id
                 LEFT JOIN staff_members sm ON sm.user_id = dostt.user_id
                 WHERE dostt.design_order_id = ${id}`;

    // Add the user_id condition if newUserId is provided
    if (newUserId) {
      query += ` AND dostt.user_id = ${newUserId}`;
    }

    // Execute the raw SQL query
    const [res] = await sequelize.query(query);

    // Return results if found, else return false
    if (res && res.length > 0) {
      return res;
    } else {
      return [];
    }
  } catch (error) {
    console.error("Error fetching design order staff task timelogs with SQL:", error);
    throw error;
  }
};

const getAllDesignOrderJobCount = async (userType,userId) => {
  try {

    let query = '';
    const designerCondition = ` AND (do.working_designer_id IS NULL OR do.working_designer_id = ${userId}) `;
    if (userType == 1 || userType == 8) {
      query = `
        SELECT 
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 1 AND do.hold = 0 THEN do.id END) AS newCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 2 AND do.hold = 0 THEN do.id END) AS inProgressCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 3 AND do.hold = 0 THEN do.id END) AS completedCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 4 AND do.hold = 0 THEN do.id END) AS rejectedCount,
          COUNT(DISTINCT CASE WHEN do.hold = 1 THEN do.id END) AS holdCount
        FROM 
          design_orders do
        INNER JOIN 
          design_order_services dos ON do.id = dos.design_order_id  -- Exclude design orders without services
        WHERE 
          do.status NOT IN (0, 3)
      `;
    } else if (userType === 3) {
      query = `
        SELECT 
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 1 AND do.hold = 0 THEN do.id END) AS newCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 2 AND do.hold = 0 THEN do.id END) AS inProgressCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 3 AND do.hold = 0 THEN do.id END) AS completedCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 4 AND do.hold = 0 THEN do.id END) AS rejectedCount,
          COUNT(DISTINCT CASE WHEN do.hold = 1 THEN do.id END) AS holdCount
        FROM 
          design_orders do
        INNER JOIN 
          design_order_services dos ON do.id = dos.design_order_id  -- Ensure only orders with services are counted
        LEFT JOIN 
          partners p ON do.client = p.id
        WHERE 
          p.user_id = ${userId} 
          AND do.status NOT IN (0, 3);
      `;
    } else {
      query = `
        SELECT 
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 1 AND do.hold = 0 THEN do.id END) AS newCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 2 AND do.hold = 0 THEN do.id END) AS inProgressCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 3 AND do.hold = 0 THEN do.id END) AS completedCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 4 AND do.hold = 0 THEN do.id END) AS rejectedCount,
          COUNT(DISTINCT CASE WHEN do.hold = 1 THEN do.id END) AS holdCount
        FROM 
          design_orders do
        INNER JOIN 
          design_order_services dos ON do.id = dos.design_order_id  -- Exclude orders without services
        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)
          ${designerCondition};
      `;
    }
    
    const [results] = await sequelize.query(query);

    // Extract results
    const { newCount, inProgressCount, completedCount, holdCount, rejectedCount } = results[0] || {};

    // Ensure counts default to 0 if undefined
    return {
      newCount: newCount,
      inProgressCount:  inProgressCount,
      completedCount:  completedCount,
      holdCount:  holdCount,
      rejectedCount:  rejectedCount,
    };
  } catch (error) {
    console.error("Error fetching design order job counts:", error);
    throw error;
  }
};

const getOptimizedDesignOverviewCounts = async (userType, userId) => {
  try {
    let joinClause = '';
    let accessWhereClause = '1=1';

    if (userType === 3) {
      joinClause = ' LEFT JOIN partners p ON d.client = p.id ';
      accessWhereClause = 'p.user_id = :userId';
    } else if (userType !== 1 && userType !== 8) {
      joinClause = `
        LEFT JOIN design_order_project_members pm ON d.id = pm.design_order_id
        LEFT JOIN staff_members sm ON pm.staff_id = sm.id
      `;
      accessWhereClause = `
        (sm.user_id = :userId OR d.added_by = :userId)
        AND (d.working_designer_id IS NULL OR d.working_designer_id = :userId OR d.added_by = :userId)
      `;
    }

    const [rows] = await sequelize.query(
      `
      SELECT
        COUNT(DISTINCT CASE
          WHEN d.design_order_job_status = 1
            AND d.hold = 0
            AND d.status NOT IN (0, 3)
            AND EXISTS (
              SELECT 1 FROM design_order_services dos WHERE dos.design_order_id = d.id
            )
          THEN d.id END
        ) AS newDesignJobs,
        COUNT(DISTINCT CASE
          WHEN d.design_order_job_status = 3
            AND d.hold = 0
            AND d.status NOT IN (0, 3)
            AND EXISTS (
              SELECT 1 FROM design_order_services dos WHERE dos.design_order_id = d.id
            )
          THEN d.id END
        ) AS completedDesignJobs,
        COUNT(DISTINCT CASE WHEN d.status = 2 AND d.hold = 0 THEN d.id END) AS approvedDesigns,
        COUNT(DISTINCT CASE WHEN d.status = 6 AND d.hold = 0 THEN d.id END) AS rejectedDesigns,
        COUNT(DISTINCT CASE
          WHEN d.status = 1 AND d.hold = 0 AND d.is_in_queue = 0
            AND d.design_order_job_status = 1 AND d.send_client_app_req = 0
          THEN d.id END
        ) AS newDesigns,
        COUNT(DISTINCT CASE
          WHEN d.status = 1 AND d.hold = 0 AND d.is_in_queue = 1
            AND d.design_order_job_status = 1 AND d.send_client_app_req = 0
          THEN d.id END
        ) AS inQueueDesigns,
        COUNT(DISTINCT CASE
          WHEN d.status = 1 AND d.hold = 0
            AND d.design_order_job_status = 2 AND d.send_client_app_req = 0
          THEN d.id END
        ) AS inDesignOrders,
        COUNT(DISTINCT CASE
          WHEN d.design_order_job_status = 3
            AND d.send_client_app_req = 0 AND d.status != 0 AND d.hold = 0
          THEN d.id END
        ) AS designJobCompleted,
        COUNT(DISTINCT CASE
          WHEN d.status = 1 AND d.hold = 0 AND d.send_client_app_req = 1
          THEN d.id END
        ) AS designsAwaitingApproval,
        COUNT(DISTINCT CASE WHEN d.hold = 1 AND d.status != 0 THEN d.id END) AS designsOnHold
      FROM design_orders d
      ${joinClause}
      WHERE ${accessWhereClause}
      `,
      {
        replacements: { userId },
        type: sequelize.QueryTypes.SELECT,
      }
    );

    const data = rows || {};
    return {
      newDesignJobs: Number(data.newDesignJobs) || 0,
      completedDesignJobs: Number(data.completedDesignJobs) || 0,
      approvedDesigns: Number(data.approvedDesigns) || 0,
      rejectedDesigns: Number(data.rejectedDesigns) || 0,
      newDesigns: Number(data.newDesigns) || 0,
      inQueueDesigns: Number(data.inQueueDesigns) || 0,
      inDesignOrders: Number(data.inDesignOrders) || 0,
      designJobCompleted: Number(data.designJobCompleted) || 0,
      designsAwaitingApproval: Number(data.designsAwaitingApproval) || 0,
      designsOnHold: Number(data.designsOnHold) || 0,
    };
  } catch (error) {
    console.error('Error in getOptimizedDesignOverviewCounts:', error);
    throw error;
  }
};


const getDesignOrderJobCount = async (userType,userId) => {
  try {

    let query = '';
    const designerCondition = ` AND (do.working_designer_id IS NULL OR do.working_designer_id = ${userId}) `;
    if (userType === 1 || userType == 8) {
      query = `
        SELECT 
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 1 AND do.hold = 0 THEN do.id END) AS newCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 2 AND do.hold = 0 THEN do.id END) AS inProgressCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 3 AND do.hold = 0 THEN do.id END) AS completedCount,
          COUNT(DISTINCT CASE WHEN do.hold = 1 THEN do.id END) AS holdCount
        FROM 
          design_orders do
        INNER JOIN 
          design_order_services dos ON do.id = dos.design_order_id  -- Exclude design orders without services
        WHERE 
          do.status NOT IN (0, 3, 4);
      `;
    } else if (userType === 3) {
      query = `
        SELECT 
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 1 AND do.hold = 0 THEN do.id END) AS newCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 2 AND do.hold = 0 THEN do.id END) AS inProgressCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 3 AND do.hold = 0 THEN do.id END) AS completedCount,
          COUNT(DISTINCT CASE WHEN do.hold = 1 THEN do.id END) AS holdCount
        FROM 
          design_orders do
        INNER JOIN 
          design_order_services dos ON do.id = dos.design_order_id  -- Ensure only orders with services are counted
        LEFT JOIN 
          partners p ON do.client = p.id
        WHERE 
          p.user_id = ${userId} 
          AND do.status NOT IN (0, 3, 4);
      `;
    } else {
      query = `
        SELECT 
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 1 AND do.hold = 0 THEN do.id END) AS newCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 2 AND do.hold = 0 THEN do.id END) AS inProgressCount,
          COUNT(DISTINCT CASE WHEN do.design_order_job_status = 3 AND do.hold = 0 THEN do.id END) AS completedCount,
          COUNT(DISTINCT CASE WHEN do.hold = 1 THEN do.id END) AS holdCount
        FROM 
          design_orders do
        INNER JOIN 
          design_order_services dos ON do.id = dos.design_order_id  -- Exclude orders without services
        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} 
          AND do.status NOT IN (0, 3, 4)
          ${designerCondition};
      `;
    }
    
    // const [results] = await sequelize.query(query);

    // // Extract results
    // const { newCount, inProgressCount, completedCount, holdCount } = results[0] || {};

    // Ensure counts default to 0 if undefined
    return {
      newCount: 0,
      inProgressCount:  0,
      completedCount:  0,
      holdCount:  0,
    };
  } catch (error) {
    console.error("Error fetching design order job counts:", error);
    throw error;
  }
};


const updateDesignOrderJobStatus= async (data, id) => {
  let res = await DesignOrders.update(data, {
    where: { id: id }
  })
  if (res) {
    return true
  } else {
    return false
  }
}

const addDesignOrderStaffTaskTimelog = async(data)=>{
    try{
        const results = await designOrderStaffTaskTimelogs.create(data);
        if (results) {
            return results.dataValues.id;
        }
        else {
            return false;
        }
    }catch(error){
        console.error("Error adding the staff job timelog ", error);
        return false;
    }
}


const fetchClockedInDesignOrderStaffTaskTimelog = async (userId = null, designOrderId = null, taskId = null) => {
  try {
    let whereCondition = '';
    if (designOrderId) {
      whereCondition = ` AND dst.design_order_id = ${designOrderId} `;
    }
    if (taskId) {
      whereCondition += ` AND dst.task_id = ${taskId} `;
    }
    if (userId) {
      whereCondition += ` AND dst.user_id = ${userId} `;
    }

    const results = await sequelize.query(
      `SELECT dst.*, lcs.name AS task_name, 
              CONCAT(u.first_name, ' ', u.last_name) AS staff_name, 
              sm.id AS staff_id, sm.hourly_rate AS staff_hourly_rate,
              do.name AS design_order_name 
       FROM design_order_staff_task_timelogs dst 
       LEFT JOIN users u ON u.id = dst.user_id 
       LEFT JOIN staff_members sm ON sm.user_id = dst.user_id 
       LEFT JOIN design_order_services dos ON dos.id = dst.task_id 
       LEFT JOIN labour_cost_services lcs ON dos.labour_cost_service_id = lcs.id 
       LEFT JOIN design_orders do ON do.id = dst.design_order_id 
       WHERE dst.end_time IS NULL ${whereCondition}`
    );

    if (results[0]?.length) {
      return results[0];
    } else {
      return false;
    }
  } catch (error) {
    console.error("Error fetching the design order staff task timelog", error);
    return false;
  }
};


const updateDesignOrderStaffTaskTimelog = async(data, taskId, projectId, installationId, userId, timeLogId)=>{
    try{

        const whereCondition = {
            [Sequelize.Op.and]: [
                ...(taskId ? [{ task_id: taskId }] : []),
                ...(projectId ? [{ design_order_id: projectId }] : []),
                { user_id: userId },
                { id: timeLogId }
            ]
        };

        const results = await designOrderStaffTaskTimelogs.update(data, {
            where: whereCondition
        });

        if (results) {
            return true;
        }
        else {
            return false;
        }
    }catch(error){
        console.error("Error updating the staff job timelog ", error);
        return false;
    }
}




const addDesignOrderPayOut=async(data)=>{
  let res=await designOrderPayOut.create(data)
  return res.id;
}

const updateDesignPayOut=async(data,id)=>{
  let res=await designOrderPayOut.update(data, {
    where: { id: id }
  })
  return res;
}

const getDesignPayOutById=async(id)=>{
  let query= await sequelize.query(`SELECT d.* FROM design_order_payouts d
  WHERE id=${id}`)
  let data=[]
  if(query[0].length>0){
    data=query[0]
  }
  return data;
}

const deleteDesignPayOut=async(editId)=>{
  try{
    let deleted = await designOrderPayOut.destroy({
      where: { id : editId
      }
    });
    console.log('deletedddddd',deleted)
    if (deleted) {
          console.log('deletedddddd11',deleted)
      return true;
    }
    else {
      return false;
    }
  } catch (error) {
    console.log("Delete error......", error)
    return false;
  }
}

const deleteDesignStaffTaskTimelogsForPayout = async (projId,taskId,staffUserId,startTime,endTime) => {
    try {
        console.log('projId,taskId,staffUserId',projId,taskId,staffUserId)
        const deleted = await designOrderStaffTaskTimelogs.destroy({
            where: {
                design_order_id: projId,
                task_id:taskId,
                user_id:staffUserId,
                start_time:startTime,
                end_time: endTime
            },
        });
        if (deleted) {
            return true;
        }
        else {
            return false;
        }
    }
    catch (error) {
        console.log("Delete error......", error)
        return false;
    }
}


const getDesignOrderProjectTaskById = async (id) => {
  try {
    const query = await sequelize.query(
      `SELECT dos.*, 
              CONCAT(u.first_name, ' ', u.last_name) AS authorized_by, 
              do.name AS project_name 
       FROM design_order_services dos
       LEFT JOIN design_orders do ON dos.design_order_id = do.id
       LEFT JOIN users u ON do.client = u.id
       WHERE dos.id = ${id}`
    );

    if (query[0].length === 1) {
      return query[0];
    } else {
      return false;
    }
  } catch (error) {
    console.error("Error in getDesignOrderProjectTaskById:", error);
    throw error;
  }
};

const getDesignOrderServicesByDesignOrder = async (id, serviceId = false, productId = false, productIndex = false) => {
  try {
    let whereCondition = ''
    if (serviceId) {
      whereCondition += ` AND rs.labour_cost_service_id=${serviceId} `
    }
   
    if (productIndex) {
      whereCondition += ` AND rs.product_index='${productIndex}' `
    }
    const result = await sequelize.query(`SELECT DISTINCT rs.*,rs.quantity AS quantity,ls.name,ls.cost,ls.total_cost AS service_original_cost,ls.markup as originalMarkup
      FROM design_order_services rs 
      LEFT JOIN labour_cost_services ls ON ls.id = rs.labour_cost_service_id
       WHERE rs.design_order_id=${id} ${whereCondition}`)
    if (result[0]?.length > 0) {
      return result[0]
    } else {
      return []
    }
  } catch (error) {
    console.log(error, 'error in getRequestServices')
    return false
  }
}


const getDesignOrderPayOutByTaskId=async(taskId, team_id=false,jobcostTimelog)=>{
  try{
    let whereCondition = '';
    if(team_id){
      whereCondition = ` and team = ${team_id}  `
      // whereCondition = ` and team = ${team_id} or added_by = ${team_id} `
    }
    // if(jobcostTimelog && !team_id){
    //   whereCondition = ` or team IS NULL `
    // }
    let query= await sequelize.query(`SELECT p.* FROM design_order_payouts p
    WHERE task_id=${taskId} ${whereCondition}`)
    let data=[]
    if(query[0].length>0){
      data=query[0]
    }
    return data;
  }catch(error){
    return [];
  }
}


const updateDesignOrderLogStatus = async(data, id)=>{
    try{
        const results = await designOrderStaffTaskTimelogs.update(data,{
            where : { id:id }
        });
        if (results) {
            return true;
        }
        else {
            return false;
        }
    }catch(error){
        console.error("Error updating the staff job timelog ", error);
        return false;
    }
}

const fetchAllPayOutByDesignOrderId=async(projectId)=>{
  let query= await sequelize.query(`SELECT p.* FROM design_order_payouts p
  WHERE design_order_id=${projectId} and p.status=1`)
  let data=[]
  if(query[0].length>0){
    data=query[0]
  }
  return data;
}

const getAllDesignOrderAttachments=async(projectId)=>{
  let query= await sequelize.query(`SELECT doa.* FROM design_order_attachments doa
  WHERE doa.design_order_id=${projectId} AND doa.is_reference = 0 order by id desc`)
  let data=[]
  if(query[0].length>0){
    data=query[0]
  }
  return data;
}

const getAllDesignOrderReferenceAttachments=async(projectId)=>{
  let query= await sequelize.query(`SELECT doa.* FROM design_order_attachments doa
  WHERE doa.design_order_id=${projectId} AND doa.is_reference = 1 order by id desc`)
  let data=[]
  if(query[0].length>0){
    data=query[0]
  }
  return data;
}


const getAllRequestAttachmentsForCards = async (requestId, isFromDesignOrder) => {
  let whereCondition = isFromDesignOrder
    ? { request_id: requestId, status: 1 }  
    : { request_id: requestId, status: 1, approved: 1 };  

  let res = await RequestAttachments.findAll({
    where: whereCondition,
    order: [['id', 'DESC']] 
  });

  return res;
};

// NEW OPTIMIZED FUNCTION - getAllRequestsOptimized
// This function combines all optimizations including bulk attachment fetching and optimized query processing
const getAllRequestsOptimized = async (requestId, userId, userType, page, rowPerpage, search, where = '', sort, fromDate, toDate, filterCommunity, dueData, clientFilter, filterProjectType, filterUser, splitOrder, filterProjectCategory) => {
  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 r.participation_ends BETWEEN ${fromTimestamp} AND ${toTimestamp}`;
    } else if (fromTimestamp) {
      dateCondition = `AND r.participation_ends >= ${fromTimestamp}`;
    } else if (toTimestamp) {
      dateCondition = `AND r.participation_ends <= ${toTimestamp}`;
    }

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

    let offset = null
    if (rowPerpage && page) {
      offset = (page - 1) * rowPerpage;
    }
    let totalCount = 0
    let allCount=0
    let openCount=0
    let acceptedCount=0
    let inProductionCount=0
    let completedCount=0
    let installsCount=0
    let totalCompletedCount = 0
    let partnerWhere = '';
    let query = '';
    let countQuery = '';
    let content = ''

    if (search) {
      const escapedSearch = search.replace(/'/g, "''").trim();
      const normalizedSearch = escapedSearch.toLowerCase();
    
      content = `AND (
        LOWER(COALESCE(r.name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.description, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(pc.name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(c_ord.customer_name, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.doc_number, '')) LIKE '%${normalizedSearch}%'
        OR LOWER(COALESCE(r.est_doc_number, '')) LIKE '%${normalizedSearch}%'`
      
      // Include com.name only if userType is not 3 (com is joined only in that case)
      if (userType !== 3) {
        content += ` OR LOWER(COALESCE(com.name, '')) LIKE '%${normalizedSearch}%'`;
      }
    
      content += `)`;
    }   

    let WhereCondition = ''
    let CountwhereCondition = ''
    if (requestId) {
      WhereCondition = ` r.id=${requestId}`
      CountwhereCondition = ` r.id=${requestId}`
    }
    else {
      WhereCondition = ` r.status <>0  and r.status<>8 ${dateCondition}`
      CountwhereCondition = ` r.status <>0  and r.status<>8 ${dateCondition}`
      if (!empty(where)) {
        WhereCondition = ` r.status != 0  and r.status<>8 AND ${where} ${dateCondition}`
        CountwhereCondition = ` r.status != 0  and r.status<>8 ${dateCondition}`
      }
    }

    if (!WhereCondition.trim()) {
      WhereCondition = '1=1'; 
    }
    if (!CountwhereCondition.trim()) {
      CountwhereCondition = '1=1'; 
    }
    let community=''
    let communityConditionNew=''
    if (filterCommunity && filterCommunity.length > 0) {
      const communityCondition = ` AND r.community IN (${filterCommunity.join(',')}) `;
      communityConditionNew = ` WHERE r.community IN (${filterCommunity.join(',')}) `;
      WhereCondition += ` ${communityCondition}`;
      CountwhereCondition += ` ${communityCondition}`;
      community += ` ${communityCondition}`;
    }
    let clientCondition = '';
    let clientConditionNew = '';
    if (clientFilter && clientFilter.length > 0) {
      const clientFilterCondition = ` AND c_ord.customer_id IN (${clientFilter.join(',')}) `;
      clientConditionNew = ` WHERE c_ord.customer_id IN (${clientFilter.join(',')}) `;
      WhereCondition += ` ${clientFilterCondition}`;
      CountwhereCondition += ` ${clientFilterCondition}`;
      clientCondition += ` ${clientFilterCondition}`;
    }

    let userCondition = '';
    let userConditionNew = '';
    if (filterUser && filterUser.length > 0) {
      const projectMemberExists = `EXISTS (SELECT 1 FROM projects p JOIN project_members pm ON pm.project_id = p.id WHERE p.request_id = r.id AND p.is_estimate_job=0 AND pm.staff_id IN (${filterUser.join(',')}))`;
      const collaboratorChecks = filterUser.map((id) => `FIND_IN_SET(${parseInt(id, 10)}, REPLACE(TRIM(COALESCE(r.collaborators,'')), ' ', '')) > 0`).join(' OR ');
      const userFilterCondition = ` AND ( ${projectMemberExists} OR (TRIM(COALESCE(r.collaborators,'')) != '' AND (${collaboratorChecks})) ) `;
      userConditionNew = ` WHERE ( ${projectMemberExists} OR (TRIM(COALESCE(r.collaborators,'')) != '' AND (${collaboratorChecks})) ) `;
      WhereCondition += ` ${userFilterCondition}`;
      CountwhereCondition += ` ${userFilterCondition}`;
      userCondition += ` ${userFilterCondition}`;
    }

    if (filterProjectType === 1) {
      WhereCondition += ` AND r.project_type = 1`;
    } else if (filterProjectType === 2) {
      WhereCondition += ` AND r.project_type = 2`;
    }else if (filterProjectType === 3) {
      WhereCondition += ` AND r.is_split_order = 1`;
    } else if (filterProjectType === 'NULL'){
      WhereCondition += ` AND r.project_type IS NULL`;
    } else {
      WhereCondition += ` AND (r.project_type IS NULL OR r.project_type IS NOT NULL)`;
    }

    if(filterProjectCategory == 1){
      WhereCondition += ` AND r.project_category = 15`;
    }else if(filterProjectCategory == 2){
      WhereCondition += ` AND r.project_category = 9`;
    }

    let limit = ''
    if (rowPerpage) {
      limit = `LIMIT ${rowPerpage} OFFSET ${offset}`
    }

    if (userType != 3) {
      
      query = await sequelize.query("SELECT `r`.*,proj.noServiceNoTask AS proj_noServiceNoTask,proj.status AS proj_status,proj.id AS isProject,rp.id as rt_partner_id ,c_ord.total as invoice_total,CONCAT(u.first_name, ' ', u.last_name) as added_by_name, u.user_type as added_by_user_type, c_ord.grandTotal as invoice_grand_total,u2.profile_pic AS customer_pic,com.name AS community_name, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count,i.status as installationStatus,i.complete_status AS installationCompleteStatus, COALESCE(i.pending_review, 0) AS installation_pending_review,c_ord.customer_name,c_ord.customer_id,ct.billing_type, "
        + ` 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,`
        + ` CASE 
                WHEN r.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 r.project_category = 11 THEN 
                CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
                WHEN r.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 proj.status = 3 AND proj.noServiceNoTask = 0
            )
            THEN 1
            ELSE 0
          END AS allInstallationCompleted,`
          + `CASE 
            WHEN 
            (
              (COALESCE(inst_non_edit.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
            )
            THEN 1
            ELSE 0
          END AS enableEditOnStaged,`
        + ` COALESCE(reqPay.totalAmount, 0) AS totalPaidAmount,`
        + ` (COALESCE(c_ord.total, 0) - COALESCE(reqPay.totalAmount, 0)) AS dueAmount,`
        + ` inst_counts.installation_count, inst_non_edit.installation_count AS staged_installation_count, total_inst_counts.total_installation_count, cop.product_count, rss.service_count, `
        + ` CASE WHEN COALESCE(partial_inst.partial_installation_count, 0) > 0 THEN 1 ELSE 0 END AS partial_install, `
        + ` COALESCE(mixed_inst.mixed_installation, 0) AS mixed_installation, `
        + " pc.name AS job_category_name FROM `requests` `r` "
        + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
        + " LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c "
        + " left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id LIMIT 1),0) and c.user_id!=1 group by c.request_id) rm ON `r`.`id`=`rm`.`request_id` "
        + " LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM `request_proposals` where status=1 group by request_id) rps ON `rps`.`request_id`=`r`.`id` "
        // + ` LEFT JOIN community com ON com.id = r.community`
        + ` left join customer_orders c_ord on c_ord.request_id = r.id `
        + ` left join projects proj on proj.request_id = r.id  AND proj.is_estimate_job = 0`
        + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
        + ` LEFT JOIN request_partners rp ON rp.request_id=r.id`
        + ` left join partners p2 on p2.id = c_ord.customer_id `
        + ` left join customer_type ct on p2.customerTypeId = ct.id `
        + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
        + ` left join users u2 on u2.id = p2.user_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 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, 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 installation_count FROM installations WHERE status = 1 GROUP BY request_id) inst_non_edit ON inst_non_edit.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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id) partial_inst ON partial_inst.request_id = r.id `
        + ` LEFT JOIN (SELECT request_id, CASE WHEN COUNT(DISTINCT COALESCE(complete_status, -1)) > 1 THEN 1 ELSE 0 END AS mixed_installation FROM installations GROUP BY request_id) mixed_inst ON mixed_inst.request_id = r.id `
        + ` LEFT JOIN users u ON r.added_by=u.id WHERE ${WhereCondition} ${content} ${createdAt} ${limit}`)

      // totalCount = await sequelize.query(`SELECT COUNT(r.id) as totalCount FROM requests r `
      //   + ` LEFT JOIN project_categories pc ON pc.id = r.project_category `
      //   + " LEFT JOIN (select count(c.id) as cnt,c.request_id from request_messages c "
      //   + " left join partners p on p.id=c.partner_id where c.timestamp>=COALESCE((select rml.timestamp from request_message_last_seen rml where rml.request_id=c.request_id and rml.user_id=1 and rml.partner_id=c.partner_id LIMIT 1),0) and c.user_id!=1 group by c.request_id) rm ON `r`.`id`=`rm`.`request_id` "
      //   + " LEFT JOIN (SELECT COUNT(id) as cnt,request_id FROM `request_proposals` where status=1 group by request_id) rps ON `rps`.`request_id`=`r`.`id` "
      //   + ` left join customer_orders c_ord on c_ord.request_id = r.id `
      //   + ` left join projects proj on proj.request_id = r.id `
      //   + ` LEFT JOIN  community com ON com.id=r.community and FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1`
      //   + ` JOIN request_partners rp ON rp.request_id=r.id`
      //   + ` left join partners p2 on p2.id = c_ord.customer_id `
      //   + ` left join customer_type ct on p2.customerTypeId = ct.id `
      //   + ` left join (SELECT SUM(amount) AS totalAmount,request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay on reqPay.request_id = r.id `
      //   + ` left join users u2 on u2.id = p2.user_id `
      //   + ` 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 = 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, 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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id) partial_inst ON partial_inst.request_id = r.id `
      //   + ` LEFT JOIN users u ON r.added_by=u.id WHERE ${WhereCondition} ${content}`);
    }
    if (userType == 3) {
      query = await sequelize.query(`SELECT rp.id as rt_partner_id,proj.noServiceNoTask AS proj_noServiceNoTask,proj.status AS proj_status,proj.id AS isProject, u2.profile_pic AS customer_pic, com.name AS community_name, rp.accept_status, i.status as installationStatus,CONCAT(u.first_name, ' ', u.last_name) as added_by_name, u.user_type as added_by_user_type, i.complete_status AS installationCompleteStatus, COALESCE(i.pending_review, 0) AS installation_pending_review, p.user_id as partner_user_id, trps.proposal_added_by, trps.proposal_status, r.*, coalesce(rm.cnt, 0) as msg_count, coalesce(rps.cnt, 0) as proposal_count, CONCAT(u.first_name, " ", u.last_name) as send_to, u.id as sender_id, u.profile_pic as pic, c_ord.customer_name,c_ord.customer_id, ct.billing_type, 
        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, 
        CASE 
          WHEN r.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 r.project_category = 11 THEN 
          CASE WHEN inst_counts.installation_count >= COALESCE(rss.service_count, 0) THEN 1 ELSE 0 END 
          WHEN r.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 proj.status = 3 AND proj.noServiceNoTask = 0
            )
            THEN 1
            ELSE 0
          END AS allInstallationCompleted,
          CASE 
            WHEN 
              (
                (COALESCE(inst_non_edit.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
              )
              THEN 1
              ELSE 0
          END AS enableEditOnStaged,
        COALESCE(reqPay.totalAmount, 0) AS totalPaidAmount, 
        (COALESCE(c_ord.total, 0) - COALESCE(reqPay.totalAmount, 0)) AS dueAmount, 
        inst_counts.installation_count,inst_non_edit.installation_count AS staged_installation_count, total_inst_counts.total_installation_count, cop.product_count, rss.service_count, 
        CASE WHEN COALESCE(partial_inst.partial_installation_count, 0) > 0 THEN 1 ELSE 0 END AS partial_install,
        COALESCE(mixed_inst.mixed_installation, 0) AS mixed_installation,
        pc.name AS job_category_name
        FROM requests r 
      LEFT JOIN project_categories pc ON pc.id = r.project_category 
      LEFT JOIN (SELECT COUNT(c.id) AS cnt, c.request_id FROM request_messages c 
          LEFT JOIN partners p ON p.id = c.partner_id WHERE c.timestamp >= COALESCE((SELECT rml.timestamp FROM request_message_last_seen rml WHERE rml.request_id = c.request_id AND rml.user_id = ${userId} AND rml.partner_id = c.partner_id LIMIT 1), 0) AND c.user_id != ${userId} AND p.user_id = ${userId} GROUP BY c.request_id) rm ON r.id = rm.request_id 
      LEFT JOIN (SELECT COUNT(id) AS cnt, request_id FROM request_proposals WHERE status = 1 GROUP BY request_id) rps ON rps.request_id = r.id 
      LEFT JOIN users u ON r.added_by = u.id 
      LEFT JOIN request_partners rp ON rp.request_id = r.id 
      JOIN partners p ON p.id = rp.partner_id 
      LEFT JOIN customer_orders c_ord ON c_ord.request_id = r.id
      left join projects proj on proj.request_id = r.id AND proj.is_estimate_job = 0
      LEFT JOIN partners p2 ON p2.id = c_ord.customer_id 
      LEFT JOIN customer_type ct ON p2.customerTypeId = ct.id 
      LEFT JOIN users u2 ON u2.id = p2.user_id 
      LEFT JOIN community com ON com.id = r.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1 
      LEFT JOIN (SELECT request_id AS rid, added_by AS proposal_added_by, COALESCE(status, 'NA') AS proposal_status FROM request_proposals WHERE added_by = ${userId}) trps ON trps.rid = r.id 
    
      LEFT JOIN (SELECT MAX(status) AS status, MAX(complete_status) AS complete_status, request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id
    
      LEFT JOIN (SELECT SUM(amount) AS totalAmount, request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay ON reqPay.request_id = r.id 
      LEFT JOIN (
        SELECT request_id, COUNT(*) AS installation_count 
        FROM installations 
        WHERE status = 1 
        GROUP BY request_id
      ) inst_non_edit ON inst_non_edit.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, 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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id) partial_inst ON partial_inst.request_id = r.id
      LEFT JOIN (SELECT request_id, CASE WHEN COUNT(DISTINCT COALESCE(complete_status, -1)) > 1 THEN 1 ELSE 0 END AS mixed_installation FROM installations GROUP BY request_id) mixed_inst ON mixed_inst.request_id = r.id
      WHERE p.user_id = ${userId} AND ${WhereCondition} AND r.status != 1 ${content} ${createdAt} ${limit}`);
    
          // totalCount = await sequelize.query(`select count(r.id) as totalCount from requests r
          //   LEFT JOIN project_categories pc ON pc.id = r.project_category 
          //   LEFT JOIN (SELECT COUNT(c.id) AS cnt, c.request_id FROM request_messages c 
          //   LEFT JOIN partners p ON p.id = c.partner_id WHERE c.timestamp >= COALESCE((SELECT rml.timestamp FROM request_message_last_seen rml WHERE rml.request_id = c.request_id AND rml.user_id = ${userId} AND rml.partner_id = c.partner_id LIMIT 1), 0) AND c.user_id != ${userId} AND p.user_id = ${userId} GROUP BY c.request_id) rm ON r.id = rm.request_id 
          //   LEFT JOIN (SELECT COUNT(id) AS cnt, request_id FROM request_proposals WHERE status = 1 GROUP BY request_id) rps ON rps.request_id = r.id 
          //   JOIN users u ON r.added_by = u.id 
          //   JOIN request_partners rp ON rp.request_id = r.id 
          //   JOIN partners p ON p.id = rp.partner_id 
          //   LEFT JOIN customer_orders c_ord ON c_ord.request_id = r.id 
          //   left join projects proj on proj.request_id = r.id
          //   LEFT JOIN partners p2 ON p2.id = c_ord.customer_id 
          //   LEFT JOIN customer_type ct ON p2.customerTypeId = ct.id 
          //   LEFT JOIN users u2 ON u2.id = p2.user_id 
          //   LEFT JOIN community com ON com.id = r.community AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0 AND com.status = 1 
          //   LEFT JOIN (SELECT request_id AS rid, added_by AS proposal_added_by, COALESCE(status, 'NA') AS proposal_status FROM request_proposals WHERE added_by = ${userId}) trps ON trps.rid = r.id 
          
          //   LEFT JOIN (SELECT MAX(status) AS status, MAX(complete_status) AS complete_status, request_id FROM installations GROUP BY request_id) i ON i.request_id = r.id
          
          //   LEFT JOIN (SELECT SUM(amount) AS totalAmount, request_id FROM request_payments WHERE status = 1 GROUP BY request_id) reqPay ON reqPay.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, 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 request_id, COUNT(*) AS partial_installation_count FROM installations WHERE status = 5 GROUP BY request_id
          //   ) partial_inst ON partial_inst.request_id = r.id 
          //   WHERE p.user_id = ${userId} AND ${WhereCondition} AND r.status != 1 ${content} `
          // )
    }
    let result = query[0]

    if (result.length >= 1) {
      
      // const allRequestIds = result.map((row) => row.id);
      
      // Attachments/designs/partners fetching removed as per requirement. Backup retained in comments.
      // const [allDesigns, allPartners, allAttachments] = await Promise.all([
      //   FetchAllApprovedDesignsBulk(allRequestIds),
      //   getRequestPartnersBulk(false, allRequestIds),
      //   getAllRequestAttachmentsForCardsBulk(allRequestIds, result.reduce((map, row) => {
      //     map[row.id] = row.isFromDesignOrder;
      //     return map;
      //   }, {}))
      // ]);

      // const designsMap = {};
      // allDesigns.forEach((design) => {
      //   if (!designsMap[design.request_id]) designsMap[design.request_id] = [];
      //   designsMap[design.request_id].push(design);
      // });

      // const partnersMap = {};
      // allPartners.forEach((partner) => {
      //   if (!partnersMap[partner.request_id]) partnersMap[partner.request_id] = [];
      //   partnersMap[partner.request_id].push(partner);
      // });

      // const attachmentsMap = {};
      // allAttachments.forEach((attachment) => {
      //   if (!attachmentsMap[attachment.request_id]) attachmentsMap[attachment.request_id] = [];
      //   attachmentsMap[attachment.request_id].push(attachment);
      // });

      // Simplified mapping - no attachments/designs/partners enrichment
      const newData = result.map((row) => {
        return parseDecimalFields(row);
      });

      return {
        data: newData,
        totalCount: 0,
        allCount: 0,
        openCount: 0,
        acceptedCount: 0,
        inProductionCount: 0,
        completedCount: 0,
        installsCount: 0,
        pickupCount: 0,
        shippingCount: 0
       };
    }
    else {
      return { data:[], 
        totalCount: 0,
        allCount: 0,
        openCount: 0,
        acceptedCount: 0,
        inProductionCount: 0,
        completedCount: 0,
        installsCount: 0,
        pickupCount: 0,
        shippingCount: 0
       };
    }
  } catch (error) {
    console.error(error);
    return error;
  }
};

// INTERNAL HELPER FUNCTION - Bulk attachment fetching (used only within getAllRequestsOptimized)
const getAllRequestAttachmentsForCardsBulk = async (requestIds, isFromDesignOrderMap = {}) => {
  if (!requestIds || requestIds.length === 0) {
    return [];
  }

  // Create a map to track which requests are from design orders
  const requestIdList = requestIds.join(',');
  
  // Use raw SQL for better performance with bulk operations
  const query = `
    SELECT * 
    FROM request_attachments 
    WHERE request_id IN (${requestIdList}) 
      AND status = 1 
      AND (
        CASE 
          WHEN request_id IN (${Object.keys(isFromDesignOrderMap).filter(id => isFromDesignOrderMap[id]).join(',') || '0'}) 
          THEN 1=1 
          ELSE approved = 1 
        END
      )
    ORDER BY request_id, id DESC
  `;

  const result = await sequelize.query(query, {
    type: sequelize.QueryTypes.SELECT,
  });

  return result;
};

const updateRequestAttachmentsDeisgnOrderId = async (attachmentId,requestId, data) => {
  let res = await RequestAttachments.update(data, {
    where: { request_id: requestId, id:attachmentId }
  })
  return res;
}


const getDesignOrderByIdNew = async (id) => {
  let res = await DesignOrders.findAll( {
    where: { id: id }
  })
  if (res) {
    return res
  } else {
    return false
  }
}

const updateRequestAttachmentsById = async (id, data) => {

  let res = await RequestAttachments.update(data, {
    where: { id: id }
  })
  return res;
}

const updateRequestById = async (id, data) => {

  let res = await Requests.update(data, {
    where: { id: id }
  })
  return res;
}

const updateRequestByOriginFacilityId = async (originFacilityId, requestId, data) => {
  let res = await Requests.update(data, {
    where: { origin_facility_id: originFacilityId, origin_facility_request_id: requestId, status: 0 }
  })
  return res;
}

const FindReqDataById = async (id) => {
  let res = await Requests.findAll( {
    where: { id: id }
  })
  if (res) {
    return res[0].dataValues
  } else {
    return false
  }
}

const deleteRequestAttachments = async (id) => {
  try{
    let result = await RequestAttachments.destroy({
      where: { request_id: id }
    })
    if (result[0] > 0) {
      return true;
    } else {
      return false;
    }
  }catch(error){
    console.log('Error : ',error);
    return error
  }
}
  const addEstimateTabCount = async (data) => {
    try {
      const [newOrderCount, created] = await EstimateTabCount.findOrCreate({
        where: { user_id: data.user_id },
        defaults: { 
          open_count: 0,
          approved_count: 0,
          archive_count: 0,
          open_count_ids: null,
          approved_count_ids: null,
          archive_count_ids: null,
          timestamp: data.timestamp

        }
      });
  
      return newOrderCount.id;
    } catch (error) {
      console.error('Failed to add estimate tab count:', error);
      throw error;
    }
  };

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

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

  const EstimateTabIncrementField = async (userId, field, amount, fieldIds, estimateId, increase = true) => {
    try {
      const userCount = await EstimateTabCount.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(estimateId.toString())) {
          console.warn(`Estimate ID not found in ${fieldIds}, cannot reduce count.`);
          return false;
        }
      }
      if (increase) {
        if (!currentIds.includes(estimateId.toString())) {
          currentIds.push(estimateId.toString());
          amount = 1;
        } else {
          console.warn(`Estimate ID ${estimateId} already exists in ${fieldIds}, count remains the same.`);
          amount = 0;
        }
      } else {
  
        currentIds = currentIds.filter(id => id !== estimateId.toString());
      }
      const fieldUpdate = sequelize.literal(`GREATEST(${field} + (${amount}), 0)`);
      
      const result = await EstimateTabCount.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 getEstimateTabCountByUser = async (userId) => {
    let res = await EstimateTabCount.findOne({
      where: { user_id: userId, status: 1 }
    })
    return res;
  }
  const getEstimateCountByUser = async (userId) => {
    let res = await EstimateTabCount.findOne({
      where: { user_id: userId, status: 1 }
    })
    return res;
  }

  const addSalesOrderTabCount = async (data) => {
    try {
      console.log('sales order adding')
      const [newOrderCount, created] = await SalesOrderTabCount.findOrCreate({
        where: { user_id: data.user_id },
        defaults: { 
          open_count: 0,
          approved_count: 0,
          in_production_count: 0,
          installs_count: 0,
          pickup_count: 0,
          shipping_count: 0,
          invoicing_count: 0,
          completed_count: 0,
          timestamp: data.timestamp
        }
      });
      console.log("Sales order count added")
  
      return newOrderCount.id;
    } catch (error) {
      console.error('Failed to add estimate tab count:', error);
      throw error;
    }
  };

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

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

  const salesOrderIncrementField = async (userId, field, amount, fieldIds, requestId, increase = true) => {
    try {
      const userCount = await SalesOrderTabCount.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(requestId.toString())) {
          console.warn(`Sales order ID not found in ${fieldIds}, cannot reduce count.`);
          return false;
        }
      }
      if (increase) {
        if (!currentIds.includes(requestId.toString())) {
          currentIds.push(requestId.toString());
          amount = 1;
        } else {
          console.warn(`Sales order ID ${requestId} already exists in ${fieldIds}, count remains the same.`);
          amount = 0;
        }
      } else {
  
        currentIds = currentIds.filter(id => id !== requestId.toString());
      }
      const fieldUpdate = sequelize.literal(`GREATEST(${field} + (${amount}), 0)`);
      
      const result = await SalesOrderTabCount.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 getSalesOrderCountByUser = async (userId) => {
    let res = await SalesOrderTabCount.findOne({
      where: { user_id: userId, status: 1 }
    })
    return res;
  }

  const chageNewSalesOrderStatus = async (requestId) => {
    let res = await Requests.update({new_order: 0}, {
      where: { id: requestId }
    })
    return res;
  }


  const getJobCostDetails = async (requestId) => {
    try {
      const [result] = await sequelize.query(`
        SELECT 
  r.name,
  r.id,
  pt.quickBookId AS projectTypeQuickBookId,

  (
    SELECT COALESCE(SUM(jc.total), 0)
    FROM projects p
    LEFT JOIN job_costs jc ON jc.project_id = p.id
    WHERE p.request_id = r.id
      AND jc.taken = 1
  ) AS productTotal,
  (
    SELECT COALESCE(SUM(rs.jobcost_total_cost), 0)
    FROM request_services rs
    WHERE rs.request_id = r.id
      AND rs.taken = 1
  ) AS serviceTotal
FROM 
  requests r
  left join project_types pt on pt.id = r.project_type
WHERE 
  r.id = :requestId;


      `, {
        replacements: { requestId },
        type: sequelize.QueryTypes.SELECT
      });
  
      return result;
    } catch (error) {
      console.error("Error fetching job cost total:", error);
      throw error;
    }
  };
  

  // async function run() {
  //   let EstimateData = await getJobCostDetails(378);
  //   console.log("EstimateData",EstimateData)
  // }
  // run()
  const getJobCostDetailsForMaterials = async (requestId) => {
    try {
      const [result] = await sequelize.query(`
        SELECT 
  r.name,pt.quickBookId AS projectTypeQuickBookId,
  r.id,r.doc_number,r.syncWithQuickbooks,

  -- Total taken product cost
  (
    SELECT COALESCE(SUM(jc.total), 0)
    FROM projects p
    LEFT JOIN job_costs jc ON jc.project_id = p.id
    LEFT JOIN material_inventory mi ON mi.id = jc.product_id
    LEFT JOIN products prod ON prod.id = mi.material_id
    WHERE p.request_id = r.id AND jc.taken = 1
    ) AS productTotal,
    
  --  AND mi.receive_order_id IS NOT NULL
  -- Total taken service cost
  (
    SELECT COALESCE(SUM(rs.jobcost_total_cost), 0)
    FROM request_services rs
    WHERE rs.request_id = r.id
      AND rs.taken = 1
  ) AS serviceTotal,

  -- 1 if all job_costs have taken = 1 (or no job_costs), else 0
  (
    SELECT 
      CASE 
        WHEN COUNT(jc.id) = 0 THEN 1
        WHEN COUNT(jc.id) = SUM(CASE WHEN jc.taken = 1 THEN 1 ELSE 0 END) THEN 1
        ELSE 0
      END
    FROM projects p
    LEFT JOIN job_costs jc ON jc.project_id = p.id
    WHERE p.request_id = r.id
  ) AS everyProductTaken,

  -- 1 if all request_services have taken = 1 (or no services), else 0
  (
    SELECT
      CASE
        WHEN COUNT(jc.id) = 0 THEN 1
        WHEN COUNT(jc.id) = SUM(CASE WHEN jc.taken = 1 THEN 1 ELSE 0 END) THEN 1
        ELSE 0
      END
    FROM projects p
    LEFT JOIN job_costs jc ON jc.project_id = p.id
    WHERE p.request_id = r.id
  ) AS everyProductTaken,

  -- 1 if all request_services have taken = 1 (or no services), else 0
(
  SELECT
    CASE
      WHEN COUNT(rs.id) = 0 THEN 1
      WHEN COUNT(rs.id) = SUM(
        CASE 
          WHEN rs.taken = 1 THEN 1 
          ELSE 0 
        END
      ) THEN 1
      ELSE 0
    END
  FROM request_services rs
  LEFT JOIN labour_cost_services lcs 
         ON lcs.id = rs.labour_cost_service_id
  LEFT JOIN products p 
         ON p.id = rs.product_id
  WHERE rs.request_id = r.id
    AND (
          (
            rs.product_id IS NOT NULL
            AND p.inhouse = 1
            AND p.isTrafficcatalog = 0
            AND lcs.jobCost = 1
          )
          OR
          (
            rs.product_id IS NOT NULL
            AND (p.inhouse != 1 OR p.isTrafficcatalog != 0)
            AND rs.recipe_id IS NULL
          )
          OR
          (
            rs.product_id IS NULL
            AND lcs.jobCost = 1
          )
        )
) AS everyServiceTaken

FROM 
  requests r
  left join project_types pt on pt.id = r.project_type
WHERE 
  r.id = :requestId;

      `, {
        replacements: { requestId },
        type: sequelize.QueryTypes.SELECT
      });
  
      return result;
    } catch (error) {
      console.error("Error fetching job cost total:", error);
      throw error;
    }
  };

//   const getJobCostDetailsForMaterials = async (requestId) => {
//     try {
//       const [result] = await sequelize.query(`
//         SELECT 
//   r.name,
//   r.id,

//   -- Total taken product cost
//   (
//     SELECT COALESCE(SUM(jc.total), 0)
//     FROM projects p
//     LEFT JOIN job_costs jc ON jc.project_id = p.id
//     LEFT JOIN material_inventory mi ON mi.id = jc.product_id
//     LEFT JOIN products prod ON prod.id = mi.material_id
//     WHERE p.request_id = r.id AND jc.taken = 1
//     ) AS productTotal,
    
//   --  AND mi.receive_order_id IS NOT NULL
//   -- Total taken service cost
//   (
//     SELECT COALESCE(SUM(rs.jobcost_total_cost), 0)
//     FROM request_services rs
//     WHERE rs.request_id = r.id
//       AND rs.taken = 1
//   ) AS serviceTotal,

//   -- 1 if all job_costs have taken = 1 (or no job_costs), else 0
//   (
//     SELECT 
//       CASE 
//         WHEN COUNT(jc.id) = 0 THEN 1
//         WHEN COUNT(jc.id) = SUM(CASE WHEN jc.taken = 1 THEN 1 ELSE 0 END) THEN 1
//         ELSE 0
//       END
//     FROM projects p
//     LEFT JOIN job_costs jc ON jc.project_id = p.id
//     WHERE p.request_id = r.id
//   ) AS everyProductTaken,

//   -- 1 if all request_services have taken = 1 (or no services), else 0
//   (
//     SELECT 
//       CASE 
//         WHEN COUNT(rs.id) = 0 THEN 1
//         WHEN COUNT(rs.id) = SUM(CASE WHEN rs.taken = 1 THEN 1 ELSE 0 END) THEN 1
//         ELSE 0
//       END
//     FROM request_services rs
//     LEFT JOIN labour_cost_services lcs ON lcs.id = rs.labour_cost_service_id 
//     WHERE rs.request_id = r.id AND lcs.jobCost = 1
//   ) AS everyServiceTaken

// FROM 
//   requests r
// WHERE 
//   r.id = :requestId;

//       `, {
//         replacements: { requestId },
//         type: sequelize.QueryTypes.SELECT
//       });
  
//       return result;
//     } catch (error) {
//       console.error("Error fetching job cost total:", error);
//       throw error;
//     }
//   };

  const getJobCostMaterialDetails = async (requestId) => {
    try {
      const result = await sequelize.query(`
        SELECT 
  r.name AS request_name,
  r.id AS request_id,
  jc.total,
  jc.taken,
  jc.id,
  jc.product_id,
  jc.qb_journal_entry,
  jc.actual_unit_price,
  prod.syncWithQuickbooks,

  CASE 
    WHEN mi.receive_order_id IS NOT NULL THEN TRUE
    ELSE FALSE
  END AS isReceived

FROM 
  requests r
JOIN projects p ON p.request_id = r.id
JOIN job_costs jc ON jc.project_id = p.id
LEFT JOIN material_inventory mi ON mi.id =jc.product_id
LEFT JOIN products prod ON prod.id =mi.material_id
WHERE 
  r.id =:requestId AND mi.receive_order_id IS NOT NULL AND prod.syncWithQuickbooks =1

      `, {
        replacements: { requestId },
        type: sequelize.QueryTypes.SELECT
      });
  
      return result;
    } catch (error) {
      console.error("Error fetching job cost total:", error);
      throw error;
    }
  };

const getDesignOrderDesigners = async (design_order_id) => {
  try {
    const result = await sequelize.query(
      `SELECT staff_id as id
       FROM design_order_project_members
       WHERE design_order_id = :design_order_id
       AND staff_id IS NOT NULL`,
      {
        replacements: { design_order_id },
        type: sequelize.QueryTypes.SELECT
      }
    );
    return result; // Correct: returns array of { id: ... }
  } catch (error) {
    console.error('Error fetching design order designers (raw SQL):', error);
    return [];
  }
};

const getUsersByIds = async (ids) => {
  try {
    if (!ids || ids.length === 0) return [];

    const idList = ids.map(id => parseInt(id)).filter(Boolean).join(',');
    
    const [result] = await sequelize.query(`
      SELECT 
        sm.id AS id, 
        CONCAT(sm.first_name, ' ', COALESCE(sm.last_name, '')) AS name, 
        sm.email,
        sm.phone,
        u.smsEnabled,
        u.emailEnabled,
        u.id AS user_id,
        CASE 
        WHEN FIND_IN_SET(251, ur.user_permissions) > 0 THEN 1 
        ELSE 0 
        END AS pcb_new_design_jobs,
        COALESCE((SELECT pcb_email_enabled FROM user_pcb_preferences WHERE user_id = COALESCE(u.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 = COALESCE(u.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(252, ur.user_permissions) > 0 THEN 1 
          ELSE 0 
        END AS approve_design_permission,
        COALESCE((SELECT pcb_email_enabled FROM user_pcb_preferences WHERE user_id = COALESCE(u.id, sm.user_id) AND pcb_item_id = 15 AND status != 0 LIMIT 1), 0) AS approve_design_permission_email,
        COALESCE((SELECT pcb_sms_enabled FROM user_pcb_preferences WHERE user_id = COALESCE(u.id, sm.user_id) AND pcb_item_id = 15 AND status != 0 LIMIT 1), 0) AS approve_design_permission_sms,
        CASE 
          WHEN FIND_IN_SET(253, ur.user_permissions) > 0 THEN 1 
          ELSE 0 
        END AS reject_design_permission,
        COALESCE((SELECT pcb_email_enabled FROM user_pcb_preferences WHERE user_id = COALESCE(u.id, sm.user_id) AND pcb_item_id = 16 AND status != 0 LIMIT 1), 0) AS reject_design_permission_email,
        COALESCE((SELECT pcb_sms_enabled FROM user_pcb_preferences WHERE user_id = COALESCE(u.id, sm.user_id) AND pcb_item_id = 16 AND status != 0 LIMIT 1), 0) AS reject_design_permission_sms,
        CASE 
          WHEN FIND_IN_SET(254, ur.user_permissions) > 0 THEN 1 
          ELSE 0 
        END AS view_design_permission
      FROM design_order_project_members dopm
      JOIN staff_members sm ON sm.id = dopm.staff_id
      LEFT JOIN users u ON u.id = sm.user_id
      LEFT JOIN user_roles ur ON ur.id = u.user_type
      WHERE dopm.staff_id IN (${idList}) 
        AND sm.status = 1
      GROUP BY sm.id
    `);

    return result;
  } catch (error) {
    console.error('Error fetching users by IDs:', error);
    return [];
  }
};


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

const getRequestByOriginRequestId = async (request_id,for_parent_facility) => {
  if (!empty(request_id)) {
    let query = `SELECT rt.*, co.id AS cust_order_id, co.total,p.id as project_id,co.budget,pc.name AS job_category_name,cusTyp.billing_type,part.name AS customer_name,part.email AS customer_email FROM requests rt `
      + ` LEFT JOIN customer_orders co ON co.request_id = rt.id `
      + ` LEFT JOIN project_categories pc ON pc.id = rt.project_category `
      + ` LEFT JOIN projects p ON p.request_id = rt.id AND p.is_estimate_job = 0 `
      + ` LEFT JOIN partners part ON part.id = co.customer_id `
      + ` LEFT JOIN customer_type cusTyp ON cusTyp.id = part.customerTypeId `
      + ` WHERE rt.origin_facility_request_id = ${request_id} AND rt.for_parent_facility = ${for_parent_facility}`;

    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT,
    });

    if (result.length === 1) {
      const data = result.map((row) => row);
      return data.map(record => parseDecimalFields(record));
    } else {
      return false;
    }
  } else {
    return false;
  }
};

const getOriginParentRequestId = async (request_id) => {
  let query = `SELECT origin_facility_request_id FROM requests WHERE id = ${request_id}`;
  const result = await sequelize.query(query, {
    type: sequelize.QueryTypes.SELECT,
  });
  return result;
}

const deleteRequestServicesByLabourCostServiceId = async (requestId, labourCostServiceId) => {
  try {
    const result = await RequestServices.destroy({
      where: { 
        request_id: requestId,
        labour_cost_service_id: labourCostServiceId
      }
    })
    console.log("Deleted services with labour_cost_service_id:", labourCostServiceId, "for request:", requestId, "Result:", result);
    return result > 0;
  } catch (error) {
    console.log(error, 'error in deleteRequestServicesByLabourCostServiceId')
    return false
  }
}


const getAllSalesOrderTabCountsForOverview = async (
  requestId,
  userId,
  userType,
  page,
  rowPerpage,
  search,
  where = '',
  sort,
  fromDate,
  toDate,
  filterCommunity,
  dueData,
  clientFilter,
  filterProjectType,
  filterUser,
  filterProjectCategory
) => {
  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 = '';
    let content = '';

    let WhereCondition = '';
    if (requestId) {
      WhereCondition = `r.id = ${requestId}`;
    } else {
      WhereCondition = `r.status <> 0 AND r.status <> 8 ${dateCondition}`;
      if (!empty(where)) {
        WhereCondition = `r.status != 0 AND r.status <> 8 AND ${where} ${dateCondition}`;
      }
    }

    if (!WhereCondition.trim()) {
      WhereCondition = '1=1';
    }

    if (clientFilter && clientFilter.length > 0) {
      WhereCondition += ` AND c_ord.customer_id IN (${clientFilter.join(',')})`;
    }

    if (filterUser && filterUser.length > 0) {
      const projectMemberExists = `
        EXISTS (
          SELECT 1
          FROM projects p
          JOIN project_members pm ON pm.project_id = p.id
          WHERE p.request_id = r.id
            AND p.is_estimate_job = 0
            AND pm.staff_id IN (${filterUser.join(',')})
        )
      `;

      const collaboratorChecks = filterUser
        .map((id) => `FIND_IN_SET(${parseInt(id, 10)}, REPLACE(TRIM(COALESCE(r.collaborators,'')), ' ', '')) > 0`)
        .join(' OR ');

      WhereCondition += `
        AND (
          ${projectMemberExists}
          OR (
            TRIM(COALESCE(r.collaborators,'')) != ''
            AND (${collaboratorChecks})
          )
        )
      `;
    }

    let query = '';

    if (userType != 3) {
      query = `
        SELECT
          COUNT(DISTINCT CASE
            WHEN r.new_order = 1 AND r.quotation = 0 AND r.hold = 0 AND r.is_split_order = 0
            THEN r.id END) AS newSalesOrder,

          COUNT(DISTINCT CASE
            WHEN (
              ((proj.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 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)))
              AND r.installation_acceptance IS NULL
              AND r.isReview = 2
              AND r.is_split_order = 0
            )
            THEN r.id END) AS reviewOrders,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.status = 2) OR (r.status = 3 AND r.min_payment_status = 0) OR (r.split_mirror_status = 7 AND r.status = 3))
              AND r.hold = 0
              AND r.new_order = 0
              AND r.is_split_order = 0
            )
            THEN r.id END) AS salesOrderAwaitingApproval,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.status = 4 AND (i.status IS NULL OR i.status = 0) AND proj.status <> 3 AND r.hold = 0 AND r.new_order = 0)
              OR
              (r.for_parent_facility = 2 AND r.status = 4 AND r.received_status = 0))
              AND (r.split_mirror_status = 0 OR r.split_mirror_status = 6 OR r.split_mirror_status = 8)
              AND r.is_split_order = 0
            )
            THEN r.id END) AS inProductionSalesOrders,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1)
              OR
              (i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND r.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.status = 4 AND r.received_status = 1 AND r.split_mirror_status = 1))
              AND r.is_split_order = 0
            )
            THEN r.id END) AS salesOrderInstallation,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2)
              OR
              (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.status = 4 AND r.received_status = 1 AND r.split_mirror_status = 2))
              AND r.is_split_order = 0
            )
            THEN r.id END) AS salesOrderPickup,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3)
              OR
              (i.status IS NOT NULL AND i.status != 5 AND i.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.status = 4 AND r.received_status = 1 AND r.split_mirror_status = 3))
              AND r.is_split_order = 0
            )
            THEN r.id END) AS salesOrderShipping,

          COUNT(DISTINCT CASE
            WHEN (
              i.status IS NOT NULL
              AND i.status = 5
              AND i.complete_status IN (1,2,3)
              AND i.status != 0
              AND r.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)
              AND r.is_split_order = 0
            )
            THEN r.id END) AS returnedOrders,

          COUNT(DISTINCT CASE
            WHEN r.status = 6 AND r.hold = 0 AND r.is_split_order = 0
            THEN r.id END) AS rejectedOrders,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)
              OR
              (((proj.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 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)))
              AND r.installation_acceptance IS NOT NULL
              AND NOT (r.installation_acceptance = 1 AND r.timestamp <= UNIX_TIMESTAMP() - (30 * 24 * 60 * 60))))
              AND r.is_split_order = 0
            )
            THEN r.id END) AS completedSalesOrders,

          COUNT(DISTINCT CASE
            WHEN r.hold = 1 AND r.is_split_order = 0
            THEN r.id END) AS holdSalesOrders,

          COUNT(DISTINCT CASE
            WHEN (
              r.installation_acceptance IS NOT NULL
              AND r.installation_acceptance = 1
              AND r.timestamp <= UNIX_TIMESTAMP() - (30 * 24 * 60 * 60)
              AND r.quotation = 0
              AND r.is_split_order = 0
            )
            THEN r.id END) AS archiveOrders,

          COUNT(DISTINCT CASE
            WHEN (
              r.status = 3
              AND r.min_payment_status = 1
              AND r.hold = 0
              AND r.new_order = 0
              AND r.split_mirror_status = 0
              AND r.is_split_order = 0
            )
            THEN r.id END) AS approvedSalesOrder,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4)
              OR
              (((proj.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 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)))
              AND r.installation_acceptance IS NULL
              AND r.isReview != 2))
              AND r.is_split_order = 0
            )
            THEN r.id END) AS finalInvoice

        FROM requests r
        LEFT JOIN project_categories pc ON pc.id = r.project_category
        LEFT JOIN (
          SELECT COUNT(c.id) AS cnt, c.request_id
          FROM request_messages c
          LEFT JOIN partners p ON p.id = c.partner_id
          WHERE c.timestamp >= COALESCE((
            SELECT rml.timestamp
            FROM request_message_last_seen rml
            WHERE rml.request_id = c.request_id
              AND rml.user_id = 1
              AND rml.partner_id = c.partner_id
            LIMIT 1
          ), 0)
          AND c.user_id != 1
          GROUP BY c.request_id
        ) rm ON r.id = rm.request_id
        LEFT JOIN (
          SELECT COUNT(id) AS cnt, request_id
          FROM request_proposals
          WHERE status = 1
          GROUP BY request_id
        ) rps ON rps.request_id = r.id
        LEFT JOIN customer_orders c_ord ON c_ord.request_id = r.id
        LEFT JOIN projects proj ON proj.request_id = r.id AND proj.is_estimate_job = 0
        LEFT JOIN community com ON com.id = r.community
          AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0
          AND com.status = 1
        LEFT JOIN request_partners rp ON rp.request_id = r.id
        LEFT JOIN partners p2 ON p2.id = c_ord.customer_id
        LEFT JOIN customer_type ct ON p2.customerTypeId = ct.id
        LEFT JOIN (
          SELECT SUM(amount) AS totalAmount, request_id
          FROM request_payments
          WHERE status = 1
          GROUP BY request_id
        ) reqPay ON reqPay.request_id = r.id
        LEFT JOIN users u2 ON u2.id = p2.user_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 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, 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 request_id, COUNT(*) AS partial_installation_count
          FROM installations
          WHERE status = 5
          GROUP BY request_id
        ) partial_inst ON partial_inst.request_id = r.id
        LEFT JOIN users u ON r.added_by = u.id
        WHERE ${WhereCondition} ${content}
      `;
    } else {
      query = `
        SELECT
          COUNT(DISTINCT CASE
            WHEN r.new_order = 1 AND r.quotation = 0 AND r.hold = 0 AND r.is_split_order = 0
            THEN r.id END) AS newSalesOrder,

          COUNT(DISTINCT CASE
            WHEN (
              ((proj.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 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)))
              AND r.installation_acceptance IS NULL
              AND r.isReview = 2
              AND r.is_split_order = 0
            )
            THEN r.id END) AS reviewOrders,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.status = 2) OR (r.status = 3 AND r.min_payment_status = 0) OR (r.split_mirror_status = 7 AND r.status = 3))
              AND r.hold = 0
              AND r.new_order = 0
              AND r.is_split_order = 0
            )
            THEN r.id END) AS salesOrderAwaitingApproval,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.status = 4 AND (i.status IS NULL OR i.status = 0) AND proj.status <> 3 AND r.hold = 0 AND r.new_order = 0)
              OR
              (r.for_parent_facility = 2 AND r.status = 4 AND r.received_status = 0))
              AND (r.split_mirror_status = 0 OR r.split_mirror_status = 6 OR r.split_mirror_status = 8)
              AND r.is_split_order = 0
            )
            THEN r.id END) AS inProductionSalesOrders,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 1)
              OR
              (i.status IS NOT NULL AND i.status != 5 AND i.complete_status = 1 AND i.status != 0 AND r.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.status = 4 AND r.received_status = 1 AND r.split_mirror_status = 1))
              AND r.is_split_order = 0
            )
            THEN r.id END) AS salesOrderInstallation,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 2)
              OR
              (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.status = 4 AND r.received_status = 1 AND r.split_mirror_status = 2))
              AND r.is_split_order = 0
            )
            THEN r.id END) AS salesOrderPickup,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 3)
              OR
              (i.status IS NOT NULL AND i.status != 5 AND i.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.status = 4 AND r.received_status = 1 AND r.split_mirror_status = 3))
              AND r.is_split_order = 0
            )
            THEN r.id END) AS salesOrderShipping,

          COUNT(DISTINCT CASE
            WHEN (
              i.status IS NOT NULL
              AND i.status = 5
              AND i.complete_status IN (1,2,3)
              AND i.status != 0
              AND r.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)
              AND r.is_split_order = 0
            )
            THEN r.id END) AS returnedOrders,

          COUNT(DISTINCT CASE
            WHEN r.status = 6 AND r.hold = 0 AND r.is_split_order = 0
            THEN r.id END) AS rejectedOrders,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 5)
              OR
              (((proj.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 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)))
              AND r.installation_acceptance IS NOT NULL
              AND NOT (r.installation_acceptance = 1 AND r.timestamp <= UNIX_TIMESTAMP() - (30 * 24 * 60 * 60))))
              AND r.is_split_order = 0
            )
            THEN r.id END) AS completedSalesOrders,

          COUNT(DISTINCT CASE
            WHEN r.hold = 1 AND r.is_split_order = 0
            THEN r.id END) AS holdSalesOrders,

          COUNT(DISTINCT CASE
            WHEN (
              r.installation_acceptance IS NOT NULL
              AND r.installation_acceptance = 1
              AND r.timestamp <= UNIX_TIMESTAMP() - (30 * 24 * 60 * 60)
              AND r.quotation = 0
              AND r.is_split_order = 0
            )
            THEN r.id END) AS archiveOrders,

          COUNT(DISTINCT CASE
            WHEN (
              r.status = 3
              AND r.min_payment_status = 1
              AND r.hold = 0
              AND r.new_order = 0
              AND r.split_mirror_status = 0
              AND r.is_split_order = 0
            )
            THEN r.id END) AS approvedSalesOrder,

          COUNT(DISTINCT CASE
            WHEN (
              ((r.for_parent_facility = 2 AND r.status = 4 AND r.split_mirror_status = 4)
              OR
              (((proj.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 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)))
              AND r.installation_acceptance IS NULL
              AND r.isReview != 2))
              AND r.is_split_order = 0
            )
            THEN r.id END) AS finalInvoice

        FROM requests r
        LEFT JOIN project_categories pc ON pc.id = r.project_category
        LEFT JOIN (
          SELECT COUNT(c.id) AS cnt, c.request_id
          FROM request_messages c
          LEFT JOIN partners p3 ON p3.id = c.partner_id
          WHERE c.timestamp >= COALESCE((
            SELECT rml.timestamp
            FROM request_message_last_seen rml
            WHERE rml.request_id = c.request_id
              AND rml.user_id = ${userId}
              AND rml.partner_id = c.partner_id
            LIMIT 1
          ), 0)
          AND c.user_id != ${userId}
          AND p3.user_id = ${userId}
          GROUP BY c.request_id
        ) rm ON r.id = rm.request_id
        LEFT JOIN (
          SELECT COUNT(id) AS cnt, request_id
          FROM request_proposals
          WHERE status = 1
          GROUP BY request_id
        ) rps ON rps.request_id = r.id
        LEFT JOIN users u ON r.added_by = u.id
        LEFT JOIN request_partners rp ON rp.request_id = r.id
        JOIN partners p ON p.id = rp.partner_id
        LEFT JOIN customer_orders c_ord ON c_ord.request_id = r.id
        LEFT JOIN projects proj ON proj.request_id = r.id AND proj.is_estimate_job = 0
        LEFT JOIN partners p2 ON p2.id = c_ord.customer_id
        LEFT JOIN customer_type ct ON p2.customerTypeId = ct.id
        LEFT JOIN users u2 ON u2.id = p2.user_id
        LEFT JOIN community com ON com.id = r.community
          AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0
          AND com.status = 1
        LEFT JOIN (
          SELECT request_id AS rid,
                 added_by AS proposal_added_by,
                 COALESCE(status, 'NA') AS proposal_status
          FROM request_proposals
          WHERE added_by = ${userId}
        ) trps ON trps.rid = r.id
        LEFT JOIN (
          SELECT MAX(status) AS status,
                 MAX(complete_status) AS complete_status,
                 MAX(COALESCE(pending_review, 0)) AS pending_review,
                 request_id
          FROM installations
          GROUP BY request_id
        ) i ON i.request_id = r.id
        LEFT JOIN (
          SELECT SUM(amount) AS totalAmount, request_id
          FROM request_payments
          WHERE status = 1
          GROUP BY request_id
        ) reqPay ON reqPay.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, 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 request_id, COUNT(*) AS partial_installation_count
          FROM installations
          WHERE status = 5
          GROUP BY request_id
        ) partial_inst ON partial_inst.request_id = r.id
        WHERE p.user_id = ${userId}
          AND ${WhereCondition}
          AND r.status != 1
          ${content}
      `;
    }

    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT
    });

    return result?.[0] || {};
  } catch (error) {
    console.error(error);
    return error;
  }
};

const getAllQuotationsCountForOverviewOptimized = async (
  requestId,
  userId,
  userType,
  page,
  rowPerpage,
  search,
  where = '',
  sort,
  fromDate,
  toDate,
  filterClient,
  filterProjectType,
  filterUser,
  dueData,
  filterCommunity,
  projectEstimate = false
) => {
  try {
    let content = '';
    let query = '';

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

    let dateCondition = '';

    let WhereCondition = '';
    if (requestId) {
      WhereCondition = `r.id = ${requestId}`;
    } else {
      WhereCondition = `r.quotation = 1 `;
      
    }

    if (userType === 3) {
      WhereCondition += ` AND (r.send_to_client = 1 OR r.added_by = ${userId})`;
    }

    let clientCondition = '';


    let userCondition = '';


    let communityCondition = '';
    if (filterCommunity && filterCommunity.length > 0) {
      communityCondition = ` AND r.community IN (${filterCommunity.join(',')}) `;
    }

    let projectTypeCondition = '';
    if (filterProjectType && filterProjectType.length > 0) {
      projectTypeCondition = ` AND r.project_category IN (${filterProjectType.join(',')}) `;
    }

    let designOrderCondition = '';
    if (projectEstimate) {
      designOrderCondition = ` LEFT JOIN design_orders d_ord ON d_ord.request_id = r.id `;
    }

    if (userType != 3) {
      query = `
        SELECT
          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 2 AND r.hold = 0
            THEN r.id END) AS newEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 3 AND est_prj.status = 1 AND r.hold = 0
            THEN r.id END) AS inQueueEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 3 AND est_prj.status = 2 AND r.hold = 0
            THEN r.id END) AS inprogressEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 3 AND est_prj.status = 3 AND r.hold = 0
            THEN r.id END) AS reviewSendForApprovalEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 9 AND r.hold = 0
            THEN r.id END) AS awaitingApproval,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 4 AND r.hold = 0
            THEN r.id END) AS approvedEstimates,

          COUNT(DISTINCT CASE
            WHEN r.quotation = 1 AND r.quotation_status = 6 AND r.hold = 0
            THEN r.id END) AS rejectedEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.hold = 1
            THEN r.id END) AS holdEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 1 AND r.hold = 0
            THEN r.id END) AS draftEstimates

        FROM requests r
        LEFT JOIN customer_orders c_ord ON c_ord.request_id = r.id
        LEFT JOIN projects est_prj
          ON est_prj.request_id = r.id
          AND est_prj.is_estimate_job = 1
          AND r.quotation = 1
        LEFT JOIN community com
          ON com.id = r.community
          AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0
          AND com.status = 1
        LEFT JOIN (
          SELECT MAX(status) AS status, request_id
          FROM installations
          GROUP BY request_id
        ) i ON i.request_id = r.id
        WHERE ${WhereCondition}
      `;
    }

    if (userType == 3) {
      query = `
        SELECT
          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 2 AND r.hold = 0
            THEN r.id END) AS newEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 3 AND est_prj.status = 1 AND r.hold = 0
            THEN r.id END) AS inQueueEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 3 AND est_prj.status = 2 AND r.hold = 0
            THEN r.id END) AS inprogressEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 3 AND est_prj.status = 3 AND r.hold = 0
            THEN r.id END) AS reviewSendForApprovalEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 9 AND r.hold = 0
            THEN r.id END) AS awaitingApproval,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 4 AND r.hold = 0
            THEN r.id END) AS approvedEstimates,

          COUNT(DISTINCT CASE
            WHEN r.quotation = 1 AND r.quotation_status = 6 AND r.hold = 0
            THEN r.id END) AS rejectedEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.hold = 1
            THEN r.id END) AS holdEstimates,

          COUNT(DISTINCT CASE
            WHEN r.status = 8 AND r.quotation_status = 1 AND r.hold = 0
            THEN r.id END) AS draftEstimates

        FROM requests r
        LEFT JOIN request_partners rp ON rp.request_id = r.id
        ${designOrderCondition}
        LEFT JOIN projects est_prj
          ON est_prj.request_id = r.id
          AND est_prj.is_estimate_job = 1
          AND r.quotation = 1
        JOIN partners p ON p.id = rp.partner_id
        LEFT JOIN customer_orders c_ord ON c_ord.request_id = r.id
        LEFT JOIN community com
          ON com.id = r.community
          AND FIND_IN_SET(c_ord.customer_id, com.clients) > 0
          AND com.status = 1
        LEFT JOIN (
          SELECT MAX(status) AS status, request_id
          FROM installations
          GROUP BY request_id
        ) i ON i.request_id = r.id
        WHERE p.user_id = ${userId}
          ${content}
          ${userCondition}
          ${communityCondition}
          ${projectTypeCondition}
          AND ${WhereCondition}
          AND r.status != 1
      `;
    }

    const result = await sequelize.query(query, {
      type: sequelize.QueryTypes.SELECT
    });

    return result?.[0] || {
      newEstimates: 0,
      inQueueEstimates: 0,
      inprogressEstimates: 0,
      reviewSendForApprovalEstimates: 0,
      awaitingApproval: 0,
      approvedEstimates: 0,
      rejectedEstimates: 0,
      holdEstimates: 0,
      draftEstimates: 0
    };
  } catch (error) {
    console.error(error);
    return {
      newEstimates: 0,
      inQueueEstimates: 0,
      inprogressEstimates: 0,
      reviewSendForApprovalEstimates: 0,
      awaitingApproval: 0,
      approvedEstimates: 0,
      rejectedEstimates: 0,
      holdEstimates: 0,
      draftEstimates: 0
    };
  }
};

module.exports = {
  RequestsModel: Requests,
  RequestAttachmentsModel: RequestAttachments,
  RequestLocationsModel:RequestLocation,
  getAllRequests,
  getAllRequestsForUser,
  getAllQuotationsCount,
  getAllTeamBatch,
  getServices,
  addRequest,
  getRequestById,
  getSalesOrderRequestByDesignOrderId,
  getEstimateRequestByDesignOrderId,
  getRequestEstimateByDesignOrderId,
  editRequest,
  deleteRequestById,
  addRequestClients, getRequestPartnersByIds,
  getRequestTeamUserIds,
  updateRequets,
  searchRequests,
  getAllClientRequestId,
  addRequestAttachments,
  addRequestPayment,
  deletePayment,
  updateRequestPayment,
  updateRequestAttachments,
  getAllRequestAttachments,
  getRequestAttachmentById,
  getRequestAttachmentsByLocationId,
  addLocation,
  updateLocation,
  deleteLocation,
  deleteMaterialLocationByOrderId,
  FetchAllApprovedDesigns,
  getRequestByCommunityId,
  getProjectByCommunityId,
  getProjectByClientId,
  getJobsByClientId,
  checkExistingProject,
  
  checkExistingEstimateProject,

  checkExistingTask, checkExistingSubTask,
  getRequestByIdOptimized,
  addRequestServices,
  updateRequestServices,
  updateRequestServiceWorkflowById,
  deleteRequestServices, getRequestServices, updateRequestServiceStatus,
  deleteRequestServicesById, getRequestServiceByServiceId,
  updateProductRequestServiceStatus,
  deleteRequestServicesWithoutRecipe,
  getAllServiceByRequest,
  getProjectExisting,
  getAllQuotations,
  addServiceLocation, updateServiceLocation, deleteServiceLocation, deleteServiceLocationByServiceId,
  updateCardOrder,
  addDesignOrders, updateDesignOrders, updateDesignOrderCardOrder, getAllDesignOrders, checkIfUserIsClient,
  addDesignOrderAttachments, updateDesignOrderAttachments, updateMultipleDesignOrderAttachments,
  getAllDesignOrdersCount, deleteDesignOrderById,
  fetchAllDesignOrderAttachments, getDesignOrderPartnersByIds, deleteDesignOrderAttachments,
  deleteDesignOrderAttachmentsBulk,
  findTotalPaidAmount,
  editRequestTable,
  findRequestAndPaymentById,
  addDesignOrderServices,
  addDesignOrderProducts,
  getDesignOrderProductsByDesignOrderId,
  deleteDesignOrderProductsByDesignOrderId,
  getDesignOrderById,
  updateDesignOrderService,
  getAllServiceByDesignOrder,
  addDesignOrdersSubTask,
  getDesignOrdersSubTaskByTask,
  getDesignOrdersSubTaskByDesignOrder,
  deleteDesignOrdersSubTask,
  updateDesignOrdersSubTask,
  deleteDesignOrderServices,
  getAllDesignOrderTasks,
  addDesignOrdersProjectMember,
  projectMemberExist,
  deleteDesignOrdersProjectMember,
  deleteDesignOrdersProjectMemberById,
  getAllDesignOrderProjectMembers,
  getAllDesignOrderProjectMembersNew,
  addDesignOrdersProjectSubtaskMember,
  deleteDesignOrdersProjectSubtaskMember,
  projectSubtaskMemberExist,
  getAllDesignOrderProjectSubTaskBytaskId,
  designOrderProjectSubTaskSkills,
  fetchDesignOrderStaffTaskTimelog,
  fetchAllServicesByDesignOrderId,
  fetchAllAdditionalServicesByDesignOrderId,
  getAllDesignOrderStaffTaskTimelogs,
  getDesignOrderJobCount,
  updateDesignOrderJobStatus,
  getDesignOrderServicesByDesignOrderId,
  addDesignOrderStaffTaskTimelog,
  fetchClockedInDesignOrderStaffTaskTimelog,
  updateDesignOrderStaffTaskTimelog,
  addDesignOrderPayOut,
  getDesignOrderProjectTaskById,
  getDesignOrderServicesByDesignOrder,
  getDesignOrderPayOutByTaskId,
  updateDesignOrderLogStatus,
  fetchAllPayOutByDesignOrderId,
  getAllDesignOrderAttachments,
  getAllDesignOrderReferenceAttachments,
  fetchAllDesignOrderReferenceAttachments,
  getAllRequestAttachmentsForCards,
  getAllRequestsOptimized,
  getAllRequestsTotalCount,
  getCompletedInstallsByCommunityId ,
  getCompleteDesignByCommunityId,
  getCompleteDesignOrdersByCommunityId,
  getAllDesignOrderJobCount,
  getOptimizedDesignOverviewCounts,
  updateRequestAttachmentsDeisgnOrderId,
  updateLocationProducts,
  updateLocationIsLinkedAll,
  getRequestLocationsByRequestIdWhereIsLinkedAllZero,
  updateLocationIsLinkedAllByLocationId,
  updateRouteServiceLocation,
  getLocationProductsById,
  getLocationProductsByLocId,
  getRouteServiceLocationById,
  fetchAllDesignOrderAttachmentsForConvert,
  getDesignOrderByIdNew,
  getCompletedInstallsByCommunityIdForFilter,
  updateRequestAttachmentsById,
  updateRequestById,
  updateRequestByOriginFacilityId,
  FindReqDataById,
  addDesignOrderCount,
  updateDesignOrderCount,
  getDesignOrderCountByUserId,
  designCountIncrementField,
  getDesignCountByUser,
  getDesignOrderCountByUserData,
  deleteRequestAttachments,
  addEstimateTabCount,
  updateEstimateTabCount,
  getEstimateTabCountByUserId,
  getEstimateTabCountByUserData,
  EstimateTabIncrementField,
  getEstimateTabCountByUser,
  getEstimateCountByUser,
  addSalesOrderTabCount,
  updateSalesOrderTabCount,
  getSalesOrderByUserId,
  getSalesOrderByUserData,
  salesOrderIncrementField,
  getSalesOrderCountByUser,
  getJobCostDetails,
  getJobCostDetailsForMaterials,
  getJobCostMaterialDetails,
  getDesignOrderDesigners,
  getUsersByIds,
  getDesignPayOutById,
  deleteDesignStaffTaskTimelogsForPayout,
  deleteDesignPayOut,
  updateDesignPayOut,
  getAllLocationProductsById,
  getAllLocationServiceByRequestId,
  getAllServiceByRequestId,updateDesignOrderAttachmentsByDesignOrderId,
  deleteDesignOrderAttachment,
  deleteRequestServicesWithRequestId,
  getAllRecipeRequestServices,
  updateAllRecipesTakenByRequestId,
  getSingleRequestService10,
  getRequestByOriginRequestId,
  addDesignOrderRejectedFiles,
  getDesignOrderRejectedAttachments,
  chageNewSalesOrderStatus,
  getOriginParentRequestId,
  deleteExistingAttachments,
  getSplitRequestServices,
  getRequestServicesNew,
  deleteRequestServicesByLabourCostServiceId,
  destroyRequestById,
  getRequestServiceById,
  addEmail,
  getEmails,
  getAllQuotationsCountForOverview,
  getAllSalesOrderTabCountsForOverview,
  getAllQuotationsCountForOverviewOptimized,
}