const sequelize = require("../config/dbconnection");
const Sequelize = require("sequelize");
const Admin = require("../models/admin");
const { empty, getAgoString } = require("../Helpers/Common");
const { DOMAIN } = require("../constants/constant");

const TICKET_PREFIX = (DOMAIN == 'arizona') ? 'AZ-' : (DOMAIN == 'riv') ? 'RIV-' : (DOMAIN == 'la') ? 'LA-' : (DOMAIN == 'nca') ? 'NCA-' : 'SW-'

const Tickets = sequelize.define('staff_tasks', {
  ID: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  name: { type: Sequelize.CHAR, allowNull: false, defaultValue: null },
  ticket_uid: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  description: { type: Sequelize.TEXT, allowNull: false },
  // start_date: { type: Sequelize.INTEGER, allowNull: false, defaultValue: null },
  // due_date: { type: Sequelize.INTEGER, allowNull: false, defaultValue: null },
  ticket_file: { type: Sequelize.TEXT, allowNull: true, defaultValue: null },
  priority: { type: Sequelize.TINYINT, allowNull: true, defaultValue: null },
  ticket_type: { type: Sequelize.TINYINT, allowNull: true, defaultValue: null },
  timestamp: { type: Sequelize.INTEGER, allowNull: false, defaultValue: null },
  due_date: { type: Sequelize.INTEGER, allowNull: false },
  first_name: { type: Sequelize.CHAR, allowNull: true, defaultValue: null },
  email_id: { type: Sequelize.CHAR, allowNull: true, defaultValue: null },
  status: { type: Sequelize.INTEGER, allowNull: false, defaultValue: null },
  last_name: { type: Sequelize.CHAR, allowNull: true, defaultValue: null },
  userid: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  complete: { type: Sequelize.INTEGER, allowNull: false, },
  complete_sync: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 1 },
  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 },
  project_id: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  dev_due_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  dev_due_date_updated_by: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  start_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  start_date_updated_by: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  delivery_date: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  delivery_date_updated_by: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  status_updated: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  priority_updated: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  type_updated: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  module: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
  created_from_installation_id: {
     type: Sequelize.INTEGER,
     allowNull: true,
     defaultValue: null,
  },
},
  { timestamps: false })

const ModuleNames = sequelize.define('module_names', {
  id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  module_name: { type: Sequelize.STRING, allowNull: false },
},
  { timestamps: false })

const Staff_Task_Files = sequelize.define('staff_task_files', {
  ID: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  userid: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0 },
  taskid: { type: Sequelize.INTEGER, allowNull: false },
  extension: { type: Sequelize.STRING, allowNull: false },
  file_size: { type: Sequelize.STRING, allowNull: false },
  file_type: { type: Sequelize.STRING, allowNull: false },
  file_url: { type: Sequelize.STRING, allowNull: false },
  timestamp: { type: Sequelize.STRING, allowNull: false },
  upload_file_name: { type: Sequelize.STRING, allowNull: false },
},
  { timestamps: false })

const TicketTimeLog = sequelize.define('ticket_time_log', {
  id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  user_id: { type: Sequelize.INTEGER, allowNull: false },
  task_id: { type: Sequelize.INTEGER, allowNull: false },
  team_id: { type: Sequelize.INTEGER, allowNull: false },
  start_time: { type: Sequelize.INTEGER, allowNull: false },
  end_time: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
},
  { timestamps: false, tableName: "ticket_time_log" })


const StickyNote = sequelize.define('sticky_notes', {
  id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  sticky_note: {
    type: Sequelize.STRING(600),
    allowNull: true,
    charset: 'utf8mb4',
    collate: 'utf8mb4_unicode_ci',
  },
  added_by: { type: Sequelize.INTEGER, allowNull: false },
  timestamp: { type: Sequelize.INTEGER, allowNull: false },
  status: { type: Sequelize.TINYINT, allowNull: true, defaultValue: 1 },
  updated_by: { type: Sequelize.INTEGER, allowNull: true },
  updated_on: { type: Sequelize.INTEGER, allowNull: true },
}, {
  timestamps: false,
  tableName: 'sticky_notes',
});
const StickyNoteIndividual = sequelize.define('sticky_notes_individual', {
  id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
  sticky_note: {
    type: Sequelize.STRING(600),
    allowNull: true,
    charset: 'utf8mb4',
    collate: 'utf8mb4_unicode_ci',
  },
  added_by: { type: Sequelize.INTEGER, allowNull: false },
  timestamp: { type: Sequelize.INTEGER, allowNull: false },
  status: { type: Sequelize.TINYINT, allowNull: true, defaultValue: 1 },
  updated_by: { type: Sequelize.INTEGER, allowNull: true },
  updated_on: { type: Sequelize.INTEGER, allowNull: true },
  is_private: { type: Sequelize.INTEGER, allowNull: true, defaultValue: 0 },
  archive: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0 },
  share_with: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
  color: { type: Sequelize.STRING(300), allowNull: true, defaultValue: "#FFE16A" },
}, {
  timestamps: false,
  tableName: 'sticky_notes_individual',
});

const getAllTasks = async (client_id, userType, staff_id, limit = null, offset = 0, filters = {}) => {
  try {
    let condition = ''
    if (client_id) {
      condition = ` and  staff_tasks.partner_id = ${client_id}`
    }
    if (staff_id) {
      condition = ` and  (stm.userid = ${staff_id} OR staff_tasks.userid = ${staff_id})`
    }

    // Build filter conditions
    let filterConditions = '';
    if (filters.search && filters.search.trim()) {
      const searchTerm = filters.search.trim().replace(/'/g, "''");
      
      // Extract numeric ID if search term is in format "SW-933" or just "933"
      let numericId = null;
      // const swMatch = searchTerm.match(/^SW-?(\d+)$/i);
      const swMatch = searchTerm.match(new RegExp(`^${TICKET_PREFIX}?(\d+)$`, 'i'));
      const numMatch = searchTerm.match(/^(\d+)$/);
      
      if (swMatch) {
        numericId = parseInt(swMatch[1]);
      } else if (numMatch) {
        numericId = parseInt(numMatch[1]);
      }
      
      // Build search conditions
      let searchConditions = '';
      
      // If numeric ID found, check if it's a partial or exact match
      if (numericId !== null) {
        const numericStr = String(numericId);
        // const isExactMatch = searchTerm === numericStr || searchTerm.toUpperCase() === `SW-${numericStr}` || searchTerm.toUpperCase() === `SW${numericStr}`;
        const isExactMatch = searchTerm === numericStr || searchTerm.toUpperCase() === `${TICKET_PREFIX}${numericStr}` || searchTerm.toUpperCase() === `${TICKET_PREFIX.slice(0, -1)}${numericStr}`;
        
        if (isExactMatch) {
          // Exact numeric/ID search - match exact ID and also partial matches for flexibility
          // searchConditions = `(
          //   staff_tasks.ID = ${numericId} 
          //   OR staff_tasks.ticket_uid = ${numericId}
          //   OR CONCAT('SW-', staff_tasks.ID) = 'SW-${numericId}'
          //   OR CAST(staff_tasks.ID AS CHAR) LIKE '${numericStr}%'
          //   OR CAST(staff_tasks.ticket_uid AS CHAR) LIKE '${numericStr}%'
          //   OR CONCAT('SW-', staff_tasks.ID) LIKE 'SW-${numericStr}%'
          //   OR CONCAT(COALESCE(p.short_code, ''), 'SW', staff_tasks.ticket_uid) LIKE '%${searchTerm}%'
          // )`;
          searchConditions = `(
            staff_tasks.ID = ${numericId} 
            OR staff_tasks.ticket_uid = ${numericId}
            OR CONCAT('${TICKET_PREFIX}', staff_tasks.ID) = '${TICKET_PREFIX}${numericId}'
            OR CAST(staff_tasks.ID AS CHAR) LIKE '${numericStr}%'
            OR CAST(staff_tasks.ticket_uid AS CHAR) LIKE '${numericStr}%'
            OR CONCAT('${TICKET_PREFIX}', staff_tasks.ID) LIKE '${TICKET_PREFIX}${numericStr}%'
            OR CONCAT(COALESCE(p.short_code, ''), '${TICKET_PREFIX.slice(0, -1)}', staff_tasks.ticket_uid) LIKE '%${searchTerm}%'
          )`;
        } else {
          // Partial numeric search (e.g., "8" should match 899, 898, 881, etc.)
          // Also include text search for mixed content
          searchConditions = `(
            CAST(staff_tasks.ID AS CHAR) LIKE '${numericStr}%'
            OR CAST(staff_tasks.ticket_uid AS CHAR) LIKE '${numericStr}%'
            OR CONCAT('${TICKET_PREFIX}', staff_tasks.ID) LIKE '${TICKET_PREFIX}${numericStr}%'
            OR CONCAT('${TICKET_PREFIX}', staff_tasks.ID) LIKE '%${searchTerm}%'
            OR CONCAT(COALESCE(p.short_code, ''), '${TICKET_PREFIX.slice(0, -1)}', staff_tasks.ticket_uid) LIKE '%${searchTerm}%'
            OR staff_tasks.name LIKE '%${searchTerm}%' 
            OR staff_tasks.description LIKE '%${searchTerm}%'
          )`;
          // searchConditions = `(
          //   CAST(staff_tasks.ID AS CHAR) LIKE '${numericStr}%'
          //   OR CAST(staff_tasks.ticket_uid AS CHAR) LIKE '${numericStr}%'
          //   OR CONCAT('SW-', staff_tasks.ID) LIKE 'SW-${numericStr}%'
          //   OR CONCAT('SW-', staff_tasks.ID) LIKE '%${searchTerm}%'
          //   OR CONCAT(COALESCE(p.short_code, ''), 'SW', staff_tasks.ticket_uid) LIKE '%${searchTerm}%'
          //   OR staff_tasks.name LIKE '%${searchTerm}%' 
          //   OR staff_tasks.description LIKE '%${searchTerm}%'
          // )`;
        }
      } else {
        // Text search (no numeric ID detected)
        searchConditions = `(
          staff_tasks.name LIKE '%${searchTerm}%' 
          OR staff_tasks.description LIKE '%${searchTerm}%'
          OR CONCAT(COALESCE(p.short_code, ''), '${TICKET_PREFIX.slice(0, -1)}', staff_tasks.ticket_uid) LIKE '%${searchTerm}%'
          OR CONCAT('${TICKET_PREFIX}', staff_tasks.ID) LIKE '%${searchTerm}%'
        )`;
      }
      
      filterConditions += ` AND ${searchConditions}`;
    }
    if (filters.status !== null && filters.status !== undefined && filters.status !== '') {
      const statusValue = parseInt(filters.status);
      if (!isNaN(statusValue)) {
        filterConditions += ` AND staff_tasks.status = ${statusValue}`;
      }
    }
    if (filters.module !== null && filters.module !== undefined && filters.module !== '') {
      const moduleValue = parseInt(filters.module);
      if (!isNaN(moduleValue)) {
        filterConditions += ` AND staff_tasks.module = ${moduleValue}`;
      }
    }
    if (filters.priority !== null && filters.priority !== undefined && filters.priority !== '') {
      const priorityValue = parseInt(filters.priority);
      if (!isNaN(priorityValue)) {
        filterConditions += ` AND staff_tasks.priority = ${priorityValue}`;
      }
    }
    if (filters.ticket_type !== null && filters.ticket_type !== undefined && filters.ticket_type !== '') {
      const ticketTypeValue = parseInt(filters.ticket_type);
      if (!isNaN(ticketTypeValue)) {
        filterConditions += ` AND staff_tasks.ticket_type = ${ticketTypeValue}`;
      }
    }
    if (filters.dateRange && filters.dateRange.length === 2) {
      const [startDate, endDate] = filters.dateRange;
      if (startDate && endDate) {
        const startUnix = Math.floor(new Date(startDate).getTime() / 1000);
        const endUnix = Math.floor(new Date(endDate).getTime() / 1000);
        filterConditions += ` AND (
          (staff_tasks.timestamp >= ${startUnix} AND staff_tasks.timestamp <= ${endUnix})
          OR (staff_tasks.due_date >= ${startUnix} AND staff_tasks.due_date <= ${endUnix})
        )`;
      }
    }

    // Build pagination
    let pagination = '';
    if (limit !== null) {
      pagination = ` LIMIT ${parseInt(limit)} OFFSET ${parseInt(offset)}`;
    }

    let result = null;
    let countResult = null;

    if (userType === 1) {
      // Count query for userType 1
      countResult = await sequelize.query(`
        SELECT COUNT(DISTINCT staff_tasks.ID) as total
        FROM staff_tasks
        LEFT JOIN leads AS l ON l.id = staff_tasks.lead_id
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        LEFT JOIN module_names mn ON mn.id = staff_tasks.module
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
      `);

      // Data query for userType 1
      result = await sequelize.query(`
        SELECT 
            staff_tasks.name, 
            staff_tasks.ID,
            staff_tasks.ticket_uid, 
            staff_tasks.status, 
            staff_tasks.description,
            staff_tasks.complete,
            staff_tasks.partner_id,
            staff_tasks.contact_id,
            staff_tasks.timestamp,
            staff_tasks.lead_id,
            staff_tasks.start_date,
            staff_tasks.due_date,
            staff_tasks.priority,
            staff_tasks.ticket_type,
            staff_tasks.dev_due_date,
            staff_tasks.delivery_date,
            staff_tasks.status_updated,
            staff_tasks.userid,
            staff_tasks.created_from_installation_id,
            mn.module_name,
            concat(u.first_name,' ',u.last_name) as created_by,
            l.name AS task_lead_name,
            p.name AS project_name,
            p.short_code AS short_code
        FROM staff_tasks
        LEFT JOIN (
            SELECT taskid, COUNT(*) AS no_of_tasks 
            FROM staff_task_objectives 
            GROUP BY taskid
        ) AS st ON st.taskid = staff_tasks.ID
        LEFT JOIN (
            SELECT taskid, COUNT(*) AS no_of_completed_tasks 
            FROM staff_task_objectives 
            WHERE complete = 1 
            GROUP BY taskid
        ) AS st1 ON st1.taskid = staff_tasks.ID
        LEFT JOIN (
            SELECT taskid, COUNT(*) AS no_of_pending_tasks 
            FROM staff_task_objectives 
            WHERE complete = 0 
            GROUP BY taskid
        ) AS st2 ON st2.taskid = staff_tasks.ID
        LEFT JOIN leads AS l ON l.id = staff_tasks.lead_id
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        LEFT JOIN module_names mn ON mn.id = staff_tasks.module
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
        ORDER BY staff_tasks.ID DESC ${pagination}
      `);
    } else if (userType === 3) {
      // Count query for userType 3
      countResult = await sequelize.query(`
        SELECT COUNT(DISTINCT staff_tasks.ID) as total
        FROM staff_tasks
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
      `);

      // Data query for userType 3
      result = await sequelize.query(`
        SELECT staff_tasks.name,staff_tasks.timestamp, concat(u.first_name,' ',u.last_name) as created_by,staff_tasks.userid,
          staff_tasks.created_from_installation_id,staff_tasks.delivery_date,
        staff_tasks.ID, staff_tasks.ticket_uid,staff_tasks.status, staff_tasks.due_date,staff_tasks.start_date,
        staff_tasks.description,staff_tasks.complete,staff_tasks.priority,staff_tasks.ticket_type,
        staff_tasks.dev_due_date,staff_tasks.status_updated, p.name AS project_name,p.short_code AS short_code 
        FROM staff_tasks
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
        ORDER BY staff_tasks.ID DESC ${pagination}
      `);
    } else {
      // Count query for other userTypes
      countResult = await sequelize.query(`
        SELECT COUNT(DISTINCT staff_tasks.ID) as total
        FROM staff_tasks
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        LEFT JOIN staff_task_members stm ON stm.taskid = staff_tasks.ID
        LEFT JOIN module_names mn ON mn.id = staff_tasks.module
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
      `);

      // Data query for other userTypes
      result = await sequelize.query(`
        SELECT staff_tasks.name,staff_tasks.timestamp, concat(u.first_name,' ',u.last_name) as created_by,staff_tasks.userid,
          staff_tasks.created_from_installation_id,staff_tasks.delivery_date,
        staff_tasks.ID, staff_tasks.ticket_uid,staff_tasks.status, staff_tasks.due_date,staff_tasks.start_date,
        mn.module_name,staff_tasks.description,staff_tasks.complete,staff_tasks.priority,staff_tasks.ticket_type,
        staff_tasks.dev_due_date,staff_tasks.status_updated, p.name AS project_name,p.short_code AS short_code 
        FROM staff_tasks
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        LEFT JOIN staff_task_members stm ON stm.taskid = staff_tasks.ID
        LEFT JOIN module_names mn ON mn.id = staff_tasks.module
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
        GROUP BY staff_tasks.ID
        ORDER BY staff_tasks.ID DESC ${pagination}
      `);
    }

    const totalCount = countResult && countResult[0] && countResult[0].length > 0 
      ? parseInt(countResult[0][0].total) 
      : 0;

    if (result[0].length >= 1) {
      const data = result[0].map((row) => row);
      return { tasks: data, totalCount };
    } else {
      return { tasks: [], totalCount: 0 };
    }

  } catch (error) {
    console.log(error);
    return { tasks: [], totalCount: 0 };
  }
};

const getStatusCounts = async (client_id, userType, staff_id, filters = {}) => {
  try {
    let condition = ''
    if (client_id) {
      condition = ` and  staff_tasks.partner_id = ${client_id}`
    }
    if (staff_id) {
      condition = ` and  (stm.userid = ${staff_id} OR staff_tasks.userid = ${staff_id})`
    }

    // Build filter conditions (excluding status filter for counts)
    let filterConditions = '';
    if (filters.search && filters.search.trim()) {
      const searchTerm = filters.search.trim().replace(/'/g, "''");
      
      // Extract numeric ID if search term is in format "SW-933" or just "933"
      let numericId = null;
      // const swMatch = searchTerm.match(/^SW-?(\d+)$/i);
      const swMatch = searchTerm.match(new RegExp(`^${TICKET_PREFIX}?(\d+)$`, 'i'));
      const numMatch = searchTerm.match(/^(\d+)$/);
      
      if (swMatch) {
        numericId = parseInt(swMatch[1]);
      } else if (numMatch) {
        numericId = parseInt(numMatch[1]);
      }
      
      // Build search conditions
      let searchConditions = '';
      
      // If numeric ID found, check if it's a partial or exact match
      if (numericId !== null) {
        const numericStr = String(numericId);
        const isExactMatch = searchTerm === numericStr || searchTerm.toUpperCase() === `${TICKET_PREFIX}${numericStr}` || searchTerm.toUpperCase() === `${TICKET_PREFIX.slice(0, -1)}${numericStr}`;
        
        if (isExactMatch) {
          // Exact numeric/ID search - match exact ID and also partial matches for flexibility
          searchConditions = `(
            staff_tasks.ID = ${numericId} 
            OR staff_tasks.ticket_uid = ${numericId}
            OR CONCAT('${TICKET_PREFIX}', staff_tasks.ID) = '${TICKET_PREFIX}${numericId}'
            OR CAST(staff_tasks.ID AS CHAR) LIKE '${numericStr}%'
            OR CAST(staff_tasks.ticket_uid AS CHAR) LIKE '${numericStr}%'
            OR CONCAT('${TICKET_PREFIX}', staff_tasks.ID) LIKE '${TICKET_PREFIX}${numericStr}%'
            OR CONCAT(COALESCE(p.short_code, ''), '${TICKET_PREFIX.slice(0, -1)}', staff_tasks.ticket_uid) LIKE '%${searchTerm}%'
          )`;
        } else {
          // Partial numeric search (e.g., "8" should match 899, 898, 881, etc.)
          // Also include text search for mixed content
          searchConditions = `(
            CAST(staff_tasks.ID AS CHAR) LIKE '${numericStr}%'
            OR CAST(staff_tasks.ticket_uid AS CHAR) LIKE '${numericStr}%'
            OR CONCAT('${TICKET_PREFIX}', staff_tasks.ID) LIKE '${TICKET_PREFIX}${numericStr}%'
            OR CONCAT('${TICKET_PREFIX}', staff_tasks.ID) LIKE '%${searchTerm}%'
            OR CONCAT(COALESCE(p.short_code, ''), '${TICKET_PREFIX.slice(0, -1)}', staff_tasks.ticket_uid) LIKE '%${searchTerm}%'
            OR staff_tasks.name LIKE '%${searchTerm}%' 
            OR staff_tasks.description LIKE '%${searchTerm}%'
          )`;
        }
      } else {
        // Text search (no numeric ID detected)
        searchConditions = `(
          staff_tasks.name LIKE '%${searchTerm}%' 
          OR staff_tasks.description LIKE '%${searchTerm}%'
          OR CONCAT(COALESCE(p.short_code, ''), '${TICKET_PREFIX.slice(0, -1)}', staff_tasks.ticket_uid) LIKE '%${searchTerm}%'
          OR CONCAT('${TICKET_PREFIX}', staff_tasks.ID) LIKE '%${searchTerm}%'
        )`;
      }
      
      filterConditions += ` AND ${searchConditions}`;
    }
    if (filters.module !== null && filters.module !== undefined && filters.module !== '') {
      const moduleValue = parseInt(filters.module);
      if (!isNaN(moduleValue)) {
        filterConditions += ` AND staff_tasks.module = ${moduleValue}`;
      }
    }
    if (filters.priority !== null && filters.priority !== undefined && filters.priority !== '') {
      const priorityValue = parseInt(filters.priority);
      if (!isNaN(priorityValue)) {
        filterConditions += ` AND staff_tasks.priority = ${priorityValue}`;
      }
    }
    if (filters.ticket_type !== null && filters.ticket_type !== undefined && filters.ticket_type !== '') {
      const ticketTypeValue = parseInt(filters.ticket_type);
      if (!isNaN(ticketTypeValue)) {
        filterConditions += ` AND staff_tasks.ticket_type = ${ticketTypeValue}`;
      }
    }
    if (filters.dateRange && filters.dateRange.length === 2) {
      const [startDate, endDate] = filters.dateRange;
      if (startDate && endDate) {
        const startUnix = Math.floor(new Date(startDate).getTime() / 1000);
        const endUnix = Math.floor(new Date(endDate).getTime() / 1000);
        filterConditions += ` AND (
          (staff_tasks.timestamp >= ${startUnix} AND staff_tasks.timestamp <= ${endUnix})
          OR (staff_tasks.due_date >= ${startUnix} AND staff_tasks.due_date <= ${endUnix})
        )`;
      }
    }

    let result = null;
    if (userType === 1) {
      result = await sequelize.query(`
        SELECT staff_tasks.status, COUNT(DISTINCT staff_tasks.ID) as count
        FROM staff_tasks
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        LEFT JOIN module_names mn ON mn.id = staff_tasks.module
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
        GROUP BY staff_tasks.status
      `);
    } else if (userType === 3) {
      result = await sequelize.query(`
        SELECT staff_tasks.status, COUNT(DISTINCT staff_tasks.ID) as count
        FROM staff_tasks
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
        GROUP BY staff_tasks.status
      `);
    } else {
      result = await sequelize.query(`
        SELECT staff_tasks.status, COUNT(DISTINCT staff_tasks.ID) as count
        FROM staff_tasks
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        LEFT JOIN staff_task_members stm ON stm.taskid = staff_tasks.ID
        LEFT JOIN module_names mn ON mn.id = staff_tasks.module
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
        GROUP BY staff_tasks.status
      `);
    }

    // Get total count (all statuses)
    let totalResult = null;
    if (userType === 1) {
      totalResult = await sequelize.query(`
        SELECT COUNT(DISTINCT staff_tasks.ID) as total
        FROM staff_tasks
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        LEFT JOIN module_names mn ON mn.id = staff_tasks.module
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
      `);
    } else if (userType === 3) {
      totalResult = await sequelize.query(`
        SELECT COUNT(DISTINCT staff_tasks.ID) as total
        FROM staff_tasks
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
      `);
    } else {
      totalResult = await sequelize.query(`
        SELECT COUNT(DISTINCT staff_tasks.ID) as total
        FROM staff_tasks
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        LEFT JOIN users u ON u.id = staff_tasks.userid
        LEFT JOIN staff_task_members stm ON stm.taskid = staff_tasks.ID
        LEFT JOIN module_names mn ON mn.id = staff_tasks.module
        WHERE staff_tasks.status != 0 ${condition} ${filterConditions}
      `);
    }

    const statusCounts = {};
    if (result && result[0] && result[0].length > 0) {
      result[0].forEach(row => {
        statusCounts[row.status] = parseInt(row.count);
      });
    }

    const totalCount = totalResult && totalResult[0] && totalResult[0].length > 0 
      ? parseInt(totalResult[0][0].total) 
      : 0;

    return { statusCounts, totalCount };
  } catch (error) {
    console.log(error);
    return { statusCounts: {}, totalCount: 0 };
  }
};

const AddTickets = async (data) => {
  try {
    let result = await Tickets.create(data)

    return result.ID
  } catch (error) {
    console.log(error)
  }
}
const getTask = async (id) => {
  try {
    let result = await sequelize.query(`
        SELECT staff_tasks.*, projects.name AS project_name, projects.short_code
        FROM staff_tasks
        LEFT JOIN projects ON projects.id = staff_tasks.project_id
        WHERE staff_tasks.ID = ${id}
        `)
    if (!empty(result)) {
      if (result) {
        const data = result.map((row) => row);
        return data;
      } else {
        return false
      }
    }
  } catch (error) {
    console.log(error)
  }
}
const getTicketId = async (id) => {
  try {
    let result = await sequelize.query(`
        SELECT COALESCE(MAX(ticket_uid), 0) AS count FROM staff_tasks WHERE project_id = ${id}
        `, { type: sequelize.QueryTypes.SELECT });

    if (result && result.length > 0) {
      const data = result[0].count;
      return parseInt(data) + 1;
    } else {
      return 1;
    }
  } catch (error) {
    console.error(error);

  }
};
const deleteMessages = async (id) => {
  try {
    let result = await sequelize.query(`
        DELETE FROM staff_task_messages WHERE ID = ${id};
        `)
    if (result) {
      return true
    } else {
      return false
    }
  } catch (error) {
    console.log(error);
    return false
  }
}

const getTaskActivity = async (id, limit) => {
  try {
    const result = await sequelize.query(`
      SELECT
        user_action_log.timestamp,
        user_action_log.ID,
        user_action_log.message,
        user_action_log.url,
        users.id AS userid,
        CONCAT(users.first_name, ' ', users.last_name) AS username,
        users.profile_pic
      FROM
        user_action_log
      JOIN
        users ON users.id = user_action_log.userid
      WHERE
        user_action_log.taskid = :taskId
      ORDER BY
        user_action_log.ID DESC
      LIMIT :limit;
    `, {
      replacements: { taskId: id, limit: parseInt(limit) },
      type: Sequelize.QueryTypes.SELECT
    });

    if (result) {
      const data = result.map((row) => row);
      return data;
    } else {
      return false;
    }
  } catch (error) {
    console.error("Error fetching task activity:", error);
  }
};

const getUserAssignedTasks = async (field_name, user_id,) => {
  try {

    const result = await sequelize.query(`
        SELECT 
          staff_tasks.name,
          staff_tasks.ID,
          staff_tasks.status,
          p.short_code AS short_code,
          staff_tasks.ticket_uid,
          staff_tasks.due_date,
          staff_tasks.start_date,
          COALESCE(st.no_of_tasks, 0) AS no_of_tasks,
          COALESCE(st1.no_of_completed_tasks, 0) AS no_of_completed_tasks,
          COALESCE(st2.no_of_pending_tasks, 0) AS no_of_pending_tasks,
          staff_tasks.description,
          staff_tasks.complete
        FROM staff_tasks
        LEFT JOIN (
          SELECT taskid, COUNT(*) AS no_of_tasks
          FROM staff_task_objectives
          GROUP BY taskid
        ) AS st ON st.taskid = staff_tasks.ID
        LEFT JOIN (
          SELECT taskid, COUNT(*) AS no_of_completed_tasks
          FROM staff_task_objectives
          WHERE complete = 1
          GROUP BY taskid
        ) AS st1 ON st1.taskid = staff_tasks.ID
        LEFT JOIN (
          SELECT taskid, COUNT(*) AS no_of_pending_tasks
          FROM staff_task_objectives
          WHERE complete = 0
          GROUP BY taskid
        ) AS st2 ON st2.taskid = staff_tasks.ID
        LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
        WHERE staff_tasks.${field_name} = :user_id
        ORDER BY staff_tasks.ID DESC;
      `, {
      replacements: { user_id },
      type: Sequelize.QueryTypes.SELECT,
    });


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

  } catch (error) {
    console.error(error);
    throw new Error('Failed to fetch tasks');
  }
};

const getTicketById = async (id) => {
  let query = await sequelize.query(`SELECT s.*,prt.name as client_name,u.profile_pic as client_pic,concat(u1.first_name,' ',u1.last_name) as created_by, p.name as project_name, p.short_code,mn.module_name FROM staff_tasks s`
    + ` LEFT JOIN projects p ON p.id = s.project_id`
    + ` LEFT JOIN module_names  mn ON mn.id = s.module`
    + ` LEFT JOIN partners prt ON prt.id = s.partner_id`
    + ` LEFT JOIN users u ON u.id = prt.user_id`
    + ` LEFT JOIN users u1 ON u1.id=s.userid`
    + ` WHERE s.ID=${id}`);

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

const getUsers = async (id) => {
  try {
    let userid = [];
    let query1 = await sequelize.query(`SELECT userid FROM staff_task_members WHERE taskid=${id}`);

    if (query1.length > 0) {
      userid = query1[0].map(item => item.userid);
    }

    let whereCondition = "";
    if (userid.length > 0) {
      whereCondition = " AND users.id NOT IN (" + userid.join(",") + ")";
    }

    let query2 = await sequelize.query(`
      SELECT users.id, users.first_name, users.last_name
      FROM staff_members
      LEFT JOIN users ON users.id = staff_members.user_id
      WHERE (users.status = 1 AND staff_members.status = 1) AND (users.user_type = 51 OR users.user_type = 52 OR users.user_type = 60) ${whereCondition}
    `, { type: Sequelize.QueryTypes.SELECT });

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

    return data;
  } catch (error) {
    console.error("Error fetching users:", error);
    return [];
  }
};

const getTaskMembers = async (id) => {
  try {
    const query = await sequelize.query(`
      SELECT
        users.id AS userid,
        CONCAT(users.first_name, ' ', users.last_name) AS username,
        users.profile_pic,
        users.email,
        users.email_notification,
        users.active,
        staff_task_members.ID
      FROM
        staff_task_members
      LEFT JOIN
        users ON users.id = staff_task_members.userid
      WHERE
        staff_task_members.taskid = :taskId`, {
      replacements: { taskId: id },
      type: Sequelize.QueryTypes.SELECT
    });

    let data = [];
    if (query.length > 0) {
      data = query;
    }
    return data;
  } catch (error) {
    console.error("Error fetching task members:", error);
    return [];
  }
};

const getTaskObjectives = async (id) => {
  let query = await sequelize.query(`select * from staff_task_objectives where taskid=${id}`)
  let data = []
  if (query.length > 0) {
    data = query[0];

  }
  return data;
}
const getTaskSheets = async (id) => {
  let query = await sequelize.query(`select.* from staff_task_sheets where taskid=${id}`)
  let data = []
  console.log(query, '!!!!!!!!!!!!!!!!!!!!!!!!')
  if (query.length > 0) {
    data = query[0];

  }
  return data;
}
const getAttachedFiles = async (id) => {
  let query = await sequelize.query(` select staff_task_files.ID,
  staff_task_files.extension, staff_task_files.upload_file_name,
  staff_task_files.file_size, staff_task_files.file_url,
  staff_task_files.file_type, staff_task_files.taskid from staff_task_files`
    + ` where taff_task_files.taskid=${id} `)
  let data = []
  if (query.length > 0) {
    data = query[0];

  }
  return data;
}
const getTaskMessages = async (id) => {
  let query = await sequelize.query(` select staff_task_messages.ID, staff_task_messages.message,staff_task_messages.timestamp,staff_task_messages.sent_from_installation_id,  staff_task_messages.userid, staff_task_messages.taskid, users.username, users.profile_pic, users.active from staff_task_messages`
    + `  join users on users.id = staff_task_messages.userid`
    + ` where staff_task_messages.taskid=${id} order by staff_task_messages.ID`)
  let data = []
  if (query.length > 0) {
    data = query[0];

  }
  return data;
}
const getActivityLog = async (id) => {
  try {
    const query = await sequelize.query(`SELECT user_action_log.timestamp,user_action_log.ID,
        user_action_log.message,user_action_log.url, users.id AS userid,CONCAT(users.first_name, ' ', users.last_name) AS username,
        users.profile_pic,users.active FROM  user_action_log LEFT JOIN users ON users.id = user_action_log.userid
         WHERE  user_action_log.taskid = ${id}
         ORDER BY user_action_log.ID DESC`, {

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

    }
    return data;
  } catch (error) {
    console.error("Error fetching activity log:", error);
    return [];
  }
};
const deleteTicket = async (id) => {
  try {
    const deleted = await Tickets.destroy({
      where: {
        ID: id
      },
    });
    if (deleted) {
      return true;
    }
    else {
      return false;
    }
  } catch (error) {
    console.log(error)
  }
}
const updateTicket = async (data, id) => {
  const result = await Tickets.update(data, {
    where: { ID: id },
    returning: true,
  });
  if (result) {
    return true
  } else {
    return false
  }
}
const getAllicketsMessages = async (id) => {
  try {
    let result = await sequelize.query(`select tm.*, concat(u.first_name,' ', u.last_name) as name ,u.profile_pic as profile_pic from staff_task_messages as tm left join users u on u.id = tm.userid where taskid=${id} 
    ORDER BY tm.ID DESC
    `)
    if (result[0].length > 0) {
      return result[0]
    } else {
      return []
    }
  } catch (error) {
    console.log(error)
  }
}
const getTicketsForClients = async (id) => {
  let result = await sequelize.query(`
  SELECT staff_tasks.name, staff_tasks.ID, staff_tasks.ticket_uid,staff_tasks.status,staff_tasks.timestamp,
  staff_tasks.description,staff_tasks.complete, p.name AS project_name,p.short_code AS short_code FROM staff_tasks
LEFT JOIN projects AS p ON p.id = staff_tasks.project_id
WHERE staff_tasks.status != 0 and  staff_tasks.partner_id = ${id}
ORDER BY staff_tasks.ID DESC;
  `)
  if (result[0].length > 0) {
    return result[0]
  } else {
    return []
  }
}


const getTeamData = async () => {
  try {

    let query2 = await sequelize.query(`
      SELECT users.id,CONCAT(users.first_name, ' ', users.last_name) AS name,staff_members.id as member_id,staff_members.email
      FROM staff_members
      LEFT JOIN users ON users.id = staff_members.user_id
      WHERE (users.status = 1 AND staff_members.status = 1) AND (users.user_type = 51 OR users.user_type = 52 OR users.user_type = 60);
    `, { type: Sequelize.QueryTypes.SELECT });

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

    return data;
  } catch (error) {
    console.error("Error fetching users:", error);
    return [];
  }
};


const GetAllModuleNames = async (data) => {
  try {
    let result = await ModuleNames.findAll()

    return result
  } catch (error) {
    console.log(error)
  }
}


const AddFilesToTask = async (data) => {
  try {
    let result = await Staff_Task_Files.create(data)

    return result.ID
  } catch (error) {
    console.log(error)
  }
}

const fetchFilesByTaskId = async (taskid) => {
  try {
    const files = await Staff_Task_Files.findAll({
      where: { taskid },
    });
    return files;
  } catch (error) {
    console.error("Error fetching files by taskid:", error);
    throw error;
  }
};


const AddTimeLog = async (data) => {
  try {
    let result = await TicketTimeLog.create(data)

    return result.id
  } catch (error) {
    console.log(error)
  }
}

const getTimeLogByTask = async (taskId, teamId) => {
  try {
    const timeLogs = await TicketTimeLog.findAll({
      where: {
        task_id: taskId,
        team_id: teamId,
        end_time: null, // Only fetch logs with end_time as null
      },
    });

    return timeLogs; // Returns the array of matching time logs
  } catch (error) {
    console.error("Error fetching time logs:", error);
    throw error;
  }
};

const updateTimeLog = async (id, data) => {
  try {
    const [updatedRowsCount] = await TicketTimeLog.update(data, {
      where: {
        id: id,
      },
    });


    if (updatedRowsCount === 0) {
      throw new Error("No record found to update");
    }

    const updatedTimeLog = await TicketTimeLog.findByPk(id);

    return updatedTimeLog;

  } catch (error) {
    console.error('Error in updateTimeLog:', error); // Log the error
    throw new Error('Failed to update time log'); // Rethrow the error for further handling
  }
};

const getTimeLogById = async (id) => {
  try {
    const timeLogs = await TicketTimeLog.findAll({
      where: {
        id: id
      },
    });

    return timeLogs; // Returns the array of matching time logs
  } catch (error) {
    console.error("Error fetching time logs:", error);
    throw error;
  }
};

const getAllTimeLogDataByTaskId = async (taskId) => {
  try {
    const timeLogs = await TicketTimeLog.findAll({
      where: {
        task_id: taskId
      },
    });

    return timeLogs; // Returns the array of matching time logs
  } catch (error) {
    console.error("Error fetching time logs:", error);
    throw error;
  }
};

// MODEL
const addStickyNote = async (data) => {
  try {
    const result = await StickyNote.create(data);
    return result.id;  // Return created ID
  } catch (error) {
    console.error('Error adding sticky note:', error);
    throw error;
  }
};

const editStickyNote = async (id, data) => {
  try {
    const result = await StickyNote.update(data, {
      where: { id }
    });
    return result[0] > 0; // true if rows were affected
  } catch (error) {
    console.error('Error editing sticky note:', error);
    throw error;
  }
};

const getStickyNote = async () => {
  try {
    const result = await sequelize.query(`
      SELECT sn.*, 
             CONCAT(u.first_name, ' ', u.last_name) AS user_name,
             CONCAT(u2.first_name, ' ', u2.last_name) AS updated_by_name,
             sn.updated_on
      FROM sticky_notes sn
      LEFT JOIN users u ON sn.added_by = u.id
      LEFT JOIN users u2 ON sn.updated_by = u2.id
      WHERE sn.status = 1
      ORDER BY sn.id DESC
      LIMIT 1
    `, {
      type: sequelize.QueryTypes.SELECT
    });

    return result.length > 0 ? result[0] : null;
  } catch (error) {
    console.error('Error fetching sticky note:', error);
    throw error;
  }
};
const addStickyNoteIndividual = async (data) => {
  try {
    const result = await StickyNoteIndividual.create(data);
    return result.id;  // Return created ID
  } catch (error) {
    console.error('Error adding sticky note:', error);
    throw error;
  }
};

const editStickyNoteIndividual = async (id, data) => {
  try {
    const result = await StickyNoteIndividual.update(data, {
      where: { id }
    });
    return result[0] > 0; // true if rows were affected
  } catch (error) {
    console.error('Error editing sticky note:', error);
    throw error;
  }
};

const getStickyNoteIndividual = async (userId) => {
  try {
    const result = await sequelize.query(`
      SELECT sn.*, 
             CONCAT(u.first_name, ' ', u.last_name) AS user_name,
             CONCAT(u2.first_name, ' ', u2.last_name) AS updated_by_name,
             sn.updated_on
      FROM sticky_notes_individual sn
      LEFT JOIN users u ON sn.added_by = u.id
      LEFT JOIN users u2 ON sn.updated_by = u2.id
      WHERE sn.status = 1
      AND sn.archive != 1
        AND (
          sn.added_by = :userId 
          OR (FIND_IN_SET(:userId, sn.share_with) AND sn.is_private = 0)
        )
      ORDER BY sn.id DESC
    `, {
      type: sequelize.QueryTypes.SELECT,
      replacements: { userId: String(userId) }  // ðŸ‘ˆ ensures correct behavior
    });

    console.log('result=====', userId, result)
    return result.length > 0 ? result : null;
  } catch (error) {
    console.error('Error fetching sticky note:', error);
    throw error;
  }
};



const getAllTeamsForNotes = async (userId, userType) => {
  console.log('usersId,usersType++++++++++', userId, userType)
  try {
    let sql = `
      SELECT DISTINCT p.*, 
        CASE WHEN p.onboard_complete = 0 THEN 'N' ELSE 'Y' END AS active,
        ts.service_id, 
        u.username, u.company_name, u.company_logo, u.user_type, u.status AS user_status, u.profile_pic,
        s.short_name AS state,
        0 AS rating, 0 AS no_of_reviews,
        COALESCE(rp.no_of_requests, 0) AS no_of_requests,
        ur.name AS userRole
      FROM staff_members p
      LEFT JOIN users u ON p.user_id = u.id
      LEFT JOIN states s ON p.state_id = s.id
      LEFT JOIN user_roles ur ON ur.id = u.user_type
      LEFT JOIN team_services ts ON ts.team_id = p.id
      LEFT JOIN (
        SELECT COUNT(rt.id) AS no_of_requests, rt.team_user_id 
        FROM request_teams rt
        LEFT JOIN requests r ON r.id = rt.request_id
        WHERE rt.status = 1 AND r.status != 0
        GROUP BY rt.team_user_id
      ) rp ON p.id = rp.team_user_id
      WHERE p.status = 1`;

    if (userId) {
      sql += ` AND p.user_id != ${userId}`;
    }

    if (userType === 3) {
      sql += ` AND p.added_by = ${userId}`;
    } else {
      sql += ` AND u.added_by_client = 0`;
    }

    sql += ` ORDER BY p.card_order ASC`;

    const result = await sequelize.query(sql);
    const data = result[0];
    console.log('data+++++++++++', result)
    console.log('data+++++++++++', data)

    const totalCountQuery = `
      SELECT COUNT(p.id) AS totalCount 
      FROM staff_members p
      WHERE p.status = 1
      ${userType === 3 ? `AND p.added_by = ${userId}` : `AND p.user_id != ${userId}`}
    `;

    const totalCount = await sequelize.query(totalCountQuery);
    let adminData = [];
    let UpdateData = [];
    if (userId !== 1) {
      adminData = await Admin.getUserByIdForteam(1)
      console.log('adminData++++++', adminData)
      UpdateData = [...data, ...adminData]
    } else {
      UpdateData = data
    }

    if (UpdateData?.length > 0) {
      return {
        data: UpdateData,
        totalCount: totalCount[0][0].totalCount
      };
    } else {
      return { data: [], totalCount: 0 };
    }
  } catch (error) {
    console.error("Error fetching teams:", error);
    return false;
  }
};

const getArchivedStickyNotes = async (userId) => {
  try {
    const result = await sequelize.query(`
      SELECT sn.*, 
             CONCAT(u.first_name, ' ', u.last_name) AS user_name,
             CONCAT(u2.first_name, ' ', u2.last_name) AS updated_by_name,
             sn.updated_on
      FROM sticky_notes_individual sn
      LEFT JOIN users u ON sn.added_by = u.id
      LEFT JOIN users u2 ON sn.updated_by = u2.id
      WHERE sn.status = 1
        AND sn.archive = 1
        AND sn.added_by = :userId
      ORDER BY sn.id DESC
    `, {
      type: sequelize.QueryTypes.SELECT,
      replacements: { userId: String(userId) }
    });

    return result.length > 0 ? result : [];
  } catch (error) {
    console.error("Error fetching archived sticky notes:", error);
    throw error;
  }
};

const getStickyNoteIndividualById = async (id) => {
  try {
    const result = await sequelize.query(`
      SELECT * FROM sticky_notes_individual WHERE id = :id LIMIT 1
    `, {
      replacements: { id },
      type: sequelize.QueryTypes.SELECT
    });

    return result.length > 0 ? result[0] : null;
  } catch (error) {
    console.error("Error fetching sticky note by ID:", error);
    throw error;
  }
};

module.exports = {
  getAllTasks,
  getStatusCounts,
  AddTickets,
  getTask,
  getTicketId,
  deleteMessages,
  getTaskActivity,
  getUserAssignedTasks,
  getTicketById,
  getUsers,
  getTaskMembers,
  getTaskObjectives,
  getTaskSheets,
  getAttachedFiles,
  getTaskMessages,
  getActivityLog,
  deleteTicket,
  getAllicketsMessages,
  updateTicket,
  getTicketsForClients,
  getTeamData,
  GetAllModuleNames,
  AddFilesToTask,
  fetchFilesByTaskId,
  AddTimeLog,
  getTimeLogByTask,
  updateTimeLog,
  getTimeLogById,
  getAllTimeLogDataByTaskId,
  getStickyNote,
  addStickyNote,
  editStickyNote,
  getStickyNoteIndividual,
  addStickyNoteIndividual,
  editStickyNoteIndividual,
  getAllTeamsForNotes,
  getArchivedStickyNotes,
  getStickyNoteIndividualById,
}


