SET FOREIGN_KEY_CHECKS = 0;
**
CREATE TABLE IF NOT EXISTS `acc_districts_master` (
  `state_name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
  `state_code` int DEFAULT NULL,
  `district_code` int DEFAULT NULL,
  `district_name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
  `town_code` int DEFAULT NULL,
  `town_name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**
CREATE TABLE IF NOT EXISTS `acc_state_master` (
  `state_id` int NOT NULL AUTO_INCREMENT,
  `state_name` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT '',
  `state_code` varchar(3) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
  `state_abbreviation` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`state_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
**
INSERT INTO `acc_state_master` (`state_id`, `state_name`, `state_code`, `state_abbreviation`) VALUES
	(1, 'Andaman & Nicobar Islands', '35', 'AN'),
	(2, 'Andhra Pradesh', '28', 'AP'),
	(3, 'Arunachal Pradesh', '12', 'AR'),
	(4, 'Assam', '18', 'AS'),
	(5, 'Bihar', '10', 'BH'),
	(6, 'Chandigarh', '04', 'CH'),
	(7, 'Chhattisgarh', '22', 'CT'),
	(8, 'Dadra & Nagar Haveli', '26', 'DN'),
	(9, 'Daman & Diu', '25', 'DD'),
	(10, 'Delhi', '07', 'DL'),
	(11, 'Goa', '30', 'GA'),
	(12, 'Gujarat', '24', 'GJ'),
	(13, 'Haryana', '06', 'HR'),
	(14, 'Himachal Pradesh', '02', 'HP'),
	(15, 'Jammu & Kashmir', '01', 'JK'),
	(16, 'Jharkhand', '20', 'JH'),
	(17, 'Karnataka', '29', 'KA'),
	(18, 'Kerala', '32', 'KL'),
	(19, 'Lakshadweep', '31', 'LD'),
	(20, 'Madhya Pradesh', '23', 'MP'),
	(21, 'Maharashtra', '27', 'MH'),
	(22, 'Manipur', '14', 'MN'),
	(23, 'Meghalaya', '17', 'ME'),
	(24, 'Mizoram', '15', 'MI'),
	(25, 'Nagaland', '13', 'NL'),
	(26, 'Odisha', '21', 'OR'),
	(27, 'Puducherry', '34', 'PY'),
	(28, 'Punjab', '03', 'PB'),
	(29, 'Rajasthan', '08', 'RJ'),
	(30, 'Sikkim', '11', 'SK'),
	(31, 'Tamil Nadu', '33', 'TN'),
	(32, 'Tripura', '16', 'TR'),
	(33, 'Uttar Pradesh', '09', 'UP'),
	(34, 'Uttarakhand', '05', 'UT'),
	(35, 'West Bengal', '19', 'WB'),
	(36, 'Andhra Pradesh (New)', '37', 'AD'),
	(37, 'Telangana', '36', 'TS'),
	(38, 'Other', '00', '--');

**
CREATE TABLE IF NOT EXISTS `acc_theme_master` (
  `id` smallint NOT NULL AUTO_INCREMENT,
  `theme` varchar(20) NOT NULL,
  `class` varchar(50) NOT NULL,
  `color` varchar(50) NOT NULL,
  `is_default` tinyint(1) NOT NULL DEFAULT '0',
  `status` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb3;

**
INSERT INTO `acc_theme_master` (`id`, `theme`, `class`, `color`, `is_default`, `status`) VALUES
	(1, 'Indigo', 'indigo', '#4d83d1', 1, 1),
	(2, 'Deep Purple', 'deep-purple', '#4a148c', 0, 1),
	(3, 'Teal', 'teal', '#00695c', 0, 1),
	(4, 'Cyan', 'cyan', '#00838f', 0, 1),
	(5, 'Black', 'black', '#424242', 0, 1);

**
CREATE PROCEDURE `AgentlogReport`(
	IN `user_id` TEXT,
	IN `queue_id` VARCHAR(50),
	IN `sqlcondition` TEXT,
	IN `limit_offset` VARCHAR(10)
)
BEGIN
set  @a:=0;

SET @sqlquery=CONCAT ('select @a:=@a+1 as SrNo, 
ttm.ticket_unique_id AS ticket_id ,ttm.ticket_id AS ticket,ttm.Person_name,ttm.mobile_no,ctm.title AS MODE,
tms_queue_master.queue as Queue,tqp.priority_name as Priority,tqp.colour_code as PriorityColour,
tqs.status_name as Status,tqs.colour_code as StatusColour,ttm.created_date as created_date ,ttm.last_updated_on as last_updated_on,ifnull(tumby.user_name,"Auto") as assigned_by
,concat(ttm.created_date ,''\n'', ttm.last_updated_on) as date_update,ttm.subject as subject
/*, Case when IFNULL(tqs.is_close_status, "0") = 1 and TIMESTAMPDIFF(hour,ttm.created_date,conversation_date)<=ifnull(tqe.hours,10) then ''Yes'' else ''No'' end as IsClosedInSLA ,      
ttm.created_date as TicketStartDate,
Case when IFNULL(tqs.is_close_status, "0") = 1 
 then conversation_date else now() end as ClsT_or_CUT,
concat(round(Case when IFNULL(tqs.is_close_status, "0") = 1 
then TIMESTAMPDIFF(second,ttm.created_date,tcm.conversation_date) 
else TIMESTAMPDIFF(second,ttm.created_date,now()) end/ 86400,0)
,''d '',
sec_to_time(Case when IFNULL(tqs.is_close_status, "0") = 1 
then TIMESTAMPDIFF(second,ttm.created_date,tcm.conversation_date) 
else TIMESTAMPDIFF(second,ttm.created_date,now()) end % 86400)) AS TAT   */          
,tms_queue_category_',queue_id,'.category_name as Category,tms_queue_sub_category_',queue_id,'.sub_category_name as Subcategory,
 tum.user_name as AssignedTo,tum.user_name as ReadBy
from tms_ticket_master_',queue_id,' ttm
left Join tms_user_master tum on tum.user_id=ttm.assigned_to
left Join tms_user_master tumby on tumby.user_id=ttm.assigned_by

/*JOIN (SELECT user_id FROM tms_user_master WHERE user_id=',user_id,' UNION ALL SELECT user_id FROM tms_user_master WHERE manager_id=',user_id,' UNION ALL SELECT 0) hie on hie.user_id=tum.user_id*/

left join tms_queue_priority_',queue_id,' tqp on tqp.priority_id=ttm.priority_id
left JOIN (SELECT MAX(conversation_id) AS Last_conversation_id, ticket_unique_id FROM tms_conversation_master_',queue_id,'  GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = ttm.ticket_unique_id 
left join tms_conversation_master_',queue_id,' tcm on tcm.conversation_id = Last_con.Last_conversation_id 	   
left JOIN tms_queue_escalationmatrix_',queue_id,' tqe ON tqe.priority_id =ifnull(ttm.priority_id,3) AND (TIMESTAMPDIFF(SECOND, ttm.created_date, tcm.conversation_date) / 3600) = hours AND ((TIMESTAMPDIFF(SECOND, ttm.created_date, tcm.conversation_date) % 3600) / 60) >= minute   
left Join tms_queue_master on ttm.queue_id = tms_queue_master.id
left join tms_conversation_type_master ctm on ctm.id=ttm.Start_mode
left join tms_queue_category_',queue_id,' on ttm.category_id = tms_queue_category_',queue_id,'.category_id
left join tms_queue_sub_category_',queue_id,' on ttm.subcategory_id = tms_queue_sub_category_',queue_id,'.sub_category_id
left join tms_queue_status_',queue_id,' tqs on tqs.status_id=ttm.status_id
where 1=1 AND IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0  and IFNULL(ttm.is_draft,0) = 0   ',
 if( IFNULL(user_id,"")!="",CONCAT(' and tum.user_id in (',user_id,')'),""),'
');


if sqlcondition!= '' then
	 set @sqlquery=CONCAT(@sqlquery,sqlcondition);
END if;

if limit_offset !='' then
	SET @sqlquery = CONCAT(@sqlquery,' LIMIT ', limit_offset);
END if;
   
PREPARE stmtsqlquery FROM @sqlquery;
    EXECUTE stmtsqlquery;
    DEALLOCATE PREPARE stmtsqlquery;
END
**

CREATE TABLE IF NOT EXISTS `agent_productivity_report_log` (
  `id` int NOT NULL AUTO_INCREMENT,
  `agent_id` int DEFAULT NULL,
  `agent_name` varchar(50) DEFAULT NULL,
  `ticket_id` int DEFAULT NULL,
  `queue_id` int DEFAULT NULL,
  `start_time` datetime DEFAULT NULL,
  `end_time` datetime DEFAULT NULL,
  `duration` varchar(50) DEFAULT NULL,
  `state` varchar(50) DEFAULT NULL,
  `break_id` int DEFAULT NULL,
  `break_name` varchar(50) DEFAULT NULL,
  `ip_address` varchar(100) DEFAULT NULL,
  `is_login` int DEFAULT NULL,
  `remark` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE PROCEDURE `Agent_report`(
	IN `fromDate` VARCHAR(50),
	IN `toDate` VARCHAR(50),
	IN `user_id` VARCHAR(100),
	IN `queue_id` INT,
	IN `fullcontrol` INT,
	IN `limit_offset` VARCHAR(30)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
   BEGIN
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
       SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
   
        ROLLBACK;   
   END; 
   START TRANSACTION;

SET @fromDate = case when IFNULL(fromDate,'')='' then CURDATE() ELSE fromDate END;
SET @toDate = case when IFNULL(toDate,'')='' then NOW() ELSE toDate END;

 SET SESSION group_concat_max_len = 10000000;
 SET @user_id=user_id;
 
SET @sql = CONCAT('SELECT group_concat(DISTINCT status_id) INTO @status_ids
FROM tms_user_master tum JOIN tms_statuspermission_',queue_id,' tsp ON tum.user_type=tsp.user_type
WHERE tsp.is_checked=1 AND tum.user_id in (',user_id,') ');

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;
 
 
    SET @col1 = CONCAT('SELECT GROUP_CONCAT(CONCAT("SUM(CASE WHEN IFNULL(tqs.status_name, """") = ''",status_name,"'' THEN 1 ELSE 0 END) AS ''",status_name,"''"))  
    into @exactcol1
    FROM tms_queue_status_',queue_id,' tqs  where 1=1 ',if( IFNULL(fullcontrol,0)=0,CONCAT('and  tqs.status_id in (',@status_ids,')'),""),' ORDER BY order_no ASC');
    
    PREPARE stmtcol1 FROM @col1;
    EXECUTE stmtcol1;
    DEALLOCATE PREPARE stmtcol1; 
   
    
    
    
    SET @sqlquery = 'SELECT  ';    
	    SET @sqlquery = CONCAT(@sqlquery, ' tum.user_name as "User Name" , tum.user_id as user_id  ');
	 
	  
    SET @sqlquery = CONCAT(@sqlquery,'  , tqp.priority_name, tqp.colour_code, COUNT(1) AS TotalTicket,
    SUM(CASE WHEN tqs.ticket_status_type=1 THEN 1 ELSE 0 END) Final,
    SUM(CASE WHEN tqs.ticket_status_type!=1 THEN 1 ELSE 0 END) Non_Final, ',if(IFNULL(@exactcol1,'')='','',CONCAT(@exactcol1,',')),   
    ' "new" AS SLAPercentage 
	 ',    
    'FROM tms_ticket_master_',queue_id,' AS ttm ', 
    'LEFT JOIN tms_user_master tum ON tum.user_id = ttm.assigned_to ',    
    'LEFT JOIN (SELECT MAX(conversation_id) AS Last_conversation_id, ticket_unique_id FROM tms_conversation_master_',queue_id,' tcm GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = ttm.ticket_unique_id ',
    'LEFT JOIN tms_conversation_master_',queue_id,' tcm ON tcm.conversation_id = Last_con.Last_conversation_id ', 	   
    'LEFT JOIN tms_queue_escalationmatrix_',queue_id,' tqe ON tqe.priority_id =ifnull(ttm.priority_id,3) AND (TIMESTAMPDIFF(SECOND, ttm.created_date, tcm.conversation_date) / 3600) = hours AND ((TIMESTAMPDIFF(SECOND, ttm.created_date, tcm.conversation_date) % 3600) / 60) >= minute ',   
    'LEFT JOIN tms_queue_priority_',queue_id,' tqp ON ttm.priority_id = tqp.priority_id ',
    'LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id ',
    ' where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 and IFNULL(ttm.is_draft,0) = 0   ',if( IFNULL(user_id,"")!="",CONCAT(' and tum.user_id in (',user_id,')'),""),if( IFNULL(fullcontrol,0)=0,CONCAT('and  tqs.status_id in (',@status_ids,')'),""), ' AND ttm.last_updated_on>="',CONCAT(@fromDate, ' ','00:00:00'),'" and ttm.last_updated_on<="',CONCAT(@toDate, ' ', '23:59:59'),'" '
    'GROUP BY priority_name, colour_code'
	 );
	 
	    SET @sqlquery = CONCAT(@sqlquery, ',tum.user_name,tum.user_id');
	 
	 
	 if limit_offset !='' then
	 	SET @sqlquery = CONCAT(@sqlquery,' LIMIT ', limit_offset);
	 END if;
  # SELECT @sqlquery;
 PREPARE stmtsqlquery FROM @sqlquery;
    EXECUTE stmtsqlquery;
    DEALLOCATE PREPARE stmtsqlquery;
COMMIT;
END
**


CREATE TABLE IF NOT EXISTS `auth_type` (
  `id` int NOT NULL AUTO_INCREMENT,
  `type` varchar(50) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
**

INSERT INTO `auth_type` (`id`, `type`) VALUES
	(1, 'Logout BY Software'),
	(2, 'Logout By Master'),
	(3, 'Auto Session Expired'),
	(4, '24 Hours Session Expired'),
	(5, 'Other'),
	(6, 'Login Other IP'),
	(7, 'Login With Master Password'),
	(8, 'Login With Original Password'),
	(9, 'CRM Login'),
	(10, 'CRM Logout');

**
CREATE PROCEDURE `autoMailAssign`(
	IN `queueid` INT,
	IN `ticketid` VARCHAR(20),
	IN `type` VARCHAR(15)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN		
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
    SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
    
      SET @sql1 = CONCAT('drop table if exists temp_assigned_to_',@curdatetime,',temp_table_',@curdatetime);

		PREPARE stmt1 FROM @sql1; 
		EXECUTE stmt1; 
		DEALLOCATE PREPARE stmt1;
		
        ROLLBACK;   
    END; 
START TRANSACTION;
SET @auto_assign_login_agent_count=0;
SELECT COUNT(1) INTO @auto_assign_login_agent_count from tms_user_master WHERE tms_user_master.is_login=1 AND tms_user_master.auto_assign=1 AND FIND_IN_SET(queueid,tms_user_master.queue_id) AND  COALESCE(break_state,0)!= 1;

SET @auto_assign_queue_count=0;
SET @assign_shift_wise='';
SET @before_assign_shift=''; 

SELECT tms_queue_master.id,assign_shift_wise,before_assign_shift 
INTO @auto_assign_queue_count,@assign_shift_wise,@before_assign_shift 
from tms_queue_master WHERE  tms_queue_master.auto_assign=1 AND tms_queue_master.id=queueid;

if (IfNULL(@auto_assign_login_agent_count,0)>0 AND IFNULL(@auto_assign_queue_count,0)>0)
then 

	SET @curdatetime = replace(replace(replace(replace(current_timestamp(6),'-',''),':',''),' ','_'),'.','_');

	# SELECT id INTO @usertypeid from tms_user_type where title='agent';

	SET @sql1 = CONCAT('drop table if exists temp_assigned_to_',queueid,'_',@curdatetime,',temp_table_',queueid,'_',@curdatetime);

	PREPARE stmt2 FROM @sql1; 
	EXECUTE stmt2; 
	DEALLOCATE PREPARE stmt2;

	select assigntimegap,mailassignlimit INTO @assign_Time_Gap,@agent_Maillimit from tms_company_master;


	SET @sql1 = CONCAT('create table temp_assigned_to_',queueid,'_',@curdatetime,' select count(1) as total_count,assigned_to from tms_ticket_master_',queueid,' tick_mast join tms_queue_status_',queueid,' que_stats on tick_mast.status_id=que_stats.status_id where ifnull(que_stats.is_close_status,0)=0 AND tick_mast.is_deleted_ticket=0 AND tick_mast.is_junk=0 and assigned_to>0 group by assigned_to');


	PREPARE stmt3 FROM @sql1; 
	EXECUTE stmt3; 
	DEALLOCATE PREPARE stmt3;

	SET @sql1 = CONCAT('update tms_user_master join temp_assigned_to_',queueid,'_',@curdatetime,' on user_id=assigned_to set ticket_assigned= total_count');


	PREPARE stmt4 FROM @sql1; 
	EXECUTE stmt4; 
	DEALLOCATE PREPARE stmt4;


	SET @sql1 = CONCAT('select ifnull( ',IFNULL(@agent_Maillimit,0),'-sum(ifnull(ticket_assigned,0)),0) 
										INTO @tickets_To_Assign 
						     from tms_user_master user_master
							  where user_master.auto_assign=1 and user_master.is_login = 1 and  COALESCE(break_state,0)!= 1
							  and ifnull(ticket_assigned,0) < ',@agent_Maillimit,' 
							  AND FIND_IN_SET("',queueid,'",user_master.queue_id)');
#SELECT @sql1;
	PREPARE stmt5 FROM @sql1; 
	EXECUTE stmt5; 
	DEALLOCATE PREPARE stmt5;

	SET @row_num=0;
	SET @sql1 = CONCAT('create table temp_table_',queueid,'_',@curdatetime,' select @row_num:=@row_num+1 SrNo,ticket_unique_id,ticket_id,assigned_to,is_assigned,a.queue_id
							FROM tms_ticket_master_',queueid,' a
							JOIN tms_queue_status_',queueid,' c ON a.status_id=c.status_id
							WHERE( (ifnull(assigned_to,0)=0 and ifnull(is_assigned,0)=1 )or (ifnull(assigned_to,0)=0 and ifnull(is_assigned,0)=0 )) and c.ticket_status_type=2
							and a.queue_id ="',queueid,'"
							',if(IFNULL(ticketid,"")!="",CONCAT(' and ticket_unique_id="',ticketid,'" '),""),'
							ORDER BY created_date asc LIMIT ',if(ifnull(@tickets_To_Assign,0)<0,0,@tickets_To_Assign) );

	 #SELECT @sql1;
	PREPARE stmt6 FROM @sql1; 
	EXECUTE stmt6; 
	DEALLOCATE PREPARE stmt6;

	SET @sql1 = CONCAT('select count(1) into @total_count_tickets from temp_table_',queueid,'_',@curdatetime);

	PREPARE stmt7 FROM @sql1; 
	EXECUTE stmt7; 
	DEALLOCATE PREPARE stmt7;
	
	if(IFNULL(@total_count_tickets,0)>0) 
	then
SET @u_id='';	

		SET @startFlag = 1;

		WHILE(@startFlag <= ifnull(@total_count_tickets,0)) DO
	
		SET @sql1 = CONCAT('select queue_id,ticket_id into @D_Queue,@TId FROM temp_table_',queueid,'_',@curdatetime,' WHERE SrNo=',@startFlag);
	

		PREPARE stmt8 FROM @sql1; 
		EXECUTE stmt8; 
		DEALLOCATE PREPARE stmt8;
		
	
if (IFNULL(TYPE,"")="" OR IFNULL(TYPE,"")="default") then 	
SET @u_id='';	
		SET @sql1 = CONCAT('select user_master.user_id,ifnull(ticket_assigned,0) INTO @u_id,@assign_tc
								from tms_user_master user_master
								left JOIN tms_shift_master shift_master on shift_master.id=user_master.shift_id
								where    
								 user_master.auto_assign=1 AND user_master.is_login=1 and  COALESCE(break_state,0)!= 1
								 AND FIND_IN_SET("',queueid,'",user_master.queue_id)
								 and ifnull(ticket_assigned,0) < ',@agent_Maillimit,'
								and  ifnull(TIMESTAMPDIFF(MINUTE,last_assign_time,NOW()),',@assign_Time_Gap,') >= ',@assign_Time_Gap,'
								AND CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 
								AND shift_master.id IS NOT NULL THEN NOW() ELSE CURDATE() END
									BETWEEN CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 AND shift_master.id IS NOT NULL 
									THEN CONCAT(CURDATE()," ",shift_master.time_from) ELSE CURDATE() END
									AND CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 AND shift_master.Id IS NOT NULL 
									THEN DATE_ADD(CONCAT(CURDATE()," ",shift_master.time_to),INTERVAL -"',IFNULL(@before_assign_shift,0),'" MINUTE)
									 ELSE CURDATE() END
								
								ORDER BY last_assign_time asc LIMIT 1');

		#SELECT @sql1;
		PREPARE stmt9 FROM @sql1; 
		EXECUTE stmt9; 
		DEALLOCATE PREPARE stmt9;
#SELECT @u_id;
if(IFNULL(@u_id,0)>0  ) then

		UPDATE tms_user_master SET ticket_assigned=ifnull(ticket_assigned,0)+1 WHERE user_id=ifnull(@u_id,0);

		SET @SQL4 = CONCAT('update temp_table_',queueid,'_',@curdatetime,' set assigned_to=',ifnull(@u_id,0),',is_assigned=1 WHERE SrNo=',@startFlag,' and ifnull(queue_id,0)=',ifnull(@D_Queue,0));

      #SELECT @SQL4; 
		PREPARE stmt10 FROM @SQL4; 
		EXECUTE stmt10; 
		DEALLOCATE PREPARE stmt10;
	
		if(select 1 from tms_user_master where User_id=ifnull(@u_id,0) and ticket_assigned <= @agent_Maillimit LIMIT 1) = 1 then
			update tms_user_master SET  last_assign_time=NOW() WHERE user_id=ifnull(@u_id,0);
		END if;
END if;			
END if;

if (IFNULL(TYPE,"")="round-robin") then 
SET @u_id='';	
SET @updated_on="";

SET @SQL=CONCAT('SELECT assigndate into @updated_on FROM tms_user_master 
WHERE assigndate>=curdate() and queue_id like "%',queueid,'%"  limit 1');
#SELECT @SQL;
PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

if IFNULL(@updated_on,"")="" then
SET @SQL1=CONCAT('UPDATE tms_user_master
SET today_count=0,
assigndate=null
WHERE assigndate<curdate() and queue_id like "%',queueid,'%"');
#SELECT @SQL1;
PREPARE stmt FROM @SQL1;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END if;	

		SET @sql1 = CONCAT('select user_master.user_id,ifnull(today_count,0) INTO @u_id,@assign_tc
								from tms_user_master user_master
								left JOIN tms_shift_master shift_master on shift_master.id=user_master.shift_id
								where    
								 user_master.auto_assign=1 AND user_master.is_login=1 and  COALESCE(break_state,0)!= 1
								 AND FIND_IN_SET("',queueid,'",user_master.queue_id)
								 and ifnull(today_count,0) < ',@agent_Maillimit,'
								and  ifnull(TIMESTAMPDIFF(MINUTE,assigndate,NOW()),',@assign_Time_Gap,') >= ',@assign_Time_Gap,'
								AND CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 
								AND shift_master.id IS NOT NULL THEN NOW() ELSE CURDATE() END
									BETWEEN CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 AND shift_master.id IS NOT NULL 
									THEN CONCAT(CURDATE()," ",shift_master.time_from) ELSE CURDATE() END
									AND CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 AND shift_master.Id IS NOT NULL 
									THEN DATE_ADD(CONCAT(CURDATE()," ",shift_master.time_to),INTERVAL -"',IFNULL(@before_assign_shift,0),'" MINUTE)
									 ELSE CURDATE() END
								
								ORDER BY assigndate asc LIMIT 1');

		#SELECT @sql1;
		PREPARE stmt9 FROM @sql1; 
		EXECUTE stmt9; 
		DEALLOCATE PREPARE stmt9;

if(IFNULL(@u_id,0)>0  ) then

		UPDATE tms_user_master SET today_count=ifnull(today_count,0)+1,overallcount=ifnull(overallcount,0)+1 WHERE user_id=ifnull(@u_id,0);

		SET @sql1 = CONCAT('update temp_table_',queueid,'_',@curdatetime,' set assigned_to=',ifnull(@u_id,0),',is_assigned=1 WHERE SrNo=',@startFlag,' and ifnull(queue_id,0)=',ifnull(@D_Queue,0));

#SELECT @sql1; 
	PREPARE stmt10 FROM @sql1; 
		EXECUTE stmt10; 
		DEALLOCATE PREPARE stmt10;
	
		if(select 1 from tms_user_master where User_id=ifnull(@u_id,0) and today_count <= @agent_Maillimit LIMIT 1) = 1 then
			update tms_user_master SET  last_assign_time=NOW(),assigndate=NOW() WHERE user_id=ifnull(@u_id,0);
		END if;
	END if;	
END if;


		SET @startFlag = @startFlag + 1; 

	END WHILE;
	
	SET @sql1 = CONCAT('INSERT INTO user_assign_logs(queue_id,ticket_id,assigned_by,assigned_to,last_assigned)
							select queue_id,ticket_unique_id,0,assigned_to,is_assigned from temp_table_',queueid,'_',@curdatetime,' where ifnull(assigned_to,0)>0');


	PREPARE stmt11 FROM @sql1; 
	EXECUTE stmt11; 
	DEALLOCATE PREPARE stmt11;

	SET @sql1 = CONCAT('update tms_ticket_master_',queueid,' a join temp_table_',queueid,'_',@curdatetime,' b on a.ticket_id = b.ticket_id
							set a.assigned_to=b.assigned_to,a.is_assigned=b.is_assigned,
							a.assigned_on=(CASE WHEN b.assigned_to IS NULL or b.assigned_to = 0 THEN NULL ELSE NOW() END) where a.ticket_id = b.ticket_id and IFNULL(b.assigned_to,0)>0 and IFNULL(a.assigned_to,0)=0');


	PREPARE stmt12 FROM @sql1; 
	EXECUTE stmt12; 
	DEALLOCATE PREPARE stmt12;

/*	SET @sql1 = CONCAT('update tms_unreadconversationcount_',queueid,' a JOIN  temp_table_',queueid,'_',@curdatetime,' b ON a.ticket_unique_id=b.ticket_unique_id
							SET user_id=b.assigned_to');



	PREPARE stmt13 FROM @sql1; 
	EXECUTE stmt13; 
	DEALLOCATE PREPARE stmt13;
*/
	SET @SQL3 = CONCAT('select temp_ticket.ticket_unique_id,temp_ticket.queue_id,temp_ticket.assigned_to from temp_table_',queueid,'_',@curdatetime,' temp_ticket join tms_ticket_master_',queueid,' ticket_master on ticket_master.ticket_unique_id=temp_ticket.ticket_unique_id where temp_ticket.is_assigned=1 and ifnull(temp_ticket.assigned_to,0)>0');

#SELECT @SQL3;
	PREPARE stmt14 FROM @SQL3; 
	EXECUTE stmt14; 
	DEALLOCATE PREPARE stmt14;
ELSE
		SELECT "" ticket_unique_id,"" queue_id,"" assigned_to LIMIT 0;
	
END if;

	SET @sql1 = CONCAT('drop table if exists temp_assigned_to_',queueid,'_',@curdatetime,',temp_table_',queueid,'_',@curdatetime);

	PREPARE stmt15 FROM @sql1; 
	EXECUTE stmt15; 
	DEALLOCATE PREPARE stmt15;

ELSE

SELECT "" ticket_unique_id,"" queue_id,"" assigned_to LIMIT 0;


END if;


	COMMIT;
END
**


CREATE PROCEDURE `autoMailAssign_1`(
	IN `queueid` INT
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN		
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
    SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
    
      SET @sql1 = CONCAT('drop table if exists temp_assigned_to_',@curdatetime,',temp_table_',@curdatetime);

		PREPARE stmt1 FROM @sql1; 
		EXECUTE stmt1; 
		DEALLOCATE PREPARE stmt1;
		
        ROLLBACK;   
    END; 
START TRANSACTION;
SELECT COUNT(1) INTO @auto_assign_login_agent_count from tms_user_master WHERE tms_user_master.is_login=1 AND tms_user_master.auto_assign=1 AND FIND_IN_SET(queueid,tms_user_master.queue_id);

SELECT COUNT(1),assign_shift_wise,before_assign_shift 
INTO @auto_assign_queue_count,@assign_shift_wise,@before_assign_shift 
from tms_queue_master WHERE  tms_queue_master.auto_assign=1 AND tms_queue_master.id=queueid;

if (IfNULL(@auto_assign_login_agent_count,0)>0 AND IFNULL(@auto_assign_queue_count,0)>0)
then 

	SET @curdatetime = replace(replace(replace(replace(current_timestamp(6),'-',''),':',''),' ','_'),'.','_');

	# SELECT id INTO @usertypeid from tms_user_type where title='agent';

	SET @sql1 = CONCAT('drop table if exists temp_assigned_to_',queueid,'_',@curdatetime,',temp_table_',queueid,'_',@curdatetime);

	PREPARE stmt2 FROM @sql1; 
	EXECUTE stmt2; 
	DEALLOCATE PREPARE stmt2;

	select assigntimegap,mailassignlimit INTO @assign_Time_Gap,@agent_Maillimit from tms_company_master;


	SET @sql1 = CONCAT('create table temp_assigned_to_',queueid,'_',@curdatetime,' select count(1) as total_count,assigned_to from tms_ticket_master_',queueid,' tick_mast join tms_queue_status_',queueid,' que_stats on tick_mast.status_id=que_stats.status_id where ifnull(que_stats.is_close_status,0)=0 and assigned_to>0 group by assigned_to');


	PREPARE stmt3 FROM @sql1; 
	EXECUTE stmt3; 
	DEALLOCATE PREPARE stmt3;

	SET @sql1 = CONCAT('update tms_user_master join temp_assigned_to_',queueid,'_',@curdatetime,' on user_id=assigned_to set ticket_assigned= total_count');


	PREPARE stmt4 FROM @sql1; 
	EXECUTE stmt4; 
	DEALLOCATE PREPARE stmt4;


	SET @sql1 = CONCAT('select ifnull(sum( ',IFNULL(@agent_Maillimit,0),'-ifnull(ticket_assigned,0)),0) 
										INTO @tickets_To_Assign 
						     from tms_user_master user_master
							  where user_master.auto_assign=1 and user_master.is_login = 1 
							  and ifnull(ticket_assigned,0) < ',@agent_Maillimit,' 
							  AND FIND_IN_SET("',queueid,'",user_master.queue_id)');
#SELECT @sql1;
	PREPARE stmt5 FROM @sql1; 
	EXECUTE stmt5; 
	DEALLOCATE PREPARE stmt5;




	SET @row_num=0;
	SET @sql1 = CONCAT('create table temp_table_',queueid,'_',@curdatetime,' select @row_num:=@row_num+1 SrNo,ticket_unique_id,ticket_id,assigned_to,is_assigned,a.queue_id
							FROM tms_ticket_master_',queueid,' a
							JOIN tms_queue_status_',queueid,' c ON a.status_id=c.status_id
							WHERE( (ifnull(assigned_to,0)=0 and ifnull(is_assigned,0)=1 )or (ifnull(assigned_to,0)=0 and ifnull(is_assigned,0)=0 )) and c.ticket_status_type=2
							and a.queue_id ="',queueid,'"
							
							ORDER BY created_date asc LIMIT ',if(ifnull(@tickets_To_Assign,0)<0,0,@tickets_To_Assign) );

	 #SELECT @sql1;
	PREPARE stmt6 FROM @sql1; 
	EXECUTE stmt6; 
	DEALLOCATE PREPARE stmt6;

	SET @sql1 = CONCAT('select count(1) into @total_count_tickets from temp_table_',queueid,'_',@curdatetime);

	PREPARE stmt7 FROM @sql1; 
	EXECUTE stmt7; 
	DEALLOCATE PREPARE stmt7;
	
	if(IFNULL(@total_count_tickets,0)>0) 
	then
		SET @startFlag = 1;

		WHILE(@startFlag <= ifnull(@total_count_tickets,0)) DO
	
		SET @sql1 = CONCAT('select queue_id,ticket_id into @D_Queue,@TId FROM temp_table_',queueid,'_',@curdatetime,' WHERE SrNo=',@startFlag);
	

		PREPARE stmt8 FROM @sql1; 
		EXECUTE stmt8; 
		DEALLOCATE PREPARE stmt8;
	
		SET @sql1 = CONCAT('select user_master.user_id,ifnull(ticket_assigned,0) INTO @u_id,@assign_tc
								from tms_user_master user_master
								left JOIN tms_shift_master shift_master on shift_master.id=user_master.shift_id
								where    
								 user_master.auto_assign=1 AND user_master.is_login=1 
								 AND FIND_IN_SET("',queueid,'",user_master.queue_id)
								 and ifnull(ticket_assigned,0) < ',@agent_Maillimit,'
								and  ifnull(TIMESTAMPDIFF(MINUTE,last_assign_time,NOW()),',@assign_Time_Gap,') >= ',@assign_Time_Gap,'
								AND CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 
								AND shift_master.id IS NOT NULL THEN NOW() ELSE CURDATE() END
									BETWEEN CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 AND shift_master.id IS NOT NULL 
									THEN CONCAT(CURDATE()," ",shift_master.time_from) ELSE CURDATE() END
									AND CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 AND shift_master.Id IS NOT NULL 
									THEN DATE_ADD(CONCAT(CURDATE()," ",shift_master.time_to),INTERVAL -"',IFNULL(@before_assign_shift,0),'" MINUTE)
									 ELSE CURDATE() END
								
								ORDER BY ifnull(ticket_assigned,0) asc LIMIT 1');

		#SELECT @sql1;
		PREPARE stmt9 FROM @sql1; 
		EXECUTE stmt9; 
		DEALLOCATE PREPARE stmt9;




		UPDATE tms_user_master SET ticket_assigned=ifnull(ticket_assigned,0)+1 WHERE user_id=ifnull(@u_id,0);

		SET @sql1 = CONCAT('update temp_table_',queueid,'_',@curdatetime,' set assigned_to=',ifnull(@u_id,0),',is_assigned=1 WHERE SrNo=',@startFlag,' and ifnull(queue_id,0)=',ifnull(@D_Queue,0));


		PREPARE stmt10 FROM @sql1; 
		EXECUTE stmt10; 
		DEALLOCATE PREPARE stmt10;
	
		if(select 1 from tms_user_master where User_id=ifnull(@u_id,0) and ticket_assigned <= @agent_Maillimit LIMIT 1) = 1 then
			update tms_user_master SET  last_assign_time=NOW() WHERE user_id=ifnull(@u_id,0);
		END if;
			


		SET @startFlag = @startFlag + 1; 

	END WHILE;
	
	SET @sql1 = CONCAT('INSERT INTO user_assign_logs(queue_id,ticket_id,assigned_by,assigned_to,last_assigned)
							select queue_id,ticket_unique_id,0,assigned_to,is_assigned from temp_table_',queueid,'_',@curdatetime,' where ifnull(assigned_to,0)>0');


	PREPARE stmt11 FROM @sql1; 
	EXECUTE stmt11; 
	DEALLOCATE PREPARE stmt11;

	SET @sql1 = CONCAT('update tms_ticket_master_',queueid,' a join temp_table_',queueid,'_',@curdatetime,' b on a.ticket_id = b.ticket_id
							set a.assigned_to=b.assigned_to,a.is_assigned=b.is_assigned,
							a.assigned_on=(CASE WHEN b.assigned_to IS NULL or b.assigned_to = 0 THEN NULL ELSE NOW() END)');


	PREPARE stmt12 FROM @sql1; 
	EXECUTE stmt12; 
	DEALLOCATE PREPARE stmt12;

	SET @sql1 = CONCAT('update tms_unreadconversationcount_',queueid,' a JOIN  temp_table_',queueid,'_',@curdatetime,' b ON a.ticket_unique_id=b.ticket_unique_id
							SET user_id=b.assigned_to');



	PREPARE stmt13 FROM @sql1; 
	EXECUTE stmt13; 
	DEALLOCATE PREPARE stmt13;

	SET @sql1 = CONCAT('select temp_ticket.ticket_unique_id,temp_ticket.queue_id,temp_ticket.assigned_to from temp_table_',queueid,'_',@curdatetime,' temp_ticket join tms_ticket_master_',queueid,' ticket_master on ticket_master.ticket_unique_id=temp_ticket.ticket_unique_id where temp_ticket.is_assigned=1');



	PREPARE stmt14 FROM @sql1; 
	EXECUTE stmt14; 
	DEALLOCATE PREPARE stmt14;
ELSE
		SELECT "" ticket_unique_id,"" queue_id,"" assigned_to LIMIT 0;
	
END if;

	SET @sql1 = CONCAT('drop table if exists temp_assigned_to_',queueid,'_',@curdatetime,',temp_table_',queueid,'_',@curdatetime);

	PREPARE stmt15 FROM @sql1; 
	EXECUTE stmt15; 
	DEALLOCATE PREPARE stmt15;

ELSE

SELECT "" ticket_unique_id,"" queue_id,"" assigned_to LIMIT 0;


END if;


	COMMIT;
END
**


CREATE PROCEDURE `autoMailAssign_20241223`(
	IN `queueid` INT
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN		
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
    SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
    
      SET @sql1 = CONCAT('drop table if exists temp_assigned_to_',@curdatetime,',temp_table_',@curdatetime);

		PREPARE stmt1 FROM @sql1; 
		EXECUTE stmt1; 
		DEALLOCATE PREPARE stmt1;
		
        ROLLBACK;   
    END; 
START TRANSACTION;
SELECT COUNT(1) INTO @auto_assign_login_agent_count from tms_user_master WHERE tms_user_master.is_login=1 AND tms_user_master.auto_assign=1 AND FIND_IN_SET(queueid,tms_user_master.queue_id) AND  COALESCE(break_state,0)!= 1;

SELECT tms_queue_master.id,assign_shift_wise,before_assign_shift 
INTO @auto_assign_queue_count,@assign_shift_wise,@before_assign_shift 
from tms_queue_master WHERE  tms_queue_master.auto_assign=1 AND tms_queue_master.id=queueid;

if (IfNULL(@auto_assign_login_agent_count,0)>0 AND IFNULL(@auto_assign_queue_count,0)>0)
then 

	SET @curdatetime = replace(replace(replace(replace(current_timestamp(6),'-',''),':',''),' ','_'),'.','_');

	# SELECT id INTO @usertypeid from tms_user_type where title='agent';

	SET @sql1 = CONCAT('drop table if exists temp_assigned_to_',queueid,'_',@curdatetime,',temp_table_',queueid,'_',@curdatetime);

	PREPARE stmt2 FROM @sql1; 
	EXECUTE stmt2; 
	DEALLOCATE PREPARE stmt2;

	select assigntimegap,mailassignlimit INTO @assign_Time_Gap,@agent_Maillimit from tms_company_master;


	SET @sql1 = CONCAT('create table temp_assigned_to_',queueid,'_',@curdatetime,' select count(1) as total_count,assigned_to from tms_ticket_master_',queueid,' tick_mast join tms_queue_status_',queueid,' que_stats on tick_mast.status_id=que_stats.status_id where ifnull(que_stats.is_close_status,0)=0 AND tick_mast.is_deleted_ticket=0 and assigned_to>0 group by assigned_to');


	PREPARE stmt3 FROM @sql1; 
	EXECUTE stmt3; 
	DEALLOCATE PREPARE stmt3;

	SET @sql1 = CONCAT('update tms_user_master join temp_assigned_to_',queueid,'_',@curdatetime,' on user_id=assigned_to set ticket_assigned= total_count');


	PREPARE stmt4 FROM @sql1; 
	EXECUTE stmt4; 
	DEALLOCATE PREPARE stmt4;


	SET @sql1 = CONCAT('select ifnull(sum( ',IFNULL(@agent_Maillimit,0),'-ifnull(ticket_assigned,0)),0) 
										INTO @tickets_To_Assign 
						     from tms_user_master user_master
							  where user_master.auto_assign=1 and user_master.is_login = 1 and  COALESCE(break_state,0)!= 1
							  and ifnull(ticket_assigned,0) < ',@agent_Maillimit,' 
							  AND FIND_IN_SET("',queueid,'",user_master.queue_id)');
#SELECT @sql1;
	PREPARE stmt5 FROM @sql1; 
	EXECUTE stmt5; 
	DEALLOCATE PREPARE stmt5;




	SET @row_num=0;
	SET @sql1 = CONCAT('create table temp_table_',queueid,'_',@curdatetime,' select @row_num:=@row_num+1 SrNo,ticket_unique_id,ticket_id,assigned_to,is_assigned,a.queue_id
							FROM tms_ticket_master_',queueid,' a
							JOIN tms_queue_status_',queueid,' c ON a.status_id=c.status_id
							WHERE( (ifnull(assigned_to,0)=0 and ifnull(is_assigned,0)=1 )or (ifnull(assigned_to,0)=0 and ifnull(is_assigned,0)=0 )) and c.ticket_status_type=2
							and a.queue_id ="',queueid,'"
							
							ORDER BY created_date asc LIMIT ',if(ifnull(@tickets_To_Assign,0)<0,0,@tickets_To_Assign) );

	 #SELECT @sql1;
	PREPARE stmt6 FROM @sql1; 
	EXECUTE stmt6; 
	DEALLOCATE PREPARE stmt6;

	SET @sql1 = CONCAT('select count(1) into @total_count_tickets from temp_table_',queueid,'_',@curdatetime);

	PREPARE stmt7 FROM @sql1; 
	EXECUTE stmt7; 
	DEALLOCATE PREPARE stmt7;
	
	if(IFNULL(@total_count_tickets,0)>0) 
	then
		SET @startFlag = 1;

		WHILE(@startFlag <= ifnull(@total_count_tickets,0)) DO
	
		SET @sql1 = CONCAT('select queue_id,ticket_id into @D_Queue,@TId FROM temp_table_',queueid,'_',@curdatetime,' WHERE SrNo=',@startFlag);
	

		PREPARE stmt8 FROM @sql1; 
		EXECUTE stmt8; 
		DEALLOCATE PREPARE stmt8;
	
		SET @sql1 = CONCAT('select user_master.user_id,ifnull(ticket_assigned,0) INTO @u_id,@assign_tc
								from tms_user_master user_master
								left JOIN tms_shift_master shift_master on shift_master.id=user_master.shift_id
								where    
								 user_master.auto_assign=1 AND user_master.is_login=1 and  COALESCE(break_state,0)!= 1
								 AND FIND_IN_SET("',queueid,'",user_master.queue_id)
								 and ifnull(ticket_assigned,0) < ',@agent_Maillimit,'
								and  ifnull(TIMESTAMPDIFF(MINUTE,last_assign_time,NOW()),',@assign_Time_Gap,') >= ',@assign_Time_Gap,'
								AND CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 
								AND shift_master.id IS NOT NULL THEN NOW() ELSE CURDATE() END
									BETWEEN CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 AND shift_master.id IS NOT NULL 
									THEN CONCAT(CURDATE()," ",shift_master.time_from) ELSE CURDATE() END
									AND CASE WHEN "',IFNULL(@assign_shift_wise,0),'"=1 AND shift_master.Id IS NOT NULL 
									THEN DATE_ADD(CONCAT(CURDATE()," ",shift_master.time_to),INTERVAL -"',IFNULL(@before_assign_shift,0),'" MINUTE)
									 ELSE CURDATE() END
								
								ORDER BY ifnull(ticket_assigned,0) asc LIMIT 1');

		#SELECT @sql1;
		PREPARE stmt9 FROM @sql1; 
		EXECUTE stmt9; 
		DEALLOCATE PREPARE stmt9;




		UPDATE tms_user_master SET ticket_assigned=ifnull(ticket_assigned,0)+1 WHERE user_id=ifnull(@u_id,0);

		SET @sql1 = CONCAT('update temp_table_',queueid,'_',@curdatetime,' set assigned_to=',ifnull(@u_id,0),',is_assigned=1 WHERE SrNo=',@startFlag,' and ifnull(queue_id,0)=',ifnull(@D_Queue,0));


		PREPARE stmt10 FROM @sql1; 
		EXECUTE stmt10; 
		DEALLOCATE PREPARE stmt10;
	
		if(select 1 from tms_user_master where User_id=ifnull(@u_id,0) and ticket_assigned <= @agent_Maillimit LIMIT 1) = 1 then
			update tms_user_master SET  last_assign_time=NOW() WHERE user_id=ifnull(@u_id,0);
		END if;
			


		SET @startFlag = @startFlag + 1; 

	END WHILE;
	
	SET @sql1 = CONCAT('INSERT INTO user_assign_logs(queue_id,ticket_id,assigned_by,assigned_to,last_assigned)
							select queue_id,ticket_unique_id,0,assigned_to,is_assigned from temp_table_',queueid,'_',@curdatetime,' where ifnull(assigned_to,0)>0');


	PREPARE stmt11 FROM @sql1; 
	EXECUTE stmt11; 
	DEALLOCATE PREPARE stmt11;

	SET @sql1 = CONCAT('update tms_ticket_master_',queueid,' a join temp_table_',queueid,'_',@curdatetime,' b on a.ticket_id = b.ticket_id
							set a.assigned_to=b.assigned_to,a.is_assigned=b.is_assigned,
							a.assigned_on=(CASE WHEN b.assigned_to IS NULL or b.assigned_to = 0 THEN NULL ELSE NOW() END)');


	PREPARE stmt12 FROM @sql1; 
	EXECUTE stmt12; 
	DEALLOCATE PREPARE stmt12;

/*	SET @sql1 = CONCAT('update tms_unreadconversationcount_',queueid,' a JOIN  temp_table_',queueid,'_',@curdatetime,' b ON a.ticket_unique_id=b.ticket_unique_id
							SET user_id=b.assigned_to');



	PREPARE stmt13 FROM @sql1; 
	EXECUTE stmt13; 
	DEALLOCATE PREPARE stmt13;
*/
	SET @sql1 = CONCAT('select temp_ticket.ticket_unique_id,temp_ticket.queue_id,temp_ticket.assigned_to from temp_table_',queueid,'_',@curdatetime,' temp_ticket join tms_ticket_master_',queueid,' ticket_master on ticket_master.ticket_unique_id=temp_ticket.ticket_unique_id where temp_ticket.is_assigned=1');


	PREPARE stmt14 FROM @sql1; 
	EXECUTE stmt14; 
	DEALLOCATE PREPARE stmt14;
ELSE
		SELECT "" ticket_unique_id,"" queue_id,"" assigned_to LIMIT 0;
	
END if;

	SET @sql1 = CONCAT('drop table if exists temp_assigned_to_',queueid,'_',@curdatetime,',temp_table_',queueid,'_',@curdatetime);

	PREPARE stmt15 FROM @sql1; 
	EXECUTE stmt15; 
	DEALLOCATE PREPARE stmt15;

ELSE

SELECT "" ticket_unique_id,"" queue_id,"" assigned_to LIMIT 0;


END if;


	COMMIT;
END

**


CREATE TABLE IF NOT EXISTS `break_logs` (
  `id` int NOT NULL AUTO_INCREMENT,
  `user_id` int NOT NULL DEFAULT '0',
  `break_id` int DEFAULT NULL,
  `break_name` varchar(100) NOT NULL DEFAULT '0',
  `break_time` varchar(100) NOT NULL DEFAULT '0',
  `break_started_on` datetime DEFAULT CURRENT_TIMESTAMP,
  `break_end_on` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `bulk_escalation_data_1` (
  `id` int NOT NULL AUTO_INCREMENT,
  `email_status` varchar(50) DEFAULT NULL,
  `from_email` text,
  `to_emails` text,
  `subject` text,
  `conversation` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;

**

CREATE TABLE IF NOT EXISTS `comp_import_master` (
  `log_id` int NOT NULL AUTO_INCREMENT,
  `queue_id` int NOT NULL DEFAULT '0',
  `import_type` varchar(50) DEFAULT NULL,
  `document_path` varchar(500) DEFAULT NULL,
  `doc_name` varchar(500) DEFAULT NULL,
  `error_file` varchar(500) DEFAULT NULL,
  `status` int NOT NULL DEFAULT '1' COMMENT '1 file uploaded,\n	 2 failed,\n	 3 terminated ,\n	 4 success',
  `remarks` text,
  `cr_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `md_date` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `process_status` tinyint NOT NULL DEFAULT '1' COMMENT '1 file uploded 2  file start processing 3 processing completed',
  `processing_start_time` datetime DEFAULT NULL,
  `processing_end_time` datetime DEFAULT NULL,
  PRIMARY KEY (`log_id`)
) ENGINE=InnoDB AUTO_INCREMENT=224 DEFAULT CHARSET=latin1;

**
CREATE FUNCTION `comp_testfun`() RETURNS varchar(20) CHARSET latin1
    DETERMINISTIC
BEGIN
  DECLARE abc VARCHAR(20);  
  SET abc ='222';
  RETURN(abc);
END

**
CREATE TABLE IF NOT EXISTS `comp_testing` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `mobile` varchar(10) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `demo` varchar(50) DEFAULT NULL,
  `demo1` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**
CREATE TABLE IF NOT EXISTS `comp_testing_1` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `mobile` varchar(10) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `demo` varchar(50) DEFAULT NULL,
  `demo1` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `comp_testing_2` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `mobile` varchar(10) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `demo` varchar(50) DEFAULT NULL,
  `demo1` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**

CREATE PROCEDURE `copyQueue`(
	IN `from_queue_id` INT,
	IN `to_queue_id` INT
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN		
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
    SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
		
        ROLLBACK;   
    END; 
START TRANSACTION;

SET @query1 = CONCAT('insert into tms_dynamicform_fields_',to_queue_id,' select * from tms_dynamicform_fields_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_queue_category_',to_queue_id,' select * from tms_queue_category_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_queue_priority_',to_queue_id,' select * from tms_queue_priority_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_queue_rule_action_',to_queue_id,' select * from tms_queue_rule_action_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_queue_rule_condition_',to_queue_id,' select * from tms_queue_rule_condition_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_queue_rule_master_',to_queue_id,' select * from tms_queue_rule_master_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_queue_status_',to_queue_id,' select * from tms_queue_status_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_queue_template_',to_queue_id,' select * from tms_queue_template_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_queue_escalationmatrix_',to_queue_id,' select * from tms_queue_escalationmatrix_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_statuspermission_',to_queue_id,' select * from tms_statuspermission_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_queue_assign_rule_action_',to_queue_id,' select * from tms_queue_assign_rule_action_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_queue_assign_rule_condition_',to_queue_id,' select * from tms_queue_assign_rule_condition_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('insert into tms_queue_assign_rule_master_',to_queue_id,' select * from tms_queue_assign_rule_master_',from_queue_id);

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;

SET @query1 = CONCAT('SELECT CONCAT("ALTER TABLE tms_ticket_master_',to_queue_id,'", GROUP_CONCAT(" ADD COLUMN ", inf.COLUMN_NAME," ",inf.COLUMN_TYPE)) COLUMN_NAME 
INTO @alterquery
FROM information_schema.`COLUMNS` inf JOIN tms_dynamicform_fields_',from_queue_id,' dyn ON inf.COLUMN_NAME=dyn.field_name
WHERE  table_schema=DATABASE() and TABLE_NAME="tms_ticket_master_',from_queue_id,'";');

PREPARE stmt1 FROM @query1; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1;


if IFNULL(@alterquery,'')!='' then
	PREPARE stmt1 FROM @alterquery; 
	EXECUTE stmt1; 
	DEALLOCATE PREPARE stmt1;
END if;

SELECT 'success' result;
COMMIT;

END
**

CREATE PROCEDURE `Custom_Agent_report`(
	IN `fromDate` VARCHAR(50),
	IN `toDate` VARCHAR(50),
	IN `user_id` VARCHAR(100),
	IN `queue_id` INT,
	IN `fullcontrol` INT,
	IN `limit_offset` VARCHAR(30)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
   BEGIN
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
       SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
   
        ROLLBACK;   
   END; 
   START TRANSACTION;

 SET SESSION group_concat_max_len = 10000000;
 SET @user_id=user_id;
 
SET @sql = CONCAT('SELECT group_concat(DISTINCT status_id) INTO @status_ids
FROM tms_user_master tum JOIN tms_statuspermission_',queue_id,' tsp ON tum.user_type=tsp.user_type
WHERE tsp.is_checked=1 
',if( IFNULL(user_id,"")!="",CONCAT(' and tum.user_id in (',user_id,')'),""),' ');

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;
 
 
    SET @col1 = CONCAT('SELECT GROUP_CONCAT(CONCAT("SUM(CASE WHEN IFNULL(tqs.status_name, """") = ''",status_name,"'' THEN 1 ELSE 0 END) AS ''",status_name,"''"))  
    into @exactcol1
    FROM tms_queue_status_',queue_id,' tqs  where 1=1 ',if( IFNULL(fullcontrol,0)=0,CONCAT('and  tqs.status_id in (',@status_ids,')'),""),' ORDER BY order_no ASC');
    
    PREPARE stmtcol1 FROM @col1;
    EXECUTE stmtcol1;
    DEALLOCATE PREPARE stmtcol1; 
     
    SET @sqlquery = CONCAT('select * from(SELECT  
	  tum.user_name as "User Name" , tum.user_id as user_id  , COUNT(1) AS TotalTicket,
    SUM(CASE WHEN tqs.ticket_status_type=1 THEN 1 ELSE 0 END) Final,
    SUM(CASE WHEN tqs.ticket_status_type!=1 THEN 1 ELSE 0 END) Non_Final, 
	 ',if(IFNULL(@exactcol1,'')='','',CONCAT(@exactcol1,'')), '    
    FROM tms_ticket_master_',queue_id,' AS ttm 
    LEFT JOIN tms_user_master tum ON tum.user_id = ttm.assigned_to   
    LEFT JOIN (SELECT MAX(conversation_id) AS Last_conversation_id, ticket_unique_id FROM tms_conversation_master_',queue_id,' tcm GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = ttm.ticket_unique_id 
    LEFT JOIN tms_conversation_master_',queue_id,' tcm ON tcm.conversation_id = Last_con.Last_conversation_id  	   
    LEFT JOIN tms_queue_escalationmatrix_',queue_id,' tqe ON tqe.priority_id =ifnull(ttm.priority_id,3) AND (TIMESTAMPDIFF(SECOND, ttm.created_date, tcm.conversation_date) / 3600) = hours AND ((TIMESTAMPDIFF(SECOND, ttm.created_date, tcm.conversation_date) % 3600) / 60) >= minute   
    LEFT JOIN tms_queue_priority_',queue_id,' tqp ON ttm.priority_id = tqp.priority_id 
    LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id 
     where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 and IFNULL(ttm.is_draft,0) = 0   
	  ',if( IFNULL(user_id,"")!="",CONCAT(' and tum.user_id in (',user_id,')'),""),'
	   AND ttm.last_updated_on>="',fromDate,'" and ttm.last_updated_on<="',toDate,'" 
    GROUP BY tum.user_name,tum.user_id
    UNION ALL
    SELECT  
	  "Grand Total" as "User Name" , "" as user_id  , COUNT(1) AS TotalTicket,
    SUM(CASE WHEN tqs.ticket_status_type=1 THEN 1 ELSE 0 END) Final,
    SUM(CASE WHEN tqs.ticket_status_type!=1 THEN 1 ELSE 0 END) Non_Final, 
	 ',if(IFNULL(@exactcol1,'')='','',CONCAT(@exactcol1,'')), '    
    FROM tms_ticket_master_',queue_id,' AS ttm 
    LEFT JOIN tms_user_master tum ON tum.user_id = ttm.assigned_to   
    LEFT JOIN (SELECT MAX(conversation_id) AS Last_conversation_id, ticket_unique_id FROM tms_conversation_master_',queue_id,' tcm GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = ttm.ticket_unique_id 
    LEFT JOIN tms_conversation_master_',queue_id,' tcm ON tcm.conversation_id = Last_con.Last_conversation_id  	   
    LEFT JOIN tms_queue_escalationmatrix_',queue_id,' tqe ON tqe.priority_id =ifnull(ttm.priority_id,3) AND (TIMESTAMPDIFF(SECOND, ttm.created_date, tcm.conversation_date) / 3600) = hours AND ((TIMESTAMPDIFF(SECOND, ttm.created_date, tcm.conversation_date) % 3600) / 60) >= minute   
    LEFT JOIN tms_queue_priority_',queue_id,' tqp ON ttm.priority_id = tqp.priority_id 
    LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id 
     where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 and IFNULL(ttm.is_draft,0) = 0   
	  ',if( IFNULL(user_id,"")!="",CONCAT(' and tum.user_id in (',user_id,')'),""),'
	   AND ttm.last_updated_on>="',fromDate,'" and ttm.last_updated_on<="',toDate,'" 
    )t
    order by case when `User Name`="Grand Total" then 1 else 0 end,`User Name`
	 ',if(IFNULL(limit_offset,"")!="",CONCAT(' LIMIT ', limit_offset),""),'');

  #SELECT @sqlquery;
PREPARE stmt FROM @sqlquery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
COMMIT;
END
**
CREATE PROCEDURE `custom_procedure`(
	IN `ticket_id` VARCHAR(50),
	IN `queue_id` INT,
	IN `start_date` DATETIME,
	IN `end_date` DATETIME,
	IN `pagination` VARCHAR(20)
)
BEGIN
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SET SESSION group_concat_max_len = 1000000; 

SET @SQL=CONCAT('SELECT concat(",",group_concat(concat("t1.",field_name))) into @dynamicSelect FROM tms_dynamicform_fields_',queue_id,' ');

PREPARE stmt FROM @SQL; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;

 SET @COLUMNS=CONCAT('SELECT t1.ticket_prefix,t1.is_draft, t1.ticket_unique_id, t1.ticket_id, t1.person_name,
t1.mobile_no, t1.unique_id, t1.parent_id, t1.subject, t1.start_date, t1.cc_email, t1.bcc_email, t1.start_mode, t1.status_id, t1.priority_id, t1.queue_id,
DATE_FORMAT(t1.last_updated_on,"%d-%m-%Y %H:%i:%s") last_updated_on, t1.is_read, t1.read_by, t1.read_date, 
DATE_FORMAT(t1.mail_date,"%d-%m-%Y %H:%i:%s") mail_date, t1.is_assigned, t4.user_name as assigned_to, t1.assigned_by, 
DATE_FORMAT(t1.assigned_on,"%d-%m-%Y %H:%i:%s") assigned_on,
t1.last_updated_by, t1.phone_no, t1.category_id, t1.subcategory_id, t1.follow_up_date, t1.ticket_created_by, t1.is_assigned_open_ticket, t1.remarks,
t1.is_replied_mail, t1.is_forward_mail, 
DATE_FORMAT(t1.created_date,"%d-%m-%Y %H:%i:%s") AS created_date, 
CASE  WHEN TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) >= 24 THEN case when length(FLOOR(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) / 24))<=1 then CONCAT("0",FLOOR(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) / 24), " days") else CONCAT(FLOOR(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) / 24), " days") end ELSE 
CONCAT(LPAD(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()), 2, "0"), ":", LPAD(MOD(TIMESTAMPDIFF(MINUTE, t1.created_date, NOW()), 60), 2, "0"), ":", 
LPAD(MOD(TIMESTAMPDIFF(SECOND, t1.created_date, NOW()), 60), 2, "0") )  END AS duration,
t1.happy_code, t1.escalation_id, t1.last_escalation_on, t1.hold_date, t1.incoming_mail_id,
t1.is_new,t1.parent_ticket_id, t1.parent_ticket_id_text, t1.is_junk, t1.is_deleted_ticket, t1.is_closed,t1.is_auto, t1.deleted_date,
if(t4.user_name is not null,ifnull(tumby.user_name,"Auto"),"") as assigned_by_with_name,
IF(0=1,mask_email(t1.to_email,"*"),t1.to_email) AS to_email,IF(0=1,mask_email(t1.from_email,"*"),t1.from_email) AS from_email,
t2.priority_name, t2.colour_code as prClr, t3.status_name,
t3.colour_code as stClr,t3.is_close_status,
concat(SUBSTRING_INDEX(Case when IFNULL(t3.is_close_status, "0") = 1
then TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),tcm.conversation_date) 
else TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),now()) end/ 86400,".",1)
,''d '',
sec_to_time(Case when IFNULL(t3.is_close_status, "0") = 1 
then TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),tcm.conversation_date) 
else TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),now()) end % 86400)) AS TAT,
concat(SUBSTRING_INDEX(Case when IFNULL(t3.is_close_status, "0") = 1
then case when TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),tcm.conversation_date)>t2.tat*60*60
 then (TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),tcm.conversation_date)-t2.tat*60*60) else 0 end
else case when TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),now())>t2.tat*60*60
then (TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),now())-t2.tat*60*60) else 0 end
 end/ 86400,".",1)
,''d '',
sec_to_time(Case when IFNULL(t3.is_close_status, "0") = 1 
then case when TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),tcm.conversation_date)>t2.tat*60*60
 then (TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),tcm.conversation_date)-t2.tat*60*60) else 0 end
else case when TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),now())>t2.tat*60*60
then (TIMESTAMPDIFF(second,IFNULL(t1.assigned_on, NOW()),now())-t2.tat*60*60) else 0 end end % 86400)) Overdue_TAT,
tms_queue_category_',queue_id,'.category_name as Category,tms_queue_sub_category_',queue_id,'.sub_category_name as Subcategory
  ',IFNULL(@dynamicSelect, ''));
 
SET @table = CONCAT('FROM tms_ticket_master_',queue_id,' as t1
LEFT JOIN tms_queue_priority_',queue_id,' as t2 ON t1.priority_id = t2.priority_id
LEFT JOIN tms_queue_status_',queue_id,' as t3 ON t1.status_id = t3.status_id
LEFT JOIN tms_user_master as t4 ON t1.assigned_to = t4.id
LEFT JOIN tms_user_master as tumby ON t1.assigned_by = tumby.user_id
left join tms_queue_category_',queue_id,' on t1.category_id = tms_queue_category_',queue_id,'.category_id
left join tms_queue_sub_category_',queue_id,' on t1.subcategory_id = tms_queue_sub_category_',queue_id,'.sub_category_id
LEFT JOIN (SELECT MAX(conversation_id) AS conversation_ids, 
 tcm.ticket_unique_id
FROM tms_conversation_master_',queue_id,' as tcm
join tms_ticket_master_',queue_id,' as t1 ON tcm.ticket_unique_id = t1.ticket_unique_id
',if(IFNULL(start_date,"")!="" AND IFNULL(end_date,"")!="",CONCAT(' where 1=1 AND t1.created_date >="',start_date,'" AND t1.created_date <="',end_date,'"'),""),'
GROUP BY tcm.ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = t1.ticket_unique_id
LEFT JOIN tms_conversation_master_',queue_id,' as tcm ON Last_con.conversation_ids=tcm.conversation_id
');

SET @WHERE = CONCAT(' ',if(IFNULL(start_date,"")!="" AND IFNULL(end_date,"")!="",CONCAT(' where 1=1 AND t1.created_date >="',start_date,'" AND t1.created_date <="',end_date,'"'),""),'');



SET @GROUP = ' GROUP BY t1.ticket_unique_id,conversation_type,tumby.user_name,tcm.conversation_date
ORDER BY is_new desc';

If (ifnull(pagination,"")!="" ) then 

SET @GROUP=CONCAT(@GROUP,' limit ',pagination,'');
END if;

SET @query_string = CONCAT(@COLUMNS, " ", @table, " ", @where, " ", @GROUP);
#SELECT @query_string;
PREPARE stmt FROM @query_string;
EXECUTE stmt;   
DEALLOCATE PREPARE stmt;

SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**


CREATE TABLE IF NOT EXISTS `custom_query_report_columns` (
  `id` int NOT NULL AUTO_INCREMENT,
  `report_id` int DEFAULT NULL,
  `srno` int DEFAULT '1',
  `field_name` varchar(100) DEFAULT NULL,
  `function_name` varchar(100) DEFAULT NULL,
  `order_by_type` varchar(50) DEFAULT NULL,
  `filed_formula` varchar(1000) DEFAULT NULL,
  `display_name` varchar(100) DEFAULT NULL,
  `criteria` varchar(250) DEFAULT NULL,
  `is_visible` tinyint DEFAULT '1',
  `aggrigate_fn` varchar(100) DEFAULT NULL,
  `group_by_type` tinyint DEFAULT '0',
  `is_link` tinyint DEFAULT '0',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=249 DEFAULT CHARSET=latin1;

**
INSERT INTO `custom_query_report_columns` (`id`, `report_id`, `srno`, `field_name`, `function_name`, `order_by_type`, `filed_formula`, `display_name`, `criteria`, `is_visible`, `aggrigate_fn`, `group_by_type`, `is_link`) VALUES
	(217, 3, 1, 'tms_ticket_master_1.ticket_id', NULL, 'asc', '', 'Ticket ID', '', 0, '', 0, 0),
	(218, 3, 1, 'tms_ticket_master_1.mobile_no', NULL, 'asc', '', 'Mobile Number', '', 0, '', 0, 0),
	(219, 3, 1, 'tms_ticket_master_1.to_email', NULL, 'asc', '', 'TO Email', '', 0, '', 0, 0),
	(220, 3, 1, 'tms_ticket_master_1.cc_email', NULL, '', '', 'CC Email', '', 0, '', 0, 0),
	(221, 3, 1, 'tms_ticket_master_1.assigned_by', NULL, 'asc', '', 'Assigned By ', '', 0, '', 0, 0),
	(222, 3, 1, 'tms_ticket_master_1.assigned_on', NULL, '', '', 'Assign On', '', 0, '', 0, 0),
	(223, 3, 1, 'tms_user_master.name', NULL, 'asc', '', 'User Name', '', 0, '', 0, 0),
	(236, 5, 1, 'tms_ticket_master_1.ticket_id', NULL, NULL, '', 'Ticket Count', '', 1, 'count', 0, 0),
	(237, 5, 1, 'tms_ticket_master_1.person_name', NULL, 'asc', '', 'Agent', '!= ""', 1, '', 1, 0),
	(238, 6, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0),
	(239, 4, 1, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL, 0),
	(248, 7, 1, '', NULL, '', '', '', '', 1, '', 0, 0);

**
CREATE TABLE IF NOT EXISTS `custom_query_search_fields` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `report_id` int DEFAULT NULL,
  `srno` int DEFAULT '1',
  `search_field_name` varchar(100) DEFAULT NULL,
  `display_name` varchar(100) DEFAULT NULL,
  `default_value` varchar(100) DEFAULT NULL,
  `allow_null` tinyint DEFAULT '1',
  `drowdown_other_db` tinyint DEFAULT NULL,
  `input_type` text,
  `select_box_value` varchar(1250) DEFAULT NULL,
  `default_operator` varchar(50) DEFAULT NULL,
  `parameter` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=240 DEFAULT CHARSET=latin1;

**
INSERT INTO `custom_query_search_fields` (`id`, `report_id`, `srno`, `search_field_name`, `display_name`, `default_value`, `allow_null`, `drowdown_other_db`, `input_type`, `select_box_value`, `default_operator`, `parameter`) VALUES
	(192, 3, 1, 'tms_ticket_master_1.ticket_id', 'Ticket ID', '', 1, 0, 'text', '', '=', ''),
	(193, 3, 2, 'tms_ticket_master_1.mobile_no', 'Mobile Number', '', 1, 0, 'text', '', '=', ''),
	(200, 5, 1, 'tms_ticket_master_1.ticket_id', 'Ticket ID', NULL, 1, 0, 'text', NULL, '=', NULL),
	(201, 6, 1, NULL, '', NULL, 0, 0, NULL, NULL, NULL, NULL),
	(202, 4, 1, NULL, 'From Date', NULL, 0, 0, 'datetime', NULL, '>=', '@fromdate'),
	(203, 4, 2, '', 'To Date', '', 0, 1, 'datetime', '', '<=', '@todate'),
	(204, 4, 3, '', 'Ticket ID', '', 1, 0, 'text', '', '=', '@ticket_id'),
	(205, 4, 4, '', 'Queue Name', '', 0, 1, 'dropdown', 'select id,queue as  options from tms_queue_master', '=', '@queue_id'),
	(206, 4, 5, '', 'status', 'Active', 1, 0, 'dropdown', 'Active,Inactive', '', '@status'),
	(236, 7, 1, '', 'From Date', '', 0, 0, 'datetime', '', '', '@fromdate'),
	(237, 7, 2, '', 'To Date', '', 0, 0, 'datetime', '', '', '@todate'),
	(238, 7, 3, '', 'Queue Name', '', 0, 1, 'dropdown', 'select id,queue as  options from tms_queue_master @adduserwisequeue', '', '@queue_id'),
	(239, 7, 4, '', 'Agent', '', 0, 1, 'multiselect', 'select id,queue as  options from tms_queue_master', '', '@agent');

**
CREATE TABLE IF NOT EXISTS `custom_query_tables` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `report_id` int DEFAULT NULL,
  `srno` int DEFAULT '1',
  `left_table_name` varchar(50) DEFAULT NULL,
  `join_name` varchar(10) DEFAULT NULL,
  `left_column_name` varchar(50) DEFAULT NULL,
  `right_table_name` varchar(50) DEFAULT NULL,
  `right_column_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=148 DEFAULT CHARSET=latin1;

**
INSERT INTO `custom_query_tables` (`id`, `report_id`, `srno`, `left_table_name`, `join_name`, `left_column_name`, `right_table_name`, `right_column_name`) VALUES
	(128, 3, 1, 'tms_ticket_master_1', 'Left', 'is_assigned', 'tms_user_master', 'user_id'),
	(129, 3, 2, 'tms_ticket_master_1', 'Left', 'ticket_id', 'tms_conversation_attachements_1', 'ticket_id'),
	(136, 5, 1, 'tms_ticket_master_1', 'Left', 'ticket_id', 'tms_conversation_attachements_1', 'ticket_id'),
	(137, 6, 1, 'tms_ticket_master_1', 'Left', 'assigned_to', 'tms_user_master', 'user_id'),
	(138, 4, 1, NULL, NULL, NULL, NULL, NULL),
	(147, 7, 1, '', '', '', '', '');

**
CREATE TABLE IF NOT EXISTS `custom_report` (
  `id` int NOT NULL AUTO_INCREMENT,
  `report_name` varchar(100) DEFAULT '0',
  `allow_export_to_excel` tinyint DEFAULT '0',
  `custom_query` tinyint DEFAULT '0',
  `report_query` varchar(25000) DEFAULT '',
  `report_query_f` varchar(25000) DEFAULT '',
  `status` tinyint DEFAULT '0',
  `queue_id` int DEFAULT NULL,
  `cr_usr` int DEFAULT NULL,
  `cr_date` datetime DEFAULT NULL,
  `md_usr` int DEFAULT NULL,
  `md_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;

**
INSERT INTO `custom_report` (`id`, `report_name`, `allow_export_to_excel`, `custom_query`, `report_query`, `report_query_f`, `status`, `queue_id`, `cr_usr`, `cr_date`, `md_usr`, `md_date`) VALUES
	(3, 'ticket report', 1, 0, 'select * from tms_ticket_master_1 Left join tms_user_master ON tms_ticket_master_1.is_assigned = tms_user_master.user_id Left join tms_conversation_attachements_1 ON tms_ticket_master_1.ticket_id = tms_conversation_attachements_1.ticket_id where 1=1 order by tms_ticket_master_1.ticket_id asc,tms_ticket_master_1.mobile_no asc,tms_ticket_master_1.to_email asc,tms_ticket_master_1.assigned_by asc,tms_user_master.name asc', '<br/>&nbsp;<b>SELECT</b>&nbsp;*&nbsp;<br/>&nbsp;<b>FROM</b>&nbsp;tms_ticket_master_1&nbsp;<br/>&nbsp;<b>LEFT</b>&nbsp;<b>JOIN</b>&nbsp;tms_user_master&nbsp;ON&nbsp;tms_ticket_master_1.is_assigned&nbsp;=&nbsp;tms_user_master.user_id&nbsp;<br/>&nbsp;<b>LEFT</b>&nbsp;<b>JOIN</b>&nbsp;tms_conversation_attachements_1&nbsp;ON&nbsp;tms_ticket_master_1.ticket_id&nbsp;=&nbsp;tms_conversation_attachements_1.ticket_id&nbsp;<br/>&nbsp;<b>WHERE</b>&nbsp;1=1&nbsp;<br/>&nbsp;<b>ORDER</b>&nbsp;<b>BY</b>&nbsp;tms_ticket_master_1.ticket_id&nbsp;asc,tms_ticket_master_1.mobile_no&nbsp;asc,tms_ticket_master_1.to_email&nbsp;asc,tms_ticket_master_1.assigned_by&nbsp;asc,tms_user_master.name&nbsp;asc', 1, NULL, NULL, '2025-03-19 09:58:16', NULL, '2025-03-24 12:05:24'),
	(4, 'custom procedure  q', 1, 1, 'call custom_procedure (@ticket_id,@queue_id,@fromdate,@todate,@rowlimit)', 'call&nbsp;custom_procedure&nbsp;(&nbsp;@ticket_id,@queue_id,@fromdate,@todate,@rowlimit)&nbsp;', 1, NULL, NULL, '2025-03-21 10:04:24', NULL, '2025-03-27 11:53:32'),
	(5, 'test ', 1, 0, 'select count(tms_ticket_master_1.ticket_id) as \'Ticket Count\',tms_ticket_master_1.person_name as \'Agent\' from tms_ticket_master_1 Left join tms_conversation_attachements_1 ON tms_ticket_master_1.ticket_id = tms_conversation_attachements_1.ticket_id where 1=1 and tms_ticket_master_1.person_name != \'\' group by tms_ticket_master_1.person_name order by tms_ticket_master_1.person_name asc', '<br/>&nbsp;<b>SELECT</b>&nbsp;count(&nbsp;tms_ticket_master_1.ticket_id)&nbsp;&nbsp;as&nbsp;\'Ticket&nbsp;Count\',tms_ticket_master_1.person_name&nbsp;as&nbsp;\'Agent\'&nbsp;<br/>&nbsp;<b>FROM</b>&nbsp;tms_ticket_master_1&nbsp;<br/>&nbsp;<b>LEFT</b>&nbsp;<b>JOIN</b>&nbsp;tms_conversation_attachements_1&nbsp;ON&nbsp;tms_ticket_master_1.ticket_id&nbsp;=&nbsp;tms_conversation_attachements_1.ticket_id&nbsp;<br/>&nbsp;<b>WHERE</b>&nbsp;1=1&nbsp;<br/>&nbsp;<b>AND</b>&nbsp;tms_ticket_master_1.person_name&nbsp;!=&nbsp;\'\'&nbsp;<br/>&nbsp;<b>GROUP</b>&nbsp;<b>BY</b>&nbsp;tms_ticket_master_1.person_name&nbsp;<br/>&nbsp;<b>ORDER</b>&nbsp;<b>BY</b>&nbsp;tms_ticket_master_1.person_name&nbsp;asc', 1, NULL, NULL, '2025-03-22 14:21:19', NULL, '2025-03-24 17:17:59'),
	(6, 'sagar', 1, NULL, 'select * from tms_ticket_master_1 Left join tms_user_master ON tms_ticket_master_1.assigned_to = tms_user_master.user_id where 1=1', '<br/>&nbsp;<b>SELECT</b>&nbsp;*&nbsp;<br/>&nbsp;<b>FROM</b>&nbsp;tms_ticket_master_1&nbsp;<br/>&nbsp;<b>LEFT</b>&nbsp;<b>JOIN</b>&nbsp;tms_user_master&nbsp;ON&nbsp;tms_ticket_master_1.assigned_to&nbsp;=&nbsp;tms_user_master.user_id&nbsp;<br/>&nbsp;<b>WHERE</b>&nbsp;1=1', 1, NULL, NULL, '2025-03-27 11:00:23', NULL, NULL),
	(7, 'Custom Agent Report', 1, 1, 'call Custom_Agent_report(@fromdate,@todate, \'\',  @queue_id, \'1\',@rowlimit)', 'call&nbsp;Custom_Agent_report(&nbsp;@fromdate,@todate,&nbsp;\'\',&nbsp;&nbsp;@queue_id,&nbsp;\'1\',@rowlimit)&nbsp;', 1, NULL, NULL, '2025-04-18 12:19:55', NULL, '2025-04-22 14:29:35');

**
CREATE TABLE IF NOT EXISTS `custom_report_search_table__notuse` (
  `general_id` int NOT NULL AUTO_INCREMENT,
  `report_id` int DEFAULT NULL,
  `first_table_name` text,
  `first_column_name` text,
  `table_join` text,
  `second_table_name` text,
  `second_column_name` text,
  PRIMARY KEY (`general_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1 COMMENT='custom_query_tables';

**
INSERT INTO `custom_report_search_table__notuse` (`general_id`, `report_id`, `first_table_name`, `first_column_name`, `table_join`, `second_table_name`, `second_column_name`) VALUES
	(1, 1, 'Password_logs', 'password_used', 'Inner', 'Password_logs', 'password_used'),
	(2, 2, 'Password_logs', 'password_used', 'Inner', 'Password_logs', 'password_used'),
	(3, 2, 'break_logs', 'break_id', 'Inner', 'break_logs', 'break_id'),
	(4, 3, 'Password_logs', 'password_used', 'Inner', 'Password_logs', 'password_used'),
	(5, 4, 'Password_logs', 'password_used', 'Inner', 'Password_logs', 'password_used'),
	(6, 5, '', '', '', '', ''),
	(7, 6, '', '', '', '', ''),
	(8, 7, '', '', '', '', ''),
	(9, 8, '', '', '', '', ''),
	(10, 9, '', '', '', '', ''),
	(11, 10, '', '', '', '', ''),
	(12, 11, 'Password_logs', 'user_id', 'Left', 'acc_theme_master', 'is_default'),
	(13, 12, '', '', '', '', ''),
	(14, 13, 'Password_logs', 'user_id', 'Left', 'Password_logs', 'user_id'),
	(15, 14, '', '', '', '', ''),
	(16, 15, NULL, NULL, NULL, NULL, NULL),
	(17, 16, NULL, NULL, NULL, NULL, NULL);

**
CREATE PROCEDURE `emailEscalation`(
	IN `queueid` INT
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN		
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
    SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
    
      SET @SQL1 = CONCAT('drop table if exists temp_escalation_matrix_',@curdatetime,',temp_matrix_',@curdatetime);
      #SELECT @sql1;
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
        ROLLBACK;   
    END; 
START TRANSACTION;

SET @curdatetime = replace(replace(replace(replace(current_timestamp(6),'-',''),':',''),' ','_'),'.','_');

SET @sql1 = CONCAT('drop table if exists temp_escalation_matrix_',@curdatetime,',temp_matrix_',@curdatetime);
#SELECT @sql1;
PREPARE stmtcdrSQL FROM @sql1; 
EXECUTE stmtcdrSQL; 
DEALLOCATE PREPARE stmtcdrSQL;

SET @close_status_id = 0;
SET @cur_time = NOW();

SET @sql1 = CONCAT('
create table temp_escalation_matrix_',@curdatetime,' as
SELECT a.category_id,a.cat_email,
(CASE WHEN days=0 THEN 0 ELSE 1440*days END+CASE WHEN hours=0 THEN 0 ELSE 60*hours END+
CASE WHEN minute=0 THEN 0 ELSE minute END) minute,a.emails,level escalation_level,a.priority_id,',queueid,' queue_id,escalation_id,shift_id,template_id,mobile_no,a.send_email_agent,a.agent_template_id,send_email,send_sms,b.dont_read_mail_before
		from tms_queue_escalationmatrix_',queueid,' a JOIN tms_queue_master b ON ',queueid,'=b.id
		WHERE ifnull(a.active,0)=1 AND ifnull(b.status,0)=1 AND ifnull(b.escalation,0)=1');
#SELECT @sql1;
PREPARE stmtcdrSQL FROM @sql1; 
EXECUTE stmtcdrSQL; 
DEALLOCATE PREPARE stmtcdrSQL;

SET @sql1 = CONCAT('SELECT group_concat(status_id) INTO @close_status_id FROM tms_queue_status_',queueid,' WHERE ifnull(is_close_status,0)=1');
#SELECT @sql1;
PREPARE stmtcdrSQL FROM @sql1; 
EXECUTE stmtcdrSQL; 
DEALLOCATE PREPARE stmtcdrSQL;

SET @sql1 = CONCAT('SELECT GROUP_CONCAT(field_name) into @master_fields FROM tms_dynamicform_fields_',queueid);
#SELECT @sql1;
PREPARE stmtcdrSQL FROM @sql1; 
EXECUTE stmtcdrSQL; 
DEALLOCATE PREPARE stmtcdrSQL;

SET @sql1 = CONCAT('create table temp_matrix_',@curdatetime,' as
SELECT IF(b.escalation_level=@_last_esc_level,@curRank:=@curRank,@curRank:=@_sequence) rowno,b.escalation_level,ticket_unique_id,last_updated_on,a.created_date,d.user_name,d.email as agent_email, happy_code,b.mobile_no mobile_send_sms,e.email account_email_id,b.priority_id,a.status_id,
ticket_id,a.subject,c.user_email_subject,c.user_email_template,c.user_sms_template,b.emails,a.mobile_no,person_name,from_email,to_email,cc_email,e.id emailaccount_id,a.queue_id,b.send_email,b.send_sms',if(IFNULL(@master_fields,'')!='',CONCAT(',',@master_fields),''),',
d.signature,b.send_email_agent,b.agent_template_id,tqt.user_email_subject as `agent_email_subject`,tqt.user_email_template as `agent_email_template`,tq.status_name,b.category_id,b.cat_email,a.category_id ticket_category_id
FROM tms_ticket_master_',queueid,' a JOIN temp_escalation_matrix_',@curdatetime,' b on a.queue_id=b.queue_id AND (b.escalation_level>ifnull(a.escalation_id,0)) AND a.priority_id=b.priority_id
AND "',@cur_time,'">DATE_ADD(CASE WHEN a.last_escalation_on IS NULL THEN a.last_updated_on WHEN a.last_escalation_on>a.last_updated_on THEN a.last_escalation_on ELSE a.last_updated_on END, INTERVAL b.minute MINUTE)  
JOIN tms_queue_template_',queueid,' c ON c.template_id=b.template_id 
left join tms_queue_status_',queueid,' tq ON tq.status_id = a.status_id
left JOIN tms_queue_template_',queueid,' tqt ON tqt.template_id=b.agent_template_id 
JOIN tms_user_master d ON d.user_id=a.assigned_to AND ifnull(d.shift_id,0)=CASE WHEN ifnull(b.shift_id,0)=0 THEN ifnull(d.shift_id,0) ELSE b.shift_id END
left JOIN tms_email_account e ON e.email=a.incoming_mail_id,(SELECT @curRank := 1, @_sequence:=1, @_last_esc_level:=0) r
WHERE IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND a.status_id not in (',@close_status_id,') AND assigned_to>0 and a.created_date>b.dont_read_mail_before');
#SELECT @sql1;
PREPARE stmtcdrSQL FROM @sql1; 
EXECUTE stmtcdrSQL; 
DEALLOCATE PREPARE stmtcdrSQL;

SET @sql1 = CONCAT('select * from temp_matrix_',@curdatetime,' where rowno=1');
#SELECT @sql1;
PREPARE stmtcdrSQL FROM @sql1; 
EXECUTE stmtcdrSQL; 
DEALLOCATE PREPARE stmtcdrSQL;

SET @sql1 = CONCAT('drop table if exists temp_escalation_matrix_',@curdatetime,',temp_matrix_',@curdatetime);

PREPARE stmtcdrSQL FROM @sql1; 
EXECUTE stmtcdrSQL; 
DEALLOCATE PREPARE stmtcdrSQL;
SELECT "Success" AS result;
COMMIT;
END
**

CREATE PROCEDURE `getCategoryWiseTicketCount`(
	IN `qid` INT,
	IN `cond` TEXT,
	IN `userids` TEXT,
	IN `fromdate` VARCHAR(100),
	IN `todate` VARCHAR(100),
	IN `fullcontrol` INT
)
BEGIN

set fromdate=if(IFNULL(fromdate,"")!="",CONCAT(' and Date_Format(ttm.created_date,"%Y-%m-%d")>="',fromdate,'" '),' ');
set todate=if(IFNULL(todate,"")!="",CONCAT(' and Date_Format(ttm.created_date,"%Y-%m-%d")<="',todate,'" '),' ');


SET @sqlquery = CONCAT('SELECT group_concat(DISTINCT status_id) INTO @status_ids
FROM tms_user_master tum JOIN tms_statuspermission_',qid,' tsp ON tum.user_type=tsp.user_type
WHERE tsp.is_checked=1 AND tum.user_id in(',userids,') ');

PREPARE stmtsqlquery FROM @sqlquery; 
EXECUTE stmtsqlquery; 
DEALLOCATE PREPARE stmtsqlquery;



SET @col = CONCAT('SELECT GROUP_CONCAT(CONCAT(''SUM(CASE WHEN tqs.status_id = '', status_id, '' THEN 1 ELSE 0 END) AS "'', REPLACE(REPLACE(status_name, '' '', ''_''), ''-'', ''_''), ''"'') order by order_no) INTO @exactcol FROM tms_queue_status_',qid,' tqs  ');

PREPARE stmtcol FROM @col; 
EXECUTE stmtcol; 
DEALLOCATE PREPARE stmtcol; 



SET @SQL = CONCAT('SELECT category_name,/*COUNT(if(Date_Format(ttm.created_date,"%Y-%m-%d")=CURDATE(),1,null))Today_total,*/
                   COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL))Total,', IFNULL(@exactcol, ''), '
                  FROM tms_ticket_master_',qid,' ttm 
                  LEFT JOIN tms_queue_status_',qid,' tqs ON ttm.status_id=tqs.status_id 
                  JOIN tms_queue_category_',qid,' tqc ON ttm.category_id=tqc.category_id                         
                  WHERE   1=1 and IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 ',fromdate,todate,if(ifnull(cond,'')!='',CONCAT(' and ',cond),''),
	               if(IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0, CONCAT('and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),''), 
	               if(IFNULL(userids,"")!="1",CONCAT(' and ttm.status_id in (',@status_ids,')'),' ') ,'
	               GROUP BY category_name ');

PREPARE stmtSQL FROM @SQL; 
EXECUTE stmtSQL; 
DEALLOCATE PREPARE stmtSQL;

SET @col2 = CONCAT('SELECT GROUP_CONCAT(CONCAT(''SUM(CASE WHEN tqs.status_id = '', status_id, '' THEN 1 ELSE 0 END) AS "'', REPLACE(REPLACE(status_name, '' '', ''_''), ''-'', ''_''), ''_today"'') order by order_no) INTO @exactcol2 FROM tms_queue_status_',qid,' tqs  ');

PREPARE stmtcol2 FROM @col2; 
EXECUTE stmtcol2; 
DEALLOCATE PREPARE stmtcol2; 

SET @SQL = CONCAT('SELECT category_name,COUNT(if(Date_Format(ttm.created_date,"%Y-%m-%d")=CURDATE(),1,null))Today_total,', IFNULL(@exactcol2, ''), '
                   /*COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL))Total,*/
                  FROM tms_ticket_master_',qid,' ttm 
                  LEFT JOIN tms_queue_status_',qid,' tqs ON ttm.status_id=tqs.status_id 
                  JOIN tms_queue_category_',qid,' tqc ON ttm.category_id=tqc.category_id                         
                  WHERE 1=1 and IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND Date_Format(ttm.created_date,"%Y-%m-%d")=CURDATE()
						', if(ifnull(cond,'')!='',CONCAT(' and ',cond),'') ,
                  if(IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0,CONCAT('and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),''), 
						if(IFNULL(userids,"")!="1",CONCAT(' and ttm.status_id in (',@status_ids,')'),'') ,	'
	               GROUP BY category_name 
						'); 

PREPARE stmtSQL FROM @SQL; 
EXECUTE stmtSQL; 
DEALLOCATE PREPARE stmtSQL;     
END

**

CREATE PROCEDURE `getChildUsers`(
	IN `user_id` INT,
	INOUT `child` TEXT
)
BEGIN
DECLARE finished INTEGER DEFAULT 0;
   DECLARE var_ch_user_id INT;
   DECLARE var_ch_users TEXT;
   DECLARE temppath TEXT;
   DECLARE childUsers
CURSOR FOR
SELECT t1.id FROM tms_user_master t1 WHERE t1.manager_id=user_id AND t1.`status` != 0;

DECLARE CONTINUE HANDLER
FOR NOT FOUND SET finished = 1;
OPEN childUsers;
getChild: LOOP
   SET max_sp_recursion_depth = 255;
   FETCH childUsers INTO var_ch_user_id;
	IF finished = 1 THEN
		LEAVE getChild;
	END IF;
   IF var_ch_user_id IS NULL
    	THEN
        SET child = child;
      ELSE
        IF child = ''
           THEN
            	SET child = var_ch_user_id;
           ELSE
        			SET child = CONCAT(child, ',', var_ch_user_id);
        END IF;
        CALL GetChildUsers(var_ch_user_id, child);
    END IF;
END LOOP getChild;
CLOSE childUsers;
END
**

CREATE PROCEDURE `getConversation_Count`(
	IN `qid` VARCHAR(20),
	IN `fromdate` TEXT,
	IN `todate` TEXT,
	IN `limit_offset` VARCHAR(50)
)
BEGIN

SET SESSION group_concat_max_len = 1000000; 

SET @SQL=CONCAT('SELECT GROUP_CONCAT(
CONCAT("SELECT 
Date(created_date) `Date`,
ifnull(Sum(case when conversation_type =""incomming mail"" then 1 ELSE 0 END),0) `Incoming`,
ifnull(Sum(case when conversation_type =""reply"" then 1 ELSE 0 END),0) `Reply`,
ifnull(Sum(case when conversation_type =""reply_all"" then 1 ELSE 0 END),0) `Reply_all`,
ifnull(Sum(case when conversation_type =""forward"" then 1 ELSE 0 END),0) `Forward`
FROM tms_ticket_master_",tqm.id," t1
LEFT JOIN tms_conversation_master_",tqm.id,"  as tcm ON tcm.ticket_unique_id = t1.ticket_unique_id
Where t1.is_junk != 1 and t1.is_deleted_ticket != 1 and t1.created_date >=""',fromdate,'""
AND t1.created_date <=""',todate,'""
group by Date(created_date)"
)
 SEPARATOR "Union All "
 )
INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @SQL;
PREPARE stmt FROM @SQL;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;

SET @QUERY=CONCAT('select  DATE_FORMAT(`Date`,"%d-%m-%Y") AS `Date`,sum(Incoming) Incoming,sum(Reply) Reply,sum(Reply_all) Reply_all,sum(Forward) Forward 
from(', @tqmtemp , ')t
group by `Date`
 ');
 if limit_offset !='' then
	 	SET @QUERY = CONCAT(@QUERY,' LIMIT ', limit_offset);
	 END if;
 
#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
END
**

CREATE PROCEDURE `getLoginAgentDashboard`(
	IN `queueid` VARCHAR(50),
	IN `userid` VARCHAR(50),
	IN `fromdate` TEXT,
	IN `todate` TEXT,
	IN `rpt_type` VARCHAR(50),
	IN `fullcontrol` INT,
	IN `Sorting` VARCHAR(50)
)
BEGIN
SET SESSION group_concat_max_len=1000000;
SET @user_id = userid;

SET @curdatetime = replace(replace(replace(replace(current_timestamp(6),'-',''),':',''),' ','_'),'.','_');

set fromdate=if(IFNULL(fromdate,"")!="",CONCAT(' and ttm.assigned_on >="',fromdate,'" '),' ');
set todate=if(IFNULL(todate,"")!="",CONCAT(' and ttm.assigned_on <="',todate,'" '),' ');

SET @dropsql = CONCAT('drop table if exists temp_table_user_1,temp_user_assigned_',@curdatetime);
PREPARE stmtdropsql FROM @dropsql;
EXECUTE stmtdropsql;
DEALLOCATE PREPARE stmtdropsql;

SET @sql = CONCAT('SELECT group_concat(DISTINCT status_id) INTO @status_ids
FROM tms_user_master tum JOIN tms_statuspermission_',queueid,' tsp ON tum.user_type=tsp.user_type
WHERE tsp.is_checked=1 and tum.user_id in(',userid,')  ');

#SELECT @SQL;
PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 



SET @sql1 = CONCAT('SELECT GROUP_CONCAT(CONCAT(''ifnull(sum(case when status_name="'',status_name,''" then 1 else 0 end),0) "'',replace(status_name," ",""),''_Tickets"'') order by order_no),
GROUP_CONCAT(CONCAT("max(case when status_name=''",status_name,"'' then tqs.status_id else 0 end)''",replace(replace(status_name," ",""),"/","_"),''_'',status_id,''_id'''''') order by order_no) 
into @statuswisecount,@maxstatusid FROM tms_queue_status_',queueid,' where  ', if( IFNULL(fullcontrol,0)=0 AND IFNULL(@status_ids,"")!="" ,CONCAT(' status_id in (',@status_ids,')'),' 1=1 '));

#SELECT @sql1;
PREPARE stmt FROM @sql1;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql1= CONCAT('create temporary table temp_user_assigned_',@curdatetime,' as SELECT ifnull(assigned_to,0) user_id,',if(IFNULL(@statuswisecount,'')='','',CONCAT(@statuswisecount,',')),
if(IFNULL(@maxstatusid,'')='','',CONCAT(@maxstatusid,',')),'
		ifnull(sum(case when ifnull(assigned_to,0)>0  AND ifnull(assigned_by,0)<=0 then 1 else 0 end),0)AutoAssigned
		,ifnull(sum(case when assigned_by != assigned_to AND assigned_to = assigned_to AND assigned_by is not null AND assigned_by != 0 then 1 else 0 end),0)AssignedByOthers
		,ifnull(sum(case when assigned_to != assigned_to AND assigned_by = assigned_to then 1 else 0 end),0)AssignedToOthers
		,ifnull(sum(case when assigned_to = assigned_to AND assigned_by = assigned_to then 1 else 0 end),0)AssignedToSelf
		,Count(1) AssignedTotalTicket
		from tms_ticket_master_',queueid,' ttm
		JOIN tms_queue_status_',queueid,' tqs on ttm.status_id=tqs.status_id
		WHERE IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 and is_draft != 1 and 1 = 1 ',fromdate,todate,'
		',if( IFNULL(fullcontrol,0)=0,CONCAT(' and ttm.assigned_to in (',userid,')'),''), if( IFNULL(fullcontrol,0)=0  AND IFNULL(@status_ids,"")!="",CONCAT(' and ttm.status_id in (',@status_ids,')'),'') ,'
		GROUP BY ifnull(assigned_to,0)');

#SELECT @sql1;
PREPARE stmt FROM @sql1;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql1 = CONCAT('create  table temp_table_user_1 as select ',queueid,' as queue_id,tempdata.* from (SELECT tum.user_id userid,temp.*,tum.user_name Agent,tum.Userlogo,
case when tll.insert_date is not null then tll.insert_date else "00:00:00" end Login ,
case when break_state=1 then "ON" else "" end On_Break,
case when ifnull(tll.status,"Logout") = "Login" then "On Work" else "Logout" end State 
FROM tms_user_master tum
LEFT JOIN temp_user_assigned_',@curdatetime,' temp ON temp.user_id=tum.user_id
LEFT JOIN(select user_id, max(id)id from tms_login_log group by user_id)LLog  on tum.user_id = LLog.user_id
left join tms_login_log tll  ON LLog.id = tll.id 
where 1=1 and tum.user_id > 1 and tum.queue_id like ("%',queueid,'%") AND ifnull(tum.status,0)=1
',if(  IFNULL(fullcontrol,0)=0,CONCAT('  and  tum.user_id in (',userid,')'),""),')tempdata 
where 1=1 and ',case when rpt_type='All' then '1=1' when rpt_type='Login' then 'tempdata.State="On Work"' ELSE 'tempdata.State="Logout"' end,'
');

#SELECT @sql1;
PREPARE stmt FROM @sql1;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @id=NULL;
SET @SQL2 = CONCAT('SELECT count(1) into @id
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME IN ("temp_table_user_1","tms_queue_master")
	AND column_name LIKE replace(replace(replace(replace("',sorting,'",'' ASC'',''%''),'' DESC'',''%''),'' asc'',''%''),'' desc'',''%'')
LIMIT 1'
);

#SELECT @SQL2;
PREPARE stmt FROM @SQL2;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


SET @query = CONCAT('select tqm.queue as queue_name, ttu.* from temp_table_user_1 ttu
join tms_queue_master tqm on queue_id=tqm.id',
if(1=@id,CONCAT(' ORDER BY ',sorting,''),""),''
);

#SELECT @QUERY;
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;



SET @dropsql = CONCAT('drop table if exists temp_table_user_1, temp_user_assigned_',@curdatetime);

PREPARE stmtdropsql FROM @dropsql;
EXECUTE stmtdropsql;
DEALLOCATE PREPARE stmtdropsql;

END
**
CREATE PROCEDURE `getParentUser`(
	IN `user_id` INT,
	INOUT `parent` TEXT
)
BEGIN
    DECLARE finished INTEGER DEFAULT 0;
    DECLARE var_ch_user_id INT;
    DECLARE var_ch_users TEXT;
    DECLARE temppath TEXT;
    DECLARE parentUsers CURSOR FOR
        SELECT t1.manager_id FROM tms_user_master t1 WHERE t1.user_id = user_id;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

    OPEN parentUsers;
    getParent: LOOP
        SET max_sp_recursion_depth = 255;
        FETCH parentUsers INTO var_ch_user_id;
        
        IF finished = 1 THEN
            LEAVE getParent;
        END IF;

        IF var_ch_user_id IS NULL THEN
            SET parent = parent;  -- Assuming 'parent' is initialized somewhere
        ELSE
            IF parent = '' THEN
                SET parent = var_ch_user_id;
            ELSE
                SET parent = CONCAT(parent, ',', var_ch_user_id);
            END IF;

            -- Call to get the upper-level users recursively
            CALL getParentUser(var_ch_user_id, parent);
        END IF;
    END LOOP getParent;

    CLOSE parentUsers;
END
**
CREATE PROCEDURE `getTicketCountWithInTatOutOfTat`(
	IN `qid` VARCHAR(50),
	IN `cond` TEXT,
	IN `userids` TEXT,
	IN `isadmin` TINYINT,
	IN `fromdate` VARCHAR(100),
	IN `todate` VARCHAR(100),
	IN `is_category` TINYINT,
	IN `fullcontrol` INT,
	IN `all_ticket` INT
)
BEGIN
DROP TABLE IF EXISTS ticket_tattemp;
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

SET SESSION group_concat_max_len = 1000000; 


set fromdate=if(IFNULL(fromdate,"")!="",CONCAT(' and date(ttm.created_date)>=''',fromdate,''' '),' ');
set todate=if(IFNULL(todate,"")!="",CONCAT(' and date(ttm.created_date)<=''',todate,''' '),' ');

SET @Sql_Query=CONCAT ('SELECT COUNT(*) into @id  FROM tms_queue_master 
WHERE id IN (',qid,')');
#SELECT @Sql_Query;
PREPARE stmt FROM @Sql_Query;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;	

SET @tqmtemp = '';

if is_category = 0 then
SET @ticketquery = CONCAT('SELECT GROUP_CONCAT(
    CONCAT(
        "SELECT ",tqm.id," Queue_id,tqs.status_name,ifnull(is_draft,0) is_draft,ifnull(status_name1,""Non Final"") status_name1, tqs.status_id, tqs.colour_code, tqs.order_no, tqs.is_close_status,
            IFNULL(today_all,0) AS today_all, IFNULL(today_out_of_tat,0) AS today_out_of_tat,
            IFNULL(today_with_in_tat,0) AS today_with_in_tat, IFNULL(out_of_tat_ALL,0) AS out_of_tat_ALL,
            IFNULL(with_in_tat_ALL,0) AS with_in_tat_ALL, IFNULL(Total,0) AS Total
        FROM tms_queue_status_",tqm.id, " AS tqs 
        LEFT JOIN (
            SELECT tqs.status_id,ifnull(is_draft,0) is_draft,case when ticket_status_type=1 then ""Final"" when ticket_status_type in (2,3) then ""Non Final"" end status_name1,
            COUNT(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),',
					 (Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),'),1,null)) AS today_all,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) > tqp.tat * 60 , 1, 0)) AS today_out_of_tat,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <= tqp.tat * 60 , 1, 0)) AS today_with_in_tat,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS out_of_tat_ALL,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <=tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS with_in_tat_ALL,
                COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL)) AS Total
            FROM tms_ticket_master_",tqm.id, " AS ttm 
            RIGHT JOIN tms_queue_status_",tqm.id, " AS tqs ON ttm.status_id = tqs.status_id 
            LEFT JOIN tms_queue_priority_",tqm.id, " AS tqp ON ttm.priority_id = tqp.priority_id 
            ',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,')) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
            LEFT JOIN (
                SELECT MAX(tcm.conversation_date) AS last_con_date, tcm.ticket_unique_id 
                FROM tms_conversation_master_",tqm.id, " AS tcm 
                join tms_ticket_master_",tqm.id, " AS ttm on tcm.ticket_unique_id = ttm.ticket_unique_id
                where 1=1  ',fromdate,todate,'
                GROUP BY tcm.ticket_unique_id
            ) AS lasttcm ON lasttcm.ticket_unique_id = ttm.ticket_unique_id
            WHERE IFNULL(is_junk,0) = 0 AND IFNULL(is_deleted_ticket,0) = 0 AND 1 = 1 /*and is_draft!=1*/
            ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
            GROUP BY tqs.status_id,is_draft,ticket_status_type 
        )AS ticket_status_count ON tqs.status_id = ticket_status_count.status_id"
		  
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')');  
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
SET @tablequery=CONCAT('CREATE TABLE ticket_tattemp SELECT * FROM (', @tqmtemp , ')t');

PREPARE stmt FROM @tablequery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

if (@id=1)
then
SET @QUERY = CONCAT(' SELECT queue_id,queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name, status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no  
Union All
SELECT queue_id,tqm.queue as queue_name,"Draft" status_name, "-1"  status_id,"#6fa8dc" colour_code,"0" order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id 
Where 1=1 and is_draft=1 
GROUP BY queue_id,tqm.queue
Union ALL
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
Union All
SELECT  queue_id,tqm.queue as queue_name, status_name1 status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY queue_id,tqm.queue,status_name1
)AS s  /*ORDER BY order_no*/
order by case when queue_id="0" then 1 ELSE 0 END,queue_id,
case when status_name="ALL" then 0
when status_name="Final" then 1
when status_name="Non Final" then 2
else 3 end,status_name;;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
ELSE 	

SET @QUERY = CONCAT(' SELECT ifnull(queue_id,"") queue_id, ifnull(queue_name,"") queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name, status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no  
Union All
SELECT queue_id,tqm.queue as queue_name,"Draft" status_name, "-1"  status_id,"#6fa8dc" colour_code,"0" order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id 
Where 1=1 and is_draft=1 
GROUP BY queue_id,tqm.queue
Union ALL
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
Union All
SELECT  queue_id,tqm.queue as queue_name, status_name1 status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY queue_id,tqm.queue,status_name1
union all
SELECT "0"queue_id,"ALL" queue_name, status_name,""status_id,colour_code,"0"order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY status_name,colour_code  
Union All
SELECT "0" queue_id,"ALL" queue_name,"Draft" status_name, ""  status_id,"#6fa8dc" colour_code,"0" order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id 
Where 1=1 and is_draft=1 
GROUP BY queue_id,tqm.queue
Union ALL
SELECT "0" queue_id,"ALL" as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
Union All
SELECT "0" queue_id,"ALL" as queue_name, status_name1 status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY status_name1
 )as c
order by case when queue_id="0" then 1 ELSE 0 END,queue_id,
case when status_name="ALL" then 0
when status_name="Open" then 1
else 2 end,status_name;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
END if;

ELSE

SET @ticketquery = CONCAT('
SELECT GROUP_CONCAT(
    CONCAT(
        "	SELECT ",tqm.id, " Queue_id,ttm.category_id,category_name,
        ifnull(is_draft,0) is_draft,
	case when ticket_status_type=1 then ""Final"" when ticket_status_type in (2,3) then ""Non Final"" end status_name1,  
	tqs.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code,
	COUNT(if(Date(ttm.created_date)=CURDATE(),1,null))cnt,
	COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL))Total
	FROM  tms_ticket_master_",tqm.id, " AS ttm 
	RIGHT JOIN tms_queue_status_",tqm.id, " as tqs on  ttm.status_id=tqs.status_id 
	JOIN tms_queue_category_",tqm.id, " as tqc ON ttm.category_id=tqc.category_id 
	',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,') ) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
	WHERE 1=1 and IFNULL(is_junk,0)=0 
	AND IFNULL(is_deleted_ticket,0)=0 and status=1 
	  ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
	GROUP BY ttm.category_id,category_name,
	tqs.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code,is_draft,ticket_status_type
 "
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
SET @tablequery=CONCAT('CREATE TABLE ticket_tattemp SELECT * FROM (', @tqmtemp , ')t');

PREPARE stmt FROM @tablequery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


if (@id=1) then

	SET @category_wise = CONCAT('SELECT queue_id,queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  From
(SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,
is_default,is_close_status, colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
group by queue_id,tqm.queue,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code
Union All
SELECT queue_id,tqm.queue as queue_name,category_id,category_name, "-1" status_id,"Draft" status_name,
is_default,is_close_status, "#6fa8dc"  colour_code,cnt,Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft=1
Union All
SELECT queue_id,tqm.queue as queue_name,category_id,category_name,"0",status_name1 status_name,
"0" is_default,"0" is_close_status,"#6fa8dc"colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY queue_id,tqm.queue,category_id,category_name,status_name1
)s
ORDER BY category_name; ');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

ELSE 

SET @category_wise = CONCAT(' SELECT queue_id,queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  From
(SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,
is_default,is_close_status, colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
group by queue_id,tqm.queue,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code
Union All
SELECT queue_id,tqm.queue as queue_name,category_id,category_name, "-1" status_id,"Draft" status_name,
is_default,is_close_status, "#6fa8dc"  colour_code,cnt,Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft=1
Union All
SELECT queue_id,tqm.queue as queue_name,category_id,category_name,"0",status_name1 status_name,
"0" is_default,"0" is_close_status,"#6fa8dc"colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY queue_id,tqm.queue,category_id,category_name,status_name1
union all
SELECT 0,"ALL" as queue_name,"",category_name,"" status_id,status_name,
is_default,is_close_status,colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
group by status_name,is_default,is_close_status,colour_code,category_name
Union All
SELECT 0,"ALL" as queue_name,"",category_name,"" status_id,"Draft" status_name,
0 is_default,0 is_close_status, "#6fa8dc"  colour_code,cnt,Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft=1
Union All
SELECT 0,"ALL" as queue_name,"",category_name,"",status_name1 status_name,
"0" is_default,"0" is_close_status,"#6fa8dc"colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY category_name,status_name1
)s
ORDER BY case when queue_id="0" then 1 ELSE 0 END,queue_id,category_name,
status_name;');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

END if; 		
END if; 
DROP TABLE IF EXISTS ticket_tattemp;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**
CREATE PROCEDURE `getTicketCountWithInTatOutOfTat_20240610`(
	IN `qid` VARCHAR(50),
	IN `cond` TEXT,
	IN `userids` TEXT,
	IN `isadmin` TINYINT,
	IN `fromdate` VARCHAR(100),
	IN `todate` VARCHAR(100),
	IN `is_category` TINYINT,
	IN `fullcontrol` INT,
	IN `all_ticket` INT
)
BEGIN
DROP TABLE IF EXISTS temp_ticketstatus;
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

SET SESSION group_concat_max_len = 1000000; 


set fromdate=if(IFNULL(fromdate,"")!="",CONCAT(' and date(ttm.created_date)>=''',fromdate,''' '),' ');
set todate=if(IFNULL(todate,"")!="",CONCAT(' and date(ttm.created_date)<=''',todate,''' '),' ');

SET @Sql_Query=CONCAT ('SELECT COUNT(*) into @id  FROM tms_queue_master 
WHERE id IN (',qid,')');
#SELECT @Sql_Query;
PREPARE stmt FROM @Sql_Query;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;	

SET @tqmtemp = '';
SET @tqmtemp1 = '';

if is_category = 0 then
SET @ticketquery = CONCAT('SELECT GROUP_CONCAT(
    CONCAT(
        "SELECT ",tqm.id," Queue_id,tqs.status_name, tqs.status_id, tqs.colour_code, tqs.order_no, tqs.is_close_status,
            IFNULL(today_all,0) AS today_all, IFNULL(today_out_of_tat,0) AS today_out_of_tat,
            IFNULL(today_with_in_tat,0) AS today_with_in_tat, IFNULL(out_of_tat_ALL,0) AS out_of_tat_ALL,
            IFNULL(with_in_tat_ALL,0) AS with_in_tat_ALL, IFNULL(Total,0) AS Total
        FROM tms_queue_status_",tqm.id, " AS tqs 
        LEFT JOIN (
            SELECT ttm.status_id,
            COUNT(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),',
					 (Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),'),1,null)) AS today_all,
                SUM(IF(Date(ttm.created_date)=CURDATE() AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) > tqp.tat * 60 , 1, 0)) AS today_out_of_tat,
                SUM(IF(Date(ttm.created_date)=CURDATE() AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <= tqp.tat * 60 , 1, 0)) AS today_with_in_tat,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS out_of_tat_ALL,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <=tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS with_in_tat_ALL,
                COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL)) AS Total
            FROM tms_ticket_master_",tqm.id, " AS ttm 
            LEFT JOIN tms_queue_status_",tqm.id, " AS tqs ON ttm.status_id = tqs.status_id 
            LEFT JOIN tms_queue_priority_",tqm.id, " AS tqp ON ttm.priority_id = tqp.priority_id 
            ',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,')) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
            LEFT JOIN (
                SELECT MAX(tcm.conversation_date) AS last_con_date, tcm.ticket_unique_id 
                FROM tms_conversation_master_",tqm.id, " AS tcm 
                JOIN tms_queue_status_",tqm.id, " AS tqs ON tcm.status_id = tqs.status_id 
                WHERE tqs.is_close_status=1
                GROUP BY tcm.ticket_unique_id
            ) AS lasttcm ON lasttcm.ticket_unique_id = ttm.ticket_unique_id
            WHERE IFNULL(is_junk,0) = 0 AND IFNULL(is_deleted_ticket,0) = 0 AND 1 = 1
            ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
            GROUP BY ttm.status_id 
        ) AS ticket_status_count ON tqs.status_id = ticket_status_count.status_id"
		  
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;


if (@id=1)
then
SET @QUERY = CONCAT(' SELECT queue_id,queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name,status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no 
Union All
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
)AS s  ORDER BY order_no;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
ELSE 	

SET @QUERY = CONCAT(' SELECT ifnull(queue_id,"") queue_id, ifnull(queue_name,"") queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name,status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no 																				
Union All
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
)AS s 
union all
SELECT queue_id, queue_name, status_name, "",colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT "0" queue_id,"ALL" queue_name,status_name, "" ,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t1
Where 1=1 GROUP BY status_name,colour_code,order_no 
Union All
SELECT  "0"queue_id,"ALL" queue_name,"ALL" status_name, "" ,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y1
)AS s1  )as c
order by case when queue_id="0" then 1 ELSE 0 END,queue_id,
case when status_name="ALL" then 0
when status_name="Open" then 1
else 2 end,status_name;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
END if;
ELSE

SET @ticketquery = CONCAT('


SELECT GROUP_CONCAT(
    CONCAT(
        "	SELECT ",tqm.id, " Queue_id,ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code,
	COUNT(if(Date(ttm.created_date)=CURDATE(),1,null))cnt,
	COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL))Total
	FROM  tms_ticket_master_",tqm.id, " AS ttm 
	left JOIN tms_queue_status_",tqm.id, " as tqs on  ttm.status_id=tqs.status_id 
	JOIN tms_queue_category_",tqm.id, " as tqc ON ttm.category_id=tqc.category_id 
	',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,') ) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
	WHERE 1=1 and IFNULL(is_junk,0)=0 
	AND IFNULL(is_deleted_ticket,0)=0 and status=1
	  ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
	GROUP BY ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code
 "
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;

if (@id=1) then

	SET @category_wise = CONCAT('SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  
FROM (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
order by category_name ');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

ELSE 

SET @category_wise = CONCAT(' SELECT queue_id,queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  From
(SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  
FROM (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Union All
SELECT   "0","ALL","",category_name,"",status_name,is_default,is_close_status,colour_code,sum(cnt) cnt,sum(Total) 
FROM (', @tqmtemp , ')y
GROUP BY category_name,status_name,is_default,is_close_status,colour_code)s
ORDER BY case when queue_id="0" then 1 ELSE 0 END,queue_id,category_name,
status_name;');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

END if; 		
END if; 
DROP TABLE IF EXISTS temp_ticketstatus;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**
CREATE PROCEDURE `getTicketCountWithInTatOutOfTat_20240625`(
	IN `qid` VARCHAR(50),
	IN `cond` TEXT,
	IN `userids` TEXT,
	IN `isadmin` TINYINT,
	IN `fromdate` VARCHAR(100),
	IN `todate` VARCHAR(100),
	IN `is_category` TINYINT,
	IN `fullcontrol` INT,
	IN `all_ticket` INT
)
BEGIN
DROP TABLE IF EXISTS temp_ticketstatus;
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

SET SESSION group_concat_max_len = 1000000; 


set fromdate=if(IFNULL(fromdate,"")!="",CONCAT(' and date(ttm.created_date)>=''',fromdate,''' '),' ');
set todate=if(IFNULL(todate,"")!="",CONCAT(' and date(ttm.created_date)<=''',todate,''' '),' ');

SET @Sql_Query=CONCAT ('SELECT COUNT(*) into @id  FROM tms_queue_master 
WHERE id IN (',qid,')');
#SELECT @Sql_Query;
PREPARE stmt FROM @Sql_Query;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;	

SET @tqmtemp = '';
SET @tqmtemp1 = '';

if is_category = 0 then
SET @ticketquery = CONCAT('SELECT GROUP_CONCAT(
    CONCAT(
        "SELECT ",tqm.id," Queue_id,tqs.status_name, tqs.status_id, tqs.colour_code, tqs.order_no, tqs.is_close_status,
            IFNULL(today_all,0) AS today_all, IFNULL(today_out_of_tat,0) AS today_out_of_tat,
            IFNULL(today_with_in_tat,0) AS today_with_in_tat, IFNULL(out_of_tat_ALL,0) AS out_of_tat_ALL,
            IFNULL(with_in_tat_ALL,0) AS with_in_tat_ALL, IFNULL(Total,0) AS Total
        FROM tms_queue_status_",tqm.id, " AS tqs 
        LEFT JOIN (
            SELECT ttm.status_id,
            COUNT(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),',
					 (Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),'),1,null)) AS today_all,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) > tqp.tat * 60 , 1, 0)) AS today_out_of_tat,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <= tqp.tat * 60 , 1, 0)) AS today_with_in_tat,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS out_of_tat_ALL,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <=tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS with_in_tat_ALL,
                COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL)) AS Total
            FROM tms_ticket_master_",tqm.id, " AS ttm 
            LEFT JOIN tms_queue_status_",tqm.id, " AS tqs ON ttm.status_id = tqs.status_id 
            LEFT JOIN tms_queue_priority_",tqm.id, " AS tqp ON ttm.priority_id = tqp.priority_id 
            ',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,')) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
            LEFT JOIN (
                SELECT MAX(tcm.conversation_date) AS last_con_date, tcm.ticket_unique_id 
                FROM tms_conversation_master_",tqm.id, " AS tcm 
                /*JOIN tms_queue_status_",tqm.id, " AS tqs ON tcm.status_id = tqs.status_id 
                WHERE tqs.is_close_status=1*/
                GROUP BY tcm.ticket_unique_id
            ) AS lasttcm ON lasttcm.ticket_unique_id = ttm.ticket_unique_id
            WHERE IFNULL(is_junk,0) = 0 AND IFNULL(is_deleted_ticket,0) = 0 AND 1 = 1
            ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
            GROUP BY ttm.status_id 
        ) AS ticket_status_count ON tqs.status_id = ticket_status_count.status_id"
		  
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;


if (@id=1)
then
SET @QUERY = CONCAT(' SELECT queue_id,queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name,status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no 
Union All
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
)AS s  ORDER BY order_no;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
ELSE 	

SET @QUERY = CONCAT(' SELECT ifnull(queue_id,"") queue_id, ifnull(queue_name,"") queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name,status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no 																				
Union All
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
)AS s 
union all
SELECT queue_id, queue_name, status_name, "",colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT "0" queue_id,"ALL" queue_name,status_name, "" ,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t1
Where 1=1 GROUP BY status_name,colour_code,order_no 
Union All
SELECT  "0"queue_id,"ALL" queue_name,"ALL" status_name, "" ,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y1
)AS s1  )as c
order by case when queue_id="0" then 1 ELSE 0 END,queue_id,
case when status_name="ALL" then 0
when status_name="Open" then 1
else 2 end,status_name;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
END if;
ELSE

SET @ticketquery = CONCAT('


SELECT GROUP_CONCAT(
    CONCAT(
        "	SELECT ",tqm.id, " Queue_id,ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code,
	COUNT(if(Date(ttm.created_date)=CURDATE(),1,null))cnt,
	COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL))Total
	FROM  tms_ticket_master_",tqm.id, " AS ttm 
	left JOIN tms_queue_status_",tqm.id, " as tqs on  ttm.status_id=tqs.status_id 
	JOIN tms_queue_category_",tqm.id, " as tqc ON ttm.category_id=tqc.category_id 
	',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,') ) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
	WHERE 1=1 and IFNULL(is_junk,0)=0 
	AND IFNULL(is_deleted_ticket,0)=0 and status=1
	  ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
	GROUP BY ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code
 "
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;

if (@id=1) then

	SET @category_wise = CONCAT('SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  
FROM (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
order by category_name ');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

ELSE 

SET @category_wise = CONCAT(' SELECT queue_id,queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  From
(SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  
FROM (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Union All
SELECT   "0","ALL","",category_name,"",status_name,is_default,is_close_status,colour_code,sum(cnt) cnt,sum(Total) 
FROM (', @tqmtemp , ')y
GROUP BY category_name,status_name,is_default,is_close_status,colour_code)s
ORDER BY case when queue_id="0" then 1 ELSE 0 END,queue_id,category_name,
status_name;');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

END if; 		
END if; 
DROP TABLE IF EXISTS temp_ticketstatus;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**
CREATE PROCEDURE `getTicketCountWithInTatOutOfTat_20240829`(
	IN `qid` VARCHAR(50),
	IN `cond` TEXT,
	IN `userids` TEXT,
	IN `isadmin` TINYINT,
	IN `fromdate` VARCHAR(100),
	IN `todate` VARCHAR(100),
	IN `is_category` TINYINT,
	IN `fullcontrol` INT,
	IN `all_ticket` INT
)
BEGIN
DROP TABLE IF EXISTS temp_ticketstatus;
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

SET SESSION group_concat_max_len = 1000000; 


set fromdate=if(IFNULL(fromdate,"")!="",CONCAT(' and date(ttm.created_date)>=''',fromdate,''' '),' ');
set todate=if(IFNULL(todate,"")!="",CONCAT(' and date(ttm.created_date)<=''',todate,''' '),' ');

SET @Sql_Query=CONCAT ('SELECT COUNT(*) into @id  FROM tms_queue_master 
WHERE id IN (',qid,')');
#SELECT @Sql_Query;
PREPARE stmt FROM @Sql_Query;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;	

SET @tqmtemp = '';
SET @tqmtemp1 = '';

if is_category = 0 then
SET @ticketquery = CONCAT('SELECT GROUP_CONCAT(
    CONCAT(
        "SELECT ",tqm.id," Queue_id,tqs.status_name, tqs.status_id, tqs.colour_code, tqs.order_no, tqs.is_close_status,
            IFNULL(today_all,0) AS today_all, IFNULL(today_out_of_tat,0) AS today_out_of_tat,
            IFNULL(today_with_in_tat,0) AS today_with_in_tat, IFNULL(out_of_tat_ALL,0) AS out_of_tat_ALL,
            IFNULL(with_in_tat_ALL,0) AS with_in_tat_ALL, IFNULL(Total,0) AS Total
        FROM tms_queue_status_",tqm.id, " AS tqs 
        LEFT JOIN (
            SELECT ttm.status_id,
            COUNT(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),',
					 (Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),'),1,null)) AS today_all,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) > tqp.tat * 60 , 1, 0)) AS today_out_of_tat,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <= tqp.tat * 60 , 1, 0)) AS today_with_in_tat,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS out_of_tat_ALL,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <=tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS with_in_tat_ALL,
                COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL)) AS Total
            FROM tms_ticket_master_",tqm.id, " AS ttm 
            LEFT JOIN tms_queue_status_",tqm.id, " AS tqs ON ttm.status_id = tqs.status_id 
            LEFT JOIN tms_queue_priority_",tqm.id, " AS tqp ON ttm.priority_id = tqp.priority_id 
            ',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,')) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
            LEFT JOIN (
                SELECT MAX(tcm.conversation_date) AS last_con_date, tcm.ticket_unique_id 
                FROM tms_conversation_master_",tqm.id, " AS tcm 
                /*JOIN tms_queue_status_",tqm.id, " AS tqs ON tcm.status_id = tqs.status_id 
                WHERE tqs.is_close_status=1*/
                GROUP BY tcm.ticket_unique_id
            ) AS lasttcm ON lasttcm.ticket_unique_id = ttm.ticket_unique_id
            WHERE IFNULL(is_junk,0) = 0 AND IFNULL(is_deleted_ticket,0) = 0 AND 1 = 1 and is_draft!=1
            ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
            GROUP BY ttm.status_id 
        ) AS ticket_status_count ON tqs.status_id = ticket_status_count.status_id"
		  
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')');  
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;

SET @ticketquery1 = CONCAT('SELECT GROUP_CONCAT(
    CONCAT(
        "SELECT ",tqm.id," Queue_id,tqs.status_name, tqs.status_id, tqs.colour_code, tqs.order_no, tqs.is_close_status,
            IFNULL(today_all,0) AS today_all, IFNULL(today_out_of_tat,0) AS today_out_of_tat,
            IFNULL(today_with_in_tat,0) AS today_with_in_tat, IFNULL(out_of_tat_ALL,0) AS out_of_tat_ALL,
            IFNULL(with_in_tat_ALL,0) AS with_in_tat_ALL, IFNULL(Total,0) AS Total
        FROM tms_queue_status_",tqm.id, " AS tqs 
        LEFT JOIN (
            SELECT ttm.status_id,
            COUNT(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),',
					 (Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),'),1,null)) AS today_all,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) > tqp.tat * 60 , 1, 0)) AS today_out_of_tat,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <= tqp.tat * 60 , 1, 0)) AS today_with_in_tat,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS out_of_tat_ALL,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <=tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS with_in_tat_ALL,
                COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL)) AS Total
            FROM tms_ticket_master_",tqm.id, " AS ttm 
            LEFT JOIN tms_queue_status_",tqm.id, " AS tqs ON ttm.status_id = tqs.status_id 
            LEFT JOIN tms_queue_priority_",tqm.id, " AS tqp ON ttm.priority_id = tqp.priority_id 
            ',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,')) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
            LEFT JOIN (
                SELECT MAX(tcm.conversation_date) AS last_con_date, tcm.ticket_unique_id 
                FROM tms_conversation_master_",tqm.id, " AS tcm 
                /*JOIN tms_queue_status_",tqm.id, " AS tqs ON tcm.status_id = tqs.status_id 
                WHERE tqs.is_close_status=1*/
                GROUP BY tcm.ticket_unique_id
            ) AS lasttcm ON lasttcm.ticket_unique_id = ttm.ticket_unique_id
            WHERE IFNULL(is_junk,0) = 0 AND IFNULL(is_deleted_ticket,0) = 0 AND 1 = 1 and is_draft=1
            ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
            GROUP BY ttm.status_id 
        ) AS ticket_status_count ON tqs.status_id = ticket_status_count.status_id"
		  
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp1
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery1;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;

if (@id=1)
then
SET @QUERY = CONCAT(' SELECT queue_id,queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name,status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no 
Union All
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
Union All
SELECT  queue_id,tqm.queue as queue_name,"Draft" status_name,"-1","#6fa8dc"colour_code,1,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp1 , ')a
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
)AS s  ORDER BY order_no;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
ELSE 	

SET @QUERY = CONCAT(' SELECT ifnull(queue_id,"") queue_id, ifnull(queue_name,"") queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name,status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no 																				
Union All
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
Union All
SELECT  queue_id,tqm.queue as queue_name,"Draft" status_name,0,"#6fa8dc"colour_code,1,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp1 , ')a
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
)AS s 
union all
SELECT queue_id, queue_name, status_name, "",colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT "0" queue_id,"ALL" queue_name,status_name, "" ,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t1
Where 1=1 GROUP BY status_name,colour_code,order_no 
Union All
SELECT  "0"queue_id,"ALL" queue_name,"ALL" status_name, "" ,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y1
Union All
SELECT  queue_id,tqm.queue as queue_name,"Draft" status_name,0,"#6fa8dc"colour_code,1,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp1 , ')a1
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
)AS s1  )as c
order by case when queue_id="0" then 1 ELSE 0 END,queue_id,
case when status_name="ALL" then 0
when status_name="Open" then 1
else 2 end,status_name;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
END if;
ELSE

SET @ticketquery = CONCAT('


SELECT GROUP_CONCAT(
    CONCAT(
        "	SELECT ",tqm.id, " Queue_id,ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code,
	COUNT(if(Date(ttm.created_date)=CURDATE(),1,null))cnt,
	COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL))Total
	FROM  tms_ticket_master_",tqm.id, " AS ttm 
	left JOIN tms_queue_status_",tqm.id, " as tqs on  ttm.status_id=tqs.status_id 
	JOIN tms_queue_category_",tqm.id, " as tqc ON ttm.category_id=tqc.category_id 
	',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,') ) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
	WHERE 1=1 and IFNULL(is_junk,0)=0 
	AND IFNULL(is_deleted_ticket,0)=0 and status=1 and is_draft!=1
	  ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
	GROUP BY ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code
 "
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
SET @ticketquery1 = CONCAT('


SELECT GROUP_CONCAT(
    CONCAT(
        "	SELECT ",tqm.id, " Queue_id,ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code,
	COUNT(if(Date(ttm.created_date)=CURDATE(),1,null))cnt,
	COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL))Total
	FROM  tms_ticket_master_",tqm.id, " AS ttm 
	left JOIN tms_queue_status_",tqm.id, " as tqs on  ttm.status_id=tqs.status_id 
	JOIN tms_queue_category_",tqm.id, " as tqc ON ttm.category_id=tqc.category_id 
	',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,') ) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
	WHERE 1=1 and IFNULL(is_junk,0)=0 
	AND IFNULL(is_deleted_ticket,0)=0 and status=1 and is_draft=1
	  ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
	GROUP BY ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code
 "
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp1
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery1;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;


if (@id=1) then

	SET @category_wise = CONCAT('SELECT queue_id,queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  From
(SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  
FROM (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Union All
SELECT  queue_id,tqm.queue as queue_name,category_id,category_name,"-1","Draft",0,0,colour_code,sum(cnt) cnt,sum(Total) 
FROM (', @tqmtemp1 , ')a
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue,category_id,category_name,colour_code)s
ORDER BY category_name; ');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

ELSE 

SET @category_wise = CONCAT(' SELECT queue_id,queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  From
(SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  
FROM (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Union All
SELECT   "0","ALL","",category_name,"",status_name,is_default,is_close_status,colour_code,sum(cnt) cnt,sum(Total) 
FROM (', @tqmtemp , ')y
GROUP BY category_name,status_name,is_default,is_close_status,colour_code
Union All
SELECT  queue_id,tqm.queue as queue_name,category_id,category_name,-1,"Draft",0,0,colour_code,sum(cnt) cnt,sum(Total) 
FROM (', @tqmtemp1 , ')a
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue,category_id,category_name,colour_code)s
ORDER BY case when queue_id="0" then 1 ELSE 0 END,queue_id,category_name,
status_name;');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

END if; 		
END if; 
DROP TABLE IF EXISTS temp_ticketstatus;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**
CREATE PROCEDURE `getTicketCountWithInTatOutOfTat_20240906`(
	IN `qid` VARCHAR(50),
	IN `cond` TEXT,
	IN `userids` TEXT,
	IN `isadmin` TINYINT,
	IN `fromdate` VARCHAR(100),
	IN `todate` VARCHAR(100),
	IN `is_category` TINYINT,
	IN `fullcontrol` INT,
	IN `all_ticket` INT
)
BEGIN
DROP TABLE IF EXISTS temp_ticketstatus;
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

SET SESSION group_concat_max_len = 1000000; 


set fromdate=if(IFNULL(fromdate,"")!="",CONCAT(' and date(ttm.created_date)>=''',fromdate,''' '),' ');
set todate=if(IFNULL(todate,"")!="",CONCAT(' and date(ttm.created_date)<=''',todate,''' '),' ');

SET @Sql_Query=CONCAT ('SELECT COUNT(*) into @id  FROM tms_queue_master 
WHERE id IN (',qid,')');
#SELECT @Sql_Query;
PREPARE stmt FROM @Sql_Query;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;	

SET @tqmtemp = '';
SET @tqmtemp1 = '';
SET @tqmtemp2 = '';

if is_category = 0 then
SET @ticketquery = CONCAT('SELECT GROUP_CONCAT(
    CONCAT(
        "SELECT ",tqm.id," Queue_id,tqs.status_name, tqs.status_id, tqs.colour_code, tqs.order_no, tqs.is_close_status,
            IFNULL(today_all,0) AS today_all, IFNULL(today_out_of_tat,0) AS today_out_of_tat,
            IFNULL(today_with_in_tat,0) AS today_with_in_tat, IFNULL(out_of_tat_ALL,0) AS out_of_tat_ALL,
            IFNULL(with_in_tat_ALL,0) AS with_in_tat_ALL, IFNULL(Total,0) AS Total
        FROM tms_queue_status_",tqm.id, " AS tqs 
        LEFT JOIN (
            SELECT ttm.status_id,
            COUNT(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),',
					 (Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),'),1,null)) AS today_all,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) > tqp.tat * 60 , 1, 0)) AS today_out_of_tat,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <= tqp.tat * 60 , 1, 0)) AS today_with_in_tat,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS out_of_tat_ALL,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <=tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS with_in_tat_ALL,
                COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL)) AS Total
            FROM tms_ticket_master_",tqm.id, " AS ttm 
            LEFT JOIN tms_queue_status_",tqm.id, " AS tqs ON ttm.status_id = tqs.status_id 
            LEFT JOIN tms_queue_priority_",tqm.id, " AS tqp ON ttm.priority_id = tqp.priority_id 
            ',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,')) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
            LEFT JOIN (
                SELECT MAX(tcm.conversation_date) AS last_con_date, tcm.ticket_unique_id 
                FROM tms_conversation_master_",tqm.id, " AS tcm 
                /*JOIN tms_queue_status_",tqm.id, " AS tqs ON tcm.status_id = tqs.status_id 
                WHERE tqs.is_close_status=1*/
                GROUP BY tcm.ticket_unique_id
            ) AS lasttcm ON lasttcm.ticket_unique_id = ttm.ticket_unique_id
            WHERE IFNULL(is_junk,0) = 0 AND IFNULL(is_deleted_ticket,0) = 0 AND 1 = 1 and is_draft!=1
            ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
            GROUP BY ttm.status_id 
        ) AS ticket_status_count ON tqs.status_id = ticket_status_count.status_id"
		  
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')');  
SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;

SET @ticketquery1 = CONCAT('SELECT GROUP_CONCAT(
    CONCAT(
        "SELECT ",tqm.id," Queue_id,tqs.status_name, tqs.status_id, tqs.colour_code, tqs.order_no, tqs.is_close_status,
            IFNULL(today_all,0) AS today_all, IFNULL(today_out_of_tat,0) AS today_out_of_tat,
            IFNULL(today_with_in_tat,0) AS today_with_in_tat, IFNULL(out_of_tat_ALL,0) AS out_of_tat_ALL,
            IFNULL(with_in_tat_ALL,0) AS with_in_tat_ALL, IFNULL(Total,0) AS Total
        FROM tms_queue_status_",tqm.id, " AS tqs  
        LEFT JOIN (
            SELECT ttm.status_id,
            COUNT(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),',
					 (Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),'),1,null)) AS today_all,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) > tqp.tat * 60 , 1, 0)) AS today_out_of_tat,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <= tqp.tat * 60 , 1, 0)) AS today_with_in_tat,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS out_of_tat_ALL,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <=tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS with_in_tat_ALL,
                COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL)) AS Total
            FROM tms_ticket_master_",tqm.id, " AS ttm 
            LEFT JOIN tms_queue_status_",tqm.id, " AS tqs ON ttm.status_id = tqs.status_id 
            LEFT JOIN tms_queue_priority_",tqm.id, " AS tqp ON ttm.priority_id = tqp.priority_id 
            ',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,')) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
            LEFT JOIN (
                SELECT MAX(tcm.conversation_date) AS last_con_date, tcm.ticket_unique_id 
                FROM tms_conversation_master_",tqm.id, " AS tcm 
                GROUP BY tcm.ticket_unique_id
            ) AS lasttcm ON lasttcm.ticket_unique_id = ttm.ticket_unique_id
            WHERE IFNULL(is_junk,0) = 0 AND IFNULL(is_deleted_ticket,0) = 0 AND 1 = 1 and is_draft=1
            ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
            GROUP BY ttm.status_id 
        ) AS ticket_status_count ON tqs.status_id = ticket_status_count.status_id"
		  
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp1
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery1;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;

SET @ticketquery2 = CONCAT('SELECT GROUP_CONCAT(
    CONCAT(
        "SELECT ",tqm.id," Queue_id,case when ticket_status_type=1 then ""Final"" when ticket_status_type in (2,3) then ""Non Final"" end  status_name, """" status_id, ""#6fa8dc"" colour_code,"""" order_no, """" is_close_status,
            IFNULL(today_all,0) AS today_all, IFNULL(today_out_of_tat,0) AS today_out_of_tat,
            IFNULL(today_with_in_tat,0) AS today_with_in_tat, IFNULL(out_of_tat_ALL,0) AS out_of_tat_ALL,
            IFNULL(with_in_tat_ALL,0) AS with_in_tat_ALL, IFNULL(Total,0) AS Total
        FROM tms_queue_status_",tqm.id, " AS tqs 
        LEFT JOIN (
            SELECT ttm.status_id,
            COUNT(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),',
					 (Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),'),1,null)) AS today_all,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) > tqp.tat * 60 , 1, 0)) AS today_out_of_tat,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <= tqp.tat * 60 , 1, 0)) AS today_with_in_tat,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS out_of_tat_ALL,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <=tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS with_in_tat_ALL,
                COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL)) AS Total
            FROM tms_ticket_master_",tqm.id, " AS ttm 
            LEFT JOIN tms_queue_status_",tqm.id, " AS tqs ON ttm.status_id = tqs.status_id 
            LEFT JOIN tms_queue_priority_",tqm.id, " AS tqp ON ttm.priority_id = tqp.priority_id 
            ',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,')) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
            LEFT JOIN (
                SELECT MAX(tcm.conversation_date) AS last_con_date, tcm.ticket_unique_id 
                FROM tms_conversation_master_",tqm.id, " AS tcm 
                /*JOIN tms_queue_status_",tqm.id, " AS tqs ON tcm.status_id = tqs.status_id 
                WHERE tqs.is_close_status=1*/
                GROUP BY tcm.ticket_unique_id
            ) AS lasttcm ON lasttcm.ticket_unique_id = ttm.ticket_unique_id
            WHERE IFNULL(is_junk,0) = 0 AND IFNULL(is_deleted_ticket,0) = 0 AND 1 = 1 and is_draft!=1
            ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
            GROUP BY ttm.status_id 
        ) AS ticket_status_count ON tqs.status_id = ticket_status_count.status_id"
		  
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp2
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')');  
#SELECT @ticketquery2;
PREPARE stmt FROM @ticketquery2;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;


if (@id=1)
then
SET @QUERY = CONCAT(' SELECT queue_id,queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name,status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no 
Union All
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
Union All
SELECT  queue_id,tqm.queue as queue_name,status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp2 , ')m
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue,status_name
Union All
SELECT  queue_id,tqm.queue as queue_name,"Draft" status_name,"-1","#6fa8dc"colour_code,1,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp1 , ')a
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
)AS s  ORDER BY order_no;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
ELSE 	

SET @QUERY = CONCAT(' SELECT ifnull(queue_id,"") queue_id, ifnull(queue_name,"") queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name,status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no 																				
Union All
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
Union All
SELECT  queue_id,tqm.queue as queue_name,status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp2 , ')m
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue,status_name
Union All
SELECT  queue_id,tqm.queue as queue_name,"Draft" status_name,"-1","#6fa8dc"colour_code,1,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp1 , ')a
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
)AS s 
union all
SELECT queue_id, queue_name, status_name, "",colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT "0" queue_id,"ALL" queue_name,status_name, "" ,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from (', @tqmtemp , ')t1
Where 1=1 GROUP BY status_name,colour_code,order_no 
Union All
SELECT  "0"queue_id,"ALL" queue_name,"ALL" status_name, "" ,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp , ')y1
Union All
SELECT  "0" queue_id,"ALL" queue_name, status_name,"","#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp2 , ')m1
GROUP BY status_name
Union All
SELECT  "0" queue_id,"ALL" queue_name,"Draft" status_name,"","#6fa8dc"colour_code,1,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from (', @tqmtemp1 , ')a1
)AS s1  )as c
order by case when queue_id="0" then 1 ELSE 0 END,queue_id,
case when status_name="ALL" then 0
when status_name="Open" then 1
else 2 end,status_name;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
END if;

ELSE

SET @ticketquery = CONCAT('
SELECT GROUP_CONCAT(
    CONCAT(
        "	SELECT ",tqm.id, " Queue_id,ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code,
	COUNT(if(Date(ttm.created_date)=CURDATE(),1,null))cnt,
	COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL))Total
	FROM  tms_ticket_master_",tqm.id, " AS ttm 
	left JOIN tms_queue_status_",tqm.id, " as tqs on  ttm.status_id=tqs.status_id 
	JOIN tms_queue_category_",tqm.id, " as tqc ON ttm.category_id=tqc.category_id 
	',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,') ) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
	WHERE 1=1 and IFNULL(is_junk,0)=0 
	AND IFNULL(is_deleted_ticket,0)=0 and status=1 and is_draft!=1
	  ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
	GROUP BY ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code
 "
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
SET @ticketquery1 = CONCAT('
SELECT GROUP_CONCAT(
    CONCAT(
        "	SELECT ",tqm.id, " Queue_id,ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code,
	COUNT(if(Date(ttm.created_date)=CURDATE(),1,null))cnt,
	COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL))Total
	FROM  tms_ticket_master_",tqm.id, " AS ttm 
	left JOIN tms_queue_status_",tqm.id, " as tqs on  ttm.status_id=tqs.status_id 
	JOIN tms_queue_category_",tqm.id, " as tqc ON ttm.category_id=tqc.category_id 
	',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,') ) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
	WHERE 1=1 and IFNULL(is_junk,0)=0 
	AND IFNULL(is_deleted_ticket,0)=0 and status=1 and is_draft=1
	  ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
	GROUP BY ttm.category_id,category_name,
	ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code
 "
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp1
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery1;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;

SET @ticketquery2 = CONCAT('
SELECT GROUP_CONCAT(
    CONCAT(
        "	SELECT ",tqm.id, " Queue_id,ttm.category_id,category_name,
		"""" status_id,case when ticket_status_type=1 then ""Final"" when ticket_status_type in (2,3) then ""Non Final"" end  status_name,
	"""" is_default,"""" is_close_status,""#6fa8dc"" colour_code,
	COUNT(if(Date(ttm.created_date)=CURDATE(),1,null))cnt,
	COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL))Total
	FROM  tms_ticket_master_",tqm.id, " AS ttm 
	left JOIN tms_queue_status_",tqm.id, " as tqs on  ttm.status_id=tqs.status_id 
	JOIN tms_queue_category_",tqm.id, " as tqc ON ttm.category_id=tqc.category_id 
	',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,') ) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
	WHERE 1=1 and IFNULL(is_junk,0)=0 
	AND IFNULL(is_deleted_ticket,0)=0 and status=1 and is_draft!=1
	  ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
	GROUP BY ttm.category_id,category_name,ticket_status_type
 "
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp2
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery2;
PREPARE stmt FROM @ticketquery2;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;

if (@id=1) then

	SET @category_wise = CONCAT('SELECT queue_id,queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  From
(SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  
FROM (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Union All
SELECT queue_id,tqm.queue as queue_name,category_id,category_name,"0" status_id,status_name,"0" is_default,"0" is_close_status,colour_code,sum(cnt) cnt,sum(Total) Total  
FROM (', @tqmtemp2, ')m
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue,category_id,category_name,colour_code,status_name
Union All
SELECT  queue_id,tqm.queue as queue_name,category_id,category_name,"-1","Draft",0,0,colour_code,sum(cnt) cnt,sum(Total) 
FROM (', @tqmtemp1 , ')a
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue,category_id,category_name,colour_code)s
ORDER BY category_name; ');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

ELSE 

SET @category_wise = CONCAT(' SELECT queue_id,queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  From
(SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  
FROM (', @tqmtemp , ')t
join tms_queue_master tqm on queue_id=tqm.id
Union All
SELECT   "0","ALL","",category_name,"",status_name,is_default,is_close_status,colour_code,sum(cnt) cnt,sum(Total) 
FROM (', @tqmtemp , ')y
GROUP BY category_name,status_name,is_default,is_close_status,colour_code
Union All
SELECT queue_id,tqm.queue as queue_name,category_id,category_name,"0" status_id,status_name,"0" is_default, 0 is_close_status,colour_code,sum(cnt) cnt,sum(Total) Total  
FROM (', @tqmtemp2,')m
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue,category_id,category_name,colour_code,status_name
Union All
SELECT "0" queue_id,"ALL","",category_name,"",status_name,"0" is_default, 0 is_close_status,colour_code,sum(cnt) cnt,sum(Total) Total  
FROM (', @tqmtemp2,')m1
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY category_name,colour_code,status_name
Union All
SELECT  queue_id,tqm.queue as queue_name,category_id,category_name,-1,"Draft",0,0,colour_code,sum(cnt) cnt,sum(Total) 
FROM (', @tqmtemp1 , ')a
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue,category_id,category_name,colour_code
Union All
SELECT  "0" queue_id,"ALL" queue_name,"",category_name,-1,"Draft",0,0,colour_code,sum(cnt) cnt,sum(Total) 
FROM (', @tqmtemp1 , ')a1
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY category_name,colour_code)s
ORDER BY case when queue_id="0" then 1 ELSE 0 END,queue_id,category_name,
status_name;');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

END if; 		
END if; 
DROP TABLE IF EXISTS temp_ticketstatus;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**
CREATE PROCEDURE `getTicketCountWithInTatOutOfTat_20241203`(
	IN `qid` VARCHAR(50),
	IN `cond` TEXT,
	IN `userids` TEXT,
	IN `isadmin` TINYINT,
	IN `fromdate` VARCHAR(100),
	IN `todate` VARCHAR(100),
	IN `is_category` TINYINT,
	IN `fullcontrol` INT,
	IN `all_ticket` INT
)
BEGIN
DROP TABLE IF EXISTS ticket_tattemp;
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

SET SESSION group_concat_max_len = 1000000; 


set fromdate=if(IFNULL(fromdate,"")!="",CONCAT(' and date(ttm.created_date)>=''',fromdate,''' '),' ');
set todate=if(IFNULL(todate,"")!="",CONCAT(' and date(ttm.created_date)<=''',todate,''' '),' ');

SET @Sql_Query=CONCAT ('SELECT COUNT(*) into @id  FROM tms_queue_master 
WHERE id IN (',qid,')');
#SELECT @Sql_Query;
PREPARE stmt FROM @Sql_Query;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;	

SET @tqmtemp = '';

if is_category = 0 then
SET @ticketquery = CONCAT('SELECT GROUP_CONCAT(
    CONCAT(
        "SELECT ",tqm.id," Queue_id,tqs.status_name,ifnull(is_draft,0) is_draft,ifnull(status_name1,""Non Final"") status_name1, tqs.status_id, tqs.colour_code, tqs.order_no, tqs.is_close_status,
            IFNULL(today_all,0) AS today_all, IFNULL(today_out_of_tat,0) AS today_out_of_tat,
            IFNULL(today_with_in_tat,0) AS today_with_in_tat, IFNULL(out_of_tat_ALL,0) AS out_of_tat_ALL,
            IFNULL(with_in_tat_ALL,0) AS with_in_tat_ALL, IFNULL(Total,0) AS Total
        FROM tms_queue_status_",tqm.id, " AS tqs 
        LEFT JOIN (
            SELECT tqs.status_id,ifnull(is_draft,0) is_draft,case when ticket_status_type=1 then ""Final"" when ticket_status_type in (2,3) then ""Non Final"" end status_name1,
            COUNT(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),',
					 (Date(ttm.created_date)=CURDATE()',if(fullcontrol=1,")",CONCAT(' or date(ttm.assigned_on)=CURDATE())')),'),1,null)) AS today_all,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) > tqp.tat * 60 , 1, 0)) AS today_out_of_tat,
                SUM(IF(if(date(reopen_date) is not null,(date(reopen_date)=CURDATE() or Date(ttm.created_date)=CURDATE()),
					 (Date(ttm.created_date)=CURDATE()))
					 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <= tqp.tat * 60 , 1, 0)) AS today_with_in_tat,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS out_of_tat_ALL,
                SUM(IF(TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
                IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <=tqp.tat * 60  ',fromdate,todate,'  ,1,0)) AS with_in_tat_ALL,
                COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL)) AS Total
            FROM tms_ticket_master_",tqm.id, " AS ttm 
            RIGHT JOIN tms_queue_status_",tqm.id, " AS tqs ON ttm.status_id = tqs.status_id 
            LEFT JOIN tms_queue_priority_",tqm.id, " AS tqp ON ttm.priority_id = tqp.priority_id 
            ',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,')) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
            LEFT JOIN (
                SELECT MAX(tcm.conversation_date) AS last_con_date, tcm.ticket_unique_id 
                FROM tms_conversation_master_",tqm.id, " AS tcm 
                GROUP BY tcm.ticket_unique_id
            ) AS lasttcm ON lasttcm.ticket_unique_id = ttm.ticket_unique_id
            WHERE IFNULL(is_junk,0) = 0 AND IFNULL(is_deleted_ticket,0) = 0 AND 1 = 1 /*and is_draft!=1*/
            ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
            GROUP BY tqs.status_id,is_draft,ticket_status_type 
        )AS ticket_status_count ON tqs.status_id = ticket_status_count.status_id"
		  
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')');  
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
SET @tablequery=CONCAT('CREATE TABLE ticket_tattemp SELECT * FROM (', @tqmtemp , ')t');

PREPARE stmt FROM @tablequery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

if (@id=1)
then
SET @QUERY = CONCAT(' SELECT queue_id,queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name, status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no  
Union All
SELECT queue_id,tqm.queue as queue_name,"Draft" status_name, "-1"  status_id,"#6fa8dc" colour_code,"0" order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id 
Where 1=1 and is_draft=1 
GROUP BY queue_id,tqm.queue
Union ALL
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
Union All
SELECT  queue_id,tqm.queue as queue_name, status_name1 status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY queue_id,tqm.queue,status_name1
)AS s  ORDER BY order_no;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
ELSE 	

SET @QUERY = CONCAT(' SELECT ifnull(queue_id,"") queue_id, ifnull(queue_name,"") queue_name, status_name,status_id,colour_code,ifnull(today_all,0)today_all,ifnull(today_with_in_tat,0)today_with_in_tat,ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(out_of_tat_ALL,0)out_of_tat_ALL, ifnull(total,0)total FROM 
(SELECT queue_id,tqm.queue as queue_name, status_name,status_id,colour_code,order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY queue_id,tqm.queue,status_name,status_id,colour_code,order_no  
Union All
SELECT queue_id,tqm.queue as queue_name,"Draft" status_name, "-1"  status_id,"#6fa8dc" colour_code,"0" order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id 
Where 1=1 and is_draft=1 
GROUP BY queue_id,tqm.queue
Union ALL
SELECT  queue_id,tqm.queue as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
GROUP BY queue_id,tqm.queue
Union All
SELECT  queue_id,tqm.queue as queue_name, status_name1 status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY queue_id,tqm.queue,status_name1
union all
SELECT "0"queue_id,"ALL" queue_name, status_name,""status_id,colour_code,"0"order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
Where 1=1 GROUP BY status_name,colour_code  
Union All
SELECT "0" queue_id,"ALL" queue_name,"Draft" status_name, ""  status_id,"#6fa8dc" colour_code,"0" order_no,sum(today_all)today_all,sum(today_with_in_tat)today_with_in_tat,sum(today_out_of_tat)today_out_of_tat,sum(with_in_tat_ALL)with_in_tat_ALL,sum(out_of_tat_ALL)out_of_tat_ALL,(sum(with_in_tat_ALL)+sum(out_of_tat_ALL))total
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id 
Where 1=1 and is_draft=1 
GROUP BY queue_id,tqm.queue
Union ALL
SELECT "0" queue_id,"ALL" as queue_name,"ALL" status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
Union All
SELECT "0" queue_id,"ALL" as queue_name, status_name1 status_name,0,"#6fa8dc"colour_code,0,sum(today_all)as today_all,sum(today_with_in_tat)as today_with_in_tat, sum(today_out_of_tat) as today_out_of_tat,SUM(with_in_tat_ALL) as with_in_tat_ALL,SUM(out_of_tat_ALL)as out_of_tat_ALL,sum(with_in_tat_ALL+out_of_tat_ALL )as card_total 
from ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY status_name1
 )as c
order by case when queue_id="0" then 1 ELSE 0 END,queue_id,
case when status_name="ALL" then 0
when status_name="Open" then 1
else 2 end,status_name;');

#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
END if;

ELSE

SET @ticketquery = CONCAT('
SELECT GROUP_CONCAT(
    CONCAT(
        "	SELECT ",tqm.id, " Queue_id,ttm.category_id,category_name,
        ifnull(is_draft,0) is_draft,
	case when ticket_status_type=1 then ""Final"" when ticket_status_type in (2,3) then ""Non Final"" end status_name1,  
	tqs.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code,
	COUNT(if(Date(ttm.created_date)=CURDATE(),1,null))cnt,
	COUNT(if(1=1 ', fromdate,todate ,' ,1,NULL))Total
	FROM  tms_ticket_master_",tqm.id, " AS ttm 
	RIGHT JOIN tms_queue_status_",tqm.id, " as tqs on  ttm.status_id=tqs.status_id 
	JOIN tms_queue_category_",tqm.id, " as tqc ON ttm.category_id=tqc.category_id 
	',if(IFNULL(userids,"")!="1" AND IFNULL(all_ticket,0)!=1,CONCAT('  LEFT JOIN (SELECT group_concat(DISTINCT status_id) status_id
						FROM tms_user_master tum 
						JOIN tms_statuspermission_",tqm.id, "  on  tms_statuspermission_",tqm.id, ".user_type = tum.user_type 
						WHERE tms_statuspermission_",tqm.id, ".is_checked=1 AND tum.user_id in (',userids,') ) tsptab ON tsptab.status_id = ttm.status_id'),"") ,'
	WHERE 1=1 and IFNULL(is_junk,0)=0 
	AND IFNULL(is_deleted_ticket,0)=0 and status=1 
	  ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userids,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userids,') '),"") ,' 
	GROUP BY ttm.category_id,category_name,
	tqs.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code,is_draft,ticket_status_type
 "
    )
    SEPARATOR " UNION ALL "
)
 INTO @tqmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')'); 
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
SET @tablequery=CONCAT('CREATE TABLE ticket_tattemp SELECT * FROM (', @tqmtemp , ')t');

PREPARE stmt FROM @tablequery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


if (@id=1) then

	SET @category_wise = CONCAT('SELECT queue_id,queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  From
(SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,
is_default,is_close_status, colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
group by queue_id,tqm.queue,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code
Union All
SELECT queue_id,tqm.queue as queue_name,category_id,category_name, "-1" status_id,"Draft" status_name,
is_default,is_close_status, "#6fa8dc"  colour_code,cnt,Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft=1
Union All
SELECT queue_id,tqm.queue as queue_name,category_id,category_name,"0",status_name1 status_name,
"0" is_default,"0" is_close_status,"#6fa8dc"colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY queue_id,tqm.queue,category_id,category_name,status_name1
)s
ORDER BY category_name; ');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

ELSE 

SET @category_wise = CONCAT(' SELECT queue_id,queue_name,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code,cnt,Total  From
(SELECT queue_id,tqm.queue as queue_name,category_id,category_name,status_id,status_name,
is_default,is_close_status, colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
group by queue_id,tqm.queue,category_id,category_name,status_id,status_name,is_default,is_close_status,colour_code
Union All
SELECT queue_id,tqm.queue as queue_name,category_id,category_name, "-1" status_id,"Draft" status_name,
is_default,is_close_status, "#6fa8dc"  colour_code,cnt,Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft=1
Union All
SELECT queue_id,tqm.queue as queue_name,category_id,category_name,"0",status_name1 status_name,
"0" is_default,"0" is_close_status,"#6fa8dc"colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY queue_id,tqm.queue,category_id,category_name,status_name1
union all
SELECT 0,"ALL" as queue_name,"",category_name,"" status_id,status_name,
is_default,is_close_status,colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
group by status_name,is_default,is_close_status,colour_code,category_name
Union All
SELECT 0,"ALL" as queue_name,"",category_name,"" status_id,"Draft" status_name,
0 is_default,0 is_close_status, "#6fa8dc"  colour_code,cnt,Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft=1
Union All
SELECT 0,"ALL" as queue_name,"",category_name,"",status_name1 status_name,
"0" is_default,"0" is_close_status,"#6fa8dc"colour_code,sum(cnt) cnt,sum(Total) Total  
FROM ticket_tattemp
join tms_queue_master tqm on queue_id=tqm.id
where is_draft!=1
GROUP BY category_name,status_name1
)s
ORDER BY case when queue_id="0" then 1 ELSE 0 END,queue_id,category_name,
status_name;');

#SELECT @category_wise;
PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;

END if; 		
END if; 
DROP TABLE IF EXISTS ticket_tattemp;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**
CREATE PROCEDURE `getTicketDetail`(
	IN `queue_id` VARCHAR(50),
	IN `cond` LONGTEXT,
	IN `reporttype` VARCHAR(50),
	IN `dynamicSelect` TEXT,
	IN `dynamicJoin` TEXT,
	IN `sorting` VARCHAR(50),
	IN `rowlimit` VARCHAR(10),
	IN `type` VARCHAR(50),
	IN `fromdate` VARCHAR(20),
	IN `todate` VARCHAR(20)
)
    DETERMINISTIC
BEGIN
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

if IFNULL(TYPE,"")="" then

 SET @COLUMNS=CONCAT('SELECT ifnull(SUM(t5.Count),0) AS is_attachment,t1.ticket_prefix,t1.is_draft, t1.ticket_unique_id, t1.ticket_id, t1.person_name,
t1.mobile_no, t1.unique_id, t1.parent_id, t1.subject, t1.start_date, t1.cc_email, t1.bcc_email, t1.start_mode, t1.status_id, t1.priority_id, t1.queue_id,
DATE_FORMAT(t1.last_updated_on,"%d-%m-%Y %H:%i:%s") last_updated_on, t1.is_read, t1.read_by, t1.read_date, 
DATE_FORMAT(t1.mail_date,"%d-%m-%Y %H:%i:%s") mail_date, t1.is_assigned, t4.user_name as assigned_to, t1.assigned_by, 
DATE_FORMAT(t1.assigned_on,"%d-%m-%Y %H:%i:%s") assigned_on,
t1.last_updated_by, t1.phone_no, t1.category_id, t1.subcategory_id, t1.follow_up_date, t1.ticket_created_by, t1.is_assigned_open_ticket, t1.remarks,
t1.is_replied_mail, t1.is_forward_mail, 
DATE_FORMAT(t1.created_date,"%d-%m-%Y %H:%i:%s") AS created_date, 
CASE  WHEN TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) >= 24 THEN case when length(FLOOR(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) / 24))<=1 then CONCAT("0",FLOOR(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) / 24), " days") else CONCAT(FLOOR(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) / 24), " days") end ELSE 
CONCAT(LPAD(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()), 2, "0"), ":", LPAD(MOD(TIMESTAMPDIFF(MINUTE, t1.created_date, NOW()), 60), 2, "0"), ":", 
LPAD(MOD(TIMESTAMPDIFF(SECOND, t1.created_date, NOW()), 60), 2, "0") )  END AS duration,
t1.happy_code, t1.escalation_id, t1.last_escalation_on, t1.hold_date, t1.incoming_mail_id,
t1.is_new,t1.parent_ticket_id, t1.parent_ticket_id_text, t1.is_junk, t1.is_deleted_ticket, t1.is_closed,t1.is_auto, t1.deleted_date,
if(t4.user_name is not null,ifnull(tumby.user_name,"Auto"),"") as assigned_by_with_name,
IF(0=1,mask_email(t1.to_email,"*"),t1.to_email) AS to_email,IF(0=1,mask_email(t1.from_email,"*"),t1.from_email) AS from_email,
t2.priority_name, t2.colour_code as prClr, t3.status_name,
t3.colour_code as stClr,t3.is_close_status,t4.user_name, `conversation_type` AS `Type`,
DATE_FORMAT(Last_conversation_date,"%d-%m-%Y %H:%i:%s") Last_conversation_date,
DATE_FORMAT(First_conversation_date,"%d-%m-%Y %H:%i:%s") First_conversation_date,tctm.title conversation_mode ',IFNULL(dynamicSelect, ''));
 
SET @table = CONCAT('FROM tms_ticket_master_',queue_id,' as t1
LEFT JOIN tms_queue_priority_',queue_id,' as t2 ON t1.priority_id = t2.priority_id
LEFT JOIN tms_queue_status_',queue_id,' as t3 ON t1.status_id = t3.status_id
LEFT JOIN tms_user_master as t4 ON t1.assigned_to = t4.id
LEFT JOIN tms_user_master as tumby ON t1.assigned_by = tumby.user_id
LEFT JOIN tms_conversation_type_master tctm ON tctm.id=t1.start_mode
LEFT JOIN (select ticket_unique_id,count(1) Count from tms_conversation_attachements_',queue_id,' group by ticket_unique_id) as t5 ON t1.ticket_unique_id = t5.ticket_unique_id
LEFT JOIN (SELECT MAX(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_id ELSE "" end) AS conversation_ids, 
max(conversation_date) Last_conversation_date,min(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_date end) First_conversation_date, tcm.ticket_unique_id
FROM tms_conversation_master_',queue_id,' as tcm
join tms_ticket_master_',queue_id,' as t1 ON tcm.ticket_unique_id = t1.ticket_unique_id
',if(IFNULL(fromdate,"")!="" AND IFNULL(todate,"")!="",CONCAT(' where 1=1 AND t1.created_date >="',fromdate,'" AND t1.created_date <="',todate,'"'),""),'
GROUP BY tcm.ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = t1.ticket_unique_id
LEFT JOIN tms_conversation_master_',queue_id,' as tcm ON Last_con.conversation_ids=tcm.conversation_id
',IFNULL(dynamicJoin, ''));

SET @WHERE = CONCAT(' WHERE 1=1 ');


IF cond != '' THEN
        SET @where    = CONCAT(@WHERE, ' AND ' , cond);
    END IF;


SET @GROUP = ' GROUP BY t1.ticket_unique_id,conversation_type,tumby.user_name,First_conversation_date,Last_conversation_date
ORDER BY is_new desc';

If (ifnull(sorting,"")!="" ) then 

SET @GROUP=CONCAT(@GROUP,' ,',sorting,'');
END if;

If (ifnull(rowlimit,"")!="" ) then 

SET @GROUP=CONCAT(@GROUP,' limit ',rowlimit,'');
END if;

SET @query_string = CONCAT(@COLUMNS, " ", @table, " ", @where, " ", @GROUP);
#SELECT @query_string;
PREPARE stmt FROM @query_string;
EXECUTE stmt;   
DEALLOCATE PREPARE stmt;

SET @COLUMNS1=CONCAT('SELECT COUNT(distinct t1.ticket_unique_id) Count ');


SET @query_string1 = CONCAT(@COLUMNS1, " ", @TABLE, " ", @WHERE);
#SELECT @query_string1;
PREPARE stmt FROM @query_string1;
EXECUTE stmt;   
DEALLOCATE PREPARE stmt;

END if;

if IFNULL(TYPE,"")="Agent" then

 SET @query_string=CONCAT('SELECT  t4.user_name as assigned_to,COUNT(1) Total_Ticket,
SUM(case when ticket_status_type in (2,3) then 1 ELSE 0 END) Non_Final_Status,
SUM(case when ticket_status_type=1 then 1 ELSE 0 END) Close
FROM tms_ticket_master_',queue_id,' as t1
LEFT JOIN tms_queue_priority_',queue_id,' as t2 ON t1.priority_id = t2.priority_id
LEFT JOIN tms_queue_status_',queue_id,' as t3 ON t1.status_id = t3.status_id
LEFT JOIN tms_user_master as t4 ON t1.assigned_to = t4.id
LEFT JOIN tms_user_master as tumby ON t1.assigned_by = tumby.user_id
LEFT JOIN tms_conversation_type_master tctm ON tctm.id=t1.start_mode
LEFT JOIN (select ticket_unique_id,count(1) Count from tms_conversation_attachements_',queue_id,' group by ticket_unique_id) as t5 ON t1.ticket_unique_id = t5.ticket_unique_id
LEFT JOIN (SELECT MAX(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_id ELSE "" end) AS conversation_ids, 
max(conversation_date) Last_conversation_date, ticket_unique_id
FROM tms_conversation_master_',queue_id,' as tcm
GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = t1.ticket_unique_id
LEFT JOIN tms_conversation_master_',queue_id,' as tcm ON Last_con.conversation_ids=tcm.conversation_id
',IFNULL(dynamicJoin, ''),'
where 1=1 ',if(IFNULL(cond,"")!="",CONCAT(' AND ' , cond,''),""),'
GROUP BY t4.user_name ',
if(IFNULL(rowlimit,"")!="",CONCAT(' LIMIT ' , rowlimit,''),""),''); 

PREPARE stmt FROM @query_string;
EXECUTE stmt;   
DEALLOCATE PREPARE stmt;


 SET @query_string1=CONCAT('SELECT COUNT(distinct t4.user_name) as COUNT
FROM tms_ticket_master_',queue_id,' as t1
LEFT JOIN tms_queue_priority_',queue_id,' as t2 ON t1.priority_id = t2.priority_id
LEFT JOIN tms_queue_status_',queue_id,' as t3 ON t1.status_id = t3.status_id
LEFT JOIN tms_user_master as t4 ON t1.assigned_to = t4.id
LEFT JOIN tms_user_master as tumby ON t1.assigned_by = tumby.user_id
LEFT JOIN tms_conversation_type_master tctm ON tctm.id=t1.start_mode
LEFT JOIN (select ticket_unique_id,count(1) Count from tms_conversation_attachements_',queue_id,' group by ticket_unique_id) as t5 ON t1.ticket_unique_id = t5.ticket_unique_id
LEFT JOIN (SELECT MAX(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_id ELSE "" end) AS conversation_ids, 
max(conversation_date) Last_conversation_date, ticket_unique_id
FROM tms_conversation_master_',queue_id,' as tcm
GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = t1.ticket_unique_id
LEFT JOIN tms_conversation_master_',queue_id,' as tcm ON Last_con.conversation_ids=tcm.conversation_id
',IFNULL(dynamicJoin, ''),'
where 1=1 ',if(IFNULL(cond,"")!="",CONCAT(' AND ' , cond,''),""),'
'); 

PREPARE stmt FROM @query_string1;
EXECUTE stmt;   
DEALLOCATE PREPARE stmt;

END if;

if IFNULL(TYPE,"")="Domain" then

 SET @query_string=CONCAT('SELECT left(insert(t1.from_email,1,INSTR(CONCAT(t1.from_email,"@"),"@"),""),instr(insert(t1.from_email,1,INSTR(CONCAT(t1.from_email,"@"),"@"),""),".")-1) Domain,
 COUNT(1) Total_Ticket,
SUM(case when ticket_status_type in (2,3) then 1 ELSE 0 END) Non_Final_Status,
SUM(case when ticket_status_type=1 then 1 ELSE 0 END) Close
FROM tms_ticket_master_',queue_id,' as t1
LEFT JOIN tms_queue_priority_',queue_id,' as t2 ON t1.priority_id = t2.priority_id
LEFT JOIN tms_queue_status_',queue_id,' as t3 ON t1.status_id = t3.status_id
LEFT JOIN tms_user_master as t4 ON t1.assigned_to = t4.id
LEFT JOIN tms_user_master as tumby ON t1.assigned_by = tumby.user_id
LEFT JOIN tms_conversation_type_master tctm ON tctm.id=t1.start_mode
LEFT JOIN (select ticket_unique_id,count(1) Count from tms_conversation_attachements_',queue_id,' group by ticket_unique_id) as t5 ON t1.ticket_unique_id = t5.ticket_unique_id
LEFT JOIN (SELECT MAX(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_id ELSE "" end) AS conversation_ids, 
max(conversation_date) Last_conversation_date, ticket_unique_id
FROM tms_conversation_master_',queue_id,' as tcm
GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = t1.ticket_unique_id
LEFT JOIN tms_conversation_master_',queue_id,' as tcm ON Last_con.conversation_ids=tcm.conversation_id
',IFNULL(dynamicJoin, ''),'
where 1=1 ',if(IFNULL(cond,"")!="",CONCAT(' AND ' , cond,''),""),'
GROUP BY left(insert(t1.from_email,1,INSTR(CONCAT(t1.from_email,"@"),"@"), ""),instr(insert(t1.from_email,1,INSTR(CONCAT(t1.from_email,"@"),"@"), ""),".")-1)
',
if(IFNULL(rowlimit,"")!="",CONCAT(' LIMIT ' , rowlimit,''),""),''); 

PREPARE stmt FROM @query_string;
EXECUTE stmt;   
DEALLOCATE PREPARE stmt;

SET @query_string=CONCAT('SELECT COUNT(distinct left(insert(t1.from_email,1,INSTR(CONCAT(t1.from_email,"@"),"@"),""),instr(insert(t1.from_email,1,INSTR(CONCAT(t1.from_email,"@"),"@"),""),".")-1)) Count
FROM tms_ticket_master_',queue_id,' as t1
LEFT JOIN tms_queue_priority_',queue_id,' as t2 ON t1.priority_id = t2.priority_id
LEFT JOIN tms_queue_status_',queue_id,' as t3 ON t1.status_id = t3.status_id
LEFT JOIN tms_user_master as t4 ON t1.assigned_to = t4.id
LEFT JOIN tms_user_master as tumby ON t1.assigned_by = tumby.user_id
LEFT JOIN tms_conversation_type_master tctm ON tctm.id=t1.start_mode
LEFT JOIN (select ticket_unique_id,count(1) Count from tms_conversation_attachements_',queue_id,' group by ticket_unique_id) as t5 ON t1.ticket_unique_id = t5.ticket_unique_id
LEFT JOIN (SELECT MAX(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_id ELSE "" end) AS conversation_ids, 
max(conversation_date) Last_conversation_date, ticket_unique_id
FROM tms_conversation_master_',queue_id,' as tcm
GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = t1.ticket_unique_id
LEFT JOIN tms_conversation_master_',queue_id,' as tcm ON Last_con.conversation_ids=tcm.conversation_id
',IFNULL(dynamicJoin, ''),'
where 1=1 ',if(IFNULL(cond,"")!="",CONCAT(' AND ' , cond,''),""),''); 

PREPARE stmt FROM @query_string;
EXECUTE stmt;   
DEALLOCATE PREPARE stmt;

END if;

SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**
CREATE PROCEDURE `getTicketDetail_20240704`(
	IN `queue_id` VARCHAR(50),
	IN `cond` LONGTEXT,
	IN `reporttype` VARCHAR(50),
	IN `dynamicSelect` TEXT,
	IN `dynamicJoin` TEXT,
	IN `sorting` VARCHAR(50),
	IN `rowlimit` VARCHAR(10)
)
    DETERMINISTIC
BEGIN
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

 SET @COLUMNS=CONCAT('SELECT COUNT(t5.ticket_unique_id) AS is_attachment,t1.ticket_prefix, t1.ticket_unique_id, t1.ticket_id, t1.person_name,
t1.mobile_no, t1.unique_id, t1.parent_id, t1.subject, t1.start_date, t1.cc_email, t1.bcc_email, t1.start_mode, t1.status_id, t1.priority_id, t1.queue_id,
DATE_FORMAT(t1.last_updated_on,"%d-%m-%Y %H:%i:%s") last_updated_on, t1.is_read, t1.read_by, t1.read_date, 
DATE_FORMAT(t1.mail_date,"%d-%m-%Y %H:%i:%s") mail_date, t1.is_assigned, t4.user_name as assigned_to, t1.assigned_by, 
DATE_FORMAT(t1.assigned_on,"%d-%m-%Y %H:%i:%s") assigned_on,
t1.last_updated_by, t1.phone_no, t1.category_id, t1.subcategory_id, t1.follow_up_date, t1.ticket_created_by, t1.is_assigned_open_ticket, t1.remarks,
t1.is_replied_mail, t1.is_forward_mail, 
DATE_FORMAT(t1.created_date,"%d-%m-%Y %H:%i:%s") AS created_date, 
CASE  WHEN TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) >= 24 THEN CONCAT(FLOOR(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) / 24), " days") ELSE 
CONCAT(LPAD(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()), 2, "0"), ":", LPAD(MOD(TIMESTAMPDIFF(MINUTE, t1.created_date, NOW()), 60), 2, "0"), ":", 
LPAD(MOD(TIMESTAMPDIFF(SECOND, t1.created_date, NOW()), 60), 2, "0") )  END AS duration,
t1.happy_code, t1.escalation_id, t1.last_escalation_on, t1.hold_date, t1.incoming_mail_id,
t1.is_new,t1.parent_ticket_id, t1.parent_ticket_id_text, t1.is_junk, t1.is_deleted_ticket, t1.is_closed,t1.is_auto, t1.deleted_date,
ifnull(tumby.user_name,"Auto") as assigned_by_with_name,
IF(0=1,mask_email(t1.to_email,"*"),t1.to_email) AS to_email,IF(0=1,mask_email(t1.from_email,"*"),t1.from_email) AS from_email,
t2.priority_name, t2.colour_code as prClr, t3.status_name,
t3.colour_code as stClr,t3.is_close_status,t4.user_name, `conversation_type` AS `Type` ',IFNULL(dynamicSelect, ''));

 
SET @table = CONCAT('FROM tms_ticket_master_',queue_id,' as t1
LEFT JOIN tms_queue_priority_',queue_id,' as t2 ON t1.priority_id = t2.priority_id
LEFT JOIN tms_queue_status_',queue_id,' as t3 ON t1.status_id = t3.status_id
LEFT JOIN tms_user_master as t4 ON t1.assigned_to = t4.id
LEFT JOIN tms_user_master as tumby ON t1.assigned_by = tumby.user_id
LEFT JOIN tms_conversation_attachements_',queue_id,' as t5 ON t1.ticket_unique_id = t5.ticket_unique_id
LEFT JOIN (SELECT MAX(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_id ELSE "" end) AS conversation_ids, 
max(conversation_date) Last_conversation_date, ticket_unique_id
FROM tms_conversation_master_',queue_id,' as tcm
GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = t1.ticket_unique_id
LEFT JOIN tms_conversation_master_',queue_id,' as tcm ON Last_con.conversation_ids=tcm.conversation_id
',IFNULL(dynamicJoin, ''));

SET @WHERE = CONCAT(' WHERE 1=1 ');


IF cond != '' THEN
        SET @where    = CONCAT(@WHERE, ' AND ' , cond);
    END IF;


SET @GROUP = ' GROUP BY t1.ticket_unique_id,conversation_type,ifnull(tumby.user_name,"Auto")
ORDER BY is_new desc';

If (ifnull(sorting,"")!="" ) then 

SET @GROUP=CONCAT(@GROUP,' ,',sorting,'');
END if;

If (ifnull(rowlimit,"")!="" ) then 

SET @GROUP=CONCAT(@GROUP,' limit ',rowlimit,'');
END if;

SET @query_string = CONCAT(@COLUMNS, " ", @table, " ", @where, " ", @GROUP);
#SELECT @query_string;
PREPARE stmt_agent_login_log FROM @query_string;
EXECUTE stmt_agent_login_log;   
DEALLOCATE PREPARE stmt_agent_login_log;

SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**
CREATE PROCEDURE `getTicketDetail_20240829`(
	IN `queue_id` VARCHAR(50),
	IN `cond` LONGTEXT,
	IN `reporttype` VARCHAR(50),
	IN `dynamicSelect` TEXT,
	IN `dynamicJoin` TEXT,
	IN `sorting` VARCHAR(50),
	IN `rowlimit` VARCHAR(10)
)
    DETERMINISTIC
BEGIN
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

 SET @COLUMNS=CONCAT('SELECT COUNT(t5.ticket_unique_id) AS is_attachment,t1.ticket_prefix,t1.is_draft, t1.ticket_unique_id, t1.ticket_id, t1.person_name,
t1.mobile_no, t1.unique_id, t1.parent_id, t1.subject, t1.start_date, t1.cc_email, t1.bcc_email, t1.start_mode, t1.status_id, t1.priority_id, t1.queue_id,
DATE_FORMAT(t1.last_updated_on,"%d-%m-%Y %H:%i:%s") last_updated_on, t1.is_read, t1.read_by, t1.read_date, 
DATE_FORMAT(t1.mail_date,"%d-%m-%Y %H:%i:%s") mail_date, t1.is_assigned, t4.user_name as assigned_to, t1.assigned_by, 
DATE_FORMAT(t1.assigned_on,"%d-%m-%Y %H:%i:%s") assigned_on,
t1.last_updated_by, t1.phone_no, t1.category_id, t1.subcategory_id, t1.follow_up_date, t1.ticket_created_by, t1.is_assigned_open_ticket, t1.remarks,
t1.is_replied_mail, t1.is_forward_mail, 
DATE_FORMAT(t1.created_date,"%d-%m-%Y %H:%i:%s") AS created_date, 
CASE  WHEN TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) >= 24 THEN CONCAT(FLOOR(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()) / 24), " days") ELSE 
CONCAT(LPAD(TIMESTAMPDIFF(HOUR, t1.created_date, NOW()), 2, "0"), ":", LPAD(MOD(TIMESTAMPDIFF(MINUTE, t1.created_date, NOW()), 60), 2, "0"), ":", 
LPAD(MOD(TIMESTAMPDIFF(SECOND, t1.created_date, NOW()), 60), 2, "0") )  END AS duration,
t1.happy_code, t1.escalation_id, t1.last_escalation_on, t1.hold_date, t1.incoming_mail_id,
t1.is_new,t1.parent_ticket_id, t1.parent_ticket_id_text, t1.is_junk, t1.is_deleted_ticket, t1.is_closed,t1.is_auto, t1.deleted_date,
if(t4.user_name is not null,ifnull(tumby.user_name,"Auto"),"") as assigned_by_with_name,
IF(0=1,mask_email(t1.to_email,"*"),t1.to_email) AS to_email,IF(0=1,mask_email(t1.from_email,"*"),t1.from_email) AS from_email,
t2.priority_name, t2.colour_code as prClr, t3.status_name,
t3.colour_code as stClr,t3.is_close_status,t4.user_name, `conversation_type` AS `Type` ',IFNULL(dynamicSelect, ''));

 
SET @table = CONCAT('FROM tms_ticket_master_',queue_id,' as t1
LEFT JOIN tms_queue_priority_',queue_id,' as t2 ON t1.priority_id = t2.priority_id
LEFT JOIN tms_queue_status_',queue_id,' as t3 ON t1.status_id = t3.status_id
LEFT JOIN tms_user_master as t4 ON t1.assigned_to = t4.id
LEFT JOIN tms_user_master as tumby ON t1.assigned_by = tumby.user_id
LEFT JOIN tms_conversation_attachements_',queue_id,' as t5 ON t1.ticket_unique_id = t5.ticket_unique_id
LEFT JOIN (SELECT MAX(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_id ELSE "" end) AS conversation_ids, 
max(conversation_date) Last_conversation_date, ticket_unique_id
FROM tms_conversation_master_',queue_id,' as tcm
GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = t1.ticket_unique_id
LEFT JOIN tms_conversation_master_',queue_id,' as tcm ON Last_con.conversation_ids=tcm.conversation_id
',IFNULL(dynamicJoin, ''));

SET @WHERE = CONCAT(' WHERE 1=1 ');


IF cond != '' THEN
        SET @where    = CONCAT(@WHERE, ' AND ' , cond);
    END IF;


SET @GROUP = ' GROUP BY t1.ticket_unique_id,conversation_type,tumby.user_name
ORDER BY is_new desc';

If (ifnull(sorting,"")!="" ) then 

SET @GROUP=CONCAT(@GROUP,' ,',sorting,'');
END if;

If (ifnull(rowlimit,"")!="" ) then 

SET @GROUP=CONCAT(@GROUP,' limit ',rowlimit,'');
END if;

SET @query_string = CONCAT(@COLUMNS, " ", @table, " ", @where, " ", @GROUP);
#SELECT @query_string;
PREPARE stmt FROM @query_string;
EXECUTE stmt;   
DEALLOCATE PREPARE stmt;

SET @COLUMNS1=CONCAT('SELECT COUNT(distinct t1.ticket_unique_id) Count ');

 
SET @TABLE1 = CONCAT('FROM tms_ticket_master_',queue_id,' as t1
LEFT JOIN tms_queue_priority_',queue_id,' as t2 ON t1.priority_id = t2.priority_id
LEFT JOIN tms_queue_status_',queue_id,' as t3 ON t1.status_id = t3.status_id
LEFT JOIN tms_user_master as t4 ON t1.assigned_to = t4.id
LEFT JOIN tms_user_master as tumby ON t1.assigned_by = tumby.user_id
LEFT JOIN tms_conversation_attachements_',queue_id,' as t5 ON t1.ticket_unique_id = t5.ticket_unique_id
LEFT JOIN (SELECT MAX(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_id ELSE "" end) AS conversation_ids, 
max(conversation_date) Last_conversation_date, ticket_unique_id
FROM tms_conversation_master_',queue_id,' as tcm
GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = t1.ticket_unique_id
LEFT JOIN tms_conversation_master_',queue_id,' as tcm ON Last_con.conversation_ids=tcm.conversation_id
',IFNULL(dynamicJoin, ''));

SET @WHERE1 = CONCAT(' WHERE 1=1 ');


IF cond != '' THEN
        SET @WHERE1    = CONCAT(@WHERE1, ' AND ' , cond);
    END IF;


SET @GROUP1 = '
ORDER BY is_new desc';

If (ifnull(sorting,"")!="" ) then 

SET @GROUP=CONCAT(@GROUP1,' ,',sorting,'');
END if;


SET @query_string1 = CONCAT(@COLUMNS1, " ", @TABLE1, " ", @WHERE1, " ", @GROUP1);
#SELECT @query_string1;
PREPARE stmt FROM @query_string1;
EXECUTE stmt;   
DEALLOCATE PREPARE stmt;


SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**
CREATE PROCEDURE `getTicketStatusWiseCount`(
	IN `qid` INT,
	IN `cond` TEXT,
	IN `userids` TEXT,
	IN `isadmin` TINYINT,
	IN `istatrec` TINYINT,
	IN `fromdate` VARCHAR(100),
	IN `todate` VARCHAR(100),
	IN `is_category` TINYINT
)
BEGIN
DROP TABLE IF EXISTS temp_ticketstatus;
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
set fromdate=if(IFNULL(fromdate,"")!="",CONCAT(' and Date_Format(ttm.created_date,"%Y-%m-%d")>="',fromdate,'" '),' ');
set todate=if(IFNULL(todate,"")!="",CONCAT(' and Date_Format(ttm.created_date,"%Y-%m-%d")<="',todate,'" '),' ');
if is_category = 0 then
	SET  @genrate_ticket_status_wise_count=CONCAT('
	CREATE TABLE `temp_ticketstatus` AS
	select tqs.status_name,tqs.status_id,tqs.colour_code,tqs.order_no,tqs.is_close_status,ifnull(today_all,0)today_all,
	ifnull(today_out_of_tat,0)today_out_of_tat,ifnull(today_with_in_tat,0)today_with_in_tat,
	ifnull(out_of_tat_ALL,0)out_of_tat_ALL,ifnull(with_in_tat_ALL,0)with_in_tat_ALL,ifnull(Total,0)Total
	  from tms_queue_status_',qid,' tqs LEFT JOIN
	(SELECT ttm.status_id,COUNT(if(Date_Format(ttm.created_date,"%Y-%m-%d")=CURDATE(),1,null))today_all,
	Sum(if(Date_Format(ttm.created_date,"%Y-%m-%d")=CURDATE() and TIMESTAMPDIFF(hour,IFNULL(ttm.priority_changed_on,ttm.created_date),if(tqs.is_close_status=1 AND ttm.ticket_id IS NOT null,last_con_date, NOW()) )>tqp.tat ,1,0))today_out_of_tat ,
	Sum(if(Date_Format(ttm.created_date,"%Y-%m-%d")=CURDATE() and TIMESTAMPDIFF(hour,IFNULL(ttm.priority_changed_on,ttm.created_date),if(tqs.is_close_status=1 AND ttm.ticket_id IS NOT null,last_con_date, NOW()) )<=tqp.tat ,1,0))today_with_in_tat ,
	Sum(if(TIMESTAMPDIFF(hour,IFNULL(ttm.priority_changed_on,ttm.created_date),if(tqs.is_close_status=1 AND ttm.ticket_id IS NOT null,last_con_date, NOW()) )>tqp.tat ',fromdate,todate,',1,0)) out_of_tat_ALL,
	Sum(if(TIMESTAMPDIFF(hour,IFNULL(ttm.priority_changed_on,ttm.created_date),if(tqs.is_close_status=1 AND ttm.ticket_id IS NOT null,last_con_date, NOW()) )<=tqp.tat ',fromdate,todate,',1,0)) with_in_tat_ALL
	,COUNT(if(1=1  ',fromdate,todate,' ,1,NULL))Total
	FROM   tms_ticket_master_',qid,' ttm JOIN tms_queue_status_',qid,' tqs on ttm.status_id=tqs.status_id
	LEFT JOIN tms_queue_priority_',qid,' tqp on ttm.priority_id=tqp.priority_id
	LEFT JOIN ( SELECT MAX(tcm.conversation_date)last_con_date,tcm.ticket_unique_id 
					FROM  tms_conversation_master_',qid,' tcm 
							JOIN tms_queue_status_',qid,' tqs  on tcm.status_id=tqs.status_id 
					WHERE tqs.is_close_status=1
	  				GROUP BY tcm.ticket_unique_id )lasttcm ON lasttcm.ticket_unique_id=ttm.ticket_unique_id
	
	WHERE   IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if( IFNULL(userids,"")!="",CONCAT(' and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),' 
	GROUP BY ttm.status_id)ticket_status_count on tqs.status_id=ticket_status_count.status_id ; 
	
	
	
	');
	PREPARE stmt_genrate_ticket_status_wise_count FROM @genrate_ticket_status_wise_count;
	EXECUTE stmt_genrate_ticket_status_wise_count;
	DEALLOCATE PREPARE stmt_genrate_ticket_status_wise_count;
	
	SET @get_ticket_status_count_with_tat=' SELECT status_name,status_id,colour_code,cnt,total,card_total FROM(
	SELECT CONCAT(UPPER(SUBSTRING(status_name,1,1)),LOWER(SUBSTRING(status_name,2)))status_name,status_id,colour_code,order_no, today_with_in_tat cnt, with_in_tat_ALL  total,Total card_total 
	FROM  temp_ticketstatus
	UNION ALL
	SELECT "TAT Exceeded" status_name,0,"#e55b5b"colour_code,100 order_no, sum(today_out_of_tat) cnt, sum(out_of_tat_ALL)  total,0 card_total 
	FROM  temp_ticketstatus
	UNION ALL
	SELECT "Closed out of TAT" status_name,status_id,""colour_code,100 order_no, sum(today_out_of_tat) cnt, sum(out_of_tat_ALL)  total,0 card_total 
	FROM  temp_ticketstatus WHERE is_close_status=1
	group by status_id
	UNION ALL
	SELECT "Closed with in TAT" status_name,status_id,""colour_code,100 order_no, sum(today_with_in_tat) cnt, sum(with_in_tat_ALL)  total,0 card_total 
	FROM  temp_ticketstatus WHERE is_close_status=1
	group by status_id
	UNION ALL
	SELECT "ALL" status_name,0,"#6fa8dc"colour_code,0 order_no, SUM(today_with_in_tat+today_out_of_tat) cnt, SUM(with_in_tat_ALL+out_of_tat_ALL)  total,SUM(Total) card_total 
	FROM  temp_ticketstatus  )status_wise_ticket_count ORDER BY order_no;
	 ';
	
	SET @get_tat_ticket_status_count='
	SELECT status_name,status_id,colour_code,cnt,total,card_total FROM(
	SELECT CONCAT(UPPER(SUBSTRING(status_name,1,1)),LOWER(SUBSTRING(status_name,2))) status_name,status_id,"#e55b5b"colour_code, order_no, today_out_of_tat cnt, out_of_tat_ALL total,0 card_total 
	FROM  temp_ticketstatus
	Union All
	SELECT "ALL" status_name,0,"#6fa8dc"colour_code,0 order_no, sum(today_out_of_tat) cnt, sum(out_of_tat_ALL)  total,0 card_total 
	FROM  temp_ticketstatus 
	  )status_wise_ticket_count ORDER BY order_no;
	
	
	';
	
	SET @get_ticket_status_wise_count=if(istatrec=1,@get_tat_ticket_status_count,@get_ticket_status_count_with_tat);
	
	PREPARE stmt_get_ticket_status_wise_count FROM @get_ticket_status_wise_count;
	EXECUTE stmt_get_ticket_status_wise_count;
	DEALLOCATE PREPARE stmt_get_ticket_status_wise_count;




ELSE
	SET @category_wise = CONCAT('
	SELECT ttm.category_id,category_name,ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code,
	COUNT(if(Date_Format(ttm.created_date,"%Y-%m-%d")=CURDATE(),1,null))cnt,COUNT(1) Total
	FROM tms_ticket_master_',qid,' ttm LEFT JOIN tms_queue_status_',qid,' tqs ON ttm.status_id=tqs.status_id 
	JOIN tms_queue_category_',qid,' tqc ON ttm.category_id=tqc.category_id 
	WHERE 1=1 ',fromdate,todate,if(ifnull(cond,'')!='',CONCAT(' and ',cond),''),
	if(ifnull(userids,'')!='',CONCAT('and (ttm.assigned_to in(',userids,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),''),'
	GROUP BY ttm.category_id,category_name,ttm.status_id,tqs.status_name,tqs.is_default,tqs.is_close_status,tqs.colour_code');
	
	PREPARE stmt_category_wise FROM @category_wise;
	EXECUTE stmt_category_wise;
	DEALLOCATE PREPARE stmt_category_wise;
	
END if;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**
CREATE FUNCTION `GetTimeLine`(`cr_date` VARCHAR(50)
) RETURNS varchar(50) CHARSET utf8mb4
    NO SQL
BEGIN
    DECLARE retval VARCHAR(50);
	DECLARE cr_year INT(10);
	DECLARE cr_month INT(10);
	DECLARE cr_day INT(10);
	DECLARE cr_hour INT(10);
	DECLARE cr_min INT(10);
	SET cr_year	 = YEAR(cr_date);
	SET cr_month = MONTH(cr_date);
	SET cr_day   = DAYOFMONTH(cr_date);
	SET cr_hour  = HOUR(cr_date);
	SET cr_min   = MINUTE(cr_date);
   IF((cr_date = '') OR (cr_date = '0000-00-00 00:00:00')) THEN
    	SET retval = '';
   ELSEIF((YEAR(cr_date) > YEAR(now())) OR (YEAR(cr_date) < YEAR(now()))) THEN
    	SET retval = DATE_FORMAT(cr_date, '%d/%m/%y');
	ELSEIF(YEAR(cr_date) = YEAR(now()) AND ((MONTH(cr_date) < MONTH(now())) OR (MONTH(cr_date) > MONTH(now())))) THEN
    	SET retval = DATE_FORMAT(cr_date, '%d %b');
	ELSEIF(YEAR(cr_date) = YEAR(now()) AND MONTH(cr_date) = MONTH(now()) AND (DAYOFMONTH(cr_date) > DAYOFMONTH(now()))) THEN
    	SET retval = DATE_FORMAT(cr_date, '%d %b');
	ELSEIF(YEAR(cr_date) = YEAR(now()) AND MONTH(cr_date) = MONTH(now()) AND (DAYOFMONTH(cr_date) < DAYOFMONTH(NOW())) AND DATEDIFF(NOW(), cr_date) < 7) THEN
    	SET retval = DATE_FORMAT(cr_date, '%W');
	ELSEIF(YEAR(cr_date) = YEAR(now()) AND MONTH(cr_date) = MONTH(now()) AND (DAYOFMONTH(cr_date) < DAYOFMONTH(NOW())) AND DATEDIFF(NOW(), cr_date) > 7) THEN
    	SET retval = DATE_FORMAT(cr_date, '%d %b');
	ELSEIF(YEAR(cr_date) = YEAR(now()) AND MONTH(cr_date) = MONTH(now()) AND DAYOFMONTH(cr_date) = DAYOFMONTH(now()) AND ((HOUR(cr_date) < HOUR(now())) OR (HOUR(cr_date) > HOUR(now())))) THEN
    	SET retval = DATE_FORMAT(cr_date, '%h:%i %p');
	ELSEIF(YEAR(cr_date) = YEAR(now()) AND MONTH(cr_date) = MONTH(now()) AND DAYOFMONTH(cr_date) = DAYOFMONTH(now()) AND HOUR(cr_date) = HOUR(now()) AND ((MINUTE(cr_date) < MINUTE(now())) OR (MINUTE(cr_date) > MINUTE(now())))) THEN
    	SET retval = DATE_FORMAT(cr_date, '%h:%i %p');
	ELSEIF(YEAR(cr_date) = YEAR(now()) AND MONTH(cr_date) = MONTH(now()) AND DAYOFMONTH(cr_date) = DAYOFMONTH(now()) AND HOUR(cr_date) = HOUR(now()) AND MINUTE(cr_date) = MINUTE(now())) THEN
    	SET retval = 'Now';
   END IF;
	RETURN (retval);
END
**
CREATE PROCEDURE `getTMSAgentReport`(
	IN `qid` VARCHAR(20),
	IN `fromdate` VARCHAR(20),
	IN `todate` VARCHAR(20),
	IN `sorting` VARCHAR(50),
	IN `rowlimit` VARCHAR(50)
)
BEGIN
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

DROP TEMPORARY TABLE IF EXISTS TMS_Ticketsstatus,AMS_TicketProdutivity;

SET SESSION group_concat_max_len = 1000000; 

SET @fromdate=if(IFNULL(fromdate,"")!="",CONCAT(' and date(ttm.assigned_on)>=''',fromdate,''' '),' ');
SET @todate=if(IFNULL(todate,"")!="",CONCAT(' and date(ttm.assigned_on)<=''',todate,''' '),' ');
SET @tmsticketstatus='';
SET @ticketquery = CONCAT('SELECT GROUP_CONCAT(
    CONCAT(
        "SELECT ttm.assigned_to user_id,
				 SUM(case when 1=1 ',@fromdate,@todate,' then 1 ELSE 0 END) `Today_Tickets`,
					SUM(case when ticket_status_type=1 ',@fromdate,@todate,' then 1 ELSE 0 END) `Today_Closed`,
					SUM(case when ticket_status_type=2 ',@fromdate,@todate,' then 1 ELSE 0 END) `Today_Open`,
					SUM(case when ticket_status_type=3 ',@fromdate,@todate,' then 1 ELSE 0 END) `Today_Pending`,
               SUM(IF( ticket_status_type=1 and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
               IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <=tqp.tat * 60  ',@fromdate,@todate,'  ,1,0)) AS Today_Closed_within_TAT,
               SUM(IF(ticket_status_type=1 and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
               IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60  ',@fromdate,@todate,'  ,1,0)) AS Today_Closed_outside_TAT,
               SUM(IF(ticket_status_type=3 and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
               IF(ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60  ',@fromdate,@todate,'  ,1,0)) AS Today_Pending_Outside_TAT,
               COUNT(1) `Total_Tickets`,
					SUM(case when ticket_status_type=1 then 1 ELSE 0 END) `Total_Closed`,
					SUM(case when ticket_status_type=2 then 1 ELSE 0 END) `Total_Open`,
					SUM(case when ticket_status_type=3 then 1 ELSE 0 END) `Total_Pending`,
               SUM(IF( ticket_status_type=1 and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
               IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) <=tqp.tat * 60,1,0)) AS Total_Closed_within_TAT,
               SUM(IF(ticket_status_type=1 and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
               IF(tqs.is_close_status=1 AND ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60,1,0)) AS Total_Closed_outside_TAT,
               SUM(IF(ticket_status_type=3 and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.priority_changed_on,ttm.created_date),
               IF(ttm.ticket_id IS NOT NULL, last_con_date, NOW())) >tqp.tat * 60,1,0)) AS Total_Pending_Outside_TAT,
               SUM(case when 1=1 ',@fromdate,@todate,' then TIMESTAMPDIFF(MINUTE,IFNULL(assigned_on,ttm.created_date),ifnull(first_con_date, NOW())) else 0 end) AS First_Response
	            FROM tms_ticket_master_",tqm.id, " AS ttm 
	            LEFT JOIN tms_queue_status_",tqm.id, " AS tqs ON ttm.status_id = tqs.status_id 
	            LEFT JOIN tms_queue_priority_",tqm.id, " AS tqp ON ttm.priority_id = tqp.priority_id 
	            LEFT JOIN (SELECT MAX(tcm.conversation_date) AS last_con_date, tcm.ticket_unique_id 
	            FROM tms_conversation_master_",tqm.id, " AS tcm GROUP BY tcm.ticket_unique_id) AS lasttcm ON lasttcm.ticket_unique_id = ttm.ticket_unique_id
	            LEFT JOIN (SELECT MIN(tcm.conversation_date) AS first_con_date, tcm.ticket_unique_id 
	            FROM tms_conversation_master_",tqm.id, " AS tcm
	            JOIN tms_ticket_master_",tqm.id, " tm ON tm.ticket_unique_id=tcm.ticket_unique_id
					WHERE ((is_auto=1 AND conversation_type NOT IN (""auto reply email"",""incomming mail"")) OR (is_auto=0 AND conversation_type NOT IN (""auto reply email""))) GROUP BY tcm.ticket_unique_id) AS firsttcm ON firsttcm.ticket_unique_id = ttm.ticket_unique_id
	            WHERE IFNULL(is_junk,0) = 0 AND IFNULL(is_deleted_ticket,0) = 0 AND 1 = 1 and is_draft!=1
	            GROUP BY ttm.assigned_to "
		  
    )
    SEPARATOR " UNION ALL "
)
 INTO @tmsticketstatus
FROM tms_queue_master tqm 
WHERE tqm.id IN (',qid,')');  
#SELECT @ticketquery;
PREPARE stmt FROM @ticketquery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @tmsquery=CONCAT('Create temporary Table TMS_Ticketsstatus select * from (',@tmsticketstatus,')s');
#SELECT @tmsquery;
PREPARE stmt FROM @tmsquery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @QUERY=CONCAT('Create temporary Table AMS_TicketProdutivity SELECT agent_id,Agent_Name,
SUM(case when state="Break" and office_break=1 then 1 ELSE 0 END) Office_Break,
SUM(case when state="Break" and office_break=0 then 1 ELSE 0 END) Personal_Break,
SUM(case when state="Break" and office_break=1 then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END) Office_Break_Time,
SUM(case when state="Break" and office_break=0 then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END) Personal_Break_Time,
SUM(case when state="Idle" then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END) Idle_Time,
(SUM(case when state NOT IN ("Idle") then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END)-SUM(case when state="Break" and office_break=0 then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END)) Work_Time,
SUM(case when state IN ("Break","Idle","Ticket View","Ticket Close","Ticket Work","Manual Ticket Generated") then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END) Total_Time,
(SUM(case when state IN ("Idle","Ticket View","Ticket Close","Ticket Work","Manual Ticket Generated") then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END)+SUM(case when state="Break" and office_break=1 then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END)) Staffed,
(SUM(case when state NOT IN ("Idle") then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END)-SUM(case when state="Break" and office_break=0 then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END))/NULLIF((SUM(case when state NOT IN ("Idle") then 1 ELSE 0 END)-SUM(case when state="Break" and office_break=0 then 1 ELSE 0 END)),0) Avg_Work,
SUM(case when state="Idle" then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END)/NULLIF(SUM(case when state="Idle" then 1 ELSE 0 END),0) Avg_Idle,
sum(case when state="Ticket View" then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END) Ticket_View,
TIME(MIN(CASE WHEN state="Login" THEN start_time END)) Login_Time,
TIME(MAX(start_time)) Logout_Time,
SEC_TO_TIME(SUM(case when state IN ("Break","Idle","Ticket View","Ticket Close","Ticket Work","Manual Ticket Generated") then TIMESTAMPDIFF(SECOND,start_time,end_time) ELSE 0 END)) Login_Hrs,
SUM(CASE WHEN state="Login" THEN 1 ELSE 0 END) Login_Count, 
SUM(CASE WHEN state="Logout" THEN 1 ELSE 0 END) Logout_Count
FROM agent_productivity_report_log agent_log
LEFT JOIN tms_break_master  ON tms_break_master.id=agent_log.break_id
LEFT JOIN TMS_Ticketsstatus tts ON tts.user_id=agent_log.agent_id
where start_time>="',fromdate,'" and start_time<="',todate,'"
GROUP BY Agent_Name,agent_id'
);
#SELECT @QUERY;
PREPARE stmt FROM @QUERY;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @SQL=CONCAT('SELECT Agent_Name,
 ifnull(Today_Tickets,0) Today_Tickets, ifnull(Today_Closed,0) Today_Closed,ifnull(Today_Open,0) Today_Open,ifnull(Today_Pending,0) Today_Pending, ifnull(Today_Closed_within_TAT,0) Today_Closed_within_TAT, 
 ifnull(Today_Closed_outside_TAT,0) Today_Closed_outside_TAT,ifnull(Today_Pending_Outside_TAT,0) Today_Pending_Outside_TAT,
 ifnull(Total_Tickets,0) Total_Tickets,ifnull(Total_Closed,0) Total_Closed, ifnull(Total_Open,0) Total_Open, ifnull(Total_Pending,0) Total_Pending, 
 ifnull(Total_Closed_within_TAT,0) Total_Closed_within_TAT,ifnull(Total_Closed_outside_TAT,0) Total_Closed_outside_TAT, ifnull(Total_Pending_Outside_TAT,0) Total_Pending_Outside_TAT,
 Office_Break,Personal_Break,SEC_TO_TIME(Office_Break_Time) Office_Break_Time,SEC_TO_TIME(Personal_Break_Time) Personal_Break_Time,SEC_TO_TIME(Idle_Time) Idle_Time,
 SEC_TO_TIME(Work_Time) Work_Time,SEC_TO_TIME(Total_Time) Total_Time,SEC_TO_TIME(Staffed) Staffed,
 DATE_FORMAT(SEC_TO_TIME(Avg_Work),"%T") Avg_Work, DATE_FORMAT(SEC_TO_TIME(Avg_Idle),"%T") Avg_Idle,
DATE_FORMAT(SEC_TO_TIME(ifnull((Ticket_View+First_Response)/NULLIF(Today_Open,0),0)),"%T")  AHT,
 DATE_FORMAT(SEC_TO_TIME(ifnull(First_Response/NULLIF(Today_Open,0),0)),"%T") ART,
 Login_Time,Logout_time,Login_Hrs,
 Login_Count,Logout_Count
 from AMS_TicketProdutivity
 left join TMS_Ticketsstatus ON user_id=agent_id
 ',if(IFNULL(sorting,"")!="",CONCAT(' Order by ',Sorting,''),""),'
  ',if(IFNULL(rowlimit,"")!="",CONCAT(' LIMIT  ',rowlimit,''),""),'');
#SELECT @SQL;
PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @Query=CONCAT('SELECT count(1) Count
 from AMS_TicketProdutivity
 left join TMS_Ticketsstatus ON user_id=agent_id
 ',if(IFNULL(sorting,"")!="",CONCAT(' Order by ',Sorting,''),""),'
 ');
#SELECT @QUERY;
PREPARE stmt FROM @Query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


DROP TEMPORARY TABLE IF EXISTS TMS_Ticketsstatus,AMS_TicketProdutivity;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END
**
CREATE PROCEDURE `Header_search`(
	IN `User_id` INT,
	IN `conditions` VARCHAR(50),
	IN `limit_offset` VARCHAR(10),
	IN `fullcontrol` INT,
	IN `all_ticket` INT
)
BEGIN
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

SET SESSION group_concat_max_len = 1000000; 

SET @queue_ids=CONCAT('select queue_id into @queueid from tms_user_master where user_id=',User_id,'');

PREPARE stmt FROM @queue_ids;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
 

SET @ticket_query = CONCAT('SELECT GROUP_CONCAT(
    CONCAT("SELECT ''",tqm.queue,"'' as Queue_Name, DATE_FORMAT(ttm.start_date,''%d-%m-%Y %H:%i:%s'') As StartDate, queue_id,
    ticket_unique_id,ticket_id,person_name,mobile_no,start_date,from_email,to_email,subject,created_date
	  FROM tms_ticket_master_",tqm.id," ttm
	 where 1=1 and ttm.is_junk =0 and ttm.is_deleted_ticket = 0  ',if(IFNULL(conditions,"")!="",CONCAT(' and (person_name like ''%',conditions,'%'' 
	 or from_email like ''%',conditions,'%'' 
	 or to_email like ''%',conditions,'%'' 
	 or mobile_no like ''%',conditions,'%'' )'),""),
   if((IFNULL(fullcontrol,0)=0 and  IFNULL(all_ticket,0)=0),CONCAT(' and (ttm.assigned_to in('  ,user_id,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(fullcontrol,0)=0 and  IFNULL(all_ticket,0)=2) ,CONCAT(' and ttm.assigned_to in(',user_id,') '),"") ,'
			 "
        )
    SEPARATOR " UNION ALL "
)
 INTO @ticket_temp
FROM tms_queue_master tqm
where tqm.id in (',@queueid,' ) '); 

#SELECT @ticket_query;
PREPARE stmt FROM @ticket_query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
 
SET @sqlquery=CONCAT('select * from(',@ticket_temp,')t
order by ticket_unique_id desc');

if limit_offset !='' then
	SET @sqlquery = CONCAT(@sqlquery,' LIMIT ', limit_offset);
END if;
#SELECT @sqlquery;
PREPARE stmt FROM @sqlquery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;



SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END
**
CREATE FUNCTION `mask_email`(
	`input_string` VARCHAR(255),
	`mask_char` CHAR(1)
) RETURNS varchar(255) CHARSET latin1
    DETERMINISTIC
BEGIN
    DECLARE output_string VARCHAR(255);
    DECLARE email_list VARCHAR(255);
    DECLARE masked_email VARCHAR(255);
    SET output_string = input_string;
    SET email_list = CONCAT(input_string, ',');

    SET masked_email = '';
    WHILE LOCATE(',', email_list) > 0 DO
        SET masked_email = CONCAT(masked_email, 
                                   SUBSTRING(email_list, 1, 2),
                                   REPEAT(mask_char, LOCATE('@', email_list) - 3),
                                   SUBSTRING_INDEX(email_list, '@', -1),
                                   '\n');
        SET email_list = SUBSTRING(email_list, LOCATE(',', email_list) + 1);
    END WHILE;

    SET masked_email = SUBSTRING(masked_email, 1, LENGTH(masked_email) - 2); -- Remove the last '<br>' tag
    SET output_string = masked_email;

    RETURN output_string;
END
**
CREATE FUNCTION `mask_number`(
    `input_string` VARCHAR(255),
    `mask_char` CHAR(1)
) RETURNS varchar(255) CHARSET latin1
    NO SQL
    DETERMINISTIC
BEGIN
    DECLARE output_string VARCHAR(255);
    SET output_string = input_string;
    SET output_string = CONCAT(
        SUBSTRING(output_string, 1, FLOOR((CHAR_LENGTH(output_string) - 4) / 2)),
        REPEAT(mask_char, 4),
        SUBSTRING(output_string, FLOOR((CHAR_LENGTH(output_string) + 2) / 2))
    );
    RETURN output_string;
END
**
CREATE PROCEDURE `moveInboxToJunk`(
	IN `queueid` INT,
	IN `ticketid` INT
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
    SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
   
        ROLLBACK;   
    END; 
START TRANSACTION;

SET @sql1 = CONCAT('update tms_ticket_master_',queueid,' set is_junk = 1 where ticket_unique_id=',ticketid);

PREPARE stmtcdrSQL FROM @sql1; 
EXECUTE stmtcdrSQL; 
DEALLOCATE PREPARE stmtcdrSQL;


COMMIT;
END
**

CREATE TABLE IF NOT EXISTS `move_to_another_queue_log` (
  `id` int NOT NULL AUTO_INCREMENT,
  `ticket_id` varchar(100) DEFAULT NULL,
  `queue_id` int DEFAULT NULL,
  `new_ticket_id` varchar(100) DEFAULT NULL,
  `new_queue_id` int DEFAULT NULL,
  `assigned_to` int DEFAULT NULL,
  `created_by` int DEFAULT NULL,
  `created_date` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

**
INSERT INTO `move_to_another_queue_log` (`id`, `ticket_id`, `queue_id`, `new_ticket_id`, `new_queue_id`, `assigned_to`, `created_by`, `created_date`) VALUES
	(1, '#TT240528-379', 1, '#TT240528-5', 7, 40, 1, '2024-05-28 14:43:14'),
	(2, '#TT240528-391', 1, '#TT240529-6', 7, 40, 1, '2024-05-29 11:19:14'),
	(3, '#TT240502-69', 1, '#TT240620-7', 7, 40, 1, '2024-06-20 14:07:14'),
	(4, '#TT240620-2188', 1, '#TT240620-8', 7, 40, 1, '2024-06-20 14:25:49'),
	(5, '#TT240711-2270', 1, '#TT240711-10', 7, 51, 1, '2024-07-11 18:16:09'),
	(6, '#TT240711-2273', 1, '#TT240711-12', 7, 51, 1, '2024-07-11 18:18:39');

**
CREATE TABLE IF NOT EXISTS `Password_logs` (
  `id` int NOT NULL AUTO_INCREMENT,
  `user_id` int DEFAULT NULL,
  `password_used` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=latin1;


**
CREATE PROCEDURE `performRulesAction`(
	IN `rule_action` VARCHAR(50),
	IN `queueid` INT,
	IN `ticketid` INT,
	IN `action_value` VARCHAR(50),
	IN `accountid` INT
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
    SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
   
        ROLLBACK;   
    END; 
START TRANSACTION;

if rule_action = 'Set Priority as' then

	SET @sql1 = CONCAT('select count(1) into @ticket_count from tms_ticket_master_',queueid,' where ticket_unique_id=',ticketid);

	PREPARE stmtcdrSQL FROM @sql1; 
	EXECUTE stmtcdrSQL; 
	DEALLOCATE PREPARE stmtcdrSQL;

	if IFNULL(@ticket_count,0) > 0 then

		SET @sql1 = CONCAT('update tms_ticket_master_',queueid,' set priority_id="',action_value,'" where ticket_unique_id=',ticketid);
	
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
		SET @sql1 = CONCAT('
									INSERT INTO tms_conversation_master_',queueid,'(conversation_date,conversation_type,ticket_unique_id,ticket_id,
									mobile_no,account_id,from_email,to_email,cc_email,bcc_email,subject,category_id,subcategory_id,status_id,
									priority_id,queue_id)
									
									Select NOW(),"Priority Updated By Rule",ticket_unique_id,ticket_id,ticket_mast.mobile_no,',accountid,',from_email,to_email,
									cc_email,bcc_email,subject,category_id,subcategory_id,status_id,priority_id,ticket_mast.queue_id
									from tms_ticket_master_',queueid,' ticket_mast
									left join tms_user_master uassignedto on ticket_mast.assigned_to=uassignedto.user_id
									left join tms_user_master uassignedby on ticket_mast.assigned_by=uassignedby.user_id 
									left join tms_user_master ulastupdatedby on ticket_mast.last_updated_by=ulastupdatedby.user_id
									where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND ticket_unique_id=',ticketid,';
									
									');
	
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
		SET @sql1 = CONCAT('
									INSERT INTO ticket_action_log(log_date,queue_id,ticket_id,login_id,log_action,action_detail)
									Values(NOW(),',queueid,',',ticketid,',0,"Priority Change","Priority Change using Rules")
									');
	
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
	END if;

ELSEIF rule_action='Set Status as' then

	SET @sql1 = CONCAT('select count(1) into @ticket_count from tms_ticket_master_',queueid,' where ticket_unique_id=',ticketid);

	PREPARE stmtcdrSQL FROM @sql1; 
	EXECUTE stmtcdrSQL; 
	DEALLOCATE PREPARE stmtcdrSQL;

	if IFNULL(@ticket_count,0) > 0 then

		SET @sql1 = CONCAT('update tms_ticket_master_',queueid,' set status_id="',action_value,'" where ticket_unique_id=',ticketid);
	
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
		SET @sql1 = CONCAT('
									INSERT INTO tms_conversation_master_',queueid,'(conversation_date,conversation_type,ticket_unique_id,ticket_id,
									mobile_no,account_id,from_email,to_email,cc_email,bcc_email,subject,category_id,subcategory_id,status_id,
									priority_id,queue_id)
									
									Select NOW(),"Status Id Updated By Rule",ticket_unique_id,ticket_id,ticket_mast.mobile_no,',accountid,',from_email,to_email,
									cc_email,bcc_email,subject,category_id,subcategory_id,status_id,priority_id,ticket_mast.queue_id
									from tms_ticket_master_',queueid,' ticket_mast
									left join tms_user_master uassignedto on ticket_mast.assigned_to=uassignedto.user_id
									left join tms_user_master uassignedby on ticket_mast.assigned_by=uassignedby.user_id 
									left join tms_user_master ulastupdatedby on ticket_mast.last_updated_by=ulastupdatedby.user_id
									where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND ticket_unique_id=',ticketid,';
									
									');
	
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
		SET @sql1 = CONCAT('
									INSERT INTO ticket_action_log(log_date,queue_id,ticket_id,login_id,log_action,action_detail)
									Values(NOW(),',queueid,',',ticketid,',0,"Status Change","Status Change using Rules")
									');
	
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
	END if;


ELSEIF rule_action='Assigned To Agent' then

	SET @sql1 = CONCAT('select count(1) into @ticket_count from tms_ticket_master_',queueid,' where ticket_unique_id=',ticketid);

	PREPARE stmtcdrSQL FROM @sql1; 
	EXECUTE stmtcdrSQL; 
	DEALLOCATE PREPARE stmtcdrSQL;

	if IFNULL(@ticket_count,0) > 0 then
		
		SET @sql1=CONCAT('SELECT user_id INTO @action_value FROM tms_user_master WHERE user_id IN (',action_value,') and is_login=1 order by RAND() LIMIT 1');
		
			PREPARE stmtcdrSQL FROM @sql1; 
			EXECUTE stmtcdrSQL; 
			DEALLOCATE PREPARE stmtcdrSQL;
	
		if IFNULL(@action_value,0) > 0 then
		
			SET @sql1 = CONCAT('select assigned_to into @last_assign from tms_ticket_master_',queueid,' where ticket_unique_id=',ticketid);
			
			PREPARE stmtcdrSQL FROM @sql1; 
			EXECUTE stmtcdrSQL; 
			DEALLOCATE PREPARE stmtcdrSQL;
			
				SET @sql1 = CONCAT('update tms_ticket_master_',queueid,' set assigned_to="',@action_value,'",assigned_by=0,is_assigned=1,assigned_on=NOW() where ticket_unique_id=',ticketid);
			
			PREPARE stmtcdrSQL FROM @sql1; 
			EXECUTE stmtcdrSQL; 
			DEALLOCATE PREPARE stmtcdrSQL;
				
				SET @sql1 = CONCAT('
											insert into user_assign_logs(queue_id,ticket_id,assigned_by,assigned_to,last_assigned,assigned_on) 
											values(',queueid,',',ticketid,',0,',@action_value,',',@last_assign,',NOW());
											');
			
			
			PREPARE stmtcdrSQL FROM @sql1; 
			EXECUTE stmtcdrSQL; 
			DEALLOCATE PREPARE stmtcdrSQL;
			
				SET @sql1 = CONCAT('
									INSERT INTO ticket_action_log(log_date,queue_id,ticket_id,login_id,log_action,action_detail)
									Values(NOW(),',queueid,',',ticketid,',0,"Assigned To ',@action_value,'","Ticket Assigned to ',@action_value,' using Rules")
									');
									
			PREPARE stmtcdrSQL FROM @sql1; 
			EXECUTE stmtcdrSQL; 
			DEALLOCATE PREPARE stmtcdrSQL;
				
				SET @sql1 = CONCAT('Update tms_user_master set ticket_assigned=ifnull(ticket_assigned,0)+1 where user_id=',@action_value);
			
			PREPARE stmtcdrSQL FROM @sql1; 
			EXECUTE stmtcdrSQL; 
			DEALLOCATE PREPARE stmtcdrSQL;
			
		END if;
	END if;

ELSEIF rule_action='Move To Junk' AND action_value='yes' then

	SET @sql1 = CONCAT('select count(1) into @ticket_count from tms_ticket_master_',queueid,' where ticket_unique_id=',ticketid);

	PREPARE stmtcdrSQL FROM @sql1; 
	EXECUTE stmtcdrSQL; 
	DEALLOCATE PREPARE stmtcdrSQL;

	if IFNULL(@ticket_count,0) > 0 then

		CALL moveInboxToJunk(queueid,ticketid);
	
		SET @sql1 = CONCAT('
					INSERT INTO ticket_action_log(log_date,queue_id,ticket_id,login_id,log_action,action_detail)
					Values(NOW(),',queueid,',',ticketid,',0,"Inbox To Junk","Move Inbox to Junk using Rules")
					');
	
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
		SET @sql1 = CONCAT('delete from tms_unreadconversationcount_',queueid,' WHERE ticket_unique_id=',ticketid);
	
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
	END if;

ELSEIF rule_action='Delete Ticket' AND action_value='yes' then

	SET @sql1 = CONCAT('select count(1) into @ticket_count from tms_ticket_master_',queueid,' where ticket_unique_id=',ticketid);

	PREPARE stmtcdrSQL FROM @sql1; 
	EXECUTE stmtcdrSQL; 
	DEALLOCATE PREPARE stmtcdrSQL;

	if IFNULL(@ticket_count,0) > 0 then

		SET @sql1 = CONCAT('delete from tms_ticket_master_',queueid,' where ticket_unique_id =',ticketid);
		
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
	
		SET @sql1 = CONCAT('delete from tms_conversation_attachements_',queueid,' where conversation_id in (select conversation_id from tms_conversation_master_',queueid,' where ticket_unique_id =',ticketid,')');
		
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
		SET @sql1 = CONCAT('delete from tms_conversation_master_',queueid,' where ticket_unique_id = ',ticketid);
		
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;

		SET @sql1 = CONCAT('
			INSERT INTO ticket_action_log(log_date,queue_id,ticket_id,login_id,log_action,action_detail)
			Values(NOW(),',queueid,',',ticketid,',0,"Delete Ticket ',ticketid,'","Delete Ticket ',ticketid,' from Inbox using Rules")
			');

		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;

		SET @sql1 = CONCAT('delete from tms_unreadconversationcount_',queueid,' WHERE ticket_unique_id=',ticketid);
	
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
	END if;
	
	

ELSEIF rule_action='Set Sub Category as' then

	SET @sql1 = CONCAT('select count(1) into @ticket_count from tms_ticket_master_',queueid,' where ticket_unique_id=',ticketid);

	PREPARE stmtcdrSQL FROM @sql1; 
	EXECUTE stmtcdrSQL; 
	DEALLOCATE PREPARE stmtcdrSQL;

	if IFNULL(@ticket_count,0) > 0 then

		SET @sql1 = CONCAT('update tms_ticket_master_',queueid,' set subcategory_id="',action_value,'" where ticket_unique_id=',ticketid);

		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
		SET @sql1 = CONCAT('
									INSERT INTO tms_conversation_master_',queueid,'(conversation_date,conversation_type,ticket_unique_id,ticket_id,
									mobile_no,account_id,from_email,to_email,cc_email,bcc_email,subject,category_id,subcategory_id,status_id,
									priority_id,queue_id)
									
									Select NOW(),"Sub Category Id Updated By Rule",ticket_unique_id,ticket_id,ticket_mast.mobile_no,',accountid,',from_email,to_email,
									cc_email,bcc_email,subject,category_id,subcategory_id,status_id,priority_id,ticket_mast.queue_id
									from tms_ticket_master_',queueid,' ticket_mast
									left join tms_user_master uassignedto on ticket_mast.assigned_to=uassignedto.user_id
									left join tms_user_master uassignedby on ticket_mast.assigned_by=uassignedby.user_id 
									left join tms_user_master ulastupdatedby on ticket_mast.last_updated_by=ulastupdatedby.user_id
									where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND ticket_unique_id=',ticketid,';
									
									');
	
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
		SET @sql1 = CONCAT('
			INSERT INTO ticket_action_log(log_date,queue_id,ticket_id,login_id,log_action,action_detail)
			Values(NOW(),',queueid,',',ticketid,',0,"Sub Category Change","Sub Category Change using Rules")
			');
	
		PREPARE stmtcdrSQL FROM @sql1; 
		EXECUTE stmtcdrSQL; 
		DEALLOCATE PREPARE stmtcdrSQL;
		
	END if;

END if;
COMMIT;
END
**
CREATE TABLE IF NOT EXISTS `Persons` (
  `ID` int NOT NULL,
  `LastName` varchar(255) NOT NULL,
  `FirstName` varchar(255) DEFAULT NULL,
  `Age` int DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE PROCEDURE `queueStatusWiseReport`(
	IN `graph_type` VARCHAR(50),
	IN `queueid` VARCHAR(10),
	IN `userid` TINYTEXT,
	IN `fullcontrol` INT,
	IN `all_ticket` INT
)
BEGIN

    DECLARE done INT DEFAULT FALSE;
    DECLARE queue_id VARCHAR(50);
    DECLARE queue_cursor CURSOR FOR SELECT id FROM tms_queue_master WHERE FIND_IN_SET(id, queueid);
   /* DECLARE queue_cursor CURSOR FOR SELECT id FROM tms_queue_master WHERE id IN (queueid) ;*/
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    

    OPEN queue_cursor;
    read_loop: LOOP
        FETCH queue_cursor INTO queue_id;
        IF done THEN
            LEAVE read_loop;
        END IF;

SET SESSION group_concat_max_len = 1000000000000;

        /*SET @sqlquery = CONCAT('SELECT group_concat(DISTINCT status_id) INTO @status_ids
                                FROM tms_user_master tum JOIN tms_statuspermission_', queue_id, ' tsp ON tum.user_type = tsp.user_type
                                WHERE tsp.is_checked = 1 AND tum.user_id IN (',userid,')');
         
        PREPARE stmtsqlquery FROM @sqlquery;
        EXECUTE stmtsqlquery;
        DEALLOCATE PREPARE stmtsqlquery;*/

        SET @col1 = CONCAT('SELECT GROUP_CONCAT(CONCAT(''ifnull('', replace(REPLACE(REPLACE(tqs.status_name, '' '', ''_''), ''-'', ''_''),''/'',''_''), '',0)  AS "'', REPLACE(REPLACE(concat(tqs.status_name," ","(",tqs.Colour_Code,")"), '' '', '' ''), ''-'', ''_''), ''"'')) INTO @exactcol1 
		  FROM tms_queue_status_', queue_id, ' tqs' );
        
		  PREPARE stmtcol1 FROM @col1;
        EXECUTE stmtcol1;
        DEALLOCATE PREPARE stmtcol1;

        SET @col2 = CONCAT('SELECT GROUP_CONCAT(CONCAT(''ifnull(SUM(CASE WHEN tqs.status_id = '', tqs.status_id, '' THEN 1 ELSE 0 END),0) AS "'', REPLACE(REPLACE(REPLACE(tqs.status_name, '' '', ''_''), ''-'', ''_''),''/'',''_''), ''"'')) INTO @exactcol2 
		  FROM tms_queue_status_', queue_id, ' tqs ');
        
		  PREPARE stmtcol2 FROM @col2;
        EXECUTE stmtcol2;
        DEALLOCATE PREPARE stmtcol2;

      
        
        				 
 IF graph_type = 'daily' THEN 
 
 SET @droptable1 = CONCAT('DROP TABLE IF EXISTS temp_table_1;');
  PREPARE stmt_droptable1 FROM @droptable1;
  EXECUTE stmt_droptable1;
  DEALLOCATE PREPARE stmt_droptable1;
  
 SET @sqlquery = CONCAT('Create table temp_table_1 as  SELECT ',queue_id,' Queue_id, CONCAT(" ",daylist.days) AS Name,', IFNULL(@exactcol1, '0'), ' 
                     FROM (SELECT 1 AS days UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5
                           UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10
                           UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15
                           UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19 UNION ALL SELECT 20
                           UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23 UNION ALL SELECT 24 UNION ALL SELECT 25
                           UNION ALL SELECT 26 UNION ALL SELECT 27 UNION ALL SELECT 28 UNION ALL SELECT 29 UNION ALL SELECT 30
                           UNION ALL SELECT 31) daylist
                     LEFT JOIN (SELECT DAY(created_date) AS days,', IFNULL(@exactcol2, '0'), '
							FROM tms_ticket_master_',queue_id,' ttm 
							LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id
							where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND MONTH(created_date) = MONTH(NOW()) AND YEAR(created_date) = YEAR(NOW())
							',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
							 GROUP BY DAY(created_date)) ttm ON daylist.days = ttm.days '); 

#SELECT  @sqlquery; 
PREPARE stmtsqlquery FROM @sqlquery; 
EXECUTE stmtsqlquery; 
DEALLOCATE PREPARE stmtsqlquery; 

ALTER TABLE `temp_table_1` ADD INDEX `queue_id` (`queue_id`) USING BTREE;
							 
SET @query=CONCAT('select tqm.queue as Queue_Name, t.* from temp_table_1 t
								join tms_queue_master tqm on t.queue_id=tqm.id');
							 
END IF;

if graph_type = 'weekly' THEN 

SET @droptable1 = CONCAT('DROP TABLE IF EXISTS temp_table_1;');
  PREPARE stmt_droptable1 FROM @droptable1;
  EXECUTE stmt_droptable1;
  DEALLOCATE PREPARE stmt_droptable1;

 SET @sqlquery = CONCAT('Create table temp_table_1 as  SELECT ',queue_id,' Queue_id, concat("week ",weeklist.weeks) as Name, ', IFNULL(@exactcol1, ''), ' FROM
                            (SELECT 1 weeks UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5) weeklist
                            LEFT JOIN (SELECT CASE WHEN DAY(created_date) >= 1 AND DAY(created_date) <= 7 THEN 1
                                                   WHEN DAY(created_date) >= 8 AND DAY(created_date) <= 14 THEN 2
                                                   WHEN DAY(created_date) >= 15 AND DAY(created_date) <= 21 THEN 3
                                                   WHEN DAY(created_date) >= 22 AND DAY(created_date) <= 28 THEN 4
                                                   ELSE 5 END weeks, ', IFNULL(@exactcol2, ''), ' 
																	FROM tms_ticket_master_',queue_id,' ttm 
																	LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id
																	where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND MONTH(created_date) = MONTH(NOW()) AND YEAR(created_date) = YEAR(NOW())
																		',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
				 GROUP BY weeks
                                                   ) ttm ON weeklist.weeks = ttm.weeks'); 

#SELECT  @sqlquery; 
PREPARE stmtsqlquery FROM @sqlquery; 
EXECUTE stmtsqlquery; 
DEALLOCATE PREPARE stmtsqlquery; 
  
ALTER TABLE `temp_table_1` ADD INDEX `queue_id` (`queue_id`) USING BTREE;
                                                   
SET @query=CONCAT('select tqm.queue as Queue_Name, t.* from temp_table_1 t
								join tms_queue_master tqm on t.queue_id=tqm.id');

END If;

if graph_type = 'monthly' THEN 

SET @droptable1 = CONCAT('DROP TABLE IF EXISTS temp_table_1;');
  PREPARE stmt_droptable1 FROM @droptable1;
  EXECUTE stmt_droptable1;
  DEALLOCATE PREPARE stmt_droptable1;

SET @sqlquery = CONCAT('Create table temp_table_1 as  SELECT ',queue_id,' Queue_id,  monthlist.months as Name, ', IFNULL(@exactcol1, ''), '  FROM
                                 (SELECT "JAN" months,1 num UNION ALL SELECT "FEB",2 num  UNION ALL SELECT "MAR",3 num  UNION ALL
                                  SELECT "APR",4 num UNION ALL SELECT "MAY",5 num  UNION ALL SELECT "JUN",6 num UNION ALL SELECT "JUL",7 num  UNION ALL
                                  SELECT "AUG",8 num UNION ALL SELECT "SEP",9 num UNION ALL SELECT " OCT",10 num UNION ALL SELECT "NOV",11 num  UNION ALL SELECT " DEC",12 num )monthlist
                                  LEFT JOIN (SELECT  MONTH(created_date) months,
                                  ', IFNULL(@exactcol2, ''), ' 
											 from tms_ticket_master_',queue_id,' ttm 
											 LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id
											 where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND YEAR(created_date) = YEAR(NOW())
                                  	',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
                                  GROUP BY MONTH(created_date))ttm ON monthlist.num=ttm.months'); 
 
#SELECT  @sqlquery; 
PREPARE stmtsqlquery FROM @sqlquery; 
EXECUTE stmtsqlquery; 
DEALLOCATE PREPARE stmtsqlquery; 
   
ALTER TABLE `temp_table_1` ADD INDEX `queue_id` (`queue_id`) USING BTREE;
	                               
SET @query=CONCAT('select tqm.queue as Queue_Name, t.* from temp_table_1 t
								join tms_queue_master tqm on t.queue_id=tqm.id');

END if;
				
if graph_type = 'Quarterly' THEN 

SET @droptable1 = CONCAT('DROP TABLE IF EXISTS temp_table_1;');
  PREPARE stmt_droptable1 FROM @droptable1;
  EXECUTE stmt_droptable1;
  DEALLOCATE PREPARE stmt_droptable1;

SET @sqlquery = CONCAT('Create table temp_table_1 as  SELECT ',queue_id,' Queue_id, concat("quarter ", Quarterlist.Quarterly) as Name, ', IFNULL(@exactcol1, ''), ' FROM
                                   (SELECT 1 Quarterly UNION ALL SELECT 2  UNION ALL SELECT 3  UNION ALL SELECT 4 )Quarterlist
                                    LEFT JOIN (SELECT  QUARTER(created_date)Quarterly,
                                     ', IFNULL(@exactcol2, ''), ' 
												 from tms_ticket_master_',queue_id,' ttm 
												 LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id
												 where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND YEAR(created_date) = YEAR(NOW())
                                     	',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
                                    GROUP BY QUARTER(created_date))ttm ON Quarterlist.Quarterly=ttm.Quarterly'); 
                                    
#SELECT  @sqlquery; 
PREPARE stmtsqlquery FROM @sqlquery; 
EXECUTE stmtsqlquery; 
DEALLOCATE PREPARE stmtsqlquery; 

ALTER TABLE `temp_table_1` ADD INDEX `queue_id` (`queue_id`) USING BTREE;

SET @query=CONCAT('select tqm.queue as Queue_Name, t.* from temp_table_1 t
								join tms_queue_master tqm on t.queue_id=tqm.id');

END if;
				
if graph_type = 'half Yearly' THEN 

SET @droptable1 = CONCAT('DROP TABLE IF EXISTS temp_table_1;');
  PREPARE stmt_droptable1 FROM @droptable1;
  EXECUTE stmt_droptable1;
  DEALLOCATE PREPARE stmt_droptable1;

SET @sqlquery = CONCAT('Create table temp_table_1 as  SELECT ',queue_id,' Queue_id, concat("halfYear ", halfYearlist.halfYear) as Name,', IFNULL(@exactcol1, ''), ' FROM
                                   (SELECT 1 halfYear UNION ALL SELECT 2)halfYearlist 
                                    LEFT JOIN (SELECT case when MONTH(created_date)>=1 AND MONTH(created_date)<=6 then 1 ELSE 2 END halfYear,
                                    ', IFNULL(@exactcol2, ''), ' 
												from tms_ticket_master_',queue_id,' ttm 
												LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id
												where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND YEAR(created_date) = YEAR(NOW())
                                    	',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
                                    GROUP BY halfYear)ttm ON halfYearlist.halfYear=ttm.halfYear'); 

#SELECT  @sqlquery; 
PREPARE stmtsqlquery FROM @sqlquery; 
EXECUTE stmtsqlquery; 
DEALLOCATE PREPARE stmtsqlquery; 

ALTER TABLE `temp_table_1` ADD INDEX `queue_id` (`queue_id`) USING BTREE;

SET @query=CONCAT('select tqm.queue as Queue_Name, t.* from temp_table_1 t
								join tms_queue_master tqm on t.queue_id=tqm.id');

END if;
				
if graph_type = 'Yearly' THEN 

SET @droptable1 = CONCAT('DROP TABLE IF EXISTS temp_table_1;');
  PREPARE stmt_droptable1 FROM @droptable1;
  EXECUTE stmt_droptable1;
  DEALLOCATE PREPARE stmt_droptable1;

SET @sqlquery = CONCAT('Create table temp_table_1 as  SELECT ',queue_id,' Queue_id,  Yearlist.Year as Name, ', IFNULL(@exactcol1, ''), ' FROM
                                  (SELECT 2023-10 YEAR UNION ALL SELECT 2023-9 UNION ALL SELECT 2023-8 UNION ALL SELECT 2023-7 UNION ALL
                                   SELECT 2023-6 UNION ALL SELECT 2023-5  UNION ALL SELECT 2023-4  UNION ALL SELECT 2023-3  UNION ALL SELECT 2023-2  UNION ALL
                                   SELECT 2023-1  UNION ALL SELECT 2023   UNION ALL SELECT 2023+1 UNION ALL SELECT 2023+2)Yearlist										  
                                   LEFT JOIN (SELECT YEAR(created_date)YEAR, ', IFNULL(@exactcol2, ''), ' 
											  from tms_ticket_master_',queue_id,' ttm 
											  LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id
											  where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0  AND YEAR(created_date)>= YEAR(NOW())-10 AND YEAR(created_date) <=YEAR(NOW())
                                   	',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
                                   GROUP BY YEAR(created_date))ttm ON Yearlist.Year=ttm.Year'); 

#SELECT  @sqlquery; 
PREPARE stmtsqlquery FROM @sqlquery; 
EXECUTE stmtsqlquery; 
DEALLOCATE PREPARE stmtsqlquery; 

ALTER TABLE `temp_table_1` ADD INDEX `queue_id` (`queue_id`) USING BTREE;

SET @query=CONCAT('select tqm.queue as Queue_Name, t.* from temp_table_1 t
								join tms_queue_master tqm on t.queue_id=tqm.id');

END if; 


#SELECT @QUERY; 
PREPARE stmtquery FROM @query; 
EXECUTE stmtquery; 
DEALLOCATE PREPARE stmtquery; 

    END LOOP;
    CLOSE queue_cursor;



SET SESSION group_concat_max_len = 1000000000000;

SET @Sql_Query=CONCAT ('SELECT COUNT(*) into @id  FROM tms_queue_master 
WHERE id IN (',queueid,')');

PREPARE stmt FROM @Sql_Query;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;


DROP TABLE IF EXISTS tempDays,tempWeek,tempMonthly,tempQuarterly,tempHalfYearly,tempYearly;

IF graph_type = 'daily' THEN

CREATE  TABLE tempDays(DAY INT); 
SET @sqlquery = CONCAT('INSERT INTO tempDays (day)
                SELECT * FROM (
                SELECT 01 day UNION SELECT 02 UNION SELECT 03 UNION SELECT 04 UNION SELECT 05 UNION SELECT 06 UNION SELECT 07 
                UNION SELECT 08 UNION SELECT 09 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12 UNION SELECT 13 UNION SELECT 14
                UNION SELECT 15 UNION SELECT 16 UNION SELECT 17 UNION SELECT 18 UNION SELECT 19 UNION SELECT 20 UNION SELECT 21 UNION SELECT 22
                UNION SELECT 23 UNION SELECT 24 UNION SELECT 25 UNION SELECT 26 UNION SELECT 27 UNION SELECT 28 UNION SELECT 29 UNION SELECT 30 
                UNION SELECT 31
                ) AS A;
	           	'); 
	           #SELECT @sqlquery;
					PREPARE stmtsqlquery FROM @sqlquery; 
					EXECUTE stmtsqlquery; 
					DEALLOCATE PREPARE stmtsqlquery; 
										
SET @query = CONCAT('SELECT GROUP_CONCAT(
    CONCAT("SELECT ",tqm.id, " as Queue_id,CONCAT(Case When LENGTH(A.day)<2 Then ""0"" ELSE """" END,A.day) as Name,ifnull(Total,0) Total FROM tempDays A LEFT JOIN (SELECT CONCAT(Case When LENGTH(day(ttm.created_date))<2 Then ""0"" ELSE """" END,day(ttm.created_date)) day,COUNT(1) Total
                from tms_ticket_master_",tqm.id, " ttm 
                WHERE IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND MONTH(created_date) = MONTH(NOW()) AND YEAR(created_date) = YEAR(NOW())
                	',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
                GROUP BY CONCAT(Case When LENGTH(day(ttm.created_date))<2 Then ""0"" ELSE """" END,day(ttm.created_date))) B ON A.day=B.day "
				 
    )
    SEPARATOR " UNION ALL "
)
 INTO @ttmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',queueid,')');
#SELECT @QUERY;
PREPARE stmtquery FROM @query; 
EXECUTE stmtquery; 
DEALLOCATE PREPARE stmtquery; 

if @id=1 then 

SET @sqlquery=CONCAT('select Queue_id,tqm.queue as Queue_Name,Name,Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id
								order by queue_id,Name');

ELSE 

SET @sqlquery=CONCAT('select Queue_id,Queue_Name,Name,Total from (select Queue_id,tqm.queue as Queue_Name,Name,Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id
								union all 
								select "0","ALL" ,Name,sum(Total) Total from (',@ttmtemp,')s
								join tms_queue_master tqm on queue_id=tqm.id
								group by Name)m
								order by case when queue_id="0" then 1 ELSE 0 END,queue_id,Name');

END if ;


END IF; 
	 

IF graph_type = 'weekly' THEN
CREATE  TABLE tempWeek (WEEK INT); 
SET @sqlquery = CONCAT('INSERT INTO tempWeek(WEEK)
                          SELECT * FROM (SELECT 1 WEEK UNION ALL SELECT 2  UNION ALL SELECT 3  UNION ALL SELECT 4  UNION ALL SELECT 5  
                     ) AS A;
						'); 
						PREPARE stmtsqlquery FROM @sqlquery; 
						EXECUTE stmtsqlquery; 
						DEALLOCATE PREPARE stmtsqlquery; 
						
						
SET @query = CONCAT('SELECT GROUP_CONCAT(
    CONCAT("SELECT ",tqm.id, " Queue_id,concat(""week "",A.WEEK) as Name, Total FROM tempWeek A 
                         LEFT JOIN (
                                    SELECT case when DAY(ttm.created_date)>=1 AND DAY(ttm.created_date)<=7 then 1
                                                when DAY(ttm.created_date)>=8 AND DAY(ttm.created_date)<=14 then 2
                                                when DAY(ttm.created_date)>=15 AND DAY(ttm.created_date)<=21 then 3
                                                when DAY(ttm.created_date)>=22 AND DAY(ttm.created_date)<=28 then 4
			                                    	ELSE 5 END WEEK,COUNT(1) total 
                                    FROM tms_ticket_master_",tqm.id, " ttm 
                                    WHERE IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND MONTH(created_date) = MONTH(NOW()) AND YEAR(created_date) = YEAR(NOW())
                                    	',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
                                    GROUP BY  case when DAY(ttm.created_date)>=1 AND DAY(ttm.created_date)<=7 then 1
                                                   when DAY(ttm.created_date)>=8 AND DAY(ttm.created_date)<=14 then 2
                                                   when DAY(ttm.created_date)>=15 AND DAY(ttm.created_date)<=21 then 3
                                                   when DAY(ttm.created_date)>=22 AND DAY(ttm.created_date)<=28 then 4
				                                       ELSE 5 END 				 				 
                                   ) B ON A.week = B.week"
    )
    SEPARATOR " UNION ALL "
)
 INTO @ttmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',queueid,')');
#SELECT @QUERY;
PREPARE stmtquery FROM @query; 
EXECUTE stmtquery; 
DEALLOCATE PREPARE stmtquery; 
    
if @id=1 then 

SET @sqlquery=CONCAT('select Queue_id,tqm.queue as Queue_Name,Name,ifnull(Total,0) Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id');

ELSE 

SET @sqlquery=CONCAT('select Queue_id,Queue_Name,Name,ifnull(Total,0) Total from (select Queue_id,tqm.queue as Queue_Name,Name,Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id
								union all 
								select "0","ALL" ,Name,sum(Total) Total from (',@ttmtemp,')s
								join tms_queue_master tqm on queue_id=tqm.id
								group by Name)m
								order by case when queue_id="0" then 1 ELSE 0 END,queue_id,Name');

END if ;    

END IF;
 
IF graph_type = 'monthly' THEN
CREATE  TABLE tempMonthly(MONTH VARCHAR(20),num INT); 
SET @sqlquery = CONCAT('INSERT INTO tempMonthly(MONTH,num)
                         SELECT * FROM (SELECT "JAN" MONTH,1 num  UNION ALL SELECT "FEB",2 num  UNION ALL SELECT "MAR",3 num  UNION ALL
                         SELECT "APR",4 num  UNION ALL SELECT "MAY",5 num  UNION ALL SELECT "JUN",6 num  UNION ALL SELECT "JUL",7 num  UNION ALL
                         SELECT "AUG",8 num  UNION ALL SELECT "SEP",9 num  UNION ALL SELECT " OCT",10 num  UNION ALL SELECT "NOV",11 num  UNION ALL SELECT " DEC",12 num  
								 ) AS A;
								'); 
							  
								PREPARE stmtsqlquery FROM @sqlquery; 
								EXECUTE stmtsqlquery; 
								DEALLOCATE PREPARE stmtsqlquery; 
								
SET @query = CONCAT('SELECT GROUP_CONCAT(
    CONCAT("SELECT ",tqm.id, " Queue_id, A.Month as Name,A.num, IFNULL(Total,0)Total FROM tempMonthly A 
                           LEFT JOIN (
                                     SELECT MONTH(ttm.created_date)MONTH,COUNT(1) total 
                                     FROM tms_ticket_master_",tqm.id, " ttm 
                                     WHERE IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND YEAR(created_date) = YEAR(NOW())
                                     	',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
                                     GROUP BY MONTH(ttm.created_date) 				 				 
                                    ) B ON A.num = B.Month"
    )
    SEPARATOR " UNION ALL "
)
 INTO @ttmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',queueid,')');
#SELECT @QUERY;
PREPARE stmtquery FROM @query; 
EXECUTE stmtquery; 
DEALLOCATE PREPARE stmtquery; 
    
if @id=1 then 

SET @sqlquery=CONCAT('select Queue_id,tqm.queue as Queue_Name,Name,Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id');

ELSE 

SET @sqlquery=CONCAT('select Queue_id,Queue_Name,Name,Total from (select Queue_id,tqm.queue as Queue_Name,num,Name,Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id
								union all 
								select "0","ALL" ,num,Name,sum(Total) Total from (',@ttmtemp,')s
								join tms_queue_master tqm on queue_id=tqm.id
								group by Name,num)m
								order by case when queue_id="0" then 1 ELSE 0 END,queue_id,num');

END if ;  
								
END IF;	
			

 IF graph_type = 'Quarterly' THEN

CREATE  TABLE tempQuarterly(Quarterly INT); 
SET @sqlquery = CONCAT('INSERT INTO tempQuarterly(Quarterly)
                                SELECT * FROM ( SELECT 1 Quarterly UNION ALL SELECT 2  UNION ALL SELECT 3  UNION ALL SELECT 4  
										  ) AS A;
										'); 
										PREPARE stmtsqlquery FROM @sqlquery; 
										EXECUTE stmtsqlquery; 
										DEALLOCATE PREPARE stmtsqlquery; 
										
						
SET @query = CONCAT('SELECT GROUP_CONCAT(
    CONCAT("SELECT ",tqm.id, " Queue_id,concat(""quarter "",A.Quarterly) as Name, IFNULL(Total,0)Total FROM tempQuarterly A 
                          LEFT JOIN (
                                    SELECT QUARTER(ttm.created_date)QUARTER,COUNT(1) total 
                                    FROM tms_ticket_master_",tqm.id, " ttm 
                                    WHERE IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND YEAR(created_date) = YEAR(NOW())
                                   	',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
                                    GROUP BY QUARTER(ttm.created_date) 				 				 
                                    ) B ON A.Quarterly = B.QUARTER"
    )
    SEPARATOR " UNION ALL "
)
 INTO @ttmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',queueid,')');
#SELECT @QUERY;
PREPARE stmtquery FROM @query; 
EXECUTE stmtquery; 
DEALLOCATE PREPARE stmtquery; 
    
if @id=1 then 

SET @sqlquery=CONCAT('select Queue_id,tqm.queue as Queue_Name,Name,Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id');

ELSE 

SET @sqlquery=CONCAT('select Queue_id,Queue_Name,Name,Total from (select Queue_id,tqm.queue as Queue_Name,Name,Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id
								union all 
								select "0","ALL" ,Name,sum(Total) Total from (',@ttmtemp,')s
								join tms_queue_master tqm on queue_id=tqm.id
								group by Name)m
								order by case when queue_id="0" then 1 ELSE 0 END,queue_id,Name');

END if ; 
										
END IF;
		 
IF graph_type = 'Half Yearly' THEN

CREATE  TABLE tempHalfYearly(halfYear INT); 
SET @sqlquery = CONCAT('INSERT INTO tempHalfYearly(halfYear)
                              SELECT * FROM (SELECT 1 halfYear UNION ALL SELECT 2 
                              ) AS A;
										'); 
										PREPARE stmtsqlquery FROM @sqlquery; 
										EXECUTE stmtsqlquery; 
										DEALLOCATE PREPARE stmtsqlquery; 
										
SET @query = CONCAT('SELECT GROUP_CONCAT(
    CONCAT("SELECT ",tqm.id, " Queue_id,concat(""halfYear "",A.halfYear) as Name, IFNULL(Total,0)Total FROM tempHalfYearly A 
                                LEFT JOIN (
                                SELECT case when MONTH(created_date)>=1 AND MONTH(created_date)<=6 then 1 ELSE 2 END DATE, COUNT(1) total 
                                FROM tms_ticket_master_",tqm.id, " ttm 
                                WHERE IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND YEAR(created_date) = YEAR(NOW())
                                	',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
                                GROUP BY case when MONTH(created_date)>=1 AND MONTH(created_date)<=6 then 1 ELSE 2 END				 				 
                               ) B ON A.halfYear = B.date"
    )
    SEPARATOR " UNION ALL "
)
 INTO @ttmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',queueid,')');
#SELECT @QUERY;
PREPARE stmtquery FROM @query; 
EXECUTE stmtquery; 
DEALLOCATE PREPARE stmtquery; 
    
if @id=1 then 

SET @sqlquery=CONCAT('select Queue_id,tqm.queue as Queue_Name,Name,Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id');

ELSE 

SET @sqlquery=CONCAT('select Queue_id,Queue_Name,Name,Total from (select Queue_id,tqm.queue as Queue_Name,Name,Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id
								union all 
								select "0","ALL" ,Name,sum(Total) Total from (',@ttmtemp,')s
								join tms_queue_master tqm on queue_id=tqm.id
								group by Name)m
								order by case when queue_id="0" then 1 ELSE 0 END,queue_id,Name');

END if ; 
										
END IF;
 IF graph_type = 'Yearly' THEN

CREATE  TABLE tempYearly(YEAR INT);
SET @sqlquery = CONCAT('INSERT INTO tempYearly(YEAR)
                             SELECT * FROM (SELECT YEAR(NOW())-10 year UNION ALL SELECT YEAR(NOW())-9 UNION ALL SELECT YEAR(NOW())-8 UNION ALL SELECT YEAR(NOW())-7 UNION ALL
                               SELECT YEAR(NOW())-6 UNION ALL SELECT YEAR(NOW())-5  UNION ALL SELECT YEAR(NOW())-4  UNION ALL SELECT YEAR(NOW())-3  UNION ALL SELECT YEAR(NOW())-2  UNION ALL
                               SELECT YEAR(NOW())-1  UNION ALL SELECT YEAR(NOW())   UNION ALL SELECT YEAR(NOW())+1 
								      ) AS A;
										'); 
										PREPARE stmtsqlquery FROM @sqlquery; 
										EXECUTE stmtsqlquery;
										DEALLOCATE PREPARE stmtsqlquery; 
										
SET @query = CONCAT('SELECT GROUP_CONCAT(
    CONCAT("SELECT ",tqm.id, " Queue_id, A.year as Name, IFNULL(Total,0)Total FROM tempYearly A 
                                LEFT JOIN (
                                SELECT YEAR(created_date)YEAR, COUNT(1) total 
                                 FROM tms_ticket_master_",tqm.id, " ttm 
                                 WHERE IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 AND YEAR(created_date)>= YEAR(NOW())-10 AND YEAR(created_date) <=YEAR(NOW())
                               	',if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=0,CONCAT(' and (ttm.assigned_to in(',userid,') or (ifnull(assigned_to,0)=0 AND ifnull(is_assigned,0)=0))'),""),
				if((IFNULL(userid,"")!="1" or IFNULL(fullcontrol,0)=0) and  IFNULL(all_ticket,0)=2 ,CONCAT(' and ttm.assigned_to in(',userid,') '),"") ,' 
                                 GROUP BY YEAR(created_date)				 				 
                                ) B ON A.year = B.year"
    )
    SEPARATOR " UNION ALL "
)
 INTO @ttmtemp
FROM tms_queue_master tqm 
WHERE tqm.id IN (',queueid,')');
#SELECT @QUERY;
PREPARE stmtquery FROM @query; 
EXECUTE stmtquery; 
DEALLOCATE PREPARE stmtquery; 
    
if @id=1 then 

SET @sqlquery=CONCAT('select Queue_id,tqm.queue as Queue_Name,Name,Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id');

ELSE 

SET @sqlquery=CONCAT('select Queue_id,Queue_Name,Name,Total from (select Queue_id,tqm.queue as Queue_Name,Name,Total from (',@ttmtemp,')t
								join tms_queue_master tqm on queue_id=tqm.id
								union all 
								select "0","ALL" ,Name,sum(Total) Total from (',@ttmtemp,')s
								join tms_queue_master tqm on queue_id=tqm.id
								group by Name)m
								order by case when queue_id="0" then 1 ELSE 0 END,queue_id,Name');
								

END IF; 

END IF; 

#SELECT @sqlquery;
PREPARE stmtsqlquery FROM @sqlquery; 
EXECUTE stmtsqlquery; 
DEALLOCATE PREPARE stmtsqlquery;

DROP TABLE IF EXISTS tempDays,tempWeek,tempMonthly,tempQuarterly,tempHalfYearly,tempYearly,temp_table_1; 

END
**
CREATE PROCEDURE `SLAReport`(
	IN `fromDate` VARCHAR(50),
	IN `toDate` VARCHAR(50),
	IN `user_id` VARCHAR(100),
	IN `ReportType` VARCHAR(50),
	IN `queue_id` INT,
	IN `fullcontrol` INT,
	IN `limit_offset` VARCHAR(30)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
   BEGIN
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
       SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
   
        ROLLBACK;   
   END; 
   START TRANSACTION;

SET @fromDate = case when IFNULL(fromDate,'')='' then CURDATE() ELSE fromDate END;
SET @toDate = case when IFNULL(toDate,'')='' then NOW() ELSE toDate END;

 SET SESSION group_concat_max_len = 10000000;
 SET @user_id=user_id;
 
SET @sql = CONCAT('SELECT group_concat(DISTINCT status_id) INTO @status_ids
FROM tms_user_master tum JOIN tms_statuspermission_',queue_id,' tsp ON tum.user_type=tsp.user_type
WHERE tsp.is_checked=1  ',if( IFNULL(user_id,"")!="",CONCAT(' AND tum.user_id in (',user_id,')'),""),' ');
#SELECT @SQL;
PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;
 
 
    SET @col1 = CONCAT('SELECT GROUP_CONCAT(CONCAT("SUM(CASE WHEN IFNULL(tqs.status_name, """") = ''",status_name,"'' THEN 1 ELSE 0 END) AS ''",status_name,"''"))  
    into @exactcol1
    FROM tms_queue_status_',queue_id,' tqs  where 1=1 ',if(IFNULL(fullcontrol,0)=0 AND IFNULL(@status_ids,'')!='',CONCAT('and  tqs.status_id in (',@status_ids,')'),""),' ORDER BY order_no ASC');
    #SELECT @col1;
    PREPARE stmtcol1 FROM @col1;
    EXECUTE stmtcol1;
    DEALLOCATE PREPARE stmtcol1; 
   
    SET @col2 = CONCAT('(SELECT GROUP_CONCAT(CONCAT("SUM(CASE WHEN IFNULL(tqs.status_name, """") = ''", status_name,"'' AND TIMESTAMPDIFF(second, IFNULL(IFNULL(ttm.assigned_on, NOW()), NOW()), NOW())/60 > IFNULL(tqp.tat *  60 , 10) THEN 1 ELSE 0 END) ''",status_name,"_TicketOutofSLA''")) 
    into @exactcol2
    FROM (SELECT order_no AS Sr, status_name FROM tms_queue_status_',queue_id,' tqs WHERE ticket_status_type IN ("2", "3")  ) AS status_master) ');
    #SELECT @col2;
    PREPARE stmtcol2 FROM @col2;
    EXECUTE stmtcol2;
    DEALLOCATE PREPARE stmtcol2;
    
    SET @col3 = CONCAT('(SELECT GROUP_CONCAT(CONCAT(
                        " SUM(CASE WHEN IFNULL(tqs.status_name, """") = ''", status_name,"'' AND TIMESTAMPDIFF(second, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date)/60 <= IFNULL(tqp.tat *  60 , 10) THEN 1 ELSE 0 END) ''",status_name,"_TicketWithInSLA'',"
                        "SUM(CASE WHEN IFNULL(tqs.status_name, """") = ''", status_name,"'' AND TIMESTAMPDIFF(second, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date)/60 > IFNULL(tqp.tat *  60 , 10) THEN 1 ELSE 0 END) ''",status_name,"_TicketOutofSLA''"
                        )) 
                        into @exactcol3
                        FROM (SELECT order_no AS Sr, status_name FROM tms_queue_status_',queue_id,' tqs WHERE IFNULL(tqs.is_close_status, "0") = 1 ) AS status_master ) 
							');
   # SELECT @col3;
    PREPARE stmtcol3 FROM @col3;
    EXECUTE stmtcol3;
    DEALLOCATE PREPARE stmtcol3;
    
    
    SET @sqlquery = 'SELECT  ';    
	 if ReportType = 'User Wise' Then
	    SET @sqlquery = CONCAT(@sqlquery, ' tum.user_name as "User Name" , tum.user_id as user_id  ');
	 ELSEIF ReportType = 'Date Wise' then 
	    SET @sqlquery = CONCAT(@sqlquery, ' DATE(IFNULL(ttm.assigned_on, NOW())) Date');    
    END if; 
	  
    SET @sqlquery = CONCAT(@sqlquery,'  , tqp.priority_name, tqp.colour_code, COUNT(1) AS TotalTicket, sum(if(ttm.is_new=1,1,0)) as `Unread Ticket`, ',if(IFNULL(@exactcol1,'')='','',CONCAT(@exactcol1,',')), '
	  ', if(IFNULL(@exactcol3,'')='','',CONCAT(@exactcol3,',')), '
	 ', if(IFNULL(@exactcol2,'')='','',CONCAT(@exactcol2,',')),     
    'ROUND((100/count(1))*SUM(CASE WHEN  IFNULL(tqs.is_close_status, "0") = 1 and TIMESTAMPDIFF(SECOND, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date)/60 <= IFNULL(tqp.tat *  60, 10)
				 THEN 1
				 ELSE 
				  0 END) ,2)
				   as SLAPercentage,
		sum(case when reply=1 and IFNULL(tqs.is_close_status, "0") = 1 then 1 else 0 end) First_reply,
		round(ifnull(sum(case when reply=1 and IFNULL(tqs.is_close_status, "0") = 1 then 1 else 0 end)*100/sum(case when IFNULL(tqs.is_close_status, "0") = 1 then 1 else 0 end),0),2) `FR Close PER`,  
	sum(case when reply>=1 AND TIMESTAMPDIFF(second, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date)/60 <= IFNULL(tqp.tat *  60 , 10)	then 1 else 0 end) `Reply Within TAT` ,
	round(ifnull(sum(case when reply>=1 AND TIMESTAMPDIFF(second, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date)/60 <= IFNULL(tqp.tat *  60 , 10)	then 1 else 0 end)*100/COUNT(1),0),2) `Reply Within TAT PER` ',    
    'FROM tms_ticket_master_',queue_id,' AS ttm ', 
    'LEFT JOIN tms_user_master tum ON tum.user_id = ttm.assigned_to ',
        
		/*JOIN (SELECT user_id FROM tms_user_master WHERE user_id=',user_id,' UNION ALL SELECT user_id FROM tms_user_master WHERE manager_id=',user_id,' UNION ALL SELECT 0) hie on hie.user_id=tum.user_id*/
	         
    'LEFT JOIN (SELECT MAX(conversation_id) AS Last_conversation_id, ticket_unique_id,SUM(case when conversation_type IN ("reply","reply_all")  then 1 ELSE 0 END) reply FROM tms_conversation_master_',queue_id,' tcm GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = ttm.ticket_unique_id ',
    'LEFT JOIN tms_conversation_master_',queue_id,' tcm ON tcm.conversation_id = Last_con.Last_conversation_id ', 	   
    'LEFT JOIN tms_queue_escalationmatrix_',queue_id,' tqe ON tqe.priority_id =ifnull(ttm.priority_id,3) AND (TIMESTAMPDIFF(SECOND, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date) / 3600) = hours AND ((TIMESTAMPDIFF(SECOND, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date) % 3600) / 60) >= minute ',   
    'LEFT JOIN tms_queue_priority_',queue_id,' tqp ON ttm.priority_id = tqp.priority_id ',
    'LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id ',
    ' where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 and IFNULL(ttm.is_draft,0)=0 ',if( IFNULL(user_id,"")!="",CONCAT(' and tum.user_id in (',user_id,')'),""),if(IFNULL(fullcontrol,0)=0 AND IFNULL(@status_ids,'')!='',CONCAT('and  tqs.status_id in (',@status_ids,')'),""), ' AND ttm.assigned_on>="',CONCAT(@fromDate, ' ','00:00:00'),'" and ttm.assigned_on<="',CONCAT(@toDate, ' ', '23:59:59'),'" '
    'GROUP BY priority_name, colour_code'
	 );
	 
	 if ReportType = 'User Wise' Then
	    SET @sqlquery = CONCAT(@sqlquery, ',tum.user_name,tum.user_id');
	 ELSEIF ReportType = 'Date Wise' then 
	    SET @sqlquery = CONCAT(@sqlquery, ',DATE(IFNULL(ttm.assigned_on, NOW()))');    
    END if;
	 
	 if limit_offset !='' then
	 	SET @sqlquery = CONCAT(@sqlquery,' LIMIT ', limit_offset);
	 END if;
   #SELECT @sqlquery;
 PREPARE stmtsqlquery FROM @sqlquery;
    EXECUTE stmtsqlquery;
    DEALLOCATE PREPARE stmtsqlquery;
COMMIT;
END
**
CREATE PROCEDURE `SLATicketlogReport`(
	IN `user_id` VARCHAR(255),
	IN `queue_id` VARCHAR(50),
	IN `sqlcondition` TEXT,
	IN `limit_offset` VARCHAR(10)
)
BEGIN
set  @a:=0;
#SELECT sqlcondition;
SET @wher = REPLACE(sqlcondition, "hours", "tqp.tat");

SET @wher = REPLACE(@wher, "TIMESTAMPDIFF(HOUR, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date)", "TIMESTAMPDIFF(second, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date)/3600");

SET @wher = REPLACE(@wher, "ttm.created_date", "IFNULL(ttm.assigned_on, NOW())");
#SELECT @wher;
SET @sqlquery=CONCAT ('select @a:=@a+1 as SrNo, 
ttm.ticket_unique_id AS ticket_id ,ttm.ticket_id AS ticket,ttm.Person_name,ttm.mobile_no,ctm.title AS MODE,
tms_queue_master.queue as Queue,tqp.priority_name as Priority,tqp.colour_code as PriorityColour,ttm.subject as subject,
tqs.status_name as Status,tqs.colour_code as StatusColour,
Case when IFNULL(tqs.is_close_status, "0") = 1 and TIMESTAMPDIFF(second,IFNULL(ttm.assigned_on, NOW()),conversation_date)/3600 <=ifnull(tqp.tat,10) then ''Yes'' else ''No'' end as IsClosedInSLA ,      
IFNULL(ttm.assigned_on, NOW()) as TicketStartDate,
Case when IFNULL(tqs.is_close_status, "0") = 1
 then conversation_date else now() end as ClsT_or_CUT,
concat(round(Case when IFNULL(tqs.is_close_status, "0") = 1
then TIMESTAMPDIFF(second,IFNULL(ttm.assigned_on, NOW()),tcm.conversation_date) 
else TIMESTAMPDIFF(second,IFNULL(ttm.assigned_on, NOW()),now()) end/ 86400,0)
,''d '',
sec_to_time(Case when IFNULL(tqs.is_close_status, "0") = 1 
then TIMESTAMPDIFF(second,IFNULL(ttm.assigned_on, NOW()),tcm.conversation_date) 
else TIMESTAMPDIFF(second,IFNULL(ttm.assigned_on, NOW()),now()) end % 86400)) AS TAT             
,tms_queue_category_',queue_id,'.category_name as Category,tms_queue_sub_category_',queue_id,'.sub_category_name as Subcategory,
 ifnull(tum.user_name,"Auto") as AssignedTo,tum.user_name as ReadBy 
from tms_ticket_master_',queue_id,' ttm
left Join tms_user_master tum on tum.user_id=ttm.assigned_to

/*JOIN (SELECT user_id FROM tms_user_master WHERE user_id=',user_id,' UNION ALL SELECT user_id FROM tms_user_master WHERE manager_id=',user_id,' UNION ALL SELECT 0) hie on hie.user_id=tum.user_id*/

left join tms_queue_priority_',queue_id,' tqp on tqp.priority_id=ttm.priority_id
left JOIN (SELECT MAX(conversation_id) AS Last_conversation_id, ticket_unique_id,SUM(case when conversation_type IN ("reply","reply_all")  then 1 ELSE 0 END) reply FROM tms_conversation_master_',queue_id,'  GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = ttm.ticket_unique_id 
left join tms_conversation_master_',queue_id,' tcm on tcm.conversation_id = Last_con.Last_conversation_id 	   
left JOIN tms_queue_escalationmatrix_',queue_id,' tqe ON tqe.priority_id =ifnull(ttm.priority_id,3) AND (TIMESTAMPDIFF(SECOND, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date) / 3600) = hours AND ((TIMESTAMPDIFF(SECOND, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date) % 3600) / 60) >= minute   
left Join tms_queue_master on ttm.queue_id = tms_queue_master.id
left join tms_conversation_type_master ctm on ctm.id=ttm.Start_mode
left join tms_queue_category_',queue_id,' on ttm.category_id = tms_queue_category_',queue_id,'.category_id
left join tms_queue_sub_category_',queue_id,' on ttm.subcategory_id = tms_queue_sub_category_',queue_id,'.sub_category_id
left join tms_queue_status_',queue_id,' tqs on tqs.status_id=ttm.status_id
where 1=1 AND IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 and IFNULL(ttm.is_draft,0) = 0 ',
 if( IFNULL(user_id,"")!="",CONCAT(' and tum.user_id in (',user_id,')'),""),'
');


if @wher!= '' then
	 set @sqlquery=CONCAT(@sqlquery,@wher);
END if;

if limit_offset !='' then
	SET @sqlquery = CONCAT(@sqlquery,' LIMIT ', limit_offset);
END if;
   
#SELECT @sqlquery;
PREPARE stmtsqlquery FROM @sqlquery;
    EXECUTE stmtsqlquery;
    DEALLOCATE PREPARE stmtsqlquery;
END
**
CREATE TABLE IF NOT EXISTS `sms_api_log_1` (
  `id` int NOT NULL AUTO_INCREMENT,
  `ticket_id` varchar(100) DEFAULT NULL,
  `conversation_id` varchar(100) DEFAULT NULL,
  `mobile_no` varchar(20) DEFAULT NULL,
  `response` text,
  `cr_date` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**
CREATE PROCEDURE `Split_string`(
	IN `queueid` INT,
	IN `mailid` TEXT
)
BEGIN
SET @in_string =CONCAT('',mailid,'');
SET @delimeter=',';
DROP TABLE if EXISTS insertmailid;
create table insertmailid (mailvalue VARCHAR(100));

 WHILE LENGTH(@in_string) > 0 DO

            INSERT INTO insertmailid(mailvalue)
            SELECT left(@in_string, INSTR(CONCAT(@in_string,','),@delimeter) -1) as mailvalue;
    
            SET @in_string = insert(@in_string, 1, INSTR(CONCAT(@in_string,@delimeter),@delimeter), '');
        END WHILE;

SET @QUERY=CONCAT('INSERT into tms_addressbook_',queueid,' (mailid) 
select distinct mailvalue FROM  insertmailid WHERE mailvalue NOT IN (SELECT mailid FROM tms_addressbook_',queueid,')');
PREPARE stmt FROM @QUERY; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;

DROP TABLE if EXISTS insertmailid;
END
**
CREATE TABLE IF NOT EXISTS `statustype_master` (
  `statustype_id` int NOT NULL AUTO_INCREMENT,
  `status_type` varchar(30) DEFAULT NULL,
  `created_date` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`statustype_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

**
INSERT INTO `statustype_master` (`statustype_id`, `status_type`, `created_date`) VALUES
	(1, 'Final Status', '2023-03-07 12:32:20'),
	(2, 'Initial Status', '2023-03-07 12:32:20'),
	(3, 'Non Final Status', '2023-03-07 12:32:20');

**
CREATE PROCEDURE `TATReport`(
	IN `fromDate` VARCHAR(50),
	IN `toDate` VARCHAR(50),
	IN `user_id` VARCHAR(100),
	IN `ReportType` VARCHAR(50),
	IN `queue_id` INT,
	IN `fullcontrol` INT,
	IN `limit_offset` VARCHAR(30)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
   BEGIN
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
       SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
   
        ROLLBACK;   
   END; 
   START TRANSACTION;

SET @fromDate = case when IFNULL(fromDate,'')='' then CURDATE() ELSE fromDate END;
SET @toDate = case when IFNULL(toDate,'')='' then NOW() ELSE toDate END;

 SET SESSION group_concat_max_len = 10000000;
 SET @user_id=user_id;
 
SET @sql = CONCAT('SELECT group_concat(DISTINCT status_id) INTO @status_ids
FROM tms_user_master tum JOIN tms_statuspermission_',queue_id,' tsp ON tum.user_type=tsp.user_type
WHERE tsp.is_checked=1  ',if( IFNULL(user_id,"")!="",CONCAT(' AND tum.user_id in (',user_id,')'),""),' ');
#SELECT @SQL;
PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;

SET @sqlquery = 'SELECT  ';    
if ReportType = 'User Wise' Then
 SET @sqlquery = CONCAT(@sqlquery, ' tum.user_name as "User Name" , tum.user_id as user_id,  ');
END if; 
	  
	    SET @sqlquery = CONCAT(@sqlquery, ' tqp.priority_name,tqp.colour_code, ',if(IFNULL(ReportType,"")="",CONCAT(' "TAT" TAT, '),""),' 
	    SUM(CASE WHEN First_conversation_date is not null and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)<=5
	    THEN 1 ELSE 0 END) `Within 0-5 Minutes`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN First_conversation_date is not null and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)<=5
	    THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `Within 0-5 Minutes%`,
 SUM(CASE WHEN First_conversation_date is not null and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)>=6
		 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)<=10
	    THEN 1 ELSE 0 END) `Within 6-10 Minutes`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN First_conversation_date is not null and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)>=6
		 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)<=10
	    THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `Within 6-10 Minutes%`,
 SUM(CASE WHEN First_conversation_date is not null and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)>=11
		 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)<=20
	    THEN 1 ELSE 0 END) `Within 11-20 Minutes`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN First_conversation_date is not null and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)>=11
		 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)<=20
	    THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `Within 11-20 Minutes%`,
 SUM(CASE WHEN First_conversation_date is not null and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)>=21
		 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)<=30
	    THEN 1 ELSE 0 END) `Within 21-30 Minutes`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN First_conversation_date is not null and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)>=21
		 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)<=30
	    THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `Within 21-30 Minutes%`,
	    SUM(CASE WHEN First_conversation_date is not null and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)>=31
	    THEN 1 ELSE 0 END) `>30 Minutes`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN First_conversation_date is not null and TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), First_conversation_date)>=31
	    THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `>30 Minutes%`,
	     SUM(CASE WHEN First_conversation_date IS NULL THEN 1 ELSE 0 END) `No Reply`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN First_conversation_date IS NULL THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `No Reply%`,
	    Count(1) `Total`,
	CONCAT(ROUND(IFNULL(Count(1)*100/NULLIF(Count(1),0),0),0),"%") `Total Percentage`
FROM tms_ticket_master_',queue_id,' AS ttm  
LEFT JOIN tms_user_master tum ON tum.user_id = ttm.assigned_to 
LEFT JOIN (SELECT MAX(conversation_id) AS Last_conversation_id, ticket_unique_id,SUM(case when conversation_type IN ("reply","reply_all")  then 1 ELSE 0 END) reply,min(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_date end) First_conversation_date FROM tms_conversation_master_',queue_id,' tcm GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = ttm.ticket_unique_id 
LEFT JOIN tms_conversation_master_',queue_id,' tcm ON tcm.conversation_id = Last_con.Last_conversation_id
LEFT JOIN tms_queue_priority_',queue_id,' tqp ON ttm.priority_id = tqp.priority_id 
LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id 
where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 and IFNULL(ttm.is_draft,0)=0 ',if( IFNULL(user_id,"")!="",CONCAT(' and tum.user_id in (',user_id,')'),""),if(IFNULL(fullcontrol,0)=0 AND IFNULL(@status_ids,'')!='',CONCAT('and  tqs.status_id in (',@status_ids,')'),""), ' AND ttm.assigned_on>="',CONCAT(@fromDate, ' ','00:00:00'),'" and ttm.assigned_on<="',CONCAT(@toDate, ' ', '23:59:59'),'" 
GROUP BY tqp.priority_name,tqp.colour_code'
);
	 
	 if ReportType = 'User Wise' Then
	    SET @sqlquery = CONCAT(@sqlquery, ' ,tum.user_name,tum.user_id');
    END if;
	 
	 if limit_offset !='' then
	 	SET @sqlquery = CONCAT(@sqlquery,' LIMIT ', limit_offset);
	 END if;
   #SELECT @sqlquery;
	PREPARE stmtsqlquery FROM @sqlquery;
    EXECUTE stmtsqlquery;
    DEALLOCATE PREPARE stmtsqlquery;
COMMIT;
END
**
CREATE PROCEDURE `TATTicketlogReport`(
	IN `user_id` VARCHAR(255),
	IN `queue_id` VARCHAR(50),
	IN `sqlcondition` TEXT,
	IN `limit_offset` VARCHAR(10)
)
BEGIN
set  @a:=0;

SET @sqlquery=CONCAT ('select @a:=@a+1 as SrNo, 
ttm.ticket_unique_id AS ticket_id ,ttm.ticket_id AS ticket,ttm.Person_name,ttm.mobile_no,ctm.title AS MODE,
tms_queue_master.queue as Queue,tqp.priority_name as Priority,tqp.colour_code as PriorityColour,ttm.subject as subject,concat(DATE_FORMAT(ttm.created_date,''%d-%m-%Y %H:%i:%s'') ,''\n'', DATE_FORMAT(ttm.last_updated_on,''%d-%m-%Y %H:%i:%s'')) as date_update,
DATE_FORMAT(ttm.created_date,''%d-%m-%Y %H:%i:%s'') created_date,
DATE_FORMAT(ttm.last_updated_on,''%d-%m-%Y %H:%i:%s'') last_updated_on,
tqs.status_name as Status,tqs.colour_code as StatusColour,
Case when IFNULL(tqs.is_close_status, "0") = 1 and TIMESTAMPDIFF(second,IFNULL(ttm.assigned_on, NOW()),conversation_date)/3600 <=ifnull(tqp.tat,10) then ''Yes'' else ''No'' end as IsClosedInSLA ,      
IFNULL(DATE_FORMAT(ttm.assigned_on,''%d-%m-%Y %H:%i:%s''), DATE_FORMAT(NOW(),''%d-%m-%Y %H:%i:%s'')) as TicketStartDate,
Case when IFNULL(tqs.is_close_status, "0") = 1
 then DATE_FORMAT(conversation_date,''%d-%m-%Y %H:%i:%s'') else DATE_FORMAT(NOW(),''%d-%m-%Y %H:%i:%s'') end as ClsT_or_CUT,
concat(round(Case when IFNULL(tqs.is_close_status, "0") = 1
then TIMESTAMPDIFF(second,IFNULL(DATE_FORMAT(ttm.assigned_on,''%d-%m-%Y %H:%i:%s''), DATE_FORMAT(NOW(),''%d-%m-%Y %H:%i:%s'')),DATE_FORMAT(conversation_date,''%d-%m-%Y %H:%i:%s'')) 
else TIMESTAMPDIFF(second,IFNULL(DATE_FORMAT(ttm.assigned_on,''%d-%m-%Y %H:%i:%s''), DATE_FORMAT(NOW(),''%d-%m-%Y %H:%i:%s'')),DATE_FORMAT(NOW(),''%d-%m-%Y %H:%i:%s'')) end/ 86400,0)
,''d '',
sec_to_time(Case when IFNULL(tqs.is_close_status, "0") = 1 
then TIMESTAMPDIFF(second,IFNULL(DATE_FORMAT(ttm.assigned_on,''%d-%m-%Y %H:%i:%s''), DATE_FORMAT(NOW(),''%d-%m-%Y %H:%i:%s'')),DATE_FORMAT(conversation_date,''%d-%m-%Y %H:%i:%s'')) 
else TIMESTAMPDIFF(second,IFNULL(DATE_FORMAT(ttm.assigned_on,''%d-%m-%Y %H:%i:%s''), DATE_FORMAT(NOW(),''%d-%m-%Y %H:%i:%s'')),DATE_FORMAT(NOW(),''%d-%m-%Y %H:%i:%s'')) end % 86400)) AS TAT             
,tms_queue_category_',queue_id,'.category_name as Category,tms_queue_sub_category_',queue_id,'.sub_category_name as Subcategory,
 ifnull(tum.user_name,"Auto") as AssignedTo,tum.user_name as ReadBy,DATE_FORMAT(First_conversation_date,''%d-%m-%Y %H:%i:%s'') First_conversation_date
from tms_ticket_master_',queue_id,' ttm
left Join tms_user_master tum on tum.user_id=ttm.assigned_to
left join tms_queue_priority_',queue_id,' tqp on tqp.priority_id=ttm.priority_id
left JOIN (SELECT MAX(conversation_id) AS Last_conversation_id, ticket_unique_id,SUM(case when conversation_type IN ("reply","reply_all")  then 1 ELSE 0 END) reply,min(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_date end) First_conversation_date FROM tms_conversation_master_',queue_id,'  GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = ttm.ticket_unique_id 
left join tms_conversation_master_',queue_id,' tcm on tcm.conversation_id = Last_con.Last_conversation_id	   
left JOIN tms_queue_escalationmatrix_',queue_id,' tqe ON tqe.priority_id =ifnull(ttm.priority_id,3) AND (TIMESTAMPDIFF(SECOND, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date) / 3600) = hours AND ((TIMESTAMPDIFF(SECOND, IFNULL(ttm.assigned_on, NOW()), tcm.conversation_date) % 3600) / 60) >= minute   
left Join tms_queue_master on ttm.queue_id = tms_queue_master.id
left join tms_conversation_type_master ctm on ctm.id=ttm.Start_mode
left join tms_queue_category_',queue_id,' on ttm.category_id = tms_queue_category_',queue_id,'.category_id
left join tms_queue_sub_category_',queue_id,' on ttm.subcategory_id = tms_queue_sub_category_',queue_id,'.sub_category_id
left join tms_queue_status_',queue_id,' tqs on tqs.status_id=ttm.status_id
where 1=1 AND IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 and IFNULL(ttm.is_draft,0) = 0 ',
 if( IFNULL(user_id,"")!="",CONCAT(' and tum.user_id in (',user_id,')'),""),'
');


if sqlcondition!= '' then
	 set @sqlquery=CONCAT(@sqlquery,sqlcondition);
END if;

if limit_offset !='' then
	SET @sqlquery = CONCAT(@sqlquery,' LIMIT ', limit_offset);
END if;
   
#SELECT @sqlquery;
PREPARE stmtsqlquery FROM @sqlquery;
    EXECUTE stmtsqlquery;
    DEALLOCATE PREPARE stmtsqlquery;
END
**
CREATE TABLE IF NOT EXISTS `temp` (
  `is_attachment` bigint NOT NULL DEFAULT '0',
  `ticket_prefix` varchar(10) DEFAULT NULL,
  `ticket_unique_id` int NOT NULL DEFAULT '0',
  `ticket_id` varchar(50) DEFAULT NULL,
  `person_name` varchar(50) DEFAULT NULL,
  `mobile_no` varchar(16) DEFAULT NULL,
  `unique_id` varchar(15) DEFAULT NULL,
  `parent_id` varchar(50) DEFAULT NULL,
  `subject` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
  `start_date` datetime DEFAULT CURRENT_TIMESTAMP,
  `cc_email` varchar(2000) DEFAULT NULL,
  `bcc_email` varchar(2000) DEFAULT NULL,
  `start_mode` int DEFAULT NULL,
  `status_id` int DEFAULT NULL,
  `priority_id` int DEFAULT NULL,
  `queue_id` int DEFAULT NULL,
  `last_updated_on` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `is_read` bit(1) DEFAULT NULL,
  `read_by` int DEFAULT NULL,
  `read_date` datetime DEFAULT NULL,
  `mail_date` datetime DEFAULT NULL,
  `is_assigned` tinyint DEFAULT '0',
  `assigned_to` varchar(50) DEFAULT NULL,
  `assigned_by` int DEFAULT '0',
  `assigned_on` datetime DEFAULT NULL,
  `last_updated_by` int DEFAULT NULL,
  `phone_no` varchar(16) DEFAULT NULL,
  `category_id` int DEFAULT NULL,
  `subcategory_id` int DEFAULT NULL,
  `follow_up_date` datetime DEFAULT NULL,
  `ticket_created_by` int DEFAULT NULL,
  `is_assigned_open_ticket` bit(1) DEFAULT NULL,
  `remarks` varchar(100) DEFAULT NULL,
  `is_replied_mail` bit(1) DEFAULT NULL,
  `is_forward_mail` bit(1) DEFAULT NULL,
  `created_date` datetime DEFAULT CURRENT_TIMESTAMP,
  `happy_code` int DEFAULT NULL,
  `escalation_id` int DEFAULT NULL,
  `last_escalation_on` datetime DEFAULT NULL,
  `hold_date` datetime DEFAULT NULL,
  `incoming_mail_id` varchar(100) DEFAULT NULL,
  `is_new` tinyint DEFAULT '0' COMMENT '0 => not read,1 =>read',
  `parent_ticket_id` int DEFAULT NULL,
  `parent_ticket_id_text` varchar(30) DEFAULT NULL,
  `is_junk` tinyint DEFAULT '0',
  `is_deleted_ticket` tinyint DEFAULT '0',
  `is_closed` tinyint DEFAULT '0' COMMENT '0 => not closed,1 =>ticket_closed',
  `is_auto` tinyint DEFAULT '0',
  `deleted_date` datetime DEFAULT NULL,
  `to_email` text,
  `from_email` varchar(500) DEFAULT NULL,
  `priority_name` varchar(100) DEFAULT NULL,
  `prClr` varchar(50) DEFAULT NULL,
  `status_name` varchar(50) DEFAULT NULL,
  `stClr` varchar(50) DEFAULT NULL,
  `is_close_status` tinyint DEFAULT '0' COMMENT '0 => ''not close'',1 => ''close''',
  `user_name` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**

CREATE TABLE IF NOT EXISTS `temp_user_assigned_1` (
  `user_id` bigint NOT NULL DEFAULT '0',
  `Open_Tickets` decimal(23,0) NOT NULL DEFAULT '0',
  `Pending_Tickets` decimal(23,0) NOT NULL DEFAULT '0',
  `Hold_Tickets` decimal(23,0) NOT NULL DEFAULT '0',
  `Reopen_Tickets` decimal(23,0) NOT NULL DEFAULT '0',
  `movetoanotherqueue_Tickets` decimal(23,0) NOT NULL DEFAULT '0',
  `manualassign_Tickets` decimal(23,0) NOT NULL DEFAULT '0',
  `test1_Tickets` decimal(23,0) NOT NULL DEFAULT '0',
  `reopen/close_Tickets` decimal(23,0) NOT NULL DEFAULT '0',
  `Close_Tickets` decimal(23,0) NOT NULL DEFAULT '0',
  `Open_1_id` bigint DEFAULT NULL,
  `Pending_3_id` bigint DEFAULT NULL,
  `Hold_4_id` bigint DEFAULT NULL,
  `Reopen_5_id` bigint DEFAULT NULL,
  `movetoanotherqueue_6_id` bigint DEFAULT NULL,
  `manualassign_7_id` bigint DEFAULT NULL,
  `test1_8_id` bigint DEFAULT NULL,
  `reopen/close_9_id` bigint DEFAULT NULL,
  `Close_2_id` bigint DEFAULT NULL,
  `AutoAssigned` decimal(23,0) NOT NULL DEFAULT '0',
  `AssignedByOthers` decimal(23,0) NOT NULL DEFAULT '0',
  `AssignedToOthers` decimal(23,0) NOT NULL DEFAULT '0',
  `AssignedToSelf` decimal(23,0) NOT NULL DEFAULT '0',
  `AssignedTotalTicket` bigint NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `ticket_action_log` (
  `id` int NOT NULL AUTO_INCREMENT,
  `log_date` datetime DEFAULT NULL,
  `queue_id` int DEFAULT NULL,
  `ticket_id` int DEFAULT NULL,
  `login_id` int DEFAULT NULL,
  `log_action` varchar(50) DEFAULT NULL,
  `action_detail` varchar(300) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=latin1;

**

CREATE PROCEDURE `Ticket_Closure_Report`(
	IN `fromDate` VARCHAR(50),
	IN `toDate` VARCHAR(50),
	IN `user_id` VARCHAR(100),
	IN `ReportType` VARCHAR(50),
	IN `queue_id` INT,
	IN `fullcontrol` INT,
	IN `limit_offset` VARCHAR(30)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
   BEGIN
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
       SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
   
        ROLLBACK;   
   END; 
   START TRANSACTION;

SET @fromDate = case when IFNULL(fromDate,'')='' then CURDATE() ELSE fromDate END;
SET @toDate = case when IFNULL(toDate,'')='' then NOW() ELSE toDate END;

SET SESSION group_concat_max_len = 10000000;
 
SET @sql = CONCAT('SELECT group_concat(DISTINCT status_id) INTO @status_ids
FROM tms_user_master tum JOIN tms_statuspermission_',queue_id,' tsp ON tum.user_type=tsp.user_type
WHERE tsp.is_checked=1  ',if( IFNULL(user_id,"")!="",CONCAT(' AND tum.user_id in (',user_id,')'),""),' ');
#SELECT @SQL;
PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;
 
    SET @sqlquery = 'SELECT  ';    
	 if ReportType = 'User Wise' Then
	    SET @sqlquery = CONCAT(@sqlquery, ' tum.user_name as "User Name" , tum.user_id as user_id,  ');
    END if; 
	  
	    SET @sqlquery = CONCAT(@sqlquery, ' tqp.priority_name, tqp.colour_code,',if(IFNULL(ReportType,"")="",CONCAT(' "Ticket Closure" `Ticket Closure`, '),""),' 
	    SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=5
	    THEN 1 ELSE 0 END) `Within 0-5 Minutes`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=5
	    THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `Within 0-5 Minutes%`,
 SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=6
		 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=10
	    THEN 1 ELSE 0 END) `Within 6-10 Minutes`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=6
		 AND TIMESTAMPDIFF(MINUTE,IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=10
	     THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `Within 6-10 Minutes%`,
 SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=11
		 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=20
	    THEN 1 ELSE 0 END) `Within 11-20 Minutes`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=11
		 AND TIMESTAMPDIFF(MINUTE,IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=20
	     THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `Within 11-20 Minutes%`,
 SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=21
		 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=30
	    THEN 1 ELSE 0 END) `Within 21-30 Minutes`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=21
		 AND TIMESTAMPDIFF(MINUTE,IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=30
	     THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `Within 21-30 Minutes%`,
 SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=31
		 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=120
	    THEN 1 ELSE 0 END) `>30 Minutes`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=31
		 AND TIMESTAMPDIFF(MINUTE,IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=120
	     THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `>30 Minutes%`,
 SUM(CASE WHEN TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=2
		 AND TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=24
	    THEN 1 ELSE 0 END) `>2 Hours`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=2
		 AND TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=24
	    THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `>2 Hours%`,
 SUM(CASE WHEN TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=24 THEN 1 ELSE 0 END) `>24 Hours`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=24 THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `>24 Hours%`,

	    Count(1) `Total`,
	CONCAT(ROUND(IFNULL(Count(1)*100/NULLIF(Count(1),0),0),0),"%") `Total Percentage`
FROM tms_ticket_master_',queue_id,' AS ttm  
LEFT JOIN tms_user_master tum ON tum.user_id = ttm.assigned_to 
LEFT JOIN (SELECT MAX(conversation_id) AS Last_conversation_id, ticket_unique_id,IFNULL(SUM(case when conversation_type IN ("reply","reply_all")  then 1 ELSE 0 END),0) reply,min(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_date end) First_conversation_date FROM tms_conversation_master_',queue_id,' tcm GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = ttm.ticket_unique_id 
LEFT JOIN tms_conversation_master_',queue_id,' tcm ON tcm.conversation_id = Last_con.Last_conversation_id
LEFT JOIN tms_queue_priority_',queue_id,' tqp ON ttm.priority_id = tqp.priority_id 
LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id 
where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 and IFNULL(ttm.is_draft,0)=0 ',if( IFNULL(user_id,"")!="",CONCAT(' and tum.user_id in (',user_id,')'),""),if(IFNULL(fullcontrol,0)=0 AND IFNULL(@status_ids,'')!='',CONCAT('and  tqs.status_id in (',@status_ids,')'),""), ' AND ttm.assigned_on>="',CONCAT(@fromDate, ' ','00:00:00'),'" and ttm.assigned_on<="',CONCAT(@toDate, ' ', '23:59:59'),'" 
AND tqs.ticket_status_type=1
GROUP BY tqp.priority_name, tqp.colour_code'
);
	 
	 if ReportType = 'User Wise' Then
	    SET @sqlquery = CONCAT(@sqlquery, ' ,tum.user_name,tum.user_id');
    END if;
	 
	 if limit_offset !='' then
	 	SET @sqlquery = CONCAT(@sqlquery,' LIMIT ', limit_offset);
	 END if;
   #SELECT @sqlquery;
	PREPARE stmtsqlquery FROM @sqlquery;
    EXECUTE stmtsqlquery;
    DEALLOCATE PREPARE stmtsqlquery;
COMMIT;
END
**
CREATE TABLE IF NOT EXISTS `ticket_draft_1` (
  `id` int NOT NULL AUTO_INCREMENT,
  `ticket_id` int DEFAULT '0',
  `conversation_id` int DEFAULT '0',
  `created_date` int DEFAULT '0',
  `modified_date` int DEFAULT '0',
  `created_by` int DEFAULT '0',
  `modified_by` int DEFAULT '0',
  `status` int DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_addressbook_1` (
  `id` int NOT NULL AUTO_INCREMENT,
  `mailid` varchar(50) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mailid` (`mailid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_break_master` (
  `id` int NOT NULL AUTO_INCREMENT,
  `title` varchar(50) DEFAULT NULL,
  `break_time` int DEFAULT NULL,
  `status` tinyint DEFAULT NULL,
  `office_break` tinyint DEFAULT NULL,
  `created_by` int DEFAULT NULL,
  `created_date` datetime DEFAULT CURRENT_TIMESTAMP,
  `modified_by` int DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_break_master` (`id`, `title`, `break_time`, `status`, `office_break`, `created_by`, `created_date`, `modified_by`, `modified_date`) VALUES
	(1, 'Lunch Break', 1, 1, 0, 1, '2024-04-12 15:30:26', 38, '2024-06-29 13:54:29'),
	(3, 'Evening Break', 10, 1, 0, 38, '2024-04-18 13:42:08', 59, '2024-07-01 11:45:19'),
	(4, ' Break', 10, 1, 1, 59, '2024-06-29 12:42:25', NULL, '2024-06-29 13:54:50');

**
CREATE TABLE IF NOT EXISTS `tms_client_log` (
  `id` int NOT NULL AUTO_INCREMENT,
  `page_name` varchar(255) NOT NULL DEFAULT '0',
  `method` varchar(255) DEFAULT NULL,
  `user_id` int DEFAULT NULL,
  `type` int DEFAULT NULL,
  `message` longtext,
  `remote_ip` varchar(255) DEFAULT NULL,
  `data` longtext NOT NULL,
  `datetime` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_company_master` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(30) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `mobile_no` varchar(16) DEFAULT NULL,
  `website` varchar(50) DEFAULT NULL,
  `address` varchar(50) DEFAULT NULL,
  `smtp_email` varchar(50) DEFAULT NULL,
  `smtp_password` varchar(50) DEFAULT NULL,
  `smtp_email_server` varchar(50) DEFAULT NULL,
  `smtp_port` varchar(50) DEFAULT NULL,
  `smtp_cc_email` varchar(50) DEFAULT NULL,
  `enable_ssl` tinyint DEFAULT NULL,
  `verify_ssl` tinyint DEFAULT NULL,
  `cc_to_smtp_email` tinyint DEFAULT NULL,
  `emailserver` varchar(50) DEFAULT NULL,
  `pagesize` varchar(50) DEFAULT NULL,
  `mailassignlimit` varchar(50) DEFAULT NULL,
  `assigntimegap` varchar(50) DEFAULT NULL,
  `acesstoken` varchar(50) DEFAULT NULL,
  `ticketprifix` varchar(50) DEFAULT NULL,
  `sendmailmanualasiign` int DEFAULT NULL,
  `Queuewisericketprefix` int DEFAULT NULL,
  `serverkey` varchar(50) DEFAULT NULL,
  `senderkey` varchar(50) DEFAULT NULL,
  `companylogo` varchar(100) DEFAULT NULL,
  `all_ticket` tinyint DEFAULT NULL,
  `created_by` varchar(50) DEFAULT NULL,
  `created_date` datetime DEFAULT NULL,
  `modified_by` varchar(50) DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL,
  `status` tinyint DEFAULT NULL,
  `check_on` datetime DEFAULT NULL,
  `message` text,
  `is_valid` int DEFAULT NULL,
  `opt` varchar(4) DEFAULT NULL,
  `has_filter_conversation` tinyint DEFAULT NULL,
  `auto_generate_password` tinyint DEFAULT '0',
  `admin_change_password` tinyint DEFAULT '0',
  `admin_reset_password` tinyint DEFAULT '0',
  `admin_reset_password_days` varchar(50) DEFAULT NULL,
  `admin_previous_password_reused` tinyint DEFAULT NULL,
  `admin_enable_otp` tinyint DEFAULT NULL,
  `agent_change_password` tinyint DEFAULT NULL,
  `agent_reset_password` tinyint DEFAULT NULL,
  `agent_reset_password_days` varchar(50) DEFAULT NULL,
  `agent_previous_password_reused` tinyint DEFAULT NULL,
  `agent_enable_otp` tinyint DEFAULT NULL,
  `otp_attempt_count` varchar(50) DEFAULT NULL,
  `password_sms_api` varchar(200) DEFAULT NULL,
  `sms_template` varchar(250) DEFAULT NULL,
  `auto_logout_session_time` time DEFAULT NULL,
  `api_access_key` text,
  `api_access_token` text,
  `base_url` varchar(255) DEFAULT NULL,
  `ssh_hostname` varchar(50) DEFAULT NULL,
  `date_difference` varchar(50) DEFAULT '31',
  `ssh_port` int DEFAULT NULL,
  `ssh_username` varchar(100) DEFAULT NULL,
  `ssh_password` varchar(100) DEFAULT NULL,
  `http_port` int DEFAULT NULL,
  `https_port` int DEFAULT NULL,
  `ssl_key` text,
  `ssl_cert` text,
  `draft_time` text,
`has_captcha` TINYINT(1) NULL DEFAULT '0',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_company_master` (`id`, `name`, `email`, `mobile_no`, `website`, `address`, `smtp_email`, `smtp_password`, `smtp_email_server`, `smtp_port`, `smtp_cc_email`, `enable_ssl`, `verify_ssl`, `cc_to_smtp_email`, `emailserver`, `pagesize`, `mailassignlimit`, `assigntimegap`, `acesstoken`, `ticketprifix`, `sendmailmanualasiign`, `Queuewisericketprefix`, `serverkey`, `senderkey`, `companylogo`, `all_ticket`, `created_by`, `created_date`, `modified_by`, `modified_date`, `status`, `check_on`, `message`, `is_valid`, `opt`, `has_filter_conversation`, `auto_generate_password`, `admin_change_password`, `admin_reset_password`, `admin_reset_password_days`, `admin_previous_password_reused`, `admin_enable_otp`, `agent_change_password`, `agent_reset_password`, `agent_reset_password_days`, `agent_previous_password_reused`, `agent_enable_otp`, `otp_attempt_count`, `password_sms_api`, `sms_template`, `auto_logout_session_time`, `api_access_key`, `api_access_token`, `base_url`, `ssh_hostname`, `date_difference`, `ssh_port`, `ssh_username`, `ssh_password`, `http_port`, `https_port`, `ssl_key`, `ssl_cert`, `draft_time`) VALUES
	(2, 'San Softwares Pvt Ltd', 'support@sansoftwares.com', '', 'sansoftwares.com', '419-20 4th floor M3M Urbana Sec 67 Gurugram', 'kishan.yadav@sansoftwares.in', 'S@N1@2$@N@20250428', 'mail.sansoftwares.in', '587', 'kishan.yadav@sansoftwares.in', 1, 1, 0, '587', '100', '1000', '5', 'e04a7b92f7de3ac1bd2d53c78f9aebfc', 'no prefix', 1, 1, 'no server key', 'no sender key', '661a3e107187b.png', 1, '1', '2024-03-04 18:57:41', '1', '2025-04-29 13:56:16', 1, '2024-07-22 12:28:51', 'Outgoing email tested successfully', 1, NULL, 1, 1, 0, 0, '2', 1, 0, 1, 0, '3', 0, 1, '2', 'https://alerts.cbis.in/SMSApi/send?userid=sansoft&password=Nj7XDV44Zakq9vY&sendMethod=quick&senderid=SANSOF&msgType=text&mobile=919650247267&msg={{msg}}', 'Your one time verification code is {{code}}. Please enter this code to complete your verification at SAN Softwares.', '06:30:00', 'SanTMS', '4775d868f2972eaae47323a0e555d9efb4e7f28b75bac93094bc161f5c7d31dc', 'http://localhost:4200', 'localhost', '31', 22, 'kishan', '$aNdEv@1806#', 3000, NULL, '', '', '3 min');

**

CREATE TABLE IF NOT EXISTS `tms_conversation_attachements_1` (
  `attachement_id` int NOT NULL AUTO_INCREMENT,
  `ticket_id` varchar(100) DEFAULT NULL,
  `ticket_unique_id` int DEFAULT NULL,
  `conversation_id` int DEFAULT NULL,
  `attachement_name` varchar(200) DEFAULT NULL,
  `content_type` varchar(200) DEFAULT NULL,
  `attachement_filepath` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`attachement_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_conversation_master_1` (
  `conversation_id` int NOT NULL AUTO_INCREMENT,
  `conversation_date` datetime DEFAULT NULL,
  `conversation_type` varchar(50) DEFAULT NULL,
  `ticket_unique_id` int DEFAULT NULL,
  `ticket_id` varchar(50) DEFAULT NULL,
  `mobile_no` varchar(16) DEFAULT NULL,
  `person_name` varchar(50) CHARACTER SET utf32 COLLATE utf32_unicode_ci DEFAULT NULL,
  `email_uid` text,
  `account_id` int DEFAULT NULL,
  `from_email` text,
  `to_email` text,
  `cc_email` text,
  `bcc_email` text,
  `subject` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
  `sms_conversation` text,
  `category_id` varchar(7) DEFAULT NULL,
  `subcategory_id` varchar(7) DEFAULT NULL,
  `status_id` int DEFAULT NULL,
  `priority_id` int DEFAULT NULL,
  `queue_id` int DEFAULT NULL,
  `login_id` int DEFAULT NULL,
  `email_status` varchar(30) DEFAULT NULL,
  `sms_status` varchar(30) DEFAULT NULL,
  `whatsapp_status` varchar(30) DEFAULT NULL,
  `no_of_try` int DEFAULT NULL,
  `max_try` int DEFAULT '5',
  `email_message_id` text,
  `sms_no_of_try` int DEFAULT NULL,
  `sms_max_try` int DEFAULT '5',
  `fetch_xml_uid` text,
  `hold_date` datetime DEFAULT NULL,
  `json_file_name` text,
  `footer_url` text,
  `is_draft` tinyint DEFAULT '0',
  PRIMARY KEY (`conversation_id`),
  KEY `conversation_date` (`conversation_date`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**
CREATE TABLE IF NOT EXISTS `tms_conversation_type_master` (
  `id` int NOT NULL AUTO_INCREMENT,
  `title` varchar(50) DEFAULT NULL,
  `mobile_mandatory` tinyint NOT NULL DEFAULT '0',
  `mail_mandatory` tinyint NOT NULL DEFAULT '0',
  `is_default` tinyint NOT NULL DEFAULT '0',
  `status` tinyint DEFAULT '1',
  `created_by` int DEFAULT NULL,
  `created_date` datetime DEFAULT CURRENT_TIMESTAMP,
  `modified_by` int DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `con_type_img` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_conversation_type_master` (`id`, `title`, `mobile_mandatory`, `mail_mandatory`, `is_default`, `status`, `created_by`, `created_date`, `modified_by`, `modified_date`, `con_type_img`) VALUES
	(1, 'Incoming Call', 1, 0, 0, 1, 1, '2023-05-19 10:17:31', NULL, NULL, 'Incoming.png'),
	(2, 'Outgoing Call', 1, 0, 0, 1, 1, '2023-05-19 10:25:04', 1, '2023-05-19 10:25:04', 'Outgoing.png'),
	(3, 'E-Mail', 1, 1, 1, 1, 1, '2024-03-07 12:47:15', 1, '2024-08-31 15:08:01', 'email.png'),
	(5, 'Whatsapp', 1, 0, 0, 0, 47, '2023-06-30 12:58:18', 1, '2024-04-12 17:48:19', 'whatsapp.png'),
	(6, 'Facebook', 0, 1, 0, 1, 1, '2023-05-19 10:26:14', 1, '2024-03-30 09:49:48', 'facebook.png'),
	(7, 'Twitter', 1, 0, 0, 1, 1, '2023-05-19 10:26:27', 1, '2024-03-28 14:36:31', 'Twitter.png'),
	(11, 'Chat', 1, 0, 0, 1, 1, '2024-08-31 15:08:45', NULL, NULL, 'chat.png');

**
CREATE TABLE IF NOT EXISTS `tms_dynamicform_fields_1` (
  `field_id` int NOT NULL AUTO_INCREMENT,
  `field_name` varchar(50) DEFAULT NULL,
  `field_description` varchar(100) DEFAULT NULL,
  `data_type` varchar(50) DEFAULT NULL,
  `max_line` smallint DEFAULT NULL,
  `width` smallint DEFAULT NULL,
  `field_length` smallint DEFAULT NULL,
  `decimal_length` smallint DEFAULT NULL,
  `field_type` varchar(50) DEFAULT NULL,
  `values_from_db` tinyint(1) DEFAULT '0',
  `unique_field` tinyint(1) DEFAULT '0',
  `allow_null` tinyint(1) DEFAULT '0',
  `primary_field` tinyint(1) DEFAULT '0',
  `primary_phone_no` tinyint(1) DEFAULT '0',
  `filter` tinyint(1) DEFAULT '0',
  `excel_export` tinyint(1) DEFAULT '0',
  `print_pdf` tinyint NOT NULL DEFAULT '0',
  `list_column` tinyint(1) DEFAULT '0',
  `required` tinyint(1) DEFAULT '0',
  `field_values` text,
  `db_val_column` varchar(100) DEFAULT NULL,
  `db_txt_column` varchar(100) DEFAULT NULL,
  `onchange` varchar(100) DEFAULT NULL,
  `onkeypress` text,
  `onclick` varchar(100) DEFAULT NULL,
  `status` tinyint(1) DEFAULT '1',
  `created_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created_by` int NOT NULL,
  `modified_date` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `modified_by` int DEFAULT NULL,
  PRIMARY KEY (`field_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_dynamicform_fields_1` (`field_id`, `field_name`, `field_description`, `data_type`, `max_line`, `width`, `field_length`, `decimal_length`, `field_type`, `values_from_db`, `unique_field`, `allow_null`, `primary_field`, `primary_phone_no`, `filter`, `excel_export`, `print_pdf`, `list_column`, `required`, `field_values`, `db_val_column`, `db_txt_column`, `onchange`, `onkeypress`, `onclick`, `status`, `created_date`, `created_by`, `modified_date`, `modified_by`) VALUES
	(1, 'df_department', 'Department', 'string', NULL, 200, 200, NULL, 'dropdown', 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 'Agriculture Department, Animal Husbandry Department, Board of Revenue, Uttar Pradesh\nCommercial Tax Department, Dairy Development Department, Department of Additional Sources of Energy, Department of Agricultural Marketing & Agriculture Foreign Trade, Department of Excise, Department of Horticulture and Food Processing, Department of Labour, Department of Stamp and Registration, Department of Weights and Measures : Legal Metrology, Directorate of Electrical Safety, DMIC IITGNL, Film Bandhu, Food and Civil Supplies Department, Food Safety and Drug Administration (Drug),Forest and Wildlife Department, Geology and Mining, Gorakhpur Industrial Development, Authority (GIDA),Ground Water Department, Handloom and Textiles Department, Home Department, Housing Department, Information Technology Department, Infrastructure and Industrial Development Authority - GREATER NOIDA, Infrastructure and Industrial Development Authority - NOIDA, Infrastructure and Industrial Development Authority - UPSIDA, Infrastructure and Industrial Development Authority - YEIDA, Invest UP, Irrigation and Water Resources Department, Medical Health Department, MSME Department, PICUP, Pollution Control Board, Public Works Department, Registrar Firms Societies and Chits, Tourism Department, Transport Department, U.P. Expressways Industrial Development Authority(UPEIDA), Urban Development Department, Uttar Pradesh Fire Services, Uttar Pradesh Power Corporation Limited, UP Fun department', NULL, NULL, NULL, NULL, NULL, 1, '2024-11-14 14:57:07', 1, '2024-12-23 17:16:28', 1);

**
CREATE TABLE IF NOT EXISTS `tms_email_account` (
  `id` int NOT NULL AUTO_INCREMENT,
  `server_type` varchar(50) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `display_name` varchar(50) DEFAULT NULL,
  `exchange_service` varchar(50) DEFAULT NULL,
  `incoming_user_name` varchar(50) DEFAULT NULL,
  `incoming_password` varchar(50) DEFAULT NULL,
  `outgoing_user_name` varchar(50) DEFAULT NULL,
  `outgoing_password` varchar(50) DEFAULT NULL,
  `incoming_mail_server` varchar(50) DEFAULT NULL,
  `incoming_mail_server_port` varchar(50) DEFAULT NULL,
  `incoming_enable_SSL` tinyint DEFAULT NULL,
  `stop_incoming_email` tinyint DEFAULT NULL,
  `outgoing_mail_server` varchar(50) DEFAULT NULL,
  `outgoing_mail_server_port` varchar(50) DEFAULT NULL,
  `outgoing_enable_SSL` tinyint DEFAULT NULL,
  `stop_outgoing_email` tinyint DEFAULT NULL,
  `status` tinyint DEFAULT NULL,
  `security_protocol` varchar(50) DEFAULT NULL,
  `created_by` varchar(50) DEFAULT NULL,
  `created_date` timestamp NULL DEFAULT NULL,
  `modified_by` varchar(50) DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL,
  `forwarded_mail` varchar(100) DEFAULT NULL,
  `is_auth_enable` tinyint DEFAULT '0',
  `client_oauth2_id` text,
  `client_secret` text,
  `tenant_id` text,
  `token` text,
  `refresh_token` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_email_account` (`id`, `server_type`, `email`, `display_name`, `exchange_service`, `incoming_user_name`, `incoming_password`, `outgoing_user_name`, `outgoing_password`, `incoming_mail_server`, `incoming_mail_server_port`, `incoming_enable_SSL`, `stop_incoming_email`, `outgoing_mail_server`, `outgoing_mail_server_port`, `outgoing_enable_SSL`, `stop_outgoing_email`, `status`, `security_protocol`, `created_by`, `created_date`, `modified_by`, `modified_date`, `forwarded_mail`, `is_auth_enable`, `client_oauth2_id`, `client_secret`, `tenant_id`, `token`, `refresh_token`) VALUES
	(20, 'IMap', 'testtms1806@gmail.com', 'test mail', NULL, 'testtms1806@gmail.com', 'smzvyybhpkojynih', 'testtms1806@gmail.com', 'smzvyybhpkojynih', 'imap.gmail.com', '993', 1, 0, 'smtp.gmail.com', '587', 0, 0, 1, 'TLS', '1', '2025-01-22 09:38:03', '1', '2025-05-05 11:56:42', '', 0, '', '', '', NULL, NULL);

**
CREATE TABLE IF NOT EXISTS `tms_followup_1` (
  `id` int NOT NULL AUTO_INCREMENT,
  `followup_date` datetime DEFAULT NULL,
  `status` int DEFAULT NULL,
  `remark` text,
  `cr_date` datetime DEFAULT NULL,
  `cr_by` int DEFAULT NULL,
  `md_date` datetime DEFAULT NULL,
  `md_by` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_junkmail_master_1` (
  `junk_mail_id` int NOT NULL AUTO_INCREMENT,
  `junk_email` varchar(100) DEFAULT NULL,
  `time_stamp` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`junk_mail_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_login_log` (
  `id` int NOT NULL AUTO_INCREMENT,
  `user_name` varchar(50) DEFAULT NULL,
  `user_id` varchar(50) DEFAULT NULL,
  `user_type` varchar(50) DEFAULT NULL,
  `user_data` text,
  `queue_id` varchar(50) DEFAULT NULL,
  `action_by` varchar(100) DEFAULT NULL,
  `ip_address` varchar(50) DEFAULT NULL,
  `status` varchar(50) DEFAULT NULL,
  `insert_date` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `logout_from` varchar(50) DEFAULT NULL,
  `auth_type` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_tms_login_log_auth_type` (`auth_type`),
  CONSTRAINT `FK_tms_login_log_auth_type` FOREIGN KEY (`auth_type`) REFERENCES `auth_type` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_log_master` (
  `id` int NOT NULL AUTO_INCREMENT,
  `action_performed_by` varchar(50) DEFAULT NULL,
  `action_method` varchar(50) DEFAULT NULL,
  `action_data` text,
  `action_addreess` varchar(50) DEFAULT NULL,
  `user_address` varchar(50) DEFAULT NULL,
  `table_name` varchar(50) DEFAULT NULL,
  `action_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_mail_test` (
  `id` int NOT NULL AUTO_INCREMENT,
  `is_valid` int NOT NULL DEFAULT '0',
  `message` text NOT NULL,
  `check_by` int DEFAULT NULL,
  `check_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `email_account_id` int DEFAULT NULL,
  `email_id` varchar(100) NOT NULL,
  `form_type` varchar(20) DEFAULT NULL,
  `type` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=157 DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_menu_module` (
  `id` int NOT NULL AUTO_INCREMENT,
  `module_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `module_link` varchar(250) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `module_file_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `status` tinyint NOT NULL DEFAULT '1' COMMENT '1 active 2 inactive',
  `created_by` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_by` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;

**
INSERT INTO `tms_menu_module` (`id`, `module_name`, `module_link`, `module_file_name`, `status`, `created_by`, `updated_by`) VALUES
	(1, 'Dashboard', 'dashboard', 'DashboardModule', 1, '2023-01-04 16:22:09', '2023-01-04 16:22:09'),
	(2, 'Home', 'home', 'HomeModule', 1, '2023-01-05 09:46:40', '2023-01-05 09:46:52'),
	(3, 'Users', 'user', 'UsermasterModule', 1, '2023-01-09 14:02:49', '2023-01-09 15:51:53'),
	(4, 'User Type', 'user_type', 'UsertypeModule', 1, '2023-01-09 14:02:59', '2023-01-09 15:51:57'),
	(5, 'User Type Permission', 'type_rights', 'UsertypepermissionModule', 1, '2023-01-09 14:03:05', '2023-01-09 15:52:16'),
	(6, 'Change Password', 'user', 'ChangepasswordModule', 1, '2023-01-09 14:03:13', '2023-01-09 15:53:10'),
	(7, 'Conversation Type', 'conversation-type', 'conversationTypeModule', 1, '2023-05-17 15:54:38', '2023-05-17 15:54:43'),
	(8, 'Shift', 'shift', 'ShiftModule', 1, '2023-01-09 14:03:29', '2023-01-09 14:04:53'),
	(9, 'Company', 'company', 'CompanyModule', 1, '2023-01-09 14:03:35', '2023-01-09 14:04:45'),
	(11, 'Email Account', 'emailAccount', 'EmailaccountModule', 1, '2023-01-10 10:19:54', '2023-01-25 12:13:07'),
	(12, 'Pagination', 'pagination', 'PaginationModule', 1, '2023-01-10 10:20:17', '2023-01-10 10:20:29'),
	(17, 'Queue', 'queue', 'QueueModule', 1, '2023-02-01 10:30:30', '2023-02-01 10:30:30'),
	(19, 'New Ticket', 'new-ticket', 'NewticketModule', 1, '2023-02-04 14:46:05', '2023-02-04 15:11:24'),
	(21, 'User Log', 'userlog', 'UserlogModule', 1, '2023-02-13 15:55:33', '2023-02-13 15:56:22'),
	(22, 'Login Log', 'loginlog', 'LoginlogModule', 1, '2023-02-14 11:59:33', '2023-02-14 11:59:58'),
	(23, 'Search Tickect', 'ticket-search', 'TicketSearchModule', 1, '2023-02-16 16:34:59', '2023-07-15 13:00:02'),
	(24, 'Form Builder', 'form-builder', 'FormBuilderModule', 1, '2023-02-17 11:17:29', NULL),
	(25, 'Field Group', 'field-group', 'FieldGroupModule', 1, '2023-02-24 12:57:06', '2023-02-24 12:59:16'),
	(27, 'Juck Search', 'junk-ticket', 'JuckTicketModule', 1, '2023-02-16 16:34:59', '2023-06-06 12:51:08'),
	(28, 'Delete Ticket', 'delete-ticket', 'DeleteTicketModule', 1, '2023-02-16 16:34:59', '2023-06-06 12:51:08'),
	(29, 'TMS Log', 'tmslog', 'TmslogModule', 1, '2023-02-13 15:55:33', '2023-02-13 15:56:22'),
	(30, 'SLA Report', 'slareport', 'SlareportModule', 1, '2023-02-13 15:55:33', '2023-07-13 10:37:10'),
	(31, 'Agent Report', 'agentreport', 'AgentreportModule', 1, '2023-02-13 15:55:33', '2023-02-13 15:56:22'),
	(32, 'Update Software', 'update-software', 'UpdateSoftwareModule', 1, '2024-03-09 17:42:06', NULL),
	(34, 'Agent Summary', 'agent-summary', 'AgentSummaryModule', 1, '2024-03-11 13:55:47', '2024-03-11 13:56:03'),
	(35, 'Shortcut Keys', 'shortcut-keys', 'ShortcutKeysModule', 1, '2024-03-12 10:26:11', NULL),
	(36, 'Break', 'break', 'BreakModule', 1, '2024-04-10 13:53:32', NULL),
	(37, 'Custom Report', 'custom-report', 'CustomReportModule', 1, '2024-05-10 11:17:11', '2024-05-10 11:17:33'),
	(38, 'Node App', 'node-app', 'NodeAppModule', 1, '2024-05-20 15:14:46', NULL),
	(39, 'Conversation Count', 'conversation-count', 'conversation-countModule', 1, '2023-02-13 15:55:33', '2024-06-11 11:12:46'),
	(40, 'Agent Productivity Report', 'agent-productivity-report-log', 'AgentProductivityReportLogModule', 1, '2024-06-29 11:22:23', '2024-06-29 11:23:40'),
	(41, 'WIP Report', 'wipreport', 'WipreporttModule', 1, '2023-02-13 15:55:33', '2023-07-13 10:37:10');

**
CREATE TABLE IF NOT EXISTS `tms_module` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(80) DEFAULT NULL,
  `title` varchar(200) NOT NULL,
  `url` varchar(255) DEFAULT NULL,
  `parent_id` int DEFAULT NULL,
  `parent_name` varchar(50) DEFAULT NULL,
  `menu_module_id` int DEFAULT NULL,
  `display_order` int DEFAULT NULL,
  `icon_class` varchar(50) DEFAULT NULL,
  `icon_mobile_menu` varchar(50) DEFAULT NULL,
  `font_color` varchar(20) DEFAULT NULL,
  `background_color` varchar(20) DEFAULT NULL,
  `created_by` varchar(80) DEFAULT NULL,
  `updated_by` varchar(80) DEFAULT NULL,
  `is_registered` varchar(20) DEFAULT NULL,
  `status` tinyint DEFAULT '1',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_module` (`id`, `name`, `title`, `url`, `parent_id`, `parent_name`, `menu_module_id`, `display_order`, `icon_class`, `icon_mobile_menu`, `font_color`, `background_color`, `created_by`, `updated_by`, `is_registered`, `status`) VALUES
	(1, 'Dashboard', 'Dashboard', '#', 0, NULL, 0, 1, 'fas fa-tv', 'Dashboard.png', '', '', NULL, NULL, '1', 1),
	(2, 'Home', 'Home', 'home', 1, 'Dashboard', 1, 1, 'fas fa-home', 'Home.png', '', '', NULL, NULL, '1', 1),
	(3, 'Master', 'Master', '#', 0, NULL, 0, 2, 'fab fa-readme', 'agent-summary.png', '', '', NULL, NULL, '1', 1),
	(4, 'Users', 'Users', 'user', 3, 'Master', 3, 2, 'fas fa-user', 'Users.png', '', '', NULL, NULL, '1', 1),
	(5, 'User Type', 'User Type', 'usertype', 3, 'Master', 4, 1, 'fas fa-user-edit', 'user-type.png', NULL, NULL, NULL, NULL, '1', 1),
	(6, 'User Type Permission', 'User Type Permission', 'usertypepermission', 3, 'Master', 5, 3, 'fas fa-user-check', 'Master.png', NULL, NULL, NULL, NULL, NULL, 1),
	(7, 'Setting', 'Setting', '#', 0, NULL, 0, 5, 'fa fa-cog', 'User-rights.png', '', '', NULL, NULL, '1', 1),
	(8, 'Change Password', 'Change Password', 'changepassword', 7, 'Setting', 6, 2, 'fa fa-unlock-alt', NULL, '', '', NULL, NULL, '1', 0),
	(9, 'Conversation Type', 'Conversation Type', 'conversation-type', 3, 'Master', 7, 4, 'fas fa-comments', 'conversation-type.png', NULL, NULL, NULL, NULL, NULL, 1),
	(10, 'Shift', 'shift', 'shift', 3, 'Master', 8, 5, 'fas fa-user-friends', 'shift.png', NULL, NULL, NULL, NULL, NULL, 1),
	(11, 'Company', 'Company', 'company', 7, 'Setting', 9, 1, 'fas fa-building', NULL, '', NULL, NULL, NULL, NULL, 1),
	(13, 'Email Account', 'Email Account', 'emailaccount', 3, 'Master', 11, 7, 'fas fa-envelope', 'Email.png', NULL, NULL, NULL, NULL, NULL, 1),
	(14, 'Pagination', 'Pagination', 'pagination', 7, 'Setting', 12, 4, 'fas fa-envelope', NULL, NULL, NULL, NULL, NULL, NULL, 1),
	(19, 'Queue', 'Queue', 'queue', 3, 'Master', 17, 12, 'fas fa-layer-group', 'queue.png', NULL, NULL, NULL, NULL, '1', 1),
	(21, 'Ticket', 'Ticket', '#', 0, NULL, 0, 3, 'fas fa-ticket-alt', 'ticket.png', NULL, NULL, NULL, NULL, '1', 1),
	(22, 'New Ticket', 'New Ticket', 'new-ticket', 21, 'Ticket', 19, 1, 'fas fa-ticket-alt', 'ticket.png', NULL, NULL, NULL, NULL, '1', 1),
	(24, 'User Log', 'User Log', 'userlog', 27, 'Reports', 21, 2, 'fa fa-user-circle', 'user-log.png', NULL, NULL, NULL, NULL, '1', 1),
	(25, 'Login Log', 'Login Log', 'loginlog', 27, 'Reports', 22, 1, 'fas fa-sign-in-alt', 'user-log.png', NULL, NULL, NULL, NULL, '1', 1),
	(26, 'Search Ticket', 'Search Ticket', 'ticket-search', 21, 'Ticket', 23, 2, 'fas fa-search', 'search-ticket.png', NULL, NULL, NULL, NULL, '1', 1),
	(27, 'Reports', 'Reports', '#', 0, NULL, 0, 4, 'fas fa-file-alt', 'Reports.png', NULL, NULL, NULL, NULL, NULL, 1),
	(28, 'Junk Ticket ', 'Junk Ticket', 'junk-ticket', 21, 'Ticket', 27, 3, 'fas fa-ban', 'junk-ticket.png', NULL, NULL, NULL, NULL, '1', 1),
	(29, 'Deleted Ticket ', 'Deleted Ticket', 'delete-ticket', 21, 'Ticket', 28, 4, 'fas fa-trash-alt', 'Delete-ticket.png', NULL, NULL, NULL, NULL, '1', 1),
	(30, 'TMS Log', 'TMS Log', 'tmslog', 27, 'Reports', 39, 1, 'fas fa-file-alt', 'TMS-Log.png', NULL, NULL, NULL, NULL, '1', 1),
	(31, 'SLA Report', 'SLA Report', 'slareport', 27, 'Reports', 30, 1, 'fas fa-file-alt', 'SLA-Report.png', NULL, NULL, NULL, NULL, '1', 1),
	(32, 'Agent Report', 'Agent Report', 'agentreport', 27, 'Reports', 31, 1, 'fas fa-id-badge', 'Agent-Report.png', NULL, NULL, NULL, NULL, '1', 1),
	(33, 'Update Software', 'Update Software', 'update-software', 7, 'Setting', 32, 5, 'fa fa-wrench', NULL, NULL, NULL, NULL, NULL, NULL, 1),
	(35, 'Agent Summary', 'Agent Summary', 'agent-summary', 1, 'Dashboard', 34, 2, 'fas fa-id-badge', 'agent-summary.png', NULL, NULL, NULL, NULL, NULL, 1),
	(36, 'Shortcut Keys', 'Shortcut Keys', 'shortcut-keys', 7, 'Setting', 35, 6, 'fas fa-id-badge', NULL, NULL, NULL, NULL, NULL, NULL, 1),
	(37, 'Break', 'break', 'break', 3, 'Master', 36, 13, 'fas fa-clock', NULL, NULL, NULL, NULL, NULL, NULL, 1),
	(38, 'Custom Report', 'Custom Report', 'custom-report', 45, 'Custom Report', 37, 1, 'fas fa-file-signature', NULL, NULL, NULL, NULL, NULL, NULL, 1),
	(39, 'Node App', 'Node App', 'node-app', 7, 'Setting', 38, 7, 'fab fa-node', NULL, NULL, NULL, NULL, NULL, NULL, 1),
	(40, 'Conversation Count', 'Conversation Count', 'conversation-count', 27, 'Reports', 29, 1, 'fas fa-comments', '', NULL, NULL, NULL, NULL, '1', 1),
	(41, 'Agent Productivity Report', 'Agent Productivity Report', 'agent-productivity-report-log', 27, 'Reports', 40, 1, 'fas fa-user-graduate', NULL, NULL, NULL, NULL, NULL, NULL, 1),
	(42, 'Work In Progress Report', 'Work In Progress Report', 'wipreport', 27, 'Reports', 41, 1, 'fas fa-file-alt', 'SLA-Report.png', NULL, NULL, NULL, NULL, '1', 1),
	(43, 'First TAT Report', 'First TAT Report', 'firsttatreport', 27, 'Reports', 42, 1, 'fas fa-file-alt', 'SLA-Report.png', NULL, NULL, NULL, NULL, '1', 1),
	(44, 'Ticket Closure Timeliness', 'Ticket Closure Timeliness', 'closurereport', 27, 'Reports', 41, 1, 'fas fa-file-alt', 'SLA-Report.png', NULL, NULL, NULL, NULL, '1', 1),
	(45, 'Custom Report', 'Custom Reports', '#', 0, NULL, 0, 4, 'fas fa-file-alt', 'Reports.png', NULL, NULL, NULL, NULL, NULL, 1),
	(46, 'Custom Report Result', 'Custom Report Result', 'custom-result', 45, 'Custom Report', 37, 1, 'fas fa-file-signature', NULL, NULL, NULL, NULL, NULL, NULL, 1);

**
CREATE TABLE IF NOT EXISTS `tms_paginate` (
  `id` int NOT NULL AUTO_INCREMENT,
  `no_of_record` int DEFAULT NULL,
  `default_no_of_record` tinyint(1) DEFAULT NULL,
  `created_by` varchar(80) DEFAULT NULL,
  `updated_by` varchar(80) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_paginate` (`id`, `no_of_record`, `default_no_of_record`, `created_by`, `updated_by`) VALUES
	(2, 20, 0, NULL, NULL),
	(12, 10, 0, NULL, NULL),
	(13, 30, 0, NULL, NULL),
	(14, 40, 0, NULL, NULL),
	(15, 50, 0, NULL, NULL),
	(18, 60, 0, NULL, NULL),
	(19, 70, 0, NULL, NULL),
	(20, 80, 0, NULL, NULL),
	(24, 90, 0, NULL, NULL),
	(25, 100, 1, NULL, NULL),
	(26, 110, 0, NULL, NULL),
	(27, 120, 0, NULL, NULL),
	(28, 500, 0, NULL, NULL);

**
CREATE TABLE IF NOT EXISTS `tms_pagination_master` (
  `id` int NOT NULL AUTO_INCREMENT,
  `record` int DEFAULT NULL,
  `status` int DEFAULT NULL,
  `created_by` varchar(50) DEFAULT NULL,
  `created_date` datetime DEFAULT NULL,
  `modified_by` varchar(50) DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL,
  `is_default` int(1) unsigned zerofill DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_pagination_master` (`id`, `record`, `status`, `created_by`, `created_date`, `modified_by`, `modified_date`, `is_default`) VALUES
	(1, 100, 0, '1', '2023-07-25 10:06:31', '1', '2023-07-25 10:06:31', 0),
	(55, 500, 1, '1', '2023-07-25 10:06:12', '38', '2024-03-30 10:35:29', 0),
	(57, 10, 1, '1', '2024-03-07 10:25:16', '60', '2024-07-05 10:06:53', 1),
	(59, 2, 1, '1', '2024-03-07 10:06:11', '60', '2024-07-05 10:06:35', 0),
	(61, 3333, 0, '1', '2024-03-27 14:55:07', '1', '2024-03-29 10:06:29', 0),
	(63, 3123, 1, '1', '2024-03-28 15:13:45', NULL, NULL, 0);

**
CREATE TABLE IF NOT EXISTS `tms_queue_assign_rule_action_1` (
  `rule_action_id` int NOT NULL AUTO_INCREMENT,
  `assign_rule_id` int DEFAULT NULL,
  `action` varchar(50) DEFAULT NULL,
  `action_value` varchar(50) DEFAULT NULL,
  `assign_to_login` tinyint DEFAULT '0',
  PRIMARY KEY (`rule_action_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_queue_assign_rule_condition_1` (
  `rule_condition_id` int NOT NULL AUTO_INCREMENT,
  `assign_rule_id` int DEFAULT NULL,
  `evaluate_on` varchar(50) DEFAULT NULL,
  `operator` varchar(50) DEFAULT NULL,
  `evaluate_value` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`rule_condition_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**

CREATE TABLE IF NOT EXISTS `tms_queue_assign_rule_master_1` (
  `assign_rule_id` int NOT NULL AUTO_INCREMENT,
  `rule_name` varchar(50) DEFAULT NULL,
  `match_any_condition` bit(1) DEFAULT NULL,
  `match_all_condition` bit(1) DEFAULT NULL,
  `order_no` int DEFAULT NULL,
  `created_date` datetime DEFAULT NULL,
  `created_by` int DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL,
  `modified_by` int DEFAULT NULL,
  `time_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `is_active` bit(1) DEFAULT NULL,
  `match` varchar(50) DEFAULT NULL,
  `category_id` int DEFAULT NULL,
  `subcategory_id` int DEFAULT NULL,
  PRIMARY KEY (`assign_rule_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**
CREATE TABLE IF NOT EXISTS `tms_queue_category_1` (
  `category_id` int NOT NULL AUTO_INCREMENT,
  `category_name` varchar(100) NOT NULL DEFAULT '0',
  `status` tinyint DEFAULT '1',
  `default` tinyint DEFAULT '0',
  `priority` tinyint DEFAULT '0',
  PRIMARY KEY (`category_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_queue_category_1` (`category_id`, `category_name`, `status`, `default`, `priority`) VALUES
	(1, 'Development', 1, 0, 0),
	(2, 'test', 0, 0, 0),
	(4, 'fds', 1, 1, 0),
	(6, 'fdsfds', 0, 0, 0),
	(10, 'DEV', 1, 0, 3),
	(11, 'SUPPORT', 0, 0, 0);

**
CREATE TABLE IF NOT EXISTS `tms_queue_email` (
  `id` int NOT NULL AUTO_INCREMENT,
  `incoming_email_account` int DEFAULT NULL,
  `outgoing_email_account` int DEFAULT NULL,
  `queue_id` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_tms_queue_email_tms_email_acoount` (`incoming_email_account`),
  KEY `FK_tms_queue_email_tms_email_acoount_2` (`outgoing_email_account`),
  KEY `FK_tms_queue_email_tms_queue_master` (`queue_id`),
  CONSTRAINT `FK_tms_queue_email_tms_email_acoount` FOREIGN KEY (`incoming_email_account`) REFERENCES `tms_email_account` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `FK_tms_queue_email_tms_email_acoount_2` FOREIGN KEY (`outgoing_email_account`) REFERENCES `tms_email_account` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `FK_tms_queue_email_tms_queue_master` FOREIGN KEY (`queue_id`) REFERENCES `tms_queue_master` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=319 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_queue_email` (`id`, `incoming_email_account`, `outgoing_email_account`, `queue_id`) VALUES
	(318, 20, 20, 1);

**
CREATE TABLE IF NOT EXISTS `tms_queue_escalationmatrix_1` (
  `escalation_id` int NOT NULL AUTO_INCREMENT,
  `priority_id` int DEFAULT NULL,
  `days` int DEFAULT NULL,
  `hours` int DEFAULT NULL,
  `minute` int DEFAULT NULL,
  `emails` text,
  `mobile_no` text,
  `shift_id` int DEFAULT NULL,
  `template_id` int DEFAULT NULL,
  `category_id` varchar(50) DEFAULT NULL,
  `cat_email` text,
  `send_email` tinyint DEFAULT NULL,
  `send_sms` tinyint DEFAULT NULL,
  `active` tinyint DEFAULT NULL,
  `level` int DEFAULT NULL,
  `send_email_agent` tinyint DEFAULT NULL,
  `agent_template_id` int DEFAULT NULL,
  PRIMARY KEY (`escalation_id`) USING BTREE,
  KEY `FK_1_tms_shift_master` (`shift_id`),
  KEY `FK_tms_queue_escalationmatrix_1_tms_queue_priority_1` (`priority_id`),
  KEY `FK_tms_queue_escalationmatrix_1_tms_queue_template_1` (`template_id`),
  CONSTRAINT `FK_1_tms_shift_master` FOREIGN KEY (`shift_id`) REFERENCES `tms_shift_master` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `FK_tms_queue_escalationmatrix_1_tms_queue_priority_1` FOREIGN KEY (`priority_id`) REFERENCES `tms_queue_priority_1` (`priority_id`) ON UPDATE CASCADE,
  CONSTRAINT `FK_tms_queue_escalationmatrix_1_tms_queue_template_1` FOREIGN KEY (`template_id`) REFERENCES `tms_queue_template_1` (`template_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**
CREATE TABLE IF NOT EXISTS `tms_queue_master` (
  `id` int NOT NULL AUTO_INCREMENT,
  `queue` varchar(200) DEFAULT NULL,
  `ticket_prefix` varchar(200) DEFAULT NULL,
  `priority_id` int DEFAULT NULL,
  `before_assign_shift` varchar(200) DEFAULT NULL,
  `dont_read_mail_before` date DEFAULT NULL,
  `reopen_after` int DEFAULT NULL,
  `reopen_to_same_agent` tinyint DEFAULT '0',
  `plain_text` tinyint DEFAULT NULL,
  `is_active` tinyint DEFAULT NULL,
  `auto_assign` tinyint DEFAULT NULL,
  `auto_reply` tinyint DEFAULT NULL,
  `is_happycode` tinyint DEFAULT NULL,
  `show_happycode` tinyint DEFAULT NULL,
  `happycode_template` int DEFAULT NULL,
  `resend_happycode` tinyint DEFAULT NULL,
  `escalation` tinyint DEFAULT NULL,
  `assign_shift_wise` tinyint DEFAULT NULL,
  `assign_on_view` tinyint DEFAULT NULL,
  `map_parent` tinyint DEFAULT NULL,
  `catagory` varchar(50) DEFAULT NULL,
  `statustype` varchar(50) DEFAULT NULL,
  `sms_api` varchar(500) DEFAULT NULL,
  `wp_api` varchar(500) DEFAULT NULL,
  `closing_mail` varchar(500) DEFAULT NULL,
  `block_email_for_ticket_generate` varchar(500) DEFAULT NULL,
  `block_email_for_auto_reply` varchar(500) DEFAULT NULL,
  `block_domains_for_ticket_generate` varchar(500) DEFAULT NULL,
  `block_domains_for_auto_reply` varchar(500) DEFAULT NULL,
  `footer_name` text,
  `footer_image_width` varchar(50) DEFAULT NULL,
  `status` tinyint DEFAULT NULL,
  `all_ticket` tinyint DEFAULT NULL,
  `created_by` varchar(50) DEFAULT NULL,
  `created_date` datetime DEFAULT NULL,
  `modified_by` varchar(50) DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL,
  `mandatory_category` tinyint DEFAULT NULL,
  `bulk_escalation` tinyint DEFAULT NULL,
  `bulk_escalation_timing` time DEFAULT NULL,
  `bulk_escalation_template` int DEFAULT NULL,
  `view_all_tickets` int DEFAULT NULL,
  `edit_all_tickets` int DEFAULT NULL,
  `auto_assign_setting` varchar(20) DEFAULT NULL,
  	`sms_api_method` VARCHAR(255) DEFAULT 'GET',
	`sms_api_headers` VARCHAR(10000) DEFAULT NULL,
	`sms_api_body` VARCHAR(2000) DEFAULT NULL,
	`wp_api_method` VARCHAR(255) DEFAULT 'GET',
	`wp_api_headers` VARCHAR(1000) DEFAULT NULL,
	`wp_api_body` VARCHAR(2000) DEFAULT NULL,
	`dont_read_unread_mail` TINYINT(4) NULL DEFAULT '0',
 	`last_read_date` DATE NULL DEFAULT NULL ,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_queue_master` (`id`, `queue`, `ticket_prefix`, `priority_id`, `before_assign_shift`, `dont_read_mail_before`, `reopen_after`, `reopen_to_same_agent`, `plain_text`, `is_active`, `auto_assign`, `auto_reply`, `is_happycode`, `show_happycode`, `happycode_template`, `resend_happycode`, `escalation`, `assign_shift_wise`, `assign_on_view`, `map_parent`, `catagory`, `statustype`, `sms_api`, `wp_api`, `closing_mail`, `block_email_for_ticket_generate`, `block_email_for_auto_reply`, `block_domains_for_ticket_generate`, `block_domains_for_auto_reply`, `footer_name`, `footer_image_width`, `status`, `all_ticket`, `created_by`, `created_date`, `modified_by`, `modified_date`, `mandatory_category`, `bulk_escalation`, `bulk_escalation_timing`, `bulk_escalation_template`, `view_all_tickets`, `edit_all_tickets`, `auto_assign_setting`) VALUES
	(1, 'Support', '#TT[y][m][d]-', NULL, '10', '2025-01-21', 1, 0, 0, NULL, 1, 1, 0, 1, 7, 1, 1, 0, 0, 1, '', '', 'https://alerts.cbis.in/SMSApi/send?userid=navyivr&password=TFJD3c8y&sendMethod=quick&senderid=INDNVY&msgType=text&mobile=91{0}&msg={1}', 'https://wapp.sansoftwares.com/api/sms?token=749fbc630064409392b8a6c0ec69e085&sender_number=918527545735&Phone_No=91{0}&text={1}', 'harish.kumar@sansoftwares.com,harish@gmail.com', 'divyanshu.singh@sansoftwares.com,\nsupport.itservices@sharda.ac.in', '\nsupport.itservices@sharda.ac.in', '', '', 'TMS_Logo.png', '', 1, 0, '1', '2024-02-22 18:18:13', '1', '2025-01-22 15:08:40', 0, 1, '11:13:00', 10, 1, 0, 'round-robin');

**
CREATE TABLE IF NOT EXISTS `tms_queue_priority_1` (
  `priority_id` int NOT NULL AUTO_INCREMENT,
  `priority_name` varchar(100) DEFAULT NULL,
  `colour_code` varchar(50) DEFAULT NULL,
  `tat` varchar(50) DEFAULT NULL,
  `tat_time_min` varchar(50) DEFAULT '0',
  `order_no` varchar(50) DEFAULT NULL,
  `is_default` tinyint DEFAULT '0',
  PRIMARY KEY (`priority_id`) USING BTREE
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_queue_priority_1` (`priority_id`, `priority_name`, `colour_code`, `tat`, `tat_time_min`, `order_no`, `is_default`) VALUES
	(1, 'High', '#a60808', '2', NULL, '1', 0),
	(2, 'Medium', '#cebd03', '4', NULL, '2', 1),
	(3, 'Low', '#23980b', '6', NULL, '3', 0);

**
CREATE TABLE IF NOT EXISTS `tms_queue_rule_action_1` (
  `rule_action_id` int NOT NULL AUTO_INCREMENT,
  `rule_id` int DEFAULT NULL,
  `action` varchar(50) DEFAULT NULL,
  `action_value` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`rule_action_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**
CREATE TABLE IF NOT EXISTS `tms_queue_rule_condition_1` (
  `rule_condition_id` int NOT NULL AUTO_INCREMENT,
  `rule_id` int DEFAULT NULL,
  `evaluate_on` varchar(50) DEFAULT NULL,
  `operator` varchar(50) DEFAULT NULL,
  `evaluate_value` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`rule_condition_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**
CREATE TABLE IF NOT EXISTS `tms_queue_rule_master_1` (
  `rule_id` int NOT NULL AUTO_INCREMENT,
  `rule_name` varchar(50) DEFAULT NULL,
  `match_any_condition` bit(1) DEFAULT NULL,
  `match_all_condition` bit(1) DEFAULT NULL,
  `order_no` int DEFAULT NULL,
  `created_date` datetime DEFAULT NULL,
  `created_by` int DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL,
  `modified_by` int DEFAULT NULL,
  `time_stamp` timestamp NULL DEFAULT NULL,
  `shift_name` varchar(100) DEFAULT NULL,
  `time_from` time DEFAULT NULL,
  `time_to` time DEFAULT NULL,
  `is_active` bit(1) DEFAULT NULL,
  `match` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`rule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**
CREATE TABLE IF NOT EXISTS `tms_queue_status_1` (
  `status_id` int NOT NULL AUTO_INCREMENT,
  `status_name` varchar(50) DEFAULT NULL,
  `colour_code` varchar(50) DEFAULT NULL,
  `ticket_status_type` int DEFAULT NULL,
  `order_no` int DEFAULT NULL,
  `is_default` tinyint DEFAULT '0',
  `is_close_status` tinyint DEFAULT '0' COMMENT '0 => ''not close'',1 => ''close''',
  `template_id` int DEFAULT NULL,
  `customer_email` tinyint DEFAULT NULL,
  `customer_sms` tinyint DEFAULT NULL,
  `customer_wp` tinyint DEFAULT NULL,
  `user_email` tinyint DEFAULT NULL,
  `user_sms` tinyint DEFAULT NULL,
  `user_wp` tinyint DEFAULT NULL,
  `incomming_mail_status` int DEFAULT '0',
  PRIMARY KEY (`status_id`) USING BTREE,
  KEY `is_close_status` (`is_close_status`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_queue_status_1` (`status_id`, `status_name`, `colour_code`, `ticket_status_type`, `order_no`, `is_default`, `is_close_status`, `template_id`, `customer_email`, `customer_sms`, `customer_wp`, `user_email`, `user_sms`, `user_wp`, `incomming_mail_status`) VALUES
	(1, 'Open', '#e24040', 2, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0),
	(2, 'Close', '#238108', 1, 2, 0, 1, 2, 1, 0, 0, 0, 0, 0, 0),
	(4, 'Hold', '#66058a', 1, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0),
	(5, 'Reopen', '#0574a3', 3, 5, 0, 0, 6, 1, 0, 0, 0, 0, 0, 1),
	(6, 'move to another queue', '#b30f95', 1, 6, 0, 0, 5, 1, 0, 0, 0, 0, 0, 0),
	(7, 'manual assign', '#26c97d', 1, 7, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0),
	(9, 'reopen/close', '#000000', 1, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

**
CREATE TABLE IF NOT EXISTS `tms_queue_status_setting` (
  `id` int NOT NULL AUTO_INCREMENT,
  `queue_id` int DEFAULT NULL,
  `status_id` int DEFAULT NULL,
  `template_id` int DEFAULT NULL,
  `field_id` int DEFAULT NULL,
  `field_name` varchar(50) DEFAULT NULL,
  `field_value` varchar(50) DEFAULT NULL,
  `to_email` text,
  `customer_email` tinyint DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_queue_sub_category_1` (
  `sub_category_id` int NOT NULL AUTO_INCREMENT,
  `category_id` int NOT NULL,
  `sub_category_name` varchar(100) DEFAULT NULL,
  `message` text NOT NULL,
  `priority_id` int DEFAULT NULL,
  `default` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`sub_category_id`),
  KEY `FK_tms_queue_sub_category_1_tms_queue_category_1` (`category_id`),
  CONSTRAINT `FK_tms_queue_sub_category_1_tms_queue_category_1` FOREIGN KEY (`category_id`) REFERENCES `tms_queue_category_1` (`category_id`)
) ENGINE=InnoDB AUTO_INCREMENT=143 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_queue_sub_category_1` (`sub_category_id`, `category_id`, `sub_category_name`, `message`, `priority_id`, `default`) VALUES
	(45, 2, 'subcat1', 'ggt', NULL, 0),
	(61, 6, 'dsfsdf', '', NULL, 0),
	(78, 4, 'vxc', '', NULL, 1),
	(89, 11, 'support1', 'message for support1', NULL, 0),
	(90, 11, 'support2', ' message for support2', NULL, 1),
	(91, 11, 'support3', ' message for support3', NULL, 0),
	(129, 1, 'harish', '<p>Dear Valued Customer,</p><p><br></p><p><br></p><p><br></p><p>Greetings from BUSY!</p><p><br></p><p>We have received your request for data repair with details below. We are working on it to complete the preliminary analysis.</p><p><br></p><p>We shall connect with you within 1 working day with our observations and next steps.</p><p><br></p><p><br></p><p><br></p><p>Requested By :</p><p><br></p><p>Contact Number :&nbsp;</p><p><br></p><p>Name:&nbsp;</p><p><br></p><p>Serial Number:</p><p><br></p><p>Description of Issue:</p><p><br></p><p>URL to download the data :</p>', 0, 1),
	(139, 10, 'dev1', 'message for dev1', 1, 1),
	(140, 10, 'dev2', 'message for dev2', 0, 0),
	(141, 10, 'dev3', 'message for dev3', 0, 1),
	(142, 1, 'test', 'test', 3, 1);

**
CREATE TABLE IF NOT EXISTS `tms_queue_template` (
  `id` int NOT NULL AUTO_INCREMENT,
  `action` int DEFAULT NULL,
  `template` int DEFAULT NULL,
  `customer_email` tinyint DEFAULT NULL,
  `consumer_sms` tinyint DEFAULT NULL,
  `customer_wp` tinyint DEFAULT NULL,
  `user_email` tinyint DEFAULT NULL,
  `user_sms` tinyint DEFAULT NULL,
  `user_wp` tinyint DEFAULT NULL,
  `queue_id` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**
CREATE TABLE IF NOT EXISTS `tms_queue_template_1` (
  `template_id` int NOT NULL AUTO_INCREMENT,
  `template` varchar(100) DEFAULT NULL,
  `customer_email_subject` text,
  `user_email_subject` text,
  `customer_email_template` text,
  `user_email_template` text,
  `customer_sms_template` text,
  `customer_wp_template` text,
  `user_sms_template` text,
  `user_wp_template` text,
  `status` int DEFAULT NULL,
  PRIMARY KEY (`template_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_shift_master` (
  `id` int NOT NULL AUTO_INCREMENT,
  `title` varchar(50) DEFAULT NULL,
  `time_from` time DEFAULT NULL,
  `time_to` time DEFAULT NULL,
  `status` tinyint DEFAULT NULL,
  `created_by` int DEFAULT NULL,
  `created_date` datetime DEFAULT CURRENT_TIMESTAMP,
  `modified_by` int DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_shift_master` (`id`, `title`, `time_from`, `time_to`, `status`, `created_by`, `created_date`, `modified_by`, `modified_date`) VALUES
	(1, 'Genaral Shift', '09:00:00', '18:32:00', 1, 1, '2024-03-07 12:47:21', 60, '2024-07-09 09:48:22'),
	(2, 'Morning Shift', '08:00:00', '16:00:00', 1, 1, '2024-03-04 16:01:37', 1, '2024-06-05 10:26:29');

**
CREATE TABLE IF NOT EXISTS `tms_statuspermission_1` (
  `id` int NOT NULL AUTO_INCREMENT,
  `status_id` int NOT NULL DEFAULT '0',
  `is_checked` int NOT NULL DEFAULT '0',
  `status_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_type` int DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_statuspermission_1` (`id`, `status_id`, `is_checked`, `status_name`, `user_type`) VALUES
	(1, 2, 1, 'Close', 1),
	(2, 4, 1, 'Hold', 1),
	(3, 7, 1, 'manual assign', 1),
	(4, 6, 1, 'move to another queue', 1),
	(5, 1, 1, 'Open', 1),
	(6, 5, 1, 'Reopen', 1),
	(7, 9, 1, 'reopen/close', 1);

**
CREATE TABLE IF NOT EXISTS `tms_ticket_master_1` (
  `ticket_prefix` varchar(10) DEFAULT NULL,
  `ticket_unique_id` int NOT NULL AUTO_INCREMENT,
  `ticket_id` varchar(30) DEFAULT NULL,
  `person_name` varchar(50) CHARACTER SET utf32 COLLATE utf32_unicode_ci DEFAULT NULL,
  `mobile_no` varchar(16) DEFAULT NULL,
  `unique_id` varchar(15) DEFAULT NULL,
  `parent_id` varchar(30) DEFAULT NULL,
  `start_date` datetime DEFAULT CURRENT_TIMESTAMP,
  `from_email` varchar(500) DEFAULT NULL,
  `to_email` text,
  `cc_email` text,
  `bcc_email` text,
  `subject` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
  `start_mode` int DEFAULT NULL,
  `status_id` int DEFAULT NULL,
  `priority_id` int DEFAULT NULL,
  `queue_id` int DEFAULT NULL,
  `last_updated_on` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `is_read` bit(1) DEFAULT NULL,
  `read_by` int DEFAULT NULL,
  `read_date` datetime DEFAULT NULL,
  `mail_date` datetime DEFAULT NULL,
  `is_assigned` tinyint DEFAULT '0',
  `assigned_to` int DEFAULT NULL,
  `assigned_by` int DEFAULT '0',
  `assigned_on` datetime DEFAULT NULL,
  `last_updated_by` int DEFAULT NULL,
  `phone_no` varchar(16) DEFAULT NULL,
  `category_id` int DEFAULT NULL,
  `subcategory_id` int DEFAULT NULL,
  `follow_up_date` datetime DEFAULT NULL,
  `ticket_created_by` int DEFAULT NULL,
  `is_assigned_open_ticket` bit(1) DEFAULT NULL,
  `remarks` text,
  `is_replied_mail` bit(1) DEFAULT NULL,
  `is_forward_mail` bit(1) DEFAULT NULL,
  `created_date` datetime DEFAULT CURRENT_TIMESTAMP,
  `happy_code` int DEFAULT NULL,
  `escalation_id` int DEFAULT NULL,
  `last_escalation_on` datetime DEFAULT NULL,
  `hold_date` datetime DEFAULT NULL,
  `incoming_mail_id` text,
  `is_new` tinyint DEFAULT '0' COMMENT '0 => not read,1 =>read',
  `parent_ticket_id` int DEFAULT NULL,
  `parent_ticket_id_text` varchar(30) DEFAULT NULL,
  `is_junk` tinyint DEFAULT '0',
  `is_deleted_ticket` tinyint DEFAULT '0',
  `is_closed` tinyint DEFAULT '0' COMMENT '0 => not closed,1 =>ticket_closed',
  `is_auto` tinyint DEFAULT '0',
  `deleted_date` datetime DEFAULT NULL,
  `status_changed_on` datetime DEFAULT NULL,
  `priority_changed_on` datetime DEFAULT NULL,
  `reopen_date` datetime DEFAULT NULL,
  `ticket_closed_date` datetime DEFAULT NULL,
  `is_draft` tinyint DEFAULT '0',
  `df_department` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`ticket_unique_id`) USING BTREE,
  KEY `FK_tms_ticket_master_1_tms_conversation_type_master` (`start_mode`) USING BTREE,
  KEY `idx_queue_id` (`queue_id`) USING BTREE,
  KEY `idx_priority_id` (`priority_id`) USING BTREE,
  KEY `idx_status_id` (`status_id`) USING BTREE,
  KEY `idx_assigned_to` (`assigned_to`) USING BTREE,
  CONSTRAINT `FK_1_tms_queue_priority_1` FOREIGN KEY (`priority_id`) REFERENCES `tms_queue_priority_1` (`priority_id`) ON UPDATE CASCADE,
  CONSTRAINT `FK_1_tms_queue_status_1` FOREIGN KEY (`status_id`) REFERENCES `tms_queue_status_1` (`status_id`) ON UPDATE CASCADE,
  CONSTRAINT `FK_tms_ticket_master_1_tms_conversation_type_master` FOREIGN KEY (`start_mode`) REFERENCES `tms_conversation_type_master` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_unreadconversationcount_1` (
  `id` int NOT NULL AUTO_INCREMENT,
  `ticket_unique_id` int DEFAULT NULL,
  `ticket_id` varchar(50) DEFAULT NULL,
  `conversation_date` datetime DEFAULT NULL,
  `user_id` int DEFAULT NULL,
  `subject` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `conversation_type` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE TABLE IF NOT EXISTS `tms_updatesoft_log` (
  `id` int NOT NULL AUTO_INCREMENT,
  `uploaded_file` text,
  `response` text,
  `status` int DEFAULT '0',
  `ip_addr` varchar(50) DEFAULT NULL,
  `created_by` int DEFAULT NULL,
  `created_date` datetime DEFAULT CURRENT_TIMESTAMP,
  `modified_by` int DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=163 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_updatesoft_log` (`id`, `uploaded_file`, `response`, `status`, `ip_addr`, `created_by`, `created_date`, `modified_by`, `modified_date`) VALUES
	(12, 'update_all_db_12.txt', 'Invalid default value for \'cr_usr\'', 0, '::1', 1, '2024-03-30 16:17:48', 1, '2024-04-01 17:43:17'),
	(13, 'update_all_db_13.txt', 'Database Updated Successfully', 1, '::1', 1, '2024-03-30 16:31:35', 1, '2024-04-01 17:43:16'),
	(14, 'update_all_db_14.txt', 'Database Updated Successfully', 1, '::1', 1, '2024-04-01 17:18:36', 1, '2024-04-01 17:43:15'),
	(15, 'update_all_db_15.txt', 'Table(comp_purchase_document) Already Exists', 0, '::1', 1, '2024-04-01 17:23:53', 1, '2024-04-01 17:43:14'),
	(16, 'update_all_db_16.txt', 'Table(comp_purchase_document) Already Exists', 0, '::1', 1, '2024-04-01 17:26:22', 1, '2024-04-01 17:26:22'),
	(17, 'update_all_db_17.txt', 'Table(comp_purchase_document) Already Exists', 0, '::1', 1, '2024-04-01 17:41:30', 1, '2024-04-01 17:41:30'),
	(18, 'update_all_db_18.txt', 'Table(comp_purchase_document) Already Exists', 0, '::1', 1, '2024-04-02 16:38:11', 1, '2024-04-02 16:38:11'),
	(19, 'update_all_db_19.txt', 'Database Updated Successfully', 1, '::1', 1, '2024-04-02 16:43:01', 1, '2024-04-02 16:43:01'),
	(20, 'update_all_db_20.txt', 'Table(comp_purchase_document) Already Exists', 0, '::1', 1, '2024-04-04 14:55:09', 1, '2024-04-04 14:55:09'),
	(21, 'update_all_db_21.txt', NULL, 0, '::1', 1, '2024-04-04 14:56:19', 1, '2024-04-04 14:56:19'),
	(22, 'update_all_db_22.txt', 'Database Updated Successfully', 1, '::1', 1, '2024-04-04 14:59:19', 1, '2024-04-04 14:59:19'),
	(23, 'update_all_db_23.txt', 'Table(comp_abc) Not Exists', 0, '::1', 1, '2024-04-04 15:00:45', 1, '2024-04-04 15:00:45'),
	(24, 'update_all_db_24.txt', 'Table(comp_purchase_document) Renamed  to (comp_demo) Successfully', 1, '::1', 1, '2024-04-04 15:13:49', 1, '2024-04-04 15:13:49'),
	(25, 'update_all_db_25.txt', 'Table(comp_demo) Droped Successfully', 1, '::1', 1, '2024-04-04 15:15:06', 1, '2024-04-04 15:15:06'),
	(26, 'update_all_db_26.txt', 'Table(comp_data) Not Exists', 0, '::1', 1, '2024-04-04 15:55:20', 1, '2024-04-04 15:55:20'),
	(27, 'update_all_db_27.txt', 'Table(comp_demo) Renamed  to (comp_test) Successfully', 1, '::1', 1, '2024-04-04 16:21:38', 1, '2024-04-04 16:21:38'),
	(28, 'update_all_db_28.txt', 'Table(comp_demo) Not Exists', 0, '::1', 1, '2024-04-04 16:26:08', 1, '2024-04-04 16:26:08'),
	(29, 'update_all_db_29.txt', NULL, 0, '::1', 1, '2024-04-04 16:26:29', 1, '2024-04-04 16:26:29'),
	(30, 'update_all_db_30.txt', NULL, 0, '::1', 1, '2024-04-04 16:26:52', 1, '2024-04-04 16:26:52'),
	(31, 'update_all_db_31.txt', 'Unknown column \'abc\' in \'comp_test\'', 0, '::1', 1, '2024-04-04 16:27:28', 1, '2024-04-04 16:27:28'),
	(32, 'update_all_db_32.txt', 'Column(testing_col) added in table(comp_test)', 1, '::1', 1, '2024-04-04 16:27:51', 1, '2024-04-04 16:27:51'),
	(33, 'update_all_db_33.txt', NULL, 0, '::1', 1, '2024-04-05 13:17:18', 1, '2024-04-05 13:17:18'),
	(34, 'update_all_db_34.txt', NULL, 0, '::1', 1, '2024-04-05 13:18:08', 1, '2024-04-05 13:18:08'),
	(35, 'update_all_db_35.txt', NULL, 0, '::1', 1, '2024-04-05 13:19:04', 1, '2024-04-05 13:19:04'),
	(36, 'update_all_db_36.txt', NULL, 0, '::1', 1, '2024-04-05 13:24:46', 1, '2024-04-05 13:24:46'),
	(37, 'update_all_db_37.txt', NULL, 0, '::1', 1, '2024-04-05 13:27:50', 1, '2024-04-05 13:27:50'),
	(38, 'update_all_db_38.txt', NULL, 0, '::1', 1, '2024-04-05 13:28:17', 1, '2024-04-05 13:28:17'),
	(39, 'update_all_db_39.txt', NULL, 0, '::1', 1, '2024-04-05 13:41:55', 1, '2024-04-05 13:41:55'),
	(40, 'update_all_db_40.txt', NULL, 0, '::1', 1, '2024-04-05 13:54:01', 1, '2024-04-05 13:54:01'),
	(41, 'update_all_db_41.txt', NULL, 0, '::1', 1, '2024-04-05 13:56:15', 1, '2024-04-05 13:56:15'),
	(42, 'update_all_db_42.txt', NULL, 0, '::1', 1, '2024-04-05 13:57:12', 1, '2024-04-05 13:57:12'),
	(43, 'update_all_db_43.txt', NULL, 0, '::1', 1, '2024-04-05 13:59:15', 1, '2024-04-05 13:59:15'),
	(44, 'update_all_db_44.txt', 'Procedure (AgentlogReport) has been created successfully', 1, '::1', 1, '2024-04-05 14:05:20', 1, '2024-04-05 14:05:20'),
	(45, 'update_all_db_45.txt', NULL, 0, '::1', 1, '2024-04-05 14:51:26', 1, '2024-04-05 14:51:26'),
	(46, 'update_all_db_46.txt', NULL, 0, '::1', 1, '2024-04-05 14:57:28', 1, '2024-04-05 14:57:28'),
	(47, 'update_all_db_47.txt', 'Function (comp_testfun) has been created successfully', 1, '::1', 1, '2024-04-05 15:51:06', 1, '2024-04-05 15:51:06'),
	(48, 'update_all_db_48.txt', 'Function (comp_testfun) has been created successfully', 1, '::1', 1, '2024-04-05 17:12:10', 1, '2024-04-05 17:12:10'),
	(49, 'update_all_db_49.txt', 'Table(comp_abc) Created Successfully', 1, '::1', 1, '2024-04-06 11:10:11', 1, '2024-04-06 11:10:11'),
	(50, 'update_all_db_50.txt', NULL, 1, '::1', 1, '2024-04-06 11:27:24', 1, '2024-04-06 11:27:25'),
	(51, 'update_all_db_51.txt', NULL, 0, '::1', 1, '2024-04-06 11:33:52', 1, '2024-04-06 11:33:52'),
	(52, 'update_all_db_52.txt', NULL, 1, '::1', 1, '2024-04-06 11:34:02', 1, '2024-04-06 11:34:02'),
	(53, 'update_all_db_53.txt', 'Function (comp_testfun) has been created successfully,Table(comp_purchase_document) Created Successfully,Table(comp_abc) Created Successfully,Table(comp_abc) Created Successfully', 1, '::1', 1, '2024-04-06 11:39:02', 1, '2024-04-06 11:39:02'),
	(54, 'update_all_db_54.txt', 'Function (comp_testfun) has been created successfully, Table(comp_purchase_document) Already Exists', 0, '::1', 1, '2024-04-06 14:20:29', 1, '2024-04-06 14:20:29'),
	(55, 'update_all_db_55.txt', 'Function (comp_testfun) has been created successfully, Table(comp_purchase_document) Already Exists', 0, '::1', 1, '2024-04-06 14:20:43', 1, '2024-04-06 14:20:43'),
	(56, 'update_all_db_56.txt', 'Function (comp_testfun) has been created successfully, Table(comp_purchase_document) Already Exists', 0, '::1', 1, '2024-04-06 14:20:50', 1, '2024-04-06 14:20:50'),
	(57, 'update_all_db_57.txt', NULL, 0, '::1', 1, '2024-04-06 15:09:27', 1, '2024-04-06 15:09:27'),
	(58, 'update_all_db_58.txt', NULL, 0, '::1', 1, '2024-04-06 15:34:06', 1, '2024-04-06 15:34:06'),
	(59, 'update_all_db_59.txt', 'Table(comp_purchase_document_1) Created Successfully, Table(comp_purchase_document_2) Created Successfully, ', 0, '::1', 1, '2024-04-06 15:36:50', 1, '2024-04-06 15:36:50'),
	(60, 'update_all_db_60.txt', 'Table(comp_purchase_document_1) Created Successfully, Table(comp_purchase_document_2) Created Successfully', 0, '::1', 1, '2024-04-06 15:39:24', 1, '2024-04-06 15:39:24'),
	(61, 'update_all_db_61.txt', 'Table(comp_purchase_document_1) Created Successfully, Table(comp_purchase_document_2) Created Successfully, ', 0, '::1', 1, '2024-04-06 15:40:21', 1, '2024-04-06 15:40:21'),
	(62, 'update_all_db_62.txt', 'Table(comp_purchase_document_1) Created Successfully, Table(comp_purchase_document_2) Created Successfully', 0, '::1', 1, '2024-04-06 15:42:51', 1, '2024-04-06 15:42:51'),
	(63, 'update_all_db_63.txt', 'Table(comp_purchase_document_1) Created Successfully, Table(comp_purchase_document_2) Created Successfully, ', 0, '::1', 1, '2024-04-06 15:44:16', 1, '2024-04-06 15:44:16'),
	(64, 'update_all_db_64.txt', 'Table(comp_purchase_document_1) Already Exists', 0, '::1', 1, '2024-04-06 15:44:37', 1, '2024-04-06 15:44:37'),
	(65, 'update_all_db_65.txt', 'Table(comp_purchase_document_1) Created Successfully, Table(comp_purchase_document_2) Created Successfully, ', 1, '::1', 1, '2024-04-06 15:45:25', 1, '2024-04-06 15:45:25'),
	(66, 'update_all_db_66.txt', 'Table(comp_purchase_document_1) Created Successfully, Table(comp_purchase_document_2) Created Successfully, ', 1, '::1', 1, '2024-04-06 15:49:02', 1, '2024-04-06 15:49:02'),
	(67, 'update_all_db_67.txt', 'Table(comp_purchase_document_1) Created Successfully, Table(comp_purchase_document_2) Created Successfully, Table(comp_abc) Created Successfully', 1, '::1', 1, '2024-04-06 15:52:51', 1, '2024-04-06 15:52:51'),
	(68, 'update_all_db_68.txt', 'Table(comp_purchase_document_1) Already Exists', 0, '::1', 1, '2024-04-06 16:06:56', 1, '2024-04-06 16:06:56'),
	(69, 'update_all_db_69.txt', 'Table(comp_purchase_document_1) Created Successfully, Table(comp_purchase_document_2) Created Successfully, Table(comp_abc_1) Created Successfully, Can\'t write; duplicate key in table \'comp_abc_2\'', 0, '::1', 1, '2024-04-06 16:07:37', 1, '2024-04-06 16:07:37'),
	(70, 'update_all_db_70.txt', 'Table(comp_purchase_document_1) Created Successfully, Table(comp_purchase_document_2) Created Successfully', 1, '::1', 1, '2024-04-06 16:11:20', 1, '2024-04-06 16:11:20'),
	(71, 'update_all_db_71.txt', NULL, 0, '::1', 1, '2024-04-06 16:12:37', 1, '2024-04-06 16:12:37'),
	(72, 'update_all_db_72.txt', 'Table(comp_abc_1) Created Successfully, Table(comp_abc_2) Created Successfully', 1, '::1', 1, '2024-04-06 16:14:50', 1, '2024-04-06 16:14:50'),
	(73, 'update_all_db_73.txt', 'Table(comp_abc_1) Created Successfully, Table(comp_abc_2) Created Successfully', 1, '::1', 1, '2024-04-06 16:16:43', 1, '2024-04-06 16:16:43'),
	(74, 'update_all_db_74.txt', 'Table(comp_purchase_document_1) Created Successfully, Table(comp_purchase_document_2) Created Successfully, Table(comp_abc_1) Created Successfully, Table(comp_abc_2) Created Successfully', 1, '::1', 1, '2024-04-06 17:09:34', 1, '2024-04-06 17:09:34'),
	(75, 'update_all_db_75.txt', 'Table(comp_abc_1) Dropped Successfully, Table(comp_abc_2) Dropped Successfully, ', 0, '::1', 1, '2024-04-06 17:14:14', 1, '2024-04-06 17:14:14'),
	(76, 'update_all_db_76.txt', 'Table(comp_abc_1) Dropped Successfully, Table(comp_abc_2) Dropped Successfully, ', 0, '::1', 1, '2024-04-06 17:18:25', 1, '2024-04-06 17:18:25'),
	(77, 'update_all_db_77.txt', 'Table(comp_abc_1) Dropped Successfully, Table(comp_abc_2) Dropped Successfully, ', 0, '::1', 1, '2024-04-06 17:21:07', 1, '2024-04-06 17:21:07'),
	(78, 'update_all_db_78.txt', 'Table(comp_abc_1) Dropped Successfully, Table(comp_abc_2) Dropped Successfully', 0, '::1', 1, '2024-04-06 17:21:56', 1, '2024-04-06 17:21:56'),
	(79, 'update_all_db_79.txt', 'Table(comp_abc_1) Dropped Successfully, Table(comp_abc_2) Dropped Successfully, ', 0, '::1', 1, '2024-04-06 17:28:05', 1, '2024-04-06 17:28:05'),
	(80, 'update_all_db_80.txt', 'Table(comp_abc_1) Dropped Successfully, Table(comp_abc_2) Dropped Successfully, ', 0, '::1', 1, '2024-04-06 17:30:36', 1, '2024-04-06 17:30:36'),
	(81, 'update_all_db_81.txt', 'Table(comp_abc_1) Not Exists', 0, '::1', 1, '2024-04-06 17:32:08', 1, '2024-04-06 17:32:08'),
	(82, 'update_all_db_82.txt', 'Table(comp_abc_1) Dropped Successfully, Table(comp_abc_2) Dropped Successfully, ', 0, '::1', 1, '2024-04-06 17:35:07', 1, '2024-04-06 17:35:07'),
	(83, 'update_all_db_83.txt', 'Table(comp_abc_1) Created Successfully, Table(comp_abc_2) Created Successfully, ', 0, '::1', 1, '2024-04-06 17:38:19', 1, '2024-04-06 17:38:19'),
	(84, 'update_all_db_84.txt', 'Table(comp_abc_1) Already Exists', 0, '::1', 1, '2024-04-06 17:38:31', 1, '2024-04-06 17:38:31'),
	(85, 'update_all_db_85.txt', 'Table(comp_abc_1) Dropped Successfully, Table(comp_abc_2) Dropped Successfully', 0, '::1', 1, '2024-04-06 17:46:52', 1, '2024-04-06 17:46:52'),
	(86, 'update_all_db_86.txt', 'Table(comp_abc_1) Dropped Successfully, Table(comp_abc_2) Dropped Successfully, ', 0, '::1', 1, '2024-04-06 17:50:43', 1, '2024-04-06 17:50:43'),
	(87, 'update_all_db_87.txt', 'Table(comp_abc_1) Dropped Successfully, Table(comp_abc_2) Dropped Successfully, ', 0, '::1', 1, '2024-04-06 17:51:31', 1, '2024-04-06 17:51:31'),
	(88, 'update_all_db_88.txt', 'Table(comp_abc_1) Dropped Successfully, Table(comp_abc_2) Dropped Successfully, ', 1, '::1', 1, '2024-04-06 17:52:18', 1, '2024-04-06 17:52:18'),
	(89, 'update_all_db_89.txt', 'Table(comp_abc_1) Renamed  to (comp_xyz_1) Successfully, Table(comp_abc_2) Renamed  to (comp_xyz_2) Successfully, ', 1, '::1', 1, '2024-04-06 18:06:14', 1, '2024-04-06 18:06:14'),
	(90, 'update_all_db_90.txt', 'Table(comp_xyz_1) Renamed  to (comp_abc_1) Successfully, Table(comp_xyz_2) Renamed  to (comp_abc_2) Successfully, ', 1, '::1', 1, '2024-04-06 18:09:22', 1, '2024-04-06 18:09:22'),
	(91, 'update_all_db_91.txt', 'Column(demo_col) added in Table(comp_abc_1), Column(demo_col) added in Table(comp_abc_2), ', 1, '::1', 1, '2024-04-06 18:15:51', 1, '2024-04-06 18:15:51'),
	(92, 'update_all_db_92.txt', 'Column(demo_col) dropped in Table(comp_abc_1), Column(demo_col) dropped in Table(comp_abc_2), ', 1, '::1', 1, '2024-04-06 18:26:54', 1, '2024-04-06 18:26:54'),
	(93, 'update_all_db_93.txt', 'Table() Not Exists', 0, '::1', 1, '2024-04-08 11:09:05', 1, '2024-04-08 11:09:05'),
	(94, 'update_all_db_94.txt', NULL, 0, '::1', 1, '2024-04-08 11:10:43', 1, '2024-04-08 11:10:43'),
	(95, 'update_all_db_95.txt', NULL, 0, '::1', 1, '2024-04-08 11:25:05', 1, '2024-04-08 11:25:05'),
	(96, 'update_all_db_96.txt', 'Column(abc_name) has been altered in table (comp_abc_1), Column(abc_name) has been altered in table (comp_abc_2), ', 1, '::1', 1, '2024-04-08 11:27:37', 1, '2024-04-08 11:27:37'),
	(97, 'update_all_db_97.txt', 'Column(abc_name1) has been altered to (abc_name) in table (comp_abc_1), Column(abc_name1) has been altered to (abc_name) in table (comp_abc_2), ', 1, '::1', 1, '2024-04-08 11:29:40', 1, '2024-04-08 11:29:40'),
	(98, 'update_all_db_98.txt', 'Column(send_email_agent) Already Exists in Table(tms_queue_escalationmatrix_1)', 0, '::1', 1, '2024-04-18 09:56:42', 1, '2024-04-18 09:56:42'),
	(99, 'update_all_db_99.txt', 'Query has been run successfully, ', 1, '::1', 1, '2024-04-18 10:33:30', 1, '2024-04-18 10:33:30'),
	(100, 'update_all_db_100.txt', 'Query has been run successfully, ', 1, '::1', 1, '2024-04-18 10:35:48', 1, '2024-04-18 10:35:48'),
	(101, 'update_all_db_101.txt', 'Duplicate column name \'email\'', 0, '::1', 1, '2024-04-18 10:36:30', 1, '2024-04-18 10:36:30'),
	(102, 'update_all_db_102.txt', 'Duplicate column name \'email\'', 0, '::1', 1, '2024-04-18 10:44:21', 1, '2024-04-18 10:44:21'),
	(103, 'update_all_db_103.txt', 'Duplicate column name \'email\'', 0, '::1', 1, '2024-04-18 10:45:40', 1, '2024-04-18 10:45:40'),
	(104, 'update_all_db_104.txt', 'Duplicate column name \'email\'', 0, '::1', 1, '2024-04-18 10:46:34', 1, '2024-04-18 10:46:34'),
	(105, 'update_all_db_105.txt', 'Duplicate column name \'email\'', 0, '::1', 1, '2024-04-18 10:47:11', 1, '2024-04-18 10:47:11'),
	(106, 'update_all_db_106.txt', 'Duplicate column name \'email\'', 0, '::1', 1, '2024-04-18 10:52:56', 1, '2024-04-18 10:52:56'),
	(107, 'update_all_db_107.txt', 'Duplicate column name \'email\'', 0, '::1', 1, '2024-04-18 10:53:32', 1, '2024-04-18 10:53:32'),
	(108, 'update_all_db_108.txt', 'Duplicate column name \'email\'', 0, '::1', 1, '2024-04-18 10:53:46', 1, '2024-04-18 10:53:46'),
	(109, 'update_all_db_109.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:00:22', 1, '2024-04-18 11:00:22'),
	(110, 'update_all_db_110.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:02:16', 1, '2024-04-18 11:02:16'),
	(111, 'update_all_db_111.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:02:59', 1, '2024-04-18 11:02:59'),
	(112, 'update_all_db_112.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:03:35', 1, '2024-04-18 11:03:35'),
	(113, 'update_all_db_113.txt', 'Query has been run successfully', 0, '::1', 1, '2024-04-18 11:05:02', 1, '2024-04-18 11:05:02'),
	(114, 'update_all_db_114.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:05:44', 1, '2024-04-18 11:05:44'),
	(115, 'update_all_db_115.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:06:02', 1, '2024-04-18 11:06:02'),
	(116, 'update_all_db_116.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:07:02', 1, '2024-04-18 11:07:02'),
	(117, 'update_all_db_117.txt', 'Query has been run successfully', 0, '::1', 1, '2024-04-18 11:07:36', 1, '2024-04-18 11:07:36'),
	(118, 'update_all_db_118.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:08:19', 1, '2024-04-18 11:08:19'),
	(119, 'update_all_db_119.txt', NULL, 0, '::1', 1, '2024-04-18 11:09:42', 1, '2024-04-18 11:09:42'),
	(120, 'update_all_db_120.txt', NULL, 0, '::1', 1, '2024-04-18 11:10:44', 1, '2024-04-18 11:10:44'),
	(121, 'update_all_db_121.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:11:01', 1, '2024-04-18 11:11:01'),
	(122, 'update_all_db_122.txt', 'Query has been run successfully', 0, '::1', 1, '2024-04-18 11:12:51', 1, '2024-04-18 11:12:51'),
	(123, 'update_all_db_123.txt', 'Query has been run successfully', 0, '::1', 1, '2024-04-18 11:13:16', 1, '2024-04-18 11:13:16'),
	(124, 'update_all_db_124.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:13:46', 1, '2024-04-18 11:13:46'),
	(125, 'update_all_db_125.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:14:37', 1, '2024-04-18 11:14:37'),
	(126, 'update_all_db_126.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:15:04', 1, '2024-04-18 11:15:04'),
	(127, 'update_all_db_127.txt', 'Query has been run successfully, ', 1, '::1', 1, '2024-04-18 11:15:26', 1, '2024-04-18 11:15:26'),
	(128, 'update_all_db_128.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:16:51', 1, '2024-04-18 11:16:51'),
	(129, 'update_all_db_129.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:19:08', 1, '2024-04-18 11:19:08'),
	(130, 'update_all_db_130.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:19:28', 1, '2024-04-18 11:19:28'),
	(131, 'update_all_db_131.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:20:48', 1, '2024-04-18 11:20:48'),
	(132, 'update_all_db_132.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:22:13', 1, '2024-04-18 11:22:13'),
	(133, 'update_all_db_133.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:22:40', 1, '2024-04-18 11:22:40'),
	(134, 'update_all_db_134.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:23:28', 1, '2024-04-18 11:23:28'),
	(135, 'update_all_db_135.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:24:06', 1, '2024-04-18 11:24:06'),
	(136, 'update_all_db_136.txt', 'Query has been run successfully, ', 1, '::1', 1, '2024-04-18 11:24:30', 1, '2024-04-18 11:24:30'),
	(137, 'update_all_db_137.txt', 'Query has been run successfully, ', 1, '::1', 1, '2024-04-18 11:26:12', 1, '2024-04-18 11:26:12'),
	(138, 'update_all_db_138.txt', 'Query has been run successfully, ', 1, '::1', 1, '2024-04-18 11:26:50', 1, '2024-04-18 11:26:50'),
	(139, 'update_all_db_139.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:32:43', 1, '2024-04-18 11:32:43'),
	(140, 'update_all_db_140.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:32:49', 1, '2024-04-18 11:32:49'),
	(141, 'update_all_db_141.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:33:11', 1, '2024-04-18 11:33:11'),
	(142, 'update_all_db_142.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:33:34', 1, '2024-04-18 11:33:34'),
	(143, 'update_all_db_143.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:33:52', 1, '2024-04-18 11:33:52'),
	(144, 'update_all_db_144.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:34:09', 1, '2024-04-18 11:34:09'),
	(145, 'update_all_db_145.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:35:14', 1, '2024-04-18 11:35:14'),
	(146, 'update_all_db_146.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:35:57', 1, '2024-04-18 11:35:57'),
	(147, 'update_all_db_147.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:36:32', 1, '2024-04-18 11:36:32'),
	(148, 'update_all_db_148.txt', 'Query has been run successfully', 0, '::1', 1, '2024-04-18 11:39:23', 1, '2024-04-18 11:39:23'),
	(149, 'update_all_db_149.txt', 'Query has been run successfully', 0, '::1', 1, '2024-04-18 11:40:20', 1, '2024-04-18 11:40:20'),
	(150, 'update_all_db_150.txt', 'Query has been run successfully, ', 0, '::1', 1, '2024-04-18 11:40:48', 1, '2024-04-18 11:40:48'),
	(151, 'update_all_db_151.txt', 'Query has been run successfully', 0, '::1', 1, '2024-04-18 11:42:54', 1, '2024-04-18 11:42:54'),
	(152, 'update_all_db_152.txt', 'Query has been run successfully', 0, '::1', 1, '2024-04-18 11:43:45', 1, '2024-04-18 11:43:45'),
	(153, 'update_all_db_153.txt', 'Query has been run successfully', 1, '::1', 1, '2024-04-18 11:44:34', 1, '2024-04-18 11:44:34'),
	(154, 'update_all_db_154.txt', 'Duplicate column name \'demo1\'', 0, '::1', 1, '2024-04-18 11:44:57', 1, '2024-04-18 11:44:57'),
	(155, 'update_all_db_155.txt', 'Table(comp_testing_1) Created Successfully, Table(comp_testing_2) Created Successfully', 1, '::1', 1, '2024-04-18 11:47:33', 1, '2024-04-18 11:47:33'),
	(156, 'update_all_db_156.txt', 'Table(comp_testing_1) Created Successfully, Table(comp_testing_2) Created Successfully', 1, '::1', 1, '2024-04-18 11:51:40', 1, '2024-04-18 11:51:40'),
	(157, 'update_all_db_157.txt', NULL, 0, '::1', 1, '2024-04-18 11:51:41', 1, '2024-04-18 11:51:41'),
	(158, 'update_all_db_158.txt', NULL, 0, '::1', 1, '2024-04-18 11:51:45', 1, '2024-04-18 11:51:45'),
	(159, 'update_all_db_159.txt', NULL, 0, '::1', 1, '2024-04-18 11:54:43', 1, '2024-04-18 11:54:43'),
	(160, 'update_all_db_160.txt', NULL, 0, '::1', 1, '2024-04-18 11:56:23', 1, '2024-04-18 11:56:23'),
	(161, 'update_all_db_161.txt', 'Table(comp_testing_1) Already Exists', 0, '::1', 1, '2024-04-18 11:58:46', 1, '2024-04-18 11:58:46'),
	(162, 'update_all_db_162.txt', 'Table(comp_testing_1) Created Successfully, Table(comp_testing_2) Created Successfully', 1, '::1', 1, '2024-04-18 11:59:33', 1, '2024-04-18 11:59:33');

**
CREATE TABLE IF NOT EXISTS `tms_user_master` (
  `id` int NOT NULL AUTO_INCREMENT,
  `user_id` int DEFAULT NULL,
  `manager_id` int DEFAULT NULL,
  `user_name` varchar(50) DEFAULT NULL,
  `name` varchar(100) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `password` text,
  `created_date` datetime DEFAULT CURRENT_TIMESTAMP,
  `created_by` int DEFAULT NULL,
  `modified_by` int DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `status` int DEFAULT NULL,
  `time_stamp` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `full_control` int DEFAULT '0',
  `ticket_assigned` int DEFAULT NULL,
  `user_type` int DEFAULT NULL,
  `state` int DEFAULT NULL,
  `district` int DEFAULT NULL,
  `mobile_no` varchar(16) DEFAULT NULL,
  `signature` text,
  `auto_assign` tinyint DEFAULT '0',
  `maskPhone` tinyint DEFAULT '0',
  `maskEmail` tinyint DEFAULT '0',
  `queue_id` varchar(50) DEFAULT NULL,
  `action_id` varchar(50) DEFAULT NULL,
  `last_assign_time` datetime DEFAULT NULL,
  `assign_upper_level` tinyint DEFAULT '0',
  `priority_change_flag` tinyint DEFAULT '0',
  `user_profile` int DEFAULT NULL,
  `shift_id` int DEFAULT NULL,
  `device_id` int DEFAULT NULL,
  `is_login` int DEFAULT NULL,
  `Userlogo` varchar(500) DEFAULT NULL,
  `crm_theme` int DEFAULT NULL,
  `crm_pcolor` varchar(50) DEFAULT NULL,
  `last_lang` varchar(50) DEFAULT NULL,
  `pin_code` varchar(50) DEFAULT NULL,
  `address` text NOT NULL,
  `refresh_switch` tinyint DEFAULT NULL,
  `dashboard_refresh_time` varchar(50) DEFAULT NULL,
  `otp` varchar(4) DEFAULT NULL,
  `default_queue` int DEFAULT NULL,
  `login_session` varchar(100) DEFAULT NULL,
  `access_token` varchar(200) DEFAULT NULL,
  `login_state` tinyint DEFAULT NULL,
  `password_created_on` datetime DEFAULT NULL,
  `break_state` tinyint DEFAULT NULL,
  `break_id` int DEFAULT NULL,
  `break_started_time` datetime DEFAULT NULL,
  `break_closed_time` varchar(50) DEFAULT NULL,
  `break_last_time` datetime DEFAULT NULL,
  `today_count` int DEFAULT NULL,
  `overallcount` int DEFAULT NULL,
  `assigndate` datetime DEFAULT CURRENT_TIMESTAMP,
  `emp_code` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `user_type` (`user_type`),
  CONSTRAINT `FK_1_user_type` FOREIGN KEY (`user_type`) REFERENCES `tms_user_type` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=62 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_user_master` (`id`, `user_id`, `manager_id`, `user_name`, `name`, `email`, `password`, `created_date`, `created_by`, `modified_by`, `modified_date`, `status`, `time_stamp`, `full_control`, `ticket_assigned`, `user_type`, `state`, `district`, `mobile_no`, `signature`, `auto_assign`, `maskPhone`, `maskEmail`, `queue_id`, `action_id`, `last_assign_time`, `assign_upper_level`, `priority_change_flag`, `user_profile`, `shift_id`, `device_id`, `is_login`, `Userlogo`, `crm_theme`, `crm_pcolor`, `last_lang`, `pin_code`, `address`, `refresh_switch`, `dashboard_refresh_time`, `otp`, `default_queue`, `login_session`, `access_token`, `login_state`, `password_created_on`, `break_state`, `break_id`, `break_started_time`, `break_closed_time`, `break_last_time`, `today_count`, `overallcount`, `assigndate`, `emp_code`) VALUES
	(1, 1, 0, 'admint', 'admin', 'admin@sansoftwares.in', '857a9c1280437477d9f1101ad50f6e6d', '2024-03-07 12:17:09', 1, 1, '2025-05-05 12:01:35', 1, '2025-05-05 12:01:35', 1, NULL, 1, 1, 0, '6392050022', '<div><br></div><div>Warm Regards,</div><div>Aayush Kumar</div><div>SAN Support Team.</div><div>Phone : 9810018735</div><div>Email: support@sansoftwares.com</div><div>Head Office: 419, 4th Floor, M3M Urbana, Sector 67, Gurgaon, Haryana, India-122018</div><div></div>', 0, 0, 0, '1', '19', NULL, 1, 1, NULL, 2, NULL, 1, '665978e5134b9.png', 1, '#4d83d1', 'en', '', '', 0, '10000', '8521', 1, 'd705b15543a9bc7d7b3fa504bc762376', 'mozilla/5.0 (x11; linux x86_64) applewebkit/537.36 (khtml, like gecko) chrome/131.0.0.0 safari/537.3617464266958590.8032232198630957', 1, '2024-04-15 00:00:00', 0, NULL, NULL, NULL, '2025-04-29 16:27:38', 0, NULL, NULL, NULL);

**
CREATE TABLE IF NOT EXISTS `tms_user_type` (
  `id` int NOT NULL AUTO_INCREMENT,
  `title` varchar(100) DEFAULT NULL,
  `manager_id` int DEFAULT NULL,
  `assign` tinyint DEFAULT NULL,
  `move_to_junk` tinyint DEFAULT NULL,
  `move_in_box` tinyint DEFAULT NULL,
  `open_to_queue` tinyint DEFAULT '0',
  `status` tinyint DEFAULT '1',
  `created_by` int DEFAULT NULL,
  `created_date` datetime DEFAULT CURRENT_TIMESTAMP,
  `modified_by` int DEFAULT NULL,
  `modified_date` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_user_type` (`id`, `title`, `manager_id`, `assign`, `move_to_junk`, `move_in_box`, `open_to_queue`, `status`, `created_by`, `created_date`, `modified_by`, `modified_date`) VALUES
	(1, 'Admin', NULL, 1, 1, 1, 1, 1, 1, '2024-05-15 15:52:18', NULL, NULL),
	(2, 'Manager', NULL, 1, 1, 1, 1, 1, 1, '2024-05-15 15:52:27', 1, '2024-06-11 10:06:03'),
	(3, 'Agent', NULL, 1, 0, 0, 0, 1, 1, '2024-05-15 15:52:32', 1, '2024-06-11 10:37:39'),
	(4, 'test', NULL, 0, 0, 0, 0, 1, 59, '2024-05-15 15:55:21', NULL, NULL);

**
CREATE TABLE IF NOT EXISTS `tms_user_type_rights` (
  `usertype_id` int DEFAULT NULL,
  `page_id` int DEFAULT NULL,
  `view_right` tinyint DEFAULT NULL,
  `add_right` tinyint DEFAULT NULL,
  `edit_right` tinyint DEFAULT NULL,
  `delete_right` tinyint DEFAULT NULL,
  `export_right` tinyint DEFAULT NULL,
  KEY `FK_tms_user_type_rights_tms_user_type` (`usertype_id`),
  CONSTRAINT `FK_tms_user_type_rights_tms_user_type` FOREIGN KEY (`usertype_id`) REFERENCES `tms_user_type` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
INSERT INTO `tms_user_type_rights` (`usertype_id`, `page_id`, `view_right`, `add_right`, `edit_right`, `delete_right`, `export_right`) VALUES
	(3, 1, 1, 1, 1, 1, 1),
	(3, 2, 1, 1, 1, 1, 1),
	(3, 35, 1, 1, 1, 1, 1),
	(3, 3, 1, 1, 1, 1, 1),
	(3, 5, 1, 1, 1, 1, 1),
	(3, 4, 1, 1, 1, 1, 1),
	(3, 6, 1, 1, 1, 1, 1),
	(3, 9, 1, 1, 1, 1, 1),
	(3, 10, 1, 1, 1, 1, 1),
	(3, 13, 1, 1, 1, 1, 1),
	(3, 19, 1, 1, 1, 1, 1),
	(3, 37, 1, 1, 1, 1, 1),
	(3, 21, 1, 1, 1, 1, 1),
	(3, 22, 1, 1, 1, 1, 1),
	(3, 26, 1, 1, 1, 1, 1),
	(3, 28, 1, 1, 1, 1, 1),
	(3, 29, 1, 1, 1, 1, 1),
	(3, 27, 1, 1, 1, 1, 1),
	(3, 41, 1, 1, 1, 1, 1),
	(3, 38, 1, 1, 1, 1, 1),
	(3, 40, 1, 1, 1, 1, 1),
	(3, 32, 1, 1, 1, 1, 1),
	(3, 31, 1, 1, 1, 1, 1),
	(3, 30, 1, 1, 1, 1, 1),
	(3, 25, 1, 1, 1, 1, 1),
	(3, 24, 1, 1, 1, 1, 1),
	(3, 7, 1, 1, 1, 1, 1),
	(3, 11, 1, 1, 1, 1, 1),
	(3, 8, 1, 1, 1, 1, 1),
	(3, 14, 1, 1, 1, 1, 1),
	(3, 33, 1, 1, 1, 1, 1),
	(3, 36, 1, 1, 1, 1, 1),
	(2, 1, 1, 1, 1, 1, 1),
	(2, 2, 1, 1, 1, 1, 1),
	(2, 35, 1, 1, 1, 1, 1),
	(2, 3, 1, 1, 1, 1, 1),
	(2, 5, 1, 1, 1, 1, 1),
	(2, 4, 1, 1, 1, 1, 1),
	(2, 6, 1, 1, 1, 1, 1),
	(2, 9, 1, 1, 1, 1, 1),
	(2, 10, 1, 1, 1, 1, 1),
	(2, 13, 1, 1, 1, 1, 1),
	(2, 19, 1, 1, 1, 1, 1),
	(2, 37, 1, 1, 1, 1, 1),
	(2, 21, 1, 1, 1, 1, 1),
	(2, 22, 1, 1, 1, 1, 1),
	(2, 26, 1, 1, 1, 1, 1),
	(2, 28, 1, 1, 1, 1, 1),
	(2, 29, 1, 1, 1, 1, 1),
	(2, 27, 1, 1, 1, 1, 1),
	(2, 41, 1, 1, 1, 1, 1),
	(2, 38, 1, 1, 1, 1, 1),
	(2, 40, 1, 1, 1, 1, 1),
	(2, 32, 1, 1, 1, 1, 1),
	(2, 31, 1, 1, 1, 1, 1),
	(2, 30, 1, 1, 1, 1, 1),
	(2, 25, 1, 1, 1, 1, 1),
	(2, 24, 1, 1, 1, 1, 1),
	(2, 7, 1, 1, 1, 1, 1),
	(2, 11, 1, 1, 1, 1, 1),
	(2, 8, 1, 1, 1, 1, 1),
	(2, 14, 1, 1, 1, 1, 1),
	(2, 33, 1, 1, 1, 1, 1),
	(2, 36, 1, 1, 1, 1, 1),
	(4, 1, 1, 1, 1, 1, 1),
	(4, 2, 1, 1, 1, 1, 1),
	(4, 35, 1, 1, 1, 1, 1),
	(4, 3, 1, 1, 1, 1, 1),
	(4, 5, 1, 1, 1, 1, 1),
	(4, 4, 1, 1, 1, 1, 1),
	(4, 6, 1, 1, 1, 1, 1),
	(4, 9, 1, 1, 1, 1, 1),
	(4, 10, 1, 1, 1, 1, 1),
	(4, 13, 1, 1, 1, 1, 1),
	(4, 19, 1, 1, 1, 1, 1),
	(4, 37, 1, 1, 1, 1, 1),
	(4, 21, 1, 1, 1, 1, 1),
	(4, 22, 1, 1, 1, 1, 1),
	(4, 26, 1, 1, 1, 1, 1),
	(4, 28, 1, 1, 1, 1, 1),
	(4, 29, 1, 1, 1, 1, 1),
	(4, 27, 1, 1, 1, 1, 1),
	(4, 41, 1, 1, 1, 1, 1),
	(4, 38, 1, 1, 1, 1, 1),
	(4, 40, 1, 1, 1, 1, 1),
	(4, 32, 1, 1, 1, 1, 1),
	(4, 31, 1, 1, 1, 1, 1),
	(4, 30, 1, 1, 1, 1, 1),
	(4, 25, 1, 1, 1, 1, 1),
	(4, 24, 1, 1, 1, 1, 1),
	(4, 7, 1, 1, 1, 1, 1),
	(4, 11, 1, 1, 1, 1, 1),
	(4, 8, 1, 1, 1, 1, 1),
	(4, 14, 1, 1, 1, 1, 1),
	(4, 33, 1, 1, 1, 1, 1),
	(4, 36, 1, 1, 1, 1, 1),
	(1, 1, 1, 1, 1, 1, 1),
	(1, 2, 1, 1, 1, 1, 1),
	(1, 35, 1, 1, 1, 1, 1),
	(1, 3, 1, 1, 1, 1, 1),
	(1, 5, 1, 1, 1, 1, 1),
	(1, 4, 1, 1, 1, 1, 1),
	(1, 6, 1, 1, 1, 1, 1),
	(1, 9, 1, 1, 1, 1, 1),
	(1, 10, 1, 1, 1, 1, 1),
	(1, 13, 1, 1, 1, 1, 1),
	(1, 19, 1, 1, 1, 1, 1),
	(1, 37, 1, 1, 1, 1, 1),
	(1, 21, 1, 1, 1, 1, 1),
	(1, 22, 1, 1, 1, 1, 1),
	(1, 26, 1, 1, 1, 1, 1),
	(1, 28, 1, 1, 1, 1, 1),
	(1, 29, 1, 1, 1, 1, 1),
	(1, 27, 1, 1, 1, 1, 1),
	(1, 41, 1, 1, 1, 1, 1),
	(1, 38, 1, 1, 1, 1, 1),
	(1, 40, 1, 1, 1, 1, 1),
	(1, 32, 1, 1, 1, 1, 1),
	(1, 31, 1, 1, 1, 1, 1),
	(1, 30, 1, 1, 1, 1, 1),
	(1, 25, 1, 1, 1, 1, 1),
	(1, 24, 1, 1, 1, 1, 1),
	(1, 7, 1, 1, 1, 1, 1),
	(1, 11, 1, 1, 1, 1, 1),
	(1, 8, 1, 1, 1, 1, 1),
	(1, 14, 1, 1, 1, 1, 1),
	(1, 33, 1, 1, 1, 1, 1),
	(1, 36, 1, 1, 1, 1, 1);

**
CREATE PROCEDURE `updateagent_productivity`(
	IN `agentid` INT,
	IN `agentname` VARCHAR(50),
	IN `ticketid` INT,
	IN `queueid` INT,
	IN `start_time` VARCHAR(50),
	IN `end_time` VARCHAR(50),
	IN `state` VARCHAR(50),
	IN `break_id` INT,
	IN `break_name` VARCHAR(50),
	IN `ip_address` VARCHAR(20),
	IN `is_login` INT,
	IN `remark` TINYTEXT
)
BEGIN

INSERT into `updateagent_productivity_log`(`agentid`,`agentname`,`ticketid`,`queueid`,`start_time`,`end_time`,`state`,`break_id`,`break_name`,`ip_address`,`is_login`,`remark`,`inserted_on`)
VALUE (`agentid`,`agentname`,`ticketid`,`queueid`,`start_time`,`end_time`,`state`,`break_id`,`break_name`,`ip_address`,`is_login`,`remark`,`inserted_on`);

SELECT MAX(id) id INTO @id FROM agent_productivity_report_log WHERE agent_id=agentid AND state NOT IN ('Login');

if @id IS NOT NULL then
SET @startlogupdate=CONCAT('UPDATE agent_productivity_report_log
SET end_time="',start_time,'",
duration=TIMESTAMPDIFF(second,start_time,"',start_time,'")
WHERE id="',@id,'"');

#SELECT @startlogupdate; 
PREPARE stmtstartlogupdate FROM @startlogupdate; 
EXECUTE stmtstartlogupdate; 
DEALLOCATE PREPARE stmtstartlogupdate;

END if;

if state IN ("Login","Logout") then

SET @agentloginsert=CONCAT('
INSERT INTO agent_productivity_report_log (agent_id,agent_name,ticket_id,queue_id,start_time,end_time,duration,state,break_id,break_name,ip_address,is_login,remark)
VALUES ("',agentid,'","',agentname,'","',ticketid,'","',queueid,'",now(),now(),0,"',state,'",ifnull("',break_id,'",0),"',break_name,'","',ip_address,'","',is_login,'","',remark,'")');
ELSE

SET @agentloginsert=CONCAT('
INSERT INTO agent_productivity_report_log (agent_id,agent_name,ticket_id,queue_id,start_time,end_time,duration,state,break_id,break_name,ip_address,is_login,remark)
VALUES ("',agentid,'","',agentname,'","',ticketid,'","',queueid,'","',start_time,'",',case when end_time is null then CONCAT("now()") ELSE CONCAT("'",end_time,"'") END ,',TIMESTAMPDIFF(second,"',start_time,'",',case when end_time is null then CONCAT("now()") ELSE CONCAT("'",end_time,"'") END ,'),"',state,'",ifnull("',break_id,'",0),"',break_name,'","',ip_address,'","',is_login,'","',remark,'")');

END if;
#SELECT @agentloginsert; 
PREPARE stmtagentloginsert FROM @agentloginsert; 
EXECUTE stmtagentloginsert; 
DEALLOCATE PREPARE stmtagentloginsert;
END
**
CREATE TABLE IF NOT EXISTS `updateagent_productivity_log` (
  `agentid` int DEFAULT NULL,
  `agentname` varchar(50) DEFAULT NULL,
  `ticketid` int DEFAULT NULL,
  `queueid` int DEFAULT NULL,
  `start_time` varchar(50) DEFAULT NULL,
  `end_time` varchar(50) DEFAULT NULL,
  `state` varchar(50) DEFAULT NULL,
  `break_id` int DEFAULT NULL,
  `break_name` varchar(50) DEFAULT NULL,
  `ip_address` varchar(20) DEFAULT NULL,
  `is_login` int DEFAULT NULL,
  `remark` tinytext,
  `inserted_on` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
**
CREATE TABLE IF NOT EXISTS `user_assign_logs` (
  `id` int NOT NULL AUTO_INCREMENT,
  `queue_id` int DEFAULT NULL,
  `ticket_id` int DEFAULT NULL,
  `assigned_by` int DEFAULT NULL,
  `assigned_to` int DEFAULT NULL,
  `last_assigned` int DEFAULT NULL,
  `assigned_on` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `status_id` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE PROCEDURE `usp_get_ticket_status_wise_count`(
	IN `qid` INT,
	IN `cond` TEXT,
	IN `userids` TEXT,
	IN `isadmin` TINYINT,
	IN `istatrec` TINYINT,
	IN `fromdate` TEXT,
	IN `todate` TEXT
)
BEGIN

set fromdate=if(IFNULL(fromdate,"")!="",CONCAT(' and Date_Format(ttm.created_date,"%Y-%m-%d")>="',fromdate,'" '),' ');
set todate=if(IFNULL(todate,"")!="",CONCAT(' and Date_Format(ttm.created_date,"%Y-%m-%d")<="',todate,'" '),' ');
SET @sqlquery1=CONCAT('
SELECT status_id,CONCAT(UPPER(SUBSTRING(status_name, 1, 1)), LOWER(SUBSTRING(status_name, 2))) AS status_name,colour_code,cnt,Total FROM (
SELECT tqs.status_id,order_no,status_name,colour_code,ifnull(cnt,0)cnt,ifnull(Total,0)Total FROM
 (SELECT 0 status_id,"TAT Excedeed"status_name,"#e55b5b"colour_code,100 order_no UNION all
SELECT status_id,t.status_name,t.colour_code,t.order_no FROM tms_queue_status_',qid,' t) tqs LEFT join
 (
SELECT if(TIMESTAMPDIFF(hour,IFNULL(ttm.priority_changed_on,ttm.created_date),NOW())>tqp.tat and tqs.is_close_status=0,0,ttm.status_id)status_id,COUNT(if(Date_Format(ttm.created_date,"%Y-%m-%d")=CURDATE(),1,null)) cnt,COUNT(if(1=1  ',fromdate,todate,',1,NULL))Total
FROM 
tms_ticket_master_',qid,' ttm  
join tms_queue_status_',qid,' tqs on ttm.status_id=tqs.status_id
LEFT JOIN tms_queue_priority_',qid,' tqp on ttm.priority_id=tqp.priority_id

where 1=1 AND IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if(IFNULL(isadmin,0)=0 AND IFNULL(userids,"")!="",CONCAT(' and ttm.assigned_to in(',userids,') '),""),'

GROUP BY if(TIMESTAMPDIFF(hour,IFNULL(ttm.priority_changed_on,ttm.created_date),NOW())>tqp.tat and tqs.is_close_status=0,0,ttm.status_id)

)ttm
  
on ttm.status_id=tqs.status_id

UNION ALL
SELECT 0 status_id,-1 order_no,"ALL" status_name,"#6fa8dc" colour_code,COUNT(if(Date_Format(ttm.created_date,"%Y-%m-%d")=CURDATE(),1,null)) cnt,COUNT(if(1=1  ',fromdate,todate,',1,NULL))Total
FROM  
tms_ticket_master_',qid,' ttm  
LEFT JOIN tms_queue_priority_',qid,' tqp on ttm.priority_id=tqp.priority_id
where 1=1 AND IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if(IFNULL(isadmin,0)=0 AND IFNULL(userids,"")!="",CONCAT(' and ttm.assigned_to in(',userids,') '),""),' 

)t

ORDER BY order_no

;');SET @sqlquery2=CONCAT('
SELECT status_id,CONCAT(UPPER(SUBSTRING(status_name, 1, 1)), LOWER(SUBSTRING(status_name, 2))) AS status_name,colour_code,cnt,Total FROM (
SELECT tqs.status_id,order_no,status_name,colour_code,ifnull(cnt,0)cnt,ifnull(Total,0)Total FROM 
(SELECT ttm.status_id,COUNT(if(Date_Format(ttm.created_date,"%Y-%m-%d")=CURDATE(),1,null)) cnt,COUNT(if(1=1  ',fromdate,todate,',1,NULL))Total
FROM  
tms_ticket_master_',qid,' ttm 
join tms_queue_status_',qid,' tqs ON tqs.status_id=ttm.status_id 
LEFT JOIN tms_queue_priority_',qid,' tqp on ttm.priority_id=tqp.priority_id

WHERE 1=1 AND IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if(IFNULL(isadmin,0)=0 AND IFNULL(userids,"")!="",CONCAT(' and ttm.assigned_to in(',userids,') '),""),' AND TIMESTAMPDIFF(hour,IFNULL(ttm.priority_changed_on,ttm.created_date),NOW())>tqp.tat and tqs.is_close_status=0

GROUP BY ttm.status_id
)ttm
RIGHT JOIN   tms_queue_status_',qid,' tqs ON tqs.status_id=ttm.status_id

UNION ALL
SELECT 0 status_id,-1 order_no,"ALL" status_name,"#6fa8dc" colour_code,COUNT(if(Date_Format(ttm.created_date,"%Y-%m-%d")=CURDATE(),1,null)) cnt,COUNT(if(1=1  ',fromdate,todate,',1,NULL))Total
FROM  
tms_ticket_master_',qid,' ttm 
join tms_queue_status_',qid,' tqs ON tqs.status_id=ttm.status_id 
LEFT JOIN tms_queue_priority_',qid,' tqp on ttm.priority_id=tqp.priority_id
where 1=1 AND IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 ',if(IFNULL(cond,"")!="",CONCAT(' and ',cond),""),if(IFNULL(isadmin,0)=0 AND IFNULL(userids,"")!="",CONCAT(' and ttm.assigned_to in(',userids,') '),""),' AND TIMESTAMPDIFF(hour,IFNULL(ttm.priority_changed_on,ttm.created_date),NOW())>tqp.tat and tqs.is_close_status=0
)t

ORDER BY order_no
');
SET @sqlquery=if(istatrec=1,@sqlquery2,@sqlquery1);


PREPARE stmt_ticket_count FROM @sqlquery;
EXECUTE stmt_ticket_count;
DEALLOCATE PREPARE stmt_ticket_count;


END
**
CREATE TABLE IF NOT EXISTS `whatsapp_api_log_1` (
  `id` int NOT NULL AUTO_INCREMENT,
  `ticket_id` varchar(100) DEFAULT NULL,
  `conversation_id` varchar(100) DEFAULT NULL,
  `mobile_no` varchar(20) DEFAULT NULL,
  `response` text,
  `cr_date` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

**
CREATE PROCEDURE `WIPReport`(
	IN `fromDate` VARCHAR(50),
	IN `toDate` VARCHAR(50),
	IN `user_id` VARCHAR(100),
	IN `ReportType` VARCHAR(50),
	IN `queue_id` INT,
	IN `fullcontrol` INT,
	IN `limit_offset` VARCHAR(30)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
   BEGIN
     GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
       SELECT CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS Error_Message;
   
        ROLLBACK;   
   END; 
   START TRANSACTION;

SET @fromDate = case when IFNULL(fromDate,'')='' then CURDATE() ELSE fromDate END;
SET @toDate = case when IFNULL(toDate,'')='' then NOW() ELSE toDate END;

SET SESSION group_concat_max_len = 10000000;
 
SET @sql = CONCAT('SELECT group_concat(DISTINCT status_id) INTO @status_ids
FROM tms_user_master tum JOIN tms_statuspermission_',queue_id,' tsp ON tum.user_type=tsp.user_type
WHERE tsp.is_checked=1  ',if( IFNULL(user_id,"")!="",CONCAT(' AND tum.user_id in (',user_id,')'),""),' ');
#SELECT @SQL;
PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;
 
    SET @sqlquery = 'SELECT  ';    
	 if ReportType = 'User Wise' Then
	    SET @sqlquery = CONCAT(@sqlquery, ' tum.user_name as "User Name" , tum.user_id as user_id,  ');
    END if; 
	  
	    SET @sqlquery = CONCAT(@sqlquery, ' tqp.priority_name, tqp.colour_code,',if(IFNULL(ReportType,"")="",CONCAT(' "WIP" WIP, '),""),' 
	    SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=30
	    THEN 1 ELSE 0 END) `WIP 0-30 Minutes`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<30
	    THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `WIP 0-30 Minutes%`,
 SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=30
		 AND TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=60
	    THEN 1 ELSE 0 END) `WIP 30-1 Hour`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(MINUTE, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=30
		 AND TIMESTAMPDIFF(MINUTE,IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<60
	     THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `WIP 30-1 Hour%`,
 SUM(CASE WHEN TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=1
		 AND TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=24
	    THEN 1 ELSE 0 END) `WIP 1-24 Hour`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=1
		 AND TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=24
	    THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `WIP 1-24 Hour%`,
 SUM(CASE WHEN TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=24
		 AND TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=48
	    THEN 1 ELSE 0 END) `WIP More Than 24 Hour`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>=24
		 AND TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))<=48
	    THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `WIP More Than 24 Hour%`,
	    SUM(CASE WHEN TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>48
	    THEN 1 ELSE 0 END) `WIP More Than 48 Hour`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN TIMESTAMPDIFF(HOUR, IFNULL(ttm.created_date,ttm.assigned_on), IFNULL(ticket_closed_date,NOW()))>48
	    THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `WIP More Than 48 Hour%`,
	    /*SUM(CASE WHEN reply=0 THEN 1 ELSE 0 END) `No Reply`,
CONCAT(ROUND(IFNULL(SUM(CASE WHEN reply<=0 THEN 1 ELSE 0 END)*100/NULLIF(Count(1),0),0),0),"%") `No Reply%`,*/
	    Count(1) `Total`,
	CONCAT(ROUND(IFNULL(Count(1)*100/NULLIF(Count(1),0),0),0),"%") `Total Percentage`
FROM tms_ticket_master_',queue_id,' AS ttm  
LEFT JOIN tms_user_master tum ON tum.user_id = ttm.assigned_to 
LEFT JOIN (SELECT MAX(conversation_id) AS Last_conversation_id, ticket_unique_id,SUM(case when conversation_type IN ("reply","reply_all")  then 1 ELSE 0 END) reply,min(case when conversation_type IN ("reply", "reply_all", "forward") then conversation_date end) First_conversation_date FROM tms_conversation_master_',queue_id,' tcm GROUP BY ticket_unique_id) AS Last_con ON Last_con.ticket_unique_id = ttm.ticket_unique_id 
LEFT JOIN tms_conversation_master_',queue_id,' tcm ON tcm.conversation_id = Last_con.Last_conversation_id
LEFT JOIN tms_queue_priority_',queue_id,' tqp ON ttm.priority_id = tqp.priority_id 
LEFT JOIN tms_queue_status_',queue_id,' tqs ON tqs.status_id = ttm.status_id 
where IFNULL(is_junk,0)=0 AND IFNULL(is_deleted_ticket,0)=0 and IFNULL(ttm.is_draft,0)=0 ',if( IFNULL(user_id,"")!="",CONCAT(' and tum.user_id in (',user_id,')'),""),if(IFNULL(fullcontrol,0)=0 AND IFNULL(@status_ids,'')!='',CONCAT('and  tqs.status_id in (',@status_ids,')'),""), ' AND ttm.assigned_on>="',CONCAT(@fromDate, ' ','00:00:00'),'" and ttm.assigned_on<="',CONCAT(@toDate, ' ', '23:59:59'),'" 
AND tqs.ticket_status_type IN (2,3)
GROUP BY tqp.priority_name, tqp.colour_code'
);
	 
	 if ReportType = 'User Wise' Then
	    SET @sqlquery = CONCAT(@sqlquery, ' ,tum.user_name,tum.user_id');
    END if;
	 
	 if limit_offset !='' then
	 	SET @sqlquery = CONCAT(@sqlquery,' LIMIT ', limit_offset);
	 END if;
   #SELECT @sqlquery;
	PREPARE stmtsqlquery FROM @sqlquery;
    EXECUTE stmtsqlquery;
    DEALLOCATE PREPARE stmtsqlquery;
COMMIT;
END
**
SET FOREIGN_KEY_CHECKS = 1;
**