			SELECT s.RetID 'retId', s.SalID 'saleId', COALESCE(s.SalReference,'') 'saleReference', COALESCE(DATE_FORMAT(s.SalDate, '%d-%b-%Y'),'') 'saleDate', s.CustID 'custId', COALESCE(c.CustName,'') 'custName',
					 s.EmpID 'empId', COALESCE(e.EmpName,'') 'empName', COALESCE(s.NetTotalAmt,0) 'netTotalAmt'
			FROM tblsales_return s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			LEFT JOIN tblemployee e ON e.EmpID = s.EmpID
			WHERE s.EmpID = var_empId AND IF(var_search = 'all',TRUE, (
			RetID LIKE CONCAT('%',var_search,'%')
			OR SalReference LIKE CONCAT('%',var_search,'%')
			OR SalID LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR e.EmpID = var_search
			OR e.EmpName LIKE CONCAT('%',var_search,'%')
			OR s.NetTotalAmt = var_search))
			ORDER BY s.RetID DESC
			LIMIT var_num  OFFSET var_off
			;
		ELSE
			SET var_empId = (SELECT tbluseremployee.EmpID from tbluseremployee where tbluseremployee.UID = var_user_id LIMIT 1);
			SELECT  COUNT(*) INTO var_rows 
			FROM tblsales_return s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			LEFT JOIN tblemployee e ON e.EmpID = s.EmpID
			WHERE DATE(s.SalDate) BETWEEN var_fd AND var_td AND s.EmpID = var_empId AND IF(var_search = 'all',TRUE, (
			RetID LIKE CONCAT('%',var_search,'%')
			OR SalReference LIKE CONCAT('%',var_search,'%')
			OR SalID LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR e.EmpID = var_search
			OR e.EmpName LIKE CONCAT('%',var_search,'%')
			OR s.NetTotalAmt = var_search))
			;
			SELECT s.RetID 'retId', s.SalID 'saleId', COALESCE(s.SalReference,'') 'saleReference', COALESCE(DATE_FORMAT(s.SalDate, '%d-%b-%Y'),'') 'saleDate', s.CustID 'custId', COALESCE(c.CustName,'') 'custName',
					 s.EmpID 'empId', COALESCE(e.EmpName,'') 'empName', COALESCE(s.NetTotalAmt,0) 'netTotalAmt'
			FROM tblsales_return s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			LEFT JOIN tblemployee e ON e.EmpID = s.EmpID
			WHERE DATE(s.SalDate) BETWEEN var_fd AND var_td AND s.EmpID = var_empId AND IF(var_search = 'all',TRUE, (
			RetID LIKE CONCAT('%',var_search,'%')
			OR SalReference LIKE CONCAT('%',var_search,'%')
			OR SalID LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR e.EmpID = var_search
			OR e.EmpName LIKE CONCAT('%',var_search,'%')
			OR s.NetTotalAmt = var_search))
			ORDER BY s.RetID DESC
			LIMIT var_num  OFFSET var_off
			;
		END IF;
	END IF;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_customer`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_customer`(in var_user_id varchar(255), in var_num int, in var_page int, in var_search varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_empId varchar(255);
	DECLARE var_rt varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_user_id LIMIT 1)), 0);
	SET var_empId = COALESCE((SELECT EmpID FROM tbluseremployee WHERE UID = var_user_id),'');
	SET var_off = ((var_page-1)*var_num);
	SET var_search = CONCAT('%',var_search,'%');
	IF var_rt = '1' THEN
			SELECT COUNT(CustID) INTO var_rows FROM tblcustomer WHERE Inactive=0 AND custid LIKE var_search OR custname LIKE var_search;

			SELECT CustID 'custId', COALESCE(CustName, '') 'custName' , COALESCE(PriceCode,'') 'priceCode', COALESCE(TermNetDueIn,0) 'termNetDueIn', COALESCE(AID,'') shipId, 
			COALESCE((SELECT shipname FROM tblshipaddress WHERE tblshipaddress.shipid = tblcustomer.AID LIMIT 1),'') shipName, COALESCE(TermCreditLimit,'') 'termCreditLimit',
			COALESCE(CustTel1, '') 'custTel1', COALESCE(CustTel2, '') 'custTel2', COALESCE(ImagePath,'') 'logo'  
			FROM tblcustomer 
			WHERE Inactive=0  AND (custid LIKE var_search OR custname LIKE var_search)
			ORDER BY CustID
			LIMIT var_num  OFFSET var_off;
	ELSE
			SELECT COUNT(CustID) INTO var_rows FROM tblcustomer WHERE Inactive=0 AND CustID in(SELECT custid FROM tblemployeecustomer 
			WHERE empid = var_empId) AND (custid LIKE var_search OR custname LIKE var_search) ;

			SELECT CustID 'custId', COALESCE(CustName, '') 'custName' , COALESCE(PriceCode,'') 'priceCode', COALESCE(TermNetDueIn,0) 'termNetDueIn', COALESCE(AID,'') shipId, 
			COALESCE((SELECT shipname FROM tblshipaddress WHERE tblshipaddress.shipid = tblcustomer.AID LIMIT 1),'') shipName, COALESCE(TermCreditLimit,'') 'termCreditLimit',
			COALESCE(CustTel1, '') 'custTel1', COALESCE(CustTel2, '') 'custTel2', COALESCE(ImagePath,'') 'logo'  
			FROM tblcustomer 
			WHERE Inactive=0 AND CustID IN(SELECT custid FROM tblemployeecustomer WHERE empid = var_empId) AND (custid LIKE var_search OR custname LIKE var_search)
			ORDER BY CustID
			LIMIT var_num  OFFSET var_off
			;
	END IF;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_customer_group`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_customer_group`(in var_row int, in var_page int, in var_key varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);
	SELECT COUNT(CustGroupID) INTO var_rows FROM tblcustomergroup WHERE CustGroupID LIKE CONCAT('%', var_key, '%') OR CustGroupName LIKE CONCAT('%', var_key, '%'); 
	
	SELECT COALESCE(CustGroupID, '') 'custGroupId', COALESCE(CustGroupName, '') 'custGroupName' 
	FROM tblcustomergroup
	WHERE CustGroupID LIKE CONCAT('%', var_key, '%') OR CustGroupName LIKE CONCAT('%', var_key, '%')
	ORDER BY CustGroupID
	LIMIT var_row  OFFSET var_off;

	SELECT CEIL(COALESCE(var_rows,0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_industry`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_industry`(in var_row int, in var_page int, in var_key varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);
	SELECT COUNT(I_ID) INTO var_rows FROM crm_industry WHERE I_ID LIKE CONCAT('%', var_key, '%') OR I_Name LIKE CONCAT('%', var_key, '%'); 

	SELECT COALESCE(I_ID, '') 'industID', COALESCE(I_Name, '') 'industName' 
	FROM crm_industry
	WHERE I_ID LIKE CONCAT('%', var_key, '%') OR I_Name LIKE CONCAT('%', var_key, '%')
	ORDER BY I_ID
	LIMIT var_row  OFFSET var_off;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_items`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_items`(in var_user_id varchar(255), in var_key varchar(255), in var_row int, in var_page int)
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);

	SELECT COUNT(ItemID) INTO var_rows FROM tblitem 
	WHERE Inactive = 0 AND ShowOnPos = 1
										 AND ItemID LIKE CONCAT('%', var_key, '%') 
										 OR  ItemName LIKE CONCAT('%', var_key, '%') 
										 OR  itembarcode LIKE CONCAT('%', var_key, '%')
										 OR  itemCode LIKE CONCAT('%', var_key, '%');
	
	SELECT COALESCE(ItemID,'') 'id', COALESCE(ItemName,'') 'name', COALESCE(itemcode,'') 'code', COALESCE(itembarcode, '') 'barcode' , COALESCE(UomID, '') 'uom', COALESCE(ImagePath , '') 'image'
	FROM tblitem 
	WHERE Inactive = 0 AND ShowOnPos = 1
									   AND ItemID LIKE CONCAT('%', var_key, '%') 
									   OR  ItemName LIKE CONCAT('%', var_key, '%') 
									   OR  itemCode LIKE CONCAT('%', var_key, '%')
										 OR  itembarcode LIKE CONCAT('%', var_key, '%')
	ORDER BY ItemID
	LIMIT var_row  OFFSET var_off;
	
	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_list_sale_order`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_list_sale_order`(in var_row int, in var_page int, in var_type varchar(255), in var_key varchar(255), in var_userId varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE typeId varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_off INT DEFAULT 0;

	SET var_off = ((var_page - 1) * var_row);
	SET typeId = (Select RM_TypeID from crm_role where RM_ID = (SELECT URoleID FROM tbluser where UID = var_userId));

	CASE var_type
		
			WHEN 'Sale_Date' THEN

				IF typeId = '1' THEN

					SELECT COUNT(SalID) INTO var_rows 
					FROM tblsaleorder 
					where PostStatus = 'Open' AND SalDate Like CONCAT('%', var_key, '%');

					SELECT COALESCE(S.SalID,'') AS 'EntryNo', COALESCE(SalReference,'') AS 'Reference', COALESCE(DATE(S.SalDate), '') AS 'SalesOrderDate', COALESCE(S.EmpID, '') 'empId', 
					COALESCE((SELECT E.EmpName FROM tblemployee E WHERE E.EmpID =  S.EmpID limit 1), '') AS 'empName', 
					COALESCE(S.CustID, '') AS 'CustomerID',COALESCE((SELECT C.CustName FROM tblcustomer C WHERE C.CustID =  S.CustID limit 1), '') AS 'CustomerName',
					CAST(COALESCE(S.TotalAmt, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.PostStatus AS 'Status', S.ApproveStatus approvedStatus 
					FROM tblsaleorder S 
					where PostStatus = 'Open' AND S.SalDate Like CONCAT('%', var_key, '%')
					ORDER BY S.SalDate DESC

					LIMIT var_row  OFFSET var_off;
					
				ELSE

					SELECT COUNT(SalID) INTO var_rows 
					FROM tblsaleorder s 
					where s.PostStatus = 'Open' AND s.EmpID = (SELECT tbluseremployee.EmpID 
					from tbluseremployee 
					where tbluseremployee.UID = var_userId) AND s.SalDate Like CONCAT('%', var_key, '%');

					SELECT COALESCE(S.SalID,'') AS 'EntryNo', COALESCE(SalReference,'') AS 'Reference', COALESCE(DATE(S.SalDate), '') AS 'SalesOrderDate', COALESCE(S.EmpID, '') 'empId', 
					COALESCE((SELECT E.EmpName FROM tblemployee E WHERE E.EmpID =  S.EmpID limit 1),'') AS 'empName', 
					COALESCE(S.CustID, '') AS 'CustomerID',COALESCE((SELECT C.CustName FROM tblcustomer C WHERE C.CustID =  S.CustID limit 1), '') AS 'CustomerName',
					CAST(COALESCE(S.TotalAmt, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.PostStatus AS 'Status', S.ApproveStatus approvedStatus 
					FROM tblsaleorder S 
					where PostStatus = 'Open' AND S.EmpID = (SELECT tbluseremployee.EmpID 
					from tbluseremployee 
					where tbluseremployee.UID = var_userId) AND S.SalDate Like CONCAT('%', var_key, '%')
					ORDER BY S.SalDate DESC

					LIMIT var_row  OFFSET var_off;

				END IF;

			WHEN 'Sale_ID' THEN

				IF typeId = '1' THEN

					SELECT COUNT(SalID) INTO var_rows 
					FROM tblsaleorder 
					where PostStatus = 'Open' AND SalID Like CONCAT('%', var_key, '%');

					SELECT COALESCE(S.SalID,'') AS 'EntryNo', COALESCE(SalReference,'') AS 'Reference', COALESCE(DATE(S.SalDate), '') AS 'SalesOrderDate', COALESCE(S.EmpID, '') 'empId', 
					COALESCE((SELECT E.EmpName FROM tblemployee E WHERE E.EmpID =  S.EmpID limit 1), '') AS 'empName', 
					COALESCE(S.CustID, '') AS 'CustomerID',COALESCE((SELECT C.CustName FROM tblcustomer C WHERE C.CustID =  S.CustID limit 1), '') AS 'CustomerName',
					CAST(COALESCE(S.TotalAmt, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.PostStatus AS 'Status', S.ApproveStatus approvedStatus 
					FROM tblsaleorder S 
					where PostStatus = 'Open' AND S.SalID Like CONCAT('%', var_key, '%')
					ORDER BY S.SalID DESC

					LIMIT var_row  OFFSET var_off;
					
				ELSE

					SELECT COUNT(SalID) INTO var_rows 
					FROM tblsaleorder s 
					where s.PostStatus = 'Open' AND s.EmpID = (SELECT tbluseremployee.EmpID 
					from tbluseremployee 
					where tbluseremployee.UID = var_userId) AND s.SalID Like CONCAT('%', var_key, '%');

					SELECT COALESCE(S.SalID,'') AS 'EntryNo', COALESCE(SalReference,'') AS 'Reference', COALESCE(DATE(S.SalDate), '') AS 'SalesOrderDate', COALESCE(S.EmpID, '') 'empId', 
					COALESCE((SELECT E.EmpName FROM tblemployee E WHERE E.EmpID =  S.EmpID limit 1),'') AS 'empName', 
					COALESCE(S.CustID, '') AS 'CustomerID',COALESCE((SELECT C.CustName FROM tblcustomer C WHERE C.CustID =  S.CustID limit 1), '') AS 'CustomerName',
					CAST(COALESCE(S.TotalAmt, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.PostStatus AS 'Status', S.ApproveStatus approvedStatus 
					FROM tblsaleorder S 
					where PostStatus = 'Open' AND S.EmpID = (SELECT tbluseremployee.EmpID 
					from tbluseremployee 
					where tbluseremployee.UID = var_userId) AND S.SalID Like CONCAT('%', var_key, '%')
					ORDER BY S.SalID DESC

					LIMIT var_row  OFFSET var_off;

				END IF;

			WHEN 'Customer_ID' THEN

				IF typeId = '1' THEN

					SELECT COUNT(SalID) INTO var_rows 
					FROM tblsaleorder 
					where PostStatus = 'Open' AND CustID Like CONCAT('%', var_key, '%');

					SELECT COALESCE(S.SalID,'') AS 'EntryNo', COALESCE(SalReference,'') AS 'Reference', COALESCE(DATE(S.SalDate), '') AS 'SalesOrderDate', COALESCE(S.EmpID, '') 'empId', 
					COALESCE((SELECT E.EmpName FROM tblemployee E WHERE E.EmpID =  S.EmpID limit 1), '') AS 'empName', 
					COALESCE(S.CustID, '') AS 'CustomerID',COALESCE((SELECT C.CustName FROM tblcustomer C WHERE C.CustID =  S.CustID limit 1), '') AS 'CustomerName',
					CAST(COALESCE(S.TotalAmt, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.PostStatus AS 'Status', S.ApproveStatus approvedStatus 
					FROM tblsaleorder S 
					where PostStatus = 'Open' AND S.CustID Like CONCAT('%', var_key, '%')
					ORDER BY S.CustID DESC

					LIMIT var_row  OFFSET var_off;
					
				ELSE

					SELECT COUNT(SalID) INTO var_rows 
					FROM tblsaleorder s 
					where s.PostStatus = 'Open' AND s.EmpID = (SELECT tbluseremployee.EmpID 
					from tbluseremployee 
					where tbluseremployee.UID = var_userId) AND s.CustID Like CONCAT('%', var_key, '%');

					SELECT COALESCE(S.SalID,'') AS 'EntryNo', COALESCE(SalReference,'') AS 'Reference', COALESCE(DATE(S.SalDate), '') AS 'SalesOrderDate', COALESCE(S.EmpID, '') 'empId', 
					COALESCE((SELECT E.EmpName FROM tblemployee E WHERE E.EmpID =  S.EmpID limit 1),'') AS 'empName', 
					COALESCE(S.CustID, '') AS 'CustomerID',COALESCE((SELECT C.CustName FROM tblcustomer C WHERE C.CustID =  S.CustID limit 1), '') AS 'CustomerName',
					CAST(COALESCE(S.TotalAmt, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.PostStatus AS 'Status', S.ApproveStatus approvedStatus 
					FROM tblsaleorder S 
					where PostStatus = 'Open' AND S.EmpID = (SELECT tbluseremployee.EmpID 
					from tbluseremployee 
					where tbluseremployee.UID = var_userId) AND S.CustID Like CONCAT('%', var_key, '%')
					ORDER BY S.CustID DESC

					LIMIT var_row  OFFSET var_off;

				END IF;

			WHEN 'Reference' THEN

				IF typeId = '1' THEN

					SELECT COUNT(SalID) INTO var_rows 
					FROM tblsaleorder 
					where PostStatus = 'Open' AND SalReference Like CONCAT('%', var_key, '%');

					SELECT COALESCE(S.SalID,'') AS 'EntryNo', COALESCE(SalReference,'') AS 'Reference', COALESCE(DATE(S.SalDate), '') AS 'SalesOrderDate', COALESCE(S.EmpID, '') 'empId', 
					COALESCE((SELECT E.EmpName FROM tblemployee E WHERE E.EmpID =  S.EmpID limit 1), '') AS 'empName', 
					COALESCE(S.CustID, '') AS 'CustomerID',COALESCE((SELECT C.CustName FROM tblcustomer C WHERE C.CustID =  S.CustID limit 1), '') AS 'CustomerName',
					CAST(COALESCE(S.TotalAmt, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.PostStatus AS 'Status', S.ApproveStatus approvedStatus 
					FROM tblsaleorder S 
					where PostStatus = 'Open' AND S.SalReference Like CONCAT('%', var_key, '%')
					ORDER BY S.SalReference DESC

					LIMIT var_row  OFFSET var_off;
					
				ELSE

					SELECT COUNT(SalID) INTO var_rows 
					FROM tblsaleorder s 
					where s.PostStatus = 'Open' AND s.EmpID = (SELECT tbluseremployee.EmpID 
					from tbluseremployee 
					where tbluseremployee.UID = var_userId) AND s.SalReference Like CONCAT('%', var_key, '%');

					SELECT COALESCE(S.SalID,'') AS 'EntryNo', COALESCE(SalReference,'') AS 'Reference', COALESCE(DATE(S.SalDate), '') AS 'SalesOrderDate', COALESCE(S.EmpID, '') 'empId', 
					COALESCE((SELECT E.EmpName FROM tblemployee E WHERE E.EmpID =  S.EmpID limit 1),'') AS 'empName', 
					COALESCE(S.CustID, '') AS 'CustomerID',COALESCE((SELECT C.CustName FROM tblcustomer C WHERE C.CustID =  S.CustID limit 1), '') AS 'CustomerName',
					CAST(COALESCE(S.TotalAmt, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.PostStatus AS 'Status', S.ApproveStatus approvedStatus 
					FROM tblsaleorder S 
					where PostStatus = 'Open' AND S.EmpID = (SELECT tbluseremployee.EmpID 
					from tbluseremployee 
					where tbluseremployee.UID = var_userId) AND S.SalReference Like CONCAT('%', var_key, '%')
					ORDER BY S.SalReference DESC

					LIMIT var_row  OFFSET var_off;

				END IF;

			WHEN 'Employee' THEN

				IF typeId = '1' THEN

					SELECT COUNT(SalID) INTO var_rows 
					FROM tblsaleorder 
					where PostStatus = 'Open' AND EmpID Like CONCAT('%', var_key, '%');

					SELECT COALESCE(S.SalID,'') AS 'EntryNo', COALESCE(SalReference,'') AS 'Reference', COALESCE(DATE(S.SalDate), '') AS 'SalesOrderDate', COALESCE(S.EmpID, '') 'empId', 
					COALESCE((SELECT E.EmpName FROM tblemployee E WHERE E.EmpID =  S.EmpID limit 1), '') AS 'empName', 
					COALESCE(S.CustID, '') AS 'CustomerID',COALESCE((SELECT C.CustName FROM tblcustomer C WHERE C.CustID =  S.CustID limit 1), '') AS 'CustomerName',
					CAST(COALESCE(S.TotalAmt, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.PostStatus AS 'Status', S.ApproveStatus approvedStatus 
					FROM tblsaleorder S 
					where PostStatus = 'Open' AND S.EmpID Like CONCAT('%', var_key, '%')
					ORDER BY S.EmpID DESC

					LIMIT var_row  OFFSET var_off;
					
				ELSE

					SELECT COUNT(SalID) INTO var_rows 
					FROM tblsaleorder s 
					where s.PostStatus = 'Open' AND s.EmpID = (SELECT tbluseremployee.EmpID 
					from tbluseremployee 
					where tbluseremployee.UID = var_userId) AND s.EmpID Like CONCAT('%', var_key, '%');

					SELECT COALESCE(S.SalID,'') AS 'EntryNo', COALESCE(SalReference,'') AS 'Reference', COALESCE(DATE(S.SalDate), '') AS 'SalesOrderDate', COALESCE(S.EmpID, '') 'empId', 
					COALESCE((SELECT E.EmpName FROM tblemployee E WHERE E.EmpID =  S.EmpID limit 1),'') AS 'empName', 
					COALESCE(S.CustID, '') AS 'CustomerID',COALESCE((SELECT C.CustName FROM tblcustomer C WHERE C.CustID =  S.CustID limit 1), '') AS 'CustomerName',
					CAST(COALESCE(S.TotalAmt, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.PostStatus AS 'Status', S.ApproveStatus approvedStatus 
					FROM tblsaleorder S 
					where PostStatus = 'Open' AND S.EmpID = (SELECT tbluseremployee.EmpID 
					from tbluseremployee 
					where tbluseremployee.UID = var_userId) AND S.EmpID Like CONCAT('%', var_key, '%')
					ORDER BY S.EmpID DESC

					LIMIT var_row  OFFSET var_off;

				END IF;

	 END CASE;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_plan_survey`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_plan_survey`(in var_row int, in var_page int, in var_key varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);
	SELECT COUNT(MS_ID) INTO var_rows FROM crm_market_survey 
	WHERE MS_ID LIKE CONCAT('%', var_key, '%') 
				OR MS_Subject LIKE CONCAT('%', var_key, '%')
				OR MS_StartDate LIKE CONCAT('%', var_key, '%')
				OR MS_EndDate LIKE CONCAT('%', var_key, '%')
				AND  MS_Status = 'InProgress';
	
	SELECT COALESCE(MS_ID, '') 'id', COALESCE(MS_Subject, '') 'subject', COALESCE(MS_StartDate, '') 'startDate', COALESCE(MS_EndDate, '') 'endDate'
	FROM crm_market_survey
	WHERE MS_Status = 'InProgress'
				AND MS_ID LIKE CONCAT('%', var_key, '%') 
				OR MS_Subject LIKE CONCAT('%', var_key, '%')
				OR MS_StartDate LIKE CONCAT('%', var_key, '%')
				OR MS_EndDate LIKE CONCAT('%', var_key, '%')
				
	ORDER BY MS_ID 
				OR MS_Subject 
				OR MS_StartDate
				OR MS_EndDate

	LIMIT var_row  OFFSET var_off;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_price_code`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_price_code`(in var_row int, in var_page int, in var_key varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);
	SELECT COUNT(PriceCode) INTO var_rows FROM tblpricecode WHERE PriceCode LIKE CONCAT('%', var_key, '%') OR Description LIKE CONCAT('%', var_key, '%'); 
	

	SELECT COALESCE(PriceCode, '') 'priceCode', COALESCE(Description, '') 'des' 
	FROM tblpricecode
	WHERE PriceCode LIKE CONCAT('%', var_key, '%') OR Description LIKE CONCAT('%', var_key, '%')
	ORDER BY PriceCode
	LIMIT var_row  OFFSET var_off;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_product_item`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_product_item`(in var_user_id varchar(255), in var_key varchar(255), in var_num int, in var_page int)
    DETERMINISTIC
BEGIN

	DECLARE var_rt varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SET var_off = ((var_page-1)*var_num);

	SELECT COUNT(ItemID) INTO var_rows 
	FROM tblitem 
	WHERE Inactive = 0 and ItemID <> '' AND ItemID is not NULL 
	AND ItemID LIKE CONCAT('%', var_key, '%') 
	OR  ItemName LIKE CONCAT('%', var_key, '%') 
	OR  itemcode LIKE CONCAT('%', var_key, '%')
	OR  itembarcode LIKE CONCAT('%', var_key, '%');
	
	SELECT COALESCE(ItemID,'') 'id', COALESCE(ItemName,'') 'name', COALESCE(itemcode,'') 'code', COALESCE(itembarcode, '') 'barcode' , COALESCE(ImagePath , '') 'image' 
	FROM tblitem 
	WHERE Inactive = 0 and ItemID <> '' AND ItemID is not NULL AND tblitem.`status` = 'Inventory Part' AND ShowOnPos = 1
	AND ItemID LIKE CONCAT('%', var_key, '%') 
	OR  ItemName LIKE CONCAT('%', var_key, '%') 
	OR  itemcode LIKE CONCAT('%', var_key, '%')
	OR  itembarcode LIKE CONCAT('%', var_key, '%')
	ORDER BY ItemID
	LIMIT var_num  OFFSET var_off;
	
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_product_item_barcode`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_product_item_barcode`(IN `var_pc` varchar(255),IN `var_search` varchar(255), in `var_cust_id` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_price_override VARCHAR(255) DEFAULT '';
	DECLARE var_item_id VARCHAR(255) DEFAULT '';
	DECLARE var_item_name VARCHAR(255) DEFAULT '';
	DECLARE var_item_img VARCHAR(255) DEFAULT '';
	DECLARE var_rp VARCHAR(255) DEFAULT COALESCE((SELECT PriceCode FROM tblpricecode WHERE ReportPrice = 1 LIMIT 1),'');
	SELECT COALESCE(ItemID,''),COALESCE(ItemName,''),COALESCE(ImagePath,'') INTO var_item_id, var_item_name,var_item_img FROM tblitem WHERE itembarcode = var_search AND tblitem.`status` = 'Inventory Part' AND tblitem.ShowOnPos = 1 LIMIT 1;
	-- check Latest Selling Price
	IF var_pc = 'Latest Selling Price' THEN
		IF var_rp = '' THEN
			SELECT iu.ItemID 'itemId',var_item_name 'itemName',var_item_img 'image', iu.UomID 'uomId', COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName', COALESCE(iu.DefSal,0) 'defSal', crm_sale_order_item_change_latest_price(var_item_id,iu.UomID,var_cust_id) 'up', 0 'rp', COALESCE((SELECT COALESCE(IPD.DiscountPercent,0) FROM tblitempromotion IP LEFT JOIN tblitempromotiondetail IPD ON IP.PromotionID = IPD.PromotionID WHERE IPD.ItemID = var_item_id AND IPD.UomID = iu.UomID AND IP.`Status` = 0 AND DATE(IP.DateExpire) >= DATE(NOW()) ORDER BY IP.DateExpire DESC LIMIT 1),0) 'itemDiscount'
			FROM tblitemuom iu
			LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
			WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
		ELSE
				SELECT iu.ItemID 'itemId',var_item_name 'itemName',var_item_img 'image',iu.UomID 'uomId',  COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName',  COALESCE(iu.DefSal,0) 'defSal', crm_sale_order_item_change_latest_price(var_item_id,iu.UomID,var_cust_id) 'up', COALESCE((SELECT PriceAmount FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_rp AND UomID = iu.UomID LIMIT 1),0) 'rp', COALESCE((SELECT COALESCE(IPD.DiscountPercent,0) FROM tblitempromotion IP LEFT JOIN tblitempromotiondetail IPD ON IP.PromotionID = IPD.PromotionID WHERE IPD.ItemID = var_item_id AND IPD.UomID = iu.UomID AND IP.`Status` = 0 AND DATE(IP.DateExpire) >= DATE(NOW()) ORDER BY IP.DateExpire DESC LIMIT 1),0) 'itemDiscount'
				FROM tblitemuom iu
				LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
				WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
		END IF;	

	ELSE
		-- check report price
		IF var_rp = '' THEN
			SET var_price_override = COALESCE((SELECT PriceAmount FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc AND OverridePrice = 1),'');
			-- check override price
			IF var_price_override = '' THEN
				SELECT iu.ItemID 'itemId',var_item_name 'itemName',var_item_img 'image',iu.UomID 'uomId',  COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName',  COALESCE(iu.DefSal,0) 'defSal', COALESCE(ip.PriceAmount,0) 'up', 0 'rp', COALESCE((SELECT COALESCE(IPD.DiscountPercent,0) FROM tblitempromotion IP LEFT JOIN tblitempromotiondetail IPD ON IP.PromotionID = IPD.PromotionID WHERE IPD.ItemID = var_item_id AND IPD.UomID = iu.UomID AND IP.`Status` = 0 AND DATE(IP.DateExpire) >= DATE(NOW()) ORDER BY IP.DateExpire DESC LIMIT 1),0) 'itemDiscount'
				FROM tblitemuom iu
				LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
				WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
			ELSE
				SELECT iu.ItemID 'itemId',var_item_name 'itemName',var_item_img 'image',iu.UomID 'uomId',  COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName',  COALESCE(iu.DefSal,0) 'defSal', var_price_override 'up', 0 'rp', 0 'itemDiscount'
				FROM tblitemuom iu
				LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
				WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
			END IF;
		ELSE
			SET var_price_override = COALESCE((SELECT PriceAmount FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc AND OverridePrice = 1),'');
			-- check override price
			IF var_price_override = '' THEN
				SELECT iu.ItemID 'itemId',var_item_name 'itemName',var_item_img 'image',iu.UomID 'uomId',  COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName',  COALESCE(iu.DefSal,0) 'defSal', COALESCE(ip.PriceAmount,0) 'up', COALESCE((SELECT PriceAmount FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_rp AND UomID = iu.UomID LIMIT 1),0) 'rp', COALESCE((SELECT COALESCE(IPD.DiscountPercent,0) FROM tblitempromotion IP LEFT JOIN tblitempromotiondetail IPD ON IP.PromotionID = IPD.PromotionID WHERE IPD.ItemID = var_item_id AND IPD.UomID = iu.UomID AND IP.`Status` = 0 AND DATE(IP.DateExpire) >= DATE(NOW()) ORDER BY IP.DateExpire DESC LIMIT 1),0) 'itemDiscount'
				FROM tblitemuom iu
				LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
				WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
			ELSE
				SELECT iu.ItemID 'itemId',var_item_name 'itemName',var_item_img 'image',iu.UomID 'uomId',  COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName',  COALESCE(iu.DefSal,0) 'defSal', var_price_override 'up', COALESCE((SELECT PriceAmount FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_rp AND UomID = iu.UomID LIMIT 1),0) 'rp', COALESCE((SELECT COALESCE(IPD.DiscountPercent,0) FROM tblitempromotion IP LEFT JOIN tblitempromotiondetail IPD ON IP.PromotionID = IPD.PromotionID WHERE IPD.ItemID = var_item_id AND IPD.UomID = iu.UomID AND IP.`Status` = 0 AND DATE(IP.DateExpire) >= DATE(NOW()) ORDER BY IP.DateExpire DESC LIMIT 1),0) 'itemDiscount'
				FROM tblitemuom iu
				LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
				WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
			END IF;
		END IF;		
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_request_by`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_request_by`(in var_row int, in var_page int, in var_user_id varchar(255), in var_key varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rt varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_user_id LIMIT 1)), 0);	
	SET var_off = ((var_page -1 ) * var_row);

	IF var_rt = '1' THEN
			SELECT COUNT(EmpID) INTO var_rows FROM tblemployee WHERE Inactive = 0 AND EmpID LIKE CONCAT('%' , var_key, '%')  OR EmpName LIKE CONCAT('%' , var_key, '%');
			SELECT COALESCE(EmpID, '') 'EmpID', COALESCE(EmpName, '') 'EmpName' 
			FROM tblemployee 
			WHERE Inactive = 0 AND EmpID LIKE CONCAT('%' , var_key, '%')  OR EmpName LIKE CONCAT('%' , var_key, '%')
			ORDER BY EmpID
			LIMIT var_row  OFFSET var_off;
	ELSE
			SET var_user_id = COALESCE((SELECT EmpID FROM tbluseremployee WHERE UID = var_user_id), '');
			SELECT COUNT(EmpID) INTO var_rows FROM tblemployee WHERE Inactive = 0 AND EmpID = var_user_id;
			SELECT COALESCE(EmpID, '') 'EmpID', COALESCE(EmpName, '') 'EmpName' 
			FROM tblemployee 
			WHERE Inactive = 0 AND EmpID = var_user_id
			ORDER BY EmpID
			LIMIT var_row  OFFSET var_off;
	END IF;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_tem_barcode`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_tem_barcode`(in var_user_id varchar(255), in var_key varchar(255), in var_row int, in var_page int)
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);

	SELECT COUNT(ItemID) INTO var_rows FROM tblitem 
	WHERE Inactive = 0 AND ShowOnPos = 1
										 AND  itembarcode LIKE CONCAT('%', var_key, '%');
	
	SELECT COALESCE(ItemID,'') 'id', COALESCE(ItemName,'') 'name', COALESCE(itemcode,'') 'code', COALESCE(itembarcode, '') 'barcode' , COALESCE(UomID, '') 'uom', COALESCE(ImagePath , '') 'image'
	FROM tblitem 
	WHERE Inactive = 0 AND ShowOnPos = 1						
									   AND  itembarcode LIKE CONCAT('%', var_key, '%')
	ORDER BY ItemID
	LIMIT var_row  OFFSET var_off;
	
	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_type`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_type`(in var_row int, in var_page int, in var_key varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);
	SELECT COUNT(AT_ID) INTO var_rows FROM crm_account_type WHERE AT_ID LIKE CONCAT('%', var_key, '%') OR AT_Name LIKE CONCAT('%', var_key, '%'); 
	

	SELECT COALESCE(AT_ID, '') 'accountID', COALESCE(AT_Name, '') 'accountName' 
	FROM crm_account_type
	WHERE AT_ID LIKE CONCAT('%', var_key, '%') OR AT_Name LIKE CONCAT('%', var_key, '%')
	ORDER BY AT_ID
	LIMIT var_row  OFFSET var_off;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_search_visit_customer_inschedule`;
DELIMITER |
CREATE PROCEDURE `crm_mb_search_visit_customer_inschedule`(in var_row int, in var_page int, in var_userId varchar(255), in var_type varchar(255), in var_key varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE var_empId varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_roleType INT;
	DECLARE var_off INT;

	SET var_roleType = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_userId LIMIT 1)), 0);
	SET var_off = ((var_page - 1) * var_row);

	IF var_roleType = 1 THEN
		
		IF var_type = 'id' THEN

			SELECT count(VI_ID) INTO var_rows FROM crm_schedule_detail 
			WHERE SC_Customer Like CONCAT('%', var_key, '%') 
			ORDER BY SC_Customer ASC ;

			SELECT sd.VI_ID 'visitId', c.CustID 'custID', c.CustName 'custName', COALESCE(c.TermCreditLimit, 0) 'credit', COALESCE(c.TermNetDueIn, 0) 'due',
						 COALESCE(c.CustTel1, '') 'custTel1', COALESCE(c.CustTel2, '') 'custTel2', COALESCE(c.PriceCode, '') 'priceCode', COALESCE(sd.SC_startDate, '') 'date',
						  COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
			FROM crm_schedule_detail sd 
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustID Like CONCAT('%', var_key, '%')
			ORDER BY c.CustID ASC

			LIMIT var_row  OFFSET var_off;

		ELSEIF var_type = 'name' THEN

			SELECT count(sd.VI_ID) INTO var_rows FROM crm_schedule_detail sd
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustName Like CONCAT('%', var_key, '%') 
			ORDER BY c.CustID ASC;

			SELECT sd.VI_ID 'visitId', c.CustID 'custID', c.CustName 'custName', COALESCE(c.TermCreditLimit, 0) 'credit', COALESCE(c.TermNetDueIn,0) 'due',
						 COALESCE(c.CustTel1, '') 'custTel1', COALESCE(c.CustTel2, '') 'custTel2', COALESCE(c.PriceCode, '') 'priceCode', COALESCE(sd.SC_startDate, '') 'date',
						  COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
			FROM crm_schedule_detail sd 
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustName Like CONCAT('%', var_key, '%') 
			ORDER BY c.CustID ASC

			LIMIT var_row  OFFSET var_off;

		ELSEIF var_type = 'contact' THEN

			SELECT count(sd.VI_ID) INTO var_rows FROM crm_schedule_detail sd
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustTel1 Like CONCAT('%', var_key, '%') OR CustTel2 LIKE CONCAT('%', var_key, '%') 
			ORDER BY c.CustID ASC;

			SELECT sd.VI_ID 'visitId', c.CustID 'custID', c.CustName 'custName', COALESCE(c.TermCreditLimit, 0) 'credit', COALESCE(c.TermNetDueIn,0) 'due',
						 COALESCE(c.CustTel1, '') 'custTel1', COALESCE(c.CustTel2, '') 'custTel2', COALESCE(c.PriceCode, '') 'priceCode', COALESCE(sd.SC_startDate, '') 'date',
						  COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
			FROM crm_schedule_detail sd 
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustTel1 Like CONCAT('%', var_key, '%') OR CustTel2 LIKE CONCAT('%', var_key, '%') 
			ORDER BY c.CustID ASC

			LIMIT var_row  OFFSET var_off;

		ELSEIF var_type = 'group' THEN

			SELECT count(sd.VI_ID) INTO var_rows FROM crm_schedule_detail sd
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustGroupID Like CONCAT('%', var_key, '%') 
			ORDER BY c.CustID ASC;

			SELECT sd.VI_ID 'visitId', c.CustID 'custID', c.CustName 'custName', COALESCE(c.TermCreditLimit, 0) 'credit', COALESCE(c.TermNetDueIn,0) 'due',
						 COALESCE(c.CustTel1, '') 'custTel1', COALESCE(c.CustTel2, '') 'custTel2', COALESCE(c.PriceCode, '') 'priceCode', COALESCE(sd.SC_startDate, '') 'date',
						  COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
			FROM crm_schedule_detail sd 
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustGroupID Like CONCAT('%', var_key, '%') 
			ORDER BY c.CustID ASC

			LIMIT var_row  OFFSET var_off;

		ELSEIF var_type = 'priceCode' THEN

			SELECT count(sd.VI_ID) INTO var_rows FROM crm_schedule_detail sd
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.PriceCode Like CONCAT('%', var_key, '%') 
			ORDER BY c.CustID ASC;

			SELECT sd.VI_ID 'visitId', c.CustID 'custID', c.CustName 'custName', COALESCE(c.TermCreditLimit, 0) 'credit', COALESCE(c.TermNetDueIn,0) 'due',
						 COALESCE(c.CustTel1, '') 'custTel1', COALESCE(c.CustTel2, '') 'custTel2', COALESCE(c.PriceCode, '') 'priceCode', COALESCE(sd.SC_startDate, '') 'date',
						  COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
			FROM crm_schedule_detail sd 
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.PriceCode Like CONCAT('%', var_key, '%') 
			ORDER BY c.CustID ASC

			LIMIT var_row  OFFSET var_off;

		END IF;

	ELSE

		IF var_type = 'id' THEN

			SELECT count(SD.VI_ID) INTO var_rows FROM crm_schedule_detail SD WHERE SD.SC_Employee = (SELECT EmpID FROM tbluseremployee WHERE UID = var_userId LIMIT 1) 
			AND SD.SC_Customer Like CONCAT('%', var_key, '%');

			SELECT sd.VI_ID 'visitId', c.CustID 'custID', c.CustName 'custName', COALESCE(c.TermCreditLimit, 0) 'credit', COALESCE(c.TermNetDueIn,0)'due',
						 COALESCE(c.CustTel1, '') 'custTel1', COALESCE(c.CustTel2, '') 'custTel2', COALESCE(c.PriceCode, '') 'priceCode', COALESCE(sd.SC_startDate, '') 'date',
						  COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
			FROM crm_schedule_detail sd 
		  INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustID IN (SELECT ec.CustID from tblemployeecustomer ec WHERE ec.EmpID = sd.SC_Employee) 
					  AND sd.SC_Employee = (SELECT EmpID FROM tbluseremployee WHERE UID = var_userId LIMIT 1)
						AND sd.SC_Customer Like CONCAT('%', var_key, '%')
			ORDER BY c.CustID ASC LIMIT var_row  OFFSET var_off;

		ELSEIF var_type = 'name' THEN

			SELECT count(SD.VI_ID) INTO var_rows FROM crm_schedule_detail SD 
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE SD.SC_Employee = (SELECT EmpID FROM tbluseremployee WHERE UID = var_userId LIMIT 1) 
			AND c.Inactive = 0 AND c.CustName Like CONCAT('%', var_key, '%');

			SELECT sd.VI_ID 'visitId', c.CustID 'custID', c.CustName 'custName', COALESCE(c.TermCreditLimit, 0) 'credit', COALESCE(c.TermNetDueIn,0)'due',
						 COALESCE(c.CustTel1, '') 'custTel1', COALESCE(c.CustTel2, '') 'custTel2', COALESCE(c.PriceCode, '') 'priceCode', COALESCE(sd.SC_startDate, '') 'date',
						  COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
			FROM crm_schedule_detail sd 
		  INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustID IN (SELECT ec.CustID from tblemployeecustomer ec WHERE ec.EmpID = sd.SC_Employee) 
					  AND sd.SC_Employee = (SELECT EmpID FROM tbluseremployee WHERE UID = var_userId LIMIT 1)
						AND c.CustName Like CONCAT('%', var_key, '%')

			ORDER BY c.CustID ASC LIMIT var_row  OFFSET var_off;

		ELSEIF var_type = 'contact' THEN

			SELECT count(SD.VI_ID) INTO var_rows FROM crm_schedule_detail SD 
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE SD.SC_Employee = (SELECT EmpID FROM tbluseremployee WHERE UID = var_userId LIMIT 1)
			AND c.Inactive = 0 AND c.CustTel1 Like CONCAT('%', var_key, '%') OR CustTel2 LIKE CONCAT('%', var_key, '%')
			ORDER BY c.CustID ASC;

			SELECT sd.VI_ID 'visitId', c.CustID 'custID', c.CustName 'custName', COALESCE(c.TermCreditLimit, 0) 'credit', COALESCE(c.TermNetDueIn,0) 'due',
						 COALESCE(c.CustTel1, '') 'custTel1', COALESCE(c.CustTel2, '') 'custTel2', COALESCE(c.PriceCode, '') 'priceCode', COALESCE(sd.SC_startDate, '') 'date',
						  COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
			FROM crm_schedule_detail sd 
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustID IN (SELECT ec.CustID from tblemployeecustomer ec WHERE ec.EmpID = sd.SC_Employee) 
					  AND sd.SC_Employee = (SELECT EmpID FROM tbluseremployee WHERE UID = var_userId LIMIT 1)
						AND c.Inactive = 0 AND c.CustTel1 Like CONCAT('%', var_key, '%') OR CustTel2 LIKE CONCAT('%', var_key, '%')
			ORDER BY c.CustID ASC

			LIMIT var_row  OFFSET var_off;

		ELSEIF var_type = 'group' THEN

			SELECT count(SD.VI_ID) INTO var_rows FROM crm_schedule_detail SD 
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE SD.SC_Employee = (SELECT EmpID FROM tbluseremployee WHERE UID = var_userId LIMIT 1)
			AND c.Inactive = 0 AND c.CustGroupID Like CONCAT('%', var_key, '%') 
			ORDER BY c.CustID ASC;

			SELECT sd.VI_ID 'visitId', c.CustID 'custID', c.CustName 'custName', COALESCE(c.TermCreditLimit, 0) 'credit', COALESCE(c.TermNetDueIn,0) 'due',
						 COALESCE(c.CustTel1, '') 'custTel1', COALESCE(c.CustTel2, '') 'custTel2', COALESCE(c.PriceCode, '') 'priceCode', COALESCE(sd.SC_startDate, '') 'date',
						  COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
			FROM crm_schedule_detail sd 
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustID IN (SELECT ec.CustID from tblemployeecustomer ec WHERE ec.EmpID = sd.SC_Employee) 
					  AND sd.SC_Employee = (SELECT EmpID FROM tbluseremployee WHERE UID = var_userId LIMIT 1)
						AND c.Inactive = 0 AND c.CustGroupID Like CONCAT('%', var_key, '%')
			ORDER BY c.CustID ASC

			LIMIT var_row  OFFSET var_off;

		ELSEIF var_type = 'priceCode' THEN

			SELECT count(sd.VI_ID) INTO var_rows FROM crm_schedule_detail sd
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE SD.SC_Employee = (SELECT EmpID FROM tbluseremployee WHERE UID = var_userId LIMIT 1)
			AND c.Inactive = 0 AND c.PriceCode Like CONCAT('%', var_key, '%') 
			ORDER BY c.CustID ASC;

			SELECT sd.VI_ID 'visitId', c.CustID 'custID', c.CustName 'custName', COALESCE(c.TermCreditLimit, 0) 'credit', COALESCE(c.TermNetDueIn,0) 'due',
						 COALESCE(c.CustTel1, '') 'custTel1', COALESCE(c.CustTel2, '') 'custTel2', COALESCE(c.PriceCode, '') 'priceCode', COALESCE(sd.SC_startDate, '') 'date',
						  COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
			FROM crm_schedule_detail sd 
			INNER JOIN tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0 AND c.CustID IN (SELECT ec.CustID from tblemployeecustomer ec WHERE ec.EmpID = sd.SC_Employee) 
					  AND sd.SC_Employee = (SELECT EmpID FROM tbluseremployee WHERE UID = var_userId LIMIT 1)
						AND c.Inactive = 0 AND c.PriceCode Like CONCAT('%', var_key, '%') 
			ORDER BY c.CustID ASC

			LIMIT var_row  OFFSET var_off;

		END IF;

	END IF;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_select_customer_group`;
DELIMITER |
CREATE PROCEDURE `crm_mb_select_customer_group`(in var_row int, in var_page int)
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);
	SELECT COUNT(CustGroupID) INTO var_rows FROM tblcustomergroup; 
	

	SELECT COALESCE(CustGroupID, '') 'custGroupId', COALESCE(CustGroupName, '') 'custGroupName' 
	FROM tblcustomergroup
	ORDER BY CustGroupID
	LIMIT var_row  OFFSET var_off;

	SELECT CEIL(COALESCE(var_rows,0)/var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_select_cus_address`;
DELIMITER |
CREATE PROCEDURE `crm_mb_select_cus_address`(in var_cusid varchar(255))
    DETERMINISTIC
BEGIN
	
	SELECT CustAddress FROM tblcustomer WHERE CustID LIKE CONCAT('%',var_cusid, '%');

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_select_feedback`;
DELIMITER |
CREATE PROCEDURE `crm_mb_select_feedback`(var_visit_id varchar(255))
    DETERMINISTIC
BEGIN
	
	SELECT VI_Feedback FROM crm_schedule_detail WHERE VI_ID = var_visit_id;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_select_industry`;
DELIMITER |
CREATE PROCEDURE `crm_mb_select_industry`(in var_row int, in var_page int)
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);
	SELECT COUNT(I_ID) INTO var_rows FROM crm_industry; 
	

	SELECT COALESCE(I_ID, '') 'industID', COALESCE(I_Name, '') 'industName' 
	FROM crm_industry
	ORDER BY I_ID
	LIMIT var_row  OFFSET var_off;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_select_items`;
DELIMITER |
CREATE PROCEDURE `crm_mb_select_items`(in var_row int, in var_page int, in var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);

	SELECT COUNT(ItemID) INTO var_rows FROM tblitem WHERE Inactive = 0 AND ShowOnPos = 1 ;

	SELECT COALESCE(ItemID,'') 'id', COALESCE(ItemName,'') 'name', COALESCE(itemcode,'') 'code', COALESCE(itembarcode, '') 'barcode' , COALESCE(UomID, '') 'uom', COALESCE(ImagePath , '') 'image' 
	FROM tblitem 
	WHERE Inactive = 0 AND ShowOnPos = 1
	ORDER BY ItemID
	LIMIT var_row  OFFSET var_off;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_select_plan_survey`;
DELIMITER |
CREATE PROCEDURE `crm_mb_select_plan_survey`(in var_row int, in var_page int)
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);
	SELECT COUNT(MS_ID) INTO var_rows FROM crm_market_survey WHERE MS_Status = 'InProgress'; 
	
	SELECT COALESCE(MS_ID, '') 'id', COALESCE(MS_Subject, '') 'subject', COALESCE(MS_StartDate, '') 'startDate', COALESCE(MS_EndDate, '') 'endDate'
	FROM crm_market_survey
	WHERE MS_Status = 'InProgress'
	ORDER BY MS_ID
	LIMIT var_row  OFFSET var_off;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_select_price_code`;
DELIMITER |
CREATE PROCEDURE `crm_mb_select_price_code`(in var_row int, in var_page int)
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);
	SELECT COUNT(PriceCode) INTO var_rows FROM tblpricecode; 
	

	SELECT COALESCE(PriceCode, '') 'priceCode', COALESCE(Description, '') 'des' 
	FROM tblpricecode
	ORDER BY PriceCode
	LIMIT var_row  OFFSET var_off;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_select_request_by`;
DELIMITER |
CREATE PROCEDURE `crm_mb_select_request_by`(in var_row int, in var_page int, in var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rt varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_user_id LIMIT 1)), 0);
	SET var_off = ((var_page -1 ) * var_row);
	IF var_rt = '1' THEN
			SELECT COUNT(EmpID) INTO var_rows FROM tblemployee WHERE Inactive = 0;
			SELECT COALESCE(EmpID, '') 'EmpID', COALESCE(EmpName, '') 'EmpName' 
			FROM tblemployee 
			WHERE Inactive = 0
			ORDER BY EmpID
			LIMIT var_row  OFFSET var_off;
	ELSE
			SET var_user_id = (SELECT EmpID FROM tbluseremployee WHERE UID=var_user_id LIMIT 1);
			SELECT COUNT(EmpID) INTO var_rows FROM tblemployee WHERE Inactive = 0 AND EmpID = var_user_id;
			SELECT COALESCE(EmpID, '') 'EmpID', COALESCE(EmpName, '') 'EmpName' 
			FROM tblemployee 
			WHERE Inactive = 0 AND EmpID = var_user_id
			ORDER BY EmpID
			LIMIT var_row  OFFSET var_off;
	END IF;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_select_type`;
DELIMITER |
CREATE PROCEDURE `crm_mb_select_type`(in var_row int, in var_page int)
    DETERMINISTIC
BEGIN
	
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);
	SELECT COUNT(AT_ID) INTO var_rows FROM crm_account_type; 
	

	SELECT COALESCE(AT_ID, '') 'accountID', COALESCE(AT_Name, '') 'accountName' 
	FROM crm_account_type
	ORDER BY AT_ID
	LIMIT var_row  OFFSET var_off;

	SELECT CEIL(COALESCE(var_rows, 0) / var_row) 'totalPage';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_select_uom_posm`;
DELIMITER |
CREATE PROCEDURE `crm_mb_select_uom_posm`(in var_item_id varchar(255))
    DETERMINISTIC
BEGIN

	SELECT COALESCE(UomID, '') 'uomId' FROM tblitemuom WHERE ItemID = var_item_id;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_visited_customer_search_adv`;
DELIMITER |
CREATE PROCEDURE `crm_mb_visited_customer_search_adv`(in var_num int, in var_page int, in var_user_id varchar(255), var_search varchar(255),var_fd varchar(255), var_td varchar(255), var_datefilter varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_empId varchar(255);
	DECLARE var_rt varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(var_user_id)),1);
	SET var_off = ((var_page-1)*var_num);
	IF var_rt = '1' THEN	
			IF var_datefilter = 'all' THEN
				SELECT count(VI_ID) INTO var_rows 
				FROM crm_schedule_detail sd
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status IN('Visited with order','Visited without order') AND IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')));
				SELECT sd.VI_ID 'visitId', c.var_id 'custID', c.var_name 'custName', COALESCE(c.tin_overcredit, 0) 'credit', COALESCE(c.tin_overduedate,0) 'due',
						   COALESCE(c.var_tel1, '') 'custTel1', COALESCE(c.var_tel2, '') 'custTel2', COALESCE(c.var_pricecode, '') 'priceCode', COALESCE(DATE_FORMAT(sd.SC_startDate, '%d-%b-%Y %r'), '') 'date',
						   COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
				FROM crm_schedule_detail sd 
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status IN('Visited with order','Visited without order') AND
				IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				ORDER BY SC_startDate ASC
				LIMIT var_num OFFSET var_off;
			ELSE
				SELECT count(VI_ID) INTO var_rows 
				FROM crm_schedule_detail sd
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status IN('Visited with order','Visited without order') AND DATE(sd.SC_startDate) BETWEEN var_fd AND var_td AND
				IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				;
				SELECT sd.VI_ID 'visitId', c.var_id 'custID', c.var_name 'custName', COALESCE(c.tin_overcredit, 0) 'credit', COALESCE(c.tin_overduedate,0) 'due',
						   COALESCE(c.var_tel1, '') 'custTel1', COALESCE(c.var_tel2, '') 'custTel2', COALESCE(c.var_pricecode, '') 'priceCode', COALESCE(DATE_FORMAT(sd.SC_startDate, '%d-%b-%Y %r'), '') 'date',
						   COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
				FROM crm_schedule_detail sd 
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE 
					c.tin_inactive = 0 AND 
					sd.VI_Status IN('Visited with order','Visited without order') AND 
					DATE(sd.SC_startDate) BETWEEN var_fd AND var_td AND
					IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				ORDER BY SC_startDate ASC
				LIMIT var_num OFFSET var_off;
			END IF;
	ELSE
			SET var_empId = CRM_FUN_GET_EMP_ID(var_user_id);
			IF var_datefilter = 'all' THEN
				SELECT count(VI_ID) INTO var_rows 
				FROM crm_schedule_detail sd
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status IN('Visited with order','Visited without order') AND IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')));
				SELECT sd.VI_ID 'visitId', c.var_id 'custID', c.var_name 'custName', COALESCE(c.tin_overcredit, 0) 'credit', COALESCE(c.tin_overduedate,0) 'due',
						   COALESCE(c.var_tel1, '') 'custTel1', COALESCE(c.var_tel2, '') 'custTel2', COALESCE(c.var_pricecode, '') 'priceCode', COALESCE(DATE_FORMAT(sd.SC_startDate, '%d-%b-%Y %r'), '') 'date',
						   COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
				FROM crm_schedule_detail sd 
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status IN('Visited with order','Visited without order') AND sd.SC_Employee = var_empId AND
				IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				ORDER BY SC_startDate ASC
				LIMIT var_num OFFSET var_off;
			ELSE
				SELECT count(VI_ID) INTO var_rows 
				FROM crm_schedule_detail sd
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status IN('Visited with order','Visited without order') AND DATE(sd.SC_startDate) BETWEEN var_fd AND var_td AND
				IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				;
				SELECT sd.VI_ID 'visitId', c.var_id 'custID', c.var_name 'custName', COALESCE(c.tin_overcredit, 0) 'credit', COALESCE(c.tin_overduedate,0) 'due',
						   COALESCE(c.var_tel1, '') 'custTel1', COALESCE(c.var_tel2, '') 'custTel2', COALESCE(c.var_pricecode, '') 'priceCode', COALESCE(DATE_FORMAT(sd.SC_startDate, '%d-%b-%Y %r'), '') 'date',
						   COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
				FROM crm_schedule_detail sd 
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE 
					c.tin_inactive = 0 AND sd.SC_Employee = var_empId AND
					sd.VI_Status IN('Visited with order','Visited without order') AND 
					DATE(sd.SC_startDate) BETWEEN var_fd AND var_td AND
					IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				ORDER BY SC_startDate ASC
				LIMIT var_num OFFSET var_off;
			END IF;
	END IF;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_visit_customer_list`;
DELIMITER |
CREATE PROCEDURE `crm_mb_visit_customer_list`(in var_num int, in var_page int,in var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_empId varchar(255);
	DECLARE var_rt varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(var_user_id)), 0);
	SET var_empId = CRM_FUN_GET_EMP_ID(var_user_id)	;
	SET var_off = ((var_page-1)*var_num);
	IF var_rt = '1' THEN
			SELECT COUNT(var_id) INTO var_rows FROM ame_mt_cus WHERE tin_inactive=0 ;
			SELECT var_id 'custID', COALESCE(var_name, '') 'custName', COALESCE(var_tel1, '') 'custTel1', COALESCE(var_tel2, '') 'custTel2'
			FROM ame_mt_cus 
			WHERE tin_inactive=0 
			ORDER BY var_id
			LIMIT var_num  OFFSET var_off;
	ELSE
			SELECT COUNT(var_id) INTO var_rows FROM ame_mt_cus WHERE tin_inactive=0 ;
			SELECT var_id 'custID', COALESCE(var_name, '') 'custName', COALESCE(var_tel1, '') 'custTel1', COALESCE(var_tel2, '') 'custTel2'
			FROM ame_mt_cus 
			WHERE tin_inactive=0  AND var_id IN(SELECT emp.ar_cusid FROM ame_mt_cus_emp emp WHERE emp.var_empid = var_empId)
			ORDER BY var_id
			LIMIT var_num  OFFSET var_off;
	END IF;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_visit_customer_search`;
DELIMITER |
CREATE PROCEDURE `crm_mb_visit_customer_search`(in var_num int, in var_page int, in var_user_id varchar(255), var_key varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_empId varchar(255);
	DECLARE var_rt varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_user_id LIMIT 1)), 0);
	SET var_empId = COALESCE((SELECT EmpID FROM tbluseremployee WHERE UID = var_user_id),'');
	SET var_off = ((var_page-1)*var_num);
	IF var_rt = '1' THEN
			SELECT COUNT(CustID) INTO var_rows FROM tblcustomer WHERE Inactive=0 AND (CustID LIKE CONCAT('%', var_key, '%') OR  CustName LIKE CONCAT('%', var_key, '%') OR  CustTel1 LIKE CONCAT('%', var_key, '%') OR CustTel2 LIKE CONCAT('%', var_key, '%'));
			SELECT CustID 'custID', COALESCE(CustName, '') 'custName', COALESCE(CustTel1, '') 'custTel1', COALESCE(CustTel2, '') 'custTel2'
			FROM tblcustomer 
			WHERE Inactive=0 AND (CustID LIKE CONCAT('%', var_key, '%') OR  CustName LIKE CONCAT('%', var_key, '%') OR  CustTel1 LIKE CONCAT('%', var_key, '%') OR CustTel2 LIKE CONCAT('%', var_key, '%')) 
			ORDER BY CustID
			LIMIT var_num  OFFSET var_off;
	ELSE
			SELECT COUNT(CustID) INTO var_rows FROM tblcustomer WHERE Inactive=0 AND CustID in(SELECT custid FROM tblemployeecustomer WHERE empid = var_empId) AND (CustID LIKE CONCAT('%', var_key, '%') OR  CustName LIKE CONCAT('%', var_key, '%') OR  CustTel1 LIKE CONCAT('%', var_key, '%') OR CustTel2 LIKE CONCAT('%', var_key, '%'));
			SELECT CustID 'custID', COALESCE(CustName, '') 'custName', COALESCE(CustTel1, '') 'custTel1', COALESCE(CustTel2, '') 'custTel2'
			FROM tblcustomer 
			WHERE Inactive=0 AND CustID IN(SELECT custid FROM tblemployeecustomer WHERE empid = var_empId) AND (CustID LIKE CONCAT('%', var_key, '%') OR  CustName LIKE CONCAT('%', var_key, '%') OR  CustTel1 LIKE CONCAT('%', var_key, '%') OR CustTel2 LIKE CONCAT('%', var_key, '%'))
			ORDER BY CustID
			LIMIT var_num  OFFSET var_off;
	END IF;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_visit_customer_search_adv`;
DELIMITER |
CREATE PROCEDURE `crm_mb_visit_customer_search_adv`(in var_num int, in var_page int, in var_user_id varchar(255), var_search varchar(255),var_fd varchar(255), var_td varchar(255), var_datefilter varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_empId varchar(255);
	DECLARE var_rt varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(var_user_id)),1);
	SET var_off = ((var_page-1)*var_num);
	IF var_rt = '1' THEN	
			IF var_datefilter = 'all' THEN
				SELECT count(VI_ID) INTO var_rows 
				FROM crm_schedule_detail sd
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status = 'Pending' AND IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')));
				SELECT sd.VI_ID 'visitId', c.var_id 'custID', c.var_name 'custName', COALESCE(c.tin_overcredit, 0) 'credit', COALESCE(c.tin_overduedate,0) 'due',
						   COALESCE(c.var_tel1, '') 'custTel1', COALESCE(c.var_tel2, '') 'custTel2', COALESCE(c.var_pricecode, '') 'priceCode', COALESCE(DATE_FORMAT(sd.SC_startDate, '%d-%b-%Y %r'), '') 'date',
						   COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
				FROM crm_schedule_detail sd 
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status = 'Pending' AND
				IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				ORDER BY SC_startDate ASC
				LIMIT var_num OFFSET var_off;
			ELSE
				SELECT count(VI_ID) INTO var_rows 
				FROM crm_schedule_detail sd
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status = 'Pending' AND DATE(sd.SC_startDate) BETWEEN var_fd AND var_td AND
				IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				;
				SELECT sd.VI_ID 'visitId', c.var_id 'custID', c.var_name 'custName', COALESCE(c.tin_overcredit, 0) 'credit', COALESCE(c.tin_overduedate,0) 'due',
						   COALESCE(c.var_tel1, '') 'custTel1', COALESCE(c.var_tel2, '') 'custTel2', COALESCE(c.var_pricecode, '') 'priceCode', COALESCE(DATE_FORMAT(sd.SC_startDate, '%d-%b-%Y %r'), '') 'date',
						   COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
				FROM crm_schedule_detail sd 
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE 
					c.tin_inactive = 0 AND 
					sd.VI_Status = 'Pending' AND 
					DATE(sd.SC_startDate) BETWEEN var_fd AND var_td AND
					IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				ORDER BY SC_startDate ASC
				LIMIT var_num OFFSET var_off;
			END IF;
	ELSE
			SET var_empId = CRM_FUN_GET_EMP_ID(var_user_id);
			IF var_datefilter = 'all' THEN
				SELECT count(VI_ID) INTO var_rows 
				FROM crm_schedule_detail sd
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status = 'Pending' AND IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')));
				SELECT sd.VI_ID 'visitId', c.var_id 'custID', c.var_name 'custName', COALESCE(c.tin_overcredit, 0) 'credit', COALESCE(c.tin_overduedate,0) 'due',
						   COALESCE(c.var_tel1, '') 'custTel1', COALESCE(c.var_tel2, '') 'custTel2', COALESCE(c.var_pricecode, '') 'priceCode', COALESCE(DATE_FORMAT(sd.SC_startDate, '%d-%b-%Y %r'), '') 'date',
						   COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
				FROM crm_schedule_detail sd 
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status = 'Pending' AND sd.SC_Employee = var_empId AND
				IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				ORDER BY SC_startDate ASC
				LIMIT var_num OFFSET var_off;
			ELSE
				SELECT count(VI_ID) INTO var_rows 
				FROM crm_schedule_detail sd
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE c.tin_inactive = 0 AND sd.VI_Status = 'Pending' AND DATE(sd.SC_startDate) BETWEEN var_fd AND var_td AND
				IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				;
				SELECT sd.VI_ID 'visitId', c.var_id 'custID', c.var_name 'custName', COALESCE(c.tin_overcredit, 0) 'credit', COALESCE(c.tin_overduedate,0) 'due',
						   COALESCE(c.var_tel1, '') 'custTel1', COALESCE(c.var_tel2, '') 'custTel2', COALESCE(c.var_pricecode, '') 'priceCode', COALESCE(DATE_FORMAT(sd.SC_startDate, '%d-%b-%Y %r'), '') 'date',
						   COALESCE(sd.SC_Duration, '') 'duration',  COALESCE(sd.VI_Status, '') 'status'
				FROM crm_schedule_detail sd 
				INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id 
				WHERE 
					c.tin_inactive = 0 AND sd.SC_Employee = var_empId AND
					sd.VI_Status = 'Pending' AND 
					DATE(sd.SC_startDate) BETWEEN var_fd AND var_td AND
					IF(var_search = 'all',TRUE, (c.var_id = var_search OR c.var_name LIKE CONCAT('%',var_search,'%')))
				ORDER BY SC_startDate ASC
				LIMIT var_num OFFSET var_off;
			END IF;
	END IF;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_visit_delete_all`;
DELIMITER |
CREATE PROCEDURE `crm_mb_visit_delete_all`(var_vid varchar(255), var_saleid varchar(255))
    DETERMINISTIC
BEGIN
	UPDATE tblmaterialrequest SET `Status` = 'Deleted' WHERE VI_ID = var_vid;
	UPDATE tblsaleorder SET PostStatus = 'Deleted' WHERE SalID = var_saleid;
	UPDATE crm_schedule_detail SET VI_Feedback = '', VI_StartTime = NULL, VI_StartLat = NULL,  VI_StartLong = NULL, VI_Status = 'Pending', VI_EndTime = NULL, VI_EndLong = NULL, VI_EndLat = NULL  WHERE VI_ID = var_vid;
	DELETE FROM crm_market_survey_customer WHERE VI_ID = var_vid;
	DELETE FROM crm_market_survey_comment WHERE VI_ID = var_vid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_message`;
DELIMITER |
CREATE PROCEDURE `crm_message`(IN SCode varchar(255),IN SID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT  Action,CONCAT(Msg,' ',SID, ' ', Description) AS 'alert' FROM crm_message WHERE `Code` = SCode;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_meterial_request_add`;
DELIMITER |
CREATE PROCEDURE `crm_meterial_request_add`(var_ref varchar(255), var_d varchar(255), var_rd varchar(255), var_status varchar(255),var_empid varchar(255), var_remark varchar(1000),var_cid varchar(255), var_viid varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_auto_id VARCHAR(255) DEFAULT fnGetLastID("IC-MTR");
	DECLARE authId VARCHAR(255) DEFAULT "";
	DECLARE authType VARCHAR(255) DEFAULT "";
	DECLARE re INTEGER DEFAULT 0;	

	INSERT INTO tblmaterialrequest(`EntryNo`, `Reference`, `EntryDate`, `RequiredDate`, `Status`, `RequestedBy`, `Remark`,`CustID`,`VI_ID`)
	VALUES (var_auto_id, var_ref, var_d, var_rd, var_status, var_empid, var_remark,var_cid, var_viid);
	
	SET re = (SELECT RE_IsRequire FROM crm_module_require_approval WHERE RE_Module = "Material Requistion" LIMIT 1);

	IF re = 1 THEN
		SELECT ae.Auth_ID 'Auth_ID', (SELECT Auth_Type FROM hrm_authorisation WHERE Auth_ID=ae.Auth_ID) 'Auth_Type' INTO authId, authType
		FROM hrm_authorisation_employee ae
		WHERE ae.Emp_ID = var_empid
		AND ae.Auth_Process = "Material Request"; 
		IF authType = "Individual" THEN
			UPDATE tblmaterialrequest SET `MRAuthID` = authId WHERE EntryNo = var_auto_id;
			CALL spHRMAddAuthorisationTemp(authId,var_auto_id);
			CALL spHRMAddIAuthorisationApproved(authId, var_auto_id, "Material Request");
		ELSE
			UPDATE tblmaterialrequest SET `MRAuthID` = authId WHERE EntryNo = var_auto_id;
			CALL spHRMAddAuthorisationTemp(authId,var_auto_id);
			CALL spHRMAddGAuthorisationApproved(authId, var_auto_id, "Material Request");
		END IF;
	ELSE
		UPDATE tblmaterialrequest SET `Status` = 'approved' WHERE `EntryNo` = var_auto_id;
	END IF;

	SELECT var_auto_id as 'MS_ID';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_meterial_request_cancel`;
DELIMITER |
CREATE PROCEDURE `crm_meterial_request_cancel`(var_entryid varchar(255))
    DETERMINISTIC
BEGIN
	UPDATE tblmaterialrequest SET `Status` = 'Cancelled' WHERE EntryNo = var_entryid ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_meterial_request_delete`;
DELIMITER |
CREATE PROCEDURE `crm_meterial_request_delete`(var_entryid varchar(255))
    DETERMINISTIC
BEGIN
	UPDATE tblmaterialrequest SET `Status` = 'Deleted' WHERE EntryNo = var_entryid ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_meterial_request_list_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_meterial_request_list_by_id`(var_vid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT m.EntryNo 'entryId', m.Reference 'reference', m.Remark 'remark', m.CustID 'custId',COALESCE((SELECT CustName FROM tblcustomer WHERE tblcustomer.CustID=m.CustID),'') 'custName', DATE_FORMAT(m.EntryDate, '%d-%c-%Y') 'requestDate', DATE_FORMAT(m.RequiredDate, '%d-%c-%Y') 'requiredDate',m.`Status` 'status', m.RequestedBy 'empId',
			COALESCE((SELECT EmpName FROM tblemployee e WHERE e.EmpId = m.RequestedBy),'') 'empName', COALESCE(m.edittable,0) 'editable',
			d.ItemID 'itemId', COALESCE((SELECT ItemName FROM tblitem i WHERE i.ItemID = d.ItemID),'') 'itemName',
			d.FromLocationID 'locationId',  COALESCE(d.UOMID, '') 'uomId', COALESCE(d.Qty,0) 'qty' ,COALESCE((SELECT l.Des FROM tbllocation l WHERE l.LocationID = d.FromLocationID),'') 'locationName'
	FROM tblmaterialrequest m 
	LEFT JOIN tblmaterialrequestdetail d 
	ON m.EntryNo = d.EntryNo
	WHERE m.EntryNo = var_vid
	ORDER BY d.LineNo
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_meterial_request_list_by_visit`;
DELIMITER |
CREATE PROCEDURE `crm_meterial_request_list_by_visit`(var_vid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT m.EntryNo 'entryId', m.Reference 'reference', m.Remark 'remark', DATE_FORMAT(m.EntryDate, '%d-%c-%Y') 'requestDate', DATE_FORMAT(m.RequiredDate, '%d-%c-%Y') 'requiredDate',m.`Status` 'status', m.RequestedBy 'empId',
			COALESCE((SELECT EmpName FROM tblemployee e WHERE e.EmpId = m.RequestedBy),'') 'empName', COALESCE(m.edittable,0) 'editable',
			d.ItemID 'itemId', COALESCE((SELECT ItemName FROM tblitem i WHERE i.ItemID = d.ItemID),'') 'itemName',
			d.FromLocationID 'locationId', COALESCE((SELECT l.Des FROM tbllocation l WHERE l.LocationID = d.FromLocationID),'') 'locationName', COALESCE(d.UOMID, '') 'uomId', COALESCE(d.Qty,0) 'qty'
	FROM tblmaterialrequest m
	LEFT JOIN tblmaterialrequestdetail d 
	ON m.EntryNo = d.EntryNo
	WHERE VI_ID = var_vid
	ORDER BY d.LineNo
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_meterial_request_update`;
DELIMITER |
CREATE PROCEDURE `crm_meterial_request_update`(var_ref varchar(255), var_d varchar(255), var_rd varchar(255), var_status varchar(255),var_empid varchar(255), var_remark varchar(1000),var_cid varchar(255), var_viid varchar(255), var_entryno varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM tblmaterialrequestdetail WHERE EntryNo = var_entryno ;
	UPDATE tblmaterialrequest
	SET
			`Reference`=var_ref, 
      `EntryDate`=var_d, 
      `RequiredDate`=var_rd, 
      `Status`='requested',  
      `RequestedBy`=var_empid, 
      `Remark`=var_remark,
			`CustID` = var_cid,
			`VI_ID` = var_viid
	WHERE (`EntryNo`=var_entryno);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_module_employee_list`;
DELIMITER |
CREATE PROCEDURE `crm_module_employee_list`()
    DETERMINISTIC
BEGIN
	SELECT empid 'empId', empname 'empName', empsex 'empSex', empposition 'position', z.ZoneID 'zoneId', COALESCE(ZoneName, '') 'zoneName', inactive 'inactive', e.emptel1 'tel1', e.emptel2 'tel2'
	FROM tblemployee e
	LEFT JOIN crm_sale_zone z on z.ZoneID = e.crm_zoneID
	WHERE EmpID IN(SELECT EmpID FROM tblemployeesystemrole WHERE RoleName = 'Sale Representative') 
	ORDER BY EmpID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_ms_list_items_by_competitor`;
DELIMITER |
CREATE PROCEDURE `crm_ms_list_items_by_competitor`(var_cid varchar(255))
    DETERMINISTIC
BEGIN	
	SELECT ItemID 'itemId', ItemName 'itemName', ItemCode 'itemCode', Description 'description', Price 'price'
	FROM crm_market_survey_competitor_item 
	WHERE COM_ID = var_cid
	ORDER BY ItemID DESC;	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_multiple_sql_statement`;
DELIMITER |
CREATE PROCEDURE `crm_multiple_sql_statement`(in `c` int(6), in `statement_sql` text, PUser varchar(255))
    DETERMINISTIC
BEGIN
DECLARE i INTEGER DEFAULT 1;
WHILE i <= c do
SET @SQL= fnSplit_Str(statement_sql,';',i);
SET @SQL = REPLACE(@SQl,'PaUSER',PUser);
PREPARE St FROM @SQL;
EXECUTE St;
DEALLOCATE PREPARE St;
SET i = i+1;
END WHILE;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_number_prefix_update`;
DELIMITER |
CREATE PROCEDURE `crm_number_prefix_update`()
    DETERMINISTIC
BEGIN
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'DB') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('DB', 'DB', 'Database', '5', '1', '0', '', '1');
	END IF;
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'DA') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('DA', 'DA', 'Delivery Address', '5', '1', '0', '', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SN') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SN', 'INV', 'Sale Invoice', NULL, '1', '1', '', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'AC') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('AC', 'AC', 'User Activity', '5', '1', '1', 'Activities', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'AC_EV') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('AC_EV', 'EV', 'Event', '5', '1', '1', 'Activities', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'AC_NO') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('AC_NO', 'NO', 'Note', '5', '1', '1', 'Activities', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'AC_TA') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('AC_TA', 'TA', 'Task', '5', '1', '1', 'Activities', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'AC_ME') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('AC_ME', 'ME', 'Meeting', '5', '1', '1', 'Activities', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'AC_CL') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('AC_CL', 'CL', 'Call', '5', '1', '1', 'Activities', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'LOC') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('LOC', 'LO', 'Location', '5', '1', '1', 'Activities', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SC') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SC', 'SC', 'Visit', '5', '1', '1', 'Activities', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'VI') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('VI', 'VI', 'Visit Customer', '5', '1', '1', 'Activities', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'COM_ITEM') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('COM_ITEM', 'CI', 'Competitor Item', '5', '1', '1', 'Activities', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'UM') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('UM', 'U', 'User Management', '5', '1', '1', 'Administrator', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'RM') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('RM', 'R', 'Role Management', '5', '1', '1', 'Administrator', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CAT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CAT', 'CAT', 'Categories Management', NULL, '1', '1', 'Administrator', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SET_M') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SET_M', 'SET-M', 'Setting Module', NULL, '1', '1', 'Administrator', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'AUTH_GROUP') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('AUTH_GROUP', 'AUTH_GROUP', 'Authorization Group', NULL, '1', '1', 'Administrator', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SET_AUTH') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SET_AUTH', 'SET_AUTH', 'Setup Authorization', NULL, '1', '1', 'Administrator', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'EMP_ASSIGN') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('EMP_ASSIGN', 'EMP_ASSIGN', 'Employee Assignment', NULL, '1', '1', 'Administrator', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'AUTH_APPROV') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('AUTH_APPROV', 'AuthApp', 'Authorization Approval', NULL, '1', '1', 'Administrator', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'MC') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('MC', 'MC', 'Mail Configuration', NULL, '1', '1', 'Administrator', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CRMCITY') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CRMCITY', 'CRMCITY', 'City Address', '2', '1', '1', 'City Address', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'INQ_SK') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('INQ_SK', 'INQ_SK', 'Stock On Hand', '11', '1', '1', 'Inquiry', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CA') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CA', 'CA', 'Campaign', '5', '1', '1', 'Marketing', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'LE') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('LE', 'LE', 'Lead', '5', '1', '1', 'Marketing', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'COM') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('COM', 'COM', 'Competitor', '5', '1', '1', 'Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'MS') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('MS', 'MS', 'Market Survey', '5', '1', '1', 'Marketing', '1');
	END IF; IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'LP') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('LP', 'PL', 'Project List', '5', '1', '1', 'Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'PO') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('PO', 'PO', 'PO Forecasting', '5', '1', '1', 'Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'ITEM') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('ITEM', 'I', 'Product', NULL, '1', '1', 'Products', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'Q') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('Q', 'Q', 'Quotation', NULL, '1', '1', 'Quotation', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'RCP') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('RCP', 'R', 'Receipt', NULL, '1', '1', 'Receipt', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CL-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CL-RPT', 'CL-RPT', 'Call Report', NULL, '1', '1', 'Report Activities', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'ME-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('ME-RPT', 'ME-RPT', 'Meeting Report', NULL, '1', '1', 'Report Activities', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'TA-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('TA-RPT', 'TA-RPT', 'Report Task', NULL, '1', '1', 'Report Activities', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'EV-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('EV-RPT', 'EV-RPT', 'Report Event', NULL, '1', '1', 'Report Activities', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'VI_RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('VI_RPT', 'VI_RPT', 'Report Visit', NULL, '1', '1', 'Report Activities', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CA_0001') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CA_0001', 'CA-RPT', 'Top Campaign', NULL, '1', '1', 'Report Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CA_0002') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CA_0002', 'CA-RPT', 'Lead by campaign', NULL, '1', '1', 'Report Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'LE_00001') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('LE_00001', 'LE_RPT', 'Exec Leads', NULL, '1', '1', 'Report Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'RPT-PL') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('RPT-PL', 'RPT-PL', 'Report Project List', NULL, '1', '1', 'Report Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CA-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CA-RPT', 'CA-RPT', 'Report Campaign', NULL, '1', '1', 'Report Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'LE-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('LE-RPT', 'LE-RPT', 'Report Lead', NULL, '1', '1', 'Report Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'RPT-PL001') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('RPT-PL001', 'RPT-PL001', 'Project List Detail', NULL, '1', '1', 'Report Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'RPT-PL002') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('RPT-PL002', 'RPT-PL002', 'Future Project List', NULL, '1', '1', 'Report Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'RPT-PL003') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('RPT-PL003', 'RPT-PL003', 'Project List Excel', NULL, '1', '1', 'Report Marketing', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'OP_00001') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('OP_00001', 'OP_RPT', 'Opportunity', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SO-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SO-RPT', 'SO-RPT', 'Sale Order Report', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'QO-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('QO-RPT', 'QO-RPT', 'Quotation Report', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CUST-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CUST-RPT', 'CUST-RPT', 'Customer Report', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CT-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CT-RPT', 'CT-RPT', 'Report Contact', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SN-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SN-RPT', 'SN-RPT', 'Sale Invoice Report', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SR-RPT') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SR-RPT', 'SR-RPT', 'Sale Return Report', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SI-0001') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SI-0001', 'SI-0001', 'Sales By Salesman', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SI-0003') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SI-0003', 'SI-0003', 'Sale by Month', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SI-0004') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SI-0004', 'SI-0004', 'Sale By Salesman By Weekly', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SI-0005') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SI-0005', 'SI-0005', 'Sale By Salesman By Month', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SI-0006') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SI-0006', 'SI-0006', 'Sale By Customer', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SI-0007') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SI-0007', 'SI-0007', 'Stock Check', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SI-0008') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SI-0008', 'SI-0008', 'Stock Customer', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SI-0009') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SI-0009', 'SI-0009', 'Sales By Employee By Invoice', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SI-0010') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SI-0010', 'SI-0010', 'Sales By Employee By Item', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SI-0011') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SI-0011', 'SI-0011', 'Sales By Customer By Employee', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SI-0012') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SI-0012', 'SI-0012', 'Sales By Item', NULL, '1', '1', 'Report Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CS_00001') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CS_00001', 'CS_RPT', 'Case & Solution', NULL, '1', '1', 'Report Support', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'R_BG') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('R_BG', 'R_BG', 'Budget Requisition', '5', '1', '1', 'Request', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'R_G') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('R_G', 'R_G', 'General Requisition', '5', '1', '1', 'Request', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'R_MA') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('R_MA', 'R_MA', 'Material Requisition', '11', '1', '1', 'Request', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'R_OD') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('R_OD', 'R_OD', 'Temporary Over Due Date', '11', '1', '1', 'Request', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'R_TC') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('R_TC', 'R_TC', 'Temporary Credit', '11', '1', '1', 'Request', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'MSD_VI') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('MSD_VI', 'MV', 'MSD Visit', '11', '1', '0', 'Sale', '1');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'POSM') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('POSM', 'P', 'Point Of Sale Material', '5', '1', '1', 'Sale', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'S') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('S', 'S', 'Sale Order', NULL, '1', '1', 'Sale Order', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'SR') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('SR', 'R', 'Sale Return', '5', '1', '1', 'Sale Return', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'OP') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('OP', 'OP', 'Opportunity', '5', '1', '1', 'Sales', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CO') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CO', 'CON', 'Contact', '5', '1', '1', 'Sales', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CUST') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CUST', 'C', 'Customer', '5', '1', '1', 'Sales', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CONF') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CONF', 'CO', 'Default Configuration', NULL, '1', '1', 'Setting', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'CS') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('CS', 'CS', 'Case and Solution', '5', '1', '1', 'Support', '0');
	END IF; 
	IF (SELECT COUNT(*) FROM crm_numberprefix WHERE ModuleID = 'ART') = 0 THEN
		INSERT INTO  `crm_numberprefix` (`moduleid`, `numberprefix`, `remarks`, `length`, `lastid`, `status`, `group`, `hide`) VALUES ('ART', 'ART', 'Article', '5', '1', '1', 'Support', '1');
	END IF; 
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_opp_product_load`;
DELIMITER |
CREATE PROCEDURE `crm_opp_product_load`(var_oppid varchar(15))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(SysCode,'') 'systemCode', COALESCE(LocationID,'') 'locationId', COALESCE(Des,'') 'locationName' FROM tbllocation ORDER BY LocationID;
	SELECT COALESCE(ClassID,'') 'classId', COALESCE(Des, '') 'className' FROM tblclass WHERE Inactive=0;
	
	SELECT COALESCE(ItemID,'') 'itemId',COALESCE(ItemName,'') 'itemName2', COALESCE(crm_fullname(itemcode,ItemName),'') 'itemName', crm_fullname_adv(ItemID,ItemName,itemcode) 'fullname' , COALESCE(itemcode,'') 'itemCode', COALESCE(itembarcode, '') 'itemBarcode' , COALESCE(ImagePath , '') 'imagePath' 
	FROM tblitem WHERE Inactive = 0 and ItemID <> '' AND ItemID is not NULL AND tblitem.`status` = 'Inventory Part'  ORDER BY ItemID;
	
	SELECT m.OP_ID 'oppId', m.OP_CustID 'custId',  m.OP_PriceCode 'priceCode', m.OP_Class 'classId',  OP_TotalSTax 'totalSTax', OP_TotalVTax 'totalVTax',
				 OP_TotalAmt 'totalAmt',OP_TotalDis 'totalDis', OP_Amt 'netTotal',
				 OP_D_ID 'oppDId', LineNo 'line',d.ItemID 'itemId',i.ItemName 'itemName', i.itemcode 'itemCode', i.itembarcode 'itemBarcode', 
				 d.ClassID 'classIdD',d.UomID 'uomId', d.LocationID 'locationId',d.SalQty 'saleQty',d.UnitPrice 'unitPrice', d.TotalAmt 'totalAmtD',d.DisDol 'disDolD', d.DisPer 'disPerD' ,
				 d.STaxDol 'sTaxDolD', d.STaxPer 'sTaxPerD', d.VTaxDol 'vTaxDolD', d.VTaxPer 'vTaxPerD',d.NetTotalAmt 'netTotalAmtD'
	FROM crm_opportunity m
	LEFT JOIN crm_opportunity_detail d ON m.OP_ID = d.OP_ID
	LEFT JOIN tblitem i ON d.ItemID = i.ItemID
	WHERE m.OP_ID = var_oppid
	ORDER BY d.LineNo;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_process_required`;
DELIMITER |
CREATE PROCEDURE `crm_process_required`(IN var_process varchar(255))
    DETERMINISTIC
BEGIN
	select * FROM crm_module_require_approval where RE_IsRequire = 1 and RE_Module = var_process;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_project_list_all`;
DELIMITER |
CREATE PROCEDURE `crm_project_list_all`(var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rt varchar(255);
	DECLARE var_empId varchar(255);
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select ame_user.var_crm_role FROM ame_user WHERE ame_user.var_id = var_user_id LIMIT 1)), 0);
	SET var_empId = COALESCE((SELECT ame_user.var_empid FROM ame_user WHERE ame_user.var_id = var_user_id),'');
	IF var_rt = '1' THEN
		SELECT pl_id 'plId',pl.pl_buildcompleted 'buid',pl.pl_cost_in_usd 'cosUSD', pl_name 'title', pl.empid 'empId', COALESCE(e.var_name,'') 'empName', COALESCE(pt.plt_name,'') 'plType',COALESCE(ps.pls_name,'') 'plStatus',COALESCE(u.var_name,'') 'userName',
       pl.pl_createdby 'createBy', DATE_FORMAT(pl.pl_createddate,"%d-%b-%Y %r") 'createDate', DATE_FORMAT(pl.pl_enddate,"%d-%b-%Y") 'endDate'
		FROM crm_projectlist pl 
		LEFT JOIN ame_mt_emp e ON pl.empid = e.var_id
		LEFT JOIN ame_user u ON u.var_id = pl.pl_createdby
		LEFT JOIN crm_projectlist_status ps ON ps.pls_id=pl.pl_status
		LEFT JOIN crm_projectlist_type pt ON pt.plt_id=pl.pl_type
		ORDER BY pl.pl_id DESC;
	ELSE		
		SELECT pl_id 'plId',pl.pl_buildcompleted 'buid',pl.pl_cost_in_usd 'cosUSD', pl_name 'title', pl.empid 'empId', COALESCE(e.var_name,'') 'empName', COALESCE(pt.plt_name,'') 'plType',COALESCE(ps.pls_name,'') 'plStatus',COALESCE(u.var_name,'') 'userName',
       pl.pl_createdby 'createBy', DATE_FORMAT(pl.pl_createddate,"%d-%b-%Y %r") 'createDate', DATE_FORMAT(pl.pl_enddate,"%d-%b-%Y") 'endDate'
		FROM crm_projectlist pl 
		LEFT JOIN ame_mt_emp e ON pl.empid = e.var_id
		LEFT JOIN ame_user u ON u.var_id = pl.pl_createdby
		LEFT JOIN crm_projectlist_status ps ON ps.pls_id=pl.pl_status
		LEFT JOIN crm_projectlist_type pt ON pt.plt_id=pl.pl_type
		WHERE pl.empid = var_empId OR pl.pl_createdby = var_user_id
		ORDER BY pl.pl_id DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_project_list_startup`;
DELIMITER |
CREATE PROCEDURE `crm_project_list_startup`(in var_user_id varchar(255))
    DETERMINISTIC
BEGIN	
	DECLARE var_rt varchar(255);
	DECLARE var_empId varchar(255);
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_user_id LIMIT 1)), 0);
	SET var_empId = COALESCE((SELECT EmpID FROM tbluseremployee WHERE UID = var_user_id),'');
	SELECT pls_id 'statusId',pls_name 'statusName' FROM crm_projectlist_status;
	SELECT plt_id 'typeId',plt_name 'typeName' FROM crm_projectlist_type;
	IF var_rt = '1' THEN
		SELECT COALESCE(EmpID,'') 'empId', COALESCE(EmpName,'') 'empName' FROM tblemployee WHERE Inactive=0 AND EmpID IN(SELECT EmpID FROM tblemployeesystemrole WHERE RoleName = 'Sale Representative') ORDER BY EmpID;
	ELSE		
		SELECT COALESCE(EmpID,'') 'empId', COALESCE(EmpName,'') 'empName' FROM tblemployee WHERE Inactive=0 AND EmpID = var_empId ORDER BY EmpID;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_project_list_startup_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_project_list_startup_by_id`(in var_user_id varchar(255))
    DETERMINISTIC
BEGIN	
	DECLARE var_rt varchar(255);
	DECLARE var_empId varchar(255);
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_user_id LIMIT 1)), 0);
	SET var_empId = COALESCE((SELECT EmpID FROM tbluseremployee WHERE UID = var_user_id),'');
	SELECT pls_id 'statusId',pls_name 'statusName' FROM crm_projectlist_status;
	SELECT plt_id 'typeId',plt_name 'typeName' FROM crm_projectlist_type;
	IF var_rt = '1' THEN
		SELECT COALESCE(EmpID,'') 'empId', COALESCE(EmpName,'') 'empName' FROM tblemployee WHERE Inactive=0 AND EmpID IN(SELECT EmpID FROM tblemployeesystemrole WHERE RoleName = 'Sale Representative') ORDER BY EmpID;
	ELSE		
		SELECT COALESCE(EmpID,'') 'empId', COALESCE(EmpName,'') 'empName' FROM tblemployee WHERE Inactive=0 AND EmpID = var_empId ORDER BY EmpID;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CALL_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CALL_GET_BY_ID`(IN `callId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT
		cl.CL_ID AS callId,
		cl.CL_Subject AS callSubject,
		DATE_FORMAT(cl.CL_SDate,'%d/%m/%Y %h:%i %p') AS callStartDate,
		cl.CL_Duration AS callDuration,
		cl.CL_RToType AS callRelatedToModuleType,
		cl.CL_RToID AS callRelatedToFieldId,
		COALESCE(CRM_FUN_MODULE_BY_RELATED(cl.CL_RToType, cl.CL_RToID),'') AS callRelatedName,
		cl.CL_Des AS callDes,
		cl.CL_CBy AS callCreateBy,
		cl.CL_CDate AS callCreateDate,
		cl.CL_MBy AS callModifiedBy,
		cl.CL_MDate AS callModifiedDate,
		cls.CLS_ID AS callStatusId,
		cls.CLS_Name AS callStatusName,
		us.var_id AS userID,
		us.var_name AS username
	FROM 
		crm_call cl 
	INNER JOIN
		crm_call_status cls
			ON cl.CL_StatusID = cls.CLS_ID
	LEFT OUTER JOIN 
		ame_user us 
			ON cl.CL_ATo = us.var_id
	WHERE cl.CL_ID = callId;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CALL_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CALL_LIST`(IN `userId` varchar(50))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT var_crm_role FROM ame_user WHERE var_id = userId);
	IF roleType = 1 THEN
		SELECT
			cl.CL_ID AS callId,
			cl.CL_Subject AS callSubject,
			DATE_FORMAT(cl.CL_SDate,'%d/%m/%Y %h:%i %p') AS callStartDate,
			cl.CL_Duration AS callDuration,
			cl.CL_RToType AS callRelatedToModuleType,
			cl.CL_RToID AS callRelatedToFieldId,
			COALESCE(CRM_FUN_MODULE_BY_RELATED(cl.CL_RToType, cl.CL_RToID),'') relatedToName,
			cl.CL_Des AS callDes,
			cl.CL_CBy AS callCreateBy,
			COALESCE((SELECT var_name FROM ame_user WHERE var_id = cl.CL_CBy),'') 'callCreateByName',
			CAST(cl.CL_CDate AS DATE) AS callCreateDate,
			cl.CL_MBy AS callModifiedBy,
			CAST(cl.CL_MDate AS DATE) AS callModifiedDate,
			cls.CLS_ID AS callStatusId,
			cls.CLS_Name AS callStatusName,
			COALESCE(us.var_id,'') AS userID,
			COALESCE(us.var_name,'') AS username
		FROM 
			crm_call cl 
		INNER JOIN
			crm_call_status cls
				ON cl.CL_StatusID = cls.CLS_ID
		LEFT OUTER JOIN 
			ame_user us 
				ON cl.CL_ATo = us.var_id
		ORDER BY cl.CL_ID DESC;
	ELSE
		SELECT
			cl.CL_ID AS callId,
			cl.CL_Subject AS callSubject,
			DATE_FORMAT(cl.CL_SDate,'%d/%m/%Y %h:%i %p') AS callStartDate,
			cl.CL_Duration AS callDuration,
			cl.CL_RToType AS callRelatedToModuleType,
			cl.CL_RToID AS callRelatedToFieldId,
			COALESCE(CRM_FUN_MODULE_BY_RELATED(cl.CL_RToType, cl.CL_RToID),'') relatedToName,
			cl.CL_Des AS callDes,
			cl.CL_CBy AS callCreateBy,
			COALESCE((SELECT var_name FROM ame_user WHERE var_id = cl.CL_CBy),'') 'callCreateByName',
			CAST(cl.CL_CDate AS DATE) AS callCreateDate,
			cl.CL_MBy AS callModifiedBy,
			CAST(cl.CL_MDate AS DATE) AS callModifiedDate,
			cls.CLS_ID AS callStatusId,
			cls.CLS_Name AS callStatusName,
			COALESCE(us.var_id,'') AS userID,
			COALESCE(us.var_name,'') AS username
		FROM 
			crm_call cl 
		INNER JOIN
			crm_call_status cls
				ON cl.CL_StatusID = cls.CLS_ID
		LEFT OUTER JOIN 
			ame_user us 
				ON cl.CL_ATo = us.var_id
		WHERE cl.CL_ATo = userId OR cl.CL_CBy = userId
		ORDER BY cl.CL_ID DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CALL_RELATED_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CALL_RELATED_LIST`(var_related varchar(150), var_related_id varchar(150), var_user_id varchar(150))
    DETERMINISTIC
BEGIN
	SELECT
		cl.CL_ID AS callId,
		cl.CL_Subject AS callSubject,
		DATE_FORMAT(cl.CL_SDate,'%d/%m/%Y %h:%i %p') AS callStartDate,
		cl.CL_Duration AS callDuration,
		cl.CL_Des AS callDes,
		cl.CL_CBy AS callCreateBy,
		CAST(cl.CL_CDate AS DATE) AS callCreateDate,
		cl.CL_MBy AS callModifiedBy,
		CAST(cl.CL_MDate AS DATE) AS callModifiedDate,
		cls.CLS_ID AS callStatusId,
		cls.CLS_Name AS callStatusName,
		COALESCE(us.var_id,'') userID,
		COALESCE(us.var_name,'') username
	FROM 
		crm_call cl 
	INNER JOIN
		crm_call_status cls
			ON cl.CL_StatusID = cls.CLS_ID
	LEFT OUTER JOIN 
		ame_user us 
			ON cl.CL_ATo = us.var_id
	WHERE cl.CL_RToID = var_related_id
	ORDER BY cl.CL_CDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CALL_RELATED_MODULE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CALL_RELATED_MODULE`(IN `moduleId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT
		cl.CL_ID AS callId,
		cl.CL_Subject AS callSubject,
		DATE_FORMAT(cl.CL_SDate,'%d/%m/%Y %h:%i %p') AS callStartDate,
		cl.CL_Duration AS callDuration,
		cl.CL_Des AS callDes,
		cl.CL_CBy AS callCreateBy,
		CAST(cl.CL_CDate AS DATE) AS callCreateDate,
		cl.CL_MBy AS callModifiedBy,
		CAST(cl.CL_MDate AS DATE) AS callModifiedDate,
		cls.CLS_ID AS callStatusId,
		cls.CLS_Name AS callStatusName,
		COALESCE(us.var_id,'') userID,
		COALESCE(us.var_name,'') username
	FROM 
		crm_call cl 
	INNER JOIN
		crm_call_status cls
			ON cl.CL_StatusID = cls.CLS_ID
	LEFT OUTER JOIN 
		ame_user us 
			ON cl.CL_ATo = us.var_id
	WHERE cl.CL_RToID = moduleId
	ORDER BY cl.CL_CDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CALL_START_UP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CALL_START_UP`(var_obj_id varchar(50))
    DETERMINISTIC
BEGIN
	CALL CRM_PRO_CALL_STATUS_LOAD();
	CALL CRM_PRO_USER_LIST_COM('');
	IF var_obj_id <> '' THEN 
		CALL CRM_PRO_CALL_GET_BY_ID(var_obj_id);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CALL_STATUS_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CALL_STATUS_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT CLS_ID callStatusId, CLS_Name callStatusName FROM crm_call_status;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CAMP_DELETE_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CAMP_DELETE_BY_ID`(IN `campId` varchar(50))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_call WHERE crm_call.CL_RToID = campId;
	DELETE FROM crm_meeting WHERE crm_meeting.M_RToID = campId;
	DELETE FROM crm_task WHERE crm_task.TA_RToID = campId;
	DELETE FROM crm_event WHERE crm_event.EV_RToID = campId;
	DELETE FROM crm_note WHERE crm_note.N_RToID = campId;
	DELETE FROM crm_colllaboration_tags WHERE crm_colllaboration_tags.collapId IN(SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = campId); 
	DELETE FROM crm_collaboration_details WHERE crm_collaboration_details.PostID IN(SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = campId);
	DELETE FROM crm_collaboration WHERE crm_collaboration.CB_RToID = campId;
	DELETE FROM crm_opportunity WHERE crm_opportunity.OP_CampID = campId;
	DELETE FROM crm_lead WHERE crm_lead.LA_CA_ID = campId;
	DELETE FROM crm_camp  WHERE crm_camp.CA_ID = campId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CAMP_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CAMP_GET_BY_ID`(IN `campID` varchar(50))
    DETERMINISTIC
BEGIN
	SELECT 
		ca.CA_ID campID, 
		ca.CA_Name campName, 
		ca.CA_SDate startDate, 
		ca.CA_EDate endDate, 
		cas.CAS_ID statusID, 
		cas.CAS_Name statusName,
		cat.CAT_ID typeID, 
		cat.CAT_Name typeName, 
		cam.CA_ID parentID, 
		cam.CA_Name parentName, 
		cu.var_id userID, 
		cu.var_name username, 
		ca.CA_Budget budget, 
		ca.CA_ActualCost actualCost,
		ca.CA_ExpectedCost expectedCost, 
		ca.CA_ExpectedRevenue expectedRevenue, 
		ca.CA_NumSend numSend, 
		ca.CA_ExpectedResponse expectedResponse, 
		ca.CA_CBy createdBy,
		ca.CA_CDate createdDate, 
		CAST(ca.CA_MDate AS date) modifiedDate, 
		ca.CA_MBy modifiedBy, ca.CA_Des description
	FROM crm_camp ca
	INNER JOIN 
		crm_camp_status cas 
			ON ca.CA_StatusID = cas.CAS_ID
	INNER JOIN 
		crm_camp_type cat 
			ON ca.CA_TypeID = cat.CAT_ID
	LEFT OUTER JOIN 
		crm_camp cam 
			ON ca.CA_ParentID = cam.CA_ID
	LEFT OUTER JOIN 
		ame_user cu 
			ON ca.CA_ATo = cu.var_id
  WHERE ca.CA_ID = campID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CAMP_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CAMP_LIST`(dou_num integer, dou_page integer, var_TrUID varchar(255))
    DETERMINISTIC
BEGIN	
	SELECT DISTINCT 
		ca.CA_ID campID, 
		ca.CA_Name campName, 
		ca.CA_SDate startDate, 
		ca.CA_EDate endDate, 
		ca.CA_StatusID statusID, 
		(SELECT CAS_Name FROM crm_camp_status WHERE CAS_ID = ca.CA_StatusID) statusName,
		ca.CA_TypeID typeID, 
		(SELECT CAT_Name FROM crm_camp_type WHERE CAT_ID = ca.CA_TypeID) typeName, 
		ca.CA_ParentID parentID, 
		(SELECT CA_Name FROM crm_camp cam WHERE cam.CA_ID = ca.CA_ParentID) parentName, 
		ca.CA_ATo userID, 
		COALESCE((SELECT var_name FROM ame_user WHERE var_id= ca.CA_ATo),'') username, 
		ca.CA_Budget budget, 
		ca.CA_ActualCost actualCost,
		ca.CA_ExpectedCost expectedCost, 
		ca.CA_ExpectedRevenue expectedRevenue, 
		ca.CA_NumSend numSend, 
		ca.CA_ExpectedResponse expectedResponse, 
		ca.CA_CBy createdBy,
		COALESCE((SELECT var_name from ame_user WHERE var_id = ca.CA_CBy),'') createByName,
		ca.CA_CDate createdDate, 
		CAST(ca.CA_MDate AS date) modifiedDate, 
		ca.CA_MBy modifiedBy, ca.CA_Des description
	FROM crm_camp ca
  ORDER BY ca.CA_ID DESC;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CAMP_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CAMP_LOAD`(var_userId varchar(255))
    DETERMINISTIC
BEGIN
	SELECT CA_ID campID, CA_Name campName FROM crm_camp;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CAMP_OPP_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CAMP_OPP_LOAD`(var_camp_id varchar(150))
    DETERMINISTIC
BEGIN
	SELECT cus.var_id 'custId', COALESCE(cus.var_name, '') 'custName', opp.OP_ID 'opId', COALESCE(opp.OP_Name, '') 'opName', COALESCE(stage.OS_Name, '') 'opStageId',
         COALESCE(opp.OP_Amt,0) 'opAmount', DATE_FORMAT(opp.OP_CloseDate,'%d-%m-%Y') 'opCloseDate'
	FROM crm_opportunity opp 
	LEFT JOIN ame_mt_cus cus ON opp.OP_CustID = cus.var_id
	LEFT JOIN crm_opportunity_stage stage ON stage.OS_ID = opp.OP_StageID
	WHERE opp.OP_CampID = var_camp_id;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CAMP_PARENT_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CAMP_PARENT_LIST`(IN `campId` varchar(50))
    DETERMINISTIC
BEGIN

	DECLARE childCount INT DEFAULT 0;
	SELECT COUNT(CA_ID) INTO childCount FROM crm_camp WHERE CA_ParentID = campId; 

	IF childCount <= 0 THEN
		SELECT CA_ID campID, CA_Name campName
		FROM crm_camp WHERE CA_ID <> campId AND CA_ParentID IS NULL OR CA_ParentID = "";
	ELSE
		SELECT DISTINCT NULL AS campID, NULL AS campName FROM crm_camp;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CAMP_PARENT_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CAMP_PARENT_LOAD`(IN `campId` varchar(50))
    DETERMINISTIC
BEGIN
	SELECT CA_ID campID, CA_Name campName FROM crm_camp WHERE CA_ID <> campId AND CA_ParentID IS NULL OR CA_ParentID = "";
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CAMP_VIEW`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CAMP_VIEW`(objectId varchar(150), userid varchar(150))
    DETERMINISTIC
BEGIN
	SELECT COALESCE((SELECT COUNT(*) FROM crm_call WHERE CL_RToID = objectId),0) as cCall,
         COALESCE((SELECT COUNT(*) FROM crm_meeting WHERE M_RToID = objectId),0) as cMeeting,
				 COALESCE((SELECT COUNT(*) FROM crm_task WHERE TA_RToID = objectId),0) as cTask,
				 COALESCE((SELECT COUNT(*) FROM crm_event WHERE EV_RToID = objectId),0) as cEvent ;
	CALL CRM_PRO_CAMP_GET_BY_ID(objectId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CAMP_VIEW_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CAMP_VIEW_BY_ID`(IN `campId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
CALL CRM_PRO_TASK_RELATED_MODULE(campId);
CALL CRM_PRO_TASK_STATUS_LOAD();
CALL CRM_PRO_EVENT_RELATED_MODULE(campId);
CALL CRM_PRO_EVENT_LOCATION_LOAD();
CALL CRM_PRO_CALL_RELATED_MODULE(campId);
CALL CRM_PRO_CALL_STATUS_LOAD();
CALL CRM_PRO_MEETING_RELATED_MODULE(campId);
CALL CRM_PRO_MEETING_STATUS_LOAD();
CALL CRM_PRO_CAMP_PARENT_LOAD(campId);
CALL CRM_PRO_CONTACT_LOAD();
CALL CRM_PRO_NOTE_LOAD(campId);
CALL CRM_PRO_USER_LIST_COM(userId);
CALL CRM_PRO_USER_LIST_COM(userId);
CALL CRM_PRO_OPP_LOAD_BY_CAMP(campId);
CALL CRM_PRO_LEAD_LOAD_BY_CAMP(campId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_ADD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_ADD`(var_id  varchar(150), var_status varchar(250), var_type varchar(150), var_prority varchar(150), var_custid varchar(150), var_contactid varchar(150), var_subject varchar(255), var_des varchar(255), var_ato varchar(255), var_cby varchar(150), var_followupdate varchar(150), var_originid varchar(150), var_itemid varchar(150), var_enddate varchar(250))
    DETERMINISTIC
BEGIN
	DECLARE var_lastid VARCHAR(100) DEFAULT "";
	SET var_lastid = CRM_FUN_CONFIG_GENERATE_ID('CS');
	IF var_lastid <> '' THEN
		INSERT INTO `crm_case` (
			`cs_id`,
			`cs_statusid`,
			`cs_typeid`,
			`cs_priority`,
			`cs_custid`,
			`cs_contactid`,
			`cs_subject`,
			`cs_des`,
			`cs_ato`,
			`cs_cby`,
			`cs_cdate`,
			`cs_followupdate`,
			`cs_originid`,
			`cs_itemid`,
			`cs_enddate`
		)
		VALUES(var_lastid,var_status, var_type , var_prority, var_custid , var_contactid, var_subject, var_des , var_ato, var_cby ,NOW(), var_followupdate , var_originid , var_itemid, var_enddate);
	END IF;
SELECT var_lastid as 'lastId', CRM_FUN_CONFIG_IMG_PATH() AS 'IMG_PATH';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_ARTICLE_ADD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_ARTICLE_ADD`(var_id varchar(150), var_title varchar(255), var_key varchar(255), var_itemid varchar(150), var_des text, var_cby varchar(150))
    DETERMINISTIC
BEGIN
	DECLARE var_lastid VARCHAR(100) DEFAULT "";
	SET var_lastid = CRM_FUN_CONFIG_GENERATE_ID('ART');
	IF var_lastid <> '' THEN
		INSERT INTO `crm_case_article` (`A_ID`, `A_Title`, `A_Key`, `A_ItemID`, `A_Description`, `A_CDate`, `A_CBy`) 
		VALUES (var_lastid, var_title, var_key, var_itemid, var_des, NOW(), NULL);
	END IF;
	SELECT var_lastid as 'lastId', CRM_FUN_CONFIG_IMG_PATH() AS 'IMG_PATH';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_ARTICLE_DELETE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_ARTICLE_DELETE`(var_id varchar(150))
    DETERMINISTIC
BEGIN
	DELETE FROM `crm_case_article` 
	WHERE
		(`A_ID` = var_id);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_ARTICLE_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_ARTICLE_GET_BY_ID`(var_id varchar(150), var_case_id varchar(150))
    DETERMINISTIC
BEGIN
	SELECT a_id 'articleId', 
				 a_title 'articleTitle',
				 A_Description 'articleDes',
				 a_key 'articleKey', 
				 a_itemid 'itemId', COALESCE(i.var_name,'') 'itemName', var_itemcode 'itemCode',a_cby 'articleCreateBy', u.var_name 'articleCreateByName', a_cdate 'articleCreateDate'
	FROM crm_case_article a
	LEFT JOIN ame_user u ON u.var_id = a.a_cby
	LEFT JOIN ame_mt_ite i ON a.a_itemid = i.var_id
	WHERE a_id = IF(var_case_id = '',var_id, (SELECT crm_case.cs_articleid FROM crm_case WHERE crm_case.cs_id = var_case_id))
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_ARTICLE_UPDATE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_ARTICLE_UPDATE`(var_id varchar(150), var_title varchar(255), var_key varchar(255), var_itemid varchar(150), var_des text, var_cby varchar(150))
    DETERMINISTIC
BEGIN
	UPDATE `crm_case_article`
	SET
	 `A_Title` = var_title,
	 `A_Key` = var_key,
	 `A_ItemID` = var_itemid,
	 `A_Description` = var_des,
	 `A_MDate` = NOW(),
	 `A_MBy` = var_cby
	WHERE
		(`A_ID` = var_id);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_DELETE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_DELETE`(IN `caseId` varchar(50))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_call WHERE crm_call.CL_RToID = caseId;
	DELETE FROM crm_meeting WHERE crm_meeting.M_RToID = caseId;
	DELETE FROM crm_task WHERE crm_task.TA_RToID = caseId;
	DELETE FROM crm_event WHERE crm_event.EV_RToID = caseId;
	DELETE FROM crm_note WHERE crm_note.N_RToID = caseId;
	DELETE FROM crm_colllaboration_tags WHERE crm_colllaboration_tags.collapId IN (SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = caseId); 
	DELETE FROM crm_collaboration_details WHERE crm_collaboration_details.PostID IN (SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = caseId);
	DELETE FROM crm_collaboration WHERE crm_collaboration.CB_RToID = caseId;
	DELETE FROM crm_case WHERE crm_case.CS_ID = caseId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_GET_BY_ID`(caseId varchar(150))
    DETERMINISTIC
BEGIN
	SELECT
		cs.CS_ID caseId,
		css.CSS_ID statusId, 
		css.CSS_Name statusName,
		cst.CST_ID caseTypeId, 
		cst.CST_Name caseTypeName,
		csp.CSP_ID priorityId, 
		csp.CSP_Name priorityName, 
		cus.var_id custID, 
		cus.var_name custName, 
		con.CO_ID conID, 
		con.CO_Salutation conSalutation,
		con.CO_FirstName conFirstname,
		con.CO_LastName conLastname,
		cs.CS_Subject `subject`,
		cs.CS_Des des,
    cs.CS_Key caseKey,
    cs.CS_ResolvedBy resolvedBy,
		(SELECT resolve.var_name FROM ame_user resolve WHERE resolve.var_id= cs.CS_ResolvedBy) resolveByName,	
    DATE_FORMAT(cs.CS_ResolvedDate,'%d/%m/%Y %h:%i %p') resolveDate,
		cs.CS_Resolution resolution,
		u.var_id userID,
		u.var_name username,
    cs.CS_ATo assignTo,
		cs.CS_CBy createBy,
		DATE_FORMAT(cs.CS_CDate,'%d/%m/%Y %h:%i %p') createDate,
		cs.CS_MBy modifyBy,
		DATE_FORMAT(cs.CS_MDate,'%d/%m/%Y %h:%i %p') modifyDate,
		DATE_FORMAT(cs.CS_FollowupDate,'%d/%m/%Y %h:%i %p') followupDate,
		DATE_FORMAT(cs.CS_EndDate,'%d/%m/%Y %h:%i %p') endDate,
		cs.CS_OriginID caseOriginId,
		(SELECT org.CS_Title FROM crm_case_origin org WHERE org.CS_OriginID = cs.CS_OriginID) caseOriginTitle,
		cs.CS_PriceCode casePriceCode,
		(SELECT ame_mt_pri_cod.var_name FROM ame_mt_pri_cod WHERE ame_mt_pri_cod.var_id = cs.CS_PriceCode) casePriceCodeDes,
		cs.CS_Class as caseClassId,
		(SELECT ame_mt_cla.var_name FROM ame_mt_cla WHERE ame_mt_cla.var_id = cs.CS_Class) caseClassName,
		cs.CS_ItemID caseItemId,
		(SELECT ame_mt_ite.var_name FROM ame_mt_ite  WHERE ame_mt_ite.var_id = cs.CS_ItemID) caseItemName,
		 cs.CS_ArticleID articleId,
    (SELECT art.A_Title FROM crm_case_article art WHERE art.A_ID= cs.CS_ArticleID) articleTitle,
		cs.CS_OriginID originId,
		(SELECT CS_Title FROM crm_case_origin WHERE CS_OriginID = cs.CS_OriginID) originName
	FROM 
		crm_case cs
	INNER JOIN
		crm_case_status css 
			ON css.CSS_ID = cs.CS_StatusID
	INNER JOIN 
		crm_case_priority csp 
			ON csp.CSP_ID = cs.CS_Priority
	INNER JOIN 
		crm_case_type cst 
			ON cst.CST_ID = cs.CS_TypeID
	LEFT OUTER JOIN 
		ame_mt_cus cus 
			ON cus.var_id = cs.CS_CustID
	LEFT OUTER JOIN 
		crm_contact con 
			ON con.CO_ID = cs.CS_ContactID
  LEFT OUTER JOIN 
		ame_user u 
			ON u.var_id = cs.CS_ATo
			
	WHERE cs.CS_ID = caseId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_LIST`(userId varchar(150))
    DETERMINISTIC
BEGIN
DECLARE roleType INT DEFAULT 0;
SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT `ame_user`.var_crm_role FROM `ame_user` WHERE `ame_user`.var_id = userId);
IF roleType = 1 THEN
SELECT
cs.CS_ID caseId,
cs.CS_StatusID statusId,
(SELECT CSS_Name FROM crm_case_status WHERE CSS_ID = cs.CS_StatusID) statusName,
cs.CS_TypeID caseTypeId,
(SELECT CST_Name FROM crm_case_type WHERE CST_ID = cs.CS_TypeID) caseTypeName,
cs.CS_Priority priorityId,
(SELECT CSP_Name FROM crm_case_priority WHERE CSP_ID = cs.CS_Priority) priorityName,
cs.CS_CustID custID,
(SELECT var_name FROM ame_mt_cus c WHERE c.var_id = cs.CS_CustID) custName,
cs.CS_ContactID conID,
(SELECT CONCAT(co.CO_Salutation," ",co.CO_FirstName," ",co.CO_LastName) FROM crm_contact co WHERE co.CO_ID = cs.CS_ContactID) conName,
cs.CS_Subject subject,
cs.CS_Des des,
cs.CS_Resolution resolution,
cs.CS_ATo userID,
(SELECT ass.var_name FROM ame_user ass WHERE ass.var_id = cs.CS_ATo) username,
cs.CS_CBy createBy,
(SELECT cd.var_name FROM ame_user cd WHERE cd.var_id = cs.CS_CBy) createByName,
TIMESTAMP(cs.CS_CDate) createDate,
TIMESTAMP(cs.CS_EndDate) endDate,
TIMESTAMP(cs.CS_FollowupDate) followupDate,
cs.CS_ItemID productId,
(SELECT var_name FROM ame_mt_ite ite WHERE ite.var_id = cs.CS_ItemID) productName
FROM
crm_case cs WHERE cs.CS_EndDate > NOW() OR CS_StatusID = 5
ORDER BY cs.CS_CDate DESC, cs.CS_ID DESC;
SELECT
cs.CS_ID caseId,
cs.CS_StatusID statusId,
(SELECT CSS_Name FROM crm_case_status WHERE CSS_ID = cs.CS_StatusID) statusName,
cs.CS_TypeID caseTypeId,
(SELECT CST_Name FROM crm_case_type WHERE CST_ID = cs.CS_TypeID) caseTypeName,
cs.CS_Priority priorityId,
(SELECT CSP_Name FROM crm_case_priority WHERE CSP_ID = cs.CS_Priority) priorityName,
cs.CS_CustID custID,
(SELECT var_name FROM ame_mt_cus c WHERE c.var_id = cs.CS_CustID) custName,
cs.CS_ContactID conID,
(SELECT CONCAT(co.CO_Salutation," ",co.CO_FirstName," ",co.CO_LastName) FROM crm_contact co WHERE co.CO_ID = cs.CS_ContactID) conName,
cs.CS_Subject subject,
cs.CS_Des des,
cs.CS_Resolution resolution,
cs.CS_ATo userID,
(SELECT ass.var_name FROM ame_user ass WHERE ass.var_id = cs.CS_ATo) username,
cs.CS_CBy createBy,
(SELECT var_name FROM ame_user cd WHERE cd.var_id = cs.CS_CBy) createByName,
TIMESTAMP(cs.CS_CDate) createDate,
TIMESTAMP(cs.CS_EndDate) endDate,
TIMESTAMP(cs.CS_FollowupDate) followupDate,
cs.CS_ItemID productId,
(SELECT ite.var_name FROM ame_mt_ite ite WHERE ite.var_id = cs.CS_ItemID) productName
FROM
crm_case cs WHERE cs.CS_EndDate < NOW() AND CS_StatusID <> 5
ORDER BY cs.CS_ID DESC;
SELECT COUNT(CS_ID) 'numOfOverDueDateCases' FROM crm_case WHERE CS_EndDate < NOW() AND CS_StatusID <> 5;
ELSE
SELECT
cs.CS_ID caseId,
cs.CS_StatusID statusId,
(SELECT CSS_Name FROM crm_case_status WHERE CSS_ID = cs.CS_StatusID) statusName,
cs.CS_TypeID caseTypeId,
(SELECT CST_Name FROM crm_case_type WHERE CST_ID = cs.CS_TypeID) caseTypeName,
cs.CS_Priority priorityId,
(SELECT CSP_Name FROM crm_case_priority WHERE CSP_ID = cs.CS_Priority) priorityName,
cs.CS_CustID custID,
(SELECT CustName FROM tblcustomer c WHERE c.CustID = cs.CS_CustID) custName,
cs.CS_ContactID conID,
(SELECT CONCAT(co.CO_Salutation," ",co.CO_FirstName," ",co.CO_LastName) FROM crm_contact co WHERE co.CO_ID = cs.CS_ContactID) conName,
cs.CS_Subject subject,
cs.CS_Des des,
cs.CS_Resolution resolution,
cs.CS_ATo userID,
(SELECT UName FROM tbluser WHERE UID = cs.CS_ATo) username,
cs.CS_CBy createBy,
(SELECT UName FROM tbluser WHERE UID = cs.CS_CBy) createByName,
TIMESTAMP(cs.CS_CDate) createDate,
TIMESTAMP(cs.CS_EndDate) endDate,
TIMESTAMP(cs.CS_FollowupDate) followupDate,
cs.CS_ItemID productId,
(SELECT ItemName FROM tblitem WHERE ItemID = cs.CS_ItemID) productName
FROM
crm_case cs WHERE (cs.CS_CBy = userId OR cs.CS_ATo = userId) AND cs.CS_EndDate > NOW() OR CS_StatusID = 5
ORDER BY cs.CS_CDate DESC, cs.CS_ID DESC ;
SELECT
cs.CS_ID caseId,
cs.CS_StatusID statusId,
(SELECT CSS_Name FROM crm_case_status WHERE CSS_ID = cs.CS_StatusID) statusName,
cs.CS_TypeID caseTypeId,
(SELECT CST_Name FROM crm_case_type WHERE CST_ID = cs.CS_TypeID) caseTypeName,
cs.CS_Priority priorityId,
(SELECT CSP_Name FROM crm_case_priority WHERE CSP_ID = cs.CS_Priority) priorityName,
cs.CS_CustID custID,
(SELECT CustName FROM tblcustomer c WHERE c.CustID = cs.CS_CustID) custName,
cs.CS_ContactID conID,
(SELECT CONCAT(co.CO_Salutation," ",co.CO_FirstName," ",co.CO_LastName) FROM crm_contact co WHERE co.CO_ID = cs.CS_ContactID) conName,
cs.CS_Subject subject,
cs.CS_Des des,
cs.CS_Resolution resolution,
cs.CS_ATo userID,
(SELECT UName FROM tbluser WHERE UID = cs.CS_ATo) username,
cs.CS_CBy createBy,
(SELECT UName FROM tbluser WHERE UID = cs.CS_CBy) createByName,
TIMESTAMP(cs.CS_CDate) createDate,
TIMESTAMP(cs.CS_EndDate) endDate,
TIMESTAMP(cs.CS_FollowupDate) followupDate,
cs.CS_ItemID productId,
(SELECT ItemName FROM tblitem WHERE ItemID = cs.CS_ItemID) productName
FROM
crm_case cs WHERE (cs.CS_CBy = userId OR cs.CS_ATo = userId) AND cs.CS_EndDate < NOW()
ORDER BY cs.CS_CDate DESC, cs.CS_ID DESC;
SELECT COUNT(CS_ID) 'numOfOverDueDateCases' FROM crm_case WHERE CS_EndDate < NOW() AND (CS_CBy = userId OR CS_ATo = userId) AND CS_StatusID <> 5;
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_ORIGIN_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_ORIGIN_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT CS_OriginID 'originId', CS_Title 'originTitle' FROM crm_case_origin ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_PRIORITY_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_PRIORITY_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT CSP_ID 'priorityId', CSP_Name 'priorityName' FROM crm_case_priority;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_START_UP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_START_UP`(var_userid varchar(255), var_objectid varchar(255))
    DETERMINISTIC
BEGIN
	CALL CRM_PRO_CASE_STATUS_LOAD();
	CALL CRM_PRO_CASE_TYPE_LOAD();
	CALL CRM_PRO_CASE_ORIGIN_LOAD();
	CALL CRM_PRO_CASE_PRIORITY_LOAD();
	CALL CRM_PRO_CUSTOMER_LOAD(var_userid);
	CALL CRM_PRO_CONTACT_LOAD();
	CALL CRM_PRO_USER_LIST_COM(var_userid);
	CALL CRM_PRO_ITEM_LOAD(var_userid);
	IF var_objectid <> '' THEN 
		CALL CRM_PRO_CASE_GET_BY_ID(var_objectid);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_STATUS_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_STATUS_LOAD`()
    DETERMINISTIC
BEGIN	
	SELECT CSS_ID 'statusId', CSS_Name 'statusName' FROM crm_case_status;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_TYPE_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_TYPE_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT CST_ID 'caseTypeId', CST_Name 'caseTypeName' FROM crm_case_type ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_UPDATE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_UPDATE`(var_id  varchar(150), var_status varchar(250), var_type varchar(150), var_prority varchar(150), var_custid varchar(150), var_contactid varchar(150), var_subject varchar(255), var_des varchar(255), var_ato varchar(255), var_cby varchar(150), var_followupdate varchar(150), var_originid varchar(150), var_itemid varchar(150), var_enddate varchar(250))
    DETERMINISTIC
BEGIN
	UPDATE `crm_case`
	SET 
	 `cs_statusid` = var_status,
	 `cs_typeid` = var_type,
	 `cs_priority` = var_prority,
	 `cs_custid` = var_custid,
	 `cs_contactid` = var_contactid,
	 `cs_subject` = var_subject,
	 `cs_des` = var_des,
	 `cs_ato` = var_ato,
	 `cs_mby` = var_cby,
	 `cs_mdate` = NOW(),
	 `cs_followupdate` = var_followupdate,
	 `cs_originid` = var_originid,
	 `cs_itemid` = var_itemid,
	 `cs_enddate` = var_enddate
	WHERE
		(`cs_id` = var_id);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CASE_VIEW`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CASE_VIEW`(objectId varchar(150), userid varchar(150))
    DETERMINISTIC
BEGIN
		SELECT COALESCE((SELECT COUNT(*) FROM crm_call WHERE CL_RToID = objectId),0) as cCall,
         COALESCE((SELECT COUNT(*) FROM crm_meeting WHERE M_RToID = objectId),0) as cMeeting,
				 COALESCE((SELECT COUNT(*) FROM crm_task WHERE TA_RToID = objectId),0) as cTask,
				 COALESCE((SELECT COUNT(*) FROM crm_event WHERE EV_RToID = objectId),0) as cEvent ;
	CALL CRM_PRO_CASE_GET_BY_ID(objectId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CLASS_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CLASS_LOAD`(userId varchar(150))
    DETERMINISTIC
BEGIN
	SELECT var_id 'classId', var_name 'className' FROM ame_mt_cla;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_COLLABORATE_BY_RELATED`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_COLLABORATE_BY_RELATED`(var_related varchar(100), var_userId varchar(100))
    DETERMINISTIC
BEGIN
	SET SESSION group_concat_max_len = 1000000;
	SELECT c.CB_ID 'colId', c.CB_Des 'colDes', u.var_name 'colUser',u.var_id 'colUserId',
       DATE_FORMAT(c.CB_CreateDate,'%d/%m/%Y %h:%i %p') 'colCreateDate', (SELECT COUNT(*) FROM crm_user_like_collaboration WHERE LK_CBID = c.CB_ID) as 'like',
       IF(((SELECT COUNT(*) FROM crm_user_like_collaboration WHERE LK_CBID = c.CB_ID AND LK_UID = var_userId) > 0), 'True', 'False') as 'checkLike',
       CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"userId":"',COALESCE(t.userId,''),'", "username":"',COALESCE(ut.var_name,''),'"}'))  FROM crm_colllaboration_tags t  LEFT JOIN ame_user ut on ut.var_id = t.userId  WHERE collapId = c.CB_ID),']') as 'tags', 
			 CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"commentId":',d.CommentID,', "postId":', d.PostID,', "comment":"',d.`Comment`,'", "userId":"',d.UID,'", "username":"', uc.var_name,'", "createDate": "',DATE_FORMAT(d.CreateDate,'%d/%m/%Y %h:%i %p'),'"}'))  FROM crm_collaboration_details d  LEFT JOIN ame_user uc ON d.UID = uc.var_id WHERE d.PostID = c.CB_ID ),']') AS 'details'
	FROM crm_collaboration c
	LEFT JOIN ame_user u ON u.var_id = c.CB_UID
	WHERE c.CB_RToID = var_related
	ORDER BY c.CB_ID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_COLLABORATE_COMMENT_ADD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_COLLABORATE_COMMENT_ADD`(var_posid integer, var_comment varchar(255), var_userid varchar(255))
    DETERMINISTIC
BEGIN
	INSERT INTO `crm_collaboration_details` (`PostID`, `Comment`, `CreateDate`, `UID`) VALUES (var_posid, var_comment, NOW(), var_userid);
	SELECT LAST_INSERT_ID() 'commentId', PostID 'postId', `Comment` 'comment', DATE_FORMAT(CreateDate,'%d/%m/%Y %h:%i %p') 'createDate' , d.UID 'userId', u.var_name 'username' 
  FROM crm_collaboration_details d
	LEFT JOIN ame_user u ON d.UID = u.var_id
	WHERE `CommentID` = LAST_INSERT_ID();
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_COLLABORATE_DELETE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_COLLABORATE_DELETE`(collapId integer)
    DETERMINISTIC
BEGIN
	delete from crm_collaboration_details where PostID = collapId;
	delete from crm_colllaboration_tags where collapId = collapId;
	delete from crm_user_like_collaboration where LK_CBID = collapId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_COLLABORATE_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_COLLABORATE_GET_BY_ID`(var_postid varchar(255), var_userId varchar(100))
    DETERMINISTIC
BEGIN
	SET SESSION group_concat_max_len = 1000000;
	SELECT c.CB_ID 'colId', c.CB_Des 'colDes', u.var_name 'colUser',u.var_id 'colUserId',
       DATE_FORMAT(c.CB_CreateDate,'%d/%m/%Y %h:%i %p') 'colCreateDate', (SELECT COUNT(*) FROM crm_user_like_collaboration WHERE LK_CBID = c.CB_ID) as 'like',
       IF(((SELECT COUNT(*) FROM crm_user_like_collaboration WHERE LK_CBID = c.CB_ID AND LK_UID = var_userId) > 0), 'True', 'False') as 'checkLike',
       CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"userId":"',COALESCE(t.userId,''),'", "username":"',COALESCE(ut.var_name,''),'"}'))  FROM crm_colllaboration_tags t  LEFT JOIN ame_user ut on ut.var_id = t.userId  WHERE collapId = c.CB_ID),']') as 'tags', 
			 CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"commentId":',d.CommentID,', "postId":', d.PostID,', "comment":"',d.`Comment`,'", "userId":"',d.UID,'", "username":"', uc.var_name,'", "createDate": "',DATE_FORMAT(d.CreateDate,'%d/%m/%Y %h:%i %p'),'"}'))  FROM crm_collaboration_details d  LEFT JOIN ame_user uc ON d.UID = uc.var_id WHERE d.PostID = c.CB_ID ),']') AS 'details'
	FROM crm_collaboration c
	LEFT JOIN ame_user u ON u.var_id = c.CB_UID
	WHERE c.CB_ID = var_postid 
	ORDER BY c.CB_ID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_COLLABORATE_RELATE_BY_MODULE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_COLLABORATE_RELATE_BY_MODULE`(IN `username` varchar(50),IN `moduleType` varchar(50),IN `moduleId` varchar(50))
    DETERMINISTIC
BEGIN
 
	CASE UPPER(moduleType)
		WHEN "LEAD" THEN 
			SELECT 
				col.CB_ID AS postId,
				col.CB_Des AS postDes,
				col.CB_UName AS username,
				DATE_FORMAT(col.CB_CreateDate,'%d/%m/%Y %h:%i %p') AS postCreateDate,
				col.CB_Own AS postOwner,
				del.CBS_ID AS commentId,
				del.CBS_Des AS commentDes,
				del.CBS_UName AS commentBy,
				DATE_FORMAT(del.CBS_CreateDate,'%d/%m/%Y %h:%i %p') AS commentCreateDate,
				(SELECT COUNT(LK_ID) FROM crm_user_like_collaboration WHERE LK_CBID = col.CB_ID) AS `like`,
				(SELECT COUNT(LK_ID) FROM crm_user_like_collaboration WHERE LK_UserName = username) AS likeOwner
			FROM 
				crm_collaboration col 
				INNER JOIN 
					crm_lead la 
						ON col.CB_RToID = la.LA_ID
				LEFT OUTER JOIN
					crm_collaboration_details del 
						ON col.CB_ID = del.CBS_CBID
			WHERE la.LA_ID = moduleId;
	
		WHEN "OPPORTUNITY" THEN 
			SELECT 
				col.CB_ID AS postId,
				col.CB_Des AS postDes,
				col.CB_UName AS username,
				DATE_FORMAT(col.CB_CreateDate,'%d/%m/%Y %h:%i %p') AS postCreateDate,
				col.CB_Own AS postOwner,
				del.CBS_ID AS commentId,
				del.CBS_Des AS commentDes,
				del.CBS_UName AS commentBy,
				DATE_FORMAT(del.CBS_CreateDate,'%d/%m/%Y %h:%i %p') AS commentCreateDate,
				(SELECT COUNT(LK_ID) FROM crm_user_like_collaboration WHERE LK_CBID = col.CB_ID) AS `like`,
				(SELECT COUNT(LK_ID) FROM crm_user_like_collaboration WHERE LK_UserName = username) AS likeOwner
			FROM 
				crm_collaboration col 
				INNER JOIN 
					crm_opportunity op
						ON col.CB_RToID = op.OP_ID
				LEFT OUTER JOIN
					crm_collaboration_details del 
						ON col.CB_ID = del.CBS_CBID
			WHERE op.OP_ID = moduleId;
	
  END CASE;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CONTACT_ADD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CONTACT_ADD`(var_CO_ID varchar(255), var_CO_Salutation varchar(255), var_CO_FirstName varchar(255), var_CO_LastName varchar(255), var_CO_Phone varchar(255), var_CO_Mobile varchar(255), var_CO_Email varchar(255), var_CO_Title varchar(255), var_CO_Department varchar(255), var_CO_No varchar(255), var_CO_Street varchar(255), var_CO_Village varchar(255), var_CO_Commune varchar(255), var_CO_District varchar(255), var_CO_City varchar(255), var_CO_State varchar(255), var_CO_Country varchar(255), var_CO_ATo varchar(255), var_CO_LeadSource varchar(255), var_CO_ReportTo varchar(255), var_CO_CBy varchar(255),var_CO_CustID varchar(255),var_CO_IsApproved varchar(255),var_CO_DOB varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_lastid VARCHAR(100) DEFAULT "";
	SET var_lastid = CRM_FUN_CONFIG_GENERATE_ID('CO');
	IF var_lastid <> '' THEN
		INSERT INTO `crm_contact` (
			`CO_ID`,
			`CO_Salutation`,
			`CO_FirstName`,
			`CO_LastName`,
			`CO_Phone`,
			`CO_Mobile`,
			`CO_Email`,
			`CO_Title`,
			`CO_Department`,
			`CO_No`,
			`CO_Street`,
			`CO_Village`,
			`CO_Commune`,
			`CO_District`,
			`CO_City`,
			`CO_State`,
			`CO_Country`,
			`CO_ATo`,
			`CO_LeadSource`,
			`CO_ReportTo`,
			`CO_CBy`,
			`CO_CDate`,
			`CO_CustID`,
			`CO_IsApproved`,
			`CO_DOB`
		)
		VALUES
			(
				var_lastid,
				var_CO_Salutation,
				var_CO_FirstName,
				var_CO_LastName,
				var_CO_Phone,
				var_CO_Mobile,
				var_CO_Email,
				var_CO_Title,
				var_CO_Department,
				var_CO_No,
				var_CO_Street,
				var_CO_Village,
				var_CO_Commune,
				var_CO_District,
				var_CO_City,
				var_CO_State,
				var_CO_Country,
				var_CO_ATo,
				var_CO_LeadSource,
				var_CO_ReportTo,
				var_CO_CBy,
				NOW(),
				var_CO_CustID,
				var_CO_IsApproved,
				var_CO_DOB
			);
	END IF;
	SELECT var_lastid as 'lastId', CRM_FUN_CONFIG_IMG_PATH() AS 'IMG_PATH';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CONTACT_BY_RELATED`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CONTACT_BY_RELATED`(custid varchar(100), var_type varchar(200))
    DETERMINISTIC
BEGIN
	IF var_type = 'Opp' THEN
		CALL CRM_PRO_OPP_LOAD_BY_CONTACT(custid);
	ELSEIF var_type = 'Case' THEN
		CALL CRM_PRO_CASE_LOAD_BY_CONTACT(custid);	
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CONTACT_COUNT_RELATED`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CONTACT_COUNT_RELATED`(custid varchar(150))
    DETERMINISTIC
BEGIN
	SELECT 
		(SELECT COUNT(*) FROM crm_opportunity_contact WHERE OPCON_CONID = custid) 'cOpp',
		(SELECT COUNT(*) FROM crm_case WHERE cs_contactid = custid) 'cCase';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CONTACT_DELETE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CONTACT_DELETE`(IN `contactId` varchar(11))
    DETERMINISTIC
BEGIN

	DELETE FROM crm_call WHERE crm_call.CL_RToID = contactId;
	DELETE FROM crm_meeting WHERE crm_meeting.M_RToID = contactId;
	DELETE FROM crm_task WHERE crm_task.TA_RToID = contactId;
	DELETE FROM crm_event WHERE crm_event.EV_RToID = contactId;
	DELETE FROM crm_note WHERE crm_note.N_RToID = contactId;
	DELETE FROM crm_colllaboration_tags WHERE crm_colllaboration_tags.collapId = (SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = contactId); 
	DELETE FROM crm_collaboration_details WHERE crm_collaboration_details.PostID = (SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = contactId);
	DELETE FROM crm_collaboration WHERE crm_collaboration.CB_RToID = contactId;
	DELETE FROM crm_opportunity_contact WHERE crm_opportunity_contact.OPCON_CONID = contactId;
	UPDATE crm_case SET crm_case.CS_ContactID = NULL WHERE crm_case.CS_ContactID = contactId;
	UPDATE crm_contact SET CO_ReportTo = NULL WHERE CO_ReportTo = contactId;
	DELETE FROM crm_contact WHERE crm_contact.CO_ID = contactId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CONTACT_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CONTACT_GET_BY_ID`(var_conId varchar(150))
    DETERMINISTIC
BEGIN
	SELECT c.CO_ID 'conID', c.CO_Salutation 'conSalutation', c.CO_FirstName 'conFirstname', c.CO_LastName 'conLastname', c.CO_Phone 'conPhone', c.CO_Mobile 'conMobile', c.CO_Email 'conEmail',
			 c.CO_Title 'conTitle', c.CO_Department 'conDepartment', c.CO_No 'conNo', c.CO_Street 'conStreet', c.CO_Village 'conVillage', c.CO_Commune 'conCommune', c.CO_District 'conDistrict',
       c.CO_City 'conCity', c.CO_State 'conState', c.CO_Country 'conCountry', c.CO_DOB 'conDob', COALESCE(c.CO_ATo,'') 'conAssignToId', COALESCE(u.var_name,'') 'conAssignToName',
			 cus.var_id 'custId', COALESCE(cus.var_name,'') 'custName', c.CO_LeadSource 'conLeadSourceId', ls.LS_Name 'conLeadSourceName', 
       cg.CO_ID 'conReportToId', CONCAT(COALESCE(cg.CO_Salutation,''),'. ',COALESCE(cg.CO_FirstName,''),' ', COALESCE(cg.CO_LastName,'')) 'conReportToName',
			 c.CO_CBy 'conCreateBy', uc.var_name 'conCreateByName'
	FROM crm_contact c
	LEFT JOIN ame_user u ON u.var_id = c.CO_ATo
	LEFT JOIN ame_mt_cus cus ON cus.var_id = c.CO_CustID
	LEFT JOIN crm_lead_source ls ON ls.LS_ID = c.CO_LeadSource
	LEFT JOIN crm_contact cg ON c.CO_ReportTo = cg.CO_ID
	LEFT JOIN ame_user uc ON uc.var_id = c.CO_CBy
	WHERE c.CO_ID = var_conId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CONTACT_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CONTACT_LIST`(IN `userId` varchar(50))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT ame_user.var_crm_role FROM ame_user WHERE var_id = userId);
	IF roleType = 1 THEN
		SELECT 
			con.CO_ID conID, 
			con.CO_FirstName conFirstName,
			con.CO_LastName conLastName,
			con.CO_Salutation conSalutation,
			con.CO_Phone conPhone,
			con.CO_Mobile conMobile,
			con.CO_Email conEmail,
			con.CO_Title conTitle,
			con.CO_Department conDepartment,
			COALESCE(con.CO_ATo,'') userId,
			COALESCE((SELECT var_name FROM ame_user WHERE var_id = con.CO_ATo),'') username,
			con.CO_LeadSource sourceID,
			(SELECT LS_Name FROM crm_lead_source WHERE LS_ID = con.CO_LeadSource) sourceName,
			con.CO_ReportTo reportToId,
			(SELECT CONCAT(CO_Salutation," ",CO_FirstName," ",CO_LastName) FROM crm_contact WHERE CO_ID = con.CO_ReportTo) reportToName,
			con.CO_CBy conCreateBy,
			(SELECT var_name FROM ame_user WHERE var_id = con.CO_CBy) conCreateByName,
			con.CO_CDate conCreateDate,
			con.CO_MBy conModifyBy,
			CAST(con.CO_MDate AS date) modifyDate,
			con.CO_CustID custID, 
			COALESCE((SELECT c.var_name FROM ame_mt_cus c WHERE c.var_id = con.CO_CustID),'') custName,
			con.CO_IsApproved isApproved
		FROM 
			crm_contact con
		ORDER BY con.CO_ID DESC;
	ELSE
		SELECT 
			con.CO_ID conID, 
			con.CO_FirstName conFirstName,
			con.CO_LastName conLastName,
			con.CO_Salutation conSalutation,
			con.CO_Phone conPhone,
			con.CO_Mobile conMobile,
			con.CO_Email conEmail,
			con.CO_Title conTitle,
			con.CO_Department conDepartment,
			con.CO_ATo userId,
			COALESCE((SELECT var_name FROM ame_user WHERE var_id = con.CO_ATo),'') username,
			con.CO_LeadSource sourceID,
			(SELECT LS_Name FROM crm_lead_source WHERE LS_ID = con.CO_LeadSource) sourceName,
			con.CO_ReportTo reportToId,
			(SELECT CONCAT(CO_Salutation," ",CO_FirstName," ",CO_LastName) FROM crm_contact WHERE CO_ID = con.CO_ReportTo) reportToName,
			con.CO_CBy conCreateBy,
			(SELECT var_name FROM ame_user WHERE var_id = con.CO_CBy) conCreateByName,
			con.CO_CDate conCreateDate,
			con.CO_MBy conModifyBy,
			CAST(con.CO_MDate AS date) modifyDate,
			con.CO_CustID custID, 
			(SELECT c.var_name FROM ame_mt_cus c WHERE c.var_id = con.CO_CustID) custName,
			con.CO_IsApproved isApproved
		FROM 
			crm_contact con
		WHERE con.CO_CBy = userId OR con.CO_ATo = userId
		ORDER BY con.CO_ID DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CONTACT_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CONTACT_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT CO_ID conID, CONCAT(COALESCE(CO_Salutation,''),'. ',COALESCE(CO_FirstName,''),' ', COALESCE(CO_LastName,'')) fullName, CO_Salutation conSalutation, CO_FirstName conFirstname, CO_LastName conLastname 
				, COALESCE(CO_CustID,'') 'custId'
		FROM crm_contact;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CONTACT_PARENT_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CONTACT_PARENT_LOAD`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT CO_ID conID, CONCAT(COALESCE(CO_Salutation,''),'. ',COALESCE(CO_FirstName,''),' ', COALESCE(CO_LastName,'')) fullName, CO_Salutation conSalutation, CO_FirstName conFirstname, CO_LastName conLastname 
	FROM crm_contact WHERE COALESCE(`CO_ReportTo`,'') = '';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CONTACT_START_UP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CONTACT_START_UP`(contact_id  varchar(255) ,`userId` varchar(255))
    DETERMINISTIC
BEGIN
	CALL CRM_PRO_CUSTOMER_LOAD(userId);
	CALL CRM_PRO_USER_LIST_COM(userId);
	CALL CRM_PRO_LEAD_SOURCE_LOAD();
	CALL CRM_PRO_CONTACT_PARENT_LOAD(userId);
	IF contact_id <> '' THEN 
		CALL CRM_PRO_CONTACT_GET_BY_ID(contact_id);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CONTACT_VIEW`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CONTACT_VIEW`(objectId varchar(150), userid varchar(150))
    DETERMINISTIC
BEGIN
	SELECT COALESCE((SELECT COUNT(*) FROM crm_call WHERE CL_RToID = objectId),0) as cCall,
         COALESCE((SELECT COUNT(*) FROM crm_meeting WHERE M_RToID = objectId),0) as cMeeting,
				 COALESCE((SELECT COUNT(*) FROM crm_task WHERE TA_RToID = objectId),0) as cTask,
				 COALESCE((SELECT COUNT(*) FROM crm_event WHERE EV_RToID = objectId),0) as cEvent ;
	CALL CRM_PRO_CONTACT_GET_BY_ID(objectId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CURRENCY_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CURRENCY_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT var_id 'curId', var_name 'curName', tin_default 'default' FROM ame_mt_cur WHERE tin_inactive = 0; 
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUSTOMER_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUSTOMER_LIST`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT var_crm_role FROM ame_user WHERE var_id = userId);
	IF roleType = 1 THEN
		SELECT c.var_id 'custID', c.var_name 'custName', c.var_tel1 'custTel1', c.var_tel2 'custTel2', c.var_email 'custEmail',
			 COALESCE(g.var_id,'') 'groupId', COALESCE(g.var_name,'') 'groupName', COALESCE(pc.var_id,'') 'priceCode', COALESCE(pc.var_name,'') 'priceDes',COALESCE(var_crm_approval,'') 'approval',
       COALESCE(var_crm_latitude,'') 'latitude', COALESCE(var_crm_longitude,'') 'longitude'
		FROM ame_mt_cus c
		LEFT JOIN ame_mt_pri_cod pc ON c.var_pricecode = pc.var_id
		LEFT JOIN ame_mt_cus_gro g ON c.var_groupid = g.var_id
		ORDER BY c.var_id DESC;
	ELSE
		SELECT c.var_id 'custID', c.var_name 'custName', c.var_tel1 'custTel1', c.var_tel2 'custTel2', c.var_email 'custEmail',
			 COALESCE(g.var_id,'') 'groupId', COALESCE(g.var_name,'') 'groupName', COALESCE(pc.var_id,'') 'priceCode', COALESCE(pc.var_name,'') 'priceDes',COALESCE(var_crm_approval,'') 'approval',
       COALESCE(var_crm_latitude,'') 'latitude', COALESCE(var_crm_longitude,'') 'longitude'
		FROM ame_mt_cus c
		LEFT JOIN ame_mt_pri_cod pc ON c.var_pricecode = pc.var_id
		LEFT JOIN ame_mt_cus_gro g ON c.var_groupid = g.var_id
		WHERE c.var_id IN (CRM_PRO_CUST_BY_USER_LOAD(userId))
		ORDER BY c.var_id DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUSTOMER_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUSTOMER_LOAD`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT var_crm_role FROM ame_user WHERE var_id = userId);
	IF roleType = 1 THEN
		SELECT c.var_id 'custID', c.var_name 'custName', c.var_tel1 'custTel1', c.var_tel2 'custTel2', c.var_pricecode 'priceCode'
		FROM ame_mt_cus c
		ORDER BY c.var_id DESC;
	ELSE
		SELECT c.var_id 'custID', c.var_name 'custName', c.var_tel1 'custTel1', c.var_tel2 'custTel2',c.var_pricecode 'priceCode'
		FROM ame_mt_cus c
		WHERE c.var_id IN (CRM_PRO_CUST_BY_USER_LOAD(userId))
		ORDER BY c.var_id DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUSTOMER_NOT_APPROVE_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUSTOMER_NOT_APPROVE_LIST`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT var_crm_role FROM ame_user WHERE var_id = userId);
	IF roleType = 1 THEN
		SELECT c.var_id 'custID', c.var_name 'custName', c.var_tel1 'custTel1', c.var_tel2 'custTel2', c.var_email 'custEmail',
			 COALESCE(g.var_id,'') 'groupId', COALESCE(g.var_name,'') 'groupName', COALESCE(pc.var_id,'') 'priceCode', COALESCE(pc.var_name,'') 'priceDes',COALESCE(var_crm_approval,'') 'approval',
       COALESCE(var_crm_latitude,'') 'latitude', COALESCE(var_crm_longitude,'') 'longitude'
		FROM crm_customer c
		LEFT JOIN ame_mt_pri_cod pc ON c.var_pricecode = pc.var_id
		LEFT JOIN ame_mt_cus_gro g ON c.var_groupid = g.var_id
		ORDER BY c.var_id DESC;
	ELSE
		SELECT c.var_id 'custID', c.var_name 'custName', c.var_tel1 'custTel1', c.var_tel2 'custTel2', c.var_email 'custEmail',
			 COALESCE(g.var_id,'') 'groupId', COALESCE(g.var_name,'') 'groupName', COALESCE(pc.var_id,'') 'priceCode', COALESCE(pc.var_name,'') 'priceDes',COALESCE(var_crm_approval,'') 'approval',
       COALESCE(var_crm_latitude,'') 'latitude', COALESCE(var_crm_longitude,'') 'longitude'
		FROM crm_customer c
		LEFT JOIN ame_mt_pri_cod pc ON c.var_pricecode = pc.var_id
		LEFT JOIN ame_mt_cus_gro g ON c.var_groupid = g.var_id
		WHERE c.var_id IN (CRM_PRO_CUST_BY_USER_LOAD(userId))
		ORDER BY c.var_id DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUST_ADD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUST_ADD`(var_id varchar(50), var_name varchar(255), var_name_other varchar(255), var_name_con varchar(255),  var_tel1 varchar(255), var_tel2 varchar(255), var_fax varchar(255), var_web varchar(255), var_email varchar(255), var_addr varchar(255),var_desc varchar(255),var_pricecode  varchar(255),var_groupid varchar(255),var_accid varchar(255),var_cur varchar(255),var_img varchar(255),var_addr1 varchar(255),var_addr2 varchar(255),var_addr3 varchar(255),var_addr4 varchar(255),var_addr5 varchar(255),var_addr6 varchar(255),var_addr7 varchar(255),crm_latitude varchar(255),crm_longitude varchar(255), crm_approval varchar(100),crm_facebook  varchar(255),crm_line  varchar(255),crm_viber  varchar(255),crm_whatapp  varchar(255),crm_industry integer,crm_type integer, userId varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_lastid VARCHAR(100) DEFAULT "";
	DECLARE var_isRequire INTEGER(1) UNSIGNED DEFAULT 1;
	DECLARE int_exist INTEGER UNSIGNED DEFAULT 0;
	DECLARE var_msgstatus VARCHAR(100) DEFAULT "EXISTS";
	SET int_exist = (SELECT COUNT(*) FROM ame_mt_cus WHERE `ame_mt_cus`.`var_name` = var_name);
	IF int_exist = 0 THEN
		SET var_msgstatus = "NONE";
		SET var_lastid = CRM_FUN_CHECK_EXIST_ID('MT-CUS');
		SET var_isRequire = COALESCE((SELECT RE_IsRequire FROM crm_module_require_approval WHERE RE_Module = 'Customer'),0);
		IF var_isRequire = 0 THEN
			INSERT INTO `ame_mt_cus` (
				`var_id`, 
				`var_name`, 
				`var_name_other`, 
				`var_name_con`, 
				`var_tel1`, 
				`var_tel2`, 
				`var_fax`, 
				`var_web`, 
				`var_email`, 
				`var_addr`, 
				`var_desc`, 
				`var_pricecode`, 
				`var_groupid`, 
				`var_accid`, 
				`var_cur`, 
				`var_img`, 
				`var_addr1`, 
				`var_addr2`, 
				`var_addr3`, 
				`var_addr4`, 
				`var_addr5`, 
				`var_addr6`, 
				`var_addr7`, 
				`var_crm_latitude`, 
				`var_crm_longitude`, 
				`var_crm_approval`,
				`var_crm_facebook`,
				`var_crm_line`,
				`var_crm_viber`,
				`var_crm_whatapp`,
				`var_crm_industry`,
				`var_crm_type`,
				`var_create`,
				`dat_create`
			) 
			VALUES (
				var_lastid, 
				var_name,
				var_name_other,
				var_name_con,
				var_tel1,
				var_tel2,
				var_fax,
				var_web,
				var_email,
				var_addr,
				var_desc,
				var_pricecode, 
				var_groupid, 
				'110000', 
				var_cur, 
				IF(var_img = '', '', CONCAT(var_lastid,'.',var_img)),
				var_addr1, 
				var_addr2, 
				var_addr3, 
				var_addr4, 
				var_addr5, 
				var_addr6, 
				var_addr7, 
				crm_latitude, 
				crm_longitude, 
				'Approved',
				crm_facebook,
				crm_line,
				crm_viber,
				crm_whatapp,
				crm_industry,
				crm_type,
				userId,
				NOW()
			);
		ELSE			
			SET int_exist = (SELECT COUNT(*) FROM crm_customer WHERE `crm_customer`.`var_name` = var_name);
			IF int_exist = 0 THEN
				INSERT INTO `crm_customer` (
					`var_id`, 
					`var_name`, 
					`var_name_other`, 
					`var_name_con`, 
					`var_tel1`, 
					`var_tel2`, 
					`var_fax`, 
					`var_web`, 
					`var_email`, 
					`var_addr`, 
					`var_desc`, 
					`var_pricecode`, 
					`var_groupid`, 
					`var_accid`, 
					`var_cur`, 
					`var_img`, 
					`var_addr1`, 
					`var_addr2`, 
					`var_addr3`, 
					`var_addr4`, 
					`var_addr5`, 
					`var_addr6`, 
					`var_addr7`, 
					`var_crm_latitude`, 
					`var_crm_longitude`, 
					`var_crm_approval`,
					`var_crm_facebook`,
					`var_crm_line`,
					`var_crm_viber`,
					`var_crm_whatapp`,
					`var_crm_industry`,
					`var_crm_type`,
					`var_create`,
					`dat_create`,
					`tin_editable`
				) 
				VALUES (
					var_lastid, 
					var_name,
					var_name_other,
					var_name_con,
					var_tel1,
					var_tel2,
					var_fax,
					var_web,
					var_email,
					var_addr,
					var_desc,
					var_pricecode, 
					var_groupid, 
					'110000', 
					var_cur, 
					IF(var_img = '', '', CONCAT(var_lastid,'.',var_img)), 
					var_addr1, 
					var_addr2, 
					var_addr3, 
					var_addr4, 
					var_addr5, 
					var_addr6, 
					var_addr7, 
					crm_latitude, 
					crm_longitude, 
					'Requested',
					crm_facebook,
					crm_line,
					crm_viber,
					crm_whatapp,
					crm_industry,
					crm_type,
					userId,
					NOW(),
					1
				);				
				CALL ATS_PRO_RequestAuthEmp(var_lastid, userId, 'Customer');
			ELSE
				SET var_msgstatus = "EXISTS";
			END IF;
		END IF;
	END IF;
	SELECT var_lastid as 'lastId', CRM_FUN_CONFIG_IMG_PATH() AS 'IMG_PATH', var_isRequire as 'isRequired', var_msgstatus as 'MSG';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUST_BY_RELATED`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUST_BY_RELATED`(custid varchar(100), var_type varchar(200))
    DETERMINISTIC
BEGIN
	IF var_type = 'Opp' THEN
		CALL CRM_PRO_OPP_LOAD_BY_CUST(custid);
	ELSEIF var_type = 'Case' THEN
		CALL CRM_PRO_CASE_LOAD_BY_CUST(custid);
	ELSEIF var_type = 'Contact' THEN
		CALL CRM_PRO_CONTACT_LOAD_BY_CUST(custid);
	ELSEIF var_type = 'SO' THEN 
		CALL CRM_PRO_SO_LOAD_BY_CUST(custid);
	ELSEIF var_type = 'QO' THEN
		CALL CRM_PRO_QO_LOAD_BY_CUST(custid);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUST_BY_USER_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUST_BY_USER_LOAD`(userId varchar(255))
    DETERMINISTIC
BEGIN
	SELECT var_cusid FROM ame_mt_cus_emp WHERE var_empid = CRM_FUN_GET_EMP_ID(userId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUST_COUNT_RELATED`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUST_COUNT_RELATED`(custid varchar(150))
    DETERMINISTIC
BEGIN
	SELECT 
		(SELECT COUNT(*) FROM crm_opportunity WHERE OP_CustID = custid) 'cOpp',
		(SELECT COUNT(*) FROM crm_contact WHERE CO_CustID = custid) 'cContact',
		(SELECT COUNT(*) FROM crm_case WHERE cs_custid = custid) 'cCase',
		(SELECT COUNT(*) FROM ame_ar_so WHERE var_cusid = custid) 'cSO',
		(SELECT COUNT(*) FROM ame_ar_quo WHERE var_cusid = custid) 'cQO';	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUST_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUST_GET_BY_ID`(var_custid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT c.var_id 'custId', c.var_name 'custName', c.var_name_other 'custOtherName', c.var_name_con 'custContact',c.var_tel1 'tel1', c.var_tel2 'tel2', c.var_email 'email',
       c.var_fax 'fax', c.var_web 'website', c.var_addr 'address', c.var_desc 'desc', c.var_pricecode 'priceCode', p.var_name 'priceDes',c.var_groupid 'groupId', g.var_name 'groupName',
			 c.var_accid 'accId', a.var_name 'accName', c.var_term 'term', c.var_cur 'currency',cur.var_name 'curName', c.var_img 'image',
       c.var_addr1 'addr1', c.var_addr2 'addr2', c.var_addr3 'addr3', c.var_addr4 'addr4', c.var_addr5 'addr5', c.var_addr6 'addr6', c.var_addr7 'addr7',
			 c.dou_limit 'limit', c.tin_inactive 'inactive', c.var_crm_latitude 'latiude', c.var_crm_longitude 'longitude', c.var_crm_approval 'approval',
			 c.var_crm_industry 'industry', i.I_Name 'industryName', c.var_crm_type 'type', ca.AT_Name 'typeName',c.var_crm_facebook 'facebook', c.var_crm_line 'line',
       c.var_crm_viber 'viber', c.var_crm_whatapp 'whatapp', 
			 CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"num":"',COALESCE(ship.var_num,''),'", "id":"',COALESCE(ship.var_id,''),'" ,"name":"',COALESCE(ship.var_name,''),'", "addr":"', 
                  COALESCE(ship.var_addr,''),'", "addr1":"', COALESCE(ship.var_addr1,''),'", "addr2":"', COALESCE(ship.var_addr2,''),'", "addr3":"', 
                  COALESCE(ship.var_addr3,''),'", "addr4":"', COALESCE(ship.var_addr4,''),'", "addr5":"', COALESCE(ship.var_addr5,''),'", "addr6":"', 
                  COALESCE(ship.var_addr6,''),'", "addr7":"', COALESCE(ship.var_addr7,''),'", "latitude":"',COALESCE(ship.var_crm_latitude,''),'", "longitude":"',
                  COALESCE(ship.var_crm_longitude,''),'", "isDefault":',COALESCE(ship.tin_default,0),'}')) FROM ame_mt_ship_addr ship WHERE ship.var_num = var_custid AND ship.var_type = "MT-CUS" ORDER BY var_id),']') 'shipAddresses',
       CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"empId":"',COALESCE(emp.var_id,""),'", "empName":"',COALESCE(emp.var_name,""),'"}')) FROM ame_mt_cus_emp cusEmp LEFT JOIN ame_mt_emp emp ON emp.var_id=cusEmp.var_empid WHERE cusEmp.var_cusid = var_custid),']') as 'employees'
	FROM ame_mt_cus c
	LEFT JOIN ame_mt_cus_gro g ON g.var_id = c.var_groupid
	LEFT JOIN ame_mt_cur cur ON cur.var_id = c.var_cur
	LEFT JOIN ame_mt_pri_cod p ON c.var_pricecode = p.var_id
	LEFT JOIN ame_mt_acc a ON a.var_id = c.var_accid
	LEFT JOIN crm_industry i ON c.var_crm_industry = i.I_ID
	LEFT JOIN crm_account_type ca ON c.var_crm_type = ca.AT_ID
	WHERE c.var_id = var_custid
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUST_IDLE_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUST_IDLE_LIST`(IN `moduleType` varchar(255),IN `startDate` varchar(255),IN `endDate` varchar(255))
    DETERMINISTIC
BEGIN
	
	IF moduleType = 'Quotation' THEN
		SELECT 
			c.var_id 'custId',
			c.var_name 'custName',
			c.var_addr 'custAddress',
			c.var_pricecode 'priceCode',
			COALESCE(pc.var_name,'') 'priceDes',
			COALESCE(c.var_groupid,'') 'groupId',
			COALESCE(cg.var_name,'') 'groupName',
			c.var_cur 'currency',
			COALESCE(cur.var_name,'') 'curName',
			COALESCE((SELECT GROUP_CONCAT(CONCAT(' ',emp.var_name)) FROM ame_mt_cus_emp cus_emp  LEFT JOIN ame_mt_emp emp ON cus_emp.var_empid = emp.var_id WHERE cus_emp.var_cusid = c.var_id ),'') 'empName'
		FROM ame_mt_cus c 
		LEFT JOIN ame_mt_pri_cod pc ON c.var_pricecode = pc.var_id
		LEFT JOIN ame_mt_cus_gro cg ON c.var_groupid = cg.var_id
		LEFT JOIN ame_mt_cur cur ON c.var_cur = cur.var_id
		WHERE c.var_id NOT IN (SELECT DISTINCT q.var_cusid from ame_ar_quo q WHERE DATE(q.dat_create) BETWEEN DATE(startDate) AND DATE(endDate));
	ELSEIF moduleType = 'Sale Order' THEN
		SELECT 
			c.var_id 'custId',
			c.var_name 'custName',
			c.var_addr 'custAddress',
			c.var_pricecode 'priceCode',
			COALESCE(pc.var_name,'') 'priceDes',
			COALESCE(c.var_groupid,'') 'groupId',
			COALESCE(cg.var_name,'') 'groupName',
			c.var_cur 'currency',
			COALESCE(cur.var_name,'') 'curName',
			COALESCE((SELECT GROUP_CONCAT(CONCAT(' ',emp.var_name)) FROM ame_mt_cus_emp cus_emp  LEFT JOIN ame_mt_emp emp ON cus_emp.var_empid = emp.var_id WHERE cus_emp.var_cusid = c.var_id ),'') 'empName'
		FROM ame_mt_cus c 
		LEFT JOIN ame_mt_pri_cod pc ON c.var_pricecode = pc.var_id
		LEFT JOIN ame_mt_cus_gro cg ON c.var_groupid = cg.var_id
		LEFT JOIN ame_mt_cur cur ON c.var_cur = cur.var_id
		WHERE c.var_id NOT IN (SELECT DISTINCT q.var_cusid from ame_ar_so q WHERE DATE(q.dat_create) BETWEEN DATE(startDate) AND DATE(endDate));

	ELSEIF moduleType = 'Sale Invoice' THEN
		SELECT 
			c.var_id 'custId',
			c.var_name 'custName',
			c.var_addr 'custAddress',
			c.var_pricecode 'priceCode',
			COALESCE(pc.var_name,'') 'priceDes',
			COALESCE(c.var_groupid,'') 'groupId',
			COALESCE(cg.var_name,'') 'groupName',
			c.var_cur 'currency',
			COALESCE(cur.var_name,'') 'curName',
			COALESCE((SELECT GROUP_CONCAT(CONCAT(' ',emp.var_name)) FROM ame_mt_cus_emp cus_emp  LEFT JOIN ame_mt_emp emp ON cus_emp.var_empid = emp.var_id WHERE cus_emp.var_cusid = c.var_id ),'') 'empName'
		FROM ame_mt_cus c 
		LEFT JOIN ame_mt_pri_cod pc ON c.var_pricecode = pc.var_id
		LEFT JOIN ame_mt_cus_gro cg ON c.var_groupid = cg.var_id
		LEFT JOIN ame_mt_cur cur ON c.var_cur = cur.var_id
		WHERE c.var_id NOT IN (SELECT DISTINCT q.var_cusid from ame_ar_in q WHERE DATE(q.dat_create) BETWEEN DATE(startDate) AND DATE(endDate));
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUST_LIST_APPRO_PANDING`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUST_LIST_APPRO_PANDING`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT var_crm_role FROM ame_user WHERE var_id = userId);
	IF roleType = 1 THEN
		SELECT c.var_id 'custID', c.var_name 'custName', c.var_tel1 'custTel1', c.var_tel2 'custTel2', c.var_email 'custEmail',
			 COALESCE(g.var_id,'') 'groupId', COALESCE(g.var_name,'') 'groupName', COALESCE(pc.var_id,'') 'priceCode', COALESCE(pc.var_name,'') 'priceDes',COALESCE(var_crm_approval,'') 'approval',
       COALESCE(var_crm_latitude,'') 'latitude', COALESCE(var_crm_longitude,'') 'longitude'
		FROM ame_mt_cus c
		LEFT JOIN ame_mt_pri_cod pc ON c.var_pricecode = pc.var_id
		LEFT JOIN ame_mt_cus_gro g ON c.var_groupid = g.var_id
		ORDER BY c.var_id DESC;
	
		SELECT c.var_id 'custID', c.var_name 'custName', c.var_tel1 'custTel1', c.var_tel2 'custTel2', c.var_email 'custEmail',
			 COALESCE(g.var_id,'') 'groupId', COALESCE(g.var_name,'') 'groupName', COALESCE(pc.var_id,'') 'priceCode', COALESCE(pc.var_name,'') 'priceDes',COALESCE(var_crm_approval,'') 'approval',
       COALESCE(var_crm_latitude,'') 'latitude', COALESCE(var_crm_longitude,'') 'longitude',COALESCE(c.tin_editable,1) 'editable'
		FROM crm_customer c
		LEFT JOIN ame_mt_pri_cod pc ON c.var_pricecode = pc.var_id
		LEFT JOIN ame_mt_cus_gro g ON c.var_groupid = g.var_id
		ORDER BY c.var_id DESC;

	ELSE
		SELECT c.var_id 'custID', c.var_name 'custName', c.var_tel1 'custTel1', c.var_tel2 'custTel2', c.var_email 'custEmail',
			 COALESCE(g.var_id,'') 'groupId', COALESCE(g.var_name,'') 'groupName', COALESCE(pc.var_id,'') 'priceCode', COALESCE(pc.var_name,'') 'priceDes',COALESCE(var_crm_approval,'') 'approval',
       COALESCE(var_crm_latitude,'') 'latitude', COALESCE(var_crm_longitude,'') 'longitude'
		FROM ame_mt_cus c
		LEFT JOIN ame_mt_pri_cod pc ON c.var_pricecode = pc.var_id
		LEFT JOIN ame_mt_cus_gro g ON c.var_groupid = g.var_id
		WHERE c.var_id IN (CRM_PRO_CUST_BY_USER_LOAD(userId))
		ORDER BY c.var_id DESC;

		SELECT c.var_id 'custID', c.var_name 'custName', c.var_tel1 'custTel1', c.var_tel2 'custTel2', c.var_email 'custEmail',
			 COALESCE(g.var_id,'') 'groupId', COALESCE(g.var_name,'') 'groupName', COALESCE(pc.var_id,'') 'priceCode', COALESCE(pc.var_name,'') 'priceDes',COALESCE(var_crm_approval,'') 'approval',
       COALESCE(var_crm_latitude,'') 'latitude', COALESCE(var_crm_longitude,'') 'longitude',COALESCE(c.tin_editable,1) 'editable'
		FROM crm_customer c
		LEFT JOIN ame_mt_pri_cod pc ON c.var_pricecode = pc.var_id
		LEFT JOIN ame_mt_cus_gro g ON c.var_groupid = g.var_id
		WHERE c.var_id IN (CRM_PRO_CUST_BY_USER_LOAD(userId))
		ORDER BY c.var_id DESC;
		
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUST_PENDING_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUST_PENDING_GET_BY_ID`(var_custid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT c.var_id 'custId', c.var_name 'custName', c.var_name_other 'custOtherName', c.var_name_con 'custContact',c.var_tel1 'tel1', c.var_tel2 'tel2', c.var_email 'email',
       c.var_fax 'fax', c.var_web 'website', c.var_addr 'address', c.var_desc 'desc', c.var_pricecode 'priceCode', p.var_name 'priceDes',c.var_groupid 'groupId', g.var_name 'groupName',
			 c.var_accid 'accId', a.var_name 'accName', c.var_term 'term', c.var_cur 'currency',cur.var_name 'curName', c.var_img 'image',
       c.var_addr1 'addr1', c.var_addr2 'addr2', c.var_addr3 'addr3', c.var_addr4 'addr4', c.var_addr5 'addr5', c.var_addr6 'addr6', c.var_addr7 'addr7',
			 c.dou_limit 'limit', c.tin_inactive 'inactive', c.var_crm_latitude 'latiude', c.var_crm_longitude 'longitude', c.var_crm_approval 'approval',
			 c.var_crm_industry 'industry', i.I_Name 'industryName', c.var_crm_type 'type', ca.AT_Name 'typeName',c.var_crm_facebook 'facebook', c.var_crm_line 'line',
       c.var_crm_viber 'viber', c.var_crm_whatapp 'whatapp', 
			 CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"num":"',COALESCE(ship.var_num,''),'", "id":"',COALESCE(ship.var_id,''),'" ,"name":"',COALESCE(ship.var_name,''),'", "addr":"', 
                  COALESCE(ship.var_addr,''),'", "addr1":"', COALESCE(ship.var_addr1,''),'", "addr2":"', COALESCE(ship.var_addr2,''),'", "addr3":"', 
                  COALESCE(ship.var_addr3,''),'", "addr4":"', COALESCE(ship.var_addr4,''),'", "addr5":"', COALESCE(ship.var_addr5,''),'", "addr6":"', 
                  COALESCE(ship.var_addr6,''),'", "addr7":"', COALESCE(ship.var_addr7,''),'", "latitude":"',COALESCE(ship.var_crm_latitude,''),'", "longitude":"',
                  COALESCE(ship.var_crm_longitude,''),'", "isDefault":',COALESCE(ship.tin_default,0),'}')) FROM ame_mt_ship_addr ship WHERE ship.var_num = var_custid AND ship.var_type = "MT-CUS" ORDER BY var_id),']') 'shipAddresses',
       CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"empId":"',COALESCE(emp.var_id,""),'", "empName":"',COALESCE(emp.var_name,""),'"}')) FROM ame_mt_cus_emp cusEmp LEFT JOIN ame_mt_emp emp ON emp.var_id=cusEmp.var_empid WHERE cusEmp.var_cusid = var_custid),']') as 'employees'
	FROM crm_customer c
	LEFT JOIN ame_mt_cus_gro g ON g.var_id = c.var_groupid
	LEFT JOIN ame_mt_cur cur ON cur.var_id = c.var_cur
	LEFT JOIN ame_mt_pri_cod p ON c.var_pricecode = p.var_id
	LEFT JOIN ame_mt_acc a ON a.var_id = c.var_accid
	LEFT JOIN crm_industry i ON c.var_crm_industry = i.I_ID
	LEFT JOIN crm_account_type ca ON c.var_crm_type = ca.AT_ID
	WHERE c.var_id = var_custid
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUST_UPDATE_APPROVAL`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUST_UPDATE_APPROVAL`(var_id varchar(50), var_name varchar(255), var_name_other varchar(255), var_name_con varchar(255),  var_tel1 varchar(255), var_tel2 varchar(255), var_fax varchar(255), var_web varchar(255), var_email varchar(255), var_addr varchar(255),var_desc varchar(255),var_pricecode  varchar(255),var_groupid varchar(255),var_accid varchar(255),var_cur varchar(255),var_img varchar(255),var_addr1 varchar(255),var_addr2 varchar(255),var_addr3 varchar(255),var_addr4 varchar(255),var_addr5 varchar(255),var_addr6 varchar(255),var_addr7 varchar(255),crm_latitude varchar(255),crm_longitude varchar(255), crm_approval varchar(100),crm_facebook  varchar(255),crm_line  varchar(255),crm_viber  varchar(255),crm_whatapp  varchar(255),crm_industry integer,crm_type integer, userId varchar(255))
    DETERMINISTIC
BEGIN		
	DECLARE int_exist INTEGER UNSIGNED DEFAULT 0;
	DECLARE var_msgstatus VARCHAR(100) DEFAULT "EXISTS";
	DECLARE oldImage VARCHAR(100) DEFAULT "";
	SET int_exist = (SELECT COUNT(*) FROM `ame_mt_cus` WHERE `ame_mt_cus`.`var_name` = var_name AND `ame_mt_cus`.`var_id` <> var_id);
	SELECT COALESCE(`ame_mt_cus`.`var_img`,'') INTO oldImage FROM `ame_mt_cus` WHERE  `ame_mt_cus`.`var_id` = var_id;
	IF int_exist = 0 THEN
		SET var_msgstatus = "NONE";
		UPDATE `ame_mt_cus`
		SET
		 `var_name` = var_name,
		 `var_name_other` = var_name_other,
		 `var_name_con` = var_name_con,
		 `var_tel1` = var_tel1,
		 `var_tel2` = var_tel2,
		 `var_fax` = var_fax,
		 `var_web` = var_web,
		 `var_email` = var_email,
		 `var_addr` = var_addr,
		 #`var_desc` = '',
		 `var_pricecode` = var_pricecode,
		 `var_groupid` = var_groupid,
		 #`var_accid` = '110000',
		 #`var_tax` = NULL,
		 #`var_term` = NULL,
		 #`var_pmttype` = NULL,
		 `var_cur` = var_cur,
		 `var_img` = IF(var_img = '', '', CONCAT(var_id,'.',var_img)),
		 `var_addr1` = var_addr1,
		 `var_addr2` = var_addr2,
		 `var_addr3` = var_addr3,
		 `var_addr4` = var_addr4,
		 `var_addr5` = var_addr5,
		 `var_addr6` = var_addr6,
		 `var_addr7` = var_addr7,
		 #`dou_limit` = '0',
		 #`int_msg` = '0',
		 #`tin_so` = '0',
		 #`tin_si` = '0',
		 #`tin_overcredit` = '0',
		 #`tin_overduedate` = '0',
		 #`tin_block` = '0',
		 #`tin_alertmsg` = '0',
		 #`tin_inactive` = '0',
		 `var_modify` = userId,
		 `dat_modify` = NOW(),
		 `var_crm_latitude` = crm_latitude,
		 `var_crm_longitude` = crm_longitude,
		 #`var_crm_approval` = 'Approved',
		 `var_crm_facebook` = crm_facebook,
		 `var_crm_line` = crm_line,
		 `var_crm_viber` = crm_viber,
		 `var_crm_whatapp` = crm_whatapp,
		 `var_crm_industry` = crm_industry,
		 `var_crm_type` = crm_type
		WHERE
			(`ame_mt_cus`.`var_id` = var_id);
		DELETE FROM `ame_mt_ship_addr` WHERE `var_num` = var_id AND `var_type`= 'MT-CUS';
		DELETE FROM `ame_mt_cus_emp` WHERE `var_cusid`=var_id;
	END IF;
	SELECT var_id as 'lastId', CRM_FUN_CONFIG_IMG_PATH() AS 'IMG_PATH', 0 as 'isRequired', var_msgstatus as 'MSG', oldImage as 'oldLogo';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUST_UPDATE_PENDING`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUST_UPDATE_PENDING`(var_id varchar(50), var_name varchar(255), var_name_other varchar(255), var_name_con varchar(255),  var_tel1 varchar(255), var_tel2 varchar(255), var_fax varchar(255), var_web varchar(255), var_email varchar(255), var_addr varchar(255),var_desc varchar(255),var_pricecode  varchar(255),var_groupid varchar(255),var_accid varchar(255),var_cur varchar(255),var_img varchar(255),var_addr1 varchar(255),var_addr2 varchar(255),var_addr3 varchar(255),var_addr4 varchar(255),var_addr5 varchar(255),var_addr6 varchar(255),var_addr7 varchar(255),crm_latitude varchar(255),crm_longitude varchar(255), crm_approval varchar(100),crm_facebook  varchar(255),crm_line  varchar(255),crm_viber  varchar(255),crm_whatapp  varchar(255),crm_industry integer,crm_type integer, userId varchar(255))
    DETERMINISTIC
BEGIN		
	DECLARE int_exist INTEGER UNSIGNED DEFAULT 0;
	DECLARE var_msgstatus VARCHAR(100) DEFAULT "EXISTS";
	DECLARE oldImage VARCHAR(100) DEFAULT "";
	SET int_exist = (SELECT COUNT(*) FROM `crm_customer` WHERE `crm_customer`.`var_name` = var_name AND `crm_customer`.`var_id` <> var_id);
	SELECT COALESCE(`crm_customer`.`var_img`,'') INTO oldImage FROM `crm_customer` WHERE  `crm_customer`.`var_id` = var_id;
	IF int_exist = 0 THEN
		SET var_msgstatus = "NONE";
		UPDATE `crm_customer`
		SET
		 `var_name` = var_name,
		 `var_name_other` = var_name_other,
		 `var_name_con` = var_name_con,
		 `var_tel1` = var_tel1,
		 `var_tel2` = var_tel2,
		 `var_fax` = var_fax,
		 `var_web` = var_web,
		 `var_email` = var_email,
		 `var_addr` = var_addr,
		 #`var_desc` = '',
		 `var_pricecode` = var_pricecode,
		 `var_groupid` = var_groupid,
		 #`var_accid` = '110000',
		 #`var_tax` = NULL,
		 #`var_term` = NULL,
		 #`var_pmttype` = NULL,
		 `var_cur` = var_cur,
		 `var_img` = IF(var_img = '', '', CONCAT(var_id,'.',var_img)),
		 `var_addr1` = var_addr1,
		 `var_addr2` = var_addr2,
		 `var_addr3` = var_addr3,
		 `var_addr4` = var_addr4,
		 `var_addr5` = var_addr5,
		 `var_addr6` = var_addr6,
		 `var_addr7` = var_addr7,
		 #`dou_limit` = '0',
		 #`int_msg` = '0',
		 #`tin_so` = '0',
		 #`tin_si` = '0',
		 #`tin_overcredit` = '0',
		 #`tin_overduedate` = '0',
		 #`tin_block` = '0',
		 #`tin_alertmsg` = '0',
		 #`tin_inactive` = '0',
		 `var_modify` = userId,
		 `dat_modify` = NOW(),
		 `var_crm_latitude` = crm_latitude,
		 `var_crm_longitude` = crm_longitude,
		 #`var_crm_approval` = 'Approved',
		 `var_crm_facebook` = crm_facebook,
		 `var_crm_line` = crm_line,
		 `var_crm_viber` = crm_viber,
		 `var_crm_whatapp` = crm_whatapp,
		 `var_crm_industry` = crm_industry,
		 `var_crm_type` = crm_type
		WHERE
			(`crm_customer`.`var_id` = var_id);
		DELETE FROM `ame_mt_ship_addr` WHERE `var_num` = var_id AND `var_type`= 'MT-CUS';
		DELETE FROM `ame_mt_cus_emp` WHERE `var_cusid`=var_id;
	END IF;
	SELECT var_id as 'lastId', CRM_FUN_CONFIG_IMG_PATH() AS 'IMG_PATH', 0 as 'isRequired', var_msgstatus as 'MSG', oldImage as 'oldLogo';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_CUST_VIEW`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_CUST_VIEW`(IN `custId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COALESCE((SELECT COUNT(*) FROM crm_call WHERE CL_RToID = custId),0) as cCall,
         COALESCE((SELECT COUNT(*) FROM crm_meeting WHERE M_RToID = custId),0) as cMeeting,
				 COALESCE((SELECT COUNT(*) FROM crm_task WHERE TA_RToID = custId),0) as cTask,
				 COALESCE((SELECT COUNT(*) FROM crm_event WHERE EV_RToID = custId),0) as cEvent ;
	CALL CRM_PRO_CUST_GET_BY_ID(custId);
/*
	CALL listTasksRelatedToModule(custId);
	SELECT TS_ID taskStatusId, TS_Name taskStatusName FROM crm_task_status;
	CALL listEventsRelatedToModule(custId);
	SELECT LO_ID loId, LO_Name loName FROM crm_location;
	CALL listCallsRelatedToModule(custId);
	SELECT CLS_ID callStatusId, CLS_Name callStatusName FROM crm_call_status;
	CALL listMeetingsRelatedToModule(custId);
	SELECT MS_ID statusId, MS_Name statusName FROM crm_meeting_status;
	SELECT CO_ID conID, CO_Salutation conSalutation, CO_FirstName conFirstname, CO_LastName conLastname FROM crm_contact;
	SELECT N_ID noteId, N_Subject noteSubject, N_CBy noteCreateBy,N_Des noteDes, DATE_FORMAT(N_CDate,"%d-%m-%Y") createDate, DATE_FORMAT(N_CDate,"%h:%i %p") createTime FROM crm_note WHERE N_RToID = custId ORDER BY N_CDate DESC;
	CALL crmListSubordinateUserByUsername(userId);
	SELECT u.UID userID, u.UName username FROM tbluser u INNER JOIN tbluserapp ua ON u.UID = ua.UID WHERE UStatus = 1 AND ua.AppID="CRM" ORDER BY u.UID DESC; 
	SELECT I_ID industID, I_Name industName FROM crm_industry;
	SELECT CustGroupID custGroupId, CustGroupName custGroupName FROM tblcustomergroup;
	SELECT PriceCode priceCode, Description des FROM tblpricecode;
	SELECT AT_ID accountID, AT_Name accountName FROM crm_account_type;
	CALL crmListQuoteRelateToCustomer(custId);
	CALL crmListSaleOrderRelatedToCustomer(custId);
	SELECT OP_ID opId, OP_Name opName,OP_Amt opAmount, OP_CloseDate opCloseDate, OP_StageID stageId, (SELECT OS_Name FROM crm_opportunity_stage WHERE OS_ID = OP_StageID) stageName FROM crm_opportunity WHERE OP_custId = custId;
	SELECT CS_ID caseId, CS_Subject `subject`, DATE_FORMAT(CS_CDate,"%d/%m/%Y %h:%i %p") createDate, CS_StatusID statusId, (SELECT CSS_Name FROM crm_case_status WHERE CSS_ID = CS_StatusID) statusName,CS_TypeID caseTypeId, (SELECT CST_Name FROM crm_case_type WHERE CST_ID = CS_TypeID) caseTypeName, CS_Priority priorityId,(SELECT CSP_Name FROM crm_case_priority WHERE CSP_ID = CS_Priority) priorityName,CS_ItemID itemId, (SELECT ItemName FROM tblitem WHERE ItemID = CS_ItemID) itemName FROM crm_case WHERE CS_CustID = custId;
	SELECT CO_ID conID, CONCAT(CO_Salutation," ",CO_FirstName," ",CO_LastName) fullName,CO_Phone conPhone, CO_Mobile conMobile,CO_Email conEmail, CO_Department conDepartment, CO_Title conTitle FROM crm_contact WHERE CO_CustID = custId;
	SELECT COALESCE((SELECT CONCAT(var_nameen," (",var_namekh,")",IF(tin_province = 1," | ក្រុង","")) FROM crm_gazetteer WHERE var_id = c.CO_City),"") "City",
				 COALESCE((SELECT CONCAT(var_nameen," (",var_namekh,")",IF(tin_province = 1," | ក្រុង","")) FROM crm_gazetteer WHERE var_id = c.CO_District),"") "District",
				 COALESCE((SELECT CONCAT(var_nameen," (",var_namekh,")") FROM crm_gazetteer WHERE var_id = c.CO_Commune),"") "Commune",
				 COALESCE((SELECT CONCAT(var_nameen," (",var_namekh,")") FROM crm_gazetteer WHERE var_id = c.CO_Village),"") "Village"
	FROM tblcustomer c WHERE c.CustID = custId; 

*/
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_EMP_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_EMP_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT var_id 'empId', var_name 'empName' FROM ame_mt_emp;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_EVENT_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_EVENT_GET_BY_ID`(var_obj_id varchar(50))
    DETERMINISTIC
BEGIN
	SELECT 
			ev.EV_ID evId,
			ev.EV_Name evName,
			DATE_FORMAT(ev.EV_StartDate,'%d/%m/%Y %h:%i %p') evStartDate,
			DATE_FORMAT(ev.EV_EndDate,'%d/%m/%Y %h:%i %p') evEndDate,
			ev.EV_Duration evDuration,
			ev.EV_Budget evBudget,
			ev.EV_Description evDes,
			ev.EV_CBy evCreateBy,
			COALESCE((SELECT var_name FROM ame_user WHERE var_id = ev.EV_CBy),'') evCreateByName,
			DATE_FORMAT(ev.EV_CDate,'%d/%m/%Y %h:%i %p') evCreateDate,
			ev.EV_MBy evModifiedBy,
			CAST(ev.EV_MDate AS DATE) evModifiedDate,
			ev.EV_RToID AS evRelatedToModuleId,
			ev.EV_RToType AS evRelatedToModuleType,
			COALESCE(CRM_FUN_MODULE_BY_RELATED(ev.EV_RToType,ev.EV_RToID),'') AS evRelatedName,
			lo.LO_ID loId,
			lo.LO_Name loName,
			us.var_id userID,
			us.var_name username
		FROM 
			crm_event ev 
		LEFT OUTER JOIN 
			crm_location lo 
				ON ev.EV_LocationID = lo.LO_ID
		LEFT OUTER JOIN
			ame_user us 
				ON ev.EV_AssignTo = us.var_id
		WHERE ev.EV_ID = var_obj_id
		;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_EVENT_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_EVENT_LIST`(IN `userId` varchar(50))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT var_crm_role FROM ame_user WHERE var_id = userId);
	IF roleType = 1 THEN
		SELECT 
			ev.EV_ID evId,
			ev.EV_Name evName,
			DATE_FORMAT(ev.EV_StartDate,'%d/%m/%Y %h:%i %p') evStartDate,
			DATE_FORMAT(ev.EV_EndDate,'%d/%m/%Y %h:%i %p') evEndDate,
			ev.EV_Duration evDuration,
			ev.EV_Budget evBudget,
			ev.EV_Description evDes,
			ev.EV_CBy evCreateBy,
			COALESCE((SELECT var_name FROM ame_user WHERE var_id = ev.EV_CBy),'') evCreateByName,
			DATE_FORMAT(ev.EV_CDate,'%d/%m/%Y %h:%i %p') evCreateDate,
			ev.EV_MBy evModifiedBy,
			CAST(ev.EV_MDate AS DATE) evModifiedDate,
			ev.EV_RToID AS evRelatedToModuleId,
			ev.EV_RToType AS evRelatedToModuleType,
			COALESCE(CRM_FUN_MODULE_BY_RELATED(ev.EV_RToType,ev.EV_RToID),'') AS evRelatedName,
			lo.LO_ID loId,
			lo.LO_Name loName,
			us.var_id userID,
			us.var_name username
		
		FROM 
			crm_event ev 
		LEFT OUTER JOIN 
			crm_location lo 
				ON ev.EV_LocationID = lo.LO_ID
		LEFT OUTER JOIN
			ame_user us 
				ON ev.EV_AssignTo = us.var_id
		ORDER BY ev.EV_ID DESC;
	ELSE
		SELECT 
			ev.EV_ID evId,
			ev.EV_Name evName,
			DATE_FORMAT(ev.EV_StartDate,'%d/%m/%Y %h:%i %p') evStartDate,
			DATE_FORMAT(ev.EV_EndDate,'%d/%m/%Y %h:%i %p') evEndDate,
			ev.EV_Duration evDuration,
			ev.EV_Budget evBudget,
			ev.EV_Description evDes,
			ev.EV_CBy evCreateBy,
			COALESCE((SELECT var_name FROM ame_user WHERE var_id = ev.EV_CBy),'') evCreateByName,
			DATE_FORMAT(ev.EV_CDate,'%d/%m/%Y %h:%i %p') evCreateDate,
			ev.EV_MBy evModifiedBy,
			CAST(ev.EV_MDate AS DATE) evModifiedDate,
			ev.EV_RToID AS evRelatedToModuleId,
			ev.EV_RToType AS evRelatedToModuleType,
			COALESCE(CRM_FUN_MODULE_BY_RELATED(ev.EV_RToType,ev.EV_RToID),'') AS evRelatedName,
			lo.LO_ID loId,
			lo.LO_Name loName,
			us.var_id userID,
			us.var_name username
		
		FROM 
			crm_event ev 
		LEFT OUTER JOIN 
			crm_location lo 
				ON ev.EV_LocationID = lo.LO_ID
		LEFT OUTER JOIN
			ame_user us 
				ON ev.EV_AssignTo = us.var_id
		WHERE ev.EV_AssignTo = userId OR ev.EV_CBy = userId
		ORDER BY ev.EV_ID DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_EVENT_LOCATION_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_EVENT_LOCATION_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT LO_ID loId, LO_Name loName FROM crm_location ORDER BY LO_ID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_EVENT_RELATED_MODULE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_EVENT_RELATED_MODULE`(IN `moduleId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT 
		ev.EV_ID evId,
		ev.EV_Name evName,
		DATE_FORMAT(ev.EV_StartDate,'%d/%m/%Y %h:%i %p') evStartDate,
		DATE_FORMAT(ev.EV_EndDate,'%d/%m/%Y %h:%i %p') evEndDate,
		ev.EV_Duration evDuration,
		ev.EV_Budget evBudget,
		ev.EV_Description evDes,
		ev.EV_CBy evCreateBy,
		DATE_FORMAT(ev.EV_CDate,'%d/%m/%Y %h:%i %p') evCreateDate,
		ev.EV_MBy evModifiedBy,
		CAST(ev.EV_MDate AS DATE) evModifiedDate,
		lo.LO_ID locateId,
		lo.LO_Name locateName,
		COALESCE(us.var_id,'') userID,
		COALESCE(us.var_name,'') username
	
	FROM 
		crm_event ev 
	LEFT OUTER JOIN 
		crm_location lo 
			ON ev.EV_LocationID = lo.LO_ID
	LEFT OUTER JOIN
		ame_user us 
			ON ev.EV_AssignTo = us.var_id
	WHERE ev.EV_RToID = moduleId
	ORDER BY ev.EV_CDate DESC;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_EVENT_START_UP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_EVENT_START_UP`(var_obj_id varchar(50))
    DETERMINISTIC
BEGIN
	CALL CRM_PRO_LOCATION_LOAD();
	CALL CRM_PRO_USER_LIST_COM('');
	IF var_obj_id <> '' THEN 
		CALL CRM_PRO_EVENT_GET_BY_ID(var_obj_id);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_INDUSTRY_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_INDUSTRY_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT I_ID industID, I_Name industName FROM crm_industry;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_ITEM_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_ITEM_LOAD`(var_user_id varchar(150))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(item.var_id, '') 'itemId', COALESCE(item.var_name, '') 'itemName', COALESCE(item.var_itemcode, '') 'itemCode', 
				 COALESCE(item.var_barcode, '') 'barcode', COALESCE(item.var_img, '') 'image'
	FROM ame_mt_ite item WHERE item.tin_inactive = 0 AND item.tin_no_sal = 0; 
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LEAD_CONVERT`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LEAD_CONVERT`(var_cust varchar(150), var_con varchar(150), var_opp varchar(150), var_user varchar(150), var_lead varchar(150))
BEGIN
	UPDATE crm_lead lead 
	SET 
		lead.LA_CustID = var_cust, 
		lead.LA_ConvertedDate = NOW(), 
		lead.LA_StatusID = 4, 
		lead.LA_ConID = var_con, 
		lead.LA_ConvertBy = var_user 
	WHERE lead.LA_ID = var_lead;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LEAD_DELETE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LEAD_DELETE`(IN `leadId` varchar(11))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_call WHERE crm_call.CL_RToID = leadId;
	DELETE FROM crm_meeting WHERE crm_meeting.M_RToID = leadId;
	DELETE FROM crm_task WHERE crm_task.TA_RToID = leadId;
	DELETE FROM crm_event WHERE crm_event.EV_RToID = leadId;
	DELETE FROM crm_note WHERE crm_note.N_RToID = leadId;
	DELETE FROM crm_colllaboration_tags WHERE crm_colllaboration_tags.collapId = (SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = leadId); 
	DELETE FROM crm_collaboration_details WHERE crm_collaboration_details.PostID = (SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = leadId);
	DELETE FROM crm_collaboration WHERE crm_collaboration.CB_RToID = leadId;
	DELETE FROM crm_lead WHERE crm_lead.LA_ID = leadId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LEAD_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LEAD_GET_BY_ID`(IN `leadID` varchar(150))
    DETERMINISTIC
BEGIN
	select
        lead.LA_ID as leadID,
        lead.LA_Email as email,
        lead.LA_AccountName as accountName,
        lead.LA_City as city,
        lead.LA_Commune as commune,
        lead.LA_Country as country,
        lead.LA_CBy as createBy,
        CAST(lead.LA_CDate AS date) as createDate,
        lead.LA_Department as department,
        lead.LA_Des as description,
        lead.LA_District as district,
        lead.LA_FirstName as firstName,
        lead.LA_LastName as lastName,
        lead.LA_Mobile as mobile,
        lead.LA_MBy as modifyBy,
        CAST(lead.LA_MDate AS date) as modifyDate,
        lead.LA_No as no,
        lead.LA_Phone as phone,
        lead.LA_Salutation as salutation,
        lead.LA_State as state,
        lead.LA_Street as street,
        lead.LA_Title as title,
        lead.LA_Village as village,
        lead.LA_Website as website,
        camp.CA_ID as campID,
        camp.CA_Name as campName,
        assignto.var_id as assignToUserID,
        assignto.var_name as assignToUsername,
        indust.I_ID as industID,
        indust.I_Name as industName,
        source.LS_ID as sourceID,
        source.LS_Name as sourceName,
        status.LST_ID as statusID,
				status.LST_Name as statusName 
    from
        crm_lead lead 
    left outer join
        crm_camp camp 
            on lead.LA_CA_ID=camp.CA_ID 
    left outer join
        ame_user assignto 
            on lead.LA_ATo = assignto.var_id 
    left outer join
        crm_industry indust 
            on lead.LA_IndustID=indust.I_ID 
    left outer join
        crm_lead_source source 
            on lead.LA_SourceID=source.LS_ID 
    left outer join
        crm_lead_status status 
            on lead.LA_StatusID=status.LST_ID 
    where lead.LA_ID = leadID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LEAD_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LEAD_LIST`(IN `userId` varchar(50))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SET roleType = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select ame_user.var_crm_role FROM ame_user WHERE ame_user.var_id = userId LIMIT 1)), 0);
	IF roleType = 1 THEN
		SELECT
      lead.LA_ID as leadID,
			lead.LA_Email as email,
			lead.LA_AccountName as accountName,
			lead.LA_CBy as createBy,
			COALESCE((SELECT var_name FROM ame_user WHERE ame_user.var_id = lead.LA_CBy),'') 'createByName',
			TIMESTAMP(lead.LA_CDate) as createDate,
			lead.LA_FirstName as firstName,
			lead.LA_LastName as lastName,
			lead.LA_Des as description,
			lead.LA_MBy as modifyBy,
			CAST(lead.LA_MDate AS date) as modifyDate,
			lead.LA_Salutation as salutation,
			lead.LA_CA_ID as campID,
			(SELECT CA_Name FROM crm_camp WHERE CA_ID = lead.LA_CA_ID) as campName,
			lead.LA_ATo as assignToUserId,
			COALESCE((SELECT u.var_name FROM ame_user u WHERE u.var_id = lead.LA_ATo),'') as assignToUserName,
			lead.LA_IndustID as industID,
			(SELECT I_Name FROM crm_industry WHERE I_ID = lead.LA_IndustID) as industName,
			lead.LA_SourceID as sourceID,
			(SELECT LS_Name FROM crm_lead_source WHERE LS_ID = lead.LA_SourceID) as sourceName,
			lead.LA_StatusID as statusID,
			(SELECT LST_Name FROM crm_lead_status WHERE LST_ID = lead.LA_StatusID) as statusName
    	FROM
        	crm_lead lead 
		ORDER BY lead.LA_ID DESC;
	ELSE
		SELECT
			lead.LA_ID as leadID,
			lead.LA_Email as email,
			lead.LA_AccountName as accountName,
			lead.LA_CBy as createBy,
			lead.LA_Des as description,
			COALESCE((SELECT var_name FROM ame_user WHERE ame_user.var_id = lead.LA_CBy),'') 'createByName',
			TIMESTAMP(lead.LA_CDate) as createDate,
			lead.LA_FirstName as firstName,
			lead.LA_LastName as lastName,
			lead.LA_MBy as modifyBy,
			CAST(lead.LA_MDate AS date) as modifyDate,
			lead.LA_Salutation as salutation,
			lead.LA_CA_ID as campID,
			(SELECT CA_Name FROM crm_camp WHERE CA_ID = lead.LA_CA_ID) as campName,
			lead.LA_ATo as assignToUserId,
			COALESCE((SELECT u.var_name FROM ame_user u WHERE u.var_id = lead.LA_ATo),'') as assignToUserName,
			lead.LA_IndustID as industID,
			(SELECT I_Name FROM crm_industry WHERE I_ID = lead.LA_IndustID) as industName,
			lead.LA_SourceID as sourceID,
			(SELECT LS_Name FROM crm_lead_source WHERE LS_ID = lead.LA_SourceID) as sourceName,
			lead.LA_StatusID as statusID,
			(SELECT LST_Name FROM crm_lead_status WHERE LST_ID = lead.LA_StatusID) as statusName 
		FROM
				crm_lead lead 
		WHERE lead.LA_ATo = userId OR lead.LA_CBy = userId
		ORDER BY lead.LA_ID DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LEAD_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LEAD_LOAD`(userId varchar(100))
    DETERMINISTIC
BEGIN
	select
        lead.LA_ID as leadID,
        lead.LA_Email as email,
        lead.LA_AccountName as accountName,
        lead.LA_City as city,
        lead.LA_Commune as commune,
        lead.LA_Country as country,
        lead.LA_CBy as createBy,
        CAST(lead.LA_CDate AS date) as createDate,
        lead.LA_Department as department,
        lead.LA_Des as description,
        lead.LA_District as district,
        lead.LA_FirstName as firstName,
        lead.LA_LastName as lastName,
        lead.LA_Mobile as mobile,
        lead.LA_MBy as modifyBy,
        CAST(lead.LA_MDate AS date) as modifyDate,
        lead.LA_No as no,
        lead.LA_Phone as phone,
        lead.LA_Salutation as salutation,
        lead.LA_State as state,
        lead.LA_Street as street,
        lead.LA_Title as title,
        lead.LA_Village as village,
        lead.LA_Website as website,
        camp.CA_ID as campID,
        camp.CA_Name as campName,
        assignto.var_id as assignToUserID,
        assignto.var_name as assignToUsername,
        indust.I_ID as industID,
        indust.I_Name as industName,
        source.LS_ID as sourceID,
        source.LS_Name as sourceName,
        status.LST_ID as statusID,
				status.LST_Name as statusName,
				lead.LA_Des as description
    from
        crm_lead lead 
    left outer join
        crm_camp camp 
            on lead.LA_CA_ID=camp.CA_ID 
    left outer join
        ame_user assignto 
            on camp.CA_ATo=assignto.var_id 
    left outer join
        crm_industry indust 
            on lead.LA_IndustID=indust.I_ID 
    left outer join
        crm_lead_source source 
            on lead.LA_SourceID=source.LS_ID 
    left outer join
        crm_lead_status status 
            on lead.LA_StatusID=status.LST_ID 
    order by
        lead.LA_ID asc;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LEAD_LOAD_BY_CAMP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LEAD_LOAD_BY_CAMP`(campId varchar(50))
    DETERMINISTIC
BEGIN
	SELECT LA_ID leadId, CONCAT(LA_Salutation," ",LA_FirstName," ",LA_LastName) fullName,LA_AccountName company, LA_StatusID statusId, 
				 COALESCE((SELECT LST_Name FROM crm_lead_status WHERE LST_ID = LA_StatusID),"") statusName, LA_Email email, LA_CDate createDate 
	FROM crm_lead 
	WHERE LA_CA_ID = campId 
	ORDER BY leadId DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LEAD_SOURCE_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LEAD_SOURCE_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT LS_ID sourceID, LS_Name sourceName FROM crm_lead_source;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LEAD_START_UP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LEAD_START_UP`(IN `userId` varchar(255), var_obj_id varchar(255))
    DETERMINISTIC
BEGIN
	CALL CRM_PRO_CAMP_LOAD(userId);
	CALL CRM_PRO_INDUSTRY_LOAD();
	CALL CRM_PRO_LEAD_STATUS_LOAD();
	CALL CRM_PRO_LEAD_SOURCE_LOAD();
	CALL CRM_PRO_USER_LIST_COM(userId);
	
	IF var_obj_id <> '' THEN
		CALL CRM_PRO_LEAD_GET_BY_ID(var_obj_id);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LEAD_STATUS_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LEAD_STATUS_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT LST_ID statusID, LST_Name statusName FROM crm_lead_status;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LEAD_UPDATE_STATUS`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LEAD_UPDATE_STATUS`(IN `leadId` varchar(11),IN `custId` varchar(255),IN `opId` varchar(11))
    DETERMINISTIC
BEGIN
	IF opId = "" THEN 
		UPDATE crm_lead SET LA_StatusID = 4, LA_ConvertedDate = NOW(), LA_CustID = custId WHERE LA_ID = leadId;
	ELSE
		UPDATE crm_lead SET LA_StatusID = 4, LA_ConvertedDate = NOW(), LA_CustID = custId, LA_OPID = opId WHERE LA_ID = leadId;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LEAD_VIEW`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LEAD_VIEW`(objectId varchar(150), userid varchar(150))
    DETERMINISTIC
BEGIN
	SELECT COALESCE((SELECT COUNT(*) FROM crm_call WHERE CL_RToID = objectId),0) as cCall,
         COALESCE((SELECT COUNT(*) FROM crm_meeting WHERE M_RToID = objectId),0) as cMeeting,
				 COALESCE((SELECT COUNT(*) FROM crm_task WHERE TA_RToID = objectId),0) as cTask,
				 COALESCE((SELECT COUNT(*) FROM crm_event WHERE EV_RToID = objectId),0) as cEvent ;
	CALL CRM_PRO_LEAD_GET_BY_ID(objectId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LIST_DATABASE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LIST_DATABASE`()
BEGIN
	#Routine body goes here...

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_LOCATION_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_LOCATION_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT LO_ID 'loId', LO_Name 'loName' FROM crm_location ORDER BY LO_ID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_MEETING_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_MEETING_GET_BY_ID`(IN `meetingId` varchar(11))
    DETERMINISTIC
BEGIN
	DECLARE moduleName VARCHAR(255) DEFAULT "";
	select M_RToType into moduleName from crm_meeting where M_ID = meetingId;
	if moduleName = 'Customer' then
		SELECT
			M.M_ID meetingId,
			M.M_Subject meetingSubject, 
			DATE_FORMAT(M.M_StartDate,'%d/%m/%Y %h:%i %p') meetingStartDate,
			DATE_FORMAT(M.M_EndDate,'%d/%m/%Y %h:%i %p') meetingEndDate,
			M.M_Duration meetingDuration, 
			MS.MS_ID statusId, MS.MS_Name statusName,
			M.M_RToType meetingRelatedToModuleType,
	    M.M_RToID meetingRelatedToModuleId,
			cu.var_name mettingRelatedName,
			M.M_Location meetingLocation,
			M.M_Des meetingDes,
			U.var_id userID, 
			U.var_name username,
			M.M_CBy meetingCreateBy, 
	   	DATE_FORMAT(M.M_CDate,'%d/%m/%Y %h:%i %p') meetingCreateDate, 
			M.M_MBy meetingModifiedBy, 
			DATE_FORMAT(M.M_MDate ,'%d/%m/%Y %h:%i %p') meetingModifiedDate,
			M.M_CheckIn_Latitude meetingLatitude,
			M.M_CheckIn_Longitude meetingLongitude,
			DATE_FORMAT(M.M_CheckinDate, '%d/%m/%Y %h:%i %p') meetingCheckinDate,
			(SELECT var_name FROM ame_user WHERE var_id = M.M_CheckinBy) checkinBy,
			CRM_FUN_CONFIG_IMG_PATH() imagePath,
			M.M_CheckInDes meetingCheckinDes,
			M.M_CheckOut_Longitude meetingCheckOutLongitude,
			M.M_CheckOut_Latitude meetingCheckOutLatitude,
			M.M_CheckOutDate meetingCheckOutDate,
			M.M_CheckOutBy meetingCheckOutBy,
			M.M_CheckOutDuration meetingCheckOutDuration,
			M.M_CheckOutDes meetingCheckOutDes
	  FROM 
			crm_meeting M
		LEFT OUTER JOIN 
			crm_meeting_status MS
				ON M.M_StatusID = MS.MS_ID
		LEFT OUTER JOIN 
			ame_user U
				ON M.M_ATo = U.var_id
		left outer join 
			ame_mt_cus cu 
				on cu.var_id = M.M_RToID
		WHERE M.M_ID = meetingId;
	else	
		SELECT
			M.M_ID meetingId,
			M.M_Subject meetingSubject, 
			DATE_FORMAT(M.M_StartDate,'%d/%m/%Y %h:%i %p') meetingStartDate,
			DATE_FORMAT(M.M_EndDate,'%d/%m/%Y %h:%i %p') meetingEndDate,
			M.M_Duration meetingDuration, 
			MS.MS_ID statusId, MS.MS_Name statusName,
			M.M_RToType meetingRelatedToModuleType,
	    M.M_RToID meetingRelatedToModuleId,
			CRM_FUN_MODULE_BY_RELATED(M.M_RToType, M.M_RToID) mettingRelatedName,
			M.M_Location meetingLocation,
			M.M_Des meetingDes,
			U.var_id userID, 
			U.var_name username,
			M.M_CBy meetingCreateBy, 
	    DATE_FORMAT(M.M_CDate,'%d/%m/%Y %h:%i %p') meetingCreateDate, 
			M.M_MBy meetingModifiedBy, 
			DATE_FORMAT(M.M_MDate ,'%d/%m/%Y %h:%i %p') meetingModifiedDate,
			M.M_CheckIn_Latitude meetingLatitude,
			M.M_CheckIn_Longitude meetingLongitude,
			DATE_FORMAT(M.M_CheckinDate, '%d/%m/%Y %h:%i %p') meetingCheckinDate,
			(SELECT var_name FROM ame_user WHERE var_id = M.M_CheckinBy) checkinBy,
			CRM_FUN_CONFIG_IMG_PATH() imagePath,
			M.M_CheckInDes meetingCheckinDes,
			M.M_CheckOut_Longitude meetingCheckOutLongitude,
			M.M_CheckOut_Latitude meetingCheckOutLatitude,
			M.M_CheckOutDate meetingCheckOutDate,
			M.M_CheckOutBy meetingCheckOutBy,
			M.M_CheckOutDuration meetingCheckOutDuration,
			M.M_CheckOutDes meetingCheckOutDes
	  FROM 
			crm_meeting M
		LEFT OUTER JOIN 
			crm_meeting_status MS
				ON M.M_StatusID = MS.MS_ID
		LEFT OUTER JOIN 
			ame_user U
				ON M.M_ATo = U.var_id 
		WHERE M.M_ID = meetingId;
	end if;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_MEETING_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_MEETING_LIST`(IN `userId` varchar(50))
    DETERMINISTIC
BEGIN	
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT var_crm_role FROM ame_user WHERE var_id = userId);
	IF roleType = 1 THEN
		SELECT 
			M.M_ID meetingId,
			M.M_Subject meetingSubject, 
			DATE_FORMAT(M.M_StartDate,'%d/%m/%Y %h:%i %p') meetingStartDate,
			DATE_FORMAT(M.M_EndDate,'%d/%m/%Y %h:%i %p') meetingEndDate,
			M.M_Duration meetingDuration, 
			MS.MS_ID statusId, MS.MS_Name statusName,
			M.M_RToType meetingRelatedToModuleType,
			M.M_RToID meetingRelatedToModuleId,
			CRM_FUN_MODULE_BY_RELATED(M.M_RToType, M.M_RToID) meetingRelatedToModuleName,
			M.M_Location meetingLocation,
			M.M_Des meetingDes,
			U.var_id userID, 
			U.var_name username,
			M.M_CBy meetingCreateBy, 
			(SELECT var_name FROM ame_user WHERE var_id = M.M_CBy) meetingCreateByName,
			DATE_FORMAT(M.M_CDate,'%d/%m/%Y %h:%i %p') meetingCreateDate, 
			M.M_MBy meetingModifiedBy, 
			CAST(M.M_MDate AS date) meetingModifiedDate
		FROM 
			crm_meeting M
		LEFT OUTER JOIN 
			crm_meeting_status MS
				ON M.M_StatusID = MS.MS_ID
		LEFT OUTER JOIN 
			ame_user U
				ON M.M_ATo = U.var_id 
		ORDER BY M.M_ID DESC;
	ELSE
		SELECT 
			M.M_ID meetingId,
			M.M_Subject meetingSubject, 
			DATE_FORMAT(M.M_StartDate,'%d/%m/%Y %h:%i %p') meetingStartDate,
			DATE_FORMAT(M.M_EndDate,'%d/%m/%Y %h:%i %p') meetingEndDate,
			M.M_Duration meetingDuration, 
			MS.MS_ID statusId, MS.MS_Name statusName,
			M.M_RToType meetingRelatedToModuleType,
			M.M_RToID meetingRelatedToModuleId,
			CRM_FUN_MODULE_BY_RELATED(M.M_RToType, M.M_RToID) meetingRelatedToModuleName,
			M.M_Location meetingLocation,
			M.M_Des meetingDes,
			U.var_id userID, 
			U.var_name username,
			M.M_CBy meetingCreateBy, 
			(SELECT var_name FROM ame_user WHERE var_id = M.M_CBy) meetingCreateByName,
			DATE_FORMAT(M.M_CDate,'%d/%m/%Y %h:%i %p') meetingCreateDate, 
			M.M_MBy meetingModifiedBy, 
			CAST(M.M_MDate AS date) meetingModifiedDate
		FROM 
			crm_meeting M
		LEFT OUTER JOIN 
			crm_meeting_status MS
				ON M.M_StatusID = MS.MS_ID
		LEFT OUTER JOIN 
			ame_user U
				ON M.M_ATo = U.UID 
		WHERE M.M_ATo = userId OR M.M_CBy = userId
		ORDER BY M.M_ID DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_MEETING_RELATED_MODULE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_MEETING_RELATED_MODULE`(IN `moduleId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT 
		M.M_ID meetingId,
		M.M_Subject meetingSubject, 
		DATE_FORMAT(M.M_StartDate,'%d/%m/%Y %h:%i %p') meetingStartDate,
		DATE_FORMAT(M.M_EndDate,'%d/%m/%Y %h:%i %p') meetingEndDate,
		M.M_Duration meetingDuration, 
		MS.MS_ID statusId, MS.MS_Name statusName,
		M.M_Location meetingLocation,
		M.M_Des meetingDes,
		COALESCE(U.var_id,'') userID, 
		COALESCE(U.var_name,'') username,
		M.M_CBy meetingCreateBy, 
    DATE_FORMAT(M.M_CDate,'%d/%m/%Y %h:%i %p') meetingCreateDate,
		M.M_MBy meetingModifiedBy, 
		CAST(M.M_MDate AS date) meetingModifiedDate
  FROM 
		crm_meeting M
	LEFT OUTER JOIN 
		crm_meeting_status MS
			ON M.M_StatusID = MS.MS_ID
	LEFT OUTER JOIN 
		ame_user U
			ON M.M_ATo = U.var_id 
	WHERE M.M_RToID = moduleId
	ORDER BY M.M_CDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_MEETING_START_UP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_MEETING_START_UP`(var_obj_id varchar(50))
    DETERMINISTIC
BEGIN
	CALL CRM_PRO_MEETING_STATUS_LOAD();
	CALL CRM_PRO_USER_LIST_COM('');
	IF var_obj_id <> '' THEN 
		CALL CRM_PRO_MEETING_GET_BY_ID(var_obj_id);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_MEETING_STATUS_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_MEETING_STATUS_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT MS_ID statusId, MS_Name statusName FROM crm_meeting_status;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_MODULE_RELATED_BY_ID_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_MODULE_RELATED_BY_ID_LIST`(var_related varchar(100), var_activity varchar(100), var_entry_id varchar(100), var_user_id varchar(100))
    DETERMINISTIC
BEGIN
	IF var_activity = 'call' THEN
		CALL CRM_PRO_CALL_RELATED_MODULE(var_entry_id);
	ELSEIF var_activity = 'meeting' THEN
		CALL CRM_PRO_MEETING_RELATED_MODULE(var_entry_id);
	ELSEIF var_activity = 'event' THEN
		CALL CRM_PRO_EVENT_RELATED_MODULE(var_entry_id);
	ELSEIF var_activity = 'task' THEN
		CALL CRM_PRO_TASK_RELATED_MODULE(var_entry_id);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_MODULE_RELATED_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_MODULE_RELATED_LIST`(var_modId varchar(255), var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	IF var_modId = 'Customer' THEN
		SELECT var_id 'strKey', var_name 'strValue' FROM ame_mt_cus ORDER BY var_id;
	ELSEIF var_modId = 'Lead' THEN
		SELECT LA_ID 'strKey', CONCAT(LA_Salutation, ' ',LA_FirstName, LA_LastName) 'strValue' FROM crm_lead ORDER BY LA_ID;
	ELSEIF var_modId = 'Campaign' THEN
		SELECT CA_ID 'strKey', CA_Name 'strValue' FROM crm_camp ORDER BY CA_ID;
	ELSEIF var_modId = 'Contact' THEN
		SELECT CO_ID 'strKey', CONCAT(CO_Salutation, ' ',CO_FirstName, CO_LastName) 'strValue'  FROM crm_contact ORDER BY CO_ID;
	ELSEIF var_modId = 'Opportunity' THEN
		SELECT OP_ID 'strKey', OP_Name 'strValue' FROM crm_opportunity ORDER BY OP_ID;
	ELSEIF var_modId = 'Case' THEN
		SELECT cs_id 'strKey', cs_subject 'strValue'  FROM crm_case ORDER BY CS_ID;
	ELSEIF var_modId = 'Task' THEN
		SELECT TA_ID 'strKey', TA_Subject 'strValue' FROM crm_task ORDER BY TA_ID;
	ELSE
		SELECT '' as 'strKey', '' as 'strValue';
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_NOTE_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_NOTE_GET_BY_ID`(var_objId varchar(50))
    DETERMINISTIC
BEGIN
	SELECT n.N_ID 'noteId', n.N_Subject 'noteSubject', n.N_RToType 'noteRelatedToModuleType', n.N_RToID 'noteRelatedToModuleId', 
			     n.N_Des 'noteDes',DATE_FORMAT(n.N_CDate,'%d/%m/%Y %h:%i %p') noteCreateDate, n.N_CBy 'noteCreateBy', u.var_name 'noteCreateByName', 
			     COALESCE(CRM_FUN_MODULE_BY_RELATED(n.N_RToType, n.N_RToID),'') 'noteRelatedName'
		FROM	crm_note n 
		LEFT JOIN ame_user u ON n.N_CBy = u.var_id
		WHERE n.N_ID=var_objId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_NOTE_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_NOTE_LIST`(IN `userId` varchar(50))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT var_crm_role FROM ame_user WHERE var_id = userId);
	IF roleType = 1 THEN
		SELECT n.N_ID 'noteId', n.N_Subject 'noteSubject', n.N_RToType 'noteRelatedToModuleType', n.N_RToID 'noteRelatedToModuleId', 
			     n.N_Des 'noteDes',DATE_FORMAT(n.N_CDate,'%d/%m/%Y %h:%i %p') noteCreateDate, n.N_CBy 'noteCreateBy', u.var_name 'noteCreateByName', 
			     COALESCE(CRM_FUN_MODULE_BY_RELATED(n.N_RToType, n.N_RToID),'') 'noteRelatedName'
		FROM	crm_note n 
		LEFT JOIN ame_user u ON n.N_CBy = u.var_id
		ORDER BY n.N_ID DESC;
 	ELSE
		SELECT n.N_ID 'noteId', n.N_Subject 'noteSubject', n.N_RToType 'noteRelatedToModuleType', n.N_RToID 'noteRelatedToModuleId', 
			 n.N_Des 'noteDes',DATE_FORMAT(n.N_CDate,'%d/%m/%Y %h:%i %p') noteCreateDate, n.N_CBy 'noteCreateBy', u.var_name 'noteCreateByName', 
			 COALESCE(CRM_FUN_MODULE_BY_RELATED(n.N_RToType, n.N_RToID),'') 'noteRelatedName'
		FROM	crm_note n 
		LEFT JOIN ame_user u ON n.N_CBy = u.var_id
		WHERE n.N_CBy = userId
		ORDER BY n.N_ID DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_NOTE_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_NOTE_LOAD`(campId varchar(50))
    DETERMINISTIC
BEGIN
	SELECT N_ID noteId, N_Subject noteSubject, N_CBy noteCreateBy,N_Des noteDes, DATE_FORMAT(N_CDate,"%d-%m-%Y") createDate, DATE_FORMAT(N_CDate,"%h:%i %p") createTime 
	FROM crm_note
	WHERE N_RToID = campId
	ORDER BY N_CDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_NOTE_RELATED_LEAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_NOTE_RELATED_LEAD`(IN `leadId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT 
		note.N_ID AS noteId,
		note.N_Subject AS noteSubject,
		note.N_Des AS noteDes,
		note.N_CBy AS noteCreateBy,
		DATE_FORMAT(note.N_CDate,'%d-%m-%Y') AS noteCreateDate,
		DATE_FORMAT(note.N_CDate,'%h:%i %p') AS noteTime,
		note.N_MBy AS noteModifiedBy,
		CAST(note.N_MDate AS DATE) AS noteModifiedDate
	FROM 
		crm_note note
	INNER JOIN 
		crm_lead lead 
			ON lead.LA_ID = note.N_RToID
	WHERE lead.LA_ID = leadId
	ORDER BY note.N_CDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_NOTE_RELATED_OPP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_NOTE_RELATED_OPP`(IN `opId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT 
		note.N_ID AS noteId,
		note.N_Subject AS noteSubject,
		note.N_Des AS noteDes,
		note.N_CBy AS noteCreateBy,
		DATE_FORMAT(note.N_CDate,'%d-%m-%Y') AS noteCreateDate,
		DATE_FORMAT(note.N_CDate,'%h:%i %p') AS noteTime,
		note.N_MBy AS noteModifiedBy,
		CAST(note.N_MDate AS DATE) AS noteModifiedDate
	FROM 
		crm_note note
	INNER JOIN 
		crm_opportunity op  
			ON op.OP_ID = note.N_RToID
	WHERE op.OP_ID = opId
	ORDER BY note.N_CDate DESC;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_NOTE_RELATE_BY_MODULE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_NOTE_RELATE_BY_MODULE`(var_relate_type varchar(255), var_relateid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT n.N_ID 'noteId', n.N_Subject 'noteSubject', n.N_RToType 'noteRelatedToModuleType', n.N_RToID 'noteRelatedToModuleId',
		     n.N_Des 'noteDes', n.N_CBy 'noteCreateBy', u.var_name 'noteCreateByName', DATE_FORMAT(n.N_CDate ,'%d/%m/%Y %h:%i %p') 'noteCreateDate',
         DATE_FORMAT(n.N_CDate ,'%d-%m-%Y') 'createDate', DATE_FORMAT(n.N_CDate ,'%h:%i %p') 'createTime'
	FROM crm_note n
	LEFT JOIN ame_user u ON n.N_CBy = u.var_id
	WHERE IF(var_relate_type = 'all',TRUE, n.N_RToType = var_relate_type) AND n.N_RToID = var_relateid
	ORDER BY n.N_CDate DESC
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_NOTI_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_NOTI_LOAD`()
    DETERMINISTIC
BEGIN
	DECLARE var_appid VARCHAR(255) DEFAULT "";
	DECLARE var_chrome VARCHAR(255) DEFAULT "";
	DECLARE var_base_url VARCHAR(255) DEFAULT "";
	DECLARE var_bus_unit VARCHAR(255) DEFAULT "";
	SELECT noti_app_id, chrome_web_icon, base_url, busUnit INTO var_appid,var_chrome,var_base_url,var_bus_unit FROM crm_notification_config LIMIT 1;
	SELECT 
		noti_id 'notiId',
		COALESCE(noti_userid, '') 'userId', 
		COALESCE(noti_subject ,'') 'subject', 
		COALESCE(noti_body) 'body', 
		COALESCE(noti_url, '') 'url', 
		COALESCE(noti_email ,'') 'email',
		COALESCE(noti_email_subject, '') 'emailSubject',
		COALESCE(noti_email_body,'') 'emailBody',
		var_appid 'appId',
		var_chrome 'chromeIcon',
		var_base_url 'baseUrl',
		var_bus_unit 'bUnit'
	FROM crm_notification_push 
	WHERE noti_status = 0 AND noti_userid IS NOT NULL AND noti_userid <> '';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_NOTI_UPDATE_STATUS`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_NOTI_UPDATE_STATUS`(var_noti_id varchar(50))
    DETERMINISTIC
BEGIN
	#DELETE FROM crm_notification_push WHERE `crm_notification_push`.noti_id = var_noti_id;
	UPDATE crm_notification_push SET noti_status = 1 WHERE noti_id = var_noti_id;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_ADD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_ADD`(var_lastid varchar(255), var_OP_Name varchar(255), var_OP_CloseDate varchar(255),var_OP_TypeID varchar(255),var_OP_StageID varchar(255),var_OP_Probability varchar(255),var_OP_LeadSourceID varchar(255),var_OP_NextStep varchar(255),var_OP_CampID varchar(255),var_OP_Des text,var_OP_ATo varchar(255),var_OP_CBy varchar(255),var_OP_CustID varchar(255),var_OP_PriceCode varchar(255),var_OP_Class varchar(255),var_OP_Amt varchar(255),var_OP_IsApproved varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_lastid VARCHAR(100) DEFAULT "";
	SET var_lastid = CRM_FUN_CONFIG_GENERATE_ID('OP');
	IF var_lastid <> '' THEN
		INSERT INTO `crm_opportunity` (
			`OP_ID`,
			`OP_Name`,
			`OP_CloseDate`,
			`OP_TypeID`,
			`OP_StageID`,
			`OP_Probability`,
			`OP_LeadSourceID`,
			`OP_NextStep`,
			`OP_CampID`,
			`OP_Des`,
			`OP_ATo`,
			`OP_CBy`,
			`OP_CDate`,
			`OP_CustID`,
			`OP_PriceCode`,
			`OP_Class`,
			`OP_Amt`,
			`OP_IsApproved`
		)
		VALUES(
		var_lastid,
		var_OP_Name,
		var_OP_CloseDate,
		var_OP_TypeID,
		var_OP_StageID,
		var_OP_Probability,
		var_OP_LeadSourceID,
		var_OP_NextStep,
		var_OP_CampID,
		var_OP_Des,
		var_OP_ATo,
		var_OP_CBy,
		NOW(),
		var_OP_CustID,
		var_OP_PriceCode,
		var_OP_Class,
		var_OP_Amt,
		var_OP_IsApproved
		);
	END IF;
	SELECT var_lastid as 'lastId', CRM_FUN_CONFIG_IMG_PATH() AS 'IMG_PATH';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_CONTACT_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_CONTACT_LIST`(IN `opId` varchar(150))
    DETERMINISTIC
BEGIN
		SELECT 
			con.CO_ID conID,
			CONCAT(CO_Salutation,' ',CO_FirstName,' ',CO_LastName) conName,
			con.CO_Phone conPhone,
			con.CO_Mobile conMobile,
			con.CO_Email conEmail,
			con.CO_Title conTitle,
			con.CO_Department conDepartment,
			opcon.OPCON_Role role,
			opcon.OPCON_Type Type,
			opcon.OPCON_ID id
		FROM 
			crm_contact con 
			INNER JOIN 
				crm_opportunity_contact opcon
					ON con.CO_ID = opcon.OPCON_CONID
		WHERE 
			opcon.OPCON_OPID = opId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_DELETE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_DELETE`(IN `oppId` varchar(150))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_call WHERE crm_call.CL_RToID = oppId;
	DELETE FROM crm_meeting WHERE crm_meeting.M_RToID = oppId;
	DELETE FROM crm_task WHERE crm_task.TA_RToID = oppId;
	DELETE FROM crm_event WHERE crm_event.EV_RToID = oppId;
	DELETE FROM crm_note WHERE crm_note.N_RToID = oppId;
	DELETE FROM crm_colllaboration_tags WHERE crm_colllaboration_tags.collapId = (SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = oppId); 
	DELETE FROM crm_collaboration_details WHERE crm_collaboration_details.PostID = (SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = oppId);
	DELETE FROM crm_collaboration WHERE crm_collaboration.CB_RToID = oppId;
	DELETE FROM crm_opportunity_contact WHERE crm_opportunity_contact.OPCON_OPID = oppId;
	DELETE FROM crm_opportunity_detail WHERE crm_opportunity_detail.OP_ID = oppId;
	DELETE FROM crm_opportunity_lead_project WHERE crm_opportunity_lead_project.OPID  = oppId;
	DELETE FROM crm_opportunity_quote WHERE crm_opportunity_quote.OP_ID = oppId;
	DELETE FROM crm_opportunity_saleorder WHERE crm_opportunity_saleorder.OP_ID = oppId;
	DELETE FROM crm_opportunity WHERE crm_opportunity.OP_ID = oppId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_GET_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_GET_BY_ID`(oppId varchar(150))
    DETERMINISTIC
BEGIN
	SELECT opp.OP_ID 'opId', opp.OP_Name 'opName', opp.OP_Amt 'opAmount', opp.OP_CloseDate 'opCloseDate',
				 opp.OP_TypeID 'opTypeID', COALESCE(opptype.OT_Name,'') 'opTypeName', opp.OP_StageID 'opStageId' , COALESCE(oppstage.OS_Name,'') 'opStageName',
         COALESCE(opp.OP_Probability,0) 'opProbability', COALESCE(opp.OP_LeadSourceID,'') 'opLeadSourceID', COALESCE(ls.LS_Name,'') 'opLeadSourceName',
         COALESCE(opp.OP_NextStep, '') 'opNextStep', COALESCE(opp.OP_CampID,'') 'opCampaignId',COALESCE(camp.CA_Name,'') 'opCampaignName',
				 COALESCE(opp.OP_Des, '') 'opDes', COALESCE(opp.OP_ATo,'') 'opAssignedTo', COALESCE(u.var_name,'') 'opAssignedToName', 
				 COALESCE(opp.OP_CustID,'') 'custId', COALESCE(cus.var_name,'') 'custName',
				 COALESCE(opp.OP_PriceCode,'') 'priceCode', COALESCE(price.var_name,'') 'priceCodeDes',
				 COALESCE(opp.OP_Class,'') 'classId', COALESCE(cla.var_name, '') 'className',
				 COALESCE(opp.OP_CBy, '') 'opCreateBy', COALESCE(cby.var_name,'') 'opCreateByName'
	FROM crm_opportunity opp
	LEFT JOIN crm_opportunity_type opptype ON opp.OP_TypeID = opptype.OT_ID
	LEFT JOIN crm_opportunity_stage oppstage ON opp.OP_StageID = oppstage.OS_ID
	LEFT JOIN crm_lead_source ls ON opp.OP_LeadSourceID = ls.LS_ID
	LEFT JOIN crm_camp camp ON opp.OP_CampID = camp.CA_ID
	LEFT JOIN ame_user u ON opp.OP_ATo = u.var_id
	LEFT JOIN ame_mt_cus cus ON opp.OP_CustID = cus.var_id
	LEFT JOIN ame_mt_pri_cod price ON opp.OP_PriceCode = price.var_id
	LEFT JOIN ame_mt_cla cla ON opp.OP_Class = cla.var_id
	LEFT JOIN ame_user cby ON opp.OP_CBy = cby.var_id
	WHERE OP_ID = oppId;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_LIST`(IN `userId` varchar(50))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT `ame_user`.`var_crm_role` FROM ame_user WHERE `ame_user`.`var_id` = userId);
	IF roleType = 1 THEN
		SELECT
        op.OP_ID as opId,
        op.OP_Amt as opAmount,
        TIMESTAMP(op.OP_CloseDate) as opCloseDate,
        op.OP_CBy as opCreateBy,
				(SELECT `ame_user`.`var_name` FROM ame_user WHERE `ame_user`.`var_id` = op.OP_CBy) 'opCreateByName',
        TIMESTAMP(op.OP_CDate) as opCreateDate,
        op.OP_Des as opDes,
        op.OP_MBy as opModifyBy,
        TIMESTAMP(op.OP_MDate) as opModifyDate,
        op.OP_Name as opName,
        op.OP_NextStep as opNextStep,
        op.OP_Probability as opProbability,
        op.OP_CustID as custID,
        (SELECT var_name FROM ame_mt_cus WHERE var_id = op.OP_CustID) as custName,
        op.OP_ATo as userID,
        (SELECT `ame_user`.`var_name` FROM ame_user WHERE `ame_user`.`var_id` = op.OP_ATo) as username,
        op.OP_CampID as campID,
        (SELECT CA_Name FROM crm_camp WHERE CA_ID = op.OP_CampID) as campName,
        op.OP_LeadSourceID as sourceID,
        (SELECT LS_Name FROM crm_lead_source WHERE LS_ID = op.OP_LeadSourceID) as sourceName,
        op.OP_StageID as osId,
        (SELECT OS_Name FROM crm_opportunity_stage WHERE OS_ID = op.OP_StageID) as osName,
        op.OP_TypeID as otId,
        (SELECT OT_Name FROM crm_opportunity_type WHERE OT_ID = op.OP_TypeID) as otName ,
				op.OP_IsApproved isApproved
    FROM
        crm_opportunity op
		ORDER BY op.OP_ID DESC;

	ELSE 
		SELECT
			op.OP_ID as opId,
			op.OP_Amt as opAmount,
			TIMESTAMP(op.OP_CloseDate) as opCloseDate,
			op.OP_CBy as opCreateBy,
			(SELECT `ame_user`.`var_name` FROM ame_user WHERE `ame_user`.`var_id` = op.OP_CBy) 'opCreateByName',
			TIMESTAMP(op.OP_CDate) as opCreateDate,
			op.OP_Des as opDes,
			op.OP_MBy as opModifyBy,
			TIMESTAMP(op.OP_MDate) as opModifyDate,
			op.OP_Name as opName,
			op.OP_NextStep as opNextStep,
			op.OP_Probability as opProbability,
			op.OP_CustID as custID,
			(SELECT var_name FROM ame_mt_cus WHERE var_id = op.OP_CustID) as custName,
			op.OP_ATo as userID,
			(SELECT `ame_user`.`var_name` FROM ame_user WHERE `ame_user`.`var_id` = op.OP_ATo) as username,
			op.OP_CampID as campID,
			(SELECT CA_Name FROM crm_camp WHERE CA_ID = op.OP_CampID) as campName,
			op.OP_LeadSourceID as sourceID,
			(SELECT LS_Name FROM crm_lead_source WHERE LS_ID = op.OP_LeadSourceID) as sourceName,
			op.OP_StageID as osId,
			(SELECT OS_Name FROM crm_opportunity_stage WHERE OS_ID = op.OP_StageID) as osName,
			op.OP_TypeID as otId,
			(SELECT OT_Name FROM crm_opportunity_type WHERE OT_ID = op.OP_TypeID) as otName ,
			op.OP_IsApproved isApproved
		FROM
				crm_opportunity op 
		WHERE op.OP_ATo =  userId OR op.OP_CBy = userId
		ORDER BY op.OP_ID DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_LOAD`(userId varchar(255))
    DETERMINISTIC
BEGIN
	SELECT
        op.OP_ID as opId,
        op.OP_Amt as opAmount,
        CAST(op.OP_CloseDate AS date) as opCloseDate,
        op.OP_CBy as opCreateBy,
        CAST(op.OP_CDate AS date) as opCreateDate,
        op.OP_Des as opDes,
        op.OP_MBy as opModifyBy,
        CAST(op.OP_MDate AS date) as opModifyDate,
        op.OP_Name as opName,
        op.OP_NextStep as opNextStep,
        op.OP_Probability as opProbability,
        cust.var_id as custID,
        cust.var_name as custName,
        user.var_id as userID,
        user.var_name as username,
        camp.CA_ID as campID,
        camp.CA_Name as campName,
        leadsource.LS_ID as sourceID,
        leadsource.LS_Name as sourceName,
        ops.OS_ID as osId,
        ops.OS_Name as osName,
        opt.OT_ID as otId,
        opt.OT_Name as otName 
    FROM
        crm_opportunity op 
    INNER JOIN
        ame_mt_cus cust 
            ON op.OP_CustID=cust.var_id 
    LEFT OUTER JOIN
        ame_user user 
            ON op.OP_ATo=user.var_id 
    LEFT OUTER JOIN
        crm_camp camp 
            ON op.OP_CampID=camp.CA_ID 
    LEFT OUTER JOIN
        crm_lead_source leadsource 
            ON op.OP_LeadSourceID=leadsource.LS_ID 
    INNER JOIN
        crm_opportunity_stage ops 
            ON op.OP_StageID=ops.OS_ID 
    LEFT OUTER JOIN
        crm_opportunity_type opt 
            ON op.OP_TypeID=opt.OT_ID

		WHERE op.OP_IsApproved = 1
    ORDER BY op.OP_ID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_LOAD_BY_CAMP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_LOAD_BY_CAMP`(campId varchar(50))
    DETERMINISTIC
BEGIN
	SELECT OP_ID opId, OP_Name opName,OP_Amt opAmount,  OP_CloseDate opCloseDate, OP_CustID custID, 
				 COALESCE(c.var_name,'') custName, 
				 OP_StageID stageId, 
         COALESCE(ps.OS_Name,'') stageName 
	FROM crm_opportunity p
	LEFT JOIN ame_mt_cus c ON c.var_id = p.OP_CustID
	LEFT JOIN crm_opportunity_stage ps ON ps.OS_ID = p.OP_StageID
	WHERE OP_CampID = campId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_QUOTE_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_QUOTE_LIST`(IN `opId` varchar(150))
    DETERMINISTIC
BEGIN
	SELECT
		quote.var_id quoteId,
		quote.TotalAmt totalAmmount,
		quote.SalDate quoteDate,
		quote.StartDate startDate,
		quote.ExpireDate expireDate,
		emp.var_id empId,
		emp.var_name empName,
		L_ID opQuoteId
		FROM
			ame_ar_quo quote
		INNER JOIN
			crm_opportunity_quote opquote
				ON quote.var_id = opquote.QuotID
		LEFT OUTER JOIN 
			ame_mt_emp emp
				ON quote.var_empid = emp.var_id
		WHERE opquote.OP_ID = opId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_SO_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_SO_LIST`(IN `opId` varchar(11))
    DETERMINISTIC
BEGIN
	
	SELECT 
		 sale.var_id saleOrderId,
		 sale.TotalAmt totalAmount,
		 sale.SalDate saleOrderDate,
		 sale.DueDate saleDueDate,
		 emp.var_id empId,
		 emp.var_name empName,
		 L_ID opSaleOrderId
	FROM		
		ame_ar_so sale
	INNER JOIN
		crm_opportunity_saleorder opsale
			ON sale.var_id = opsale.S_O_ID
	LEFT OUTER JOIN 
		ame_mt_emp emp 
			ON sale.var_empid = emp.var_id
	WHERE opsale.OP_ID = opId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_STAGE_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_STAGE_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT OS_ID 'osId', COALESCE(OS_Name, '') 'osName' FROM crm_opportunity_stage ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_STARTUP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_STARTUP`(oppId varchar(150), userId varchar(150))
    DETERMINISTIC
BEGIN
	CALL CRM_PRO_USER_LIST_COM('');
	CALL CRM_PRO_OPP_TYPE_LOAD();
	CALL CRM_PRO_OPP_STAGE_LOAD();
	CALL CRM_PRO_CUSTOMER_LOAD(userId);
	CALL CRM_PRO_PRICE_CODE_LOAD();
	CALL CRM_PRO_CLASS_LOAD(userId);
	CALL CRM_PRO_CAMP_LOAD(userId);
	CALL CRM_PRO_LEAD_SOURCE_LOAD();
	
	IF oppId <> '' THEN
		CALL CRM_PRO_OPP_GET_BY_ID(oppId);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_TYPE_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_TYPE_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT OT_ID 'otId', COALESCE(OT_Name,'') 'otName' FROM crm_opportunity_type;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_UPDATE_STAGE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_UPDATE_STAGE`(IN `oppID` varchar(255),IN `stageID` int,IN `cusID` varchar(255))
    DETERMINISTIC
BEGIN
	UPDATE crm_opportunity SET OP_StageID = stageID WHERE OP_ID = oppID AND OP_CustID = cusID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPP_VIEW`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPP_VIEW`(IN `custId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COALESCE((SELECT COUNT(*) FROM crm_call WHERE CL_RToID = custId),0) as cCall,
         COALESCE((SELECT COUNT(*) FROM crm_meeting WHERE M_RToID = custId),0) as cMeeting,
				 COALESCE((SELECT COUNT(*) FROM crm_task WHERE TA_RToID = custId),0) as cTask,
				 COALESCE((SELECT COUNT(*) FROM crm_event WHERE EV_RToID = custId),0) as cEvent ;
	CALL CRM_PRO_OPP_GET_BY_ID(custId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_OPTION_TYPE_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_OPTION_TYPE_LIST`(var_table varchar(150))
    DETERMINISTIC
BEGIN
	IF var_table = 'CAMP_STATUS' THEN
		SELECT COALESCE(CAS_ID,'') as 'statusID', COALESCE(CAS_Name,'') as 'statusName' FROM crm_camp_status ORDER BY crm_camp_status.CAS_Name;
	ELSEIF var_table = 'CAMP_TYPE' THEN
		SELECT COALESCE(crm_camp_type.CAT_ID,'') as 'typeID', COALESCE(crm_camp_type.CAT_Name,'') as 'typeName' FROM crm_camp_type ORDER BY crm_camp_type.CAT_Name;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_PRICE_CODE_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_PRICE_CODE_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT var_id 'priceCode', var_name 'priceCodeName' FROM ame_mt_pri_cod;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_QUOTE_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_QUOTE_LIST`(userId varchar(150))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	IF roleType = 1 THEN	
		SELECT 
			qt.var_id AS saleId,
			COALESCE(qt.var_ref, '') 'reference',
			COALESCE(qt.var_desc,'') 'remark',
			DATE_FORMAT(qt.dat_date, '%d-%b-%Y') as 'saleDate',
			DATE_FORMAT(qt.dat_due, '%d-%b-%Y') as 'dueDate',
			qt.var_status 'PostStatus',
			COALESCE(qt.dou_funsub,'') 'totalAmt',
			COALESCE(qt.dou_fundisdol ,'') 'totalDis' , 
			COALESCE( qt.dou_funnet ,'') 'netTotalAmt',
			c.var_id AS custId, 
			c.var_name AS custName, 
			c.var_addr AS custAddress, 
			e.var_id AS empName,
			e.var_name AS empId,
			cz.var_id AS classId,
			cz.var_name AS className,
			qt.var_auth_status approvedStatus
		FROM ame_ar_quo qt
		LEFT OUTER JOIN ame_mt_cus c
			ON c.var_id = qt.var_cusid
		LEFT OUTER JOIN ame_mt_emp e
			ON e.var_id = qt.var_empid
		LEFT OUTER JOIN ame_mt_cla cz
			ON cz.var_id = qt.var_claid
		order by qt.var_id DESC,DATE(qt.dat_date) DESC;
	else
		SELECT 
			qt.var_id AS saleId,
			COALESCE(qt.var_ref, '') 'reference',
			COALESCE(qt.var_desc,'') 'remark',
			DATE_FORMAT(qt.dat_date, '%d-%b-%Y') as 'saleDate',
			DATE_FORMAT(qt.dat_due, '%d-%b-%Y') as 'dueDate',
			qt.var_status 'PostStatus',
			COALESCE(qt.dou_funsub,'') 'totalAmt',
			COALESCE(qt.dou_fundisdol ,'') 'totalDis' , 
			COALESCE( qt.dou_funnet ,'') 'netTotalAmt',
			c.var_id AS custId, 
			c.var_name AS custName, 
			c.var_addr AS custAddress, 
			e.var_id AS empName,
			e.var_name AS empId,
			cz.var_id AS classId,
			cz.var_name AS className,
			qt.var_auth_status approvedStatus
		FROM ame_ar_quo qt
		LEFT OUTER JOIN ame_mt_cus c
			ON c.var_id = qt.var_cusid
		LEFT OUTER JOIN ame_mt_emp e
			ON e.var_id = qt.var_empid
		LEFT OUTER JOIN ame_mt_cla cz
			ON cz.var_id = qt.var_claid
		WHERE qt.var_empid = CRM_FUN_GET_EMP_ID(userId)
		order by qt.var_id DESC,DATE(qt.dat_date) DESC;
	end if;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_ROLE_LOAD_BY_USER`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_ROLE_LOAD_BY_USER`(var_user_id varchar(150))
    DETERMINISTIC
BEGIN
	SELECT DISTINCT c.ModuleID 'moduleId', 
				 c.Remarks 'moduleName',
		COALESCE(tbl.RM_Access,'NO') 'roleAccess', 
		COALESCE(tbl.RM_Delete,'NO') 'roleDelete' ,
		COALESCE(tbl.RM_Edit,'NO') 'roleEdit', 
		COALESCE(tbl.RM_Export,'NO') 'roleExport',  
		COALESCE(tbl.RM_Import,'NO') 'roleImport', 
		COALESCE(tbl.RM_List,'NO') 'roleList', 
		COALESCE(tbl.RM_View,'NO') 'roleView'  
	FROM crm_numberprefix c 
	LEFT JOIN (
			SELECT RM_ModuleID,RM_Access,RM_Delete,RM_Edit,RM_Export,RM_Import,RM_List,RM_View,RM_RoleID
			FROM crm_role_detail WHERE RM_RoleID = CRM_FUN_GET_ROLE_BY_UID(var_user_id)
	) as tbl  
	ON tbl.RM_ModuleID = c.ModuleID
	WHERE c.Status = 1
	ORDER BY c.ModuleID
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_ROLE_START_UP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_ROLE_START_UP`(var_role_id varchar(255))
    DETERMINISTIC
BEGIN
	CALL crm_listSystemModulesByRoleId(var_role_id);
	SELECT * FROM crm_notification WHERE RM_ID = var_role_id;
	SELECT RMT_ID 'typeId', RMT_Name 'typeName' FROM crm_role_type;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_SALE_ORDER_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_SALE_ORDER_LIST`(var_user_id varchar(150))
    DETERMINISTIC
BEGIN
	#Routine body goes here...

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_TASK_FIND_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_TASK_FIND_BY_ID`(IN `taskId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT
		task.TA_ID taskId,
		task.TA_Subject taskSubject,
		DATE_FORMAT(task.TA_StartDate,'%d/%m/%Y %h:%i %p') taskStartDate,
		DATE_FORMAT(task.TA_DueDate,'%d/%m/%Y %h:%i %p') taskDueDate,
		task.TA_Priority taskPriority,
		tst.TS_ID taskStatusId,
		tst.TS_Name taskStatusName,
		task.TA_Des taskDes,
		task.TA_RToType taskRelatedToModule,
		task.TA_RToID taskRelatedToId,
		findModuleDetailsByModuleNameAndItsId(task.TA_RToType,task.TA_RToID) AS taskRelatedName,
		con.CO_ID conID,
		con.CO_FirstName conFirstname,
		con.CO_LastName conLastname,
		assignTo.var_id userID,
		assignTo.var_name username,
		task.TA_CBy taskCreateBy,
		DATE_FORMAT(task.TA_CDate,'%d/%m/%Y %h:%i %p') taskCreateDate,
		task.TA_MBy taskModifiedBy,
		CAST(task.TA_MDate AS DATE) taskModifiedDate
		
	FROM 
		crm_task task
	INNER JOIN
		crm_task_status tst
				ON task.TA_StatusID = tst.TS_ID
	LEFT OUTER JOIN 
		crm_contact con 
				ON task.TA_ContactID = con.CO_ID
	LEFT OUTER JOIN
		ame_user assignTo
				ON task.TA_ATo = assignTo.var_id
	WHERE task.TA_ID = taskId;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_TASK_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_TASK_LIST`(IN `userId` varchar(50))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT var_crm_role FROM ame_user WHERE var_id = userId);
	IF roleType = 1 THEN
		SELECT
			task.TA_ID taskId,
			task.TA_Subject taskSubject,
			DATE_FORMAT(task.TA_StartDate,'%d/%m/%Y %h:%i %p') taskStartDate,
			DATE_FORMAT(task.TA_DueDate,'%d/%m/%Y %h:%i %p') taskDueDate,
			task.TA_Priority taskPriority,
			tst.TS_ID taskStatusId,
			tst.TS_Name taskStatusName,
			task.TA_Des taskDes,
			task.TA_RToType taskRelatedToModule,
			task.TA_RToID taskRelatedToId,
			findModuleDetailsByModuleNameAndItsId(task.TA_RToType,task.TA_RToID) AS taskRelatedName,
			con.CO_ID conID,
			con.CO_FirstName conFirstname,
			con.CO_LastName conLastname,
			assignTo.var_id userID,
			assignTo.var_name username,
			task.TA_CBy taskCreateBy,
			(SELECT var_name FROM ame_user WHERE var_id = task.TA_CBy) taskCreateByName,
			DATE_FORMAT(task.TA_CDate,'%d/%m/%Y %h:%i %p') taskCreateDate,
			task.TA_MBy taskModifiedBy,
			CAST(task.TA_MDate AS DATE) taskModifiedDate
			
		FROM 
			crm_task task
		INNER JOIN
			crm_task_status tst
					ON task.TA_StatusID = tst.TS_ID
		LEFT OUTER JOIN 
			crm_contact con 
					ON task.TA_ContactID = con.CO_ID
		LEFT OUTER JOIN
			ame_user assignTo
					ON task.TA_ATo = assignTo.var_id
		ORDER BY task.TA_ID DESC;
	ELSE	
		SELECT
			task.TA_ID taskId,
			task.TA_Subject taskSubject,
			DATE_FORMAT(task.TA_StartDate,'%d/%m/%Y %h:%i %p') taskStartDate,
			DATE_FORMAT(task.TA_DueDate,'%d/%m/%Y %h:%i %p') taskDueDate,
			task.TA_Priority taskPriority,
			tst.TS_ID taskStatusId,
			tst.TS_Name taskStatusName,
			task.TA_Des taskDes,
			task.TA_RToType taskRelatedToModule,
			task.TA_RToID taskRelatedToId,
			findModuleDetailsByModuleNameAndItsId(task.TA_RToType,task.TA_RToID) AS taskRelatedName,
			con.CO_ID conID,
			con.CO_FirstName conFirstname,
			con.CO_LastName conLastname,
			assignTo.var_id userID,
			assignTo.var_name username,
			task.TA_CBy taskCreateBy,
			(SELECT var_name FROM ame_user WHERE var_id = task.TA_CBy) taskCreateByName,
			DATE_FORMAT(task.TA_CDate,'%d/%m/%Y %h:%i %p') taskCreateDate,
			task.TA_MBy taskModifiedBy,
			CAST(task.TA_MDate AS DATE) taskModifiedDate
			
		FROM 
			crm_task task
		INNER JOIN
			crm_task_status tst
					ON task.TA_StatusID = tst.TS_ID
		LEFT OUTER JOIN 
			crm_contact con 
					ON task.TA_ContactID = con.CO_ID
		LEFT OUTER JOIN
			ame_user assignTo
					ON task.TA_ATo = assignTo.var_id
		WHERE task.TA_ATo = userId OR task.TA_CBy = userId
		ORDER BY task.TA_ID DESC;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_TASK_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_TASK_LOAD`(IN par_user VARCHAR(255))
    DETERMINISTIC
BEGIN
	SELECT TS_ID 'taskStatusId', TS_Name 'taskStatusName' FROM crm_task_status ORDER BY TS_ID;
	SELECT CO_ID 'conID', CONCAT(CO_Salutation,' ',CO_FirstName,' ',CO_LastName) 'fullName' FROM crm_contact WHERE CO_IsApproved = 1;
	CALL CRM_PRO_USER_SUBORDINATE_LIST_BY_USERNAME(par_user);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_TASK_RELATED_MODULE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_TASK_RELATED_MODULE`(IN `moduleId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT
		task.TA_ID taskId,
		task.TA_Subject taskSubject,
		DATE_FORMAT(task.TA_StartDate,'%d/%m/%Y %h:%i %p') taskStartDate,
		DATE_FORMAT(task.TA_DueDate,'%d/%m/%Y %h:%i %p') taskDueDate,
		task.TA_Priority taskPriority,
		tst.TS_ID taskStatusId,
		tst.TS_Name taskStatusName,
		task.TA_Des taskDes,
		con.CO_ID conID,
		con.CO_FirstName conFirstname,
		con.CO_LastName conLastname,
		COALESCE(assignTo.var_id,'') userID,
		COALESCE(assignTo.var_name,'') username,
		task.TA_CBy taskCreateBy,
		DATE_FORMAT(task.TA_CDate,'%d/%m/%Y %h:%i %p') taskCreateDate,
		task.TA_MBy taskModifiedBy,
		CAST(task.TA_MDate AS DATE) taskModifiedDate
		
	FROM 
		crm_task task
	INNER JOIN
		crm_task_status tst
				ON task.TA_StatusID = tst.TS_ID
	LEFT OUTER JOIN 
		crm_contact con 
				ON task.TA_ContactID = con.CO_ID
	LEFT OUTER JOIN
		ame_user assignTo
				ON task.TA_ATo = assignTo.var_id
	WHERE task.TA_RToID = moduleId
	ORDER BY task.TA_CDate DESC;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_TASK_START_UP`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_TASK_START_UP`(var_obj_id varchar(50))
    DETERMINISTIC
BEGIN
	CALL CRM_PRO_TASK_STATUS_LOAD();
	CALL CRM_PRO_USER_LIST_COM('');
	CALL CRM_PRO_CONTACT_LOAD();
	IF var_obj_id <> '' THEN 
		CALL CRM_PRO_TASK_FIND_BY_ID(var_obj_id);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_TASK_STATUS_LOAD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_TASK_STATUS_LOAD`()
    DETERMINISTIC
BEGIN
	SELECT TS_ID taskStatusId, TS_Name taskStatusName FROM crm_task_status;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_TEMP_CREDIT_ADD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_TEMP_CREDIT_ADD`(v_id varchar(100), v_cusid varchar(150),v_status varchar(100), v_desc varchar(255), v_userid varchar(150),d_from varchar(250), d_to varchar(250), dou_amount DOUBLE, crm_relate varchar(150), crm_relateid varchar(150))
    DETERMINISTIC
BEGIN
	DECLARE var_lastid VARCHAR(100) DEFAULT "";
	DECLARE v_cur VARCHAR(100) DEFAULT CRM_FUN_CUST_GET_CUR_BY_CID(v_cusid);
	DECLARE dou_rate DOUBLE DEFAULT CRM_FUN_CUR_GET_RATE(v_cur);
	SET var_lastid = CRM_FUN_CONFIG_AME_GET_LASTID('AR_IN_TC',1);
	IF var_lastid <> '' THEN
		INSERT INTO `ame_mt_tem_tc` (
			`var_id`,
			`var_type`,
			`var_cusid`,
			`var_status`,
			`var_desc`,
			`var_cur`,
			`var_create`,
			`dat_date`,
			`dat_from`,
			`dat_to`,
			`dat_create`,
			`dou_amt`,
			`dou_funamt`,
			`dou_rate`,
			`tin_editable`,
			`var_crm_relate`,
			`var_crm_relateid`
		)
		VALUES(var_lastid, 'Customer',v_cusid,v_status,v_desc,v_cur,v_userid,NULL,d_from,d_to, NOW(),dou_amount, (dou_amount*dou_rate),dou_rate, 1,crm_relate,crm_relateid );
		CALL crm_approval_templory(var_lastid, v_userid,'Temporary Credit');
	END IF;
	SELECT var_lastid as 'lastId', CRM_FUN_CONFIG_IMG_PATH() AS 'IMG_PATH';
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_TEMP_CREDIT_UPDATE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_TEMP_CREDIT_UPDATE`(v_id varchar(100), v_cusid varchar(150),v_status varchar(100), v_desc varchar(255), v_userid varchar(150),d_from varchar(250), d_to varchar(250), dou_amount DOUBLE, crm_relate varchar(150), crm_relateid varchar(150))
    DETERMINISTIC
BEGIN
	DECLARE v_cur VARCHAR(100) DEFAULT CRM_FUN_CUST_GET_CUR_BY_CID(v_cusid);
	DECLARE dou_rate DOUBLE DEFAULT CRM_FUN_CUR_GET_RATE(v_cur);
	UPDATE `ame_mt_tem_tc` SET `var_type`='Customer', `var_cusid`= v_cusid, `var_status`=v_status, `var_desc`=v_desc, `var_cur`=v_cur, `var_modify`=v_userid, `dat_date`=NULL, `dat_from`=d_from, 
	`dat_to`=d_to, `dat_modify`=NOW(), `dou_amt`=dou_amount, `dou_funamt`=(dou_amount*dou_rate), `dou_rate`=dou_rate, `tin_editable`=1, `var_crm_relate`=crm_relate, `var_crm_relateid`=crm_relateid WHERE (`var_id`=v_id);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_TEMP_OD_ADD`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_TEMP_OD_ADD`(v_id varchar(100), v_cusid varchar(150),v_status varchar(100), v_desc varchar(255), v_userid varchar(150),d_from varchar(250), d_to varchar(250), crm_relate varchar(150), crm_relateid varchar(150))
    DETERMINISTIC
BEGIN
	DECLARE var_lastid VARCHAR(100) DEFAULT "";
	SET var_lastid = CRM_FUN_CONFIG_AME_GET_LASTID('AR_IN_ODD',1);
	IF var_lastid <> '' THEN
		INSERT INTO `ame_mt_tem_odd` (
			`var_id`,
			`var_type`,
			`var_cusid`,
			`var_status`,
			`var_desc`,
			`var_create`,
			`dat_date`,
			`dat_from`,
			`dat_to`,
			`dat_create`,
			`tin_editable`,
			`var_crm_relate`,
			`var_crm_relateid`
		)
		VALUES(var_lastid, 'Customer',v_cusid,v_status,v_desc,v_userid,NULL,d_from,d_to, NOW(), 1,crm_relate,crm_relateid );
		CALL crm_approval_templory(var_lastid,v_userid,'Over Due Date');
	END IF;
	SELECT var_lastid as 'lastId', CRM_FUN_CONFIG_IMG_PATH() AS 'IMG_PATH';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_TEMP_OD_UPDATE`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_TEMP_OD_UPDATE`(v_id varchar(100), v_cusid varchar(150),v_status varchar(100), v_desc varchar(255), v_userid varchar(150),d_from varchar(250), d_to varchar(250), crm_relate varchar(150), crm_relateid varchar(150))
    DETERMINISTIC
BEGIN
	UPDATE `ame_mt_tem_odd` SET `var_type`='Customer', `var_cusid`= v_cusid, `var_status`=v_status, `var_desc`=v_desc, `var_modify`=v_userid, `dat_date`=NULL, `dat_from`=d_from, 
	`dat_to`=d_to, `dat_modify`=NOW(),`tin_editable`=1, `var_crm_relate`=crm_relate, `var_crm_relateid`=crm_relateid WHERE (`var_id`=v_id);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_USER_ACTIVITY_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_USER_ACTIVITY_LIST`()
    DETERMINISTIC
BEGIN
	SELECT 
		AC_ID 'actId',
		TIMESTAMP(AC_Date) 'actCreateDate',
		AC_Action 'action',
		AC_ModuleName 'moduleName',
		AC_ModuleID 'moduleId',
		AC_ByUser 'userId',
		(SELECT u.var_name FROM ame_user u WHERE u.var_id = AC_ByUser) 'userName'
	FROM crm_activity ORDER BY AC_Date DESC, AC_ID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_USER_LIST_COM`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_USER_LIST_COM`(IN `username` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
		u.var_id userID, 
		u.var_name username
	FROM 
		ame_user u
	INNER JOIN 
		ame_user_app ua 
			ON u.var_id = ua.var_id
	WHERE ua.var_appid ='CRM' AND u.tin_inactive=0 #AND u.URoleID <> (SELECT RM_ID FROM crm_role WHERE RM_Name = 'CRM_ADMINISTRATOR')
	ORDER BY u.var_name ASC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_USER_LOAD_COMPONENT`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_USER_LOAD_COMPONENT`()
    DETERMINISTIC
BEGIN
	SELECT 
		u.var_id userID, 
		u.var_name username
	FROM 
		ame_user u
	INNER JOIN 
		ame_user_app ua 
			ON u.var_id = ua.var_id
	WHERE ua.var_appid ='CRM' AND u.tin_inactive=0 #AND u.URoleID <> (SELECT RM_ID FROM crm_role WHERE RM_Name = 'CRM_ADMINISTRATOR')
	ORDER BY u.var_name ASC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_USER_LOGIN`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_USER_LOGIN`(IN `USERID` varchar(50), IN `APP` varchar(5))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(u.var_id,'') 'UID',COALESCE(u.var_name,'') 'UName', COALESCE(u.var_pwd,'') 'PWD', COUNT(u.var_id) as 'HAS',COUNT(a.var_id) as 'PMS'
	FROM ame_user u
	LEFT JOIN ame_user_app a on u.var_id = a.var_id AND a.var_appid = APP AND u.tin_inactive = 0
	WHERE u.var_id = USERID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_PRO_USER_SUBORDINATE_LIST_BY_USERNAME`;
DELIMITER |
CREATE PROCEDURE `CRM_PRO_USER_SUBORDINATE_LIST_BY_USERNAME`(IN `username` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
		u.var_id userID, 
		u.var_name username
	FROM 
		ame_user u
	INNER JOIN 
		ame_user_app ua 
			ON u.var_id = ua.var_id
	WHERE ua.var_appid ='CRM' #AND u.URoleID <> (SELECT RM_ID FROM crm_role WHERE RM_Name = 'CRM_ADMINISTRATOR')
	ORDER BY u.var_name ASC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_query_to_json`;
DELIMITER |
CREATE PROCEDURE `crm_query_to_json`()
    DETERMINISTIC
BEGIN
	SELECT LocationID 'locationId', Des 'locationName' from tbllocation;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_quotation_check_id`;
DELIMITER |
CREATE PROCEDURE `crm_quotation_check_id`(in var_sale_id varchar(255))
    DETERMINISTIC
BEGIN
	select SalID FROM tblsbquote WHERE SalID=var_sale_id  AND PostStatus= 'Open';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_quote_item_change`;
DELIMITER |
CREATE PROCEDURE `crm_quote_item_change`(in `var_itemid` varchar(100), in `var_pricecode` varchar(100))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(iu.ItemID,'') 'itemId',COALESCE((SELECT VAT FROM tblitem WHERE ItemID=var_itemid),0) 'VAT',COALESCE((SELECT STax FROM tblitem WHERE ItemID=var_itemid),0) 'ST', iu.UomID,iu.DefSal, tblip.PriceAmount,tblip.OverridePrice FROM tblitemuom iu
	LEFT JOIN (SELECT UomID,PriceAmount,OverridePrice FROM tblitempricing WHERE ItemID = var_itemid AND PriceCode = var_pricecode) as tblip ON iu.UomID=tblip.UomID
	WHERE iu.ItemID = var_itemid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_quote_obj`;
DELIMITER |
CREATE PROCEDURE `crm_quote_obj`(in `var_sale_id` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE v_finished INTEGER DEFAULT 0;
	DECLARE var_item_id varchar(255) DEFAULT "";
	DECLARE var_cust_id varchar(255) DEFAULT "";
	DECLARE var_price_id varchar(255) DEFAULT "";
	DEClARE CustID_Cursor CURSOR FOR SELECT ItemID FROM tblsbquotedetails WHERE SalID = var_sale_id ORDER BY LineNo;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
	SELECT CustID, PriceCode INTO var_cust_id, var_price_id FROM tblsbquote WHERE SalID = var_sale_id LIMIT 1;
	
	SELECT SalID 'saleId', COALESCE(SalType, '') 'salType',COALESCE(classId,'') 'classId', COALESCE(Remark,'') 'remark', COALESCE(SalReference,'') 'salReference', COALESCE(PriceCode,'') 'priceCode', COALESCE(PostStatus,'') 'postStatus',COALESCE(EmpID,'') 'empId', COALESCE(CustID,'') 'custId', 
       COALESCE(TotalAmt,0) 'tAmount', COALESCE(DisInvDol,0) 'disInvDol', COALESCE(DisInvPer,0) 'disInvPer',COALESCE(DATE_FORMAT(SalDate,'%e-%b-%Y'),'') 'quoteDate', COALESCE(DATE_FORMAT(StartDate,'%e-%b-%Y'),'') 'startDate', COALESCE(DATE_FORMAT(ExpireDate,'%e-%b-%Y'),'') 'expireDate', COALESCE(TotalDis,0) 'totalDis', COALESCE(TotalSTax,0) 'totalSTax', COALESCE(TotalVTax,0) 'totalVTax', COALESCE(NetTotalAmt,0) 'netTotalAmt', COALESCE(ShipTo,'') 'shipTo'
	FROM tblsbquote WHERE SalID = var_sale_id;

	SELECT SalID AS saleId, LineNo AS lineNo, ItemID AS itemId, UomID AS uomId, LocationID AS locationId, SalQty AS saleQuantity, UnitPrice AS unitPrice, TotalAmt AS totalAmt,   
				 PostStatus AS postStatus, NetTotalAmt AS netTotalAmt, DisDol AS disDol, DisPer AS disPer, STaxDol AS staxDol,   
				 STaxPer AS staxPer, VTaxDol AS vtaxDol, VTaxPer as  vtaxPer, ItemStatus AS itemStatus, ReportPrice AS reportPrice,  
				 Factor AS factor, IsVariable AS isVariable, ClassID AS classId, DisInv AS disInv	 ,COALESCE(var_item_detail ,'') description
	FROM tblsbquotedetails WHERE SalID = var_sale_id ORDER BY LineNo ASC ;

	OPEN CustID_Cursor;
		GetCustID: LOOP
			FETCH CustID_Cursor INTO var_item_id;
				IF v_finished = 1 THEN
					LEAVE GetCustID;
				END IF;
				CALL crm_sale_order_item_change(var_price_id,var_item_id,var_cust_id);
		END LOOP GetCustID;
	CLOSE CustID_Cursor;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_quote_obj_not_uom_list`;
DELIMITER |
CREATE PROCEDURE `crm_quote_obj_not_uom_list`(in `var_sale_id` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT SalID 'saleId', COALESCE(SalType, '') 'salType',COALESCE(classId,'') 'classId', COALESCE(Remark,'') 'remark', COALESCE(SalReference,'') 'salReference', COALESCE(s.PriceCode,'') 'priceCode', COALESCE(PostStatus,'') 'postStatus',COALESCE(EmpID,'') 'empId', COALESCE(s.CustID,'') 'custId', COALESCE(c.custname,'') 'custName',  COALESCE(CONCAT(c.CustTel1,'/',c.CustTel2),'') 'custTel', COALESCE(c.custaddress, '') 'shipAdd', 
       COALESCE(TotalAmt,0) 'tAmount', COALESCE(DisInvDol,0) 'disInvDol', COALESCE(DisInvPer,0) 'disInvPer',DATE_FORMAT(SalDate,'%e-%b-%Y') 'salDate', DATE_FORMAT(ExpireDate,'%e-%b-%Y') 'dueDate', COALESCE(TotalDis,0) 'totalDis', COALESCE(TotalSTax,0) 'totalSTax', COALESCE(TotalVTax,0) 'totalVTax', COALESCE(NetTotalAmt,0) 'netTotalAmt', COALESCE(ShipTo,'') 'shipTo' ,COALESCE((SELECT shipname FROM tblshipaddress WHERE docid= c.CustID AND shipid = ShipTo ), '') 'shipAdd1'
	FROM tblsbquote s
	LEFT JOIN tblcustomer c on c.custid = s.custid
	WHERE SalID = var_sale_id;

	SELECT SalID AS saleId, LineNo AS lineNo, sd.ItemID AS itemId, COALESCE((select ItemName from tblitem i WHERE i.ItemID = sd.ItemID limit 1), '') 'itemName', UomID AS uomId, LocationID AS locationId, SalQty AS saleQuantity, UnitPrice AS unitPrice, TotalAmt AS totalAmt,   
				 PostStatus AS postStatus, NetTotalAmt AS netTotalAmt, DisDol AS disDol, DisPer AS disPer, STaxDol AS staxDol,   
				 STaxPer AS staxPer, VTaxDol AS vtaxDol, VTaxPer as  vtaxPer, ItemStatus AS itemStatus, ReportPrice AS reportPrice,  
				 Factor AS factor, IsVariable AS isVariable, ClassID AS classId, DisInv AS disInv	 ,COALESCE(var_item_detail ,'') description
	FROM tblsbquotedetails sd WHERE SalID = var_sale_id ORDER BY LineNo ASC ;

	SELECT ComName 'comEN', ComNameKh 'comKH', ComAddEn 'comAddrEN', ComAddKH 'comAddrKH', Logo1 'logo' FROM tblcompanyreport;
	select ImagePath FROM tblconfiguration LIMIT 1 ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_quote_startup_page`;
DELIMITER |
CREATE PROCEDURE `crm_quote_startup_page`(in var_user_id varchar(255), in var_obj_id varchar(255))
    DETERMINISTIC
BEGIN
DECLARE var_empId varchar(255);
DECLARE var_img_url varchar(255);
DECLARE var_rt varchar(255);
SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_user_id LIMIT 1)), 0);
SET var_empId = COALESCE((SELECT EmpID FROM tbluseremployee WHERE UID = var_user_id),'');

IF var_rt = '1' THEN
	SELECT CustID 'custId', COALESCE(CustName, '') 'custName' , COALESCE(PriceCode,'') 'priceCode', COALESCE(TermNetDueIn,0) 'termNetDueIn', COALESCE(AID,'') shipId, COALESCE(TermCreditLimit,'') 'termCreditLimit'  FROM tblcustomer WHERE Inactive=0 ORDER BY CustID;
	SELECT COALESCE(EmpID,'') 'empId', COALESCE(EmpName,'') 'empName' FROM tblemployee WHERE Inactive=0 AND EmpID IN(SELECT EmpID FROM tblemployeesystemrole WHERE RoleName = 'Sale Representative') ORDER BY EmpID;
	SELECT ec.EmpID 'empId', ec.CustID 'custId' from  tblemployeecustomer ec ORDER BY ec.CustID;
ELSE
	SELECT CustID 'custId', COALESCE(CustName, '') 'custName' , COALESCE(PriceCode,'') 'priceCode', COALESCE(TermNetDueIn,0) 'termNetDueIn', COALESCE(AID,'') shipId, COALESCE(TermCreditLimit,'') 'termCreditLimit'  FROM tblcustomer WHERE Inactive=0 and CustID IN (SELECT CustID from tblemployeecustomer WHERE EmpID = var_empId) ORDER BY CustID;
	SELECT COALESCE(EmpID,'') 'empId', COALESCE(EmpName,'') 'empName' FROM tblemployee WHERE Inactive=0 AND EmpID = var_empId ORDER BY EmpID;
	SELECT ec.EmpID 'empId', ec.CustID 'custId' FROM tblemployeecustomer ec WHERE ec.EmpID=var_empId ORDER BY ec.CustID;
END IF;

SELECT COALESCE(SysCode,'') 'systemCode', COALESCE(LocationID,'') 'locationId', COALESCE(Des,'') 'locationName' FROM tbllocation ORDER BY LocationID;
SELECT COALESCE(ClassID,'') 'classId', COALESCE(Des, '') 'className' FROM tblclass WHERE Inactive=0;
SELECT COALESCE(ItemID,'') 'itemId',COALESCE(ItemName,'') 'itemName2', COALESCE(crm_fullname(itemcode,ItemName),'') 'itemName', crm_fullname_adv(ItemID,ItemName,itemcode) 'fullname' , COALESCE(itemcode,'') 'itemCode', COALESCE(itembarcode, '') 'itemBarcode' , COALESCE(ImagePath , '') 'imagePath' FROM tblitem WHERE Inactive = 0 and ItemID <> '' AND ItemID is not NULL AND tblitem.`status` = 'Inventory Part'  ORDER BY ItemID;
SELECT COALESCE(q.SalID,'') 'salId', COALESCE(DATE(q.SalDate),'') 'salDate', COALESCE(q.PostStatus,'') 'postStatus', COALESCE(q.SalReference,'') 'salReference', COALESCE(q.CustID,'') 'custId', COALESCE((SELECT CustName FROM tblcustomer WHERE CustID = q.CustID),'') 'custName', COALESCE(NetTotalAmt,'') 'netTotalAme' FROM tblsbquote q ;
SELECT COALESCE(PriceCode,'') 'priceCodeId', COALESCE(Description,'') 'priceCodeName'  FROM tblpricecode ORDER BY PriceCode;
SELECT COALESCE(docid, '') 'custId', COALESCE(shipid, '') 'shipId', COALESCE(shipname, '') 'shipName' FROM tblshipaddress WHERE moduleid='MT-CUS' AND docid <> '' OR docid is NULL AND inactive = 0;
SELECT EmpID 'empId' FROM tbluseremployee WHERE UID = var_user_id;
IF var_obj_id <> '' THEN
select ImagePath 'ImagePath' FROM tblconfiguration LIMIT 1 ;
CAll crm_quote_obj(var_obj_id);
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_receipt_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_receipt_by_id`(var_saleid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT  s.RcpID 'rcpId',RcpReference 'reference', COALESCE(DATE(s.RcpDate),'') 'rcpDate', s.CustID 'custId', COALESCE(c.CustName,'') 'custName',COALESCE(s.TotalRcpAmount,0) 'rcpTotalAmt',
		s.RcpType 'pmtType',s.PostStatus 'postStatus', s.ClassID 'classId', COALESCE((SELECT tblclass.Des FROM tblclass WHERE tblclass.ClassID=s.ClassID),'') 'className',
		s.rcpmethodref 'pmtReference',s.remark 'remark', COALESCE(s.TotalRcpAmount,0) 'rcpAmount',COALESCE(s.TotalDiscount,0) 'totalDis',COALESCE(s.TotalCash,0) 'totalCash', COALESCE(s.AppliedAmt,0) 'appliedAmt',
		s.PrefixNumber 'prefix',s.rcpmethod 'pmtMethod',s.CashAccNo 'accountId',

		sd.RevAccID 'revAccId',sd.AppliedAmt 'appliedAmtD',sd.ClassID 'classIdD',COALESCE((SELECT tblclass.Des FROM tblclass WHERE tblclass.ClassID=sd.ClassID),'') 'classNameD',
		sd.SalID 'saleId',sd.PostStatus 'postStatusD',sd.LineNo 'line',sd.Discount 'discountD', sd.RcpAmount 'rcpAmountD',sd.transdescription 'transDescription',
		sal.SalReference 'saleReference',DATE(sal.SalDate) 'saleDate',COALESCE(sal.NetTotalAmt,0) 'saleNetTotalAmt',
		COALESCE((SELECT SUM(COALESCE(tblreceiptdetails.Discount,0)+COALESCE(tblreceiptdetails.RcpAmount,0)+COALESCE(tblreceiptdetails.AppliedAmt,0)) FROM tblreceiptdetails WHERE tblreceiptdetails.SalID=sal.SalID),0) 'rcpToDate'
	FROM tblreceipt s
	LEFT JOIN tblreceiptdetails sd ON s.RcpID = sd.RcpID
	LEFT JOIN tblcustomer c ON c.CustID = s.CustID
	LEFT JOIN tblsales sal	on sal.SalID=sd.SalID
	WHERE s.RcpID = var_saleid
	ORDER BY sd.LineNo
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_receipt_delete`;
DELIMITER |
CREATE PROCEDURE `crm_receipt_delete`(rcpId varchar(255))
    DETERMINISTIC
BEGIN
	UPDATE `tblreceipt` SET `PostStatus`='Deleted' WHERE (`RcpID`=rcpId);
	UPDATE tblreceiptdetails SET PostStatus = 'Deleted' WHERE (`RcpID`=rcpId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_receipt_invoice_add_online`;
DELIMITER |
CREATE PROCEDURE `crm_receipt_invoice_add_online`(var_rcpId varchar(255), var_Ref varchar(255), var_saleDate varchar(255), var_custid varchar(255), var_rcpType varchar(255), var_accId  varchar(255), rcpAmount double,  var_appliedAmt double,var_TotalDis double,var_totalCash double, var_remark varchar(255), var_clid varchar(255), var_puid varchar(255), var_prefix varchar(255),var_pmtmethod varchar(255),var_pmtRef varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_check_id VARCHAR(255) DEFAULT COALESCE((SELECT CONCAT(var_id,crm_generate_zero(int_length,int_lastid)) FROM tblnumberprefix_custom WHERE var_id = var_prefix AND var_type ='AR-PY'),"");
	IF var_check_id <> '' THEN
		UPDATE tblnumberprefix_custom SET `int_lastid`=(int_lastid+1) WHERE (`var_type`='AR-PY') AND (`var_id`=var_prefix);
		INSERT INTO `tblreceipt` (`RcpID`, `RcpDate`, `PeriodM`, `PeriodY`, `RcpReference`, `RcpType`, `CustID`, `CashAccNo`, `TotalDiscount`, `TotalRcpAmount`, `PostStatus`,`AppliedAmt`, `AppliedStatus`, `remark`, `TotalCash`, `ClassID`, `rcpmethod`, `rcpmethodref`, `uidcreate`, `datecreate`, `PrefixNumber`) 
		VALUES (var_check_id,var_saleDate,MONTH(var_saleDate), YEAR(var_saleDate),var_Ref,var_rcpType,var_custid ,var_accId,var_TotalDis,rcpAmount,'Open', var_appliedAmt,'Partially Paid',var_remark,var_totalCash,var_clid ,var_pmtmethod,var_pmtRef,var_puid,now(),var_prefix)
		;
	END IF;
	SELECT var_check_id as 'msg';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_receipt_invoice_update_online`;
DELIMITER |
CREATE PROCEDURE `crm_receipt_invoice_update_online`(var_rcpId varchar(255), var_Ref varchar(255), var_saleDate varchar(255), var_custid varchar(255), var_rcpType varchar(255), var_accId  varchar(255), rcpAmount double,  var_appliedAmt double,var_TotalDis double,var_totalCash double, var_remark varchar(255), var_clid varchar(255), var_puid varchar(255), var_prefix varchar(255),var_pmtmethod varchar(255),var_pmtRef varchar(255))
    DETERMINISTIC
BEGIN		
		UPDATE `tblreceipt` 
		SET  
			  `RcpDate`=var_saleDate, 
				`PeriodM`=MONTH(var_saleDate), 
				`PeriodY`=YEAR(var_saleDate), 
				`RcpReference`=var_Ref, 
				`RcpType`=var_rcpType, 
				`CustID`=var_custid, 
				`CashAccNo`=var_accId, 
				`TotalDiscount`=var_TotalDis, 
				`TotalRcpAmount`=rcpAmount, 
				`PostStatus`='Open',
				`AppliedAmt`=var_appliedAmt, 
				`AppliedStatus`='Partially Paid',
				`remark`=var_remark, 
				`TotalCash`=var_totalCash, 
				`ClassID`=var_clid, 
				`rcpmethod`=var_pmtmethod, 
				`rcpmethodref`=var_pmtRef, 
				`uidmodify`=var_puid, 
				`datemodify`=now(),
				`PrefixNumber`=var_prefix 
		WHERE (`RcpID`=var_rcpId);
	DELETE FROM tblreceiptdetails WHERE RcpID=var_rcpId;
	SELECT 'True' as 'msg';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_receipt_list_sale_unpaid`;
DELIMITER |
CREATE PROCEDURE `crm_receipt_list_sale_unpaid`(var_cust_id varchar(255))
    DETERMINISTIC
BEGIN
	SELECT SalID 'saleId',SalReference 'saleReference',DATE(SalDate) 'saleDate',NetTotalAmt 'saleNetTotalAmt',
			   COALESCE((SELECT SUM(COALESCE(tblreceiptdetails.Discount,0)+COALESCE(tblreceiptdetails.RcpAmount,0)+COALESCE(tblreceiptdetails.AppliedAmt,0)) FROM tblreceiptdetails WHERE tblreceiptdetails.SalID=tblsales.SalID),0) 'rcpToDate'
	FROM tblsales 
	WHERE CustID = var_cust_id AND PmtStatus <> 'Fully Paid' AND PostStatus = 'Posted'
	ORDER BY SalID
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_report_quote_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_report_quote_by_id`(var_sid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT s.SalID as 'SalID', DATE_FORMAT(s.SalDate, '%d-%b-%Y') as 'SalDate', s.SalReference as 'SalRef', s.CustID as 'CustID', c.CustName 'CustName', COALESCE(c.CustAddress, '') 'Delivery',
		 (SELECT sad.shipname FROM tblshipaddress sad WHERE sad.shipid = s.ShipTo) as 'Delivery1', c.CustTel1 'Tel', c.CustTel2 'Tel2' ,
			sd.ItemID 'ItemID', i.ItemName as 'ItemName', i.itemcode 'ItemCode',sd.UomID 'UomID', sd.SalQty 'SalQty', sd.UnitPrice 'UnitPrice', sd.TotalAmt 'Amount', s.NetTotalAmt 'NetTotalAmt', '' as 'Receiver'
	FROM tblsbquote s
	LEFT JOIN tblsbquotedetails sd ON s.SalID=sd.SalID
	LEFT JOIN tblcustomer c on c.CustID = s.CustID
	LEFT JOIN tblitem i ON i.ItemID = sd.ItemID
	WHERE s.SalID = var_sid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_report_sale_order_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_report_sale_order_by_id`(var_sid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT s.SalID as 'SalID', DATE_FORMAT(s.SalDate, '%d-%b-%Y') as 'SalDate', s.SalReference as 'SalRef', s.CustID as 'CustID', COALESCE(c.CustName,'') 'CustName', COALESCE(c.CustAddress, '') 'Delivery',
		 (SELECT sad.shipname FROM tblshipaddress sad WHERE sad.shipid = s.ShipTo) as 'Delivery1', c.CustTel1 'Tel', c.CustTel2 'Tel2' , c.TermFormat 'term',
			sd.ItemID 'ItemID', i.ItemName as 'ItemName', i.itemcode 'ItemCode',sd.UomID 'UomID', sd.SalQty 'SalQty', sd.UnitPrice 'UnitPrice', sd.TotalAmt 'Amount', s.NetTotalAmt 'NetTotalAmt', '' as 'Receiver'
	FROM tblsaleorder s
	LEFT JOIN tblsaleorderdetails sd ON s.SalID=sd.SalID
	LEFT JOIN tblcustomer c on c.CustID = s.CustID
	LEFT JOIN tblitem i ON i.ItemID = sd.ItemID
	WHERE s.SalID = var_sid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_report_sale_order_codition_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_report_sale_order_codition_by_id`(var_sid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 'The above cost are excluded VAT 10%.' as 'VATDes', ' 45-60 days from the deposit of meterial order 30% taken date' as 'DevliveryDes', 
	'30 Days from the issue date' as 'Validity', 'Interest rate of 2% per day will be chargeable to the overdue invoices.' as 'InterestRate', 
	'Cash/Cheque/TT' as 'PmtMethod', '20% deposite after delivery at Site, 30% deposit after work completed 50%, 50% payment completed after work' as 'Term'; 
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_request_budget`;
DELIMITER |
CREATE PROCEDURE `crm_request_budget`(in var_userId varchar(255))
    DETERMINISTIC
BEGIN
DECLARE var_rt varchar(255);
DECLARE var_emp varchar(255);
DECLARE role_id varchar(255);
SET var_emp = (SELECT ame_user.var_empid FROM ame_user WHERE ame_user.var_id=var_userId );
SET var_rt = 1;
IF var_rt = '1' THEN
		SELECT f.FrmID as 'frmId', f.EmpID as 'empId', (SELECT e.var_name FROM ame_mt_emp e WHERE e.var_id= f.EmpID) 'empName', f.Department 'department',Position as 'position', f.edittable 'editable',
         DATE_FORMAT(f.FrmDate, '%d-%b-%Y') 'frmDate',DATE_FORMAT(f.ApprovalDate, '%d-%b-%Y') 'approvalDate', f.ApprovalStatus 'status', f.Objective 'objective', f.Reason 'reason', f.Phone 'phone', f.CBy 'createBy'
				,COALESCE(f.CustID,'') 'custId',COALESCE(c.var_name,'') 'custName'
		FROM crm_frm_budget f 
		LEFT JOIN ame_mt_cus c ON c.var_id=f.CustID
		ORDER BY f.FrmID DESC;

		SELECT COALESCE(emp.var_id, '') as 'empId', COALESCE(emp.var_name, '') 'empName', COALESCE(emp.var_posid, '') as 'position', IF(var_emp = emp.var_id, 'true', 'false') 'SL' , COALESCE(emp.var_tel1,'') 'phone1', COALESCE(emp.var_tel2,'') 'phone2'
		FROM ame_mt_emp emp WHERE emp.tin_inactive = 0;
		SELECT cus.var_id 'custId', COALESCE(cus.var_name, '') 'custName' , COALESCE(cus.var_pricecode,'') 'priceCode'  FROM ame_mt_cus cus WHERE cus.tin_inactive=0 ORDER BY cus.var_id;
ELSE	
		SELECT IsOnlyRole ,uroleid INTO var_rt,role_id FROM tbluser WHERE UID = var_userId;
		IF var_rt = '1' THEN
			SELECT f.FrmID as 'frmId', f.EmpID as 'empId', (SELECT e.EmpName FROM tblemployee e WHERE e.EmpID= f.EmpID) 'empName', f.Department 'department',Position as 'position', f.EditTable 'editable',
			DATE_FORMAT(f.FrmDate, '%d-%b-%Y') 'frmDate',DATE_FORMAT(f.ApprovalDate, '%d-%b-%Y') 'approvalDate', f.ApprovalStatus 'status', f.Objective 'objective', f.Reason 'reason', f.Phone 'phone', f.CBy 'createBy'
			,COALESCE(f.CustID,'') 'custId',COALESCE(c.CustName,'') 'custName'
			FROM crm_frm_budget f 
			LEFT JOIN tblcustomer c ON c.CustID=f.CustID
			WHERE f.empid IN(SELECT EmpID FROM tbluseremployee ue INNER JOIN (SELECT UID FROM tbluser WHERE uroleid = uroleid) as users ON users.UID=ue.uid)
			ORDER BY f.FrmID DESC;

			SELECT COALESCE(EmpID, '') as 'empId', COALESCE(EmpName, '') 'empName', COALESCE(EmpPosition, '') as 'position', IF(var_emp = EmpID, 'true', 'false') 'SL' 
			FROM tblemployee 
			WHERE Inactive = 0
			AND empid IN(SELECT EmpID FROM tbluseremployee ue INNER JOIN (SELECT UID FROM tbluser WHERE uroleid = uroleid) as users ON users.UID=ue.uid)
			;
			SELECT CustID 'custId', COALESCE(CustName, '') 'custName' , COALESCE(PriceCode,'') 'priceCode', COALESCE(TermNetDueIn,0) 'termNetDueIn', COALESCE(AID,'') shipId, COALESCE(TermCreditLimit,'') 'termCreditLimit'  FROM tblcustomer WHERE Inactive=0 ORDER BY CustID;
		ELSE
			SELECT f.FrmID as 'frmId', f.EmpID as 'empId', (SELECT e.EmpName FROM tblemployee e WHERE e.EmpID= f.EmpID) 'empName', f.Department 'department',Position as 'position', f.EditTable 'editable',
			DATE_FORMAT(f.FrmDate, '%d-%b-%Y') 'frmDate',DATE_FORMAT(f.ApprovalDate, '%d-%b-%Y') 'approvalDate', f.ApprovalStatus 'status', f.Objective 'objective', f.Reason 'reason', f.Phone 'phone', f.CBy 'createBy'
			,COALESCE(f.CustID,'') 'custId',COALESCE(c.CustName,'') 'custName'
			FROM crm_frm_budget f 
			LEFT JOIN tblcustomer c ON c.CustID=f.CustID
			WHERE f.empid = var_emp
			ORDER BY f.FrmID DESC;		

			SELECT COALESCE(EmpID, '') as 'empId', COALESCE(EmpName, '') 'empName', COALESCE(EmpPosition, '') as 'position', IF(var_emp = EmpID, 'true', 'false') 'SL' , COALESCE(EmpTel1,'') 'phone1', COALESCE(EmpTel2,'') 'phone2'
			FROM tblemployee 
			WHERE Inactive = 0
			AND empid = var_emp
			;
			SELECT CustID 'custId', COALESCE(CustName, '') 'custName' , COALESCE(PriceCode,'') 'priceCode', COALESCE(TermNetDueIn,0) 'termNetDueIn', COALESCE(AID,'') shipId, COALESCE(TermCreditLimit,'') 'termCreditLimit'  FROM tblcustomer WHERE Inactive=0 and CustID IN (SELECT CustID from tblemployeecustomer WHERE EmpID = var_emp) ORDER BY CustID;
		END IF;
		
	END IF;
	SELECT var_emp;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_request_budget_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_request_budget_by_id`(var_objid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT f.FrmID as 'frmId', f.EmpID as 'empId', (SELECT e.empname FROM tblemployee e WHERE e.EmpID= f.EmpID) 'empName', f.Department 'department',Position as 'position',COALESCE(f.CustID,'') 'custId',COALESCE(c.CustName,'') 'custName',
				DATE_FORMAT(f.FrmDate, '%d-%b-%Y') 'frmDate',DATE_FORMAT(f.ApprovalDate, '%d-%b-%Y') 'approvalDate', f.ApprovalStatus 'status', f.Objective 'objective', f.Reason 'reason', f.Phone 'phone', f.CBy 'createBy'
	FROM crm_frm_budget f 
	LEFT JOIN tblcustomer c ON c.CustID=f.CustID
	WHERE f.FrmID = var_objid;
	SELECT ComName 'comEN', ComNameKh 'comKH',Unit 'unit' FROM tblcompanyreport;
	SELECT EmpID 'empId', EmpName 'empName', EmpPosition 'position' , EmpTel1 'tel'
	FROM tblemployee WHERE EmpID in (select Auth_EmpID from hrm_authorisation_approved WHERE Auth_ProcessID = var_objid AND Auth_Status = 'approved');
	SELECT EmpID 'empId', EmpName 'empName', EmpPosition 'position' , EmpTel1 'tel'
	FROM tblemployee WHERE EmpID in (select Auth_EmpID from hrm_authorisation_approved WHERE Auth_ProcessID = var_objid AND Auth_Status = 'rejected');
	select ImagePath FROM tblconfiguration LIMIT 1 ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_request_general`;
DELIMITER |
CREATE PROCEDURE `crm_request_general`(in var_userId varchar(255))
    DETERMINISTIC
BEGIN
DECLARE var_rt varchar(255);
DECLARE var_emp varchar(255);
DECLARE role_id varchar(255);
SET var_emp = (SELECT ame_user.var_empid FROM ame_user WHERE ame_user.var_id=var_userId );
SET var_rt = 1;
IF var_rt = '1' THEN
	SELECT f.FrmID as 'frmId', f.EmpID as 'empId', (SELECT e.var_name FROM ame_mt_emp e WHERE e.var_id= f.EmpID) 'empName', f.Department 'department',Position as 'position',
				 DATE_FORMAT(f.FrmDate, '%d-%b-%Y') 'frmDate',DATE_FORMAT(f.ApprovalDate, '%d-%b-%Y') 'approvalDate', f.ApprovalStatus 'status', f.Objective 'objective', f.Reason 'reason', f.Phone 'phone', f.CBy 'createBy',
         COALESCE(f.ReqType,'') 'reqType', COALESCE(f.ReqDescription,'') 'reqDescription', f.EditTable 'editable', COALESCE(ta.tmpname, '') 'reqTypeName',COALESCE(f.CustID,'') 'custId',COALESCE(c.var_name,'') 'custName'
  FROM crm_frm_general f
	LEFT JOIN ame_mt_cus c ON c.var_id=f.CustID
	LEFT JOIN crm_template_authorization ta on ta.tmpid = f.reqtype
	ORDER BY f.FrmID DESC;

	SELECT COALESCE(emp.var_id, '') as 'empId', COALESCE(emp.var_name, '') 'empName', COALESCE(emp.var_posid, '') as 'position', IF(var_emp = emp.var_id, 'true', 'false') 'SL' , COALESCE(emp.var_tel1,'') 'phone1', COALESCE(emp.var_tel2,'') 'phone2'
		FROM ame_mt_emp emp WHERE emp.tin_inactive = 0;
		SELECT cus.var_id 'custId', COALESCE(cus.var_name, '') 'custName' , COALESCE(cus.var_pricecode,'') 'priceCode'  FROM ame_mt_cus cus WHERE cus.tin_inactive=0 ORDER BY cus.var_id;
ELSE	
	SELECT IsOnlyRole ,uroleid INTO var_rt,role_id FROM tbluser WHERE UID = var_userId;
	IF var_rt = '1' THEN
		SELECT f.FrmID as 'frmId', f.EmpID as 'empId', (SELECT e.empname FROM tblemployee e WHERE e.EmpID= f.EmpID) 'empName', f.Department 'department',Position as 'position',
				 DATE_FORMAT(f.FrmDate, '%d-%b-%Y') 'frmDate',DATE_FORMAT(f.ApprovalDate, '%d-%b-%Y') 'approvalDate', f.ApprovalStatus 'status', f.Objective 'objective', f.Reason 'reason', f.Phone 'phone', f.CBy 'createBy',
         COALESCE(f.ReqType,'') 'reqType', COALESCE(f.ReqDescription,'') 'reqDescription', f.EditTable 'editable', COALESCE(ta.tmpname, '') 'reqTypeName',COALESCE(f.CustID,'') 'custId',COALESCE(c.CustName,'') 'custName'
		FROM crm_frm_general f 
		LEFT JOIN tblcustomer c ON c.CustID=f.CustID
		LEFT JOIN crm_template_authorization ta on ta.tmpid = f.reqtype
		WHERE f.empid IN(SELECT EmpID FROM tbluseremployee ue INNER JOIN (SELECT UID FROM tbluser WHERE uroleid = uroleid) as users ON users.UID=ue.uid)
		ORDER BY f.FrmID DESC;

		SELECT COALESCE(EmpID, '') as 'empId', COALESCE(EmpName, '') 'empName', COALESCE(EmpPosition, '') as 'position', IF(var_emp = EmpID, 'true', 'false') 'SL' 
		FROM tblemployee 
		WHERE Inactive = 0
		AND empid IN(SELECT EmpID FROM tbluseremployee ue INNER JOIN (SELECT UID FROM tbluser WHERE uroleid = uroleid) as users ON users.UID=ue.uid)
		;
		SELECT CustID 'custId', COALESCE(CustName, '') 'custName' , COALESCE(PriceCode,'') 'priceCode', COALESCE(TermNetDueIn,0) 'termNetDueIn', COALESCE(AID,'') shipId, COALESCE(TermCreditLimit,'') 'termCreditLimit'  FROM tblcustomer WHERE Inactive=0 ORDER BY CustID;
	ELSE
		SELECT f.FrmID as 'frmId', f.EmpID as 'empId', (SELECT e.empname FROM tblemployee e WHERE e.EmpID= f.EmpID) 'empName', f.Department 'department',Position as 'position',
				 DATE_FORMAT(f.FrmDate, '%d-%b-%Y') 'frmDate',DATE_FORMAT(f.ApprovalDate, '%d-%b-%Y') 'approvalDate', f.ApprovalStatus 'status', f.Objective 'objective', f.Reason 'reason', f.Phone 'phone', f.CBy 'createBy',
         COALESCE(f.ReqType,'') 'reqType', COALESCE(f.ReqDescription,'') 'reqDescription', f.EditTable 'editable', COALESCE(ta.tmpname, '') 'reqTypeName',COALESCE(f.CustID,'') 'custId',COALESCE(c.CustName,'') 'custName'
		FROM crm_frm_general f 
		LEFT JOIN tblcustomer c ON c.CustID=f.CustID
		LEFT JOIN crm_template_authorization ta on ta.tmpid = f.reqtype
		WHERE f.empid = var_emp
		ORDER BY f.FrmID DESC;

		SELECT COALESCE(EmpID, '') as 'empId', COALESCE(EmpName, '') 'empName', COALESCE(EmpPosition, '') as 'position', IF(var_emp = EmpID, 'true', 'false') 'SL' 
		FROM tblemployee 
		WHERE Inactive = 0
		AND empid = var_emp
		;
		SELECT CustID 'custId', COALESCE(CustName, '') 'custName' , COALESCE(PriceCode,'') 'priceCode', COALESCE(TermNetDueIn,0) 'termNetDueIn', COALESCE(AID,'') shipId, COALESCE(TermCreditLimit,'') 'termCreditLimit'  FROM tblcustomer WHERE Inactive=0 and CustID IN (SELECT CustID from tblemployeecustomer WHERE EmpID = var_emp) ORDER BY CustID;
	END IF;
END IF;
SELECT var_emp;
SELECT TmpID 'tmpId', TmpName 'tmpName', TmpDescription 'tmpDescription' FROM crm_template_authorization;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_request_general_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_request_general_by_id`(var_objid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT f.FrmID as 'frmId', f.EmpID as 'empId', (SELECT e.empname FROM tblemployee e WHERE e.EmpID= f.EmpID) 'empName', f.Department 'department',Position as 'position',COALESCE(f.CustID,'') 'custId',COALESCE(c.CustName,'') 'custName',
				DATE_FORMAT(f.FrmDate, '%d-%b-%Y') 'frmDate',DATE_FORMAT(f.ApprovalDate, '%d-%b-%Y') 'approvalDate', f.ApprovalStatus 'status', f.Objective 'objective', f.Reason 'reason', f.Phone 'phone', f.CBy 'createBy',
				COALESCE(f.ReqType,'') 'reqType',COALESCE(ta.TmpName,'') 'reqTypeDes', COALESCE(f.ReqDescription,'') 'reqDescription'
	FROM crm_frm_general f 
	LEFT JOIN tblcustomer c ON c.CustID=f.CustID
	LEFT JOIN crm_template_authorization ta on ta.TmpID=f.ReqType
	WHERE f.FrmID = var_objid;
	SELECT ComName 'comEN', ComNameKh 'comKH',Unit 'unit' FROM tblcompanyreport;
	SELECT EmpID 'empId', EmpName 'empName', EmpPosition 'position' , EmpTel1 'tel'
	FROM tblemployee WHERE EmpID in (select Auth_EmpID from hrm_authorisation_approved WHERE Auth_ProcessID = var_objid AND Auth_Status = 'approved');
	SELECT EmpID 'empId', EmpName 'empName', EmpPosition 'position' , EmpTel1 'tel'
	FROM tblemployee WHERE EmpID in (select Auth_EmpID from hrm_authorisation_approved WHERE Auth_ProcessID = var_objid AND Auth_Status = 'rejected');
	select ImagePath FROM tblconfiguration LIMIT 1 ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_project_list_detail`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_project_list_detail`(var_empid varchar(255), var_type varchar(255), var_status varchar(255),var_proid varchar(255))
    DETERMINISTIC
BEGIN
SELECT pl.pl_id 'plId', pl.pl_name 'plName', COALESCE(plt.plt_name,'') 'plType' , COALESCE(pls.pls_name,'') 'plStatus', COALESCE(e.empname,'') 'salePerson',pl.pl_remark 'remark', COALESCE(DATE_FORMAT(pl.pl_startdate,'%d-%b-%Y'),'') 'startDate', 
			 COALESCE(DATE_FORMAT(pl.pl_enddate,'%d-%b-%Y'),'') 'endDate',COALESCE(DATE_FORMAT(pl.pl_next_follow_date,'%d-%b-%Y'),'') 'nextFollow', COALESCE(DATE_FORMAT(pl.pl_last_visit,'%d-%b-%Y'),'') 'lastVisit',
			 pl.pl_buildcompleted 'build', pl.pl_cost_in_usd 'costUSD', pl.pl_owner 'owner', 
			 COALESCE(pl.pl_location,'') 'plAddress', COALESCE(pl.co_street,'') 'plStreet'  ,COALESCE(pl.co_no,'') 'plNo', 
       IF(COALESCE(pl.co_city,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.co_city limit 1),'') 'plCity',
			 IF(COALESCE(pl.co_district,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.co_district limit 1),'') 'plDistrict',
       IF(COALESCE(pl.co_commune,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.co_commune limit 1),'') 'plCommune',
       IF(COALESCE(pl.co_village,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.co_village limit 1),'') 'plVillage',
			 COALESCE(pl.company_address,'') 'officeAddress', COALESCE(pl.company_street,'') 'officeStreet'  ,COALESCE(pl.company_no,'') 'officeNo',
       IF(COALESCE(pl.company_city,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.company_city limit 1),'') 'officeCity',
			 IF(COALESCE(pl.company_district,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.company_district limit 1),'') 'officeDistrict',
       IF(COALESCE(pl.company_commune,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.company_commune limit 1),'') 'officeCommune',
       IF(COALESCE(pl.company_village,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.company_village limit 1),'') 'officeVillage',
			 COALESCE(pl.ComName,'') 'company' , COALESCE(pl.SizeBus,'') 'sizeBus' , COALESCE(pl.TypeBus,'') 'TypeBus' , COALESCE(pl.Url,'') 'url' , 
			 COALESCE(pl.Architect,'') 'architect' ,COALESCE(pl.ArchPerson,'') 'architectPerson' ,COALESCE(pl.ArchNumber,'') 'architectNumber' ,
			 COALESCE(pl.Consultant,'') 'consultant' ,COALESCE(pl.ConsulPerson,'') 'consultantPerson' ,COALESCE(pl.ConsulNumber,'') 'consultantNumber' ,
       COALESCE(pl.MainConstuctor,'') 'mainConstuctor' ,COALESCE(pl.MainPerson,'') 'mainPerson' ,COALESCE(pl.MainNumber,'') 'mainNumber' ,
			 CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"mainCon":"',COALESCE(pld_mainconstructor,''),'", "con":"',pld_constructor,'","contact":"',pld_contact,'", "person":"',pld_personincharge, '", "tel":"', pld_mobile, '"}')) FROM crm_projectlist_details WHERE crm_projectlist_details.pl_id = pl.pl_id),']') 'contacts',
			 CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"itemId":"',pd.itemid,'","itemName":"',COALESCE(i.itemname,''),'","itemCode":"',COALESCE(i.itemcode,''),'","uomId":"',pd.uomid,
																						 '","itemGroupId":"',COALESCE(i.itemgroupid,''),'", "itemGroupName":"',COALESCE(ig.itemgroupname,''),
                                             '","boq":',pd.plp_boq,',"qty":',pd.plp_qty,',"up":',pd.plp_unitprice,',"pricePer":', pd.plp_priceper, ',"total":',pd.plp_totalbalance,
																						 ',"qtyToUse":',pd.plp_qtytoused,', "perToBuy":',pd.plp_percentagetobuy,',"qtyToBuy":',pd.plp_qtytobuy,
																						 ',"expectedDate":"', COALESCE(DATE_FORMAT(pd.plp_dateexptouse,'%d-%b-%Y'),''),'","proStatus":"',COALESCE(pds.plps_name,''),'","grandTotal":',pd.plp_totalbalfinished,'}'

													))
													FROM crm_projectlist_product pd
													LEFT JOIN crm_projectlist_product_status pds ON pd.plp_status = pds.plps_id
													LEFT JOIN tblitem i ON i.itemid = pd.itemid
                          LEFT JOIN tblitemgroup ig ON ig.itemgroupid = i.itemgroupid
													WHERE pd.pl_id = pl.pl_id),']') 'proDetail'
	FROM crm_projectlist pl
	LEFT JOIN tblemployee e ON e.empid = pl.empid
	LEFT JOIN crm_projectlist_status pls ON pls.pls_id = pl.pl_status
	LEFT JOIN crm_projectlist_type plt ON plt.plt_id = pl.pl_type
	WHERE IF(var_empid = 'all', TRUE,pl.empid = var_empid)
	AND IF(var_type = 'all', TRUE,pl.pl_type = var_type)
	AND IF(var_status = 'all', TRUE,pl.pl_status = var_status)
	AND IF(var_proid = 'all', TRUE,pl.pl_id = var_proid)
	ORDER BY pl_id
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_project_list_detail_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_project_list_detail_by_id`(var_pl_id varchar(255))
    DETERMINISTIC
BEGIN
SELECT pl.pl_id 'plId', pl.pl_name 'plName', COALESCE(plt.plt_name,'') 'plType' , COALESCE(pls.pls_name,'') 'plStatus', COALESCE(e.empname,'') 'salePerson',pl.pl_remark 'remark', COALESCE(DATE_FORMAT(pl.pl_startdate,'%d-%b-%Y'),'') 'startDate', 
			 COALESCE(DATE_FORMAT(pl.pl_enddate,'%d-%b-%Y'),'') 'endDate',COALESCE(DATE_FORMAT(pl.pl_next_follow_date,'%d-%b-%Y'),'') 'nextFollow', COALESCE(DATE_FORMAT(pl.pl_last_visit,'%d-%b-%Y'),'') 'lastVisit',
			 pl.pl_buildcompleted 'build', pl.pl_cost_in_usd 'costUSD', pl.pl_owner 'owner', 
			 COALESCE(pl.pl_location,'') 'plAddress', COALESCE(pl.co_street,'') 'plStreet'  ,COALESCE(pl.co_no,'') 'plNo',
       IF(COALESCE(pl.co_city,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.co_city limit 1),'') 'plCity',
			 IF(COALESCE(pl.co_district,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.co_district limit 1),'') 'plDistrict',
       IF(COALESCE(pl.co_commune,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.co_commune limit 1),'') 'plCommune',
       IF(COALESCE(pl.co_village,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.co_village limit 1),'') 'plVillage',
			 COALESCE(pl.company_address,'') 'officeAddress', COALESCE(pl.company_street,'') 'officeStreet'  ,COALESCE(pl.company_no,'') 'officeNo',
       IF(COALESCE(pl.company_city,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.company_city limit 1),'') 'officeCity',
			 IF(COALESCE(pl.company_district,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.company_district limit 1),'') 'officeDistrict',
       IF(COALESCE(pl.company_commune,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.company_commune limit 1),'') 'officeCommune',
       IF(COALESCE(pl.company_village,'') <> '' ,(SELECT CONCAT(var_nameen,' / ',var_namekh) FROM crm_gazetteer WHERE var_id = pl.company_village limit 1),'') 'officeVillage',
			 COALESCE(pl.Architect,'') 'architect' ,COALESCE(pl.ArchPerson,'') 'architectPerson' ,COALESCE(pl.ArchNumber,'') 'architectNumber' ,
			 COALESCE(pl.Consultant,'') 'consultant' ,COALESCE(pl.ConsulPerson,'') 'consultantPerson' ,COALESCE(pl.ConsulNumber,'') 'consultantNumber' ,
       COALESCE(pl.MainConstuctor,'') 'mainConstuctor' ,COALESCE(pl.MainPerson,'') 'mainPerson' ,COALESCE(pl.MainNumber,'') 'mainNumber' ,
			 CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"mainCon":"',COALESCE(pld_mainconstructor,''),'", "con":"',pld_constructor,'","contact":"',pld_contact,'", "person":"',pld_personincharge, '", "tel":"', pld_mobile, '"}')) FROM crm_projectlist_details WHERE crm_projectlist_details.pl_id = pl.pl_id),']') 'contacts',
			 CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"itemId":"',pd.itemid,'","itemName":"',COALESCE(i.itemname,''),'","itemCode":"',COALESCE(i.itemcode,''),'","uomId":"',pd.uomid,
																						 '","itemGroupId":"',COALESCE(i.itemgroupid,''),'", "itemGroupName":"',COALESCE(ig.itemgroupname,''),
                                             '","boq":',pd.plp_boq,',"qty":',pd.plp_qty,',"up":',pd.plp_unitprice,',"pricePer":', pd.plp_priceper, ',"total":',pd.plp_totalbalance,
																						 ',"qtyToUse":',pd.plp_qtytoused,', "perToBuy":',pd.plp_percentagetobuy,',"qtyToBuy":',pd.plp_qtytobuy,
																						 ',"expectedDate":"', COALESCE(DATE_FORMAT(pd.plp_dateexptouse,'%d-%b-%Y'),''),'","proStatus":"',COALESCE(pds.plps_name,''),'","grandTotal":',pd.plp_totalbalfinished,'}'

													))
													FROM crm_projectlist_product pd
													LEFT JOIN crm_projectlist_product_status pds ON pd.plp_status = pds.plps_id
													LEFT JOIN tblitem i ON i.itemid = pd.itemid
                          LEFT JOIN tblitemgroup ig ON ig.itemgroupid = i.itemgroupid
													WHERE pd.pl_id = pl.pl_id),']') 'proDetail'
	FROM crm_projectlist pl
	LEFT JOIN tblemployee e ON e.empid = pl.empid
	LEFT JOIN crm_projectlist_status pls ON pls.pls_id = pl.pl_status
	LEFT JOIN crm_projectlist_type plt ON plt.plt_id = pl.pl_type
	WHERE pl.pl_id = var_pl_id
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_by_customer`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_by_customer`(var_sdate varchar(255), var_tdate varchar(255), var_empid varchar(255), var_cid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT c.custid 'custId', c.custname 'custName',
		ROUND(SUM(s.totalamt),2) 'totalAmt',
		ROUND(SUM(s.totalvtax),2) 'vat',
		ROUND(SUM(s.nettotalamt),2) 'netTotalAmt',
		ROUND(COALESCE((SELECT SUM(COALESCE(rd.rcpamount,0)+COALESCE(rd.discount,0)+COALESCE(rd.appliedamt,0)) FROM tblreceipt r INNER JOIN tblreceiptdetails rd ON rd.rcpid = r.rcpid WHERE DATE(rcpdate) BETWEEN var_sdate AND var_tdate AND r.custid = c.custid),0),2) 'balance'
	FROM tblsales s
	LEFT JOIN tblcustomer c on c.custid=s.custid
	WHERE DATE(s.saldate) BETWEEN var_sdate AND var_tdate AND s.PostStatus IN('Open','Posted')
	AND IF(var_empid = 'all', TRUE,s.empid = var_empid)
	AND IF(var_cid = 'all', TRUE,s.custid = var_cid)
	GROUP BY c.custid
	ORDER BY c.custid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_by_customer_by_emp`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_by_customer_by_emp`(var_sdate varchar(255), var_tdate varchar(255), var_empid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT c.custid 'custId', c.custname 'custName',
		ROUND(SUM(s.totalamt),2) 'totalAmt',
		ROUND(SUM(s.totalvtax),2) 'vat',
		ROUND(SUM(s.nettotalamt),2) 'netTotalAmt',
		ROUND(0,2) 'balance'
	FROM tblsales s
	LEFT JOIN tblcustomer c on c.custid=s.custid
	WHERE DATE(s.saldate) BETWEEN var_sdate AND var_tdate AND s.empid = var_empid AND s.PostStatus IN('Open','Posted')
	GROUP BY c.custid
	ORDER BY c.custid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_by_customer_by_employee_all`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_by_customer_by_employee_all`(var_sdate varchar(255), var_tdate varchar(255), var_pc varchar(255), var_fempid varchar(255), var_tempid varchar(255),var_fcustid varchar(255),var_tcustid varchar(255), var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_empId varchar(255);
	DECLARE var_img_url varchar(255);
	DECLARE var_rt varchar(255);
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_user_id LIMIT 1)), 0);
	IF var_rt <> '1' THEN
		SET var_empId = COALESCE((SELECT EmpID FROM tbluseremployee WHERE UID = var_user_id),'');
		SET var_fempid = var_empId;
		SET var_tempid = var_empId;
	END IF;

	SELECT c.custid 'custId', c.custname 'custName', e.empid 'empId', e.empname 'empName',
		     ROUND(SUM(s.nettotalamt),2) 'netTotalAmt'
	FROM tblsales s
	LEFT JOIN tblcustomer c on c.custid=s.custid
	LEFT JOIN tblemployee e ON e.empid=s.empid
	WHERE DATE(s.saldate) BETWEEN var_sdate AND var_tdate 
	AND IF(var_pc = 'all', s.poststatus IN('Open','Posted'), s.poststatus = var_pc)
	AND IF(var_fempid = 'all', TRUE, s.empid >= var_fempid) 
	AND IF(var_tempid = 'all', TRUE, s.empid <= var_tempid) 
	AND IF(var_fcustid = 'all', TRUE, c.custid >= var_fcustid)
	AND IF(var_tcustid = 'all', TRUE, c.custid <= var_tcustid)
	GROUP BY c.custid,s.empid
	ORDER BY c.custname;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_by_employee_by_invoice`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_by_employee_by_invoice`(IN var_fd varchar(255), IN var_td varchar(255),IN var_pc varchar(255), IN var_fE varchar(255), IN var_tE varchar(255), IN var_fclid varchar(255), IN var_tclid varchar(255), IN var_fcid varchar(255), IN var_tcid varchar(255), var_uid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT
		E.EmpID 'empId',
		E.EmpName 'empName',
		S.CustID 'custId',
		COALESCE((SELECT CustName FROM tblcustomer C WHERE C.CustID = S.CustID),'') 'custName',
		S.SalID 'saleId',
		S.SalReference 'saleReference',
		DATE_FORMAT(S.SalDate, "%d-%b-%Y") AS 'SalDate',
    ROUND(SUM(COALESCE(SD.totalamt,0)),2) 'totalAmt',
		ROUND(SUM(COALESCE(SD.NetTotalAmt,0) - COALESCE(SD.VTaxDol,0) - COALESCE(SD.STaxDol,0) + COALESCE(SD.DisDol,0)),2) AS 'NetTotalAmt',
		ROUND(SUM(COALESCE(SD.DisDol,0) + COALESCE(SD.DisInv,0)),2) AS 'DisDol',
		ROUND(SUM(COALESCE(SD.VTaxDol,0) + COALESCE(SD.STaxDol,0)),2) AS 'TTax',
		ROUND(COALESCE(S.PmtToDate,0),2) AS PmtTotal,
		ROUND((SUM(COALESCE(SD.NetTotalAmt,0) - COALESCE(SD.VTaxDol,0) - COALESCE(SD.STaxDol,0) + COALESCE(SD.DisDol,0)) - COALESCE(S.PmtToDate,0)),2)	as 'NetTotalAmtDue',
		S.PostStatus 'postStatus',
		COALESCE(S.ClassID,'') 'classId',
		COALESCE((SELECT C.Des FROM tblclass C WHERE C.ClassID = S.ClassID),'') AS 'ClassName'
	FROM (tblsales S LEFT JOIN tblsalesdetails SD ON S.SalID = SD.SalID)
	LEFT JOIN tblemployee E ON S.EmpID = E.EmpID
	WHERE DATE(S.SalDate) BETWEEN var_fd AND var_td AND
	CASE WHEN var_pc  = 'all' THEN S.PostStatus IN('Open','Posted') ELSE S.PostStatus = var_pc END AND
	CASE WHEN var_fE = 'all' THEN TRUE ELSE S.EmpID >= var_fE END AND CASE WHEN var_tE  = 'all' THEN TRUE ELSE S.EmpID <= var_tE  END AND
	CASE WHEN var_fcid = 'all' THEN TRUE ELSE S.CustID >= var_fcid END AND CASE WHEN var_tcid = 'all' THEN TRUE ELSE S.CustID <= var_tcid END AND
	CASE WHEN var_fclid = 'all' THEN TRUE ELSE SD.ClassID >= var_fclid END AND CASE WHEN var_tclid = 'all' THEN TRUE ELSE SD.ClassID <= var_tclid END
	AND IF(ISNULL((SELECT T.UID FROM tbluserprofile T WHERE T.UID = var_uid AND T.APPID = 'LOAD EMPLOYEE')), TRUE, S.CustID IN(SELECT var_cusid FROM tblusercustomer WHERE var_uid = var_uid))
	GROUP BY S.SalID 
  ORDER BY E.EmpID,S.SalID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_by_employee_by_item`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_by_employee_by_item`(IN var_fd varchar(255), IN var_td varchar(255),IN var_pc varchar(255), IN var_fE varchar(255), IN var_tE varchar(255), IN var_fclid varchar(255), IN var_tclid varchar(255), IN var_fcid varchar(255), IN var_tcid varchar(255), var_uid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT
		S.EmpID 'EmpID',
		COALESCE((SELECT E.EmpName FROM tblemployee E WHERE E.EmpID = S.EmpID),'') AS 'EmpName',
		CASE WHEN COALESCE(SD.ItemID,'') = '' THEN SD.AccID ELSE SD.ItemID END AS 'ItemID',
		CASE WHEN COALESCE(SD.ItemID,'') = '' THEN COALESCE((SELECT A.AccName FROM tblaccount A WHERE A.AccID = SD.AccID),'') ELSE COALESCE((SELECT I.ItemName FROM tblitem I WHERE I.ItemID = SD.ItemID),'') END AS 'ItemName',
		SD.UomID 'UomID',
		COALESCE((SELECT IU.QRCode FROM tblitemuom IU WHERE IU.ItemID = SD.ItemID AND IU.UomID = SD.UomID),'') AS 'ItemCode',
		S.PostStatus 'PostStatus',
		SD.ClassID 'ClassID',
		(SELECT C.Des FROM tblclass C WHERE C.ClassID = SD.ClassID) AS 'ClassName',
		SUM(COALESCE(SD.SalQty,0)) AS Qty,
		COALESCE(SD.UnitPrice,0) AS UP,
		SUM(COALESCE(SD.totalamt,0)) 'AMT',
		SUM(COALESCE(SD.NetTotalAmt,0) - COALESCE(SD.VTaxDol,0) - COALESCE(SD.STaxDol,0) + COALESCE(SD.DisDol,0)) AS TAmt, SUM(COALESCE(SD.DisInv,0) + COALESCE(SD.DisDol,0)) AS 'DisDol',
		SUM(COALESCE(SD.VTaxDol,0) + COALESCE(SD.STaxDol,0)) AS TTax,
		SUM(COALESCE(SD.NetTotalAmt,0)) 'NetAMT'
	FROM tblsales S LEFT JOIN tblsalesdetails SD ON S.SalID = SD.SalID
	WHERE DATE(S.SalDate) BETWEEN var_fd AND var_td AND
	CASE WHEN var_pc = 'all' THEN S.PostStatus IN('Open','Posted') ELSE S.PostStatus = var_pc END AND
	CASE WHEN var_fE = 'all' THEN TRUE ELSE S.EmpID >= var_fE END AND CASE WHEN var_tE = 'all' THEN TRUE ELSE S.EmpID <= var_tE END AND
	CASE WHEN var_fcid = 'all' THEN TRUE ELSE SD.ItemID >= var_fcid END AND CASE WHEN var_tcid = 'all' THEN TRUE ELSE SD.ItemID <= var_tcid END AND
	CASE WHEN var_fclid = 'all' THEN TRUE ELSE SD.ClassID >= var_fclid END AND CASE WHEN var_tclid = 'all' THEN TRUE ELSE SD.ClassID <= var_tclid END
	AND IF(ISNULL((SELECT T.UID FROM tbluserprofile T WHERE T.UID = var_uid AND T.APPID = 'LOAD EMPLOYEE')), TRUE, S.CustID IN(SELECT var_cusid FROM tblusercustomer WHERE var_uid = var_uid))
	GROUP BY S.EmpID,SD.LocationID,SD.ItemID,SD.AccID,SD.UomID,SD.UnitPrice,SD.ClassID,S.PostStatus;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_by_employee_by_weekly`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_by_employee_by_weekly`(var_month integer, var_year integer, var_empid varchar(255), var_uom varchar(255),var_ig varchar(255))
    DETERMINISTIC
BEGIN
	SELECT sd.itemid 'itemId',i.itemcode 'itemCode',COALESCE(i.itemname,'') 'itemName',DAY(s.saldate) 'Day', SUM(IF(sd.uomid = i.uomid ,sd.salqty,(sd.salqty*(COALESCE((SELECT Conversion FROM tblitemuom WHERE tblitemuom.ItemID = sd.itemid AND tblitemuom.UomID = sd.uomid),0))))) as 'salQty', sd.uomid 'uomId', SUM(sd.nettotalamt) 'amount'
	FROM tblsales s
	LEFT JOIN tblsalesdetails sd on s.SalID = sd.SalID 
	LEFT JOIN tblitem i on i.itemid=sd.itemid
  LEFT JOIN tblitemuom iu on iu.itemid = sd.itemid 
	WHERE s.empid = var_empid AND MONTH(s.saldate) = var_month AND Year(s.saldate) = var_year AND iu.uomid = var_uom AND s.PostStatus IN('Open','Posted')
	AND IF(var_ig = '', TRUE, i.itemgroupid=var_ig)
	GROUP BY DAY(s.saldate),sd.itemid
	ORDER BY sd.itemid,DATE(s.saldate);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_by_employee_by_weekly_copy`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_by_employee_by_weekly_copy`(var_month integer, var_year integer, var_empid varchar(255), var_uom varchar(255))
    DETERMINISTIC
BEGIN
	SELECT sd.itemid 'itemId',crm_fullname_adv(sd.itemid,i.itemname,i.itemcode) 'itemName',DAY(s.saldate) 'Day', SUM(IF(sd.uomid = i.uomid ,sd.salqty,(sd.salqty*(COALESCE((SELECT Conversion FROM tblitemuom WHERE tblitemuom.ItemID = sd.itemid AND tblitemuom.UomID = sd.uomid),0))))) as 'salQty', sd.uomid 'uomId', SUM(sd.nettotalamt) 'amount'
	FROM tblsales s
	LEFT JOIN tblsalesdetails sd on s.SalID = sd.SalID 
	LEFT JOIN tblitem i on i.itemid=sd.itemid
	WHERE s.empid = var_empid AND MONTH(s.saldate) = var_month AND Year(s.saldate) = var_year AND i.uomid = var_uom AND s.PostStatus IN('Open','Posted')
	GROUP BY DAY(s.saldate),sd.itemid
	ORDER BY sd.itemid,DATE(s.saldate);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_by_item`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_by_item`(var_sdate varchar(255), var_tdate varchar(255), var_pc varchar(255), var_fempid varchar(255), var_tempid varchar(255),var_fcustid varchar(255),var_tcustid varchar(255),  var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_empId varchar(255);
	DECLARE var_img_url varchar(255);
	DECLARE var_rt varchar(255);
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_user_id LIMIT 1)), 0);
	IF var_rt <> '1' THEN
		SET var_empId = COALESCE((SELECT EmpID FROM tbluseremployee WHERE UID = var_user_id),'');
		SET var_fempid = var_empId;
		SET var_tempid = var_empId;
	END IF;
	SELECT * 
	FROM (
		SELECT COALESCE(sd.itemid,'') 'itemId',COALESCE(i.itemname,'') 'itemName',COALESCE(i.itemcode,'') 'itemCode',COALESCE(i.itemgroupid,'') 'itemGroupId',i.uomid 'sku',COALESCE(SUM(sd.salqty*COALESCE(iu.conversion,1)),0) 'trqty'
		FROM tblsales s 
		INNER JOIN tblsalesdetails sd ON s.salid=sd.salid
		LEFT JOIN tblitemuom iu ON iu.itemid = sd.itemid AND iu.uomid = sd.uomid
		LEFT JOIN tblitem i ON i.itemid = sd.itemid
		WHERE DATE(s.saldate) BETWEEN var_sdate AND var_tdate
		AND IF(var_pc = 'all', s.poststatus IN('Open','Posted'), s.poststatus = var_pc)
		AND IF(var_fempid = 'all', TRUE, s.empid >= var_fempid) 
		AND IF(var_tempid = 'all', TRUE, s.empid <= var_tempid) 
		AND IF(var_fcustid = 'all', TRUE, sd.itemid >= var_fcustid)
		AND IF(var_tcustid = 'all', TRUE, sd.itemid <= var_tcustid)
		GROUP BY sd.itemid
	)as tbl
	WHERE tbl.trqty > 0
	ORDER BY tbl.itemId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_by_monthly`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_by_monthly`(var_month integer, var_year integer,var_userid varchar(255),var_empid varchar(255),var_custid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT e.empid 'empId', e.empname 'empName', 
		ROUND(SUM(IF(DAY(s.saldate) BETWEEN 1 AND 7,s.nettotalamt,0 )),2) 'week1', 
		ROUND(SUM(IF(DAY(s.saldate) BETWEEN 8 AND 14,s.nettotalamt,0 )),2) 'week2',
		ROUND(SUM(IF(DAY(s.saldate) BETWEEN 15 AND 21,s.nettotalamt,0 )),2) 'week3',
		ROUND(SUM(IF(DAY(s.saldate) BETWEEN 22 AND 28,s.nettotalamt,0 )),2) 'week4',
		ROUND(SUM(IF(DAY(s.saldate) BETWEEN 29 AND 31,s.nettotalamt,0 )),2) 'week5',
		ROUND(SUM(s.nettotalamt),2) 'total'
	FROM tblsales s
	LEFT JOIN tblemployee e on e.empid=s.empid
	WHERE MONTH(s.saldate) = var_month AND Year(s.saldate) = var_year AND s.PostStatus IN('Open','Posted')
	AND IF(crm_user_role_type(var_userid) = 1, TRUE, s.empid = COALESCE((SELECT empid FROM tbluseremployee WHERE tbluseremployee.uid = var_userid LIMIT 1),''))
	AND IF(var_empid = 'all',TRUE,e.empid =var_empid)
	AND IF(var_custid = 'all',TRUE,s.CustID =var_custid)
	GROUP BY e.empid
	ORDER BY e.empname;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_by_weekly`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_by_weekly`(var_month integer, var_year integer, var_uom varchar(255),var_ig varchar(255),var_userid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT sd.itemid 'itemId',i.itemcode 'itemCode',COALESCE(i.itemname,'') 'itemName',DAY(s.saldate) 'Day', SUM(IF(sd.uomid = i.uomid ,sd.salqty,(sd.salqty*(COALESCE((SELECT Conversion FROM tblitemuom WHERE tblitemuom.ItemID = sd.itemid AND tblitemuom.UomID = sd.uomid),0))))) as 'salQty', sd.uomid 'uomId', SUM(sd.nettotalamt) 'amount'
	FROM tblsales s
	LEFT JOIN tblsalesdetails sd on s.SalID = sd.SalID 
	LEFT JOIN tblitem i on i.itemid=sd.itemid
	LEFT JOIN tblitemuom iu on iu.itemid = sd.itemid 
	WHERE MONTH(s.saldate) = var_month AND Year(s.saldate) = var_year AND iu.uomid = var_uom AND s.PostStatus IN('Open','Posted')
	AND IF(var_ig = '', TRUE, i.itemgroupid=var_ig)
	AND IF(crm_user_role_type(var_userid) = 1, TRUE, s.empid = COALESCE((SELECT empid FROM tbluseremployee WHERE tbluseremployee.uid = var_userid LIMIT 1),''))
	GROUP BY DAY(s.saldate),sd.itemid
	ORDER BY sd.itemid,DATE(s.saldate);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_by_yearly`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_by_yearly`(var_year integer,var_userid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT e.empid 'empId', e.empname 'empName',
		ROUND(SUM(IF(MONTH(s.saldate) = 1 ,s.nettotalamt,0 )),2) 'm1', 
		ROUND(SUM(IF(MONTH(s.saldate) = 2,s.nettotalamt,0 )),2) 'm2',
		ROUND(SUM(IF(MONTH(s.saldate) = 3,s.nettotalamt,0 )),2) 'm3',
		ROUND(SUM(IF(MONTH(s.saldate) = 4,s.nettotalamt,0 )),2) 'm4',
		ROUND(SUM(IF(MONTH(s.saldate) = 5,s.nettotalamt,0 )),2) 'm5',
		ROUND(SUM(IF(MONTH(s.saldate) = 6 ,s.nettotalamt,0 )),2) 'm6', 
		ROUND(SUM(IF(MONTH(s.saldate) = 7,s.nettotalamt,0 )),2) 'm7',
		ROUND(SUM(IF(MONTH(s.saldate) = 8,s.nettotalamt,0 )),2) 'm8',
		ROUND(SUM(IF(MONTH(s.saldate) = 9,s.nettotalamt,0 )),2) 'm9',
		ROUND(SUM(IF(MONTH(s.saldate) = 10,s.nettotalamt,0 )),2) 'm10',
		ROUND(SUM(IF(MONTH(s.saldate) = 11,s.nettotalamt,0 )),2) 'm11',
		ROUND(SUM(IF(MONTH(s.saldate) = 12,s.nettotalamt,0 )),2) 'm12',
		ROUND(SUM(s.nettotalamt),2) 'total'
	FROM tblsales s
	LEFT JOIN tblemployee e on e.empid=s.empid
	WHERE YEAR(s.saldate) = var_year AND s.PostStatus IN('Open','Posted')
	AND IF(crm_user_role_type(var_userid) = 1, TRUE, s.empid = COALESCE((SELECT empid FROM tbluseremployee WHERE tbluseremployee.uid = var_userid LIMIT 1),''))
	GROUP BY e.empid
	ORDER BY e.empid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_grap`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_grap`(var_p varchar(50), P_UID varchar(50))
    DETERMINISTIC
BEGIN
	DECLARE var_empId varchar(255);
	DECLARE var_rt varchar(255);
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(P_UID)), 0);	
	SET var_empId = COALESCE((SELECT us.var_empid FROM ame_user us WHERE us.var_id = P_UID),'');
	IF var_p = 'daily' THEN
		SELECT DATE_FORMAT(dat_date,'%Y-%m-%d') 'day',ROUND(SUM(dou_net),2) 'total'
		FROM ame_ar_in
		WHERE DATE(dat_date) BETWEEN ame_get_first_last_day('thisMonth','FirstDay') AND ame_get_first_last_day('thisMonth','LastDay') AND var_status IN('Posted','Open')
		AND IF(var_rt = 1, TRUE,var_cusid IN(SELECT emp.var_cusid FROM ame_mt_cus_emp emp WHERE emp.var_empid = var_empId))
		GROUP BY DAY(dat_date);
	ELSEIF var_p = 'weekly' THEN
		SELECT CONCAT(DATE_FORMAT(dat_date,'%Y'),' W',WEEK(saldate)+1) 'day',ROUND(SUM(dou_net),2) 'total'
		FROM ame_ar_in
		WHERE DATE(dat_date) BETWEEN ame_get_first_last_day('thisYear','FirstDay') AND ame_get_first_last_day('thisYear','LastDay') AND var_status IN('Posted','Open')
		AND IF(var_rt = 1, TRUE,var_cusid IN(SELECT emp.var_cusid FROM ame_mt_cus_emp emp WHERE emp.var_empid = var_empId))
		GROUP BY WEEK(dat_date);
	ELSEIF var_p = 'monthly' THEN
		SELECT DATE_FORMAT(dat_date,'%Y-%m') 'day',ROUND(SUM(dou_net),2) 'total'
		FROM ame_ar_in
		WHERE DATE(dat_date) BETWEEN ame_get_first_last_day('thisYear','FirstDay') AND ame_get_first_last_day('thisYear','LastDay') AND var_status IN('Posted','Open')
		AND IF(var_rt = 1, TRUE,var_cusid IN(SELECT emp.var_cusid FROM ame_mt_cus_emp emp WHERE emp.var_empid = var_empId))
		GROUP BY MONTH(dat_date);
	ELSEIF var_p = 'quarterly' THEN
		SELECT CONCAT(DATE_FORMAT(dat_date,'%Y'),' Q',QUARTER(dat_date)) 'day',ROUND(SUM(dou_net),2) 'total'
		FROM ame_ar_in
		WHERE DATE(dat_date) BETWEEN ame_get_first_last_day('thisYear','FirstDay') AND ame_get_first_last_day('thisYear','LastDay') AND var_status IN('Posted','Open')
		AND IF(var_rt = 1, TRUE,var_cusid IN(SELECT emp.var_cusid FROM ame_mt_cus_emp emp WHERE emp.var_empid = var_empId))	
		GROUP BY QUARTER(dat_date);
	ELSEIF var_p = 'yearly' THEN
		SELECT DATE_FORMAT(dat_date,'%Y') 'day',ROUND(SUM(dou_net),2) 'total'
		FROM ame_ar_in
		WHERE var_status IN('Posted','Open')
		AND IF(var_rt = 1, TRUE,var_cusid IN(SELECT emp.var_cusid FROM ame_mt_cus_emp emp WHERE emp.var_empid = var_empId))
		GROUP BY YEAR(dat_date);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_invoice_grap`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_invoice_grap`(IN var_fd varchar(255), IN var_fcid varchar(255), IN var_tcid varchar(255), DRN tinyint(1),RET tinyint(1),CRN tinyint(1),PRE tinyint(1),P_UID varchar(100))
    DETERMINISTIC
BEGIN
	CALL AME_PRO_REP_RPT_M002D006_D1("Admin", "0", "USD", "Default","A-Z","", NOW(), NOW(), "All","All","All", "All", "All", "All","All","All", "All", "All", "All","All","All", "All", "All", "All","All",
																	 "All", "All", "All", "All","All","All", "1", "1", "1","1");
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_sale_invoice_out_grap`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_sale_invoice_out_grap`(IN var_fd varchar(255), IN var_fcid varchar(255), IN var_tcid varchar(255), DRN tinyint(1),RET tinyint(1),CRN tinyint(1),PRE tinyint(1),P_UID varchar(100))
    DETERMINISTIC
BEGIN
CALL AME_PRO_REP_RPT_M002D001_M1("Admin", "0", "USD", "Default","A-Z","All", NOW(), NOW(), "All","All","All", "All", "All", "All","All","All", "All", "All", "All","All","All", "All", "All", "All","All",
																	 "All", "All", "All", "All","All","All", "0", "0", "1","1","1","1");
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_stock_check`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_stock_check`(var_fitemid varchar(255),var_titemid varchar(255),var_figid varchar(255),var_tigid varchar(255),var_flocid varchar(255),var_tlocid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT i.itemid 'itemId', COALESCE(i.itemname,'') 'itemName', COALESCE(i.itemcode,'') 'itemCode', i.itemgroupid 'itemGroupId', COALESCE(ig.itemgroupname,'') 'itemGroupName', i.uomid 'sku',
       IF(i.uomid <> iu.uomid, CONCAT(i.uomid,'/',iu.uomid), i.uomid) 'uom',
			 COALESCE(iu.uomid,'') 'bUomId', COALESCE(iu.conversion,0) 'conversion',
			 ROUND(SUM(COALESCE(bc.QtyBalance,0)), 4) 'qty',
			 ROUND(SUM(IF(bc.locationid IN (SELECT locationid FROM tbllocation WHERE isBroken = 1) , COALESCE(bc.QtyBalance,0),0)),4) 'broken',
			 ROUND(COALESCE(tr.trqty,0),4) 'custStock'
	FROM tblitem i
	LEFT JOIN tblitemgroup ig ON ig.itemgroupid = i.itemgroupid
	LEFT JOIN tblitemuom iu ON iu.itemid = i.itemid
	LEFT JOIN tblbatchcost bc ON bc.itemid = i.itemid
	LEFT JOIN tbllocation l ON l.locationid=bc.locationid
	LEFT JOIN 
						(
							SELECT sd.itemid,COALESCE(SUM(sd.salqty*COALESCE(iu.conversion,1)),0) - COALESCE(tr.trqty,0) 'trqty'
							FROM tblsales s 
							INNER JOIN tblsalesdetails sd ON s.salid=sd.salid
							LEFT JOIN tblitemuom iu ON iu.itemid = sd.itemid AND iu.uomid = sd.uomid
							LEFT JOIN (
							SELECT trd.itemid,COALESCE(SUM(trd.trqty*COALESCE(iu.conversion,1)),0) 'trqty'  
							FROM tbltrack tr INNER JOIN tbltrackdetails trd ON tr.trid = trd.trid 
							LEFT JOIN tblitemuom iu on iu.itemid = trd.itemid AND iu.uomid=trd.uomid
							WHERE tr.poststatus = 'Open' AND tr.isprogress=0 AND COALESCE(tr.trtype,'Invoice') = 'Invoice'
							GROUP BY trd.itemid
							) tr ON tr.itemid = sd.itemid
							WHERE s.poststatus = 'Posted'
							GROUP BY sd.itemid
						) as tr ON tr.itemid=i.itemid
	WHERE i.inactive = 0 AND 
	IF((SELECT COUNT(*) FROM tblitemuom WHERE tblitemuom.itemid = i.itemid AND tblitemuom.bigConversion=1) > 0, iu.bigConversion = 1 , iu.uomid=i.uomid) #iu.uomid=i.uomid
	AND i.showonpos = 1 AND i.`Status` = 'Inventory Part' AND l.isrestrict = 0
  AND IF(var_fitemid = 'all',TRUE,i.itemid >= var_fitemid)
	AND IF(var_titemid = 'all',TRUE,i.itemid <= var_titemid)
	AND IF(var_figid = 'all',TRUE,i.ItemGroupID >= var_figid)
	AND IF(var_tigid = 'all',TRUE,i.ItemGroupID <= var_tigid)
	AND IF(var_flocid = 'all',TRUE,bc.LocationID >= var_flocid)
	AND IF(var_tlocid = 'all',TRUE,bc.LocationID <= var_tlocid)
	GROUP BY i.itemid
	ORDER BY ig.itemgroupid,i.itemid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_stock_check_1`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_stock_check_1`(var_fd varchar(255),var_td varchar(255),var_fitemid varchar(255),var_titemid varchar(255),var_figid varchar(255),var_tigid varchar(255),var_flocid varchar(255),var_tlocid varchar(255),var_userid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT T1.itemid 'itemId', T1.itemname 'itemName',T1.itemCode 'itemCode',T1.itemgroupid 'itemGroupId',T1.itemgroupname 'itemGroupName', 
         T1.SKU as 'sku',
				 #T2.uomid 'conversion',
         IF(T1.SKU <> T2.uomid, CONCAT(T1.SKU,'/',T2.uomid), T1.SKU) 'uom',
				 COALESCE(T4.BRO,0) 'broken', 
         (COALESCE(T4.BRO,0) + T1.SKU_QTY + COALESCE(T3.STO_CUS, 0)) AS 'qty', 
         ROUND((COALESCE(T4.BRO,0)+T1.SKU_QTY + COALESCE(T3.STO_CUS, 0)) / COALESCE(T2.conversion, 1), 4) AS 'BIG', 
         COALESCE(T3.STO_CUS, 0) AS 'custStock', 
         COALESCE(T2.conversion, 1) AS 'conversion' 
	FROM (
				SELECT T1.itemid, T2.itemname, ROUND(SUM(IF(T3.isBroken <> 1, T1.tdrcurmqty - T1.tcrcurmqty, 0)), 4) AS SKU_QTY, T2.uomid AS SKU, T2.itemcode 'itemCode',T2.itemgroupid,TG.itemgroupname 
        FROM tblsl_inv T1 
				LEFT JOIN tblitem T2 ON T1.itemid = T2.itemid
				LEFT JOIN tblitemgroup TG ON TG.itemgroupid = T2.itemgroupid
				LEFT JOIN tbllocation T3 ON T1.locationid = T3.locationid
				WHERE T2.inactive = 0 AND T2.`Status` = 'Inventory Part' AND T3.isrestrict = 0
				AND DATE(CONCAT(COALESCE(T1.periody,0),'-',COALESCE(T1.periodm,0),'-',COALESCE(T1.periodd,0))) <= var_td				
        AND IF(var_fitemid = 'all',TRUE,T2.itemid >= var_fitemid)
				AND IF(var_titemid = 'all',TRUE,T2.itemid <= var_titemid)
				AND IF(var_figid = 'all',TRUE,TG.ItemGroupID >= var_figid)
				AND IF(var_tigid = 'all',TRUE,TG.ItemGroupID <= var_tigid)
				AND IF(var_flocid = 'all',TRUE,T3.LocationID >= var_flocid)
				AND IF(var_tlocid = 'all',TRUE,T3.LocationID <= var_tlocid)
				GROUP BY T1.itemid
				) AS T1 #table T1
	LEFT JOIN (
		SELECT T1.itemid, ROUND(SUM(T1.tdrcurmqty - T1.tcrcurmqty), 4) AS BRO
        FROM tblsl_inv T1 
				LEFT JOIN tblitem T2 ON T1.itemid = T2.itemid
				LEFT JOIN tblitemgroup TG ON TG.itemgroupid = T2.itemgroupid
				LEFT JOIN tbllocation T3 ON T1.locationid = T3.locationid
				WHERE T2.inactive = 0 AND T2.`Status` = 'Inventory Part' AND T3.isrestrict = 0
				AND DATE(CONCAT(COALESCE(T1.periody,0),'-',COALESCE(T1.periodm,0),'-',COALESCE(T1.periodd,0))) <= var_td				
        AND IF(var_fitemid = 'all',TRUE,T2.itemid >= var_fitemid)
				AND IF(var_titemid = 'all',TRUE,T2.itemid <= var_titemid)
				AND IF(var_figid = 'all',TRUE,TG.ItemGroupID >= var_figid)
				AND IF(var_tigid = 'all',TRUE,TG.ItemGroupID <= var_tigid)
				AND T3.isBroken = 1
				GROUP BY T1.itemid
	) as T4 ON T1.itemid = T4.itemid
	LEFT JOIN tblitemuom T2 ON (T1.itemid = T2.itemid AND T2.bigConversion = 1) # table T2
	LEFT JOIN (
			SELECT T1.salid , T2.itemid, ROUND(SUM((COALESCE(T2.salqty, 0) - COALESCE(T4.trqty, 0)) * COALESCE(T5.conversion, 1)), 4) AS STO_CUS
			FROM tblsales T1 
			INNER JOIN tblsalesdetails T2 ON T1.salid = T2.salid
			LEFT JOIN (
								SELECT tr.salid,tr.custid,trd.itemid,SUM(trd.trqty) 'trqty',trd.uomid  
								FROM tbltrack tr INNER JOIN tbltrackdetails trd ON tr.trid = trd.trid 
								LEFT JOIN tblitemuom iu on iu.itemid = trd.itemid AND iu.uomid=trd.uomid
								WHERE tr.poststatus = 'Open' AND tr.isprogress = 0 AND COALESCE(tr.trtype,'Invoice') = 'Invoice' AND DATE(tr.trdate) <= var_td
								GROUP BY tr.salid,tr.custid,trd.itemid
			) AS T4 ON (T1.salid = T4.salid AND T2.itemid = T4.itemid AND T2.uomid = T4.uomid)
			LEFT JOIN tblitemuom T5 ON T2.itemid = T5.itemid AND T2.uomid = T5.uomid
			INNER JOIN tblitem T6 ON T2.itemid = T6.itemid
			WHERE T1.saltype = "General Item Sale" AND T1.poststatus = "Posted"  AND T6.`status` = "Inventory Part" AND T6.inactive = 0 
			AND DATE(T1.saldate) <= var_td      
			AND IF(var_figid = 'all',TRUE,T6.ItemGroupID >= var_figid)
			AND IF(var_tigid = 'all',TRUE,T6.ItemGroupID <= var_tigid)
			AND IF(var_fitemid = 'all',TRUE,T6.itemid >= var_fitemid)
			AND IF(var_titemid = 'all',TRUE,T6.itemid <= var_titemid)
			AND IF(var_flocid = 'all',TRUE,T2.locationid >= var_flocid)
			AND IF(var_tlocid = 'all',TRUE,T2.locationid <= var_tlocid)				
			GROUP BY T2.itemid HAVING STO_CUS > 0
	) AS T3 ON T1.itemid = T3.itemid
	WHERE ((COALESCE(T4.BRO,0) + T1.SKU_QTY + COALESCE(T3.STO_CUS, 0)) = 0 AND T3.STO_CUS = 0) <> TRUE
	; #table T3
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_rpt_stock_customer`;
DELIMITER |
CREATE PROCEDURE `crm_rpt_stock_customer`(var_fd varchar(255),var_td varchar(255),var_fcid varchar(255),var_tcid varchar(255),var_fitemid varchar(255),var_titemid varchar(255),var_flocid varchar(255),var_tlocid varchar(255),var_userid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT T1.salid 'saleId', T2.itemid 'itemId',T6.itemname 'itemName',T6.itemcode 'itemCode',
				 TC.custid 'custId',TC.custname 'custName',DATE_FORMAT(T1.saldate,'%d-%b-%Y') 'saleDate',
         ROUND(SUM((COALESCE(T2.salqty, 0) - COALESCE(T4.trqty, 0)) * COALESCE(T5.conversion, 1)), 4) AS trqty
	FROM tblsales T1 
	INNER JOIN tblsalesdetails T2 ON T1.salid = T2.salid
	LEFT JOIN tblcustomer TC ON T1.custid = TC.custid
	LEFT JOIN (
						SELECT tr.salid,tr.custid,trd.itemid,SUM(trd.trqty) 'trqty',trd.uomid  
						FROM tbltrack tr INNER JOIN tbltrackdetails trd ON tr.trid = trd.trid 
						LEFT JOIN tblitemuom iu on iu.itemid = trd.itemid AND iu.uomid=trd.uomid
						WHERE tr.poststatus = 'Open' AND tr.isprogress = 0 AND COALESCE(tr.trtype,'Invoice') = 'Invoice' AND DATE(tr.trdate) <= var_td
						GROUP BY tr.salid,tr.custid,trd.itemid
	) AS T4 ON (T1.salid = T4.salid AND T2.itemid = T4.itemid AND T2.uomid = T4.uomid)
	LEFT JOIN tblitemuom T5 ON T2.itemid = T5.itemid AND T2.uomid = T5.uomid
	INNER JOIN tblitem T6 ON T2.itemid = T6.itemid
	WHERE T1.saltype = "General Item Sale" AND T1.poststatus = "Posted"  AND T6.`status` = "Inventory Part" AND T6.inactive = 0
	AND DATE(T1.saldate) <= var_td
	AND IF(var_fitemid = 'all',TRUE,T6.itemid >= var_fitemid)
	AND IF(var_titemid = 'all',TRUE,T6.itemid <= var_titemid)
	AND IF(var_fcid = 'all',TRUE,TC.custid >= var_fcid)
	AND IF(var_tcid = 'all',TRUE,TC.custid <= var_tcid)
	AND IF(var_flocid = 'all',TRUE,T2.locationid >= var_flocid)
	AND IF(var_tlocid = 'all',TRUE,T2.locationid <= var_tlocid)
	GROUP BY T1.salid,TC.custid, T2.itemid 
  HAVING trqty > 0
	ORDER BY T2.itemid,TC.custname,T1.salid
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_invoice_add`;
DELIMITER |
CREATE PROCEDURE `crm_sale_invoice_add`(var_saleid varchar(255), var_saleRef varchar(255), var_saleDate varchar(255), var_custid varchar(255), var_pc varchar(255), var_ps  varchar(255), var_eid varchar(255), var_tAmt  double, var_DisInvDol double, var_DisInvPer double, var_TotalDis double, var_TotalSTax double, var_TotalVTax double,var_NetTotalAmt double, var_DueDate varchar(255), var_remark varchar(255), var_clid varchar(255), var_ship varchar(255),var_puid varchar(255), var_prefix varchar(255),var_term varchar(255),var_note varchar(255),var_location varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_check_id INTEGER DEFAULT COALESCE((SELECT COUNT(*) FROM tblsales WHERE SalID=var_saleid),0);
	IF var_check_id > 0 THEN
		SELECT 'Exists' as 'msg';
	ELSE
		INSERT INTO tblsales
			   (`SalID`, `SalType`, `SalReference`, `SalDate`, `PeriodM`, `PeriodY`, `CustID`, `PriceCode`, `PostStatus`, `PmtStatus`,`EmpID`, `TotalAmt`, `DisInvDol`, `DisInvPer`, `TotalDis`, `TotalSTax`, `TotalVTax`, `NetTotalAmt`,`Remark`,`LocationID`, `DueDate`, `ClassID`, `ShipTo`, `PrefixNumber`,`UserAction`, `uidcreate`,`datecreate`,`CusTerm`, `Note`) 
		VALUES (var_saleid,'General Item Sale',var_saleRef,var_saleDate,MONTH(var_saleDate), YEAR(var_saleDate),var_custid,var_pc,var_ps,'Unpaid',var_eid,var_tAmt,var_DisInvDol,var_DisInvPer,var_TotalDis,var_TotalSTax, var_TotalVTax,var_NetTotalAmt,var_remark,var_location,var_DueDate,var_clid,crm_sale_order_generate_ship_to(var_ship,var_custid),var_prefix,var_puid,var_puid,now(),var_term,var_note)
		;
		SELECT 'True' as 'msg';
	END IF;	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_invoice_add_online`;
DELIMITER |
CREATE PROCEDURE `crm_sale_invoice_add_online`(var_saleid varchar(255), var_saleRef varchar(255), var_saleDate varchar(255), var_custid varchar(255), var_pc varchar(255), var_ps  varchar(255), var_eid varchar(255), var_tAmt  double, var_DisInvDol double, var_DisInvPer double, var_TotalDis double, var_TotalSTax double, var_TotalVTax double,var_NetTotalAmt double, var_DueDate varchar(255), var_remark varchar(255), var_clid varchar(255), var_ship varchar(255),var_puid varchar(255), var_prefix varchar(255),var_term varchar(255),var_note varchar(255),var_location varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_check_id VARCHAR(255) DEFAULT COALESCE((SELECT CONCAT(var_id,crm_generate_zero(int_length,int_lastid)) FROM tblnumberprefix_custom WHERE var_id = var_prefix AND var_type ='AR-IN'),"");
	IF var_check_id <> '' THEN
		UPDATE tblnumberprefix_custom SET `int_lastid`=(int_lastid+1) WHERE (`var_type`='AR-IN') AND (`var_id`=var_prefix);
		INSERT INTO tblsales
				 (`SalID`, `SalType`, `SalReference`, `SalDate`, `PeriodM`, `PeriodY`, `CustID`, `PriceCode`, `PostStatus`, `PmtStatus`,`EmpID`, `TotalAmt`, `DisInvDol`, `DisInvPer`, `TotalDis`, `TotalSTax`, `TotalVTax`, `NetTotalAmt`,`Remark`,`LocationID`, `DueDate`, `ClassID`, `ShipTo`, `PrefixNumber`,`UserAction`, `uidcreate`,`datecreate`,`CusTerm`, `Note`) 
		VALUES (var_check_id,'General Item Sale',var_saleRef,var_saleDate,MONTH(var_saleDate), YEAR(var_saleDate),var_custid,var_pc,var_ps,'Unpaid',var_eid,var_tAmt,var_DisInvDol,var_DisInvPer,var_TotalDis,var_TotalSTax, var_TotalVTax,var_NetTotalAmt,var_remark,var_location,var_DueDate,var_clid,crm_sale_order_generate_ship_to(var_ship,var_custid),var_prefix,var_puid,var_puid,now(),var_term,var_note)
		;
	END IF;
	SELECT var_check_id as 'msg';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_invoice_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_sale_invoice_by_id`(var_saleid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT  
		s.SalID 'saleId',s.SalType 'saleType', DATE_FORMAT(s.SalDate, '%d-%m-%Y') 'saleDate', s.SalReference 'saleReference', s.PostStatus 'postStatus', s.Remark 'remark',DATE_FORMAT(s.DueDate, '%d-%m-%Y') 'dueDate',
		s.EmpID 'empId', COALESCE((SELECT e.EmpName FROM tblemployee e WHERE e.EmpID = s.EmpID LIMIT 1),'') 'empName',
		s.CustID 'custId', COALESCE((SELECT c.CustName FROM tblcustomer c WHERE c.CustID = s.CustID LIMIT 1),'') 'custName', 
		s.PriceCode 'priceCode', COALESCE((SELECT pc.Description FROM tblpricecode pc WHERE pc.PriceCode= s.PriceCode LIMIT 1),'') 'priceCodeDes',
		s.ClassID 'classId', COALESCE((SELECT Des FROM tblclass c WHERE c.ClassID = s.ClassID LIMIT 1), '') 'className',
		s.ShipTo 'shipAddr', COALESCE((SELECT sp.ShipName FROM tblshipaddress sp WHERE sp.shipid = s.ShipTo),'') 'shipName',
		s.TotalAmt 'totalAmtMaster', s.TotalDis 'totalDisMaster', s.TotalSTax 'totalSTaxMaster', s.TotalVTax 'totalVTaxMaster', s.NetTotalAmt 'netTotalAmtMaster', 
		s.CusTerm 'term',s.Note 'note', s.PrefixNumber 'prefix',
		s.LocationID 'locationMaster',COALESCE((SELECT rcpid FROM tbltemp_inv_paidatsales WHERE salid = var_saleid ORDER BY rcpid DESC LIMIT 1),'') 'rcpId',
		sd.ItemID 'itemId', COALESCE((SELECT i.ItemName FROM tblitem i WHERE i.ItemID = sd.ItemID LIMIT 1), '') 'itemName','' as 'itemImage',
		sd.LocationID 'locationId', COALESCE((SELECT l.Des FROM tbllocation l WHERE l.LocationID = sd.LocationID LIMIT 1), '') 'locationName',
		sd.ClassID 'classIdD', COALESCE((SELECT cd.Des FROM tblclass cd WHERE cd.ClassID = sd.ClassID LIMIT 1), '') 'classNameD',
		sd.UomID 'uomId', sd.SalQty 'salQty', sd.LineNo 'line',sd.Des 'description',
		sd.UnitPrice 'unitPrice', sd.Factor 'factor', sd.ReportPrice 'reportPrice',
		sd.TotalAmt 'totalAmt', sd.DisPer 'disPer', sd.DisDol 'disDol', sd.STaxPer 'sTaxPer', sd.STaxDol 'sTaxDol', sd.VTaxPer 'vTaxPer', sd.VTaxDol 'vTaxDol',sd.NetTotalAmt 'netTotalAmt'
	FROM tblsales s 
	LEFT JOIN tblsalesdetails sd ON s.SalID = sd.SalID
	WHERE s.SalID = var_saleid
	ORDER BY sd.LineNo ASC
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_invoice_delete`;
DELIMITER |
CREATE PROCEDURE `crm_sale_invoice_delete`(var_saleid varchar(255))
    DETERMINISTIC
BEGIN
	UPDATE tblsales SET `PostStatus`='Deleted' WHERE `SalID`=var_saleid AND PostStatus = 'Open';
	UPDATE tblsalesdetails SET `PostStatus`='Deleted' WHERE `SalID`=var_saleid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_invoice_paid`;
DELIMITER |
CREATE PROCEDURE `crm_sale_invoice_paid`(var_saleId varchar(255), var_rcpId varchar(255),var_account int(11),var_prefix  varchar(255), var_pmtMethod varchar(255), var_classId varchar(255),var_pmtRef varchar(255), var_ref varchar(255),var_remark varchar(255), du_dis double,du_amt double)
    DETERMINISTIC
BEGIN
	DECLARE var_receipt_id VARCHAR(255) DEFAULT COALESCE((SELECT CONCAT(var_id,crm_generate_zero(int_length,int_lastid)) FROM tblnumberprefix_custom WHERE var_type = 'AR-PY' AND var_id = var_prefix),''); 
	INSERT INTO `tbltemp_inv_paidatsales` (`salid`, `rcpid`, `accid`, `discount`, `amount`, `classid`, `pmtmethod`, `pmtmethodref`, `reference`, `remark`) 
	VALUES (var_saleId, var_receipt_id, var_account, du_dis, du_amt, var_classId, var_pmtMethod, var_pmtRef, var_ref, var_remark);
	SELECT var_receipt_id;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_invoice_paid_delete`;
DELIMITER |
CREATE PROCEDURE `crm_sale_invoice_paid_delete`(var_saleId varchar(255), var_rcpId varchar(255),var_account int(11))
    DETERMINISTIC
BEGIN
	DELETE FROM tbltemp_inv_paidatsales WHERE (`salid`=var_saleId) AND (`rcpid`=var_rcpId) AND (`accid`=var_account);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_invoice_paid_update`;
DELIMITER |
CREATE PROCEDURE `crm_sale_invoice_paid_update`(var_saleId varchar(255), var_rcpId varchar(255),var_account int(11),var_prefix  varchar(255), var_pmtMethod varchar(255), var_classId varchar(255),var_pmtRef varchar(255), var_ref varchar(255),var_remark varchar(255), du_dis double,du_amt double)
    DETERMINISTIC
BEGIN
	UPDATE `tbltemp_inv_paidatsales` SET `discount`=du_dis, `amount`=du_amt, `classid`=var_classId, `pmtmethod`=var_pmtMethod, `pmtmethodref`=var_pmtRef, `reference`=var_ref, `remark`=var_remark 
  WHERE (`salid`=var_saleId) AND (`rcpid`=var_rcpId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_invoice_update`;
DELIMITER |
CREATE PROCEDURE `crm_sale_invoice_update`(var_saleid varchar(255), var_saleRef varchar(255), var_saleDate varchar(255), var_custid varchar(255), var_pc varchar(255), var_ps  varchar(255), var_eid varchar(255), var_tAmt  double, var_DisInvDol double, var_DisInvPer double, var_TotalDis double, var_TotalSTax double, var_TotalVTax double,var_NetTotalAmt double, var_DueDate varchar(255), var_remark varchar(255), var_clid varchar(255), var_ship varchar(255),var_puid varchar(255), var_prefix varchar(255),var_term varchar(255),var_note varchar(255),var_location varchar(255))
    DETERMINISTIC
BEGIN
		UPDATE tblsales SET 
			`SalReference`=var_saleRef, 
			`SalDate`=var_saleDate, 
			`PeriodM`=MONTH(var_saleDate), 
			`PeriodY`=YEAR(var_saleDate), 
			`CustID`=var_custid, 
			`PriceCode`=var_pc, 
			`PostStatus`=var_ps,
			`EmpID`=var_eid, 
			`TotalAmt`=var_tAmt, 
			`DisInvDol`=var_DisInvDol, 
			`DisInvPer`=var_DisInvPer, 
			`TotalDis`=var_TotalDis, 
			`TotalSTax`=var_TotalSTax, 
			`TotalVTax`=var_TotalVTax, 
			`NetTotalAmt`=var_NetTotalAmt, 
			`Remark`=var_remark, 
			`LocationID`=var_location, 
			`DueDate`=var_DueDate, 
			`ClassID`=var_clid, 
			`ShipTo`=crm_sale_order_generate_ship_to(var_ship,var_custid), 
			`PrefixNumber`=var_prefix,
			`UserAction`=var_puid,
			`uidmodify`=var_puid,
			`datemodify`=now(), 
			`CusTerm`=var_term, 
			`Note`=var_note 
		WHERE `SalID`=var_saleid AND PostStatus = 'Open';
		DELETE FROM tblsalesdetails WHERE SalID = var_saleid;
		SELECT 'True' as 'msg';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_order_check_id`;
DELIMITER |
CREATE PROCEDURE `crm_sale_order_check_id`(in var_sale_id varchar(255))
    DETERMINISTIC
BEGIN
	select SalID FROM tblsaleorder WHERE SalID=var_sale_id  AND PostStatus= 'Open';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_order_generate_from_quote`;
DELIMITER |
CREATE PROCEDURE `crm_sale_order_generate_from_quote`(in `var_sale_id` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE v_finished INTEGER DEFAULT 0;
	DECLARE var_item_id varchar(255) DEFAULT "";
	DECLARE var_cust_id varchar(255) DEFAULT "";
	DECLARE var_price_id varchar(255) DEFAULT "";
	DEClARE CustID_Cursor CURSOR FOR SELECT ItemID FROM tblsbquotedetails WHERE SalID = var_sale_id ORDER BY LineNo;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
	SELECT CustID, PriceCode INTO var_cust_id, var_price_id FROM tblsbquote WHERE SalID = var_sale_id LIMIT 1;
	
	SELECT SalID 'saleId', COALESCE(SalType, '') 'salType',COALESCE(classId,'') 'classId', COALESCE(Remark,'') 'remark', COALESCE(SalReference,'') 'salReference', COALESCE(PriceCode,'') 'priceCode', COALESCE(PostStatus,'') 'postStatus',COALESCE(EmpID,'') 'empId', COALESCE(CustID,'') 'custId', 
       COALESCE(TotalAmt,0) 'tAmount', COALESCE(DisInvDol,0) 'disInvDol', COALESCE(DisInvPer,0) 'disInvPer', COALESCE(TotalDis,0) 'totalDis', COALESCE(TotalSTax,0) 'totalSTax', COALESCE(TotalVTax,0) 'totalVTax', COALESCE(NetTotalAmt,0) 'netTotalAmt', COALESCE(ShipTo,'') 'shipTo'
	FROM tblsbquote WHERE SalID = var_sale_id;

	SELECT SalID AS saleId, LineNo AS lineNo, ItemID AS itemId, UomID AS uomId, LocationID AS locationId, SalQty AS saleQuantity, UnitPrice AS unitPrice, TotalAmt AS totalAmt,   
				 PostStatus AS postStatus, NetTotalAmt AS netTotalAmt, DisDol AS disDol, DisPer AS disPer, STaxDol AS staxDol,   
				 STaxPer AS staxPer, VTaxDol AS vtaxDol, VTaxPer as  vtaxPer, ItemStatus AS itemStatus, ReportPrice AS reportPrice,  
				 Factor AS factor, IsVariable AS isVariable, ClassID AS classId, DisInv AS disInv	 ,COALESCE(var_item_detail ,'') description
	FROM tblsbquotedetails WHERE SalID = var_sale_id ORDER BY LineNo ASC ;

	OPEN CustID_Cursor;
		GetCustID: LOOP
			FETCH CustID_Cursor INTO var_item_id;
				IF v_finished = 1 THEN
					LEAVE GetCustID;
				END IF;
				CALL crm_sale_order_item_change(var_price_id,var_item_id,var_cust_id);
		END LOOP GetCustID;
	CLOSE CustID_Cursor;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_order_item_change`;
DELIMITER |
CREATE PROCEDURE `crm_sale_order_item_change`(IN `var_pc` varchar(255),IN `var_item_id` varchar(255), in `var_cust_id` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_price_override DOUBLE DEFAULT 0;
	DECLARE var_rp VARCHAR(255) DEFAULT COALESCE((SELECT PriceCode FROM tblpricecode WHERE ReportPrice = 1 LIMIT 1),'');
	
	
	-- check Latest Selling Price
	/*
	IF var_pc = 'Latest Selling Price' THEN
		IF var_rp = '' THEN
			SELECT iu.UomID 'uomId', COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName', COALESCE(iu.DefSal,0) 'defSal', crm_sale_order_item_change_latest_price(var_item_id,iu.UomID,var_cust_id) 'up', 0 'rp', COALESCE((SELECT COALESCE(IPD.DiscountPercent,0) FROM tblitempromotion IP LEFT JOIN tblitempromotiondetail IPD ON IP.PromotionID = IPD.PromotionID WHERE IPD.ItemID = var_item_id AND IPD.UomID = iu.UomID AND IP.`Status` = 0 AND DATE(IP.DateExpire) >= DATE(NOW()) ORDER BY IP.DateExpire DESC LIMIT 1),0) 'itemDiscount'
			FROM tblitemuom iu
			LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
			WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
		ELSE
				SELECT iu.UomID 'uomId',  COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName',  COALESCE(iu.DefSal,0) 'defSal', crm_sale_order_item_change_latest_price(var_item_id,iu.UomID,var_cust_id) 'up', COALESCE((SELECT PriceAmount FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_rp AND UomID = iu.UomID LIMIT 1),0) 'rp', COALESCE((SELECT COALESCE(IPD.DiscountPercent,0) FROM tblitempromotion IP LEFT JOIN tblitempromotiondetail IPD ON IP.PromotionID = IPD.PromotionID WHERE IPD.ItemID = var_item_id AND IPD.UomID = iu.UomID AND IP.`Status` = 0 AND DATE(IP.DateExpire) >= DATE(NOW()) ORDER BY IP.DateExpire DESC LIMIT 1),0) 'itemDiscount'
				FROM tblitemuom iu
				LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
				WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
		END IF;	

	ELSE
		-- check report price
		IF var_rp = '' THEN
			SET var_price_override = COALESCE((SELECT PriceAmount FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc AND OverridePrice = 1),0);
			-- check override price
			IF var_price_override = 0 THEN
				SELECT iu.UomID 'uomId',  COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName',  COALESCE(iu.DefSal,0) 'defSal', COALESCE(ip.PriceAmount,0) 'up', 0 'rp', COALESCE((SELECT COALESCE(IPD.DiscountPercent,0) FROM tblitempromotion IP LEFT JOIN tblitempromotiondetail IPD ON IP.PromotionID = IPD.PromotionID WHERE IPD.ItemID = var_item_id AND IPD.UomID = iu.UomID AND IP.`Status` = 0 AND DATE(IP.DateExpire) >= DATE(NOW()) ORDER BY IP.DateExpire DESC LIMIT 1),0) 'itemDiscount'
				FROM tblitemuom iu
				LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
				WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
			ELSE
				SELECT iu.UomID 'uomId',  COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName',  COALESCE(iu.DefSal,0) 'defSal', var_price_override 'up', 0 'rp', 0 'itemDiscount'
				FROM tblitemuom iu
				LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
				WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
			END IF;
		ELSE
			SET var_price_override = COALESCE((SELECT PriceAmount FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc AND OverridePrice = 1),0);
			-- check override price
			IF var_price_override = 0 THEN
				SELECT iu.UomID 'uomId',  COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName',  COALESCE(iu.DefSal,0) 'defSal', COALESCE(ip.PriceAmount,0) 'up', COALESCE((SELECT PriceAmount FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_rp AND UomID = iu.UomID LIMIT 1),0) 'rp', COALESCE((SELECT COALESCE(IPD.DiscountPercent,0) FROM tblitempromotion IP LEFT JOIN tblitempromotiondetail IPD ON IP.PromotionID = IPD.PromotionID WHERE IPD.ItemID = var_item_id AND IPD.UomID = iu.UomID AND IP.`Status` = 0 AND DATE(IP.DateExpire) >= DATE(NOW()) ORDER BY IP.DateExpire DESC LIMIT 1),0) 'itemDiscount'
				FROM tblitemuom iu
				LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
				WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
			ELSE
				SELECT iu.UomID 'uomId',  COALESCE((SELECT Des FROM tbluom WHERE UomID= iu.UomID LIMIT 1),'') 'uomName',  COALESCE(iu.DefSal,0) 'defSal', var_price_override 'up', COALESCE((SELECT PriceAmount FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_rp AND UomID = iu.UomID LIMIT 1),0) 'rp', COALESCE((SELECT COALESCE(IPD.DiscountPercent,0) FROM tblitempromotion IP LEFT JOIN tblitempromotiondetail IPD ON IP.PromotionID = IPD.PromotionID WHERE IPD.ItemID = var_item_id AND IPD.UomID = iu.UomID AND IP.`Status` = 0 AND DATE(IP.DateExpire) >= DATE(NOW()) ORDER BY IP.DateExpire DESC LIMIT 1),0) 'itemDiscount'
				FROM tblitemuom iu
				LEFT JOIN (SELECT UomID, PriceAmount,PriceDate FROM tblitempricing WHERE ItemID = var_item_id AND PriceCode = var_pc) as ip on ip.UomID=iu.UomID
				WHERE iu.ItemID = var_item_id AND iu.UomID is NOT NULL;
			END IF;
		END IF;		
	END IF;
*/
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_order_obj`;
DELIMITER |
CREATE PROCEDURE `crm_sale_order_obj`(in `var_sale_id` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE v_finished INTEGER DEFAULT 0;
	DECLARE var_item_id varchar(255) DEFAULT "";
	DECLARE var_cust_id varchar(255) DEFAULT "";
	DECLARE var_price_id varchar(255) DEFAULT "";
	DEClARE CustID_Cursor CURSOR FOR SELECT ItemID FROM tblsaleorderdetails WHERE SalID = var_sale_id ORDER BY LineNo;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
	SELECT CustID, PriceCode INTO var_cust_id, var_price_id FROM tblsaleorder WHERE SalID = var_sale_id LIMIT 1;
	
	SELECT SalID 'saleId', COALESCE(SalType, '') 'salType',COALESCE(classId,'') 'classId', COALESCE(Remark,'') 'remark', COALESCE(SalReference,'') 'salReference', COALESCE(PriceCode,'') 'priceCode', COALESCE(PostStatus,'') 'postStatus',COALESCE(EmpID,'') 'empId', COALESCE(CustID,'') 'custId', 
       COALESCE(TotalAmt,0) 'tAmount', COALESCE(DisInvDol,0) 'disInvDol', COALESCE(DisInvPer,0) 'disInvPer',DATE_FORMAT(SalDate,'%e-%b-%Y') 'salDate', DATE_FORMAT(DueDate,'%e-%b-%Y') 'dueDate', COALESCE(TotalDis,0) 'totalDis', COALESCE(TotalSTax,0) 'totalSTax', COALESCE(TotalVTax,0) 'totalVTax', COALESCE(NetTotalAmt,0) 'netTotalAmt', COALESCE(ShipTo,'') 'shipTo'
	FROM tblsaleorder WHERE SalID = var_sale_id;

	SELECT SalID AS saleId, LineNo AS lineNo, ItemID AS itemId, UomID AS uomId, LocationID AS locationId, SalQty AS saleQuantity, UnitPrice AS unitPrice, TotalAmt AS totalAmt,   
				 PostStatus AS postStatus, NetTotalAmt AS netTotalAmt, DisDol AS disDol, DisPer AS disPer, STaxDol AS staxDol,   
				 STaxPer AS staxPer, VTaxDol AS vtaxDol, VTaxPer as  vtaxPer, ItemStatus AS itemStatus, ReportPrice AS reportPrice,  
				 Factor AS factor, IsVariable AS isVariable, ClassID AS classId, DisInv AS disInv	 ,COALESCE(TransDesc ,'') description
	FROM tblsaleorderdetails WHERE SalID = var_sale_id ORDER BY LineNo ASC ;

	OPEN CustID_Cursor;
		GetCustID: LOOP
			FETCH CustID_Cursor INTO var_item_id;
				IF v_finished = 1 THEN
					LEAVE GetCustID;
				END IF;
				CALL crm_sale_order_item_change(var_price_id,var_item_id,var_cust_id);
		END LOOP GetCustID;
	CLOSE CustID_Cursor;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_order_obj_not_uom_list`;
DELIMITER |
CREATE PROCEDURE `crm_sale_order_obj_not_uom_list`(in `var_sale_id` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT SalID 'saleId', COALESCE(SalType, '') 'salType',COALESCE(classId,'') 'classId', COALESCE(Remark,'') 'remark', COALESCE(SalReference,'') 'salReference', COALESCE(s.PriceCode,'') 'priceCode', COALESCE(PostStatus,'') 'postStatus',COALESCE(EmpID,'') 'empId', COALESCE(s.CustID,'') 'custId', COALESCE(c.custname,'') 'custName',  COALESCE(CONCAT(c.CustTel1,'/',c.CustTel2),'') 'custTel', COALESCE(c.custaddress, '') 'shipAdd', 
       COALESCE(TotalAmt,0) 'tAmount', COALESCE(DisInvDol,0) 'disInvDol', COALESCE(DisInvPer,0) 'disInvPer',DATE_FORMAT(SalDate,'%e-%b-%Y') 'salDate', DATE_FORMAT(DueDate,'%e-%b-%Y') 'dueDate', COALESCE(TotalDis,0) 'totalDis', COALESCE(TotalSTax,0) 'totalSTax', COALESCE(TotalVTax,0) 'totalVTax', COALESCE(NetTotalAmt,0) 'netTotalAmt', COALESCE(ShipTo,'') 'shipTo' ,COALESCE((SELECT shipname FROM tblshipaddress WHERE docid= c.CustID AND shipid = ShipTo ), '') 'shipAdd1'
	FROM tblsaleorder s
	LEFT JOIN tblcustomer c on c.custid = s.custid
	WHERE SalID = var_sale_id;

	SELECT SalID AS saleId, LineNo AS lineNo, ItemID AS itemId,COALESCE((select ItemName from tblitem i WHERE i.ItemID = sd.ItemID limit 1), '') 'itemName', UomID AS uomId, LocationID AS locationId, SalQty AS saleQuantity, UnitPrice AS unitPrice, TotalAmt AS totalAmt,   
				 PostStatus AS postStatus, NetTotalAmt AS netTotalAmt, DisDol AS disDol, DisPer AS disPer, STaxDol AS staxDol,   
				 STaxPer AS staxPer, VTaxDol AS vtaxDol, VTaxPer as  vtaxPer, ItemStatus AS itemStatus, ReportPrice AS reportPrice,  
				 Factor AS factor, IsVariable AS isVariable, ClassID AS classId, DisInv AS disInv	 ,COALESCE(TransDesc ,'') description
	FROM tblsaleorderdetails sd WHERE SalID = var_sale_id ORDER BY LineNo ASC ;
	SELECT ComName 'comEN', ComNameKh 'comKH' FROM tblcompanyreport;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_order_startup_page`;
DELIMITER |
CREATE PROCEDURE `crm_sale_order_startup_page`(in var_user_id varchar(255), in var_obj_id varchar(255))
    DETERMINISTIC
BEGIN
DECLARE var_empId varchar(255);
DECLARE var_img_url varchar(255);
DECLARE var_rt varchar(255);
SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_user_id LIMIT 1)), 0);
SET var_empId = COALESCE((SELECT EmpID FROM tbluseremployee WHERE UID = var_user_id),'');

IF var_rt = '1' THEN
	SELECT CustID 'custId', COALESCE(CustName, '') 'custName' , COALESCE(PriceCode,'') 'priceCode', COALESCE(TermNetDueIn,0) 'termNetDueIn', COALESCE(AID,'') shipId, COALESCE(TermCreditLimit,'') 'termCreditLimit', COALESCE(TermFormat, '') 'termFormat'  FROM tblcustomer WHERE Inactive=0 ORDER BY CustID;
	SELECT COALESCE(EmpID,'') 'empId', COALESCE(EmpName,'') 'empName' FROM tblemployee WHERE Inactive=0 AND EmpID IN(SELECT EmpID FROM tblemployeesystemrole WHERE RoleName = 'Sale Representative') ORDER BY EmpID;
	SELECT ec.EmpID 'empId', ec.CustID 'custId' from  tblemployeecustomer ec ORDER BY ec.CustID;
ELSE
	SELECT CustID 'custId', COALESCE(CustName, '') 'custName' , COALESCE(PriceCode,'') 'priceCode', COALESCE(TermNetDueIn,0) 'termNetDueIn', COALESCE(AID,'') shipId, COALESCE(TermCreditLimit,'') 'termCreditLimit' , COALESCE(TermFormat, '') 'termFormat'   FROM tblcustomer WHERE Inactive=0 and CustID IN (SELECT CustID from tblemployeecustomer WHERE EmpID = var_empId) ORDER BY CustID;
	SELECT COALESCE(EmpID,'') 'empId', COALESCE(EmpName,'') 'empName' FROM tblemployee WHERE Inactive=0 AND EmpID = var_empId ORDER BY EmpID;
	SELECT ec.EmpID 'empId', ec.CustID 'custId' FROM tblemployeecustomer ec WHERE ec.EmpID=var_empId ORDER BY ec.CustID;
END IF;

SELECT COALESCE(SysCode,'') 'systemCode', COALESCE(LocationID,'') 'locationId', COALESCE(Des,'') 'locationName' FROM tbllocation ORDER BY LocationID;
SELECT COALESCE(ClassID,'') 'classId', COALESCE(Des, '') 'className' FROM tblclass WHERE Inactive=0;
SELECT COALESCE(ItemID,'') 'itemId', COALESCE(crm_fullname(itemcode,ItemName),'') 'itemName', crm_fullname(ItemID,ItemName) 'fullname' , COALESCE(itemcode,'') 'itemCode', COALESCE(itembarcode, '') 'itemBarcode' , COALESCE(ImagePath , '') 'imagePath' FROM tblitem WHERE Inactive = 0 and ItemID <> '' AND ItemID is not NULL AND tblitem.`status` = 'Inventory Part'  ORDER BY ItemID;
SELECT COALESCE(q.SalID,'') 'salId', COALESCE(DATE(q.SalDate),'') 'salDate', COALESCE(q.PostStatus,'') 'postStatus', COALESCE(q.SalReference,'') 'salReference', COALESCE(q.CustID,'') 'custId', COALESCE((SELECT CustName FROM tblcustomer WHERE CustID = q.CustID),'') 'custName', COALESCE(NetTotalAmt,'') 'netTotalAme' FROM tblsbquote q WHERE PostStatus = 'Open';
SELECT COALESCE(PriceCode,'') 'priceCodeId', COALESCE(Description,'') 'priceCodeName'  FROM tblpricecode ORDER BY PriceCode;
SELECT COALESCE(docid, '') 'custId', COALESCE(shipid, '') 'shipId', COALESCE(shipname, '') 'shipName' FROM tblshipaddress WHERE moduleid='MT-CUS' AND docid <> '' OR docid is NULL AND inactive = 0;
SELECT EmpID 'empId' FROM tbluseremployee WHERE UID = var_user_id;
IF var_obj_id  <> '' THEN
CALL crm_sale_order_obj(var_obj_id);
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_order_update_quote_status`;
DELIMITER |
CREATE PROCEDURE `crm_sale_order_update_quote_status`(in var_quote varchar(255))
    DETERMINISTIC
BEGIN
	UPDATE tblsbquote SET PostStatus = 'Closed' WHERE SalID=var_quote;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_return_add`;
DELIMITER |
CREATE PROCEDURE `crm_sale_return_add`(var_saleid varchar(255), var_saleRef varchar(255), var_saleDate varchar(255), var_custid varchar(255), var_pc varchar(255), var_ps  varchar(255), var_eid varchar(255), var_tAmt  double, var_DisInvDol double, var_DisInvPer double, var_TotalDis double, var_TotalSTax double, var_TotalVTax double,var_NetTotalAmt double, var_DueDate varchar(255), var_remark varchar(255), var_clid varchar(255), var_ship varchar(255),var_puid varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_auto_id VARCHAR(255) DEFAULT fnGetLastID("AR-RET");
	INSERT 
	INTO tblsales_return
       (`RetID`, `SalID`, `SalReference`, `SalDate`,`CustID`, `PriceCode`, `PostStatus`, `EmpID`, `TotalAmt`, `DisInvDol`, `DisInvPer`, `TotalDis`, `TotalSTax`, `TotalVTax`, `NetTotalAmt`, `DueDate`, `Remark`, `ClassID`, `ShipTo`, `uidcreate`, `datecreate`) 
	VALUES (var_auto_id,var_saleid, var_saleRef, var_saleDate, var_custid, var_pc, var_ps , var_eid, var_tAmt, var_DisInvDol, var_DisInvPer, var_TotalDis, var_TotalSTax, var_TotalVTax,var_NetTotalAmt, var_DueDate, var_remark, var_clid, crm_sale_order_generate_ship_to(var_ship,var_custid),var_puid, now());
	SELECT var_auto_id as 'MS_ID';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_return_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_sale_return_by_id`(var_retid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT  
		s.RetID 'retId', s.SalID 'saleId', DATE_FORMAT(s.SalDate, '%d-%m-%Y') 'saleDate', s.SalReference 'saleReference', s.PostStatus 'postStatus', s.Remark 'remark',DATE_FORMAT(s.DueDate, '%d-%m-%Y') 'dueDate',
		s.EmpID 'empId', COALESCE((SELECT e.EmpName FROM tblemployee e WHERE e.EmpID = s.EmpID LIMIT 1),'') 'empName',
		s.CustID 'custId', COALESCE((SELECT c.CustName FROM tblcustomer c WHERE c.CustID = s.CustID LIMIT 1),'') 'custName', 
		s.PriceCode 'priceCode', COALESCE((SELECT pc.Description FROM tblpricecode pc WHERE pc.PriceCode= s.PriceCode LIMIT 1),'') 'priceCodeDes',
		s.ClassID 'classId', COALESCE((SELECT Des FROM tblclass c WHERE c.ClassID = s.ClassID LIMIT 1), '') 'className',
		s.ShipTo 'shipAddr', COALESCE((SELECT sp.ShipName FROM tblshipaddress sp WHERE sp.shipid = s.ShipTo),'') 'shipName',
		s.TotalAmt 'totalAmtMaster', s.TotalDis 'totalDisMaster', s.TotalSTax 'totalSTaxMaster', s.TotalVTax 'totalVTaxMaster', s.NetTotalAmt 'netTotalAmtMaster', 

		sd.ItemID 'itemId', COALESCE((SELECT i.ItemName FROM tblitem i WHERE i.ItemID = sd.ItemID LIMIT 1), '') 'itemName','' as 'itemImage',
		sd.LocationID 'locationId', COALESCE((SELECT l.Des FROM tbllocation l WHERE l.LocationID = sd.LocationID LIMIT 1), '') 'locationName',
		sd.ClassID 'classIdD', COALESCE((SELECT cd.Des FROM tblclass cd WHERE cd.ClassID = sd.ClassID LIMIT 1), '') 'classNameD',
		sd.UomID 'uomId', sd.RetQty 'retQty',
		COALESCE((SELECT SUM(sdd.RetQty) FROM tblsalereturndetails sdd WHERE sdd.RetID IN (SELECT sr.RetID FROM tblsales_return sr WHERE sr.SalID = s.SalID AND sr.PostStatus IN ('Open', 'Posted')) AND sdd.ItemID = sd.ItemID), 0) 'retToDate',		
		COALESCE((SELECT md.SalQty FROM tblsalesdetails md WHERE md.SalID = s.SalID AND md.ItemID = sd.ItemID), 0) 'salQty', 		
		sd.UnitPrice 'unitPrice', sd.Factor 'factor', sd.ReportPrice 'reportPrice',
		sd.TotalAmt 'totalAmt', sd.DisPer 'disPer', sd.DisDol 'disDol', sd.STaxPer 'sTaxPer', sd.STaxDol 'sTaxDol', sd.VTaxPer 'vTaxPer', sd.VTaxDol 'vTaxDol',sd.NetTotalAmt 'netTotalAmt'
	FROM tblsales_return s 
	LEFT JOIN tblsalereturndetails sd ON s.RetID = sd.RetID
	WHERE s.RetID = var_retid
	ORDER BY sd.LineNo ASC
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_return_delete`;
DELIMITER |
CREATE PROCEDURE `crm_sale_return_delete`(var_entryid varchar(255), var_puid varchar(255))
    DETERMINISTIC
BEGIN
	UPDATE tblsales_return 
	SET `PostStatus`="Deleted", 
			`uidmodify`=var_puid,
			`datemodify`=now() 
	WHERE (`RetID`=var_entryid);
	UPDATE tblsalereturndetails SET PostStatus = 'Deleted' WHERE (`RetID`=var_entryid);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_return_list`;
DELIMITER |
CREATE PROCEDURE `crm_sale_return_list`(var_puid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT s.RetID 'entryId', s.SalID 'saleId', DATE_FORMAT(s.SalDate, '%d-%c-%Y') 'saleDate', s.SalReference 'saleReference', s.EmpID 'empId', COALESCE((SELECT EmpName FROM tblemployee e WHERE e.EmpID = s.EmpID),'') 'empName',
			s.CustID 'custId', COALESCE((SELECT CustName FROM tblcustomer c WHERE c.CustID = s.CustID), '') 'custName', NetTotalAmt 'netTotalAmt'
	FROM tblsales_return s
	ORDER BY RetID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_return_update`;
DELIMITER |
CREATE PROCEDURE `crm_sale_return_update`(var_saleid varchar(255), var_saleRef varchar(255), var_saleDate varchar(255), var_custid varchar(255), var_pc varchar(255), var_ps  varchar(255), var_eid varchar(255), var_tAmt  double, var_DisInvDol double, var_DisInvPer double, var_TotalDis double, var_TotalSTax double, var_TotalVTax double,var_NetTotalAmt double, var_DueDate varchar(255), var_remark varchar(255), var_clid varchar(255), var_ship varchar(255),var_puid varchar(255), var_entryid varchar(255))
    DETERMINISTIC
BEGIN
		DECLARE var_found INTEGER DEFAULT (SELECT COUNT(*) FROM tblsales_return WHERE `SalID`=var_saleid AND PostStatus = 'Open');
		IF var_found > 0 THEN 
			DELETE FROM tblsalereturndetails WHERE RetID = var_entryid;
			UPDATE tblsales_return
			SET 
				`SalID`=var_saleid,
				`SalReference`=var_saleRef, 
				`SalDate`=var_saleDate, 
				`CustID`=var_custid, 
				`PriceCode`=var_pc, 
				`PostStatus`=var_ps,
				`EmpID`=var_eid, 
				`TotalAmt`=var_tAmt, 
				`DisInvDol`=var_DisInvDol, 
				`DisInvPer`=var_DisInvPer, 
				`TotalDis`=var_TotalDis, 
				`TotalSTax`=var_TotalSTax, 
				`TotalVTax`=var_TotalVTax, 
				`NetTotalAmt`=var_NetTotalAmt,
				`DueDate`=var_DueDate,
				`Remark`=var_remark,
				`ClassID`=var_clid, 
				`ShipTo`=crm_sale_order_generate_ship_to(var_ship,var_custid),
				`uidmodify`=var_puid,
				`datemodify`=now()
			WHERE (`RetID`=var_entryid);	
		END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_zone_delete`;
DELIMITER |
CREATE PROCEDURE `crm_sale_zone_delete`(var_obj_id varchar(255), var_name varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE countSatus INT;
	SELECT COUNT(*) INTO countSatus FROM tblemployee WHERE crm_ZoneID = var_obj_id;
	IF countSatus <> 0 THEN
			SELECT 'USED' as 'Action',crmGenerateMessage("1061",'sale zone',var_obj_id) as 'alert';
	ELSE 
			DELETE FROM crm_sale_zone WHERE ZoneID = var_obj_id;
			SELECT 'DELETED' as 'Action',crmGenerateMessage("1002",'sale zone',var_obj_id) as 'alert';
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_zone_list`;
DELIMITER |
CREATE PROCEDURE `crm_sale_zone_list`()
    DETERMINISTIC
BEGIN
	SELECT c.ZoneID 'zoneId', c.ZoneName 'zoneName', c.ParentID 'parentId' , COALESCE(p.ZoneName,'') 'parentName'
	FROM crm_sale_zone c
	LEFT JOIN crm_sale_zone p ON p.ZoneID = c.ParentID
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sale_zone_start_up`;
DELIMITER |
CREATE PROCEDURE `crm_sale_zone_start_up`(var_zone_id varchar(255))
    DETERMINISTIC
BEGIN
	SELECT c.ZoneID 'zoneId', c.ZoneName 'zoneName'
	FROM crm_sale_zone c
	WHERE c.ParentID is null OR c.ParentID = "";
	IF var_zone_id <> 'all' THEN
		SELECT c.ZoneID 'zoneId', COALESCE(c.ZoneName,'') 'zoneName',COALESCE(c.Description,'') 'description', COALESCE(c.ParentID,'') 'parentId',COALESCE(c.co_street,'') 'street'  ,COALESCE(c.co_no,'') 'houseNo',
				   COALESCE(c.co_city,'') 'city' ,COALESCE(c.co_district,'') 'district',COALESCE(c.co_commune,'') 'commune',COALESCE(c.co_village,'') 'village'
		FROM crm_sale_zone c;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_SCHEDULE_CLONE_BY_CUST`;
DELIMITER |
CREATE PROCEDURE `CRM_SCHEDULE_CLONE_BY_CUST`(custID varchar(255))
    DETERMINISTIC
SELECT
	d.SC_Title 'Title',
	m.SC_Repeat 'Repeat',
	m.SC_Frequency 'Frequency',
	m.SC_Amount 'Amount',
	m.SC_Tag 'Tag',
	m.SC_StartDate 'StartDate',
	m.SC_EndRepeat 'EndDate',
	d.SC_Duration 'Duration',
	d.SC_Des 'Description'
FROM
	crm_schedule_master m
INNER JOIN crm_schedule_detail d
WHERE
	m.SC_ID = d.SC_ID
AND d.SC_Customer = custID
LIMIT 1 |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_SCHEDULE_DELETE__ALL`;
DELIMITER |
CREATE PROCEDURE `CRM_SCHEDULE_DELETE__ALL`(IN var_id VARCHAR(255))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_schedule_detail WHERE SC_ID = var_id;
	DELETE FROM crm_schedule_master WHERE SC_ID = var_id;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_SCHEDULE_EDIT_STARTUP`;
DELIMITER |
CREATE PROCEDURE `CRM_SCHEDULE_EDIT_STARTUP`(par_sc_id VARCHAR(100))
    DETERMINISTIC
BEGIN
	#MASTER
	SELECT
		sc_id 'SC_ID',
		sc_repeat 'SC_Repeat',
		sc_frequency 'SC_Frequency',
		sc_amount 'SC_Amount',
		sc_tag 'SC_Tag',
		sc_endrepeat 'SC_EndRepeat',
		sc_createby 'SC_CreateBy',
		sc_startdate 'SC_StartDate',
		sc_modifiedby 'SC_ModifiedBy',
		sc_modifieddate 'SC_ModifiedDate'
	FROM
		crm_schedule_master
	WHERE SC_ID = par_sc_id;

	#DETAIL
	SELECT
		VI_ID 'Id',
		SC_ID 'sc_Id',
		SC_Title 'scheduleTitle',
		SC_Des 'scheduleDes',
		DATE_FORMAT(
			SC_startDate,
			'%a %d-%m-%Y %h:%i %p'
		) 'startDate',
		SC_Duration 'scheduleDuration',
		SC_Location 'scheduleLocation',
		SC_Customer 'scheduleCustomer',
		SC_Employee 'scheduleEmployee',
		SC_Lat 'latitude',
		SC_Lng 'longitude'
	FROM
		crm_schedule_detail
	WHERE
		sc_Id = par_sc_id;
	
	#Employee
	SELECT var_id 'empId', COALESCE(var_name , '') 'empName' FROM ame_mt_emp WHERE tin_inactive = 0 ORDER BY var_name;

	#Customer by Employee
	SELECT var_cusid 'custId', var_empid 'empId' FROM ame_mt_cus_emp;

	#Customers
	SELECT var_id 'CustID', var_name 'CustName' FROM ame_mt_cus WHERE tin_inactive = 0 ORDER BY var_name;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_SCHEDULE_GET_EMPCUST_BY_ROLE`;
DELIMITER |
CREATE PROCEDURE `CRM_SCHEDULE_GET_EMPCUST_BY_ROLE`(IN empId VARCHAR(255))
    DETERMINISTIC
BEGIN
	#Role
	SELECT 
		RM_TypeID INTO @type 
	FROM crm_role cr 
	WHERE 
		RM_ID = (
			SELECT 
				u.var_crm_role 
			FROM 
				ame_user u 
			INNER JOIN ame_user_emp ue ON u.var_id = ue.var_id 
			INNER JOIN ame_mt_emp e ON ue.var_empid = e.var_id
			WHERE ue.var_empid = empId
		);
	#Get Cust Emp by Role
	IF @type = 1 THEN
		SELECT 
			var_id 'CustID', 
			COALESCE(var_name,'') 'CustName' 
		FROM 
			ame_mt_cus 
		ORDER BY var_name;
	ELSEIF @type = 2 THEN
		SELECT 
			c.var_id 'CustID', 
			COALESCE(var_name,'') 'CustName' 
		FROM 
			ame_mt_cus c 
		INNER JOIN 
			ame_mt_cus_emp ec ON ec.var_cusid = c.var_id
		WHERE ec.var_empid = empId 
		ORDER BY var_name;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_SCHEDULE_LIST`;
DELIMITER |
CREATE PROCEDURE `CRM_SCHEDULE_LIST`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT var_crm_role FROM ame_user WHERE var_id = userId);
	
	#Get Schedule List
	IF roleType = 1 THEN
		SELECT 
			VI_ID 'Id' ,
			SC_ID , 
			SC_Title 'Title' , 
			SC_Employee 'empId', 
			SC_Customer 'custID', 
			SC_Location 'Location', 
			SC_Des 'Description', 
			SC_Duration ,
			CONCAT("[",SC_Customer,"] ",(SELECT var_name FROM ame_mt_cus WHERE var_id = SC_Customer)) 'Customer', 
			CONCAT("[",SC_Employee,"] ",(SELECT var_name FROM ame_mt_emp WHERE var_id = SC_Employee)) 'Employee' , 
			DATE_FORMAT(SUBSTRING_INDEX(SC_startDate,' ',1),'%a') 'Day',
			DATE_FORMAT(SUBSTRING_INDEX(SC_startDate,' ',1), '%d/%m/%Y') 'Date', 
			TIME_FORMAT(SUBSTRING_INDEX(SC_startDate,' ',-1),'%h:%i %p') 'Time', 
			CONCAT(SC_Duration, ' mins') 'Duration', 
			SC_Lat 'Latitude', 
			SC_Lng 'Longitude', 
			VI_Status 'Status', 
			DATE_FORMAT(SC_startDate, '%Y-%m-%d %H:%i:%S') 'SC_startDate' 
		FROM crm_schedule_detail ORDER BY SC_startDate, Time;
	ELSE
		SELECT 
			VI_ID 'Id' ,
			SC_ID , 
			SC_Title 'Title' , 
			SC_Employee 'empId', 
			SC_Customer 'custID', 
			SC_Location 'Location', 
			SC_Des 'Description', 
			SC_Duration ,
			CONCAT("[",SC_Customer,"] ",(SELECT CustName FROM tblcustomer WHERE CustID = SC_Customer)) 'Customer', 
			CONCAT("[",SC_Employee,"] ",(SELECT EmpName FROM tblemployee WHERE EmpID = SC_Employee)) 'Employee' , 
			DATE_FORMAT(SUBSTRING_INDEX(SC_startDate,' ',1),'%a') 'Day' ,
			DATE_FORMAT(SUBSTRING_INDEX(SC_startDate,' ',1), '%d/%m/%Y') 'Date', 
			TIME_FORMAT(SUBSTRING_INDEX(SC_startDate,' ',-1),'%h:%i %p') 'Time', 
			CONCAT(SC_Duration, ' mins') 'Duration', 
			SC_Lat 'Latitude', 
			SC_Lng 'Longitude', 
			VI_Status 'Status', 
			DATE_FORMAT(SC_startDate, '%Y-%m-%d %H:%i:%S') 'SC_startDate' 
			FROM crm_schedule_detail 
			WHERE SC_Customer IN (select empc.var_cusid from ame_mt_cus_emp empc where empc.var_empid = (select ue.var_empid from ame_user_emp ue where ue.var_id = userId)) ORDER BY SC_startDate, Time;
	END IF;

	#Get Employees
	SELECT var_id 'empId', COALESCE(var_name , '') 'empName' FROM ame_mt_emp WHERE tin_inactive = 0 ORDER BY var_name;
	
	#Get Role Type
	SELECT roleType 'roleType';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_SCHEDULE_LIST_BY_ID`;
DELIMITER |
CREATE PROCEDURE `CRM_SCHEDULE_LIST_BY_ID`(IN var_id VARCHAR(255))
    DETERMINISTIC
SELECT 
	VI_ID 'Id' ,
	d.SC_ID , 
	SC_Title 'Title' , 
	SC_Employee 'empId', 
	SC_Customer 'custID', 
	SC_Location 'Location', 
	SC_Des 'Description', 
	SC_Duration ,
	CONCAT("[",SC_Customer,"] ",(SELECT CustName FROM tblcustomer WHERE CustID = SC_Customer)) 'Customer', 
	CONCAT("[",SC_Employee,"] ",(SELECT EmpName FROM tblemployee WHERE EmpID = SC_Employee)) 'Employee' , 
	DATE_FORMAT(SUBSTRING_INDEX(d.SC_startDate,' ',1),'%a') 'Day' ,
	DATE_FORMAT(SUBSTRING_INDEX(d.SC_startDate,' ',1), '%d/%m/%Y') 'Date', 
	TIME_FORMAT(SUBSTRING_INDEX(d.SC_startDate,' ',-1),'%h:%i %p') 'Time', 
	CONCAT(SC_Duration, ' mins') 'Duration', 
	SC_Lat 'Latitude', 
	SC_Lng 'Longitude', 
	VI_Status 'Status', 
	m.SC_CreateBy 'CreateBy', 
	m.SC_StartDate 'CreateDate', 
	d.VI_StartTime 'TimeCheckin', 
	d.VI_StartLat 'StartLatitute', 
	d.VI_StartLong 'StartLongitude', 
	d.VI_EndTime 'TimeCheckout', 
	d.VI_EndLat 'EndLatitude', 
	d.VI_EndLong 'EndLongitude', 
	TIMESTAMPDIFF(MICROSECOND, STR_TO_DATE(d.VI_StartTime, '%d-%m-%Y %h:%i %p'), 
	STR_TO_DATE(d.VI_EndTime, '%d-%m-%Y %h:%i %p'))/1000 'CheckDuration', 
	d.VI_Feedback 'Feedback' 
FROM 
	crm_schedule_detail d 
LEFT JOIN 
	crm_schedule_master m 
ON d.SC_ID = m.SC_ID WHERE VI_ID = var_id |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_SCHEDULE_LIST_CUST_ON_MAP`;
DELIMITER |
CREATE PROCEDURE `CRM_SCHEDULE_LIST_CUST_ON_MAP`()
    DETERMINISTIC
BEGIN
	SELECT 
		M_CheckIn_Longitude 'Longitude', 
		M_CheckIn_Latitude 'Latitude', 
		M_RToID 'Customer' 
	FROM 
		crm_meeting cm 
	WHERE M_CheckIn_Longitude <> '' AND M_CheckIn_Latitude <> '';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_SCHEDULE_REPORT`;
DELIMITER |
CREATE PROCEDURE `CRM_SCHEDULE_REPORT`(var_status varchar(5), var_sd varchar(255), var_ed varchar(255), var_emp varchar(100), var_cust varchar(100))
    DETERMINISTIC
BEGIN
	DECLARE var_date VARCHAR(255) DEFAULT ('');
	DECLARE var_person VARCHAR(255) DEFAULT ('');
	IF var_sd = '' AND var_ed = '' AND var_emp = '' AND var_cust = '' THEN
		IF var_status = 'show' THEN
			SET @SQL = CONCAT("SELECT CONCAT('[',SC_Customer,'] ',(SELECT var_name FROM ame_mt_cus WHERE var_id = SC_Customer)) 'custName', CONCAT('[',SC_Employee,'] ',(SELECT var_name FROM ame_mt_emp WHERE var_id = SC_Employee)) 'empName', DATE_FORMAT(SC_startDate,'%d-%b-%y %h:%i %p') 'dateTime', CONCAT(SC_Duration, ' mins') 'duration', SUBSTRING_INDEX(SC_Location, '|' ,- 1) 'location', COALESCE ((SELECT var_tel1 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel1', COALESCE ((SELECT var_tel2 FROM ame_mt_cus WHERE CustID = SC_Customer),'') 'custTel2', COALESCE (SC_Lat, '') 'SC_Lat', COALESCE (SC_Lng, '') 'SC_Lng', VI_Status,SC_startDate FROM crm_schedule_detail ORDER BY SC_startDate;");
		ELSE
			SET @SQL = CONCAT("SELECT (SELECT var_name FROM ame_mt_cus WHERE var_id = SC_Customer) 'custName',(SELECT var_name FROM ame_mt_emp WHERE var_id = SC_Employee) 'empName', DATE_FORMAT(SC_startDate, '%d-%b-%y %h:%i %p') 'dateTime', CONCAT(SC_Duration, ' mins')'duration', SUBSTRING_INDEX(SC_Location,'|',-1) 'location',COALESCE((SELECT var_tel1 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel1', COALESCE((SELECT var_tel2 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel2', COALESCE(SC_Lat,'') 'SC_Lat', COALESCE(SC_Lng,'') 'SC_Lng', VI_Status, SC_startDate FROM crm_schedule_detail ORDER BY SC_startDate;");
		END IF;
	ELSE
		-- DATE
		IF var_sd <> '' AND var_ed <> '' THEN
			SET var_date = CONCAT("CAST(SC_startDate AS date) >= CAST('", var_sd ,"' AS date) AND CAST(SC_startDate AS date) <= CAST('", var_ed, "' AS date)");
		ELSE
			IF var_ed = '' AND var_sd <> '' THEN
				SET var_date = CONCAT("CAST(SC_startDate AS date) >= CAST('", var_sd , "' AS date)");
			ELSEIF var_sd = '' AND var_ed <> '' THEN
				SET var_date = CONCAT("CAST(SC_startDate AS date) <= CAST('", var_ed , "' AS date)");
			END IF;
		END IF;
		-- EMP & CUST
		IF var_emp <> '' AND var_cust <> '' THEN
			SET var_person = CONCAT("SC_Employee = '" , var_emp , "' AND SC_Customer = '", var_cust , "'");
		ELSE
			IF var_cust = '' AND var_emp <> '' THEN
				SET var_person = CONCAT("SC_Employee = '" , var_emp, "'");
			ELSEIF var_emp = '' AND var_cust <> '' THEN
				SET var_person = CONCAT("SC_Customer = '" , var_cust, "'");
			END IF;
		END IF;
		IF var_date <> '' AND var_person <> '' THEN
			IF var_status = 'show' THEN
				SET @SQL = CONCAT("SELECT CONCAT('[',SC_Customer,'] ',(SELECT var_name FROM ame_mt_cus WHERE var_id = SC_Customer)) 'custName',CONCAT('[',SC_Employee,'] ',(SELECT var_name FROM ame_mt_emp WHERE var_id = SC_Employee)) 'empName', DATE_FORMAT(SC_startDate, '%d-%b-%y %h:%i %p') 'dateTime', CONCAT(SC_Duration, ' mins')'duration', SUBSTRING_INDEX(SC_Location,'|',-1) 'location', COALESCE((SELECT var_tel1 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel1', COALESCE((SELECT var_tel2 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel2', COALESCE(SC_Lat,'') 'SC_Lat', COALESCE(SC_Lng,'') 'SC_Lng', VI_Status, SC_startDate FROM crm_schedule_detail WHERE ", var_date, " AND " , var_person, " ORDER BY SC_startDate;");
			ELSE
				SET @SQL = CONCAT("SELECT (SELECT var_name FROM ame_mt_cus WHERE var_id = SC_Customer) 'custName',(SELECT var_name FROM ame_mt_emp WHERE var_id = SC_Employee) 'empName', DATE_FORMAT(SC_startDate, '%d-%b-%y %h:%i %p') 'dateTime', CONCAT(SC_Duration, ' mins')'duration', SUBSTRING_INDEX(SC_Location,'|',-1) 'location', COALESCE((SELECT var_tel1 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel1', COALESCE((SELECT var_tel2 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel2', COALESCE(SC_Lat,'') 'SC_Lat', COALESCE(SC_Lng,'') 'SC_Lng', VI_Status, SC_startDate FROM crm_schedule_detail WHERE ", var_date, " AND " , var_person, " ORDER BY SC_startDate;");
			END IF;
		ELSE
			IF var_person = '' THEN
				IF var_status = 'show' THEN
					SET @SQL = CONCAT("SELECT CONCAT('[',SC_Customer,'] ',(SELECT var_name FROM ame_mt_cus WHERE var_id = SC_Customer)) 'custName',CONCAT('[',SC_Employee,'] ',(SELECT var_name FROM ame_mt_emp WHERE var_id = SC_Employee)) 'empName', DATE_FORMAT(SC_startDate, '%d-%b-%y %h:%i %p') 'dateTime', CONCAT(SC_Duration, ' mins')'duration', SUBSTRING_INDEX(SC_Location,'|',-1) 'location', COALESCE((SELECT var_tel1 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel1', COALESCE((SELECT var_tel2 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel2', COALESCE(SC_Lat,'') 'SC_Lat', COALESCE(SC_Lng,'') 'SC_Lng', VI_Status, SC_startDate FROM crm_schedule_detail WHERE ", var_date, " ORDER BY SC_startDate;");
				ELSE
					SET @SQL = CONCAT("SELECT (SELECT var_name FROM ame_mt_cus WHERE var_id = SC_Customer) 'custName',(SELECT var_name FROM ame_mt_emp WHERE var_id = SC_Employee) 'empName', DATE_FORMAT(SC_startDate, '%d-%b-%y %h:%i %p') 'dateTime', CONCAT(SC_Duration, ' mins')'duration', SUBSTRING_INDEX(SC_Location,'|',-1) 'location', COALESCE((SELECT var_tel1 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel1', COALESCE((SELECT var_tel2 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel2', COALESCE(SC_Lat,'') 'SC_Lat', COALESCE(SC_Lng,'') 'SC_Lng', VI_Status, SC_startDate FROM crm_schedule_detail WHERE ", var_date, " ORDER BY SC_startDate;");
				END IF;
			ELSE
				IF var_status = 'show' THEN
					SET @SQL = CONCAT("SELECT CONCAT('[',SC_Customer,'] ',(SELECT var_name FROM ame_mt_cus WHERE var_id = SC_Customer)) 'custName',CONCAT('[',SC_Employee,'] ',(SELECT var_name FROM ame_mt_emp WHERE var_id = SC_Employee)) 'empName', DATE_FORMAT(SC_startDate, '%d-%b-%y %h:%i %p') 'dateTime', CONCAT(SC_Duration, ' mins')'duration', SUBSTRING_INDEX(SC_Location,'|',-1) 'location', COALESCE((SELECT var_name FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel1', COALESCE((SELECT var_tel2 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel2', COALESCE(SC_Lat,'') 'SC_Lat', COALESCE(SC_Lng,'') 'SC_Lng', VI_Status, SC_startDate FROM crm_schedule_detail WHERE ", var_person, " ORDER BY SC_startDate;");
				ELSE
					SET @SQL = CONCAT("SELECT (SELECT var_name FROM ame_mt_cus WHERE var_id = SC_Customer) 'custName',(SELECT var_name FROM ame_mt_emp WHERE var_id = SC_Employee) 'empName', DATE_FORMAT(SC_startDate, '%d-%b-%y %h:%i %p') 'dateTime', CONCAT(SC_Duration, ' mins')'duration', SUBSTRING_INDEX(SC_Location,'|',-1) 'location', COALESCE((SELECT var_tel1 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel1', COALESCE((SELECT var_tel2 FROM ame_mt_cus WHERE var_id = SC_Customer),'') 'custTel2', COALESCE(SC_Lat,'') 'SC_Lat', COALESCE(SC_Lng,'') 'SC_Lng', VI_Status, SC_startDate FROM crm_schedule_detail WHERE ", var_person, " ORDER BY SC_startDate;");
				END IF;
			END IF;
		END IF;
	END IF;
	PREPARE St FROM @SQL;
	EXECUTE St;
	DEALLOCATE PREPARE St;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_SCHEDULE_VIEW`;
DELIMITER |
CREATE PROCEDURE `CRM_SCHEDULE_VIEW`(par_visit_id VARCHAR(255))
    DETERMINISTIC
BEGIN
#Schedule
	SELECT
		d.vi_id 'VI_ID',
		d.sc_id 'SC_ID',
		d.sc_title 'SC_Title',
		d.sc_des 'SC_Des',
		d.sc_startdate 'SC_startDate',
		d.sc_duration 'SC_Duration',
		d.sc_employee 'SC_Employee',
		d.sc_customer 'SC_Customer',
		d.sc_location 'SC_Location',
		d.sc_lat 'SC_Lat',
		d.sc_lng 'SC_Lng',
		d.sc_shop 'SC_Shop',
		d.sc_visittype 'SC_VisitType',
		d.vi_starttime 'VI_StartTime',
		d.vi_startlat 'VI_StartLat',
		d.vi_startlong 'VI_StartLong',
		d.vi_endtime 'VI_EndTime',
		d.vi_endlat 'VI_EndLat',
		d.vi_endlong 'VI_EndLong',
		d.vi_status 'VI_Status',
		d.vi_feedback 'VI_FeedBack',
		d.saleid 'saleId',
		m.SC_StartDate 'StartCreate',
		m.SC_EndRepeat 'EndSchedule',
		SC_CreateBy 'SC_CreateBy',
		SC_ModifiedBy 'SC_ModifiedBy',
		SC_ModifiedDate 'SC_ModifiedDate',
		(SELECT var_name FROM ame_mt_emp WHERE var_id = d.SC_Employee) 'EmpName',
		(SELECT var_name FROM ame_mt_cus WHERE var_id = d.SC_Customer) 'CustName',
		TIMESTAMPDIFF(MICROSECOND,STR_TO_DATE(d.VI_StartTime,'%d-%m-%Y %h:%i %p'),STR_TO_DATE(d.VI_EndTime,'%d-%m-%Y %h:%i %p')) / 1000 'CheckDuration'
	FROM
		crm_schedule_detail d
	LEFT JOIN crm_schedule_master m ON d.SC_ID = m.SC_ID
	WHERE
		VI_ID = par_visit_id;

#Sale Order
	SELECT
		s.var_id 'saleId',
		COALESCE (var_type, '') 'salType',
		COALESCE (var_claid, '') 'classId',
		COALESCE ('', '') 'remark',
		COALESCE (var_ref, '') 'salReference',
		COALESCE (s.var_pricecode, '') 'priceCode',
		COALESCE (var_post, '') 'postStatus',
		COALESCE (var_empid, '') 'empId',
		COALESCE (s.var_cusid, '') 'custId',
		COALESCE (c.var_name, '') 'custName',
		COALESCE (CONCAT(c.var_tel1, '/', c.var_tel2),'') 'custTel',
		COALESCE (c.var_addr1, '') 'shipAdd',
		COALESCE (dou_sub, 0) 'tAmount',
		COALESCE (dou_disdol, 0) 'disInvDol',
		COALESCE (dou_disper, 0) 'disInvPer',
		DATE_FORMAT(dat_create, '%e-%b-%Y') 'salDate',
		DATE_FORMAT(dat_due, '%e-%b-%Y') 'dueDate',
		COALESCE (null, 0) 'totalDis',
		COALESCE (null, 0) 'totalSTax',
		COALESCE (null, 0) 'totalVTax',
		COALESCE (dou_net, 0) 'netTotalAmt',
		COALESCE (var_shipid, '') 'shipTo',
		COALESCE ((SELECT var_addr FROM ame_mt_ship_addr WHERE var_num = c.var_id AND var_id = var_shipid),'') 'shipAdd1'
	FROM
		ame_ar_so s
	LEFT JOIN ame_mt_cus c ON c.var_id = s.var_cusid
	WHERE
		s.var_id = (SELECT SaleID FROM crm_schedule_detail WHERE VI_ID = par_visit_id);

#Sale Detail
	SELECT
		var_id AS saleId,
		int_line AS lineNo,
		var_itemid AS itemId,
		COALESCE ((SELECT var_name FROM ame_mt_ite i WHERE i.var_id = sd.var_itemid LIMIT 1 ),'') 'itemName',
		var_uomid AS uomId,
		var_locid AS locationId,
		dou_orderqty AS saleQuantity,
		dou_price AS unitPrice,
		dou_sub AS totalAmt,
		'' AS postStatus,
		dou_net AS netTotalAmt,
		dou_disdol AS disDol,
		dou_disper AS disPer,
		dou_taxdol AS staxDol,
		dou_taxper AS staxPer,
		dou_taxdol1 AS vtaxDol,
		dou_taxper1 AS vtaxPer,
		'' AS itemStatus,
		'' AS reportPrice,
		'' AS factor,
		'' AS isVariable,
		var_claid AS classId,
		'' AS disInv,
		COALESCE ('', '') description
	FROM
		ame_ar_so_det sd
	WHERE
		var_id = (SELECT SaleID FROM crm_schedule_detail WHERE VI_ID = par_visit_id)
	ORDER BY
		LineNo ASC;

#Company NAME	
	SELECT 
		var_name2 'comEN', 
		var_name1 'comKH' 
	FROM 
		ame_mt_com;

#Survey
	SELECT
		ms.MS_ID,
		ms.MS_Subject,
		ms.MS_StartDate,
		ms.MS_EndDate,
		ms.MS_Status,
		ms.MS_CreateBy
	FROM
		crm_market_survey ms
	WHERE
		ms.MS_ID IN (
			SELECT
				SUBSTRING_INDEX(MSD_ID, '_', 1) 'MS_ID'
			FROM
				crm_market_survey_customer sc
			WHERE
				sc.VI_ID = par_visit_id
			GROUP BY
				MS_ID
		);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_search_schedule`;
DELIMITER |
CREATE PROCEDURE `crm_search_schedule`(IN var_startDate DATETIME ,
	IN var_endDate DATETIME,
	IN var_emp VARCHAR(255),
	IN var_cust VARCHAR(255))
    DETERMINISTIC
BEGIN

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sk_qty`;
DELIMITER |
CREATE PROCEDURE `crm_sk_qty`(IN var_lid varchar(255), IN var_lid_to varchar(255),IN var_itemid varchar(255), IN var_itemid_to varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
		COALESCE(i.itemgroupid,'') 'ItemGroupID',
		COALESCE(i.itemid,'') 'ItemID', 
		COALESCE(i.itemname,'') 'ItemName',
		COALESCE(i.itemcode,'') 'ItemCode', 
		COALESCE(i.uomid,'') 'SKU', 
		COALESCE((select CONCAT(COALESCE(iu.uomid,''),'!@#',COALESCE(iu.conversion,1)) from tblitemuom iu WHERE iu.itemid = i.itemid AND iu.defsal = 1),'!@#') 'UOM_SALE',  
		-- COALESCE(sl.locationid,'') 'LocationID', 
		COALESCE(SUM(sl.tdrcurmqty-sl.tcrcurmqty),0) as 'SKQty'
	FROM tblitem i
	LEFT JOIN tblsl_inv sl on sl.itemid = i.itemid
	WHERE ShowOnPos = 1 AND	
	IF(LOWER(var_lid) = 'all', TRUE, COALESCE(sl.locationid,'') >= var_lid) AND IF(LOWER(var_lid_to) = 'all', TRUE, COALESCE(sl.locationid,'') <= var_lid_to) AND
	IF(LOWER(var_itemid) = 'all', TRUE, COALESCE(i.itemid,'') >= var_itemid) AND IF(LOWER(var_itemid_to) = 'all', TRUE, COALESCE(i.itemid,'') <= var_itemid_to)
	GROUP BY i.itemid,sl.locationid
	ORDER BY i.itemid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sk_qty_by_item`;
DELIMITER |
CREATE PROCEDURE `crm_sk_qty_by_item`(IN var_itemid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
		COALESCE(i.itemgroupid,'') 'ItemGroupID',
		COALESCE(i.itemid,'') 'ItemID', 
		COALESCE(i.itemname,'') 'ItemName',
		COALESCE(i.itemcode,'') 'ItemCode',  
		COALESCE(sl.LocationID,'') 'LocationID',
		COALESCE(iu.UomID,'') 'UOM_SALE',
		COALESCE((COALESCE(SUM(sl.tdrcurmqty-sl.tcrcurmqty),0) / COALESCE(iu.Conversion,0)),0) as 'SKQty' 
	FROM tblitem i
	LEFT JOIN tblsl_inv sl on sl.itemid = i.itemid
	LEFT JOIN tblitemuom iu ON iu.ItemID = i.ItemID
	LEFT JOIN tbllocation l on l.LocationID=sl.LocationID
	WHERE i.ItemID = var_itemid
	GROUP BY sl.LocationID, iu.UomID;
	SELECT COALESCE((SELECT UomID  FROM tblitemuom WHERE ItemID  = var_itemid) ,'') 'uomId';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_sk_qty_startup`;
DELIMITER |
CREATE PROCEDURE `crm_sk_qty_startup`()
    DETERMINISTIC
BEGIN
	SELECT 
		COALESCE(i.itemgroupid,'') 'ItemGroupID',
		COALESCE(i.itemid,'') 'ItemID', 
		COALESCE(i.itemname,'') 'ItemName',
		COALESCE(i.itemcode,'') 'ItemCode', 
		COALESCE(i.uomid,'') 'SKU', 
		COALESCE((select CONCAT(COALESCE(iu.uomid,''),'!@#',COALESCE(iu.conversion,1)) from tblitemuom iu WHERE iu.itemid = i.itemid AND iu.defsal = 1 limit 1),'!@#') 'UOM_SALE',  
		-- COALESCE(sl.locationid,'') 'LocationID', 
		COALESCE(SUM(sl.tdrcurmqty-sl.tcrcurmqty),0) as 'SKQty'
	FROM tblitem i
	LEFT JOIN tblsl_inv sl on sl.itemid = i.itemid
	WHERE i.`Status` = 'Inventory Part' #i.ShowOnPos = 1 AND 
	GROUP BY i.itemid
	ORDER BY i.itemid,sl.locationid;
	SELECT COALESCE(ItemID,'') 'itemId', COALESCE(ItemName,'') 'itemName', crm_fullname(ItemID,ItemName) 'fullname' , COALESCE(itemcode,'') 'itemCode', COALESCE(itembarcode, '') 'itemBarcode' , COALESCE(ImagePath , '') 'imagePath' FROM tblitem WHERE Inactive = 0 and ItemID <> '' AND ItemID is not NULL AND tblitem.`status` = 'Inventory Part'	 ORDER BY ItemID;
	SELECT COALESCE(SysCode,'') 'systemCode', COALESCE(LocationID,'') 'locationId', COALESCE(Des,'') 'locationName' FROM tbllocation ORDER BY LocationID;
	SELECT COALESCE(itemgroupid, '') 'itemGroupId', itemgroupname 'itemGroupName' FROM tblitemgroup;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_stock_check`;
DELIMITER |
CREATE PROCEDURE `crm_stock_check`(var_item varchar(100), var_uom varchar(100))
    DETERMINISTIC
BEGIN
	SELECT LocationID 'locationId', ROUND(ROUND(SUM(QtyBalance), 4) / fnGetConversion(var_item, var_uom), 4) AS 'qty' FROM tblbatchcost WHERE ItemID = var_item GROUP BY LocationID, ItemID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_temporary_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_temporary_by_id`(var_objid varchar(255), var_type varchar(255))
    DETERMINISTIC
BEGIN
	IF var_type = 'temporary-over-due-date' THEN
		SELECT IssueID 'frmId', CustID 'custId', COALESCE((SELECT CustName FROM tblcustomer WHERE tblcustomer.CustID = tblcustomeroverdue.CustID),'') 'custName',
				 COALESCE(DATE_FORMAT(InstallmentDate, '%d-%b-%Y'), '') 'approvalDate', COALESCE(DATE_FORMAT(StartDate, '%d-%b-%Y'), '') 'startDate', COALESCE(DATE_FORMAT(EndDate, '%d-%b-%Y'), '') 'endDate', 
				 `Status` 'status', Relate 'relate', RelateID 'relateId',IF (Relate = 'Quotation',(SELECT NetTotalAmt FROM tblsbquote WHERE SalID = RelateID LIMIT 1), (SELECT NetTotalAmt FROM tblsaleorder WHERE SalID = RelateID LIMIT 1)) 'SaleAmount', Remark 'reason', 
				e.EmpID 'empId', e.EmpName 'empName', e.EmpPosition 'position', e.EmpTel1 'phone'
		FROM tblcustomeroverdue 
		LEFT JOIN tblemployee e ON e.EmpID = (SELECT EmpID FROM tbluseremployee WHERE UID = tblcustomeroverdue.CreateBy) 
		WHERE IssueID = var_objid;
	ELSE
		SELECT IssueID 'frmId', CustID 'custId', COALESCE((SELECT CustName FROM tblcustomer WHERE tblcustomer.CustID = tblcustomerissue.CustID),'') 'custName', IssueAmt 'amount',
			 COALESCE(DATE_FORMAT(InstallmentDate, '%d-%b-%Y'), '') 'approvalDate', COALESCE(DATE_FORMAT(StartDate, '%d-%b-%Y'), '') 'startDate', COALESCE(DATE_FORMAT(EndDate, '%d-%b-%Y'), '') 'endDate', 
       `Status` 'status', Relate 'relate', RelateID 'relateId',IF (Relate = 'Quotation',(SELECT NetTotalAmt FROM tblsbquote WHERE SalID = RelateID LIMIT 1), (SELECT NetTotalAmt FROM tblsaleorder WHERE SalID = RelateID LIMIT 1)) 'SaleAmount', Remark 'reason', 
        e.EmpID 'empId', e.EmpName 'empName', e.EmpPosition 'position', e.EmpTel1 'phone'
		FROM tblcustomerissue 
		LEFT JOIN tblemployee e ON e.EmpID = (SELECT EmpID FROM tbluseremployee WHERE UID = tblcustomerissue.CreateBy) 
		WHERE IssueID = var_objid;
	END IF;

	SELECT ComName 'comEN', ComNameKh 'comKH',Unit 'unit' FROM tblcompanyreport;
	
	SELECT EmpID 'empId', EmpName 'empName', EmpPosition 'position' , EmpTel1 'tel'
	FROM tblemployee WHERE EmpID in (select Auth_EmpID from hrm_authorisation_approved WHERE Auth_ProcessID = var_objid AND Auth_Status = 'approved');
	
	SELECT EmpID 'empId', EmpName 'empName', EmpPosition 'position' , EmpTel1 'tel'
	FROM tblemployee WHERE EmpID in (select Auth_EmpID from hrm_authorisation_approved WHERE Auth_ProcessID = var_objid AND Auth_Status = 'rejected');

	SELECT ImagePath FROM tblconfiguration LIMIT 1 ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_temporary_credit`;
DELIMITER |
CREATE PROCEDURE `crm_temporary_credit`(in var_userId varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rt varchar(255);
	DECLARE var_emp varchar(255);
	DECLARE role_id varchar(255);
	SET var_emp = (SELECT ame_user.var_empid FROM ame_user WHERE ame_user.var_id=var_userId );
	SET var_rt = 1;
	IF var_rt = '1' THEN
		SELECT ci.var_id 'issueId', ci.var_cusid 'custId', (SELECT var_name FROM ame_mt_cus c WHERE c.var_id=ci.var_cusid LIMIT 1 ) 'custName', COALESCE(DATE_FORMAT(ci.dat_date,'%e-%b-%Y'),'') 'approvalDate', COALESCE(DATE_FORMAT(ci.dat_from,'%e-%b-%Y'),'') 'startDate', COALESCE(DATE_FORMAT(ci.dat_to,'%e-%b-%Y'),'') 'endDate', var_desc 'remark', ci.var_status 'status', ci.var_create 'createBy', ci.dou_amt 'amount'
					, '' AS 'auth', ci.var_crm_relate 'relate', ci.var_crm_relateid 'relateId', ci.tin_editable 'editable'
		FROM ame_mt_tem_tc ci ORDER BY ci.var_id DESC;
		SELECT cus.var_id 'custId', COALESCE(cus.var_name, '') 'custName' , COALESCE(cus.var_pricecode,'') 'priceCode'  FROM ame_mt_cus cus WHERE cus.tin_inactive=0 ORDER BY cus.var_id;
	ELSE	
		SELECT IsOnlyRole ,uroleid INTO var_rt,role_id FROM tbluser WHERE UID = var_userId;
		IF var_rt = '1' THEN
			SELECT ci.IssueID 'issueId', ci.CustID 'custId', (SELECT CustName FROM tblcustomer c WHERE c.CustID=ci.CustID LIMIT 1 ) 'custName', COALESCE(DATE_FORMAT(InstallmentDate,'%e-%b-%Y'),'') 'approvalDate', COALESCE(DATE_FORMAT(StartDate,'%e-%b-%Y'),'') 'startDate', COALESCE(DATE_FORMAT(EndDate,'%e-%b-%Y'),'') 'endDate', Remark 'remark', `Status` 'status', CreateBy 'createBy', IssueAmt 'amount'
						, '' AS 'auth', ci.Relate 'relate', ci.RelateID 'relateId', ci.EditTable 'editable'
			FROM tblcustomerissue ci 
			WHERE createby IN(SELECT UID FROM tbluser WHERE uroleid = role_id)
			ORDER BY ci.IssueID DESC;
			
			SELECT CustID 'custId', CustName 'custName' , crm_fullname(CustID,CustName) 'fullname' FROM tblcustomer ;
		ELSE
			SELECT ci.IssueID 'issueId', ci.CustID 'custId', (SELECT CustName FROM tblcustomer c WHERE c.CustID=ci.CustID LIMIT 1 ) 'custName', COALESCE(DATE_FORMAT(InstallmentDate,'%e-%b-%Y'),'') 'approvalDate', COALESCE(DATE_FORMAT(StartDate,'%e-%b-%Y'),'') 'startDate', COALESCE(DATE_FORMAT(EndDate,'%e-%b-%Y'),'') 'endDate', Remark 'remark', `Status` 'status', CreateBy 'createBy', IssueAmt 'amount'
						, '' AS 'auth', ci.Relate 'relate', ci.RelateID 'relateId', ci.EditTable 'editable'
			FROM tblcustomerissue ci 
			WHERE createby = var_userId
			ORDER BY ci.IssueID DESC;		
			SELECT CustID 'custId', CustName 'custName' , crm_fullname(CustID,CustName) 'fullname' FROM tblcustomer WHERE CustID in (SELECT CustID FROM tblemployeecustomer WHERE EmpID = var_emp );
		END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_temporary_credit_check_status`;
DELIMITER |
CREATE PROCEDURE `crm_temporary_credit_check_status`(IN var_obj_id varchar(255))
    DETERMINISTIC
BEGIN
	SELECT * FROM ame_mt_tem_tc WHERE var_id = var_obj_id AND var_status = 'Requested' AND tin_editable = 1;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_temporary_over_due`;
DELIMITER |
CREATE PROCEDURE `crm_temporary_over_due`(in var_userId varchar(255))
    DETERMINISTIC
BEGIN
DECLARE var_rt varchar(255);
DECLARE var_emp varchar(255);
DECLARE role_id varchar(255);
SET var_emp = (SELECT ame_user.var_empid FROM ame_user WHERE ame_user.var_id=var_userId );
SET var_rt = 1;
IF var_rt = '1' THEN
	SELECT ci.var_id 'issueId', ci.var_cusid 'custId', (SELECT var_name FROM ame_mt_cus c WHERE c.var_id=ci.var_cusid LIMIT 1 ) 'custName', COALESCE(DATE_FORMAT(ci.dat_approved,'%e-%b-%Y'),'') 'approvalDate', COALESCE(DATE_FORMAT(ci.dat_from,'%e-%b-%Y'),'') 'startDate', COALESCE(DATE_FORMAT(ci.dat_to,'%e-%b-%Y'),'') 'endDate', ci.var_desc 'remark', ci.var_status 'status', ci.var_create 'createBy', 
	       '' as 'auth', ci.var_crm_relate 'relate', ci.var_crm_relateid 'relateId', ci.tin_editable 'editable'
	FROM ame_mt_tem_odd ci 
	ORDER BY ci.var_id DESC;
	SELECT cus.var_id 'custId', COALESCE(cus.var_name, '') 'custName' ,crm_fullname(cus.var_id, cus.var_name) 'fullname', COALESCE(cus.var_pricecode,'') 'priceCode'  FROM ame_mt_cus cus WHERE cus.tin_inactive=0 ORDER BY cus.var_id;
ELSE	
	SELECT IsOnlyRole ,uroleid INTO var_rt,role_id FROM tbluser WHERE UID = var_userId;
	IF var_rt = '1' THEN
		SELECT ci.IssueID 'issueId', ci.CustID 'custId', (SELECT CustName FROM tblcustomer c WHERE c.CustID=ci.CustID LIMIT 1 ) 'custName', COALESCE(DATE_FORMAT(InstallmentDate,'%e-%b-%Y'),'') 'approvalDate', COALESCE(DATE_FORMAT(StartDate,'%e-%b-%Y'),'') 'startDate', COALESCE(DATE_FORMAT(EndDate,'%e-%b-%Y'),'') 'endDate', Remark 'remark', `Status` 'status', CreateBy 'createBy', 
		       '' as 'auth', ci.Relate 'relate', ci.RelateID 'relateId', ci.EditTable 'editable'
		FROM tblcustomeroverdue ci
		WHERE createby IN(SELECT UID FROM tbluser WHERE uroleid = role_id)
		ORDER BY ci.IssueID DESC;
		SELECT CustID 'custId', CustName 'custName' , crm_fullname(CustID,CustName) 'fullname' FROM tblcustomer ;
	ELSE
		SELECT ci.IssueID 'issueId', ci.CustID 'custId', (SELECT CustName FROM tblcustomer c WHERE c.CustID=ci.CustID LIMIT 1 ) 'custName', COALESCE(DATE_FORMAT(InstallmentDate,'%e-%b-%Y'),'') 'approvalDate', COALESCE(DATE_FORMAT(StartDate,'%e-%b-%Y'),'') 'startDate', COALESCE(DATE_FORMAT(EndDate,'%e-%b-%Y'),'') 'endDate', Remark 'remark', `Status` 'status', CreateBy 'createBy', 
		       '' as 'auth', ci.Relate 'relate', ci.RelateID 'relateId', ci.EditTable 'editable'
		FROM tblcustomeroverdue ci
		WHERE createby = var_userId
		ORDER BY ci.IssueID DESC;
		SELECT CustID 'custId', CustName 'custName' , crm_fullname(CustID,CustName) 'fullname' FROM tblcustomer WHERE CustID in (SELECT CustID FROM tblemployeecustomer WHERE EmpID = var_emp );
	END IF;
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_temporary_over_due_check_status`;
DELIMITER |
CREATE PROCEDURE `crm_temporary_over_due_check_status`(IN var_obj_id varchar(255))
    DETERMINISTIC
BEGIN
	SELECT * FROM ame_mt_tem_odd WHERE var_id = var_obj_id AND `var_status` = 'Requested' AND tin_editable = 1;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_updateOpportunityStageField`;
DELIMITER |
CREATE PROCEDURE `crm_updateOpportunityStageField`(IN `oppID` varchar(255),IN `stageID` int,IN `cusID` varchar(255))
    DETERMINISTIC
BEGIN
UPDATE crm_opportunity SET OP_StageID = stageID WHERE OP_ID = oppID AND OP_CustID = cusID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_user_employee_add`;
DELIMITER |
CREATE PROCEDURE `crm_user_employee_add`(var_userid varchar(255), var_empid varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM tbluseremployee WHERE UID = var_userid;
	INSERT tbluseremployee(UID, EmpID) VALUES(var_userid,var_empid);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `findCrmCallById`;
DELIMITER |
CREATE PROCEDURE `findCrmCallById`(IN `callId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT
		cl.CL_ID AS callId,
		cl.CL_Subject AS callSubject,
		DATE_FORMAT(cl.CL_SDate,'%d/%m/%Y %h:%i %p') AS callStartDate,
		cl.CL_Duration AS callDuration,
		cl.CL_RToType AS callRelatedToModuleType,
		cl.CL_RToID AS callRelatedToFieldId,
		findModuleDetailsByModuleNameAndItsId(cl.CL_RToType,cl.CL_RToID) AS callRelatedName,
		cl.CL_Des AS callDes,
		cl.CL_CBy AS callCreateBy,
		cl.CL_CDate AS callCreateDate,
		cl.CL_MBy AS callModifiedBy,
		cl.CL_MDate AS callModifiedDate,
		cls.CLS_ID AS callStatusId,
		cls.CLS_Name AS callStatusName,
		us.UID AS userID,
		us.UName AS username
	FROM 
		crm_call cl 
	INNER JOIN
		crm_call_status cls
			ON cl.CL_StatusID = cls.CLS_ID
	LEFT OUTER JOIN 
		tbluser us 
			ON cl.CL_ATo = us.UID
	WHERE cl.CL_ID = callId;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `findCrmCampaignById`;
DELIMITER |
CREATE PROCEDURE `findCrmCampaignById`(IN `campID` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT 
		ca.CA_ID campID, 
		ca.CA_Name campName, 
		ca.CA_SDate startDate, 
		ca.CA_EDate endDate, 
		cas.CAS_ID statusID, 
		cas.CAS_Name statusName,
		cat.CAT_ID typeID, 
		cat.CAT_Name typeName, 
		cam.CA_ID parentID, 
		cam.CA_Name parentName, 
		cu.UID userID, 
		cu.UName username, 
		ca.CA_Budget budget, 
		ca.CA_ActualCost actualCost,
		ca.CA_ExpectedCost expectedCost, 
		ca.CA_ExpectedRevenue expectedRevenue, 
		ca.CA_NumSend numSend, 
		ca.CA_ExpectedResponse expectedResponse, 
		ca.CA_CBy createdBy,
		ca.CA_CDate createdDate, 
		CAST(ca.CA_MDate AS date) modifiedDate, 
		ca.CA_MBy modifiedBy, ca.CA_Des description
	FROM crm_camp ca
	INNER JOIN 
		crm_camp_status cas 
			ON ca.CA_StatusID = cas.CAS_ID
	INNER JOIN 
		crm_camp_type cat 
			ON ca.CA_TypeID = cat.CAT_ID
	LEFT OUTER JOIN 
		crm_camp cam 
			ON ca.CA_ParentID = cam.CA_ID
	LEFT OUTER JOIN 
		tbluser cu 
			ON ca.CA_ATo = cu.UID
  WHERE ca.CA_ID = campID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `findCrmCaseById`;
DELIMITER |
CREATE PROCEDURE `findCrmCaseById`(IN `caseId` varchar(11))
    DETERMINISTIC
BEGIN
SELECT
cs.CS_ID caseId,
css.CSS_ID statusId,
css.CSS_Name statusName,
cst.CST_ID caseTypeId,
cst.CST_Name caseTypeName,
csp.CSP_ID priorityId,
csp.CSP_Name priorityName,
cus.CustID custID,
cus.CustName custName,
con.CO_ID conID,
con.CO_Salutation conSalutation,
con.CO_FirstName conFirstname,
con.CO_LastName conLastname,
cs.CS_Subject `subject`,
cs.CS_Des des,
cs.CS_Key caseKey,
cs.CS_ResolvedBy resolvedBy,
(SELECT tbluser.UName FROM tbluser WHERE UID= cs.CS_ResolvedBy) resolveByName,
DATE_FORMAT(cs.CS_ResolvedDate,'%d/%m/%Y %h:%i %p') resolveDate,
cs.CS_Resolution resolution,
u.UID userID,
u.UName username,
cs.CS_ATo assignTo,
cs.CS_CBy createBy,
DATE_FORMAT(cs.CS_CDate,'%d/%m/%Y %h:%i %p') createDate,
cs.CS_MBy modifyBy,
DATE_FORMAT(cs.CS_MDate,'%d/%m/%Y %h:%i %p') modifyDate,
DATE_FORMAT(cs.CS_FollowupDate,'%d/%m/%Y %h:%i %p') followupDate,
DATE_FORMAT(cs.CS_EndDate,'%d/%m/%Y %h:%i %p') endDate,
cs.CS_OriginID caseOriginId,
(SELECT org.CS_Title FROM crm_case_origin org WHERE org.CS_OriginID = cs.CS_OriginID) caseOriginTitle,
cs.CS_PriceCode casePriceCode,
(SELECT Description FROM tblpricecode WHERE PriceCode = cs.CS_PriceCode) casePriceCodeDes,
cs.CS_Class as caseClassId,
(SELECT tblclass.Des FROM tblclass WHERE ClassID = cs.CS_Class) caseClassName,
cs.CS_ItemID caseItemId,
(SELECT ItemName FROM tblitem WHERE tblitem.ItemID = cs.CS_ItemID) caseItemName,
cs.CS_ArticleID articleId,
(SELECT art.A_Title FROM crm_case_article art WHERE art.A_ID= cs.CS_ArticleID) articleTitle,
cs.CS_OriginID originId,
(SELECT CS_Title FROM crm_case_origin WHERE CS_OriginID = cs.CS_OriginID) originName
FROM
crm_case cs
INNER JOIN
crm_case_status css
ON css.CSS_ID = cs.CS_StatusID
INNER JOIN
crm_case_priority csp
ON csp.CSP_ID = cs.CS_Priority
INNER JOIN
crm_case_type cst
ON cst.CST_ID = cs.CS_TypeID
LEFT OUTER JOIN
tblcustomer cus
ON cus.CustID = cs.CS_CustID
LEFT OUTER JOIN
crm_contact con
ON con.CO_ID = cs.CS_ContactID
LEFT OUTER JOIN
tbluser u
ON u.UID = cs.CS_ATo
WHERE cs.CS_ID = caseId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `findCrmContactById`;
DELIMITER |
CREATE PROCEDURE `findCrmContactById`(IN `conID` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT con.CO_ID conID, 
				con.CO_FirstName conFirstName,
				con.CO_LastName conLastName,
				con.CO_Salutation conSalutation,
				con.CO_Phone conPhone,
				con.CO_Mobile conMobile,
				con.CO_Email conEmail,
				con.CO_Title conTitle,
				con.CO_Department conDepartment,
				con.CO_No conNo,
				con.CO_Street conStreet,
				con.CO_Village conVillage,
				con.CO_Commune conCommune,
				con.CO_District conDistrict,
				con.CO_City conCity,
				con.CO_State conState,
				con.CO_Country conCountry,
				cu.UID assignToUserId,
				cu.UName assignToUsername,
				les.LS_ID sourceID,
				les.LS_Name sourceName,
				pcon.CO_ID reportToContactId,
				pcon.CO_FirstName reportToFirstname,
				pcon.CO_LastName reportToLastName,
				pcon.CO_Salutation reportToSalutation,
				con.CO_CBy conCreateBy,
				con.CO_CDate conCreateDate,
				con.CO_MBy conModifyBy,
				CAST(con.CO_MDate AS date) modifyDate,
				cust.CustID custID, 
				cust.CustName custName,
				con.CO_DOB 'conDob'
	FROM 
		crm_contact con 
	LEFT OUTER JOIN 
		tbluser cu 
			ON cu.UID = con.CO_ATo
  LEFT OUTER JOIN 
		crm_lead_source les 
			ON les.LS_ID = con.CO_LeadSource
  LEFT OUTER JOIN 
		crm_contact pcon 
			ON pcon.CO_ID = con.CO_ReportTo
  LEFT OUTER JOIN 
		tblcustomer cust 
			ON cust.CustID = con.CO_CustID
	WHERE con.CO_ID = conID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `findCrmEventById`;
DELIMITER |
CREATE PROCEDURE `findCrmEventById`(IN `evId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT 
		ev.EV_ID evId,
		ev.EV_Name evName,
		DATE_FORMAT(ev.EV_StartDate,'%d/%m/%Y %h:%i %p') evStartDate,
		DATE_FORMAT(ev.EV_EndDate,'%d/%m/%Y %h:%i %p') evEndDate,
		ev.EV_Duration evDuration,
		ev.EV_Budget evBudget,
		ev.EV_Description evDes,
		ev.EV_CBy evCreateBy,
		DATE_FORMAT(ev.EV_CDate,'%d/%m/%Y %h:%i %p') evCreateDate,
		ev.EV_MBy evModifiedBy,
		ev.EV_MDate AS evModifiedDate,
		ev.EV_RToID AS evRelatedToModuleId,
		ev.EV_RToType AS evRelatedToModuleType,
		findModuleDetailsByModuleNameAndItsId(ev.EV_RToType,ev.EV_RToID) AS evRelatedName,
		lo.LO_ID loId,
		lo.LO_Name loName,
		us.UID userID,
		us.UName username
	
	FROM 
		crm_event ev 
	LEFT OUTER JOIN 
		crm_location lo 
			ON ev.EV_LocationID = lo.LO_ID
	LEFT OUTER JOIN
		tbluser us 
			ON ev.EV_AssignTo = us.UID
	WHERE ev.EV_ID = evId;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `findCrmLeadById`;
DELIMITER |
CREATE PROCEDURE `findCrmLeadById`(IN `leadID` varchar(11))
    DETERMINISTIC
BEGIN
select
lead.LA_ID as leadID,
lead.LA_Email as email,
lead.LA_AccountName as accountName,
lead.LA_City as city,
lead.LA_Commune as commune,
lead.LA_Country as country,
lead.LA_CBy as createBy,
CAST(lead.LA_CDate AS date) as createDate,
lead.LA_Department as department,
lead.LA_Des as description,
lead.LA_District as district,
lead.LA_FirstName as firstName,
lead.LA_LastName as lastName,
lead.LA_Mobile as mobile,
lead.LA_MBy as modifyBy,
CAST(lead.LA_MDate AS date) as modifyDate,
lead.LA_No as no,
lead.LA_Phone as phone,
lead.LA_Salutation as salutation,
lead.LA_State as state,
lead.LA_Street as street,
lead.LA_Title as title,
lead.LA_Village as village,
lead.LA_Website as website,
camp.CA_ID as campID,
camp.CA_Name as campName,
assignto.UID as assignToUserID,
assignto.UName as assignToUsername,
indust.I_ID as industID,
indust.I_Name as industName,
source.LS_ID as sourceID,
source.LS_Name as sourceName,
status.LST_ID as statusID,
status.LST_Name as statusName
from
crm_lead lead
left outer join
crm_camp camp
on lead.LA_CA_ID=camp.CA_ID
left outer join
tbluser assignto
on lead.LA_ATo = assignto.UID
left outer join
crm_industry indust
on lead.LA_IndustID=indust.I_ID
left outer join
crm_lead_source source
on lead.LA_SourceID=source.LS_ID
left outer join
crm_lead_status status
on lead.LA_StatusID=status.LST_ID
where lead.LA_ID = leadID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `findCrmMeetingById`;
DELIMITER |
CREATE PROCEDURE `findCrmMeetingById`(IN `meetingId` varchar(11))
    DETERMINISTIC
BEGIN
	DECLARE moduleName VARCHAR(255) DEFAULT "";
	select M_RToType into moduleName from crm_meeting where M_ID = meetingId;
	if moduleName = 'Customer' then
		SELECT
			M.M_ID meetingId,
			M.M_Subject meetingSubject, 
			DATE_FORMAT(M.M_StartDate,'%d/%m/%Y %h:%i %p') meetingStartDate,
			DATE_FORMAT(M.M_EndDate,'%d/%m/%Y %h:%i %p') meetingEndDate,
			M.M_Duration meetingDuration, 
			MS.MS_ID statusId, MS.MS_Name statusName,
			M.M_RToType meetingRelatedToModuleType,
	    M.M_RToID meetingRelatedToModuleId,
			cu.CustName mettingRelatedName,
			M.M_Location meetingLocation,
			M.M_Des meetingDes,
			U.UID userID, 
			U.UName username,
			M.M_CBy meetingCreateBy, 
	   	DATE_FORMAT(M.M_CDate,'%d/%m/%Y %h:%i %p') meetingCreateDate, 
			M.M_MBy meetingModifiedBy, 
			DATE_FORMAT(M.M_MDate ,'%d/%m/%Y %h:%i %p') meetingModifiedDate,
			M.M_CheckIn_Latitude meetingLatitude,
			M.M_CheckIn_Longitude meetingLongitude,
			DATE_FORMAT(M.M_CheckinDate, '%d/%m/%Y %h:%i %p') meetingCheckinDate,
			(SELECT UName FROM tbluser WHERE UID = M.M_CheckinBy) checkinBy,
			(SELECT ImagePath FROM tblconfiguration LIMIT 1) imagePath,
			M.M_CheckInDes meetingCheckinDes,
			M.M_CheckOut_Longitude meetingCheckOutLongitude,
			M.M_CheckOut_Latitude meetingCheckOutLatitude,
			M.M_CheckOutDate meetingCheckOutDate,
			M.M_CheckOutBy meetingCheckOutBy,
			M.M_CheckOutDuration meetingCheckOutDuration,
			M.M_CheckOutDes meetingCheckOutDes
	  FROM 
			crm_meeting M
		LEFT OUTER JOIN 
			crm_meeting_status MS
				ON M.M_StatusID = MS.MS_ID
		LEFT OUTER JOIN 
			tbluser U
				ON M.M_ATo = U.UID
		left outer join 
			tblcustomer cu 
				on cu.CustID = M.M_RToID
		WHERE M.M_ID = meetingId;
	else	
		SELECT
			M.M_ID meetingId,
			M.M_Subject meetingSubject, 
			DATE_FORMAT(M.M_StartDate,'%d/%m/%Y %h:%i %p') meetingStartDate,
			DATE_FORMAT(M.M_EndDate,'%d/%m/%Y %h:%i %p') meetingEndDate,
			M.M_Duration meetingDuration, 
			MS.MS_ID statusId, MS.MS_Name statusName,
			M.M_RToType meetingRelatedToModuleType,
	    M.M_RToID meetingRelatedToModuleId,
			findModuleDetailsByModuleNameAndItsId(M.M_RToType, M.M_RToID) mettingRelatedName,
			M.M_Location meetingLocation,
			M.M_Des meetingDes,
			U.UID userID, 
			U.UName username,
			M.M_CBy meetingCreateBy, 
	    DATE_FORMAT(M.M_CDate,'%d/%m/%Y %h:%i %p') meetingCreateDate, 
			M.M_MBy meetingModifiedBy, 
			DATE_FORMAT(M.M_MDate ,'%d/%m/%Y %h:%i %p') meetingModifiedDate,
			M.M_CheckIn_Latitude meetingLatitude,
			M.M_CheckIn_Longitude meetingLongitude,
			DATE_FORMAT(M.M_CheckinDate, '%d/%m/%Y %h:%i %p') meetingCheckinDate,
			(SELECT UName FROM tbluser WHERE UID = M.M_CheckinBy) checkinBy,
			(SELECT ImagePath FROM tblconfiguration LIMIT 1) imagePath,
			M.M_CheckInDes meetingCheckinDes,
			M.M_CheckOut_Longitude meetingCheckOutLongitude,
			M.M_CheckOut_Latitude meetingCheckOutLatitude,
			M.M_CheckOutDate meetingCheckOutDate,
			M.M_CheckOutBy meetingCheckOutBy,
			M.M_CheckOutDuration meetingCheckOutDuration,
			M.M_CheckOutDes meetingCheckOutDes
	  FROM 
			crm_meeting M
		LEFT OUTER JOIN 
			crm_meeting_status MS
				ON M.M_StatusID = MS.MS_ID
		LEFT OUTER JOIN 
			tbluser U
				ON M.M_ATo = U.UID 
		WHERE M.M_ID = meetingId;
	end if;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `findCrmOpportunityById`;
DELIMITER |
CREATE PROCEDURE `findCrmOpportunityById`(IN `opId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT
        op.OP_ID as opId,
        op.OP_Amt as opAmount,
        CAST(op.OP_CloseDate AS date) as opCloseDate,
        op.OP_CBy as opCreateBy,
        CAST(op.OP_CDate AS date) as opCreateDate,
        op.OP_Des as opDes,
        op.OP_MBy as opModifyBy,
        CAST(op.OP_MDate AS date) as opModifyDate,
        op.OP_Name as opName,
        op.OP_NextStep as opNextStep,
        op.OP_Probability as opProbability,
				op.OP_PriceCode as priceCode,
				op.OP_TotalSTax as totalSTax,
				op.OP_TotalVTax as totalVTax,
				op.OP_TotalAmt as totalAmt,
				op.OP_DisInvDol as disInvDol,
				op.OP_DisInvPer as disInvPer,
				op.OP_TotalDis as totalDis,
				(SELECT Description FROM tblpricecode WHERE PriceCode = op.OP_PriceCode) as priceCodeName,
				op.OP_Class as classId,
				(SELECT Des FROM tblclass WHERE ClassID = op.OP_Class) AS className,
        cust.CustID as custID,
        cust.CustName as custName,
        user.UID as userID,
        user.UName as username,
        camp.CA_ID as campID,
        camp.CA_Name as campName,
        leadsource.LS_ID as sourceID,
        leadsource.LS_Name as sourceName,
        ops.OS_ID as osId,
        ops.OS_Name as osName,
        opt.OT_ID as otId,
        opt.OT_Name as otName
				
    FROM
        crm_opportunity op 
    INNER JOIN
        tblcustomer cust 
            ON op.OP_CustID=cust.CustID 
    LEFT OUTER JOIN
        tbluser user 
            ON op.OP_ATo=user.UID 
    LEFT OUTER JOIN
        crm_camp camp 
            ON op.OP_CampID=camp.CA_ID 
    LEFT OUTER JOIN
        crm_lead_source leadsource 
            ON op.OP_LeadSourceID=leadsource.LS_ID 
    INNER JOIN
        crm_opportunity_stage ops 
            ON op.OP_StageID=ops.OS_ID 
    LEFT OUTER JOIN
        crm_opportunity_type opt 
            ON op.OP_TypeID=opt.OT_ID
    WHERE op.OP_ID = opId;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `findModuleDetailsByModuleNameAndItsId`;
DELIMITER |
CREATE PROCEDURE `findModuleDetailsByModuleNameAndItsId`(IN `moduleName` varchar(50),IN `contentId` varchar(50))
    DETERMINISTIC
BEGIN
	IF COALESCE(moduleName, "") <> "" THEN
		CASE UPPER(moduleName)
				WHEN "CAMPAIGN" THEN
					SELECT 
						CA_Name AS campName
					FROM 	
						crm_camp ca 
					WHERE CA_ID = contentId;
		
				WHEN "LEAD" THEN
					SELECT 
						LA_Salutation AS salutation,
						LA_FirstName AS firstName,
						LA_LastName AS	lastName
					FROM
						crm_lead
					WHERE LA_ID = contentId;

				WHEN "OPPORTUNITY" THEN	
					SELECT 
						OP_Name AS opName
					FROM
						crm_opportunity
					WHERE OP_ID = contenId;

				WHEN "CASE" THEN
					SELECT 
						CS_Subject AS Subject
					FROM 
						crm_case 
					WHERE CS_ID = contentId;

				WHEN "CONTACT" THEN
					SELECT 
						CO_Salutation AS conSalutation,
						CO_FirstName AS conFirstname,
						CO_LastName AS conLastName
					FROM
						crm_contact
					WHERE CO_ID = contentId;
				
				WHEN "EVENT" THEN
					SELECT 
						EV_Name AS evName
					FROM
						crm_event
					WHERE EV_ID = contenId;

				WHEN "METTING" THEN
					SELECT 
						M_Subject AS meetingSubject
					FROM 
						crm_meeting
					WHERE M_ID = contentId;

				WHEN "TASK" THEN
					SELECT 
						TA_Subject AS taskSubject
					FROM 
						crm_task
					WHERE TA_ID = contentId;
				ELSE
					SELECT `COALESCE`('','');
			END CASE;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `findQuoteById`;
DELIMITER |
CREATE PROCEDURE `findQuoteById`(IN `saleId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
			sr.SalID,COALESCE(sr.SalType,'') 'saleType',
			DATE_FORMAT(sr.SalDate, '%d-%b-%Y') as 'saleDate',
			DATE_FORMAT(sr.DueDate, '%d-%b-%Y') as 'dueDate',
			COALESCE(sr.Remark,'') 'remark',
			COALESCE(sr.PriceCode,'') 'priceCode',
			COALESCE(sr.SalReference,'') 'saleReference',  
			COALESCE(sr.CustID,'') 'custId',
			COALESCE(sr.EmpID,'') 'empId',
			COALESCE(sr.ClassID,'') 'classId',
			COALESCE(sr.TotalAmt,0) 'totalAmt',
			COALESCE(sr.DisInvDol,0) 'disInvDol',
			COALESCE(sr.DisInvPer,0) 'disInvPer',
			COALESCE( sr.PmtToDate ,0) 'pmtToDate', 
			COALESCE(sr.TotalDis ,0) 'totalDis' , 
			COALESCE( sr.NetTotalAmt ,0) 'netTotalAmt', 
			COALESCE(sr.PostStatus,'') 'postStatus',		
			COALESCE(sd.ItemID,'') 'itemId',
			COALESCE(sd.LocationID,'') 'locationId',
			COALESCE(sd.ClassID,'') 'ClassDetailID', 
			COALESCE(sd.UomID,'') 'uomId',
			COALESCE(sd.SalQty,0) 'saleQuantity',
			COALESCE(sd.UnitPrice,0) 'unitPrice', 
			COALESCE(sd.Factor,0) 'factor', 
			COALESCE(sd.ReportPrice,'') 'reportPrice', 
			COALESCE(sd.TotalAmt,'') 'totalAmt', 
			COALESCE(sd.DisPer,0) 'disPer', 
			COALESCE(sd.DisDol,0) 'disDol',
			COALESCE(sd.VTaxDol,0) 'vtaxDol', 
			COALESCE(sd.VTaxPer,0) 'vtaxPer', 
			COALESCE(sd.STaxDol,0) 'staxDol', 
			COALESCE(sd.STaxPer,0) 'staxPer', 
			COALESCE(sd.NetTotalAmt,0) 'netTotalAmt',
			COALESCE(sr.ShipTo,'') 'shipTo'	
		FROM tblsaleorder sr 
		LEFT JOIN tblsaleorderdetails sd on sd.SalID = sr.SalID
		Where sr.SalID = saleId
		ORDER BY sd.LineNo;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `findRoleDetailsByUsername`;
DELIMITER |
CREATE PROCEDURE `findRoleDetailsByUsername`(IN `username` varchar(255), IN `moduleId` varchar(11))
    DETERMINISTIC
BEGIN
	
	SELECT 
		us.UID AS userId,
		us.UName AS username,
		role.RM_ID AS roleId,
		role.RM_Name AS role,
		detail.RM_DetailID AS roleDetailId,
		detail.RM_Delete AS roleDelete,
		detail.RM_Edit AS roleEdit,
		detail.RM_Export AS roleExport,
		detail.RM_Import AS roleImport,
		detail.RM_Access AS roleAccess,
		detail.RM_List AS roleList,
		detail.RM_View AS roleView,
		prefix.ModuleID AS moduleId,
		prefix.Remarks AS moduleName
	FROM 
		tbluser us 
	INNER JOIN 
		crm_role role
			ON us.URoleID = role.RM_ID
	INNER JOIN 
		crm_role_detail detail
			ON role.RM_ID = detail.RM_RoleID
	INNER JOIN 
		crm_numberprefix prefix
			ON detail.RM_ModuleID = prefix.ModuleID
	WHERE us.UName = username AND prefix.ModuleID = moduleId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `hrm_message`;
DELIMITER |
CREATE PROCEDURE `hrm_message`(IN SCode varchar(255),IN SModule varchar(255),IN SAction varchar(255),IN SID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT CONCAT(Msg1,' ',SID, ' ', Msg2) AS 'alert' FROM hrm_message WHERE Code = SCode AND Module = SModule AND Action = SAction;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `hrm_message_param3`;
DELIMITER |
CREATE PROCEDURE `hrm_message_param3`(IN SCode varchar(255),IN SModule varchar(255),IN SAction varchar(255),IN Param1 varchar(255),IN Param2 varchar(255),IN Param3 varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE alert Text;
	SELECT CONCAT(Msg1,' ', Msg2) INTO alert FROM hrm_message WHERE Code = SCode AND Module = SModule AND Action = SAction;
	set alert = REPLACE(alert, 'Param1' ,Param1);
	set alert = REPLACE(alert, 'Param2' ,Param2);
	set alert = REPLACE(alert, 'Param3' ,Param3);
	SELECT alert;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listAllActivitiesRelatedToLead`;
DELIMITER |
CREATE PROCEDURE `listAllActivitiesRelatedToLead`(IN `leadId` varchar(50))
    DETERMINISTIC
BEGIN
(SELECT
ev.EV_ID id,
ev.EV_Name name,
CAST(ev.EV_StartDate AS DATE) startDate,
CAST(ev.EV_EndDate AS DATE) endDate,
null AS taskDueDate,
ev.EV_Duration duration,
ev.EV_Budget budget,
null taskPriority,
null AS statusId,
null AS statusName,
ev.EV_Description des,
null AS contactId,
null AS contactFirstname,
null AS contactLastname,
ev.EV_CBy createBy,
DATE_FORMAT(ev.EV_CDate,'%d-%m-%Y') AS createDate,
DATE_FORMAT(ev.EV_CDate,'%h:%i %p') AS time,
ev.EV_MBy modifiedBy,
CAST(ev.EV_MDate AS DATE) modifiedDate,
lo.LO_ID locateId,
lo.LO_Name locateName,
us.UID userID,
us.UName username,
'events' AS activity
FROM
crm_event ev
LEFT OUTER JOIN
crm_location lo
ON ev.EV_LocationID = lo.LO_ID
LEFT OUTER JOIN
tbluser us
ON ev.EV_AssignTo = us.UID
INNER JOIN
crm_lead la
ON la.LA_ID = ev.EV_RToID
WHERE la.LA_ID = leadId)
UNION ALL
(SELECT
M.M_ID meetingId,
M.M_Subject meetingSubject,
CAST(M.M_StartDate AS DATE) meetingStartDate,
CAST(M.M_EndDate AS DATE) meetingEndDate,
null AS taskDueDate,
M.M_Duration meetingDuration,
null AS evBudget,
null taskPriority,
MS.MS_ID statusId,
MS.MS_Name statusName,
M.M_Des meetingDes,
null AS contactId,
null AS contactFirstname,
null AS contactLastname,
M.M_CBy meetingCreateBy,
DATE_FORMAT(M.M_CDate,'%d-%m-%Y') AS meetingCreateDate,
DATE_FORMAT(M.M_CDate,'%h:%i %p') AS time,
M.M_MBy meetingModifiedBy,
CAST(M.M_MDate AS date) meetingModifiedDate,
null AS locateId,
M.M_Location meetingLocation,
U.UID userID,
U.UName username,
'meetings'
FROM
crm_meeting M
LEFT OUTER JOIN
crm_meeting_status MS
ON M.M_StatusID = MS.MS_ID
LEFT OUTER JOIN
tbluser U
ON M.M_ATo = U.UID
INNER JOIN
crm_lead la
ON la.LA_ID = M_RToID
WHERE la.LA_ID = leadId)
UNION ALL
(SELECT
cl.CL_ID AS callId,
cl.CL_Subject AS callSubject,
CAST(cl.CL_SDate AS DATE) AS callStartDate,
null AS meetingEndDate,
null AS taskDueDate,
cl.CL_Duration AS callDuration,
null AS evBudget,
null taskPriority,
cls.CLS_ID AS callStatusId,
cls.CLS_Name AS callStatusName,
cl.CL_Des AS callDes,
null AS contactId,
null AS contactFirstname,
null AS contactLastname,
cl.CL_CBy AS callCreateBy,
DATE_FORMAT(cl.CL_CDate,'%d-%m-%Y') AS callCreateDate,
DATE_FORMAT(cl.CL_CDate,'%h:%i %p') AS time,
cl.CL_MBy AS callModifiedBy,
CAST(cl.CL_MDate AS DATE) AS callModifiedDate,
null AS locateId,
null AS meetingLocation,
us.UID AS userID,
us.UName AS username,
'calls'
FROM
crm_call cl
INNER JOIN
crm_call_status cls
ON cl.CL_StatusID = cls.CLS_ID
LEFT OUTER JOIN
tbluser us
ON cl.CL_ATo = us.UID
INNER JOIN
crm_lead la
ON la.LA_ID = cl.CL_RToID
WHERE la.LA_ID = leadId)
UNION ALL
(SELECT
task.TA_ID taskId,
task.TA_Subject taskSubject,
CAST(task.TA_StartDate AS DATE) taskStartDate,
null AS meetingEndDate,
CAST(task.TA_DueDate AS DATE) taskDueDate,
null AS callDuration,
null AS evBudget,
task.TA_Priority taskPriority,
tst.TS_ID taskStatusId,
tst.TS_Name taskStatusName,
task.TA_Des taskDes,
con.CO_ID conID,
con.CO_FirstName conFirstname,
con.CO_LastName conLastname,
task.TA_CBy taskCreateBy,
DATE_FORMAT(task.TA_CDate,'%d-%m-%Y') AS taskCreateDate,
DATE_FORMAT(task.TA_CDate,'%h:%i %p') AS time,
task.TA_MBy taskModifiedBy,
CAST(task.TA_MDate AS DATE) taskModifiedDate,
null AS locateId,
null AS meetingLocation,
assignTo.UID userID,
assignTo.UName username,
'tasks'
FROM
crm_task task
INNER JOIN
crm_task_status tst
ON task.TA_StatusID = tst.TS_ID
LEFT OUTER JOIN
crm_contact con
ON task.TA_ContactID = con.CO_ID
LEFT OUTER JOIN
tbluser assignTo
ON task.TA_ATo = assignTo.UID
INNER JOIN
crm_lead la
ON la.LA_ID = TA_RToID
WHERE la.LA_ID = leadId)
UNION ALL
(SELECT
note.N_ID AS noteId,
note.N_Subject AS noteSubject,
null AS taskStartDate,
null AS meetingEndDate,
null AS taskDueDate,
null AS callDuration,
null AS evBudget,
null AS taskPriority,
null AS taskStatusId,
null AS taskStatusName,
note.N_Des AS noteDes,
null AS conID,
null AS conFirstname,
null AS conLastname,
note.N_CBy AS noteCreateBy,
DATE_FORMAT(note.N_CDate,'%d-%m-%Y') AS noteCreateDate,
DATE_FORMAT(note.N_CDate,'%h:%i %p') AS noteTime,
note.N_MBy AS noteModifiedBy,
CAST(note.N_MDate AS DATE) AS noteModifiedDate,
null AS locateId,
null AS meetingLocation,
null AS userID,
null AS username,
'notes'
FROM
crm_note note
INNER JOIN
crm_lead lead
ON lead.LA_ID = note.N_RToID
WHERE lead.LA_ID = leadId)
ORDER BY createDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listAllCollaborationRelatedToModule`;
DELIMITER |
CREATE PROCEDURE `listAllCollaborationRelatedToModule`(IN `username` varchar(50),IN `moduleType` varchar(50),IN `moduleId` varchar(50))
    DETERMINISTIC
BEGIN
CASE UPPER(moduleType)
WHEN "LEAD" THEN
SELECT
col.CB_ID AS postId,
col.CB_Des AS postDes,
col.CB_UName AS username,
DATE_FORMAT(col.CB_CreateDate,'%d/%m/%Y %h:%i %p') AS postCreateDate,
col.CB_Own AS postOwner,
del.CBS_ID AS commentId,
del.CBS_Des AS commentDes,
del.CBS_UName AS commentBy,
DATE_FORMAT(del.CBS_CreateDate,'%d/%m/%Y %h:%i %p') AS commentCreateDate,
(SELECT COUNT(LK_ID) FROM crm_user_like_collaboration WHERE LK_CBID = col.CB_ID) AS `like`,
(SELECT COUNT(LK_ID) FROM crm_user_like_collaboration WHERE LK_UserName = username) AS likeOwner
FROM
crm_collaboration col
INNER JOIN
crm_lead la
ON col.CB_RToID = la.LA_ID
LEFT OUTER JOIN
crm_collaboration_details del
ON col.CB_ID = del.CBS_CBID
WHERE la.LA_ID = moduleId;
WHEN "OPPORTUNITY" THEN
SELECT
col.CB_ID AS postId,
col.CB_Des AS postDes,
col.CB_UName AS username,
DATE_FORMAT(col.CB_CreateDate,'%d/%m/%Y %h:%i %p') AS postCreateDate,
col.CB_Own AS postOwner,
del.CBS_ID AS commentId,
del.CBS_Des AS commentDes,
del.CBS_UName AS commentBy,
DATE_FORMAT(del.CBS_CreateDate,'%d/%m/%Y %h:%i %p') AS commentCreateDate,
(SELECT COUNT(LK_ID) FROM crm_user_like_collaboration WHERE LK_CBID = col.CB_ID) AS `like`,
(SELECT COUNT(LK_ID) FROM crm_user_like_collaboration WHERE LK_UserName = username) AS likeOwner
FROM
crm_collaboration col
INNER JOIN
crm_opportunity op
ON col.CB_RToID = op.OP_ID
LEFT OUTER JOIN
crm_collaboration_details del
ON col.CB_ID = del.CBS_CBID
WHERE op.OP_ID = moduleId;
END CASE;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listCallsRelatedToLead`;
DELIMITER |
CREATE PROCEDURE `listCallsRelatedToLead`(IN `leadId` varchar(11))
    DETERMINISTIC
BEGIN
SELECT
cl.CL_ID AS callId,
cl.CL_Subject AS callSubject,
DATE_FORMAT(cl.CL_SDate,'%d/%m/%Y %h:%i %p') AS callStartDate,
cl.CL_Duration AS callDuration,
cl.CL_Des AS callDes,
cl.CL_CBy AS callCreateBy,
CAST(cl.CL_CDate AS DATE) AS callCreateDate,
cl.CL_MBy AS callModifiedBy,
CAST(cl.CL_MDate AS DATE) AS callModifiedDate,
cls.CLS_ID AS callStatusId,
cls.CLS_Name AS callStatusName,
us.UID AS userID,
us.UName AS username
FROM
crm_call cl
INNER JOIN
crm_call_status cls
ON cl.CL_StatusID = cls.CLS_ID
LEFT OUTER JOIN
tbluser us
ON cl.CL_ATo = us.UID
INNER JOIN
crm_lead la
ON la.LA_ID = cl.CL_RToID
WHERE la.LA_ID = leadId
ORDER BY cl.CL_CDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listCallsRelatedToModule`;
DELIMITER |
CREATE PROCEDURE `listCallsRelatedToModule`(IN `moduleId` varchar(11))
    DETERMINISTIC
BEGIN
SELECT
cl.CL_ID AS callId,
cl.CL_Subject AS callSubject,
DATE_FORMAT(cl.CL_SDate,'%d/%m/%Y %h:%i %p') AS callStartDate,
cl.CL_Duration AS callDuration,
cl.CL_Des AS callDes,
cl.CL_CBy AS callCreateBy,
CAST(cl.CL_CDate AS DATE) AS callCreateDate,
cl.CL_MBy AS callModifiedBy,
CAST(cl.CL_MDate AS DATE) AS callModifiedDate,
cls.CLS_ID AS callStatusId,
cls.CLS_Name AS callStatusName,
us.UID AS userID,
us.UName AS username
FROM
crm_call cl
INNER JOIN
crm_call_status cls
ON cl.CL_StatusID = cls.CLS_ID
LEFT OUTER JOIN
tbluser us
ON cl.CL_ATo = us.UID
WHERE cl.CL_RToID = moduleId
ORDER BY cl.CL_CDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listCallsRelatedToOpportunity`;
DELIMITER |
CREATE PROCEDURE `listCallsRelatedToOpportunity`(IN `opId` varchar(11))
    DETERMINISTIC
BEGIN
SELECT
cl.CL_ID AS callId,
cl.CL_Subject AS callSubject,
DATE_FORMAT(cl.CL_SDate,'%d/%m/%Y %h:%i %p') AS callStartDate,
cl.CL_Duration AS callDuration,
cl.CL_Des AS callDes,
cl.CL_CBy AS callCreateBy,
CAST(cl.CL_CDate AS DATE) AS callCreateDate,
cl.CL_MBy AS callModifiedBy,
CAST(cl.CL_MDate AS DATE) AS callModifiedDate,
cls.CLS_ID AS callStatusId,
cls.CLS_Name AS callStatusName,
us.UID AS userID,
us.UName AS username
FROM
crm_call cl
INNER JOIN
crm_call_status cls
ON cl.CL_StatusID = cls.CLS_ID
LEFT OUTER JOIN
tbluser us
ON cl.CL_ATo = us.UID
INNER JOIN
crm_opportunity op
ON op.OP_ID = cl.CL_RToID
WHERE op.OP_ID = opId
ORDER BY cl.CL_CDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listContactsRelatedToOpportunity`;
DELIMITER |
CREATE PROCEDURE `listContactsRelatedToOpportunity`(IN `opId` varchar(11))
    DETERMINISTIC
BEGIN
SELECT
con.CO_ID conID,
CONCAT(CO_Salutation,' ',CO_FirstName,' ',CO_LastName) conName,
con.CO_Phone conPhone,
con.CO_Mobile conMobile,
con.CO_Email conEmail,
con.CO_Title conTitle,
con.CO_Department conDepartment,
opcon.OPCON_Role role,
opcon.OPCON_Type Type,
opcon.OPCON_ID id
FROM
crm_contact con
INNER JOIN
crm_opportunity_contact opcon
ON con.CO_ID = opcon.OPCON_CONID
WHERE
opcon.OPCON_OPID = opId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listCrmCalls`;
DELIMITER |
CREATE PROCEDURE `listCrmCalls`(IN `userId` varchar(50))
    DETERMINISTIC
BEGIN
DECLARE roleType INT DEFAULT 0;
SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT var_crm_role FROM ame_user WHERE var_id = userId);
IF roleType = 1 THEN
SELECT
cl.CL_ID AS callId,
cl.CL_Subject AS callSubject,
DATE_FORMAT(cl.CL_SDate,'%d/%m/%Y %h:%i %p') AS callStartDate,
cl.CL_Duration AS callDuration,
cl.CL_RToType AS callRelatedToModuleType,
cl.CL_RToID AS callRelatedToFieldId,
COALESCE(CRM_FUN_MODULE_BY_RELATED(cl.CL_RToType, cl.CL_RToID),'') relatedToName,
cl.CL_Des AS callDes,
cl.CL_CBy AS callCreateBy,
COALESCE((SELECT var_name FROM ame_user WHERE var_id = cl.CL_CBy),'') 'callCreateByName',
CAST(cl.CL_CDate AS DATE) AS callCreateDate,
cl.CL_MBy AS callModifiedBy,
CAST(cl.CL_MDate AS DATE) AS callModifiedDate,
cls.CLS_ID AS callStatusId,
cls.CLS_Name AS callStatusName,
COALESCE(us.var_id,'') AS userID,
COALESCE(us.var_name,'') AS username
FROM
crm_call cl
INNER JOIN
crm_call_status cls
ON cl.CL_StatusID = cls.CLS_ID
LEFT OUTER JOIN
ame_user us
ON cl.CL_ATo = us.var_id
ORDER BY cl.CL_ID DESC;
ELSE
SELECT
cl.CL_ID AS callId,
cl.CL_Subject AS callSubject,
DATE_FORMAT(cl.CL_SDate,'%d/%m/%Y %h:%i %p') AS callStartDate,
cl.CL_Duration AS callDuration,
cl.CL_RToType AS callRelatedToModuleType,
cl.CL_RToID AS callRelatedToFieldId,
COALESCE(CRM_FUN_MODULE_BY_RELATED(cl.CL_RToType, cl.CL_RToID),'') relatedToName,
cl.CL_Des AS callDes,
cl.CL_CBy AS callCreateBy,
COALESCE((SELECT var_name FROM ame_user WHERE var_id = cl.CL_CBy),'') 'callCreateByName',
CAST(cl.CL_CDate AS DATE) AS callCreateDate,
cl.CL_MBy AS callModifiedBy,
CAST(cl.CL_MDate AS DATE) AS callModifiedDate,
cls.CLS_ID AS callStatusId,
cls.CLS_Name AS callStatusName,
COALESCE(us.var_id,'') AS userID,
COALESCE(us.var_name,'') AS username
FROM
crm_call cl
INNER JOIN
crm_call_status cls
ON cl.CL_StatusID = cls.CLS_ID
LEFT OUTER JOIN
ame_user us
ON cl.CL_ATo = us.var_id
WHERE cl.CL_ATo = userId OR cl.CL_CBy = userId
ORDER BY cl.CL_ID DESC;
END IF;
END |
