										UPDATE ame_ar_ret_det T1 SET T1.dou_shipqty = P_QTY, T1.dou_shipfoc = P_FOC WHERE T1.var_id = P_DOC AND T1.int_poline = P_LIN AND T1.var_locid = P_LOC AND T1.var_itemid = P_ITE AND T1.var_uomid = P_UOM;
								END LOOP L;
						CLOSE C1;			
				END;
				BEGIN
						DECLARE D2 INTEGER DEFAULT 0;
						DECLARE P_QTY DOUBLE DEFAULT 0.0;
						DECLARE P_QTY_ORD DOUBLE DEFAULT 0.0;
						DECLARE P_STA_CLEAR_UN VARCHAR(100) DEFAULT "";
						DECLARE P_STA_CLEAR_PARTIAL VARCHAR(100) DEFAULT "";
						DECLARE P_STA_CLEAR_FULL VARCHAR(100) DEFAULT "";
						DECLARE C2 CURSOR FOR SELECT AME_FUN_ROUND(T1.dou_shipqty + T1.dou_shipfoc, P_DEC_QTY), AME_FUN_ROUND(T1.dou_qty + T1.dou_foc, P_DEC_QTY) FROM ame_ar_ret_det T1 WHERE T1.var_id = P2;
						DECLARE CONTINUE HANDLER FOR NOT FOUND SET D2 = 1;
						OPEN C2;
								IF FOUND_ROWS() > 0 THEN
										L2 : LOOP FETCH C2 INTO P_QTY_ORD, P_QTY;
												IF D2 = 1 THEN LEAVE L2; END IF;
												IF P_QTY_ORD = 0 AND P_QTY > 0 THEN
														SET P_STA_CLEAR_UN = "Not";
												ELSEIF P_QTY_ORD < P_QTY THEN
														SET P_STA_CLEAR_PARTIAL = 'Partial'; LEAVE L2;
												ELSEIF P_QTY_ORD >= P_QTY THEN
														SET P_STA_CLEAR_FULL = 'Full';
												END IF;
										END LOOP L2;	
										IF P_STA_CLEAR_PARTIAL <> "" OR (P_STA_CLEAR_FULL <> "" AND P_STA_CLEAR_UN <> "") THEN 
												UPDATE ame_ar_ret T1 SET T1.var_shipstatus = 'Open', T1.var_shippmtstatus = 'Partially Shipped' WHERE T1.var_id = P2; 
										ELSEIF P_STA_CLEAR_FULL <> "" AND P_STA_CLEAR_UN = "" THEN
												UPDATE ame_ar_ret T1 SET T1.var_shipstatus = 'Closed', T1.var_shippmtstatus = 'Fully Shipped' WHERE T1.var_id = P2; 
										ELSE
												UPDATE ame_ar_ret T1 SET T1.var_shipstatus = 'Open', T1.var_shippmtstatus = 'Unshipped' WHERE T1.var_id = P2;
										END IF;		
								ELSE
										UPDATE ame_ar_ret T1 SET T1.var_shipstatus = 'Open', T1.var_shippmtstatus = 'Unshipped' WHERE T1.var_id = P2;
								END IF;
						CLOSE C2;
				END;
		WHEN "AR-SM-CN" THEN
				# UPDATE RETURN
				UPDATE ame_ar_cn_det T1 SET T1.dou_shipqty = 0, T1.dou_shipfoc = 0 WHERE T1.var_id = P2;	
				BEGIN
						DECLARE D1 INTEGER DEFAULT 0;
						DECLARE P_LIN INTEGER DEFAULT 0;
						DECLARE P_DOC VARCHAR(100) DEFAULT "";
						DECLARE P_LOC VARCHAR(100) DEFAULT "";
						DECLARE P_ITE VARCHAR(100) DEFAULT "";
						DECLARE P_UOM VARCHAR(100) DEFAULT "";
						DECLARE P_QTY DOUBLE DEFAULT 0.0;
						DECLARE P_FOC DOUBLE DEFAULT 0.0;
						DEClARE C1 CURSOR FOR SELECT T1.var_poid, T1.int_poline, T1.var_locid, T1.var_itemid, T1.var_uomid, AME_FUN_ROUND(COALESCE(SUM(T1.dou_qty), 0), P_DEC_QTY), AME_FUN_ROUND(COALESCE(SUM(T1.dou_foc), 0), P_DEC_QTY) FROM ame_ar_sm_det T1 LEFT JOIN ame_ar_sm T2 ON T1.var_id = T2.var_id WHERE T1.var_poid = P2 AND T2.var_status = 'Open' AND T2.var_type = 'AR-CN' GROUP BY T1.var_locid, T1.var_itemid, T1.var_uomid, T1.int_poline;
						DECLARE CONTINUE HANDLER FOR NOT FOUND SET D1 = 1;
						OPEN C1;		
								L: LOOP FETCH C1 INTO P_DOC, P_LIN, P_LOC, P_ITE, P_UOM, P_QTY, P_FOC;
										IF D1 = 1 THEN LEAVE L; END IF;
										UPDATE ame_ar_cn_det T1 SET T1.dou_shipqty = P_QTY, T1.dou_shipfoc = P_FOC WHERE T1.var_id = P_DOC AND T1.int_poline = P_LIN AND T1.var_locid = P_LOC AND T1.var_itemid = P_ITE AND T1.var_uomid = P_UOM;
								END LOOP L;
						CLOSE C1;			
				END;
				BEGIN
						DECLARE D2 INTEGER DEFAULT 0;
						DECLARE P_QTY DOUBLE DEFAULT 0.0;
						DECLARE P_QTY_ORD DOUBLE DEFAULT 0.0;
						DECLARE P_STA_CLEAR_UN VARCHAR(100) DEFAULT "";
						DECLARE P_STA_CLEAR_PARTIAL VARCHAR(100) DEFAULT "";
						DECLARE P_STA_CLEAR_FULL VARCHAR(100) DEFAULT "";
						DECLARE C2 CURSOR FOR SELECT AME_FUN_ROUND(T1.dou_shipqty + T1.dou_shipfoc, P_DEC_QTY), AME_FUN_ROUND(T1.dou_qty + T1.dou_foc, P_DEC_QTY) FROM ame_ar_cn_det T1 WHERE T1.var_id = P2;
						DECLARE CONTINUE HANDLER FOR NOT FOUND SET D2 = 1;
						OPEN C2;
								IF FOUND_ROWS() > 0 THEN
										L2 : LOOP FETCH C2 INTO P_QTY_ORD, P_QTY;
												IF D2 = 1 THEN LEAVE L2; END IF;
												IF P_QTY_ORD = 0 AND P_QTY > 0 THEN
														SET P_STA_CLEAR_UN = "Not";
												ELSEIF P_QTY_ORD < P_QTY THEN
														SET P_STA_CLEAR_PARTIAL = 'Partial'; LEAVE L2;
												ELSEIF P_QTY_ORD >= P_QTY THEN
														SET P_STA_CLEAR_FULL = 'Full';
												END IF;
										END LOOP L2;	
										IF P_STA_CLEAR_PARTIAL <> "" OR (P_STA_CLEAR_FULL <> "" AND P_STA_CLEAR_UN <> "") THEN 
												UPDATE ame_ar_cn T1 SET T1.var_shipstatus = 'Open', T1.var_shippmtstatus = 'Partially Shipped' WHERE T1.var_id = P2; 
										ELSEIF P_STA_CLEAR_FULL <> "" AND P_STA_CLEAR_UN = "" THEN
												UPDATE ame_ar_cn T1 SET T1.var_shipstatus = 'Closed', T1.var_shippmtstatus = 'Fully Shipped' WHERE T1.var_id = P2; 
										ELSE
												UPDATE ame_ar_cn T1 SET T1.var_shipstatus = 'Open', T1.var_shippmtstatus = 'Unshipped' WHERE T1.var_id = P2;
										END IF;		
								ELSE
										UPDATE ame_ar_cn T1 SET T1.var_shipstatus = 'Open', T1.var_shippmtstatus = 'Unshipped' WHERE T1.var_id = P2;
								END IF;
						CLOSE C2;
				END;
		ELSE
				SET @Donothing = NULL;
		END CASE;
		
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `AME_PRO_UPDATE_SL_AP`;
DELIMITER |
CREATE PROCEDURE `AME_PRO_UPDATE_SL_AP`(P1 varchar(100), P2 varchar(100), P3 date, P4 double, P5 integer, P6 varchar(100), P7 double, P8 integer)
    DETERMINISTIC
BEGIN
		# NOTE : P1 = var_venid,	P2 = Dr or Cr, P3 = dat_date, P4 = dou_dr or dou_cr, P5 = Decimal
		DECLARE P_COUNT INTEGER DEFAULT 0;
		SELECT COUNT(var_venid) INTO P_COUNT FROM ame_sl_ap T WHERE T.dat_date = P3 AND T.var_venid = P1 AND T.var_cur = P6;
		IF P_COUNT > 0 THEN
				IF P2 = "Dr" Then
						UPDATE ame_sl_ap T SET T.dou_dr = AME_FUN_ROUND(COALESCE(T.dou_dr, 0) + P4, P5), T.dou_fundr = AME_FUN_ROUND(COALESCE(T.dou_fundr, 0) + P7, P8) WHERE T.dat_date = P3 AND T.var_venid = P1 AND T.var_cur = P6;
				ELSE
						UPDATE ame_sl_ap T SET T.dou_cr = AME_FUN_ROUND(COALESCE(T.dou_cr, 0) + P4, P5), T.dou_funcr = AME_FUN_ROUND(COALESCE(T.dou_funcr, 0) + P7, P8) WHERE T.dat_date = P3 AND T.var_venid = P1 AND T.var_cur = P6;
				END IF;
		ELSE
				IF P2 = "Dr" Then
						INSERT INTO ame_sl_ap(var_venid, var_cur, dat_date, dou_dr, dou_cr, dou_fundr, dou_funcr) VALUES(P1, P6, P3, AME_FUN_ROUND(P4, P5), 0, AME_FUN_ROUND(P7, P8), 0);
				ELSE
						INSERT INTO ame_sl_ap(var_venid, var_cur, dat_date, dou_dr, dou_cr, dou_fundr, dou_funcr) VALUES(P1, P6, P3, 0, AME_FUN_ROUND(P4, P5), 0, AME_FUN_ROUND(P7, P8));
				END IF;
		END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `AME_PRO_UPDATE_SL_AP_HIS`;
DELIMITER |
CREATE PROCEDURE `AME_PRO_UPDATE_SL_AP_HIS`(P1 varchar(100), P2 varchar(100), P3 varchar(100), P4 varchar(100), P5 varchar(100), P6 varchar(100), P7 varchar(100), P8 varchar(100), P9 varchar(250), P10 varchar(250), P11 varchar(2000), P12 datetime, P13 datetime, P14 double, P15 integer, P16 tinyint(1), P17 varchar(100), P18 integer, P19 integer, P20 varchar(100), P21 varchar(100), P22 double, P23 double)
    DETERMINISTIC
BEGIN
		DECLARE P_NUM INTEGER DEFAULT 0;
		DECLARE P_DR DOUBLE DEFAULT 0.0;
		DECLARE P_CR DOUBLE DEFAULT 0.0;
		DECLARE P_DR_FUN DOUBLE DEFAULT 0.0;
		DECLARE P_CR_FUN DOUBLE DEFAULT 0.0;
		IF P17 = "Dr" THEN SET P_DR = P14; SET P_DR_FUN = P23; ELSE SET P_CR = P14; SET P_CR_FUN = P23; END IF;
		IF P18 = -1 THEN SET P_NUM = AME_FUN_NEW_SL_AP_HIS_NUM(); ELSE SET P_NUM = P18; END IF;
		IF P16 = 1 THEN
				IF P17 = "Dr" THEN
						UPDATE ame_sl_ap_his SET dou_dr = AME_FUN_ROUND(P_DR, P15), dou_fundr = P_DR_FUN WHERE int_line = IF(P18 = -1, P_NUM - 1, P_NUM);
				ELSE
						UPDATE ame_sl_ap_his SET dou_cr = AME_FUN_ROUND(P_CR, P15), dou_funcr = P_CR_FUN WHERE int_line = IF(P18 = -1, P_NUM - 1, P_NUM);
				END IF;
		ELSE
				INSERT INTO ame_sl_ap_his(int_line, var_modid, var_doctype, var_docid, var_venid, var_claid, var_accid, var_apaccid, var_term, var_pmttype, var_pmtref, var_ref, var_desc, dat_date, dat_due, dou_dr, dou_cr, int_jid, var_cur, dou_rate, dou_fundr, dou_funcr)
				VALUES(P_NUM, P1, P2, P3, P4, P5, P6, P20, P7, P8, P9, P10, P11, P12, P13, P_DR, P_CR, P19, P21, P22, P_DR_FUN, P_CR_FUN);
		END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `AME_PRO_UPDATE_SL_AR`;
DELIMITER |
CREATE PROCEDURE `AME_PRO_UPDATE_SL_AR`(P1 varchar(100), P2 varchar(100), P3 date, P4 double, P5 integer, P6 varchar(100), P7 double, P8 integer)
    DETERMINISTIC
BEGIN
		# NOTE : P1 = var_cusid,	P2 = Dr or Cr, P3 = dat_date, P4 = dou_dr or dou_cr, P5 = Decimal
		DECLARE P_COUNT INTEGER DEFAULT 0;
		SELECT COUNT(var_cusid) INTO P_COUNT FROM ame_sl_ar T WHERE T.dat_date = P3 AND T.var_cusid = P1 AND T.var_cur = P6;
		IF P_COUNT > 0 THEN
				IF P2 = "Dr" Then
						UPDATE ame_sl_ar T SET T.dou_dr = AME_FUN_ROUND(COALESCE(T.dou_dr, 0) + P4, P5), T.dou_fundr = AME_FUN_ROUND(COALESCE(T.dou_fundr, 0) + P7, P8) WHERE T.dat_date = P3 AND T.var_cusid = P1 AND T.var_cur = P6;
				ELSE
						UPDATE ame_sl_ar T SET T.dou_cr = AME_FUN_ROUND(COALESCE(T.dou_cr, 0) + P4, P5), T.dou_funcr = AME_FUN_ROUND(COALESCE(T.dou_funcr, 0) + P7, P8) WHERE T.dat_date = P3 AND T.var_cusid = P1 AND T.var_cur = P6;
				END IF;
		ELSE
				IF P2 = "Dr" Then
						INSERT INTO ame_sl_ar(var_cusid, var_cur, dat_date, dou_dr, dou_cr, dou_fundr, dou_funcr) VALUES(P1, P6, P3, AME_FUN_ROUND(P4, P5), 0, ROUND(P7, P8), 0);
				ELSE
						INSERT INTO ame_sl_ar(var_cusid, var_cur, dat_date, dou_dr, dou_cr, dou_fundr, dou_funcr) VALUES(P1, P6, P3, 0, AME_FUN_ROUND(P4, P5), 0, ROUND(P7, P8));
				END IF;
		END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `AME_PRO_UPDATE_SL_AR_HIS`;
DELIMITER |
CREATE PROCEDURE `AME_PRO_UPDATE_SL_AR_HIS`(P1 varchar(100), P2 varchar(100), P3 varchar(100), P4 varchar(100), P5 varchar(100), P6 varchar(100), P7 varchar(100), P8 varchar(100), P9 varchar(100), P10 varchar(250), P11 varchar(250), P12 varchar(2000), P13 datetime, P14 datetime, P15 double, P16 int(11), P17 tinyint(1), P18 varchar(100), P19 int(11), P20 int(11), P21 varchar(100), P22 varchar(100), P23 double, P24 double)
    DETERMINISTIC
BEGIN
		DECLARE P_NUM INTEGER DEFAULT 0;
		DECLARE P_DR DOUBLE DEFAULT 0;
		DECLARE P_CR DOUBLE DEFAULT 0;
		DECLARE P_DR_FUN DOUBLE DEFAULT 0.0;
		DECLARE P_CR_FUN DOUBLE DEFAULT 0.0;
		IF P18 = "Dr" THEN SET P_DR = P15; SET P_DR_FUN = P24; ELSE SET P_CR = P15; SET P_CR_FUN = P24; END IF;
		IF P19 = -1 THEN SET P_NUM = AME_FUN_NEW_SL_AR_HIS_NUM(); ELSE SET P_NUM = P19; END IF;
		IF P17 = 1 THEN
				IF P18 = "Dr" THEN
						UPDATE ame_sl_ar_his SET dou_dr = ROUND(P_DR, P16), dou_fundr = P_DR_FUN WHERE int_line = IF(P19 = -1, P_NUM - 1, P_NUM);
				ELSE
						UPDATE ame_sl_ar_his SET dou_cr = ROUND(P_CR, P16), dou_funcr = P_CR_FUN WHERE int_line = IF(P19 = -1, P_NUM - 1, P_NUM);
				END IF;
		ELSE
				INSERT INTO ame_sl_ar_his(int_line, var_modid, var_doctype, var_docid, var_cusid, var_empid, var_claid, var_accid, var_araccid, var_term, var_pmttype, var_pmtref, var_ref, var_desc, dat_date, dat_due, dou_dr, dou_cr, int_jid, var_cur, dou_rate, dou_fundr, dou_funcr)
				VALUES(P_NUM, P1, P2, P3, P4, P5, P6, P7, P21, P8, P9, P10, P11, P12, P13, P14, P_DR, P_CR, P20, P22, P23, P_DR_FUN, P_CR_FUN);
		END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `AME_PRO_UPDATE_SL_IC`;
DELIMITER |
CREATE PROCEDURE `AME_PRO_UPDATE_SL_IC`(P1 varchar(100), P2 varchar(100), P3 integer, P4 date, P5 double, P6 double,  P7 double, P8 double, P9 double, P10 double, P11 double, P12 varchar(100), P13 integer, P14 integer)
    DETERMINISTIC
BEGIN
		DECLARE P_COUNT INTEGER DEFAULT 0;
		SELECT COUNT(T.var_itemid) INTO P_COUNT FROM ame_sl_ic T WHERE T.var_locid = P1 AND T.var_itemid = P2 AND T.int_batchno = P3 AND T.dat_date = P4;
		IF P_COUNT > 0 THEN
				IF P12 = "Dr" Then
						UPDATE ame_sl_ic T SET T.dou_drqty = AME_FUN_ROUND(COALESCE(T.dou_drqty, 0) + P5, P13),
						T.dou_druc = AME_FUN_ROUND(COALESCE(T.dou_druc, 0) + P6, P14),
						T.dou_drac1 = AME_FUN_ROUND(COALESCE(T.dou_drac1, 0) + P7, P14),
						T.dou_drac2 = AME_FUN_ROUND(COALESCE(T.dou_drac2, 0) + P8, P14),
						T.dou_drac3 = AME_FUN_ROUND(COALESCE(T.dou_drac3, 0) + P9, P14),
						T.dou_drac4 = AME_FUN_ROUND(COALESCE(T.dou_drac4, 0) + P10, P14),
						T.dou_drac5 = AME_FUN_ROUND(COALESCE(T.dou_drac5, 0) + P11, P14)
						WHERE T.var_locid = P1 AND T.var_itemid = P2 AND T.int_batchno = P3 AND T.dat_date = P4;
				ELSE
						UPDATE ame_sl_ic T SET T.dou_crqty = AME_FUN_ROUND(COALESCE(T.dou_crqty, 0) + P5, P13),
						T.dou_cruc = AME_FUN_ROUND(COALESCE(T.dou_cruc, 0) + P6, P14),
						T.dou_crac1 = AME_FUN_ROUND(COALESCE(T.dou_crac1, 0) + P7, P14),
						T.dou_crac2 = AME_FUN_ROUND(COALESCE(T.dou_crac2, 0) + P8, P14),
						T.dou_crac3 = AME_FUN_ROUND(COALESCE(T.dou_crac3, 0) + P9, P14),
						T.dou_crac4 = AME_FUN_ROUND(COALESCE(T.dou_crac4, 0) + P10, P14),
						T.dou_crac5 = AME_FUN_ROUND(COALESCE(T.dou_crac5, 0) + P11, P14)
						WHERE T.var_locid = P1 AND T.var_itemid = P2 AND T.int_batchno = P3 AND T.dat_date = P4;
				END IF;
		ELSE
				IF P12 = "Dr" THEN
						INSERT INTO ame_sl_ic(var_locid, var_itemid, int_batchno, dat_date, dou_drqty, dou_druc, dou_drac1, dou_drac2, dou_drac3, dou_drac4, dou_drac5) VALUES
						(P1, P2, P3, P4, AME_FUN_ROUND(P5, P13), AME_FUN_ROUND(P6, P14), AME_FUN_ROUND(P7, P14), AME_FUN_ROUND(P8, P14), AME_FUN_ROUND(P9, P14), AME_FUN_ROUND(P10, P14), AME_FUN_ROUND(P11, P14));
				ELSE
						INSERT INTO ame_sl_ic(var_locid, var_itemid, int_batchno, dat_date, dou_crqty, dou_cruc, dou_crac1, dou_crac2, dou_crac3, dou_crac4, dou_crac5) VALUES
						(P1, P2, P3, P4, AME_FUN_ROUND(P5, P13), AME_FUN_ROUND(P6, P14), AME_FUN_ROUND(P7, P14), AME_FUN_ROUND(P8, P14), AME_FUN_ROUND(P9, P14), AME_FUN_ROUND(P10, P14), AME_FUN_ROUND(P11, P14));
				END IF;
		END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `AME_PRO_UPDATE_SL_IC_BAT`;
DELIMITER |
CREATE PROCEDURE `AME_PRO_UPDATE_SL_IC_BAT`(P1 varchar(100), P2 varchar(100), P3 integer, P4 double, P5 double,  P6 double, P7 double, P8 double, P9 double, P10 double, P12 varchar(100), P13 integer, P14 integer)
    DETERMINISTIC
BEGIN
		DECLARE P_COUNT INTEGER DEFAULT 0;
		SELECT COUNT(T.var_itemid) INTO P_COUNT FROM ame_sl_ic_batch T WHERE T.var_locid = P1 AND T.var_itemid = P2 AND T.int_batchno = P3;
		IF P_COUNT > 0 THEN
				IF P12 = "Dr" Then
						UPDATE ame_sl_ic_batch T SET T.dou_drqty = AME_FUN_ROUND(COALESCE(T.dou_drqty, 0) + P4, P13),
						T.dou_druc = AME_FUN_ROUND(COALESCE(T.dou_druc, 0) + P5, P14),
						T.dou_drac1 = AME_FUN_ROUND(COALESCE(T.dou_drac1, 0) + P6, P14),
						T.dou_drac2 = AME_FUN_ROUND(COALESCE(T.dou_drac2, 0) + P7, P14),
						T.dou_drac3 = AME_FUN_ROUND(COALESCE(T.dou_drac3, 0) + P8, P14),
						T.dou_drac4 = AME_FUN_ROUND(COALESCE(T.dou_drac4, 0) + P9, P14),
						T.dou_drac5 = AME_FUN_ROUND(COALESCE(T.dou_drac5, 0) + P10, P14),
						T.dou_qty = AME_FUN_ROUND(COALESCE(T.dou_qty, 0) + P4, P13)
						WHERE T.var_locid = P1 AND T.var_itemid = P2 AND T.int_batchno = P3;
				ELSE
						UPDATE ame_sl_ic_batch T SET T.dou_crqty = AME_FUN_ROUND(COALESCE(T.dou_crqty, 0) + P4, P13),
						T.dou_cruc = AME_FUN_ROUND(COALESCE(T.dou_cruc, 0) + P5, P14),
						T.dou_crac1 = AME_FUN_ROUND(COALESCE(T.dou_crac1, 0) + P6, P14),
						T.dou_crac2 = AME_FUN_ROUND(COALESCE(T.dou_crac2, 0) + P7, P14),
						T.dou_crac3 = AME_FUN_ROUND(COALESCE(T.dou_crac3, 0) + P8, P14),
						T.dou_crac4 = AME_FUN_ROUND(COALESCE(T.dou_crac4, 0) + P9, P14),
						T.dou_crac5 = AME_FUN_ROUND(COALESCE(T.dou_crac5, 0) + P10, P14),
						T.dou_qty = AME_FUN_ROUND(COALESCE(T.dou_qty, 0) - P4, P13)
						WHERE T.var_locid = P1 AND T.var_itemid = P2 AND T.int_batchno = P3;
				END IF;
		ELSE
				IF P12 = "Dr" THEN
						INSERT INTO ame_sl_ic_batch(var_locid, var_itemid, int_batchno, dou_drqty, dou_druc, dou_drac1, dou_drac2, dou_drac3, dou_drac4, dou_drac5, dou_qty) VALUES
						(P1, P2, P3, AME_FUN_ROUND(P4 ,P13), AME_FUN_ROUND(P5, P14), AME_FUN_ROUND(P6, P14), AME_FUN_ROUND(P7, P14), AME_FUN_ROUND(P8, P14), AME_FUN_ROUND(P9, P14), AME_FUN_ROUND(P10, P14), AME_FUN_ROUND(P4, P13));
				ELSE
						INSERT INTO ame_sl_ic_batch(var_locid, var_itemid, int_batchno, dou_crqty, dou_cruc, dou_crac1, dou_crac2, dou_crac3, dou_crac4, dou_crac5, dou_qty) VALUES
						(P1, P2, P3, AME_FUN_ROUND(P4 ,P13), AME_FUN_ROUND(P5, P14), AME_FUN_ROUND(P6, P14), AME_FUN_ROUND(P7, P14), AME_FUN_ROUND(P8, P14), AME_FUN_ROUND(P9, P14), AME_FUN_ROUND(P10, P14), AME_FUN_ROUND(P4, P13));
				END IF;
		END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `AME_PRO_UPDATE_SL_IC_BATCH`;
DELIMITER |
CREATE PROCEDURE `AME_PRO_UPDATE_SL_IC_BATCH`(P1 varchar(100), P2 varchar(100), P3 varchar(100), P4 integer, P5 double,  P6 double, P7 double, P8 double, P9 double, P10 double, P11 double, P13 integer, P14 integer, P15 integer, P16 varchar(100), P17 double, P18 double, P19 double, P20 double, P21 double, P22 double)
    DETERMINISTIC
BEGIN
DECLARE P_COUNT INTEGER DEFAULT 0;
SELECT COUNT(T.var_itemid) INTO P_COUNT FROM ame_sl_ic_batch T WHERE T.var_locid = P1 AND T.var_itemid = P2 AND T.var_cur = P16 AND T.int_batchno = P4;
IF P_COUNT > 0 THEN
IF P3 = "Dr" Then
UPDATE ame_sl_ic_batch T SET T.dou_drqty = AME_FUN_ROUND(COALESCE(T.dou_drqty, 0) + P5, P13),
T.dou_druc = AME_FUN_ROUND(COALESCE(T.dou_druc, 0) + P6, P14),
T.dou_drac1 = AME_FUN_ROUND(COALESCE(T.dou_drac1, 0) + P7, P14),
T.dou_drac2 = AME_FUN_ROUND(COALESCE(T.dou_drac2, 0) + P8, P14),
T.dou_drac3 = AME_FUN_ROUND(COALESCE(T.dou_drac3, 0) + P9, P14),
T.dou_drac4 = AME_FUN_ROUND(COALESCE(T.dou_drac4, 0) + P10, P14),
T.dou_drac5 = AME_FUN_ROUND(COALESCE(T.dou_drac5, 0) + P11, P14),
T.dou_qty = AME_FUN_ROUND(COALESCE(T.dou_qty, 0) + P5, P13),
T.dou_fundruc = AME_FUN_ROUND(COALESCE(T.dou_fundruc, 0) + P17, P15),
T.dou_fundrac1 = AME_FUN_ROUND(COALESCE(T.dou_fundrac1, 0) + P18, P15),
T.dou_fundrac2 = AME_FUN_ROUND(COALESCE(T.dou_fundrac2, 0) + P19, P15),
T.dou_fundrac3 = AME_FUN_ROUND(COALESCE(T.dou_fundrac3, 0) + P20, P15),
T.dou_fundrac4 = AME_FUN_ROUND(COALESCE(T.dou_fundrac4, 0) + P21, P15),
T.dou_fundrac5 = AME_FUN_ROUND(COALESCE(T.dou_fundrac5, 0) + P22, P15)
WHERE T.var_locid = P1 AND T.var_itemid = P2 AND T.var_cur = P16 AND T.int_batchno = P4;
ELSE
UPDATE ame_sl_ic_batch T SET T.dou_crqty = AME_FUN_ROUND(COALESCE(T.dou_crqty, 0) + P5, P13),
T.dou_cruc = AME_FUN_ROUND(COALESCE(T.dou_cruc, 0) + P6, P14),
T.dou_crac1 = AME_FUN_ROUND(COALESCE(T.dou_crac1, 0) + P7, P14),
T.dou_crac2 = AME_FUN_ROUND(COALESCE(T.dou_crac2, 0) + P8, P14),
T.dou_crac3 = AME_FUN_ROUND(COALESCE(T.dou_crac3, 0) + P9, P14),
T.dou_crac4 = AME_FUN_ROUND(COALESCE(T.dou_crac4, 0) + P10, P14),
T.dou_crac5 = AME_FUN_ROUND(COALESCE(T.dou_crac5, 0) + P11, P14),
T.dou_qty = AME_FUN_ROUND(COALESCE(T.dou_qty, 0) - P5, P13),
T.dou_funcruc = AME_FUN_ROUND(COALESCE(T.dou_funcruc, 0) + P17, P15),
T.dou_funcrac1 = AME_FUN_ROUND(COALESCE(T.dou_funcrac1, 0) + P18, P15),
T.dou_funcrac2 = AME_FUN_ROUND(COALESCE(T.dou_funcrac2, 0) + P19, P15),
T.dou_funcrac3 = AME_FUN_ROUND(COALESCE(T.dou_funcrac3, 0) + P20, P15),
T.dou_funcrac4 = AME_FUN_ROUND(COALESCE(T.dou_funcrac4, 0) + P21, P15),
T.dou_funcrac5 = AME_FUN_ROUND(COALESCE(T.dou_funcrac5, 0) + P22, P15)
WHERE T.var_locid = P1 AND T.var_itemid = P2 AND T.var_cur = P16 AND T.int_batchno = P4;
END IF;
ELSE
IF P3 = "Dr" Then
INSERT INTO ame_sl_ic_batch(var_locid, var_itemid, var_cur, int_batchno, dou_drqty, dou_druc, dou_drac1, dou_drac2, dou_drac3, dou_drac4, dou_drac5, dou_qty, dou_fundruc, dou_fundrac1, dou_fundrac2, dou_fundrac3, dou_fundrac4, dou_fundrac5) VALUES
(P1, P2, P16, P4, AME_FUN_ROUND(P5, P13), AME_FUN_ROUND(P6, P14), AME_FUN_ROUND(P7, P14), AME_FUN_ROUND(P8, P14), AME_FUN_ROUND(P9, P14), AME_FUN_ROUND(P10, P14), AME_FUN_ROUND(P11, P14), AME_FUN_ROUND(P5, P13), AME_FUN_ROUND(P17, P15), AME_FUN_ROUND(P18, P15), AME_FUN_ROUND(P19, P15), AME_FUN_ROUND(P20, P15), AME_FUN_ROUND(P21, P15), AME_FUN_ROUND(P22, P15));
ELSE
INSERT INTO ame_sl_ic_batch(var_locid, var_itemid, var_cur, int_batchno, dou_crqty, dou_cruc, dou_crac1, dou_crac2, dou_crac3, dou_crac4, dou_crac5, dou_qty, dou_funcruc, dou_funcrac1, dou_funcrac2, dou_funcrac3, dou_funcrac4, dou_funcrac5) VALUES
(P1, P2, P16, P4, AME_FUN_ROUND(P5, P13), AME_FUN_ROUND(P6, P14), AME_FUN_ROUND(P7, P14), AME_FUN_ROUND(P8, P14), AME_FUN_ROUND(P9, P14), AME_FUN_ROUND(P10, P14), AME_FUN_ROUND(P11, P14), AME_FUN_ROUND(P5, P13), AME_FUN_ROUND(P17, P15), AME_FUN_ROUND(P18, P15), AME_FUN_ROUND(P19, P15), AME_FUN_ROUND(P20, P15), AME_FUN_ROUND(P21, P15), AME_FUN_ROUND(P22, P15));
END IF;
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `AME_PRO_UPDATE_SL_IC_HIS`;
DELIMITER |
CREATE PROCEDURE `AME_PRO_UPDATE_SL_IC_HIS`(P1 varchar(100), P2 varchar(100), P3 integer, P4 datetime, P5 double, P6 double,  P7 double, P8 double, P9 double, P10 double, P11 double, P12 integer, P13 integer, P14 varchar(100), P15 varchar(100), P16 varchar(100), P17 varchar(100), P18 varchar(100), P19 varchar(100), P20 varchar(100), P21 varchar(250), P22 varchar(2000), P23 varchar(2000), P24 varchar(100), P25 double, P26 double, P27 integer)
    DETERMINISTIC
BEGIN
		INSERT INTO ame_sl_ic_his(int_id,	int_line,	var_locid, var_itemid, int_batchno,	dat_date,	dou_qty, dou_uc, dou_ac1,	dou_ac2, dou_ac3,	dou_ac4, dou_ac5,	var_modid, var_doctype, var_docid, var_venid,	var_cusid, var_empid,	var_claid, var_ref,	var_desc,	var_desc_det,	var_cur, dou_rate, dou_foc, int_jid)	VALUES
		(P12, P13, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, P24, P25, P26, P27);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ats_add_user_activity`;
DELIMITER |
CREATE PROCEDURE `ats_add_user_activity`(var_action varchar(255), var_module varchar(255), var_mId varchar(255), var_uid varchar(255))
    DETERMINISTIC
BEGIN
	INSERT INTO `ats_activity` (`AC_ID`, `AC_Action`, `AC_ModuleName`, `AC_ModuleID`, `AC_ByUser`, `AC_Date`) 
  VALUES (ATS_FUN_generateAutoId("AC"), var_action, var_module,  var_mId, var_uid, NOW());
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ats_delete_role_by_id`;
DELIMITER |
CREATE PROCEDURE `ats_delete_role_by_id`(rId varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM ats_role WHERE ats_role.RM_ID = rId;
	DELETE FROM ats_role_detail WHERE ats_role_detail.RM_RoleID = rId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ats_delete_role_detail_by_id`;
DELIMITER |
CREATE PROCEDURE `ats_delete_role_detail_by_id`()
    DETERMINISTIC
BEGIN
	DELETE  FROM ats_role_detail WHERE RM_RoleID is null;
END |
DELIMITER ;

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

		CASE UPPER(module)
			WHEN "CAMPAIGN" THEN
				SELECT 
					CA_ID AS campID,
					CA_Name AS campName
				FROM 	
					crm_camp ca;
	
			WHEN "LEAD" THEN
				SELECT 
					LA_ID AS leadID,
					LA_FirstName AS firstName,
					LA_LastName AS	lastName
				FROM
					crm_lead;

			WHEN "OPPORTUNITY" THEN	
				SELECT 
					OP_ID AS opId,
					OP_Name AS opName
				FROM
					crm_opportunity;

			WHEN "CASE" THEN
				SELECT 
					CS_ID AS caseId,
					CS_Subject AS Subject
				FROM 
					crm_case;

			WHEN "CONTACT" THEN
				SELECT 
					CO_ID AS conID,
					CO_FirstName AS conFirstname,
					CO_LastName AS conLastName
				FROM
					crm_contact;

			WHEN "CUSTOMER" THEN
				SELECT 
					CustID AS custID,
					CustName AS custNAme 
				FROM 
					tblcustomer;
			
			WHEN "EVENT" THEN
				SELECT 
					EV_ID AS evId,
					EV_Name AS evName
				FROM
					crm_event;

			WHEN "METTING" THEN
				SELECT 
					M_ID AS meetingId,
					M_Subject AS meetingSubject
				FROM 
					crm_meeting;

			WHEN "NOTE" THEN		
				SELECT 
					N_ID AS noteId,
					N_Subject AS noteSubject
				FROM
					crm_note;
			WHEN "TASK" THEN
				SELECT 
					TA_ID AS taskId,
					TA_Subject AS taskSubject
				FROM 
					crm_task;

			WHEN "LOCATION" THEN
				SELECT 
					LO_ID AS loId,
					LO_Name AS loName
				FROM 
					crm_location;
		END CASE;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ats_listSystemModuleByUser`;
DELIMITER |
CREATE PROCEDURE `ats_listSystemModuleByUser`(IN `userId` varchar(255) ,  IN `module` varchar(255))
    DETERMINISTIC
BEGIN
	
	SELECT m.ModuleID 'moduleId' , m.Remarks 'moduleName', m.`Group` 'groupModule', COALESCE(tbl.RM_Delete, 'NO') 'delete', COALESCE(tbl.RM_Edit, 'NO') 'edit', COALESCE(tbl.RM_Export, 'NO') 'export', COALESCE(tbl.RM_Import, 'NO') 'import', COALESCE(tbl.RM_List, 'NO') 'list',COALESCE(tbl.RM_View, 'NO') 'view',COALESCE(tbl.RM_Access, 'NO') 'access' 
	FROM ats_numberprefix m
	LEFT JOIN (SELECT * from ats_role_detail WHERE RM_RoleID=(select u.UATSRoleID from tbluser u WHERE u.UID = userId) AND RM_ModuleID=module) as tbl on tbl.RM_ModuleID = m.ModuleID
	WHERE m.`Status`=1 AND m.ModuleID=module
	ORDER BY m.`Group`;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ats_listSystemModules`;
DELIMITER |
CREATE PROCEDURE `ats_listSystemModules`()
    DETERMINISTIC
BEGIN
	SELECT 
		ModuleID AS moduleId, 
		Remarks AS moduleName,
		`Group` as groupModule,
		SUBSTRING(`Group`,1,6) 'groupType'
	FROM 
		ats_numberprefix
	WHERE Status = 1
	ORDER BY `Group`, ModuleID
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ats_listSystemModulesByRoleId`;
DELIMITER |
CREATE PROCEDURE `ats_listSystemModulesByRoleId`(IN `roleId` varchar(11))
    DETERMINISTIC
BEGIN
DECLARE roleName VARCHAR(255);
DECLARE roleTypeId INTEGER;
DECLARE roleDescription VARCHAR(255);
SELECT rm_name , rm_typeid,rm_des INTO roleName,roleTypeId,roleDescription FROM ats_role WHERE rm_id = roleId;
SELECT roleTypeId 'roleTypeId', roleName 'roleName', roleDescription 'roleDescription', m.ModuleID 'moduleId', m.Remarks 'moduleName', `Group` 'groupModule', COALESCE(tbl.RM_Delete, 'NO') 'delete', COALESCE(tbl.RM_Edit, 'NO') 'edit', COALESCE(tbl.RM_Export, 'NO') 'export', COALESCE(tbl.RM_Import, 'NO') 'import', COALESCE(tbl.RM_List, 'NO') 'list',COALESCE(tbl.RM_View, 'NO') 'view',COALESCE(tbl.RM_Access, 'NO') 'access'
,SUBSTRING(`Group`,1,6) 'groupType'
FROM ats_numberprefix m
LEFT JOIN (SELECT * from ats_role_detail join ats_role on ats_role.RM_ID = ats_role_detail.RM_RoleID WHERE RM_RoleID=roleId) as tbl on tbl.RM_ModuleID = m.ModuleID
WHERE m.`Status`=1
ORDER BY m.`Group`, m.ModuleID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ats_list_ats_users`;
DELIMITER |
CREATE PROCEDURE `ats_list_ats_users`()
    DETERMINISTIC
BEGIN
	# list all user crm
	SELECT u.var_id 'userID', u.var_name 'username',COALESCE(u.tin_ats_isonlyrole,0) 'isOwn',  u.tin_inactive 'status', u.var_ats_role 'roleId', r.RM_Name 'roleName' , COALESCE(e.var_id,'') 'empId', COALESCE(e.var_name,'') 'empName',
		     (SELECT GROUP_CONCAT(ur.RID) FROM ats_user_role ur WHERE ur.UID = u.var_id) mgRole
	FROM ame_user u
	LEFT JOIN ame_user_app ua on ua.var_id=u.var_id
	LEFT JOIN ats_role r on r.RM_ID=u.var_ats_role
	LEFT JOIN ame_mt_emp e ON e.var_id = u.var_empid
	WHERE ua.var_appid = 'ATS'  
	GROUP BY u.var_id 
	ORDER BY u.var_id;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ats_list_role_master`;
DELIMITER |
CREATE PROCEDURE `ats_list_role_master`()
    DETERMINISTIC
BEGIN
	SELECT RM_ID 'roleId', RM_Name 'roleName' FROM ats_role WHERE RM_Status=1 ORDER BY RM_Name;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_AddManyEmployeeAuthorisation`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_AddManyEmployeeAuthorisation`(userid varchar(255), SReplace tinyint, EmployeeAuth text)
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE Exist INT DEFAULT(0);

	IF SReplace <= 0 THEN
		SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_employee(Emp_ID,Auth_Process,Auth_ID) VALUES ", EmployeeAuth, " ON DUPLICATE KEY UPDATE Emp_ID = Emp_ID ,Auth_Process=Auth_Process;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			CALL spHRMAddLog(userid, "insert", "EmployeeAuthorisation", "Many");
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1102401', 'EmpAuth', 'create', '');
	ELSE
		SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_employee(Emp_ID,Auth_Process,Auth_ID) VALUES ", EmployeeAuth, " ON DUPLICATE KEY UPDATE Emp_ID = Emp_ID ,Auth_Process=Auth_Process;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			CALL spHRMAddLog(userid, "insert", "EmployeeAuthorisation", "Many");
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1102401', 'EmpAuth', 'create', '');
	END IF;
		
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_AddManyWatcherAuthorisation`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_AddManyWatcherAuthorisation`(userid varchar(255), SReplace tinyint, EmployeeAuth text)
    DETERMINISTIC
BEGIN
		DECLARE Message VARCHAR(255);
	DECLARE Exist INT DEFAULT(0);

	IF SReplace <= 0 THEN
		SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_watcher(Emp_ID,Auth_Process,Auth_ID) VALUES ", EmployeeAuth, " ON DUPLICATE KEY UPDATE Emp_ID = Emp_ID ,Auth_Process=Auth_Process;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			CALL spHRMAddLog(userid, "insert", "watcherAuthorisation", "Many");
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1102401', 'EmpAuth', 'create', '');
	ELSE
		SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_watcher(Emp_ID,Auth_Process,Auth_ID) VALUES ", EmployeeAuth, " ON DUPLICATE KEY UPDATE Emp_ID = Emp_ID ,Auth_Process=Auth_Process;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			CALL spHRMAddLog(userid, "insert", "watcherAuthorisation", "Many");
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1102401', 'EmpAuth', 'create', '');
	END IF;
		

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_ameDeleteCollaboration`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_ameDeleteCollaboration`(IN `id` varchar(255))
    DETERMINISTIC
BEGIN
	
DELETE FROM int_collaboration WHERE CB_ID = `id`;
DELETE FROM int_collaboration_details WHERE PostID = `id`;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_ameDeleteCollaborationDetail`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_ameDeleteCollaborationDetail`(IN `id` varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM int_collaboration_details WHERE CommentID = `id`;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_ameGetCheckAuthorisationApprove`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_ameGetCheckAuthorisationApprove`(IN UserID varchar(255), authProcessID varchar(255), authProcessName varchar(255), authID varchar(255), authGroupID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE SID VARCHAR(255) DEFAULT('');

	SELECT u.var_empid INTO SID FROM ame_user u WHERE u.var_id = UserID;

	if authGroupID = 'a' THEN
		SET authGroupID = '';
	END IF;

	SELECT 
				DISTINCT(al.Auth_ProcessID),
				al.Auth_ProcessName,
				al.Auth_ID, 
				al.Auth_GroupID,
				al.Auth_EmpID,
				al.Auth_Status, 
				fnHRMCheckAuthorisationGroupApproved(al.Auth_ProcessID,al.Auth_ProcessName, al.Auth_ID, al.Auth_GroupID) as "Auth_Edit",
				al.Auth_Date,
				al.EmpID,
				COALESCE(al.EmpName, '') AS 'EmpName'
				

	FROM(

	SELECT Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status, 1 AS 'Auth_Edit', Auth_Date,
		IF(Auth_ProcessName='Sale Order', sa.var_create,
		IF(Auth_ProcessName='Quote', qu.var_create,
		IF(Auth_ProcessName='Material Request', mr.RequestedBy,
		IF(Auth_ProcessName="Budget Requisition", br.EmpID,
		IF(Auth_ProcessName="General Requisition", gr.EmpID,
		IF(Auth_ProcessName='Customer', ATS_FUN_UEmp(cust.var_create),
		IF(Auth_ProcessName='Temporary Credit', ATS_FUN_UEmp(ci.var_create),
		IF(Auth_ProcessName='Over Due Date', ATS_FUN_UEmp(co.var_create),'')))))))) AS 'Auth_ProcessEmpID',

		IF(Auth_ProcessName='Customer', cust.var_crm_approval,
		IF(Auth_ProcessName='Sale Order', sa.var_auth_status,
		IF(Auth_ProcessName='Quote', qu.var_auth_status,
		IF(Auth_ProcessName="Budget Requisition", br.ApprovalStatus,
		IF(Auth_ProcessName="General Requisition", gr.ApprovalStatus,
		IF(Auth_ProcessName='Temporary Credit', ci.var_status,
		IF(Auth_ProcessName='Material Request', mr.`Status`,
		IF(Auth_ProcessName='Over Due Date', co.var_status,'')))))))) AS 'Auth_TranStatus',
		e.var_id 'EmpID',e.var_name "EmpName"
		FROM hrm_authorisation_approved ap
	LEFT JOIN ats_materialrequest mr ON ap.Auth_ProcessID = mr.EntryNo
		LEFT JOIN crm_customer cust ON ap.Auth_ProcessID = cust.var_id
		LEFT JOIN ame_mt_tem_tc ci ON ap.Auth_ProcessID = ci.var_id
		LEFT JOIN ame_ar_so sa ON ap.Auth_ProcessID = sa.var_id
		LEFT JOIN ame_ar_quo qu ON ap.Auth_ProcessID = qu.var_id
		LEFT JOIN crm_frm_general gr ON ap.Auth_ProcessID = gr.FrmID
		LEFT JOIN crm_frm_budget br ON ap.Auth_ProcessID = br.FrmID
		LEFT JOIN ame_mt_tem_odd co ON ap.Auth_ProcessID = co.var_id
	  INNER JOIN ame_mt_emp e ON ap.Auth_EmpID = e.var_id
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
  	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		WHERE ap.Auth_EmpID = SID 
	AND ap.Auth_ProcessID = authProcessID 
	AND ap.Auth_ProcessName = authProcessName AND ap.Auth_ID = authID AND ap.Auth_GroupID = authGroupID

	) al

	INNER JOIN hrm_authorisation_module m ON(LOWER(m.AM_ID) = LOWER(al.Auth_ProcessName) AND LOWER(m.AM_APP) = 'ame')
	INNER JOIN ame_mt_emp e ON e.var_id = al.Auth_ProcessEmpID
	LEFT JOIN hrm_authorisation auth ON (auth.Auth_ID = al.Auth_ID)
	ORDER BY Auth_ProcessName,Auth_TranStatus DESC,
					 al.Auth_Edit DESC, FIELD(al.Auth_Status, 'requested', 'approved', 'rejected', '');
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_ameInsertCollaboration`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_ameInsertCollaboration`(IN `desc` varchar(255),IN `id` varchar(255), IN `date` varchar(255), IN `rto` varchar(255), IN `rtotype` varchar(255),IN `cbo` varchar(255))
    DETERMINISTIC
BEGIN
	
	INSERT INTO int_collaboration (CB_Des, CB_UID, CB_CreateDate, CB_RToID, CB_RToType,CB_Own)
  VALUES (`desc`,`id`, `date`, `rto`, `rtotype`, `cbo`);

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_ameInsertCollaborationDetail`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_ameInsertCollaborationDetail`(IN `pid` varchar(255), IN `cmd` varchar(255), IN `un` varchar(255))
    DETERMINISTIC
BEGIN
	
	INSERT INTO int_collaboration_details (PostID,`Comment`,CreateDate,Username) VALUES (`pid`,`cmd`,NOW(),`un`);

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_ameUpdateAuthorisationApprove`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_ameUpdateAuthorisationApprove`(IN UserID varchar(255),IN SProID varchar(255),IN  SProName varchar(255),IN SAuthID varchar(255),IN SAuthGID varchar(255),IN SEmpID varchar(255),IN SAuthStatus varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE EmpID VARCHAR(255) DEFAULT('');
	DECLARE Message VARCHAR(20) DEFAULT('not exist');
	DECLARE L BIGINT DEFAULT(0);
	DECLARE CheckStatus INT DEFAULT(0);
	DECLARE PStatus VARCHAR(255);

	CALL ATS_PRO_ameUpdateAuthorizationEditTable(UserID, SProID, SProName);

	SELECT ap.Auth_Line,
		(IF(ap.Auth_ProcessName="Customer" AND LOWER(cust.var_crm_approval) = "requested",1,
		IF(ap.Auth_ProcessName="Budget Requisition" AND LOWER(br.`approvalstatus`) = "requested",1,
		IF(ap.Auth_ProcessName="General Requisition" AND LOWER(gr.`approvalstatus`) = "requested",1,
		IF(ap.Auth_ProcessName="Temporary Credit" AND LOWER(ci.`var_status`) = "requested",1,
		IF(ap.Auth_ProcessName="Over Due Date" AND LOWER(od.`var_status`) = "requested",1,
		IF(ap.Auth_ProcessName="Material Request" AND LOWER(mr.`Status`) = "requested",1,
		IF(Auth_ProcessName="Sale Order" AND LOWER(sa.var_auth_status) = "requested",1,
		IF(Auth_ProcessName="Quote" AND LOWER(qu.var_auth_status) = "requested",1,0))))))))) INTO L, CheckStatus
	FROM hrm_authorisation_approved ap
		LEFT JOIN crm_customer cust ON ap.Auth_ProcessID = cust.var_id
		LEFT JOIN ame_mt_tem_tc ci ON ap.Auth_ProcessID = ci.var_id
		LEFT JOIN ame_ar_so sa ON ap.Auth_ProcessID = sa.var_id
		LEFT JOIN ame_mt_tem_odd od ON ap.Auth_ProcessID = od.var_id
		LEFT JOIN ame_ar_quo qu ON ap.Auth_ProcessID = qu.var_id
		LEFT JOIN crm_frm_general gr ON ap.Auth_ProcessID = gr.FrmID
		LEFT JOIN crm_frm_budget br ON ap.Auth_ProcessID = br.FrmID
		LEFT JOIN ats_materialrequest mr ON ap.Auth_ProcessID = mr.EntryNo

	WHERE ap.Auth_ProcessID = SProID AND ap.Auth_ProcessName = SProName AND ap.Auth_ID = SAuthID AND ap.Auth_GroupID = SAuthGID AND ap.Auth_EmpID = SEmpID LIMIT 1;

	SELECT u.var_empid INTO EmpID FROM ame_user u WHERE u.var_id = UserID;

	IF SEmpID = EmpID AND L <> 0 AND CheckStatus = 1 THEN
		UPDATE hrm_authorisation_approved SET Auth_Status = LOWER(SAuthStatus) WHERE Auth_Line = L;
		CALL spHRMAddLog(UserID, "insert", "Authorsation Approve", SProID);
		CALL spHRMGetCheckAuthorisationTranApproved(UserID, SProID, SProName, SAuthID, SAuthGID);
		SET Message = 'success';
		CALL hrm_message_param3('1101301', 'AuthApprove', 'update', SAuthStatus, SProName, SProID);
	ELSE
		SET Message = 'not allow';
		CALL hrm_message_param3('1101302', 'AuthApprove', 'notallowed', SAuthStatus, SProName, SProID);
	END IF;
	
	SELECT Message;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_ameUpdateAuthorizationEditTable`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_ameUpdateAuthorizationEditTable`(IN `UserID`  varchar(255), IN `ProcessID`  varchar(255), IN `ProcessName`  varchar(255))
    DETERMINISTIC
BEGIN
	IF ProcessName = 'Customer' THEN 
		  UPDATE crm_customer SET crm_customer.tin_editable = 0 WHERE crm_customer.var_id = `ProcessID`;
	ELSEIF ProcessName = 'Sale Order' THEN
			UPDATE ame_ar_so SET ame_ar_so.tin_editable = 0 WHERE ame_ar_so.var_id = `ProcessID`;
  ELSEIF ProcessName = 'Quote' THEN 
			UPDATE ame_ar_quo SET ame_ar_quo.tin_editable = 0 WHERE ame_ar_quo.var_id = `ProcessID`;
	ELSEIF ProcessName = 'Over Due Date' THEN
			UPDATE ame_mt_tem_odd SET ame_mt_tem_odd.tin_editable = 0 WHERE ame_mt_tem_odd.var_id = `ProcessID`;
	ELSEIF ProcessName = 'Temporary Credit' THEN 
			UPDATE ame_mt_tem_tc SET ame_mt_tem_tc.tin_editable = 0 WHERE ame_mt_tem_tc.var_id = `ProcessID`;
	ELSEIF ProcessName = 'General Requisition' THEN 
			UPDATE crm_frm_general SET crm_frm_general.EditTable = 0 WHERE crm_frm_general.FrmID = `ProcessID`;
	ELSEIF ProcessName = 'Budget Requisition' THEN 
			UPDATE crm_frm_budget SET crm_frm_budget.EditTable = 0 WHERE crm_frm_budget.FrmID = `ProcessID`;
	ELSEIF ProcessName = 'Materail Requisition' THEN 
			UPDATE ats_materialrequest SET ats_materialrequest.tin_editable = 0 WHERE ats_materialrequest.EntryNo = `ProcessID`;	
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_CheckUpdateRequestApproval`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_CheckUpdateRequestApproval`(IN processid varchar(255),IN processname varchar(255))
    DETERMINISTIC
BEGIN
		
	DECLARE authId VARCHAR(255) DEFAULT "";
	DECLARE authType VARCHAR(255) DEFAULT "";
	DECLARE authCount INT(11) DEFAULT 0;
	DECLARE empid VARCHAR(255) DEFAULT "";

	SELECT COUNT(Auth_ID) INTO authCount FROM hrm_authorisation_approved WHERE Auth_ProcessID = processid AND Auth_ProcessName = processname ;

	IF authCount = 0 THEN




					IF processname = "General Requisition" THEN
						SELECT crm_frm_general.EmpID INTO empid FROM crm_frm_general WHERE crm_frm_general.FrmID = processid;
					ELSEIF processname = "Over Due Date" THEN
						SELECT ame_mt_tem_odd.var_create INTO empid  FROM ame_mt_tem_odd  WHERE ame_mt_tem_odd.var_id = processid;
					ELSEIF processname = "Temporary Credit" THEN
						SELECT ame_mt_tem_tc.var_create INTO empid FROM ame_mt_tem_tc  WHERE ame_mt_tem_tc.var_id = processid;
					ELSEIF processname = "Customer" THEN
						SELECT crm_customer.var_create INTO empid FROM crm_customer WHERE crm_customer.var_id = processid;
					ELSEIF processname = "Quote" THEN
						SELECT ame_ar_quo.var_create INTO empid FROM ame_ar_quo WHERE ame_ar_quo.var_id = processid;
					ELSEIF processname = "Sale Order" THEN
						SELECT ame_ar_so.var_create  INTO empid FROM ame_ar_so WHERE ame_ar_so.var_id = processid;
					ELSEIF processname = "Budget Requisition" THEN
						SELECT crm_frm_budget.EmpID  INTO empid FROM crm_frm_budget WHERE crm_frm_budget.FrmID = processid;
					ELSEIF processname = "Material Request" THEN
						SELECT ats_materialrequest.RequestedBy INTO empid FROM ats_materialrequest WHERE ats_materialrequest.EntryNo = processid;
					END IF; 
			
				
					
					IF LOWER(processname ) = "customer" OR LOWER(processname ) = "over due date" OR LOWER(processname ) = "temporary credit" THEN
						SELECT 
								DISTINCT ae.Auth_ID, ha.Auth_Type
								INTO authId, authType 
						FROM hrm_authorisation_employee ae 
							INNER JOIN hrm_authorisation ha
								ON ha.Auth_ID = ae.Auth_ID
						WHERE ae.Emp_ID = ATS_FUN_UEmp(empid) AND ae.Auth_Process = processname ;
					ELSE
						SELECT 
								DISTINCT ae.Auth_ID, ha.Auth_Type
								INTO authId, authType 
						FROM hrm_authorisation_employee ae 
							INNER JOIN hrm_authorisation ha
								ON ha.Auth_ID = ae.Auth_ID
						WHERE ae.Emp_ID = empid AND ae.Auth_Process = processname ;
					END IF;

					IF authId <> "" AND authType <> "" THEN 
		
									IF processname = "General Requisition" THEN
										UPDATE crm_frm_general SET crm_frm_general.GRAuthID = authId WHERE crm_frm_general.FrmID = processid;
									ELSEIF processname = "Over Due Date" THEN
										UPDATE ame_mt_tem_odd SET ame_mt_tem_odd.var_authId = authId WHERE ame_mt_tem_odd.var_id = processid;
									ELSEIF processname = "Temporary Credit" THEN
										UPDATE ame_mt_tem_tc SET ame_mt_tem_tc.var_authId = authId WHERE ame_mt_tem_tc.var_id = processid;
									ELSEIF processname = "Customer" THEN
										update crm_customer SET crm_customer.var_authId = authId WHERE crm_customer.var_id = processid;
									ELSEIF processname = "Quote" THEN
										update ame_ar_quo SET ame_ar_quo.var_authId = authId WHERE ame_ar_quo.var_id = processid;
									ELSEIF processname = "Sale Order" THEN
										update ame_ar_so SET ame_ar_so.var_authId = authId WHERE ame_ar_so.var_id = processid;
									ELSEIF processname = "Budget Requisition" THEN
										UPDATE crm_frm_budget SET crm_frm_budget.BRAuthID = authId WHERE crm_frm_budget.FrmID = processid;
									ELSEIF processname = "Material Request" THEN
										UPDATE ats_materialrequest SET ats_materialrequest.var_authId = authId WHERE ats_materialrequest.EntryNo = processid;
									END IF;


									IF authType = "Individual" THEN
											CALL spHRMAddAuthorisationTemp(authId,processid);
											CALL spHRMAddIAuthorisationApproved(authId, processid, processname);
									ELSE
											CALL spHRMAddAuthorisationTemp(authId,processid);
											CALL spHRMAddGAuthorisationApproved(authId, processid, processname);
									END IF;


					END IF;



	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_CountAuthorizationByUsername`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_CountAuthorizationByUsername`(IN `username` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COUNT(*) as count FROM hrm_authorisation_employee 
	WHERE Emp_ID = username
	AND Auth_Process IN (SELECT hrm_authorisation_module.AM_ID FROM hrm_authorisation_module WHERE LOWER(hrm_authorisation_module.AM_APP) = "ame");

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_DeleteEmployeeAuthorisationID`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_DeleteEmployeeAuthorisationID`(UserID varchar(255),EmpID varchar(255), SAuthProcess varchar(255), SAuthID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	IF EmpID != '' THEN
		DELETE FROM hrm_authorisation_employee WHERE Emp_ID = EmpID AND Auth_Process = SAuthProcess AND Auth_ID = SAuthID;

		CALL spHRMAddLog(userid, "delete", "Employee Authorisation", CONCAT(EmpID, ', ', SAuthProcess, ', ', SAuthID));

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1102403', 'EmpAuth', 'delete', SAuthID);
	ELSE
		SET Message = "fail";
		SELECT Message;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_DeleteWatcherAuthorisationID`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_DeleteWatcherAuthorisationID`(UserID varchar(255),EmpID varchar(255), SAuthProcess varchar(255), SAuthID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	IF EmpID != '' THEN
		DELETE FROM hrm_authorisation_watcher WHERE hrm_authorisation_watcher.Emp_ID = EmpID AND hrm_authorisation_watcher.Auth_Process = SAuthProcess AND hrm_authorisation_watcher.Auth_ID = SAuthID;

		CALL spHRMAddLog(userid, "delete", "Wathcer Authorisation", CONCAT(EmpID, ', ', SAuthProcess, ', ', SAuthID));

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1102403', 'EmpAuth', 'delete', SAuthID);
	ELSE
		SET Message = "fail";
		SELECT Message;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_delete_role_detail_by_id`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_delete_role_detail_by_id`()
    DETERMINISTIC
BEGIN
	DELETE  FROM ats_role_detail WHERE RM_RoleID is null;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_findRoleDetailsByUsername`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_findRoleDetailsByUsername`(IN `username` varchar(255), IN `moduleId` varchar(11))
    DETERMINISTIC
BEGIN
	
	SELECT 
		us.var_id AS userId,
		us.var_name 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 
		ame_user us 
	INNER JOIN 
		crm_role role
			ON us.var_crm_role = 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.var_name = username AND prefix.ModuleID = moduleId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetAuthDetailInv`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetAuthDetailInv`(IN ID varchar(200),IN proName varchar(200),IN SAuthID varchar(200))
    DETERMINISTIC
BEGIN
		

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetAuthorisationApproveEmpID`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetAuthorisationApproveEmpID`(IN UserID varchar(255), IN SStatus varchar(255), IN SProcessName varchar(255),IN fDate varchar(255), IN tDate varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE SID VARCHAR(255) DEFAULT('');
	SELECT u.var_empid INTO SID FROM ame_user u WHERE u.var_id = UserID;

SELECT 
	DISTINCT(al.Auth_ProcessID),
	al.Auth_ProcessName,
  al.Auth_ID,
  al.Auth_GroupID, 
  al.Auth_EmpID,
  al.Auth_Status,
  fnHRMCheckAuthorisationGroupApproved(al.Auth_ProcessID,al.Auth_ProcessName, al.Auth_ID, al.Auth_GroupID) as "Auth_Edit",
  al.Auth_Date,
  al.EmpID,
  COALESCE(al.EmpName, '') AS 'EmpName',
	COALESCE(al.EmpEmail, '') AS 'EmpEmail',
	COALESCE(al.Emp_CompanyEmail, '') AS 'Emp_CompanyEmail',
	COALESCE(al.Position, '') AS 'Position',
	COALESCE(al.PositionKhmer, '') AS 'PositionKhmer', 
	COALESCE(al.Position_Level,"") AS 'Position_Level', 
	COALESCE(al.UName, '') AS 'UName', 
  COALESCE(al.Auth_ProcessEmpID, '') AS 'Auth_ProcessEmpID', 
  CONCAT('',e.var_name) AS 'Auth_ProcessEmpName',
  fnHRMCheckAuthorisationApproved(al.Auth_ProcessID, al.Auth_ProcessName, al.Auth_ID) AS 'Auth_AmountApproved', 
  fnHRMCheckAuthorisationApprove(al.Auth_ProcessID, al.Auth_ProcessName, al.Auth_ID) AS 'Auth_AmountApprove',
	auth.Auth_ID,
  auth.Auth_Name,
  auth.Auth_Type,
  auth.Auth_AndOr,
  COALESCE((SELECT IF(LOWER(ad.Auth_GroupAndOr) = 'and', ad.Auth_GroupAmount, 1) FROM hrm_authorisation_detail_temp ad WHERE ad.Auth_TranID = al.Auth_ProcessID AND ad.Auth_ID = al.Auth_ID AND ad.Auth_GroupID = al.Auth_GroupID LIMIT 0,1),"") AS "Auth_Amount",
  Auth_TranStatus,
  ATS_FUN_ameAuthDescApproval(al.Auth_ProcessName,al.Auth_ProcessID) AS "Auth_Desc",
  ATS_FUN_ameAuthGetCustomerName(al.Auth_ProcessName,al.Auth_ProcessID) AS "Auth_Customer"
	FROM(
	SELECT Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status, 1 AS 'Auth_Edit', Auth_Date,
		IF(Auth_ProcessName='Sale Order', sa.var_create,
		IF(Auth_ProcessName='Quote', qu.var_create,
		IF(Auth_ProcessName='Material Request', mr.RequestedBy,
		IF(Auth_ProcessName="Budget Requisition", br.EmpID,
		IF(Auth_ProcessName="General Requisition", gr.EmpID,
		IF(Auth_ProcessName='Customer', ATS_FUN_UEmp(cust.var_create),
		IF(Auth_ProcessName='Temporary Credit', ATS_FUN_UEmp(ci.var_create),
		IF(Auth_ProcessName='Over Due Date', ATS_FUN_UEmp(co.var_create),'')))))))) AS 'Auth_ProcessEmpID',

		IF(Auth_ProcessName='Customer', cust.var_crm_approval,
		IF(Auth_ProcessName='Sale Order', sa.var_auth_status,
		IF(Auth_ProcessName='Quote', qu.var_auth_status,
		IF(Auth_ProcessName="Budget Requisition", br.ApprovalStatus,
		IF(Auth_ProcessName="General Requisition", gr.ApprovalStatus,
		IF(Auth_ProcessName='Temporary Credit', ci.var_status,
		IF(Auth_ProcessName='Material Request', mr.`Status`,
		IF(Auth_ProcessName='Over Due Date', co.var_status,'')))))))) AS 'Auth_TranStatus',


		COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName,
    COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail,
		COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', 
		COALESCE(pos.int_level, 0) AS 'Position_Level', COALESCE(u.var_name, '') AS UName, 
		COALESCE(e.var_hrm_internal_id, '') AS 'Emp_InternalID'

	  FROM hrm_authorisation_approved ap 

		LEFT JOIN ats_materialrequest mr ON ap.Auth_ProcessID = mr.EntryNo
		LEFT JOIN crm_customer cust ON ap.Auth_ProcessID = cust.var_id
		LEFT JOIN ame_mt_tem_tc ci ON ap.Auth_ProcessID = ci.var_id
		LEFT JOIN ame_ar_so sa ON ap.Auth_ProcessID = sa.var_id
		LEFT JOIN ame_ar_quo qu ON ap.Auth_ProcessID = qu.var_id
		LEFT JOIN crm_frm_general gr ON ap.Auth_ProcessID = gr.FrmID
		LEFT JOIN crm_frm_budget br ON ap.Auth_ProcessID = br.FrmID
		LEFT JOIN ame_mt_tem_odd co ON ap.Auth_ProcessID = co.var_id
	  INNER JOIN ame_mt_emp e ON ap.Auth_EmpID = e.var_id
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
  	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		WHERE ap.Auth_EmpID = SID 
		AND IF(fDate <> "" && tDate <> "", ap.Auth_Date BETWEEN fDate AND tDate, true)
	) al

	INNER JOIN hrm_authorisation_module m ON(LOWER(m.AM_ID) = LOWER(al.Auth_ProcessName) AND LOWER(m.AM_APP) = 'ame')
	INNER JOIN ame_mt_emp e ON e.var_id = al.Auth_ProcessEmpID
	LEFT JOIN hrm_authorisation auth ON (auth.Auth_ID = al.Auth_ID)
	WHERE if(LOWER(SStatus) = "all" && LOWER(SProcessName) = "all",
				   TRUE,
				if(LOWER(SStatus) = "all" && LOWER(SProcessName) <> "all",
				   LOWER(Auth_ProcessName) = LOWER(SProcessName),
        if(LOWER(SStatus) <> "all" && LOWER(SProcessName) <> "all",
            LOWER(Auth_TranStatus) = LOWER(SStatus) AND LOWER(Auth_ProcessName) = LOWER(SProcessName),
        if(LOWER(SStatus) <> "all" && LOWER(SProcessName) = "all",
            LOWER(Auth_TranStatus) = LOWER(SStatus),
				TRUE))))
	ORDER BY IF(SProcessName = 'all', Auth_ProcessName, TRUE), FIELD(LOWER(Auth_TranStatus), 'requested', 'approved', 'rejected', ''),al.Auth_Date DESC;

	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetAuthorizationAllProcess`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetAuthorizationAllProcess`(IN ID varchar(200),IN proName varchar(200),IN SAuthID varchar(200))
    DETERMINISTIC
BEGIN

			SET @SQL1 = CONCAT('
			 SELECT a.Auth_ID as "authId",
						 a.Auth_Name as "authName",
						 a.Auth_Type as "authType",
						 a.Auth_AndOr as "authAndOr",
						 a.Auth_Amount as "authAmount",
						 fnHRMCheckAuthorisationApproved("',ID,'", "',proName,'", "',SAuthID,'") AS "authApproved"
			 FROM hrm_authorisation_temp a WHERE a.Auth_ID = "',SAuthID,'" AND a.Auth_TranID = "',ID,'" ;');
			PREPARE St1 FROM @SQL1;
			EXECUTE St1;
			DEALLOCATE PREPARE St1;

		SET @SQL2 = CONCAT('SELECT a.Auth_ID as "authId",
									 a.Auth_EmpID as "authEmpId",
									 a.Auth_GroupID as "authGroupId",
									 a.Auth_GroupAndOr as "authGroupAndOr",
									 a.Auth_GroupAmount as "authGroupAmount",
									 app.Auth_Status as "authStatus"
			FROM hrm_authorisation_detail_temp a
			LEFT JOIN hrm_authorisation_approved app ON 
			(app.Auth_ID = "',SAuthID,'" AND app.Auth_ProcessID = "',ID,'" AND app.Auth_ProcessName = "',proName,'"	AND a.Auth_EmpID = app.Auth_EmpID AND a.Auth_GroupID = app.Auth_GroupID AND a.Auth_TranID = app.Auth_ProcessID)
			WHERE a.Auth_TranID = "',ID,'" AND a.Auth_ID = "',SAuthID,'";');
			PREPARE St2 FROM @SQL2;
			EXECUTE St2;
			DEALLOCATE PREPARE St2;

		SELECT a.AuthGroup_ID as "authGroupId",
				   a.AuthGroup_Name as "authGroupName",
					 a.AuthGroup_Description as "authGroupDescription",
					 COALESCE(d.Auth_GroupAndOr,"") as "authGroupAndOr",
					 COALESCE(d.Auth_GroupAmount,"") as "authGroupAmount",
					 (SELECT COUNT(ds.AuthGroup_ID) FROM hrm_authorisation_group_detail_temp ds WHERE ds.AuthGroup_ID = a.AuthGroup_ID AND ds.Auth_TranID = ID) as 'authGroupCount',
					 (SELECT COUNT(ds.Auth_GroupID) FROM hrm_authorisation_approved ds WHERE ds.Auth_ProcessID = ID AND ds.Auth_GroupID = a.AuthGroup_ID AND ds.Auth_ID = SAuthID AND ds.Auth_Status = "approved") AS 'authGroupApproved'
		FROM hrm_authorisation_group_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(d.Auth_GroupID = a.AuthGroup_ID AND d.Auth_ID = SAuthID AND a.Auth_TranID = ID)
		WHERE a.Auth_TranID = ID
		ORDER BY a.AuthGroup_ID DESC;

		SELECT a.AuthGroup_ID as "authGroupId",
					 a.AuthGroup_EmpID as "authGroupEmpId",
					 COALESCE(e.var_id, '') AS "empID",
					 COALESCE(e.var_name, '') AS "empName",
					 COALESCE(e.var_email, '') AS "empEmail",
					 COALESCE(e.var_hrm_company_email, '') AS "empCompanyEmail",
					 COALESCE(pos.var_id, '') AS 'Position', 
					 COALESCE(pos.var_name, '') AS 'Position', 
					 COALESCE(pos.var_addr, '') AS 'PositionKhmer',
					 COALESCE(pos.int_level, 0) AS 'Position_Level', 
					 COALESCE(u.var_name, '') AS 'UName', 
					 COALESCE(e.var_hrm_internal_id, '') AS 'empInternalID', 
					 app.Auth_Status as "authStatus"
		FROM hrm_authorisation_group_detail_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(a.AuthGroup_ID = d.Auth_GroupID AND d.Auth_ID = SAuthID AND a.Auth_TranID = d.Auth_TranID)
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_GroupID = a.AuthGroup_ID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = proName AND app.Auth_EmpID = a.AuthGroup_EmpID)
		LEFT JOIN ame_mt_emp e ON(a.AuthGroup_EmpID = e.var_id)  
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		WHERE a.Auth_TranID = ID AND d.Auth_ID = SAuthID
		ORDER BY a.AuthGroup_EmpID, a.AuthGroup_ID;


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetBudgetID`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetBudgetID`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE SYear INT DEFAULT(0);
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");

	SELECT Auth_ID INTO SAuthID FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID LIMIT 1;
	
	
	SELECT FrmID 'frmId',
				 FrmDate 'frmDate',
				 EmpID 'empId',
				(SELECT ee.var_name FROM ame_mt_emp ee WHERE ee.var_id = fg.EmpID) as "empName",
				 Department 'department',
				 Position 'position',
				 Phone 'phone',
				 COALESCE(Objective,"") as "objective",
				 COALESCE(Reason,"") as "reason",
				 COALESCE(ApprovalDate,"") as "approvalDate",
				 ApprovalStatus 'approvalStatus' FROM crm_frm_budget fg WHERE FrmID = ID ;
					
	
 CALL ATS_PRO_GetAuthorizationAllProcess(ID,"Budget Requisition",SAuthID);

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetCustomerID`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetCustomerID`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE SYear INT DEFAULT(0);
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");

	SELECT Auth_ID INTO SAuthID FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID LIMIT 1;
	

		SELECT 
				c.var_id 'custId',
				c.var_name 'custName',
				c.var_name_con 'custContact',
				c.var_tel1 'tel1',
				c.var_tel2 'tel2',
				c.var_fax 'fax',
				c.var_email 'email',
				c.var_web 'web',
				c.var_addr 'address',
				c.var_groupid 'groupId',
				c.var_pricecode 'priceCode',
				c.var_crm_facebook 'facebook',
				c.var_crm_line 'line',
				c.var_crm_viber 'viber',
				c.var_crm_whatapp 'whatapp',
				c.var_crm_approval 'status',
				c.var_img 'img',
				c.var_create 'date',
				var_name_other 'otherName',
				COALESCE((SELECT CONCAT(crm_gazetteer.var_nameen," (",crm_gazetteer.var_namekh,")",IF(tin_province = 1," | ក្រុង","")) FROM crm_gazetteer WHERE var_id = c.var_addr1),"") "city",	
				COALESCE((SELECT CONCAT(crm_gazetteer.var_nameen," (",crm_gazetteer.var_namekh,")",IF(tin_province = 1," | ក្រុង","")) FROM crm_gazetteer WHERE var_id = c.var_addr2),"") "district",
				COALESCE((SELECT CONCAT(crm_gazetteer.var_nameen," (",crm_gazetteer.var_namekh,")") FROM crm_gazetteer WHERE var_id = c.var_addr3),"") "commune",
				COALESCE((SELECT CONCAT(crm_gazetteer.var_nameen," (",crm_gazetteer.var_namekh,")") FROM crm_gazetteer WHERE var_id = c.var_addr4),"") "village" FROM crm_customer c WHERE c.var_id = ID ;
		
		CALL ATS_PRO_GetAuthorizationAllProcess(ID,"Customer",SAuthID);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetCustomerTmpID`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetCustomerTmpID`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE SYear INT DEFAULT(0);
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");
	DECLARE proName VARCHAR(200);

	SELECT Auth_ID INTO SAuthID FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID LIMIT 1;
	
	
	SET proName = "Temporary Credit";

	SELECT tc.var_id as 'id',
				 ATS_FUN_CO(tc.var_type) as 'type',
				 tc.var_cusid as 'custId',
					(SELECT ame_mt_cus.var_name FROM ame_mt_cus WHERE ame_mt_cus.var_id = tc.var_cusid) as 'custName',
					tc.var_status as 'status',
					tc.var_desc as 'remark',
					tc.var_cur  as'cur',
					tc.var_create as "createBy",
					ATS_FUN_CO(tc.dat_date)  as 'date',
					tc.dat_from as 'dateFrom',
					ATS_FUN_CO(tc.dat_to)  as "dateTo",
					tc.dat_create as 'createDate',
					tc.dou_amt  as 'amount',
					tc.dou_funamt as 'funamt',
					tc.dou_rate as'rate',
					tc.var_crm_relate as'relate',
					tc.var_crm_relateid as'relateID'
	FROM ame_mt_tem_tc tc WHERE tc.var_id = ID; 

	SET @SQL1 = CONCAT('
			 SELECT a.Auth_ID as "authId",
						 a.Auth_Name as "authName",
						 a.Auth_Type as "authType",
						 a.Auth_AndOr as "authAndOr",
						 a.Auth_Amount as "authAmount",
						 fnHRMCheckAuthorisationApproved("',ID,'", "',proName,'", "',SAuthID,'") AS "authApproved"
			 FROM hrm_authorisation_temp a WHERE a.Auth_ID = "',SAuthID,'" AND a.Auth_TranID = "',ID,'" ;');
			PREPARE St1 FROM @SQL1;
			EXECUTE St1;
			DEALLOCATE PREPARE St1;

		SET @SQL2 = CONCAT('SELECT a.Auth_ID as "authId",
									 a.Auth_EmpID as "authEmpId",
									  (SELECT ame_mt_emp.var_name FROM ame_mt_emp WHERE ame_mt_emp.var_id = a.Auth_EmpID) "authEmpName",
									 a.Auth_GroupID as "authGroupId",
									 a.Auth_GroupAndOr as "authGroupAndOr",
									 a.Auth_GroupAmount as "authGroupAmount",
									 app.Auth_Status as "authStatus"
			FROM hrm_authorisation_detail_temp a
			LEFT JOIN hrm_authorisation_approved app ON 
			(app.Auth_ID = "',SAuthID,'" AND app.Auth_ProcessID = "',ID,'" AND app.Auth_ProcessName = "',proName,'"	AND a.Auth_EmpID = app.Auth_EmpID AND a.Auth_GroupID = app.Auth_GroupID AND a.Auth_TranID = app.Auth_ProcessID)
			WHERE a.Auth_TranID = "',ID,'" AND a.Auth_ID = "',SAuthID,'";');
			PREPARE St2 FROM @SQL2;
			EXECUTE St2;
			DEALLOCATE PREPARE St2;

		SELECT DISTINCT a.AuthGroup_ID as "authGroupId",
				   a.AuthGroup_Name as "authGroupName",
					 a.AuthGroup_Description as "authGroupDescription",
					 COALESCE(d.Auth_GroupAndOr,"") as "authGroupAndOr",
					 COALESCE(d.Auth_GroupAmount,"") as "authGroupAmount",
					 (SELECT COUNT(ds.AuthGroup_ID) FROM hrm_authorisation_group_detail_temp ds WHERE ds.AuthGroup_ID = a.AuthGroup_ID AND ds.Auth_TranID = ID) as 'authGroupCount',
					 (SELECT COUNT(ds.Auth_GroupID) FROM hrm_authorisation_approved ds WHERE ds.Auth_ProcessID = ID AND ds.Auth_GroupID = a.AuthGroup_ID AND ds.Auth_ID = SAuthID AND ds.Auth_Status = "approved") AS 'authGroupApproved'
		FROM hrm_authorisation_group_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(d.Auth_GroupID = a.AuthGroup_ID AND d.Auth_ID = SAuthID AND a.Auth_TranID = ID)
		WHERE a.Auth_TranID = ID
		ORDER BY a.AuthGroup_ID DESC;


		SELECT a.AuthGroup_ID as "authGroupId",
					 a.AuthGroup_EmpID as "authGroupEmpId",
					 COALESCE(e.var_id, '') AS "empID",
					 COALESCE(e.var_name, '') AS "empName",
					 COALESCE(e.var_email, '') AS "empEmail",
					 COALESCE(e.var_hrm_company_email, '') AS "empCompanyEmail",
					 COALESCE(pos.var_id, '') AS 'Position', 
					 COALESCE(pos.var_name, '') AS 'Position', 
					 COALESCE(pos.var_addr, '') AS 'PositionKhmer',
					 COALESCE(pos.int_level, 0) AS 'Position_Level', 
					 COALESCE(u.var_name, '') AS 'UName', 
					 COALESCE(e.var_hrm_internal_id, '') AS 'empInternalID', 
					 app.Auth_Status as "authStatus"
		FROM hrm_authorisation_group_detail_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(a.AuthGroup_ID = d.Auth_GroupID AND d.Auth_ID = SAuthID AND a.Auth_TranID = d.Auth_TranID)
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_GroupID = a.AuthGroup_ID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = proName AND app.Auth_EmpID = a.AuthGroup_EmpID)
		LEFT JOIN ame_mt_emp e ON(a.AuthGroup_EmpID = e.var_id)  
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		WHERE a.Auth_TranID = ID AND d.Auth_ID = SAuthID
		ORDER BY a.AuthGroup_EmpID, a.AuthGroup_ID;

	-- CALL ATS_PRO_GetAuthorizationAllProcess(ID,"Templorary Credit",SAuthID);


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetEmployeeAuthorisationByProcessName`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetEmployeeAuthorisationByProcessName`(ProcessName varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level', COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID,
	a.Emp_ID, a.Auth_Process, a.Auth_ID,
	auth.Auth_ID,auth.Auth_Name,auth.Auth_Type,auth.Auth_AndOr,auth.Auth_Amount
	FROM ame_mt_emp e
	LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	LEFT JOIN hrm_authorisation_employee a ON a.Emp_ID = e.var_id AND IF(LOWER(ProcessName) = 'ame' OR LOWER(ProcessName) = 'hrm', LOWER(a.Auth_Process) IN((SELECT LOWER(AM_ID) FROM hrm_authorisation_module WHERE LOWER(AM_APP) = LOWER(ProcessName))), LOWER(a.Auth_Process) = LOWER(ProcessName))
	LEFT JOIN hrm_authorisation auth on auth.Auth_ID = a.Auth_ID
	ORDER BY e.var_id; 


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetEmployeeAuthorisationSubAdd`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetEmployeeAuthorisationSubAdd`(ProcessName varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level', COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID
	FROM ame_mt_emp e
	LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	WHERE e.var_id NOT IN(SELECT Emp_ID FROM hrm_authorisation_employee WHERE LOWER(Auth_Process) = ProcessName)
	ORDER BY e.var_id;
	
	SELECT d.Setting_Name FROM hrm_setting d WHERE d.Setting_Type = "Authorisation" AND d.Setting_Value != "1" AND d.Setting_Value != "0";

	SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount FROM hrm_authorisation a ORDER BY a.Auth_ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetEmployeeIDAuthorization`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetEmployeeIDAuthorization`(ID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT a.Emp_ID, a.Auth_Process, a.Auth_ID 
	,COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level', COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID
	,auth.Auth_ID,auth.Auth_Name,auth.Auth_Type,auth.Auth_AndOr,auth.Auth_Amount
	FROM hrm_authorisation_employee a
	INNER JOIN ame_mt_emp e ON a.Emp_ID = e.var_id
	INNER JOIN hrm_authorisation auth on auth.Auth_ID = a.Auth_ID
	INNER JOIN hrm_authorisation_module m ON LOWER(m.AM_ID) = LOWER(a.Auth_Process) AND LOWER(m.AM_APP) = 'ame' 
	LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	WHERE a.Emp_ID = ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetGeneralID`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetGeneralID`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE SYear INT DEFAULT(0);
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");

	SELECT Auth_ID INTO SAuthID FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID LIMIT 1;
	
	
		SELECT FrmID 'frmId',
					FrmDate 'frmDate',
					EmpID 'empId',
				 (SELECT ee.var_name FROM ame_mt_emp ee WHERE ee.var_id = fg.EmpID) as "empName",
				  Department 'department',
					 Position 'position',
					Phone 'phone',
					COALESCE(Objective,"") as "objective",
					COALESCE(Reason,"") as "reason",
					COALESCE(ApprovalDate,"") as "approvalDate",
					ApprovalStatus 'approvalStatus',
					COALESCE(ReqType,"") as "reqType",
					COALESCE(ReqDescription,"") as "reqDescription" ,
				COALESCE(fg.ApprovalDate) 'approvalDate'  FROM crm_frm_general fg WHERE FrmID = ID ;
		
		
 CALL ATS_PRO_GetAuthorizationAllProcess(ID,"General Requisition",SAuthID);


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetMaterialRequestID`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetMaterialRequestID`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE SYear INT DEFAULT(0);
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");

	SELECT Auth_ID INTO SAuthID FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID LIMIT 1;
	

		SELECT EntryNo 'entryNo',
					 Reference 'reference',
					 EntryDate 'entryDate',
					 RequiredDate 'requiredDate',
					 `Status` 'status',
					 COALESCE((SELECT CONCAT("[",ee.var_id,"] ",ee.var_name) FROM ame_mt_emp ee WHERE ee.var_id = mat.RequestedBy),"") "requestedBy",
					 Remark 'remark',
					 COALESCE((SELECT CONCAT("[",c.var_id,"] ",c.var_name) FROM ame_mt_cus c WHERE c.var_id = mat.CustID),"") "custID" 
					FROM ats_materialrequest mat WHERE EntryNo = ID ;

		SELECT dd.LineNo 'lineNo',
					dd.ItemID 'itemId',
					(SELECT ii.var_name FROM amt_mt_ite ii WHERE ii.var_id = dd.ItemID) "itemName" ,
					dd.FromLocationID 'fromLocation',
					dd.ToLocationID 'toLocation',
					dd.UOMID 'uomid',
					dd.Qty 'qty'
 FROM ats_materialrequestdetail dd WHERE dd.EntryNo = ID;
		
			
 CALL ATS_PRO_GetAuthorizationAllProcess(ID,"Material Request",SAuthID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetOverDueDateID`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetOverDueDateID`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE SYear INT DEFAULT(0);
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");

	SELECT Auth_ID INTO SAuthID FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID LIMIT 1;
	
	SELECT tc.var_id 'id',
				 ATS_FUN_CO(tc.var_type) 'type',
				 tc.var_cusid 'custId',
				(SELECT ame_mt_cus.var_name FROM ame_mt_cus WHERE ame_mt_cus.var_id = tc.var_cusid) as 'custName',
					tc.var_status 'status',
					tc.var_desc 'desc',
					tc.var_create "createBy",
					ATS_FUN_CO(tc.dat_date) 'date',
					tc.dat_from 'dateFrom',
					tc.dat_to "dateTo",
					tc.dat_create 'createDate',
					tc.var_crm_relate as'relate',
					tc.var_crm_relateid as'relateID'
	FROM ame_mt_tem_odd tc WHERE tc.var_id = ID; 

 CALL ATS_PRO_GetAuthorizationAllProcess(ID,"Over Due Date",SAuthID);




END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetQuoteID`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetQuoteID`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE SYear INT DEFAULT(0);
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");

	SELECT Auth_ID INTO SAuthID FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID LIMIT 1;
	


		SELECT s.var_id "salId",
					 s.var_type "salType",
					 s.var_cusid "custId",
					 s.var_empid 'empId',
					 ATS_FUN_CO(s.var_claid) 'classId',
					 ATS_FUN_CO(s.var_pricecode) 'priceCode',
					ATS_FUN_CO(s.var_status) 'status',
					ATS_FUN_CO(s.var_pmtstatus) 'pmtstatus',
					ATS_FUN_CO(s.var_term) 'term',
					ATS_FUN_CO(s.var_ref) 'reference',
					ATS_FUN_CO(s.var_desc) 'description',
					ATS_FUN_CO(s.var_cur)	"cur",
					ATS_FUN_CO(s.var_po) "po",
					ATS_FUN_CO(s.var_so) 'so',
					ATS_FUN_CO(s.var_shipid) 'shipId',
					ATS_FUN_CO(s.var_shipaddr) 'shipAddr',
					ATS_FUN_CO(s.var_create) 'createBy',
					ATS_FUN_CO(s.var_post) 'post',
					ATS_FUN_CO(s.var_void) 'void',
					ATS_FUN_CO(s.dat_date) 'date',
					ATS_FUN_CO(s.dat_due) "due",
					ATS_FUN_CO(s.dat_from) 'from',
					ATS_FUN_CO(s.dat_to) 'to',
					ATS_FUN_CO(s.dat_create) 'createDate',
					ATS_FUN_CO(s.dat_post) 'datePost',
					ATS_FUN_CO(s.dat_void) "dateVoid",
					ATS_FUN_CO(s.int_jid) 'jid',
					s.dou_sub 'subTotal',
					s.dou_disper 'disPer',
					s.dou_disdol 'disDol',
					s.dou_taxper 'taxPer',
					s.dou_taxdol 'taxDol',
					s.dou_taxper1 'taxPer1',
					COALESCE(s.dou_taxdol1,0) 'taxDol1',
					s.dou_net "totalNet",
					s.dou_paid 'paid',
					s.dou_rate 'rate',	
					s.dou_funsub 'funsub',
					s.dou_fundisdol 'disDol',
					s.dou_funtaxdol 'taxDol',
					s.dou_funtaxdol1 'taxDol1',
					s.dou_funnet 'funNet',
					s.dou_funpaid 'funPaid',
					s.tin_taxbfdisc 'taxBeforeDis'
 		FROM ame_ar_so s WHERE s.var_id = ID ;

		SELECT sa.var_id as "salId" ,
			    sa.int_line 'line',
					sa.var_accid 'accId',
					ATS_FUN_CO(sa.var_locid) 'locationId',
					ATS_FUN_CO(sa.var_claid) 'classId',
					sa.var_uomid 'oumId',
					ATS_FUN_CO(sa.var_desc) "desc",
					ATS_FUN_CO(sa.var_poid) 'poid',
				  sa.dou_orderqty 'dou_orderqty',
					sa.dou_orderfoc 'dou_orderfoc',
					sa.dou_qty 'dou_qty',
					sa.dou_foc 'dou_foc',
					sa.dou_price 'dou_price',
					sa.dou_pricecom 'dou_pricecom',
					sa.dou_sub 'dou_sub',
					sa.dou_disper 'dou_disper',
					sa.dou_disdol 'dou_disdol',
					sa.dou_taxper 'dou_taxper',
					sa.dou_taxdol 'dou_taxdol',
					sa.dou_taxper1 'dou_taxper1',
					sa.dou_taxdol1 'dou_taxdol1',
					sa.dou_funprice 'dou_funprice',
					sa.dou_funpricecom 'dou_funpricecom',
					sa.dou_funsub 'dou_funsub',
					sa.dou_fundisdol 'dou_fundisdol', 
					sa.dou_funtaxdol 'dou_funtaxdol',
					sa.dou_funtaxdol1 'dou_funtaxdol1',
					sa.dou_funnet 'dou_funnet',
					sa.int_batchno 'int_batchno',
					sa.int_poline 'int_poline',
					sa.tin_vat 'tin_vat',
					sa.var_itemid 'itemId',
					(SELECT i.var_name From ame_mt_ite i WHERE i.var_id = sa.var_id) "itemName"
			FROM ame_ar_so_det sa WHERE sa.var_id = ID;
		


	 CALL ATS_PRO_GetAuthorizationAllProcess(ID,"Quote",SAuthID);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetSaleOrderID`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetSaleOrderID`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE SYear INT DEFAULT(0);
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");

	SELECT Auth_ID INTO SAuthID FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID LIMIT 1;
	


		SELECT s.var_id "salId",
					 s.var_type "salType",
					 s.var_cusid "custId",
					 s.var_empid 'empId',
					 ATS_FUN_CO(s.var_claid) 'classId',
					 ATS_FUN_CO(s.var_pricecode) 'priceCode',
					ATS_FUN_CO(s.var_status) 'status',
					ATS_FUN_CO(s.var_pmtstatus) 'pmtstatus',
					ATS_FUN_CO(s.var_term) 'term',
					ATS_FUN_CO(s.var_ref) 'reference',
					ATS_FUN_CO(s.var_desc) 'description',
					ATS_FUN_CO(s.var_cur)	"cur",
					ATS_FUN_CO(s.var_po) "po",
					ATS_FUN_CO(s.var_so) 'so',
					ATS_FUN_CO(s.var_shipid) 'shipId',
					ATS_FUN_CO(s.var_shipaddr) 'shipAddr',
					ATS_FUN_CO(s.var_create) 'createBy',
					ATS_FUN_CO(s.var_post) 'post',
					ATS_FUN_CO(s.var_void) 'void',
					ATS_FUN_CO(s.dat_date) 'date',
					ATS_FUN_CO(s.dat_due) "due",
					ATS_FUN_CO(s.dat_from) 'from',
					ATS_FUN_CO(s.dat_to) 'to',
					ATS_FUN_CO(s.dat_create) 'createDate',
					ATS_FUN_CO(s.dat_post) 'datePost',
					ATS_FUN_CO(s.dat_void) "dateVoid",
					ATS_FUN_CO(s.int_jid) 'jid',
					s.dou_sub 'subTotal',
					s.dou_disper 'disPer',
					s.dou_disdol 'disDol',
					s.dou_taxper 'taxPer',
					s.dou_taxdol 'taxDol',
					s.dou_taxper1 'taxPer1',
					COALESCE(s.dou_taxdol1,0) 'taxDol1',
					s.dou_net "totalNet",
					s.dou_paid 'paid',
					s.dou_rate 'rate',	
					s.dou_funsub 'funsub',
					s.dou_fundisdol 'disDol',
					s.dou_funtaxdol 'taxDol',
					s.dou_funtaxdol1 'taxDol1',
					s.dou_funnet 'funNet',
					s.dou_funpaid 'funPaid',
					s.tin_taxbfdisc 'taxBeforeDis'
 		FROM ame_ar_so s WHERE s.var_id = ID ;

		SELECT sa.var_id as "salId" ,
			    sa.int_line 'line',
					sa.var_accid 'accId',
					ATS_FUN_CO(sa.var_locid) 'locationId',
					ATS_FUN_CO(sa.var_claid) 'classId',
					sa.var_uomid 'oumId',
					ATS_FUN_CO(sa.var_desc) "desc",
					ATS_FUN_CO(sa.var_poid) 'poid',
				  sa.dou_orderqty 'dou_orderqty',
					sa.dou_orderfoc 'dou_orderfoc',
					sa.dou_qty 'dou_qty',
					sa.dou_foc 'dou_foc',
					sa.dou_price 'dou_price',
					sa.dou_pricecom 'dou_pricecom',
					sa.dou_sub 'dou_sub',
					sa.dou_disper 'dou_disper',
					sa.dou_disdol 'dou_disdol',
					sa.dou_taxper 'dou_taxper',
					sa.dou_taxdol 'dou_taxdol',
					sa.dou_taxper1 'dou_taxper1',
					sa.dou_taxdol1 'dou_taxdol1',
					sa.dou_funprice 'dou_funprice',
					sa.dou_funpricecom 'dou_funpricecom',
					sa.dou_funsub 'dou_funsub',
					sa.dou_fundisdol 'dou_fundisdol', 
					sa.dou_funtaxdol 'dou_funtaxdol',
					sa.dou_funtaxdol1 'dou_funtaxdol1',
					sa.dou_funnet 'dou_funnet',
					sa.int_batchno 'int_batchno',
					sa.int_poline 'int_poline',
					sa.tin_vat 'tin_vat',
					sa.var_itemid 'itemId',
					(SELECT i.var_name From ame_mt_ite i WHERE i.var_id = sa.var_id) "itemName"
			FROM ame_ar_so_det sa WHERE sa.var_id = ID;
		


	 CALL ATS_PRO_GetAuthorizationAllProcess(ID,"Sale Order",SAuthID);

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetWatcherAuthorisationByProcessName`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetWatcherAuthorisationByProcessName`(ProcessName varchar(255))
    DETERMINISTIC
BEGIN

	SELECT COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level', COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID,
	a.Emp_ID, a.Auth_Process, a.Auth_ID,
	auth.Auth_ID,auth.Auth_Name,auth.Auth_Type,auth.Auth_AndOr,auth.Auth_Amount
	FROM ame_mt_emp e
	LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	LEFT JOIN hrm_authorisation_watcher a ON a.Emp_ID = e.var_id AND IF(LOWER(ProcessName) = 'ame' OR LOWER(ProcessName) = 'hrm', LOWER(a.Auth_Process) IN((SELECT LOWER(AM_ID) FROM hrm_authorisation_module WHERE LOWER(AM_APP) = LOWER(ProcessName))), LOWER(a.Auth_Process) = LOWER(ProcessName))
	LEFT JOIN hrm_authorisation auth on auth.Auth_ID = a.Auth_ID
	ORDER BY e.var_id; 

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetWatcherAuthorisationSubAdd`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetWatcherAuthorisationSubAdd`(ProcessName varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level', COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID
	FROM ame_mt_emp e
	LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	WHERE e.var_id NOT IN(SELECT Emp_ID FROM hrm_authorisation_watcher WHERE LOWER(Auth_Process) = ProcessName)
	ORDER BY e.var_id;
	
	SELECT d.Setting_Name FROM hrm_setting d WHERE d.Setting_Type = "Authorisation" AND d.Setting_Value != "1" AND d.Setting_Value != "0";

	SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount FROM hrm_authorisation a ORDER BY a.Auth_ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_GetWatcherIDAuthorisation`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_GetWatcherIDAuthorisation`(ID varchar(255))
    DETERMINISTIC
BEGIN
		SELECT a.Emp_ID, a.Auth_Process, a.Auth_ID ,
   COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level', COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID,
   auth.Auth_ID,auth.Auth_Name,auth.Auth_Type,auth.Auth_AndOr,auth.Auth_Amount
	FROM hrm_authorisation_watcher a
	INNER JOIN ame_mt_emp e ON a.Emp_ID = e.var_id
	LEFT JOIN ame_user u ON u.var_empid = e.var_id
	LEFT JOIN ame_mt_pos pos ON e.var_posid = pos.var_id
	INNER JOIN hrm_authorisation auth on auth.Auth_ID = a.Auth_ID
	INNER JOIN hrm_authorisation_module m ON LOWER(m.AM_ID) = LOWER(a.Auth_Process) AND LOWER(m.AM_APP) = 'ame'
	WHERE a.Emp_ID = ID;

END |
DELIMITER ;

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

		CASE UPPER(module)
			WHEN "CAMPAIGN" THEN
				SELECT 
					CA_ID AS campID,
					CA_Name AS campName
				FROM 	
					crm_camp ca;
	
			WHEN "LEAD" THEN
				SELECT 
					LA_ID AS leadID,
					LA_FirstName AS firstName,
					LA_LastName AS	lastName
				FROM
					crm_lead;

			WHEN "OPPORTUNITY" THEN	
				SELECT 
					OP_ID AS opId,
					OP_Name AS opName
				FROM
					crm_opportunity;

			WHEN "CASE" THEN
				SELECT 
					CS_ID AS caseId,
					CS_Subject AS Subject
				FROM 
					crm_case;

			WHEN "CONTACT" THEN
				SELECT 
					CO_ID AS conID,
					CO_FirstName AS conFirstname,
					CO_LastName AS conLastName
				FROM
					crm_contact;

			WHEN "CUSTOMER" THEN
				SELECT 
					CustID AS custID,
					CustName AS custNAme 
				FROM 
					tblcustomer;
			
			WHEN "EVENT" THEN
				SELECT 
					EV_ID AS evId,
					EV_Name AS evName
				FROM
					crm_event;

			WHEN "METTING" THEN
				SELECT 
					M_ID AS meetingId,
					M_Subject AS meetingSubject
				FROM 
					crm_meeting;

			WHEN "NOTE" THEN		
				SELECT 
					N_ID AS noteId,
					N_Subject AS noteSubject
				FROM
					crm_note;
			WHEN "TASK" THEN
				SELECT 
					TA_ID AS taskId,
					TA_Subject AS taskSubject
				FROM 
					crm_task;

			WHEN "LOCATION" THEN
				SELECT 
					LO_ID AS loId,
					LO_Name AS loName
				FROM 
					crm_location;
		END CASE;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_listSystemModuleByUser`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_listSystemModuleByUser`(IN `userId` varchar(255) ,  IN `module` varchar(255))
    DETERMINISTIC
BEGIN
	
	SELECT m.ModuleID 'moduleId' , m.Remarks 'moduleName', m.`Group` 'groupModule', COALESCE(tbl.RM_Delete, 'NO') 'delete', COALESCE(tbl.RM_Edit, 'NO') 'edit', COALESCE(tbl.RM_Export, 'NO') 'export', COALESCE(tbl.RM_Import, 'NO') 'import', COALESCE(tbl.RM_List, 'NO') 'list',COALESCE(tbl.RM_View, 'NO') 'view',COALESCE(tbl.RM_Access, 'NO') 'access' 
	FROM ats_numberprefix m
	LEFT JOIN (SELECT * from ats_role_detail WHERE RM_RoleID=(select u.UATSRoleID from tbluser u WHERE u.UID = userId) AND RM_ModuleID=module) as tbl on tbl.RM_ModuleID = m.ModuleID
	WHERE m.`Status`=1 AND m.ModuleID=module
	ORDER BY m.`Group`;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_listSystemModules`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_listSystemModules`()
    DETERMINISTIC
BEGIN
	SELECT 
		ModuleID AS moduleId, 
		Remarks AS moduleName,
		`Group` as groupModule,
		SUBSTRING(`Group`,1,6) 'groupType'
	FROM 
		ats_numberprefix
	WHERE Status = 1
	ORDER BY `Group`, ModuleID
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_listSystemModulesByRoleId`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_listSystemModulesByRoleId`(IN `roleId` varchar(11))
    DETERMINISTIC
BEGIN
DECLARE roleName VARCHAR(255);
DECLARE roleTypeId INTEGER;
DECLARE roleDescription VARCHAR(255);
SELECT rm_name , rm_typeid,rm_des INTO roleName,roleTypeId,roleDescription FROM ats_role WHERE rm_id = roleId;
SELECT roleTypeId 'roleTypeId', roleName 'roleName', roleDescription 'roleDescription', m.ModuleID 'moduleId', m.Remarks 'moduleName', `Group` 'groupModule', COALESCE(tbl.RM_Delete, 'NO') 'delete', COALESCE(tbl.RM_Edit, 'NO') 'edit', COALESCE(tbl.RM_Export, 'NO') 'export', COALESCE(tbl.RM_Import, 'NO') 'import', COALESCE(tbl.RM_List, 'NO') 'list',COALESCE(tbl.RM_View, 'NO') 'view',COALESCE(tbl.RM_Access, 'NO') 'access'
,SUBSTRING(`Group`,1,6) 'groupType'
FROM ats_numberprefix m
LEFT JOIN (SELECT * from ats_role_detail join ats_role on ats_role.RM_ID = ats_role_detail.RM_RoleID WHERE RM_RoleID=roleId) as tbl on tbl.RM_ModuleID = m.ModuleID
WHERE m.`Status`=1
ORDER BY m.`Group`, m.ModuleID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_list_ats_users`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_list_ats_users`()
    DETERMINISTIC
BEGIN
	# list all user crm
	SELECT u.UID 'userID', u.UName 'username', COALESCE(u.UType,'') 'type', u.UStatus 'status', UATSRoleID 'roleId', r.RM_Name 'roleName' , COALESCE(ue.empid,'') 'empId', COALESCE(e.empname,'') 'empName',
		     (SELECT GROUP_CONCAT(ur.RID) FROM ats_user_role ur WHERE ur.UID = u.UID) mgRole, CONCAT(u.IsOnlyRole,'.0') 'isOwn'
	FROM tbluser u
	LEFT JOIN tbluserapp ua on ua.UID=u.UID
	LEFT JOIN ats_role r on r.RM_ID=u.UATSRoleID
	LEFT JOIN tbluseremployee ue ON ue.uid = u.uid
	LEFT JOIN tblemployee e ON e.empid = ue.empid
	WHERE ua.AppID = 'ATS' and COALESCE(u.UType,'') <> 'Administrator' GROUP BY u.UID ORDER BY u.UID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_list_role_master`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_list_role_master`()
    DETERMINISTIC
BEGIN
	SELECT RM_ID 'roleId', RM_Name 'roleName' FROM ats_role WHERE RM_Status=1 ORDER BY RM_Name;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_RequestAuthEmp`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_RequestAuthEmp`(IN `proID` varchar(255), IN `empid`  varchar(255), IN proName varchar(200))
    DETERMINISTIC
BEGIN
	DECLARE authId VARCHAR(255) DEFAULT "";
	DECLARE authType VARCHAR(255) DEFAULT "";
	
	
	-- SELECT ame_user.var_empid INTO @emp FROM ame_user WHERE ame_user.var_id = empid OR ame_user.var_empid = empid;

	IF LOWER(proName) = "customer" OR LOWER(proName) = "over due date" OR LOWER(proName) = "temporary credit" THEN
			SELECT 
					DISTINCT ae.Auth_ID, ha.Auth_Type
					INTO authId, authType 
			FROM hrm_authorisation_employee ae 
				INNER JOIN hrm_authorisation ha
					ON ha.Auth_ID = ae.Auth_ID
			WHERE ae.Emp_ID = ATS_FUN_UEmp(empid) AND ae.Auth_Process = proName;
	ELSE
			SELECT 
					DISTINCT ae.Auth_ID, ha.Auth_Type
					INTO authId, authType 
			FROM hrm_authorisation_employee ae 
				INNER JOIN hrm_authorisation ha
					ON ha.Auth_ID = ae.Auth_ID
			WHERE ae.Emp_ID = empid AND ae.Auth_Process = proName;
	END IF;

	
	IF authId <> "" AND authType <> "" THEN
		IF LOWER(proName) = "customer" THEN
			IF authType = "Individual" THEN	
				UPDATE crm_customer SET crm_customer.var_authId = authId WHERE crm_customer.var_id = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddIAuthorisationApproved(authId,proID,"Customer");
			ELSE
				UPDATE crm_customer SET crm_customer.var_authId = authId WHERE crm_customer.var_id = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddGAuthorisationApproved(authId,proID,"Customer");
			END IF;
		ELSEIF LOWER(proName) = "sale order" THEN
			IF authType = "Individual" THEN	
				UPDATE ame_ar_so SET ame_ar_so.var_authId = authId WHERE ame_ar_so.var_id = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddIAuthorisationApproved(authId,proID,"Sale Order");
			ELSE
				UPDATE ame_ar_so SET ame_ar_so.var_authId = authId WHERE ame_ar_so.var_id = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddGAuthorisationApproved(authId,proID,"Sale Order");
			END IF;
		ELSEIF LOWER(proName) = "quote" THEN
				IF authType = "Individual" THEN	
				UPDATE ame_ar_quo SET ame_ar_quo.var_authId = authId WHERE ame_ar_quo.var_id = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddIAuthorisationApproved(authId,proID,"Quote");
			ELSE
				UPDATE ame_ar_quo SET ame_ar_quo.var_authId = authId WHERE ame_ar_quo.var_id = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddGAuthorisationApproved(authId,proID,"Quote");
			END IF;
		ELSEIF LOWER(proName) = "temporary credit" THEN
				IF authType = "Individual" THEN	
				UPDATE ame_mt_tem_tc SET ame_mt_tem_tc.var_authId = authId WHERE ame_mt_tem_tc.var_id = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddIAuthorisationApproved(authId,proID,"Temporary Credit");
			ELSE
				UPDATE ame_mt_tem_tc SET ame_mt_tem_tc.var_authId = authId WHERE ame_mt_tem_tc.var_id = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddGAuthorisationApproved(authId,proID,"Temporary Credit");
			END IF;
		ELSEIF LOWER(proName) = "over due date" THEN
				IF authType = "Individual" THEN	
				UPDATE ame_mt_tem_odd SET ame_mt_tem_odd.var_authId = authId WHERE ame_mt_tem_odd.var_id = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddIAuthorisationApproved(authId,proID,"Over Due Date");
			ELSE
					UPDATE ame_mt_tem_odd SET ame_mt_tem_odd.var_authId = authId WHERE ame_mt_tem_odd.var_id = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddGAuthorisationApproved(authId,proID,"Over Due Date");
			END IF;
		ELSEIF LOWER(proName) = "budget requisition" THEN
				IF authType = "Individual" THEN	
				UPDATE crm_frm_budget SET crm_frm_budget.brauthid = authId WHERE crm_frm_budget.frmid = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddIAuthorisationApproved(authId,proID,"Budget Requisition");
			ELSE
				UPDATE crm_frm_budget SET crm_frm_budget.brauthid = authId WHERE crm_frm_budget.frmid = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddGAuthorisationApproved(authId,proID,"Budget Requisition");
			END IF;
		ELSEIF LOWER(proName) = "general requisition" THEN
				IF authType = "Individual" THEN	
				UPDATE crm_frm_general SET crm_frm_general.GRAuthID = authId WHERE crm_frm_general.FrmID = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddIAuthorisationApproved(authId,proID,"General Requisition");
			ELSE
				UPDATE crm_frm_general SET crm_frm_general.GRAuthID = authId WHERE crm_frm_general.FrmID = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddGAuthorisationApproved(authId,proID,"General Requisition");
			END IF;
		ELSEIF LOWER(proName) = "material request" THEN
				IF authType = "Individual" THEN	
				UPDATE ats_materialrequest SET ats_materialrequest.var_authId = authId WHERE ats_materialrequest.EntryNo = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddIAuthorisationApproved(authId,proID,"Material Request");
			ELSE
				UPDATE ats_materialrequest SET ats_materialrequest.var_authId = authId WHERE ats_materialrequest.EntryNo = proID;
				CALL spHRMAddAuthorisationTemp(authId,proID);
				CALL spHRMAddGAuthorisationApproved(authId,proID,"Material Request");
			END IF;
		END IF;
	END IF;

	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_ROLE_ACCESS`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_ROLE_ACCESS`(IN `userId` varchar(255) ,  IN `module` varchar(255))
    DETERMINISTIC
BEGIN
	
	SELECT m.ModuleID 'moduleId' , m.Remarks 'moduleName', m.`Group` 'groupModule', COALESCE(tbl.RM_Delete, 'NO') 'delete', COALESCE(tbl.RM_Edit, 'NO') 'edit', COALESCE(tbl.RM_Export, 'NO') 'export', COALESCE(tbl.RM_Import, 'NO') 'import', COALESCE(tbl.RM_List, 'NO') 'list',COALESCE(tbl.RM_View, 'NO') 'view',COALESCE(tbl.RM_Access, 'NO') 'access' 
	FROM ats_numberprefix m
	LEFT JOIN (SELECT * from ats_role_detail WHERE RM_RoleID=(select u.var_ats_role from ame_user u WHERE u.var_id = userId) AND RM_ModuleID=module) as tbl on tbl.RM_ModuleID = m.ModuleID
	WHERE m.`Status`=1 AND m.ModuleID=module
	ORDER BY m.`Group`;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_ROLE_START_UP`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_ROLE_START_UP`(var_role_id varchar(255))
    DETERMINISTIC
BEGIN
	CALL ats_listSystemModulesByRoleId(var_role_id);
	SELECT * FROM ats_notification WHERE RM_ID = var_role_id;
END |
DELIMITER ;

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

DROP PROCEDURE IF EXISTS `ATS_PRO_user_add`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_user_add`(var_user_id varchar(255), var_user_name varchar(255), var_user_pwd varchar(255),var_status varchar(1),var_is varchar(1), var_role varchar(20),var_mrole varchar(500))
    DETERMINISTIC
BEGIN
	INSERT INTO `tbluser` (`UID`,`UName`,`UPassword`,`UStatus`,`IsOnlyRole`,`UATSRoleID`) 
	VALUES (var_user_id, var_user_name,var_user_pwd,var_status,var_is,var_role);
	INSERT INTO `tbluserapp` (`UID`, `AppID`) VALUES (var_user_id, 'ATS');
	IF var_mrole <> "" THEN
		SET @EXE_SQL = CONCAT("INSERT INTO ats_user_role(`UID`, `RID`) VALUES ",var_mrole,";");
		PREPARE STM FROM @EXE_SQL;
		EXECUTE STM;
		DEALLOCATE PREPARE STM;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ATS_PRO_user_update`;
DELIMITER |
CREATE PROCEDURE `ATS_PRO_user_update`(var_user_id varchar(255), var_user_name varchar(255), var_user_pwd varchar(255),var_status varchar(1),var_is varchar(1), var_role varchar(20),var_mrole varchar(500))
    DETERMINISTIC
BEGIN
	UPDATE `tbluser` SET `UName`=var_user_name,`UStatus`=var_status, `IsOnlyRole`=var_is, `UATSRoleID`=var_role
	WHERE (`UID`=var_user_id);
	DELETE FROM ats_user_role WHERE UID = var_user_id;
	IF var_mrole <> "" THEN
		SET @EXE_SQL = CONCAT("INSERT INTO ats_user_role(`UID`, `RID`) VALUES ",var_mrole,";");
		PREPARE STM FROM @EXE_SQL;
		EXECUTE STM;
		DEALLOCATE PREPARE STM;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ats_role_add`;
DELIMITER |
CREATE PROCEDURE `ats_role_add`(var_role_id varchar(150), var_rolename varchar(255), var_roledes varchar(255), var_status varchar(255), var_userid varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE lastId VARCHAR(255) DEFAULT "";
	SET lastId = ATS_FUN_generateAutoId('RM');
	IF lastId <> '' THEN
		INSERT INTO `ats_role` (`RM_ID`, `RM_Name`, `RM_Des`, `RM_CBy`, `RM_CDate`, `RM_MBy`, `RM_MDate`, `RM_Status`, `RM_Parent`) 
		VALUES (lastId, var_rolename,  var_roledes, var_userid, NOW(), '', NULL, var_status, NULL);
	END IF;
	SELECT lastId as 'MS_ID';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ats_role_update`;
DELIMITER |
CREATE PROCEDURE `ats_role_update`(var_role_id varchar(150), var_rolename varchar(255), var_roledes varchar(255), var_status varchar(255), var_userid varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM ats_role_detail WHERE ats_role_detail.RM_RoleID = var_role_id;
	UPDATE `ats_role` 
	SET `RM_Name`=var_rolename, `RM_Des`=var_roledes, `RM_MBy`=var_userid, `RM_MDate`=NOW(), `RM_Status`=var_status WHERE (`RM_ID`=var_role_id);
END |
DELIMITER ;

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

DROP PROCEDURE IF EXISTS `ats_user_add`;
DELIMITER |
CREATE PROCEDURE `ats_user_add`(var_user_id varchar(255), var_user_name varchar(255), var_user_pwd varchar(255),var_status varchar(1),var_is varchar(1), var_role varchar(20),var_mrole varchar(500),var_empId varchar(255))
    DETERMINISTIC
BEGIN
	INSERT INTO `ame_user` (`ame_user`.`var_id`,`ame_user`.`var_name`,`ame_user`.`var_pwd`,`ame_user`.`tin_inactive`,`ame_user`.`tin_ats_isonlyrole`,`ame_user`.var_ats_role, `ame_user`.`var_empid`) 
	VALUES (var_user_id, var_user_name,var_user_pwd,var_status,var_is,var_role,var_empId);
	INSERT INTO `ame_user_app` (ame_user_app.var_id, ame_user_app.var_appid) VALUES (var_user_id, 'ATS');
	IF var_mrole <> "" THEN
		SET @EXE_SQL = CONCAT("INSERT INTO ats_user_role(`UID`, `RID`) VALUES ",var_mrole,";");
		PREPARE STM FROM @EXE_SQL;
		EXECUTE STM;
		DEALLOCATE PREPARE STM;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `ats_user_update`;
DELIMITER |
CREATE PROCEDURE `ats_user_update`(var_user_id varchar(255), var_user_name varchar(255), var_user_pwd varchar(255),var_status varchar(1),var_is varchar(1), var_role varchar(20),var_mrole varchar(500),var_empId varchar(255))
    DETERMINISTIC
BEGIN
	UPDATE `ame_user` SET `ame_user`.var_name=var_user_name,`ame_user`.tin_inactive=var_status, tin_ats_isonlyrole=var_is, var_ats_role=var_role, var_empid= var_empId
	WHERE (`var_id`=var_user_id);
	DELETE FROM ats_user_role WHERE UID = var_user_id;
	IF var_mrole <> "" THEN
		SET @EXE_SQL = CONCAT("INSERT INTO ats_user_role(`UID`, `RID`) VALUES ",var_mrole,";");
		PREPARE STM FROM @EXE_SQL;
		EXECUTE STM;
		DEALLOCATE PREPARE STM;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `checkChildOfUser`;
DELIMITER |
CREATE PROCEDURE `checkChildOfUser`(IN `username` varchar(50))
    DETERMINISTIC
BEGIN
	
	SELECT COUNT(us.UID) child FROM tbluser us INNER JOIN tbluser pus ON us.UParentID = pus.UID WHERE pus.UName = username;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `Clear_Data`;
DELIMITER |
CREATE PROCEDURE `Clear_Data`()
    DETERMINISTIC
BEGIN
DELETE FROM ame_ap_po;
DELETE FROM ame_ap_po_det;
DELETE FROM ame_ap_in;
DELETE FROM ame_ap_in_det;
DELETE FROM ame_ap_ret;
DELETE FROM ame_ap_ret_det;
DELETE FROM ame_ap_dn;
DELETE FROM ame_ap_dn_det;
DELETE FROM ame_ap_py;
DELETE FROM ame_ap_py_app;
DELETE FROM ame_ap_py_det;
DELETE FROM ame_ar_quo;
DELETE FROM ame_ar_quo_det;
DELETE FROM ame_ar_so;
DELETE FROM ame_ar_so_det;
DELETE FROM ame_ar_in;
DELETE FROM ame_ar_in_det;
DELETE FROM ame_ar_ret;
DELETE FROM ame_ar_ret_det;
DELETE FROM ame_ar_cn;
DELETE FROM ame_ar_cn_det;
DELETE FROM ame_ar_sm;
DELETE FROM ame_ar_sm_det;
DELETE FROM ame_ar_py;
DELETE FROM ame_ar_py_app;
DELETE FROM ame_ar_py_det;
DELETE FROM ame_refund;
DELETE FROM ame_ic_tf;
DELETE FROM ame_ic_tf_det;
DELETE FROM ame_ic_iu;
DELETE FROM ame_ic_iu_det;
DELETE FROM ame_ic_icuom;
DELETE FROM ame_ic_icuom_det;
DELETE FROM ame_ic_ia;
DELETE FROM ame_ic_ia_det;
DELETE FROM ame_ic_ip;
DELETE FROM ame_ic_ip_det;
DELETE FROM ame_sl_ap;
DELETE FROM ame_sl_ap_his;
DELETE FROM ame_sl_ar;
DELETE FROM ame_sl_ar_his;
DELETE FROM ame_sl_ic;
DELETE FROM ame_sl_ic_batch;
DELETE FROM ame_sl_ic_his;
DELETE FROM ame_gl;
DELETE FROM ame_gl_his;
DELETE FROM ame_gl_je;
DELETE FROM ame_gl_je_det;
UPDATE ame_sys_prefix SET int_lastid = 1;
UPDATE ame_sys_prefix_custom SET int_lastid = 1;
DELETE FROM ame_ap_po;
DELETE FROM ame_ap_po_det;
DELETE FROM ame_ap_in;
DELETE FROM ame_ap_in_det;
DELETE FROM ame_ap_ret;
DELETE FROM ame_ap_ret_det;
DELETE FROM ame_ap_dn;
DELETE FROM ame_ap_dn_det;
DELETE FROM ame_ap_py;
DELETE FROM ame_ap_py_app;
DELETE FROM ame_ap_py_det;
DELETE FROM ame_ar_quo;
DELETE FROM ame_ar_quo_det;
DELETE FROM ame_ar_so;
DELETE FROM ame_ar_so_det;
DELETE FROM ame_ar_in;
DELETE FROM ame_ar_in_det;
DELETE FROM ame_ar_ret;
DELETE FROM ame_ar_ret_det;
DELETE FROM ame_ar_cn;
DELETE FROM ame_ar_cn_det;
DELETE FROM ame_ar_sm;
DELETE FROM ame_ar_sm_det;
DELETE FROM ame_ar_py;
DELETE FROM ame_ar_py_app;
DELETE FROM ame_ar_py_det;
DELETE FROM ame_refund;
DELETE FROM ame_ic_tf;
DELETE FROM ame_ic_tf_det;
DELETE FROM ame_ic_iu;
DELETE FROM ame_ic_iu_det;
DELETE FROM ame_ic_icuom;
DELETE FROM ame_ic_icuom_det;
DELETE FROM ame_ic_ia;
DELETE FROM ame_ic_ia_det;
DELETE FROM ame_ic_ip;
DELETE FROM ame_ic_ip_det;
DELETE FROM ame_sl_ap;
DELETE FROM ame_sl_ap_his;
DELETE FROM ame_sl_ar;
DELETE FROM ame_sl_ar_his;
DELETE FROM ame_sl_ic;
DELETE FROM ame_sl_ic_batch;
DELETE FROM ame_sl_ic_his;
DELETE FROM ame_gl;
DELETE FROM ame_gl_his;
DELETE FROM ame_gl_je;
DELETE FROM ame_gl_je_det;
UPDATE ame_sys_prefix SET int_lastid = 1;
UPDATE ame_sys_prefix_custom SET int_lastid = 1;
#Routine body goes here...
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `convertCrmLead`;
DELIMITER |
CREATE PROCEDURE `convertCrmLead`(IN `conFirstName` varchar(50),IN `conLastName` varchar(50),IN `conPhone` varchar(50),IN `conMobile` varchar(50),IN `conEmail` varchar(50),IN `conTitle` varchar(50),IN `conDepartment` varchar(100),IN `conNo` varchar(100),IN `conStreet` varchar(100),IN `conVillage` varchar(100),IN `conCommune` varchar(100),IN `conDistrict` varchar(100),IN `conCity` varchar(100),IN `conState` varchar(100),IN `conCountry` varchar(100),IN `conLeadSource` int,IN `conCBy` varchar(11),IN `conCDate` date,IN `custName` varchar(255),IN `custTel1` varchar(255),IN `custTel2` varchar(255),IN `custFax` varchar(255),IN `custEmail` varchar(255),IN `custWebsite` varchar(255),IN `custAddress` varchar(255),IN `custFacebook` varchar(255),IN `custLine` varchar(255),IN `custViber` varchar(255),IN `custWhatApp` varchar(255),IN `custIndustId` int,IN `custAccountType` int,IN `leadId` varchar(11),IN `leadStatusId` int)
    DETERMINISTIC
BEGIN

	DECLARE custId VARCHAR(255) DEFAULT "";
	
	SET custId = fnGetLastID("CUST");

	INSERT INTO tblcustomer (CustID, CustName, CustTel1, CustTel2, CustFax, CustEmail, CustWebsite, CustAddress, Facebook, Line, Viber, WhatApp, CrmIndustID, CrmAccountTypeID)
	VALUES (custId, custName, custTel1, custTel2, custFax, custEmail, custWebsite, custAddress, custFacebook, custLine, custViber, custWhatApp, custIndustId, custAccountType);
	

	INSERT INTO crm_contact (	CO_ID, 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_LeadSource, CO_CBy,CO_CDate, CO_CustID) 
	VALUES (generateAutoId("CO"), conFirstName, conLastName, conPhone, conMobile, conEmail, conTitle, conDepartment, conNo, conStreet, conVillage, conCommune, conDistrict, conCity, conState,	conCountry, conLeadSource, conCBy, conCDate, custId);
			
	UPDATE crm_lead SET LA_StatusID = leadStatusId WHERE LA_ID = leadId;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmCheckIdlingCustomer`;
DELIMITER |
CREATE PROCEDURE `crmCheckIdlingCustomer`(IN `moduleType` varchar(255),IN `startDate` varchar(255),IN `endDate` varchar(255))
    DETERMINISTIC
BEGIN
	
	IF moduleType = 'Quotation' THEN
		SELECT 
			c.CustID 'custId',
			c.CustName 'custName',
			c.CustAddress 'custAddress',
			c.PriceCode 'priceCode',
			(SELECT pc.Description from tblpricecode pc WHERE pc.PriceCode = c.PriceCode) 'priceDes',
			c.CustGroupID 'groupId',
			(SELECT cg.CustGroupName FROM tblcustomergroup cg WHERE cg.CustGroupID = c.CustGroupID) 'groupName'
		FROM tblcustomer c 
		where c.CustID NOT IN (SELECT DISTINCT q.CustID from tblsbquote q WHERE q.SalID IN (SELECT qu.SalID from tblsbquote qu WHERE DATE(qu.SalDate) BETWEEN DATE(startDate) AND DATE(endDate)));
	ELSE
		SELECT
			c.CustID 'custId',
			c.CustName 'custName',
			c.CustAddress 'custAddress',
			c.PriceCode 'priceCode',
			(SELECT pc.Description from tblpricecode pc WHERE pc.PriceCode = c.PriceCode) 'priceDes',
			c.CustGroupID 'groupId',
			(SELECT cg.CustGroupName FROM tblcustomergroup cg WHERE cg.CustGroupID = c.CustGroupID) 'groupName'
		FROM tblcustomer c 
		where c.CustID NOT IN (SELECT DISTINCT s.CustID from tblsaleorder s WHERE s.SalID IN (SELECT sr.SalID from tblsaleorder sr WHERE DATE(sr.SalDate) BETWEEN DATE(startDate) AND DATE(endDate)));
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmConvertLeadStartup`;
DELIMITER |
CREATE PROCEDURE `crmConvertLeadStartup`(IN `leadId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT CO_ID conID, CO_Salutation conSalutation, CO_FirstName conFirstname, CO_LastName conLastname FROM crm_contact where CO_IsApproved = 1;
	CALL CRM_PRO_USER_LIST_COM(userId);
	SELECT CA_ID campID, CA_Name campName FROM crm_camp;
	SELECT I_ID industID, I_Name industName FROM crm_industry;
	SELECT LST_ID statusID, LST_Name statusName FROM crm_lead_status;
	SELECT LS_ID sourceID, LS_Name sourceName FROM crm_lead_source;
	SELECT COALESCE(var_id,'') 'custGroupId' , COALESCE(var_name,'') 'custGroupName' FROM ame_mt_cus_gro;
	SELECT COALESCE(var_id,'') 'priceCode', COALESCE(var_name,'') 'des' FROM ame_mt_pri_cod;
	CALL CRM_PRO_CUSTOMER_LOAD(userId);
	SELECT AT_ID accountID, AT_Name accountName FROM crm_account_type;
	SELECT OS_ID osId, OS_Name osName FROM crm_opportunity_stage;
	SELECT OT_ID otId, OT_Name otName FROM crm_opportunity_type;
	CALL CRM_PRO_CURRENCY_LOAD();
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmCountAuthorizationByUsername`;
DELIMITER |
CREATE PROCEDURE `crmCountAuthorizationByUsername`(IN `username` varchar(255))
    DETERMINISTIC
BEGIN
SELECT COUNT(*) as count FROM hrm_authorisation_employee
WHERE Emp_ID = (SELECT EmpID FROM tbluseremployee WHERE UID = username)
AND Auth_Process IN ("Customer");
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmCustomerAdvanceInfo`;
DELIMITER |
CREATE PROCEDURE `crmCustomerAdvanceInfo`(IN `custId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
		c.CustID 'custId', 
		c.CustName 'custName' 
	FROM tblcustomer c WHERE c.CustID = custId;

	SELECT 
		ItemID 'itemId', 
		ItemName 'itemName', 
		itemcode 'itemcode' 
	FROM tblitem WHERE ItemID IN (SELECT ci.itemId FROM crm_customer_item ci WHERE ci.custId = custId);

	SELECT 
		csv_id 'id', 
		csv_os 'os', 
		csv_localIP 'localIP', 
		csv_publicIP 'publicIP',
		csv_routerIP 'routerIP',
		csv_username 'svUsername',
		csv_password 'svPassword',
		csv_routerUsername 'routerUsername',
		csv_routerPassword 'routerPassword'
	FROM crm_customer_server WHERE csv_custId = custId;
		
	SELECT
		cd_id 'id',
		cd_type 'deviceType',
		cd_macAddress 'deviceMacAddr',
		DATE_FORMAT(cd_licenseDate,'%d-%b-%Y %h:%i %p') 'licenseDate',
		DATE_FORMAT(cd_expiredDate,'%d-%b-%Y %h:%i %p') 'licenseExpiredDate',
		cd_vpnUsername 'vpnUsername',
		cd_vpnPassword 'vpnPassword',
		cd_other 'other'
	FROM crm_customer_devices WHERE cd_custId = custId;

	SELECT
		s_id 'id',
		s_name 'name',
		s_amount 'amount',
		DATE_FORMAT(s_startDate,'%d-%b-%Y %h:%i %p') 'startDate',
		DATE_FORMAT(s_endDate,'%d-%b-%Y %h:%i %p') 'endDate',
		s_createBy 'createBy',
		(SELECT UName FROM tbluser WHERE UID = s_createBy) 'createByName',
		s_status 'status',
		DATE_FORMAT(s_createDate,'%d-%b-%Y %h:%i %p') 'createDate'
	FROM crm_customer_support WHERE s_custId = custId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmDeleteCustomerService`;
DELIMITER |
CREATE PROCEDURE `crmDeleteCustomerService`(IN `serviceId` int)
    DETERMINISTIC
BEGIN
	DELETE FROM crm_service_details WHERE sv_Id = serviceId;
	DELETE FROM crm_customer_service WHERE sv_Id = serviceId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmDeleteMeeting`;
DELIMITER |
CREATE PROCEDURE `crmDeleteMeeting`(IN `meetId` varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_meeting_audio WHERE M_ID = meetId;
	DELETE FROM crm_meeting_image WHERE M_ID = meetId;
	DELETE FROM crm_meeting WHERE M_ID = meetId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmDeleteMeetingImageAndAudio`;
DELIMITER |
CREATE PROCEDURE `crmDeleteMeetingImageAndAudio`(IN `meetId` varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_meeting_audio WHERE M_ID = meetId;
	DELETE FROM crm_meeting_image WHERE M_ID = meetId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmDeleteModuleRelatedToCampaign`;
DELIMITER |
CREATE PROCEDURE `crmDeleteModuleRelatedToCampaign`(IN `campId` varchar(11))
    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 = (SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = campId); 
	DELETE FROM crm_collaboration_details WHERE crm_collaboration_details.PostID = (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 `crmDeleteModuleRelatedToCase`;
DELIMITER |
CREATE PROCEDURE `crmDeleteModuleRelatedToCase`(IN `caseId` varchar(11))
    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 `crmDeleteModuleRelatedToContact`;
DELIMITER |
CREATE PROCEDURE `crmDeleteModuleRelatedToContact`(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 `crmDeleteModuleRelatedToCustomer`;
DELIMITER |
CREATE PROCEDURE `crmDeleteModuleRelatedToCustomer`(IN `custId` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE countStatus INT DEFAULT 0;
	DECLARE logo VARCHAR(255) DEFAULT "";
	SELECT COUNT(Auth_Status) INTO countStatus from hrm_authorisation_approved WHERE Auth_ProcessID = custId AND Auth_ProcessName = "Customer" AND Auth_Status = "approved";
	SELECT crm_customer.LGT_Logo INTO logo FROM crm_customer WHERE crm_customer.CustID = custId;
	IF countStatus < 1 THEN
		DELETE FROM crm_call WHERE crm_call.CL_RToID = custId;
		DELETE FROM crm_meeting WHERE crm_meeting.M_RToID = custId;
		DELETE FROM crm_task WHERE crm_task.TA_RToID = custId;
		DELETE FROM crm_event WHERE crm_event.EV_RToID = custId;
		DELETE FROM crm_note WHERE crm_note.N_RToID = custId;
		DELETE FROM crm_colllaboration_tags WHERE crm_colllaboration_tags.collapId = (SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = custId); 
		DELETE FROM crm_collaboration_details WHERE crm_collaboration_details.PostID = (SELECT crm_collaboration.CB_ID FROM crm_collaboration WHERE crm_collaboration.CB_RToID = custId);
		DELETE FROM crm_collaboration WHERE crm_collaboration.CB_RToID = custId;
		UPDATE crm_contact SET crm_contact.CO_CustID = NULL WHERE crm_contact.CO_CustID = custId;
		DELETE FROM crm_opportunity WHERE OP_CustID = custId;
		DELETE FROM tblshipaddress WHERE moduleid = custId;
		DELETE FROM crm_customer WHERE crm_customer.CustID = custId;
		DELETE FROM hrm_authorisation_approved WHERE Auth_ProcessID = custId AND Auth_ProcessName = "Customer";
		SELECT countStatus, logo;
	ELSE 
		SELECT countStatus;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmDeleteModuleRelatedToLead`;
DELIMITER |
CREATE PROCEDURE `crmDeleteModuleRelatedToLead`(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 `crmDeleteModuleRelatedToOpportunity`;
DELIMITER |
CREATE PROCEDURE `crmDeleteModuleRelatedToOpportunity`(IN `oppId` varchar(11))
    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 `crmEditOrAddLeadStartup`;
DELIMITER |
CREATE PROCEDURE `crmEditOrAddLeadStartup`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT CA_ID campID, CA_Name campName FROM crm_camp;
	SELECT I_ID industID, I_Name industName FROM crm_industry;
	SELECT LST_ID statusID, LST_Name statusName FROM crm_lead_status;
	SELECT LS_ID sourceID, LS_Name sourceName FROM crm_lead_source;
	CALL crmListSubordinateUserByUsername(userId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmFindRoleById`;
DELIMITER |
CREATE PROCEDURE `crmFindRoleById`(IN `roleId` varchar(255))
    DETERMINISTIC
BEGIN
	
	SELECT 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 = roleId) as tbl  
on tbl.RM_ModuleID = c.ModuleID
where c.Status = 1
;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerAddCity`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerAddCity`(IN gid varchar(200), IN gnamekh varchar(255), IN gnameen varchar(255), IN grefer varchar(255), IN gremark varchar(255),IN gkrung INT(1))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;
	IF id = "" THEN
		SET Message = "Successfuly";
		SET Description = "The city was successful create!";
			INSERT INTO crm_gazetteer (var_id, var_namekh, var_nameen, var_reference, var_remark, tin_province,tin_krung, var_auto) VALUE (gid, gnamekh, gnameen, grefer, gremark, 1, gkrung, crmGazetteerAutos());
		SELECT Message, Description;
	ELSE
		SET Message = "Exist";
		SET Description = CONCAT("The city code ",gid," was exist !");
		SELECT Message, Description;
	END IF;


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerAddCommune`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerAddCommune`(IN userid varchar(255), IN par varchar(200), IN gid varchar(200), IN gnamekh varchar(255), IN gnameen varchar(255), IN grefer varchar(255), IN gremark varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";
	DECLARE auto INT(11) DEFAULT 0;

	-- SET auto = SELECT crmGazetteerAutos();

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;

	IF id = "" THEN
		SET Message = "Successfuly";
		SET Description = "The commune was successful create!";
			INSERT INTO crm_gazetteer (var_parid, var_id, var_namekh, var_nameen, var_reference, var_remark, tin_commune, var_auto) VALUE (par, gid, gnamekh, gnameen, grefer, gremark, 1, crmGazetteerAutos());
		SELECT Message, Description;
	ELSE
		SET Message = "Exist";
		SET Description = CONCAT("The commune code ",gid," was exist !");
		SELECT Message, Description;
	END IF;


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerAddDistrict`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerAddDistrict`(IN userid varchar(255), IN par varchar(200), IN gid varchar(200), IN gnamekh varchar(255), IN gnameen varchar(255), IN grefer varchar(255), IN gremark varchar(255),IN gkrung INT(1))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";
	DECLARE auto INT(11) DEFAULT 0;

	-- SET auto = SELECT crmGazetteerAutos();

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;

	IF id = "" THEN
		SET Message = "Successfuly";
		SET Description = "The district was successful create!";
			INSERT INTO crm_gazetteer (var_parid, var_id, var_namekh, var_nameen, var_reference, var_remark, tin_district, tin_krung, var_auto) VALUE (par, gid, gnamekh, gnameen, grefer, gremark, 1, gkrung, crmGazetteerAutos());
		SELECT Message, Description;
	ELSE
		SET Message = "Exist";
		SET Description = CONCAT("The district code ",gid," was exist !");
		SELECT Message, Description;
	END IF;


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerAddVillage`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerAddVillage`(IN userid varchar(255), IN par varchar(200), IN gid varchar(200), IN gnamekh varchar(255), IN gnameen varchar(255), IN grefer varchar(255), IN gremark varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";
	DECLARE auto INT(11) DEFAULT 0;

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;

	IF id = "" THEN
		SET Message = "Successfuly";
		SET Description = "The village was successful create!";
			INSERT INTO crm_gazetteer (var_parid, var_id, var_namekh, var_nameen, var_reference, var_remark, tin_village, var_auto) VALUE (par, gid, gnamekh, gnameen, grefer, gremark, 1, crmGazetteerAutos());
		SELECT Message, Description;
	ELSE
		SET Message = "Exist";
		SET Description = CONCAT("The village code ",gid," was exist !");
		SELECT Message, Description;
	END IF;


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerDeleteCity`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerDeleteCity`(IN userid varchar(255), IN gid varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE namec VARCHAR(255) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_parid = gid LIMIT 0,1;
	SELECT var_nameen INTO namec FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;
	IF id = "" THEN
		SET Message = "Successfuly";
		SET Description = "The city was successful delete!";
			DELETE FROM crm_gazetteer WHERE var_id = gid AND tin_province = 1;
		SELECT Message, Description;
	ELSE
		SET Message = "Used";
		SET Description = CONCAT("The city code ",gid,": ",namec ," was used !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerDeleteCommune`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerDeleteCommune`(IN userid varchar(255), IN gid varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE namec VARCHAR(255) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_parid = gid LIMIT 0,1;
	SELECT var_nameen INTO namec FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;
	IF id = "" THEN
		SET Message = "Successfuly";
		SET Description = "The commune was successful delete!";
			DELETE FROM crm_gazetteer WHERE var_id = gid AND tin_commune = 1;
		SELECT Message, Description;
	ELSE
		SET Message = "Used";
		SET Description = CONCAT("The commune code ",gid,": ",namec ," was used !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerDeleteDistrict`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerDeleteDistrict`(IN userid varchar(255), IN gid varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE namec VARCHAR(255) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_parid = gid LIMIT 0,1;
	SELECT var_nameen INTO namec FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;
	IF id = "" THEN
		SET Message = "Successfuly";
		SET Description = "The district was successful delete!";
			DELETE FROM crm_gazetteer WHERE var_id = gid AND tin_district = 1;
		SELECT Message, Description;
	ELSE
		SET Message = "Used";
		SET Description = CONCAT("The district code ",gid,": ",namec ," was used !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerDeleteVillage`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerDeleteVillage`(IN userid varchar(255), IN gid varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE namec VARCHAR(255) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_parid = gid LIMIT 0,1;
	SELECT var_nameen INTO namec FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;
	IF id = "" THEN
		SET Message = "Successfuly";
		SET Description = "The village was successful delete!";
			DELETE FROM crm_gazetteer WHERE var_id = gid AND tin_village = 1;
		SELECT Message, Description;
	ELSE
		SET Message = "Used";
		SET Description = CONCAT("The village code ",gid,": ",namec ," was used !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerGetCity`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerGetCity`(IN userid varchar(255), IN gid varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;
	IF id <> "" THEN
		SET Message = "Successfuly";
		SET Description = "The city was successful get!";
			SELECT var_id, var_nameen, var_namekh, COALESCE(var_reference,"") "var_reference", COALESCE(var_remark,"") "var_remark", COALESCE(tin_krung,0) 'krung' FROM crm_gazetteer WHERE var_id = gid AND tin_province = 1;
		SELECT Message, Description;
	ELSE
		SET Message = "Fail";
		SET Description = CONCAT("The city code ",gid," was fail !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerGetCommune`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerGetCommune`(IN userid varchar(255),IN vid varchar(255), IN gid varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;
	IF id <> "" THEN
		SET Message = "Successfuly";
		SET Description = "The commune was successful get!";
			SELECT var_id, COALESCE(var_parid,"") "var_parid", var_nameen, var_namekh, COALESCE(var_reference,"") "var_reference", COALESCE(var_remark,"") "var_remark",COALESCE(var_auto,0) "var_auto" FROM crm_gazetteer WHERE var_id = gid AND var_parid = vid AND tin_commune = 1;
		SELECT Message, Description;
	ELSE
		SET Message = "Fail";
		SET Description = CONCAT("The commune code ",gid," was fail !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerGetDistrict`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerGetDistrict`(IN userid varchar(255),IN vid varchar(255), IN gid varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;
	IF id <> "" THEN
		SET Message = "Successfuly";
		SET Description = "The district was successful get!";
			SELECT var_id, COALESCE(var_parid,"") "var_parid", var_nameen, var_namekh, COALESCE(var_reference,"") "var_reference", COALESCE(var_remark,"") "var_remark", COALESCE(tin_krung,0) 'krung',COALESCE(var_auto,0) "var_auto" FROM crm_gazetteer WHERE var_id = gid AND var_parid = vid AND tin_district = 1;
		SELECT Message, Description;
	ELSE
		SET Message = "Fail";
		SET Description = CONCAT("The district code ",gid," was fail !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerGetVillage`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerGetVillage`(IN userid varchar(255),IN vid varchar(255), IN gid varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_id = gid LIMIT 0,1;
	IF id <> "" THEN
		SET Message = "Successfuly";
		SET Description = "The village was successful get!";
			SELECT var_id, COALESCE(var_parid,"") "var_parid", var_nameen, var_namekh, COALESCE(var_reference,"") "var_reference", COALESCE(var_remark,"") "var_remark",COALESCE(var_auto,0) "var_auto" FROM crm_gazetteer WHERE var_id = gid AND var_parid = vid AND tin_village = 1;
		SELECT Message, Description;
	ELSE
		SET Message = "Fail";
		SET Description = CONCAT("The village code ",gid," was fail !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerListCity`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerListCity`()
    DETERMINISTIC
BEGIN

	SELECT  var_id as "code", COALESCE(var_namekh,"") as "namekh", COALESCE(var_nameen,"") as 'nameen', COALESCE(var_reference,"") as 'var_reference',
 COALESCE(var_remark,"") as "var_remark", COALESCE(tin_krung,0) 'krung' FROM crm_gazetteer WHERE tin_province = 1 ORDER BY var_id DESC;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerListCommune`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerListCommune`(IN userid varchar(255), IN city varchar(255), IN dris varchar(255))
    DETERMINISTIC
BEGIN

	SELECT  var_id as "code", COALESCE(var_namekh,"") as "namekh", 
	COALESCE(var_nameen,"") as 'nameen', COALESCE(var_reference,"") as 'var_reference',
	COALESCE(var_remark,"") as "var_remark", COALESCE(var_parid,"") as "parent", COALESCE(var_auto,0) "var_auto" FROM crm_gazetteer 
	WHERE var_parid = dris AND tin_commune = 1 ORDER BY var_id DESC;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerListDistrict`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerListDistrict`(IN userid varchar(255), IN gid varchar(255))
    DETERMINISTIC
BEGIN

	SELECT  var_id as "code", COALESCE(var_namekh,"") as "namekh", COALESCE(var_nameen,"") as 'nameen', COALESCE(tin_province,0) "tin_province", COALESCE(var_auto,0) "var_auto" FROM crm_gazetteer    WHERE var_id = gid AND tin_province  = 1;

	SELECT  var_id as "code", COALESCE(var_namekh,"") as "namekh", 
	COALESCE(var_nameen,"") as 'nameen', COALESCE(var_reference,"") as 'var_reference',
	COALESCE(var_remark,"") as "var_remark", COALESCE(var_parid,"") as "parent", COALESCE(var_auto,0) "var_auto",COALESCE(tin_krung,0) "tin_province"  FROM crm_gazetteer 
	WHERE var_parid = gid AND tin_district = 1 ORDER BY var_id DESC;



END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerListVillage`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerListVillage`(IN userid varchar(255), IN city varchar(255), IN dris varchar(255))
    DETERMINISTIC
BEGIN

	SELECT  var_id as "code", COALESCE(var_namekh,"") as "namekh", 
	COALESCE(var_nameen,"") as 'nameen', COALESCE(var_reference,"") as 'var_reference',
	COALESCE(var_remark,"") as "var_remark", COALESCE(var_parid,"") as "parent", COALESCE(var_auto,0) "var_auto" FROM crm_gazetteer 
	WHERE var_parid = dris AND tin_village = 1 ORDER BY var_id DESC;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerUpdatDistrict`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerUpdatDistrict`(IN userid varchar(255), IN par varchar(200),  IN gid varchar(200), IN gnamekh varchar(255), IN gnameen varchar(255), IN grefer varchar(255), IN gremark varchar(255),IN gkrung INT(1), IN auto INT(11))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE ids VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_auto = auto;

	IF id <> "" THEN
		
		SELECT var_id INTO ids FROM crm_gazetteer WHERE var_id = gid AND var_auto <> auto; 
		IF ids = "" THEN
			SET Message = "Successfuly";
			SET Description = "The district was successful Update!";
			UPDATE crm_gazetteer SET var_parid = par, var_id = gid,var_nameen = gnameen, var_namekh = gnamekh, var_reference = grefer, var_remark = gremark, tin_krung = gkrung WHERE var_auto = auto AND tin_district = 1;
			SELECT Message, Description;
		ELSE
			SET Message = "Exist";
			SET Description = CONCAT("The district code ",gid," was exist !");
			SELECT Message, Description;
		END IF;
	ELSE
		SET Message = "Fail";
		SET Description = CONCAT("The district code ",gid," was fail !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerUpdateCity`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerUpdateCity`(IN userid varchar(255), IN gid varchar(200), IN gnamekh varchar(255), IN gnameen varchar(255), IN grefer varchar(255), IN gremark varchar(255),IN gkrung INT(1))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_id = gid AND tin_province = 1;

	IF id <> "" THEN
		SET Message = "Successfuly";
		SET Description = "The city was successful Update!";
		UPDATE crm_gazetteer SET var_nameen = gnameen, var_namekh = gnamekh, var_reference = grefer, var_remark = gremark, tin_krung = gkrung WHERE var_id = gid AND tin_province = 1;
		SELECT Message, Description;
	ELSE
		SET Message = "Fail";
		SET Description = CONCAT("The city code ",gid," was fail !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerUpdateCommune`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerUpdateCommune`(IN userid varchar(255), IN par varchar(200),  IN gid varchar(200), IN gnamekh varchar(255), IN gnameen varchar(255), IN grefer varchar(255), IN gremark varchar(255), IN auto INT(11))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE ids VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_auto = auto;

	IF id <> "" THEN
		
		SELECT var_id INTO ids FROM crm_gazetteer WHERE var_id = gid AND var_auto <> auto; 
		IF ids = "" THEN
			SET Message = "Successfuly";
			SET Description = "The commune was successful Update!";
			UPDATE crm_gazetteer SET var_parid = par, var_id = gid,var_nameen = gnameen, var_namekh = gnamekh, var_reference = grefer, var_remark = gremark WHERE var_auto = auto AND tin_commune = 1 ;
			SELECT Message, Description;
		ELSE
			SET Message = "Exist";
			SET Description = CONCAT("The commune code ",gid," was exist !");
			SELECT Message, Description;
		END IF;
	ELSE
		SET Message = "Fail";
		SET Description = CONCAT("The commune code ",gid," was fail !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGazetteerUpdateVillage`;
DELIMITER |
CREATE PROCEDURE `crmGazetteerUpdateVillage`(IN userid varchar(255), IN par varchar(200),  IN gid varchar(200), IN gnamekh varchar(255), IN gnameen varchar(255), IN grefer varchar(255), IN gremark varchar(255), IN auto INT(11))
    DETERMINISTIC
BEGIN
	
	DECLARE id VARCHAR(100) DEFAULT "";
	DECLARE ids VARCHAR(100) DEFAULT "";
	DECLARE Message VARCHAR(200) DEFAULT "";
	DECLARE Description VARCHAR(200) DEFAULT "";

	SELECT var_id INTO id FROM crm_gazetteer WHERE var_auto = auto;

	IF id <> "" THEN
		
		SELECT var_id INTO ids FROM crm_gazetteer WHERE var_id = gid AND var_auto <> auto; 
		IF ids = "" THEN
			SET Message = "Successfuly";
			SET Description = "The village was successful Update!";
			UPDATE crm_gazetteer SET var_parid = par, var_id = gid,var_nameen = gnameen, var_namekh = gnamekh, var_reference = grefer, var_remark = gremark WHERE var_auto = auto AND tin_village = 1 ;
			SELECT Message, Description;
		ELSE
			SET Message = "Exist";
			SET Description = CONCAT("The village code ",gid," was exist !");
			SELECT Message, Description;
		END IF;
	ELSE
		SET Message = "Fail";
		SET Description = CONCAT("The village code ",gid," was fail !");
		SELECT Message, Description;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGetAuthorisationApproveEmpID`;
DELIMITER |
CREATE PROCEDURE `crmGetAuthorisationApproveEmpID`(IN UserID varchar(255), IN SStatus varchar(255), IN SProcessName varchar(255),IN fDate varchar(255), IN tDate varchar(255))
    DETERMINISTIC
BEGIN
DECLARE SID VARCHAR(255) DEFAULT('');
SELECT EmpID INTO SID FROM tbluseremployee WHERE UID = UserID;
SELECT DISTINCT(al.Auth_ProcessID), al.Auth_ProcessName, al.Auth_ID, al.Auth_GroupID, al.Auth_EmpID,
al.Auth_Status, fnHRMCheckAuthorisationGroupApproved(al.Auth_ProcessID,al.Auth_ProcessName, al.Auth_ID, al.Auth_GroupID) as "Auth_Edit", al.Auth_Date, al.EmpID, COALESCE(al.EmpName, '') AS 'EmpName',
COALESCE(al.EmpEmail, '') AS 'EmpEmail', COALESCE(al.Emp_CompanyEmail, '') AS 'Emp_CompanyEmail',
COALESCE(al.Position, '') AS 'Position', COALESCE(al.PositionKhmer, '') AS 'PositionKhmer',
COALESCE(al.Position_Level, '') AS 'Position_Level', COALESCE(al.UName, '') AS 'UName',
COALESCE(al.Auth_ProcessEmpID, '') AS 'Auth_ProcessEmpID', CONCAT('',COALESCE(e.EmpName, '')) AS 'Auth_ProcessEmpName',
fnHRMCheckAuthorisationApproved(al.Auth_ProcessID, al.Auth_ProcessName, al.Auth_ID) AS 'Auth_AmountApproved',
fnHRMCheckAuthorisationApprove(al.Auth_ProcessID, al.Auth_ProcessName, al.Auth_ID) AS 'Auth_AmountApprove',
auth.Auth_ID,auth.Auth_Name,auth.Auth_Type,auth.Auth_AndOr,
COALESCE(
(SELECT IF(LOWER(ad.Auth_GroupAndOr) = 'and', ad.Auth_GroupAmount, 1)
FROM hrm_authorisation_detail_temp ad
WHERE ad.Auth_TranID = al.Auth_ProcessID AND ad.Auth_ID = al.Auth_ID AND ad.Auth_GroupID = al.Auth_GroupID LIMIT 0,1),"") AS "Auth_Amount",
Auth_TranStatus,
ameAuthDescApproval(al.Auth_ProcessName,al.Auth_ProcessID) AS "Auth_Desc",
ameAuthGetCustomerName(al.Auth_ProcessName,al.Auth_ProcessID) AS "Auth_Customer"
FROM(
SELECT Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status, 1 AS 'Auth_Edit', Auth_Date,
IF(Auth_ProcessName='Customer', uemp.EmpID,
IF(Auth_ProcessName='Sale Order', sa.EmpID,
IF(Auth_ProcessName='Quote', qu.EmpID,
IF(Auth_ProcessName='Material Request', mr.RequestedBy,
IF(Auth_ProcessName="Budget Requisition", br.EmpID,
IF(Auth_ProcessName="General Requisition", gr.EmpID,
IF(Auth_ProcessName='Temporary Credit', ciemp.EmpID,
IF(Auth_ProcessName='Over Due Date', odd.EmpID,'')))))))) AS 'Auth_ProcessEmpID',
IF(Auth_ProcessName='Customer', IF(cust.CrmApproval = 0, "requested", IF(cust.CrmApproval = 1, "approved", "rejected")),
IF(Auth_ProcessName='Sale Order', sa.ApproveStatus,
IF(Auth_ProcessName='Quote', qu.ApproveStatus,
IF(Auth_ProcessName="Budget Requisition", br.ApprovalStatus,
IF(Auth_ProcessName="General Requisition", gr.ApprovalStatus,
IF(Auth_ProcessName='Temporary Credit', ci.`Status`,
IF(Auth_ProcessName='Material Request', mr.`Status`,
IF(Auth_ProcessName='Over Due Date', co.`Status`,'')))))))) AS 'Auth_TranStatus'
,e.EmpID,e.EmpName,e.EmpEmail,e.Emp_CompanyEmail,COALESCE(e.EmpPosition, '') AS 'Position', COALESCE(e.EmpPositionKh, '') AS 'PositionKhmer', COALESCE(e.Emp_PositionLevel) AS 'Position_Level',u.UName
FROM hrm_authorisation_approved ap
LEFT JOIN tblmaterialrequest mr ON ap.Auth_ProcessID = mr.EntryNo
LEFT JOIN crm_customer cust ON ap.Auth_ProcessID = cust.CustID
LEFT JOIN tblcustomerissue ci ON ci.IssueID = ap.Auth_ProcessID
LEFT JOIN tbluseremployee uemp ON uemp.UID = cust.CBy
LEFT JOIN tblsaleorder sa ON ap.Auth_ProcessID = sa.SalID
LEFT JOIN tblsbquote qu ON ap.Auth_ProcessID = qu.SalID
LEFT JOIN crm_frm_general gr ON ap.Auth_ProcessID = gr.FrmID
LEFT JOIN crm_frm_budget br ON ap.Auth_ProcessID = br.FrmID
LEFT JOIN tblcustomeroverdue co ON ap.Auth_ProcessID = co.IssueID
LEFT JOIN tbluseremployee odd ON (odd.UID = co.CreateBy)
LEFT JOIN tbluseremployee ciemp ON (ciemp.UID = ci.CreateBy)
INNER JOIN tblemployee e ON ap.Auth_EmpID = e.EmpID
LEFT JOIN tbluseremployee ue ON(ue.EmpID = e.EmpID)
LEFT JOIN tbluser u ON(u.UID = ue.UID)
WHERE ap.Auth_EmpID = SID
AND IF(fDate <> "" && tDate <> "", ap.Auth_Date BETWEEN fDate AND tDate, true)
) al
INNER JOIN hrm_authorisation_module m ON(LOWER(m.AM_ID) = LOWER(al.Auth_ProcessName) AND LOWER(m.AM_APP) = 'crm')
INNER JOIN tblemployee e ON e.EmpID = al.Auth_ProcessEmpID
LEFT JOIN tbluseremployee ue ON (ue.EmpID = e.EmpID)
LEFT JOIN tbluser u ON (u.UID = ue.UID)
LEFT JOIN hrm_authorisation auth ON (auth.Auth_ID = al.Auth_ID)
WHERE if(LOWER(SStatus) = "all" && LOWER(SProcessName) = "all",
TRUE,
if(LOWER(SStatus) = "all" && LOWER(SProcessName) <> "all",
LOWER(Auth_ProcessName) = LOWER(SProcessName),
if(LOWER(SStatus) <> "all" && LOWER(SProcessName) <> "all",
LOWER(Auth_TranStatus) = LOWER(SStatus) AND LOWER(Auth_ProcessName) = LOWER(SProcessName),
if(LOWER(SStatus) <> "all" && LOWER(SProcessName) = "all",
LOWER(Auth_TranStatus) = LOWER(SStatus),
TRUE))))
ORDER BY IF(SProcessName = 'all', Auth_ProcessName, TRUE), FIELD(LOWER(Auth_TranStatus), 'requested', 'approved', 'rejected', ''),al.Auth_Date DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGetAuthorisationProcess`;
DELIMITER |
CREATE PROCEDURE `crmGetAuthorisationProcess`()
    DETERMINISTIC
BEGIN
		
	SELECT AM_ID FROM hrm_authorisation_module WHERE LOWER(AM_APP) = 'crm'; 

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGetCheckAuthorisationApprove`;
DELIMITER |
CREATE PROCEDURE `crmGetCheckAuthorisationApprove`(IN UserID varchar(255), authProcessID varchar(255), authProcessName varchar(255), authID varchar(255), authGroupID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE SID VARCHAR(255) DEFAULT('');

	SELECT EmpID INTO SID FROM tbluseremployee WHERE UID = UserID;

	if authGroupID = 'a' THEN
		SET authGroupID = '';
	END IF;

	SELECT DISTINCT(al.Auth_ProcessID), al.Auth_ProcessName, al.Auth_ID, al.Auth_GroupID, al.Auth_EmpID,
 al.Auth_Status, al.Auth_Edit, al.Auth_Date, al.EmpID, COALESCE(al.EmpName, '') AS 'EmpName',
 COALESCE(al.EmpEmail, '') AS 'EmpEmail', COALESCE(al.Emp_CompanyEmail, '') AS 'Emp_CompanyEmail',
 COALESCE(al.Position, '') AS 'Position', COALESCE(al.PositionKhmer, '') AS 'PositionKhmer',
 COALESCE(al.Position_Level, '') AS 'Position_Level', COALESCE(al.UName, '') AS 'UName',
 COALESCE(al.Auth_ProcessEmpID, '') AS 'Auth_ProcessEmpID', CONCAT('',COALESCE(e.EmpName, '')) AS 'Auth_ProcessEmpName',
 fnHRMCheckAuthorisationApproved(al.Auth_ProcessID, al.Auth_ProcessName, al.Auth_ID) AS 'Auth_AmountApproved',
 fnHRMCheckAuthorisationApprove(al.Auth_ProcessID, al.Auth_ProcessName, al.Auth_ID) AS 'Auth_AmountApprove',
 auth.Auth_ID,auth.Auth_Name,auth.Auth_Type,auth.Auth_AndOr,auth.Auth_Amount, Auth_TranStatus 

	FROM(

	SELECT Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status, 1 AS 'Auth_Edit', Auth_Date,
		IF(Auth_ProcessName='Customer', uemp.EmpID,
		IF(Auth_ProcessName='Sale Order', sa.EmpID,
		IF(Auth_ProcessName='Quote', qu.EmpID,
		IF(Auth_ProcessName="Budget Requisition", br.EmpID,
		IF(Auth_ProcessName="General Requisition", gr.EmpID,
		IF(Auth_ProcessName="Material Request", mr.`RequestedBy`,
    IF(Auth_ProcessName="Expense Request", er.`RequestedBy`,
		IF(Auth_ProcessName="Logistic Material Request",lm.`RequestedBy`,
	  IF(Auth_ProcessName="Logistic Expense Request",le.`RequestedBy`,
		IF(Auth_ProcessName='Temporary Credit', ciemp.EmpID,
		IF(Auth_ProcessName='Over Due Date', odd.EmpID,''))))))))))) AS 'Auth_ProcessEmpID',

		IF(Auth_ProcessName='Customer', IF(cust.CrmApproval = 0, "requested", IF(cust.CrmApproval = 1, "approved", "rejected")),
		IF(Auth_ProcessName='Sale Order', sa.ApproveStatus,
		IF(Auth_ProcessName='Quote', qu.ApproveStatus,
		IF(Auth_ProcessName='Temporary Credit', ci.`Status`,
		IF(Auth_ProcessName="Material Request",mr.RequestedBy,
    IF(Auth_ProcessName="Expense Request",er.RequestedBy,
		IF(Auth_ProcessName="Budget Requisition", br.ApprovalStatus,
		IF(Auth_ProcessName="General Requisition", gr.ApprovalStatus,
		IF(Auth_ProcessName="Logistic Material Request",lm.RequestedBy,
	  IF(Auth_ProcessName="Logistic Expense Request",le.RequestedBy,
		IF(Auth_ProcessName='Over Due Date', co.`Status`,''))))))))))) AS 'Auth_TranStatus'

		,e.EmpID,e.EmpName,e.EmpEmail,e.Emp_CompanyEmail,COALESCE(e.EmpPosition, '') AS 'Position', COALESCE(e.EmpPositionKh, '') AS 'PositionKhmer', COALESCE(e.Emp_PositionLevel) AS 'Position_Level',u.UName
		FROM hrm_authorisation_approved ap
		LEFT JOIN crm_customer cust ON ap.Auth_ProcessID = cust.CustID
		LEFT JOIN tblcustomerissue ci ON ci.IssueID = ap.Auth_ProcessID
		LEFT JOIN tbluseremployee uemp ON uemp.UID = cust.CBy
		LEFT JOIN tblsaleorder sa ON ap.Auth_ProcessID = sa.SalID
		LEFT JOIN tblsbquote qu ON ap.Auth_ProcessID = qu.SalID
		LEFT JOIN crm_frm_general gr ON ap.Auth_ProcessID = gr.FrmID
		LEFT JOIN crm_frm_budget br ON ap.Auth_ProcessID = br.FrmID
		LEFT JOIN tblmaterialrequest mr ON ap.Auth_ProcessID = mr.EntryNo
		LEFT JOIN tblexpenserequest er ON ap.Auth_ProcessID = er.EntryNo
		LEFT JOIN logistic_material lm ON ap.Auth_ProcessID = lm.EntryNo
		LEFT JOIN logistic_expense_request le ON ap.Auth_ProcessID = le.EntryNo

		LEFT JOIN tblcustomeroverdue co ON ap.Auth_ProcessID = co.IssueID
		LEFT JOIN tbluseremployee odd ON (odd.UID = co.CreateBy)

    LEFT JOIN tbluseremployee ciemp ON (ciemp.UID = ci.CreateBy)
		INNER JOIN tblemployee e ON ap.Auth_EmpID = e.EmpID
		LEFT JOIN tbluseremployee ue ON(ue.EmpID = e.EmpID)
		LEFT JOIN tbluser u ON(u.UID = ue.UID)
		WHERE ap.Auth_EmpID = SID 
	AND ap.Auth_ProcessID = authProcessID 
	AND ap.Auth_ProcessName = authProcessName AND ap.Auth_ID = authID AND ap.Auth_GroupID = authGroupID

	) al
	INNER JOIN hrm_authorisation_module m ON(LOWER(m.AM_ID) = LOWER(al.Auth_ProcessName) AND LOWER(m.AM_APP) = 'ame')
	INNER JOIN tblemployee e ON e.EmpID = al.Auth_ProcessEmpID
	LEFT JOIN tbluseremployee ue ON (ue.EmpID = e.EmpID)
	LEFT JOIN tbluser u ON (u.UID = ue.UID)
	LEFT JOIN hrm_authorisation auth ON (auth.Auth_ID = al.Auth_ID)
	ORDER BY Auth_ProcessName,Auth_TranStatus DESC,
					 al.Auth_Edit DESC, FIELD(al.Auth_Status, 'requested', 'approved', 'rejected', '');
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGetCustomerID`;
DELIMITER |
CREATE PROCEDURE `crmGetCustomerID`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckU VARCHAR(255) DEFAULT("");
	DECLARE SYear INT DEFAULT(0);
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");
	SELECT UType INTO CheckU FROM tbluser WHERE UID = userid;
	SELECT Auth_ID INTO SAuthID FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID LIMIT 1;
	
	IF CheckU = "ESS" THEN
		SELECT CustID,CustName,CustContactName,CustTel1,CustTel2,CustFax,CustEmail,CustWebsite,CustAddress,CustGroupID,PriceCode,Feedback,LocationID,Facebook,Line,Viber,WhatApp,AID,CrmLeadSource,CrmApproval,CrmImageName,CreateFrom,ImagePath,(SELECT ci.i_name FROM crm_industry ci WHERE ci.i_id = c.CrmIndustID) "CrmIndustID",(SELECT ca.at_name FROM crm_account_type ca WHERE ca.at_id = c.CrmAccountTypeID) "CrmAccountTypeID",LGT_Logo FROM crm_customer c WHERE CustID = ID ;
		
		SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount, fnHRMCheckAuthorisationApproved(ID, 'Customer', SAuthID) AS 'Auth_Approved' FROM hrm_authorisation_temp a WHERE a.Auth_ID = SAuthID AND a.Auth_TranID = ID;

		SELECT a.Auth_ID,a.Auth_EmpID,a.Auth_GroupID,a.Auth_GroupAndOr,a.Auth_GroupAmount,
		b.EmpID,b.EmpName,b.EmpEmail,b.Emp_CompanyEmail,COALESCE(b.EmpPosition, '') AS 'Position', COALESCE(b.EmpPositionKh, '') AS 'PositionKhmer', COALESCE(b.Emp_PositionLevel) AS 'Position_Level',u.UName,app.Auth_Status 
		FROM hrm_authorisation_detail_temp a
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Customer" AND a.Auth_EmpID = app.Auth_EmpID AND a.Auth_GroupID = app.Auth_GroupID AND a.Auth_TranID = app.Auth_ProcessID)
		LEFT JOIN tblemployee b ON(a.Auth_EmpID = b.EmpID) 
		LEFT JOIN (SELECT UID,EmpID FROM tbluseremployee GROUP BY EmpID) ue ON(ue.EmpID = b.EmpID)
		LEFT JOIN tbluser u ON(u.UID = ue.UID) 
		WHERE a.Auth_TranID = ID AND a.Auth_ID = SAuthID;

		SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description,d.Auth_GroupID,COALESCE(d.Auth_GroupAndOr,"") as "Auth_GroupAndOr",COALESCE(d.Auth_GroupAmount,"") as "AuthGroup_Amount",(SELECT COUNT(ds.AuthGroup_ID) FROM hrm_authorisation_group_detail_temp ds WHERE ds.AuthGroup_ID = a.AuthGroup_ID AND ds.Auth_TranID = ID) as 'Count'
		,(SELECT COUNT(ds.Auth_GroupID) FROM hrm_authorisation_approved ds WHERE ds.Auth_ProcessID = ID AND ds.Auth_GroupID = a.AuthGroup_ID AND ds.Auth_ID = SAuthID AND ds.Auth_Status = "approved") AS 'AuthGroup_Approved'
		FROM hrm_authorisation_group_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(d.Auth_GroupID = a.AuthGroup_ID AND d.Auth_ID = SAuthID AND a.Auth_TranID = ID)
		WHERE a.Auth_TranID = ID
		ORDER BY a.AuthGroup_ID DESC;

		SELECT a.AuthGroup_ID,a.AuthGroup_EmpID,
		b.EmpID,b.EmpName,b.EmpEmail,b.Emp_CompanyEmail,COALESCE(b.EmpPosition, '') AS 'Position', COALESCE(b.EmpPositionKh, '') AS 'PositionKhmer', COALESCE(b.Emp_PositionLevel) AS 'Position_Level',u.UName,app.Auth_Status 
		FROM hrm_authorisation_group_detail_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(a.AuthGroup_ID = d.Auth_GroupID AND d.Auth_ID = SAuthID AND a.Auth_TranID = d.Auth_TranID)
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_GroupID = a.AuthGroup_ID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Customer" AND app.Auth_EmpID = a.AuthGroup_EmpID)
		LEFT JOIN tblemployee b ON(a.AuthGroup_EmpID = b.EmpID) 
		LEFT JOIN (SELECT UID,EmpID FROM tbluseremployee GROUP BY EmpID) ue ON(ue.EmpID = b.EmpID)
		LEFT JOIN tbluser u ON(u.UID = ue.UID) 
		WHERE a.Auth_TranID = ID AND d.Auth_ID = SAuthID
		ORDER BY a.AuthGroup_EmpID, a.AuthGroup_ID;

	ELSE
		SELECT CustID,CustName,CustContactName,CustTel1,CustTel2,CustFax,CustEmail,CustWebsite,CustAddress,CustGroupID,PriceCode,Feedback,LocationID,Facebook,Line,Viber,WhatApp,AID,CrmLeadSource,CrmApproval,CrmImageName,CreateFrom,ImagePath,(SELECT ci.i_name FROM crm_industry ci WHERE ci.i_id = c.CrmIndustID) "CrmIndustID",(SELECT ca.at_name FROM crm_account_type ca WHERE ca.at_id = c.CrmAccountTypeID) "CrmAccountTypeID",LGT_Logo FROM crm_customer c WHERE CustID = ID ;
		
		SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount, fnHRMCheckAuthorisationApproved(ID, 'Customer', SAuthID) AS 'Auth_Approved' FROM hrm_authorisation_temp a WHERE a.Auth_ID = SAuthID AND a.Auth_TranID = ID;

		SELECT a.Auth_ID,a.Auth_EmpID,a.Auth_GroupID,a.Auth_GroupAndOr,a.Auth_GroupAmount,
		b.EmpID,b.EmpName,b.EmpEmail,b.Emp_CompanyEmail,COALESCE(b.EmpPosition, '') AS 'Position', COALESCE(b.EmpPositionKh, '') AS 'PositionKhmer', COALESCE(b.Emp_PositionLevel) AS 'Position_Level',u.UName,app.Auth_Status 
		FROM hrm_authorisation_detail_temp a
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Customer" AND a.Auth_EmpID = app.Auth_EmpID AND a.Auth_GroupID = app.Auth_GroupID AND a.Auth_TranID = app.Auth_ProcessID)
		LEFT JOIN tblemployee b ON(a.Auth_EmpID = b.EmpID) 
		LEFT JOIN (SELECT UID,EmpID FROM tbluseremployee GROUP BY EmpID) ue ON(ue.EmpID = b.EmpID)
		LEFT JOIN tbluser u ON(u.UID = ue.UID) 
		WHERE a.Auth_TranID = ID AND a.Auth_ID = SAuthID;

		SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description,d.Auth_GroupID,COALESCE(d.Auth_GroupAndOr,"") as "Auth_GroupAndOr",COALESCE(d.Auth_GroupAmount,"") as "AuthGroup_Amount",(SELECT COUNT(ds.AuthGroup_ID) FROM hrm_authorisation_group_detail_temp ds WHERE ds.AuthGroup_ID = a.AuthGroup_ID AND ds.Auth_TranID = ID) as 'Count'
		,(SELECT COUNT(ds.Auth_GroupID) FROM hrm_authorisation_approved ds WHERE ds.Auth_ProcessID = ID AND ds.Auth_GroupID = a.AuthGroup_ID AND ds.Auth_ID = SAuthID AND ds.Auth_Status = "approved") AS 'AuthGroup_Approved'
		FROM hrm_authorisation_group_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(d.Auth_GroupID = a.AuthGroup_ID AND d.Auth_ID = SAuthID AND a.Auth_TranID = ID)
		WHERE a.Auth_TranID = ID
		ORDER BY a.AuthGroup_ID DESC;

		SELECT a.AuthGroup_ID,a.AuthGroup_EmpID,
		b.EmpID,b.EmpName,b.EmpEmail,b.Emp_CompanyEmail,COALESCE(b.EmpPosition, '') AS 'Position', COALESCE(b.EmpPositionKh, '') AS 'PositionKhmer', COALESCE(b.Emp_PositionLevel) AS 'Position_Level',u.UName,app.Auth_Status 
		FROM hrm_authorisation_group_detail_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(a.AuthGroup_ID = d.Auth_GroupID AND d.Auth_ID = SAuthID AND a.Auth_TranID = d.Auth_TranID)
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_GroupID = a.AuthGroup_ID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Customer" AND app.Auth_EmpID = a.AuthGroup_EmpID)
		LEFT JOIN tblemployee b ON(a.AuthGroup_EmpID = b.EmpID) 
		LEFT JOIN (SELECT UID,EmpID FROM tbluseremployee GROUP BY EmpID) ue ON(ue.EmpID = b.EmpID)
		LEFT JOIN tbluser u ON(u.UID = ue.UID) 
		WHERE a.Auth_TranID = ID AND d.Auth_ID = SAuthID
		ORDER BY a.AuthGroup_EmpID, a.AuthGroup_ID;

	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGetOpportunityStage`;
DELIMITER |
CREATE PROCEDURE `crmGetOpportunityStage`()
    DETERMINISTIC
BEGIN
SELECT OS_ID, OS_Name FROM crm_opportunity_stage;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmGetTranNameApproval`;
DELIMITER |
CREATE PROCEDURE `crmGetTranNameApproval`(IN `ProName` varchar(255),IN `TranID` varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE countCustApp  INT;
	DECLARE countCustPad  INT;
  DECLARE tranName  VARCHAR(200);

	IF ProName = "Customer" THEN
			SELECT COUNT(CustID) INTO countCustApp FROM crm_customer WHERE CustID = TranID;
			IF countCustApp <> 0 THEN
				SELECT CustName as "authTranName" FROM crm_customer WHERE CustID = TranID;
			ELSE
				SELECT CustName AS "authTranName" FROM tblcustomer WHERE CustID = TranID;		
			END IF;	
	ELSEIF ProName = "Over Due Date" THEN
			SELECT tblcustomeroverdue.CustID INTO tranName FROM tblcustomeroverdue WHERE tblcustomeroverdue.IssueID = TranID;
			SELECT CONCAT("[",tblcustomer.CustID,"] ", tblcustomer.CustName) "authTranName" FROM tblcustomer WHERE tblcustomer.CustID = tranName;
	ELSEIF ProName = "Temporary Credit" THEN
			SELECT tblcustomerissue.CustID INTO tranName FROM tblcustomerissue WHERE tblcustomerissue.IssueID = TranID;
			SELECT CONCAT("[",tblcustomer.CustID,"] ", tblcustomer.CustName) "authTranName" FROM tblcustomer WHERE tblcustomer.CustID = tranName;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmListCompetitorAndCustomerByItemId`;
DELIMITER |
CREATE PROCEDURE `crmListCompetitorAndCustomerByItemId`(IN `itemId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
		i.ItemID itemId,
		i.ItemName itemName,
		co.*,
		cit.CustID custId,
		cit.CustName custName
		FROM 
			tblitem i
			INNER JOIN 
				hbu_competitor_item ci 
					ON i.ItemID = ci.ItemID
			INNER JOIN 
					(SELECT 
							c.COM_ID comId,
							c.COM_Name comName,
							c.COM_Status comType FROM hbu_competitor c GROUP BY c.COM_ID) co
					ON ci.COM_ID = co.comId
			 LEFT JOIN
				(SELECT cu.CustID, cu.CustName, itemId FROM tblcustomer cu where cu.CustID in (SELECT ic.CustID FROM hbu_item_customer ic WHERE ic.ItemID = itemId)) cit
			 ON cit.itemId = i.ItemID
				
		WHERE 
			i.ItemID = itemId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmListCompetitorByItemId`;
DELIMITER |
CREATE PROCEDURE `crmListCompetitorByItemId`(IN `itemId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT
		c.COM_ID comId,
		c.COM_Name comName,
		c.COM_Status comType,
		(SELECT ItemPrice from hbu_competitor_item where hbu_competitor_item.ItemID = itemId AND hbu_competitor_item.COM_ID = c.COM_ID) itemPrice,
		(SELECT true from hbu_competitor_item where hbu_competitor_item.ItemID = itemId AND hbu_competitor_item.COM_ID = c.COM_ID) checked
	from 
		hbu_competitor c;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmListCustomerForSpecificUser`;
DELIMITER |
CREATE PROCEDURE `crmListCustomerForSpecificUser`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	SELECT RM_TypeID INTO roleType FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	IF roleType = 1 THEN
		select 
			c.CustID custID,
			c.CustName custName,
			c.CustTel1 custTel1,
			c.CustTel2 custTel2,
			c.CustEmail custEmail,
			c.CustGroupID groupId,
			c.Latitude latitude,
			c.Longitude longitude,
			c.CrmApproval 'approval',
			c.CustAddress custAddress,
			(select CustGroupName from tblcustomergroup where CustGroupID = c.CustGroupID) groupName,
			c.PriceCode priceCode,
			(select p.Description from tblpricecode p where p.PriceCode = c.PriceCode) priceDes
		from
			tblcustomer c order by c.CustID desc;
	else
		select 
			c.CustID custID,
			c.CustName custName,
			c.CustTel1 custTel1,
			c.CustTel2 custTel2,
			c.CustEmail custEmail,
			c.CustGroupID groupId,
			c.Latitude latitude,
			c.Longitude longitude,
			c.CrmApproval 'approval',
			c.CustAddress custAddress,
			(select CustGroupName from tblcustomergroup where CustGroupID = c.CustGroupID) groupName,
			c.PriceCode priceCode,
			(select p.Description from tblpricecode p where p.PriceCode = c.PriceCode) priceDes
		from
			tblcustomer c where c.CustID in (select empc.CustID from tblemployeecustomer empc where empc.EmpID = (select ue.EmpID from tbluseremployee ue where ue.UID = userId) and empc.Assigned = 1)
			order by c.CustID desc;
	end if;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmListQuoteRelateToCustomer`;
DELIMITER |
CREATE PROCEDURE `crmListQuoteRelateToCustomer`(IN `custId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT
		qt.SalID AS saleId, 
		DATE_FORMAT(qt.SalDate, '%d-%b-%Y') as 'saleDate',
		DATE_FORMAT(qt.DueDate, '%d-%b-%Y') as 'dueDate',
		qt.PostStatus postStatus,
		COALESCE(qt.PmtStatus,'') 'pmtStatus',
		COALESCE(qt.TotalAmt,'') 'totalAmt',  
		COALESCE(qt.DisInvDol,'') 'disInvDol', 
		COALESCE(qt.TotalDis ,'') 'totalDis' , 
		COALESCE( qt.NetTotalAmt ,'') 'netTotalAmt',
		qt.EmpID AS empId,
		(SELECT e.EmpName FROM tblemployee e WHERE e.EmpID = qt.EmpID) empName
	FROM tblsbquote qt
  LEFT OUTER JOIN tblcustomer c
		ON c.CustID = qt.CustID
		Where qt.CustID = custId
	order by qt.SalID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmListSaleOrderRelatedToCustomer`;
DELIMITER |
CREATE PROCEDURE `crmListSaleOrderRelatedToCustomer`(IN `custId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
		qt.SalID AS saleId, 
		DATE_FORMAT(qt.SalDate, '%d-%b-%Y') as 'saleDate',
		DATE_FORMAT(qt.DueDate, '%d-%b-%Y') as 'dueDate',
		qt.PostStatus,COALESCE(qt.PmtStatus,'') 'pmtStatus',
		COALESCE(qt.TotalAmt,'') 'totalAmt',  
		COALESCE(qt.DisInvDol,'') 'disInvDol', 
		COALESCE(qt.TotalDis ,'') 'totalDis' , 
		COALESCE( qt.NetTotalAmt ,'') 'netTotalAmt', 
		(SELECT EmpName FROM tblemployee WHERE EmpID = qt.EmpID) empName,
		qt.EmpID AS empId
	FROM tblsaleorder qt
  LEFT OUTER JOIN tblcustomer c
		ON c.CustID = qt.CustID
	Where qt.CustID = custId
	order by qt.SalID DESC;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmListSaleRapForMobile`;
DELIMITER |
CREATE PROCEDURE `crmListSaleRapForMobile`(IN `custId` varchar(255),IN `rowNum` int,IN `pageNum` int,IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	declare roleTypeId int default 0;
	declare pages int default 0;
	declare totalPage int default 0;

	select RM_TypeID into roleTypeId from crm_role where RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	set pages = (pageNum - 1) * rowNum;
	if roleTypeId = 1 then
		if custId = '' then
			select count(DISTINCT ame_mt_cus_emp.var_empid) into totalPage from ame_mt_cus_emp;
			select DISTINCT e.var_id empId, e.var_name empName from ame_mt_emp e inner join ame_mt_cus_emp ec on e.var_id = ec.var_empid limit rowNum offset pages;
		else 
			select count(DISTINCT ame_mt_cus_emp.var_empid) into totalPage from ame_mt_cus_emp WHERE ame_mt_cus_emp.var_cusid = custId;
			if totalPage > 0 then
				select DISTINCT e.var_id empId, e.var_name empName from ame_mt_emp e inner join ame_mt_cus_emp ec on e.var_id = ec.var_empid WHERE ec.var_cusid = custId limit rowNum offset pages;
			else
					select count(DISTINCT ame_mt_cus_emp.var_empid) into totalPage from ame_mt_cus_emp;
			select DISTINCT e.var_id empId, e.var_name empName from ame_mt_emp e inner join ame_mt_cus_emp ec on e.var_id = ec.var_empid limit rowNum offset pages;
			end if;
		end if;
	else
		select count(DISTINCT ame_mt_cus_emp.var_empid) into totalPage from ame_mt_cus_emp WHERE ame_mt_cus_emp.var_empid = CRM_FUN_GET_EMP_ID(userId);
		select DISTINCT e.var_id empId, e.var_name empName from ame_mt_emp e inner join ame_mt_cus_emp ec on e.var_id = ec.var_empid WHERE ec.var_empid = CRM_FUN_GET_EMP_ID(userId) limit rowNum offset pages;
	end if;
	set totalPage = CEIL(totalPage / rowNum);
	SELECT var_id empId, var_name empName,totalPage FROM ame_mt_emp WHERE var_id = CRM_FUN_GET_EMP_ID(userId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmListServiceOnCustomer`;
DELIMITER |
CREATE PROCEDURE `crmListServiceOnCustomer`(IN `custId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
			sv.sv_Id 'id', 
			sv.sv_name 'name',
			sv.sv_itemId 'itemId',
			DATE_FORMAT(sv.sv_createDate,"%d-%b-%Y h:mm a")'createDate',
			sv.sv_numOfDevice 'numOfDevice',
			IF(sv.sv_vpn = 0, 'NO', 'YES') 'isVPN',
			sv.sv_remark 'remark',
			DATE_FORMAT(svd.svd_startDate,'%d-%b-%Y h:mm a') 'startDate',
			DATE_FORMAT(svd.svd_endDate,'%d-%b-%Y h:mm a') 'endDate'
		FROM crm_customer_service sv 
			INNER JOIN  crm_service_details svd ON svd.sv_Id = sv.sv_Id

		WHERE sv_custId = custId;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmPrintPOForecasting`;
DELIMITER |
CREATE PROCEDURE `crmPrintPOForecasting`(IN `poId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
		pof.PO_Number 'no',
		pof.PO_Name 'name',
		pof.PO_PreparedBy preparedBy,
		tpr.EmpName preparedByName,
		tpr.EmpPosition preparedByPosition,
		tpr.Emp_Salutation preparedBySal,
		pof.PO_ApprovedBy approvedBy,
		tar.EmpName approvedByName,
		tar.EmpPosition approvedByPosition,
		tar.Emp_Salutation approvedBySal,
		DATE_FORMAT(pof.PO_CreatedDate,"%d-%b-%Y") createDate,
		DATE_FORMAT(pof.PO_StartDate,"%d-%b-%Y") startDate,
		DATE_FORMAT(pof.PO_EndDate,'%d-%b-%Y') endDate,
		pod.ItemID itemId,
		(SELECT ItemName ItemName FROM tblitem WHERE ItemID = pod.ItemID) itemName,
		pod.UomID uom,
		pod.POD_AmtToOrder amtToOrder,
		pod.POD_Remark remark
	FROM crm_po_forecasting pof 
	LEFT JOIN crm_po_forecasting_details pod ON pof.PO_ID = pod.PO_ID
	INNER JOIN (SELECT e.EmpID, e.EmpName, e.EmpPosition, e.Emp_Salutation FROM tblemployee e) tpr ON pof.PO_PreparedBy = tpr.EmpID
	INNER JOIN (SELECT e.EmpID, e.EmpName, e.EmpPosition, e.Emp_Salutation FROM tblemployee e) tar ON pof.PO_ApprovedBy = tar.EmpID
	WHERE pof.PO_ID = poId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRequestCustomerApproved`;
DELIMITER |
CREATE PROCEDURE `crmRequestCustomerApproved`(IN `custId` varchar(255), IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE authId VARCHAR(255) DEFAULT "";
	DECLARE authType VARCHAR(255) DEFAULT "";
	
	SELECT 
			DISTINCT ae.Auth_ID, ha.Auth_Type
			INTO authId, authType 
	FROM hrm_authorisation_employee ae 
		INNER JOIN hrm_authorisation ha
			ON ha.Auth_ID = ae.Auth_ID
		INNER JOIN ame_user emp
			ON ae.Emp_ID = emp.var_empid 
		WHERE emp.var_id = userId AND ae.Auth_Process = "Customer";

	IF authType = "Individual" THEN
		UPDATE crm_customer SET crm_customer.var_authId = authId WHERE crm_customer.var_id = custId;
		CALL spHRMAddAuthorisationTemp(authId,custId);
		CALL spHRMAddIAuthorisationApproved(authId,custId,"Customer");
		
	ELSE
		UPDATE crm_customer SET crm_customer.var_authId = authId WHERE crm_customer.var_id = custId;
		CALL spHRMAddAuthorisationTemp(authId,custId);
		CALL spHRMAddGAuthorisationApproved(authId,custId,"Customer");
		
	END IF;

	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CrmRptCall`;
DELIMITER |
CREATE PROCEDURE `CrmRptCall`(IN `fromDate` varchar(255),IN `toDate` varchar(255),IN `groupBy` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT
		cl.CL_ID AS callId,
		cl.CL_Subject AS callSubject,
		DATE_FORMAT(cl.CL_SDate,'%d-%b-%Y') 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 createBy,
		u.var_name 'createByName',
		DATE_FORMAT(cl.CL_CDate, '%d-%b-%Y') callCreateDate,
		cl.CL_StatusID AS callStatusId,
		(SELECT CLS_Name FROM crm_call_status WHERE CLS_ID = cl.CL_StatusID) AS callStatusName,
		cl.CL_ATo AS userId,
		(SELECT ass.var_name FROM ame_user ass WHERE ass.var_id = cl.CL_ATo) username,
		CRM_FUN_REPORT_HEADER() businessUnit
	FROM 
		crm_call cl
	INNER JOIN ame_user u ON u.var_id = cl.CL_CBy
	WHERE DATE(cl.CL_CDate) BETWEEN DATE(fromDate) AND DATE(toDate) 
	AND IF(groupBy = 'Module',cl.CL_RToType <> '',TRUE)
	AND IF(@typeId = 1,TRUE,(cl.CL_CBy = userId OR cl.CL_ATo = userId))
	ORDER BY
		CASE	
			WHEN groupBy = 'Module' THEN cl.CL_RToType
			WHEN groupBy = 'CreateDate' THEN cl.CL_CDate
			ELSE cl.CL_ID
		END DESC, IF(groupBy = 'CreateDate',cl.CL_ID,cl.CL_CDate) DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptCallFilter`;
DELIMITER |
CREATE PROCEDURE `crmRptCallFilter`()
    DETERMINISTIC
BEGIN
		select MIN(c.CL_CDate) minCreateDate, MAX(c.CL_CDate) maxCreateDate FROM crm_call c; 
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptCampaign`;
DELIMITER |
CREATE PROCEDURE `crmRptCampaign`(IN `fromDate` varchar(255),IN `toDate` varchar(255),IN `groupBy` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT
		ca.CA_ID campId, 
		ca.CA_Name campName, 
		DATE_FORMAT(ca.CA_SDate,'%d-%b-%Y') startDate, 
		DATE_FORMAT(ca.CA_EDate,'%d-%b-%Y') endDate, 
		ca.CA_ATo assignedToId,
		(SELECT u.var_name FROM ame_user u WHERE u.var_id = ca.CA_ATo) assignedToName,
		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 c.CA_Name FROM crm_camp c WHERE c.CA_ID = ca.CA_ParentID) parentName, 
		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,
		tblu.var_name 'createByName',
		DATE_FORMAT(ca.CA_CDate,'%d-%b-%Y') createdDate,
		CRM_FUN_REPORT_HEADER() businessUnit
	FROM crm_camp ca
		INNER JOIN (SELECT u.var_id, u.var_name FROM ame_user u) tblu ON tblu.var_id = ca.CA_CBy
	WHERE DATE(ca.CA_CDate) BETWEEN DATE(fromDate) AND DATE(toDate) 
	AND IF(@typeId = 1,TRUE,(ca.CA_CBy = userId OR ca.CA_ATo = userId))
	ORDER BY
		CASE	
			WHEN groupBy = 'CreateDate' THEN ca.CA_CDate
			ELSE ca.CA_ID
		END DESC, IF(groupBy = 'CreateDate',ca.CA_ID,ca.CA_CDate) DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptCampaignStartupFilter`;
DELIMITER |
CREATE PROCEDURE `crmRptCampaignStartupFilter`()
    DETERMINISTIC
BEGIN
	SELECT MIN(CA_CDate) minCreateDate, MAX(CA_CDate) maxCreateDate FROM crm_camp;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptCase`;
DELIMITER |
CREATE PROCEDURE `crmRptCase`(IN `fromDate` varchar(255),IN `toDate` varchar(255),IN `fromCust` varchar(255),IN `toCust` varchar(255),IN `fromPro` varchar(255),IN `toPro` varchar(255),IN `groupBy` varchar(255),IN `userId` varchar(255),IN `var_status` int(11))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT 
			cs.CS_ID caseId,
			cs.CS_StatusID statusId, 
			cst.CSS_Name 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_originid 'originId',
			(SELECT co.CS_Title FROM crm_case_origin co WHERE co.CS_OriginID = cs.cs_originid) originName,
			cs.CS_CustID custId, 
			(SELECT c.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_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,
			DATE_FORMAT(cs.CS_CDate, '%d-%b-%Y') createDate,
			DATE_FORMAT(cs.CS_EndDate, '%d-%b-%Y') endDate,
			DATE_FORMAT(cs.CS_FollowupDate, '%d-%b-%Y') followupDate,
			cs.CS_ItemID productId,
			(SELECT ite.var_id FROM ame_mt_ite ite WHERE ite.var_id = cs.CS_ItemID) productName,
			u.var_name empId,
			(SELECT emp.var_name FROM ame_mt_emp emp WHERE emp.var_id = u.var_empid) empName,
			CRM_FUN_REPORT_HEADER() businessUnit
		FROM crm_case cs 
			INNER JOIN ame_user u ON u.var_id = cs.cs_cby
			INNER JOIN crm_case_status cst ON cst.CSS_ID = cs.cs_statusid
		WHERE (DATE(cs.cs_cdate) BETWEEN DATE(fromDate) AND DATE(toDate)) 
				#AND IF(fromCust = 'all',cs.cs_custid <> '',cs.cs_custid >= fromCust)
				#AND IF(toCust = 'all',cs.cs_custid <> '',cs.cs_custid <= toCust)
				#AND IF(fromPro = 'all',cs.cs_itemid <> '', cs.cs_itemid >= fromPro)
				#AND IF(toPro = 'all',cs.cs_itemid <> '',cs.cs_itemid <= toPro)
				#AND IF(@typeId = 1, TRUE, ((cs.CS_CBy = userId) OR (cs.CS_ATo = userId)))
				AND IF(var_status = 0, TRUE, cst.CSS_ID = var_status)
				AND IF(groupBy = 'Origin', cs.cs_originid IN (SELECT co.CS_OriginID FROM crm_case_origin co), TRUE)
				AND IF(groupBy = 'Priority', cs.cs_priority IN (SELECT cp.CSP_ID FROM crm_case_priority cp), TRUE)
				AND IF(groupBy = 'Type', cs.cs_typeid IN (SELECT ct.CST_ID FROM crm_case_type ct), TRUE)
		ORDER BY 
				CASE
						WHEN groupBy = 'Customer' THEN cs.cs_custid
						WHEN groupBy = 'Employee' THEN u.var_empid
						WHEN groupBy = 'Product' THEN cs.cs_itemid
						WHEN groupBy = 'Origin' THEN cs.cs_originid
						WHEN groupBy = 'Priority' THEN cs.cs_priority
						WHEN groupBy = 'Type' THEN cs.cs_typeid
						ELSE cs.CS_CDate
				END
		DESC, caseId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptCaseStartupFilter`;
DELIMITER |
CREATE PROCEDURE `crmRptCaseStartupFilter`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT MAX(cs_cdate) maxCreatedDate, MIN(cs_cdate) minCreatedDate FROM crm_case;
	SELECT c.var_id custId, c.var_name custName FROM ame_mt_cus c WHERE IF(@typeId = 1,true,c.var_id IN (SELECT ec.var_cusid FROM ame_mt_cus_emp ec WHERE ec.var_empid = CRM_FUN_GET_EMP_ID(userId))) ORDER BY c.var_id ASC;
	CALL CRM_PRO_ITEM_LOAD(userId);
	SELECT CSS_ID statusId, CSS_Name statusName FROM crm_case_status ORDER BY CSS_ID ASC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptContact`;
DELIMITER |
CREATE PROCEDURE `crmRptContact`(IN `fromDate` varchar(255),IN `toDate` varchar(255),IN `groupBy` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
		c.CO_ID 'CO_ID',
		CONCAT(c.CO_Salutation,c.CO_FirstName,' ',c.CO_LastName) 'fullname',
		c.CO_Phone 'CO_Phone',
		IF(c.CO_Mobile = '', '-',c.CO_Mobile) 'CO_Mobile',
		COALESCE(IF(c.CO_CustID='','-',(SELECT CustName FROM tblcustomer WHERE CustID = c.CO_CustID)),'-') 'CO_Cust',
		IF(c.CO_Email = '', '-', c.CO_Email) 'CO_Email',
		COALESCE((SELECT u.UName FROM tbluser u WHERE u.UID = c.CO_ATo),'-') 'CO_ATo',
		COALESCE(IF(ol.LS_Name = '', '-', ol.LS_Name),'-') 'LeadName',
		COALESCE(IF(c.CO_ReportTo = '', '-', CONCAT('[',c.CO_ID,'] ',CONCAT(c.CO_Salutation,c.CO_FirstName,' ',c.CO_LastName))),'-') 'CO_ReportTo',
		COALESCE(IF(c.CO_Title = '', '-', c.CO_Title),'-') 'CO_Title',
		DATE_FORMAT(c.CO_CDate, '%d-%b-%Y') 'CO_CDate',
		(SELECT u.UName FROM tbluser u WHERE u.UID = c.CO_CBy) 'CO_CBy',
		(SELECT Unit FROM tblcompanyreport LIMIT 1) 'businessUnit'
	FROM crm_contact c
	INNER JOIN (SELECT u.UID, u.UName, u.UStatus FROM tbluser u) tblu ON tblu.UID = c.CO_CBy
	LEFT JOIN (SELECT cls.*, p.OPID FROM crm_lead_source cls LEFT JOIN crm_opportunity_lead_project p ON LS_ID = LPID) ol ON c.CO_LeadSource = ol.LS_ID
	WHERE DATE(c.CO_CDate) BETWEEN DATE(fromDate) AND DATE(toDate) 
		AND IF(@typeId = 1,tblu.UStatus = 1,(c.CO_CBy = userId OR c.CO_ATo = userId))
		ORDER BY
			CASE	
				WHEN groupBy = 'CreateDate' THEN c.CO_CDate
				ELSE c.CO_ID
			END DESC, IF(groupBy = 'CreateDate',c.CO_ID,c.CO_CDate) DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptContactFilter`;
DELIMITER |
CREATE PROCEDURE `crmRptContactFilter`()
    DETERMINISTIC
BEGIN
	SELECT MIN(CO_CDate) minCreateDate, MAX(CO_CDate) maxCreateDate FROM crm_contact;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptCustomer`;
DELIMITER |
CREATE PROCEDURE `crmRptCustomer`(IN `fCust` varchar(255),IN `tCust` varchar(255),IN `fEmp` varchar(255),IN `tEmp` varchar(255),IN `fGroup` varchar(255),IN `tGroup` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
		C.CustID, 
		COALESCE(CustName,'') AS 'Name', 
		COALESCE(CustContactName,'') AS 'ContactName', 
		COALESCE(CustAddress,'') AS 'Addr',
		CASE 
			WHEN COALESCE(CustTel1,'') = '' THEN COALESCE(CustTel2,'') 
			WHEN COALESCE(CustTel2,'') = '' THEN COALESCE(CustTel1,'') 
			ELSE CONCAT(COALESCE(CustTel1,''),' , ',COALESCE(CustTel2,'')) 
		END AS 'Tel',
		COALESCE(CustEmail,'') AS 'Email', 
		COALESCE(CustWebsite,'') AS 'Web', 
		COALESCE(Line,'') AS 'Line', 
		COALESCE(Facebook,'') AS 'Facebook', 
		COALESCE(WhatApp,'') AS 'WhatsApp', 
		COALESCE(Viber,'') AS 'Viber',
		CustGroupID AS 'Group', 
		PriceCode, 
		COALESCE(C.LocationID,'') AS 'Location', 
		COALESCE(DefaultRetail,'') AS 'ComparativePriceCode', 
		COALESCE(DefaultWholesale,'') AS 'SalePriceCode', 
		COALESCE(TermFormat,'') AS 'Term',
		COALESCE(Advantage,'') AS 'Remark', 
		COALESCE(s.shipname,'') AS ShipAddr, 
		IF(C.Inactive = 1, 'TRUE', 'FALSE') AS Inactive, 
		COALESCE(E.EmpName, '') AS EmpName, 
		COALESCE(EC.EmpID, '') AS EmpID,
		(SELECT Unit FROM tblcompanyreport LIMIT 1) businessUnit
	FROM tblcustomer C 
		LEFT JOIN (tblemployeecustomer EC LEFT JOIN tblemployee E ON EC.EmpID = E.EmpID) ON EC.CustID = C.CustID
		LEFT JOIN tblshipaddress S ON C.CustID = S.docid AND C.AID = S.shipid AND moduleid = 'MT-CUS' 
		WHERE 
			IF(fGroup = 'all', TRUE, C.CustGroupID >= fGroup ) 
			AND IF(tGroup  = 'all', TRUE, C.CustGroupID <= tGroup) 
			AND IF(fCust = 'all', TRUE, C.CustID >= fCust) 
			AND IF(tCust = 'all', TRUE, C.CustID <= tCust) 
			AND IF(fEmp  = 'all', TRUE, EC.EmpID >= fEmp ) 
			AND IF(tEmp  = 'all', TRUE, EC.EmpID <= tEmp )
			AND IF(ISNULL((SELECT T.UID FROM tbluserprofile T WHERE T.UID = userId AND T.APPID = 'LOAD EMPLOYEE')), TRUE, C.CustID IN(SELECT var_cusid FROM tblusercustomer WHERE var_uid = userId))
			AND IF(@typeId = 1,true,EC.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId))
			AND IF(@typeId = 1,true,C.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1))
		ORDER BY C.CustID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptCustomerStartupFilter`;
DELIMITER |
CREATE PROCEDURE `crmRptCustomerStartupFilter`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT c.CustID 'custId', c.CustName 'custName' FROM tblcustomer c WHERE IF(@typeId = 1,true,c.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1)) ORDER BY CustID;
	SELECT EmpID 'empId', EmpName 'empName' FROM tblemployee WHERE IF(@typeId = 1,true,EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId)) ORDER BY EmpID;
	SELECT CustGroupID groupId, CustGroupName groupName FROM tblcustomergroup ORDER BY CustGroupID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptEvent`;
DELIMITER |
CREATE PROCEDURE `crmRptEvent`(IN `fromDate` varchar(255),IN `toDate` varchar(255),IN `groupBy` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT
		ev.EV_ID evId,
		ev.EV_Name evName,
		DATE_FORMAT(ev.EV_StartDate,'%d-%b-%Y') startDate,
		DATE_FORMAT(ev.EV_EndDate,'%d-%b-%Y') endDate,
		ev.EV_Duration duration,
		ev.EV_Budget budget,
		ev.EV_CBy createBy,
		tblu.var_name 'createByName',
		DATE_FORMAT(ev.EV_CDate,'%d-%b-%Y') createDate,
		ev.EV_RToID AS relatedToId,
		ev.EV_RToType AS relatedToModule,
		findModuleDetailsByModuleNameAndItsId(ev.EV_RToType,ev.EV_RToID) AS relatedToName,
		ev.EV_LocationID locationId,
		(SELECT LO_Name FROM crm_location WHERE LO_ID = ev.EV_LocationID) 'locationName',
		ev.EV_AssignTo 'assignedToId',
		(SELECT ass.var_name FROM ame_user ass WHERE ass.var_id = ev.EV_AssignTo) 'assignedToName',
		CRM_FUN_REPORT_HEADER() businessUnit
	FROM 
		crm_event ev
	INNER JOIN (SELECT u.var_id, u.var_name FROM ame_user u) tblu ON tblu.var_id = ev.EV_CBy
	WHERE DATE(ev.EV_CDate) BETWEEN DATE(fromDate) AND DATE(toDate) 
	AND IF(groupBy = 'Module',ev.EV_RToType <> '',TRUE)
	AND IF(@typeId = 1,TRUE,(ev.EV_CBy = userId OR ev.EV_AssignTo = userId))
	ORDER BY
		CASE	
			WHEN groupBy = 'Module' THEN ev.EV_RToType
			WHEN groupBy = 'CreateDate' THEN ev.EV_CDate
			ELSE ev.EV_ID
		END DESC, IF(groupBy = 'CreateDate',ev.EV_ID,ev.EV_CDate) DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptEventStartupFilter`;
DELIMITER |
CREATE PROCEDURE `crmRptEventStartupFilter`()
    DETERMINISTIC
BEGIN
	SELECT MIN(EV_CDate) minCreateDate, MAX(EV_CDate) maxCreateDate FROM crm_event;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptLeadStartupFilter`;
DELIMITER |
CREATE PROCEDURE `crmRptLeadStartupFilter`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT MIN(LA_CDate) minCreateDate, MAX(LA_CDate) maxCreateDate FROM crm_lead;
	SELECT LST_ID statusId, LST_Name statusName FROM crm_lead_status;
	SELECT CA_ID campId, CA_Name campName FROM crm_camp WHERE IF(@typeId = 1, TRUE, CA_CBy = userId OR CA_ATo = userId) ORDER BY CA_ID ASC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptLeadSummary`;
DELIMITER |
CREATE PROCEDURE `crmRptLeadSummary`(IN `fromDate` varchar(255),IN `toDate` varchar(255),IN `fromCamp` varchar(255),IN `toCamp` varchar(255),IN `statusId` int,IN `groupBy` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT
		le.LA_ID as leadId,
		le.LA_Email as email,
		le.LA_AccountName as accountName,
		le.LA_Title 'title',
		le.LA_CBy as createBy,
		tblu.var_name 'createByName',
		DATE_FORMAT(le.LA_CDate, '%d-%b-%Y') as createDate,
		le.LA_Department as department,
		CONCAT(le.LA_Salutation," ",le.LA_FirstName," ",le.LA_LastName) leadName,
		le.LA_Mobile as mobile,
		le.LA_Phone as phone,
		ca.CA_ID campId,
		ca.CA_Name campName,
		le.LA_StatusID 'statusId',
		st.LST_Name 'statusName',
		le.LA_SourceID 'sourceId',
		(SELECT so.LS_Name FROM crm_lead_source so WHERE so.LS_ID = le.LA_SourceID) 'sourceName',
		le.LA_IndustID 'industId',
		(SELECT i.I_Name FROM crm_industry i WHERE i.I_ID = le.LA_IndustID) 'industName',
		le.LA_ATo 'assignedToId',
		(SELECT u.var_name FROM ame_user u WHERE u.var_id = le.LA_ATo) 'assignedToName',
		CRM_FUN_REPORT_HEADER() businessUnit
  FROM
    crm_lead le
	INNER JOIN crm_camp ca ON le.LA_CA_ID = ca.CA_ID
	INNER JOIN (SELECT u.var_id, u.var_name FROM ame_user u) tblu ON tblu.var_id = le.LA_CBy
	INNER JOIN crm_lead_status st ON st.LST_ID = le.LA_StatusID

	WHERE (DATE(le.LA_CDate) BETWEEN DATE(fromDate) AND DATE(toDate))
		AND IF(@typeId = 1, TRUE, le.LA_CBy = userId OR le.LA_ATo = userId)
		AND IF(fromCamp = 'all', TRUE, le.LA_CA_ID >= fromCamp)
		AND IF(toCamp = 'all', TRUE, le.LA_CA_ID <= toCamp)
		AND IF(statusId = 0, TRUE, le.LA_StatusID = statusId)
		AND IF(groupBy = 'Source', le.LA_SourceID IN (SELECT ls.LS_ID FROM crm_lead_source ls), TRUE)
		AND IF(groupBy = 'Industry', le.LA_IndustID IN (SELECT i.I_ID FROM crm_industry i), TRUE)
	ORDER BY 
		CASE 
			WHEN groupBy = 'Campaign' THEN le.LA_CA_ID
			WHEN groupBy = 'Status' THEN le.LA_StatusID
			WHEN groupBy = 'Source' THEN le.LA_SourceID
			WHEN groupBy = 'Industry' THEN le.LA_IndustID
			WHEN groupBy = 'CreateDate' THEN le.LA_CDate
			WHEN groupBy = 'Owner' THEN le.LA_CBy
			ELSE le.LA_ID
		END DESC, IF(groupBy = 'CreateDate', le.LA_ID, le.LA_CDate) DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptMeeting`;
DELIMITER |
CREATE PROCEDURE `crmRptMeeting`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `groupBy` varchar(255),IN `var_status` int,IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT 
			M.M_ID meetId,
			M.M_Subject 'subject', 
			DATE_FORMAT(M.M_StartDate,'%d-%b-%Y %h:%i %p') startDate,
			DATE_FORMAT(M.M_EndDate,'%d-%b-%Y %h:%i %p') endDate,
			M.M_Duration duration, 
			MS.MS_ID statusId,
			MS.MS_Name statusName,
			M.M_RToType relatedToModule,
			M.M_RToID relatedToId,
			CRM_FUN_MODULE_BY_RELATED(M.M_RToType, M.M_RToID) relatedToName,
			M.M_Location location,
			M.M_Des meetingDes,
			M.M_ATo userID, 
			(SELECT ass.var_name FROM ame_user ass WHERE ass.var_id = M.M_ATo) username,
			M.M_CBy createBy, 
			U.var_name createByName,
			DATE_FORMAT(M.M_CDate,'%d-%b-%Y') createDate,
			CRM_FUN_REPORT_HEADER() businessUnit
		FROM 
			crm_meeting M
		LEFT OUTER JOIN 
			crm_meeting_status MS
				ON M.M_StatusID = MS.MS_ID
		INNER JOIN
			ame_user U
				ON M.M_CBy = U.var_id 
		WHERE (DATE(M.M_CDate) BETWEEN DATE(startDate) AND DATE(endDate))
				AND IF(var_status = 0, TRUE, MS.MS_ID = var_status)
				AND IF(groupBy = 'Module', M.M_RToType <> '', TRUE)
				AND IF(@typeId = 1,TRUE, (M.M_CBy = userId) OR (M.M_ATo = userId))
		ORDER BY 
			CASE
				WHEN groupBy = 'Module' THEN M.M_RToType
				WHEN groupBy = 'CreateDate' THEN DATE(M.M_CDate)
				ELSE M.M_ID
			END DESC, IF(groupBy = 'CreateDate', M.M_ID, M.M_CDate) DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptMeetingStartupFilter`;
DELIMITER |
CREATE PROCEDURE `crmRptMeetingStartupFilter`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT MAX(M_CDate) maxCreateDate, MIN(M_CDate) minCreateDate from crm_meeting;
	SELECT MS_ID statusId, MS_Name statusName FROM crm_meeting_status ORDER BY MS_ID ASC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptOpportunity`;
DELIMITER |
CREATE PROCEDURE `crmRptOpportunity`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN var_stage varchar(255),IN `custId` varchar(255),IN `groupBy` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT
		o.OP_ID 'opId',
		o.OP_Name 'opName',
		DATE_FORMAT(o.OP_CDate, '%d-%b-%Y') 'cDate',
		(SELECT u.UName FROM tbluser u WHERE u.UID = o.OP_CBy) 'cBy',
		os.OS_ID 'opStageId',
		os.OS_Name 'opStage',
		os.OS_Des 'Probability',
		DATE_FORMAT(o.OP_CloseDate, '%d-%b-%Y') 'opCloseDate',
		c.CA_Name 'opCamp',
		ol.LS_Name 'opLeadName',
		cust.CustID 'opCustdId',
		cust.CustName 'opCustName',
		(SELECT u.UName FROM tbluser u WHERE u.UID = o.OP_ATo) 'opAssignTo',
		o.OP_Amt 'opAmount',
		(SELECT Unit FROM tblcompanyreport LIMIT 1) 'businessUnit'
	FROM crm_opportunity o
	INNER JOIN crm_opportunity_stage os ON o.OP_StageID = os.OS_ID
	INNER JOIN tblcustomer cust ON o.OP_CustID = cust.CustID
	LEFT JOIN crm_camp c ON o.OP_CampID = c.CA_ID 
	LEFT JOIN (SELECT cls.*, p.OPID FROM crm_lead_source cls LEFT JOIN crm_opportunity_lead_project p ON LS_ID = LPID) ol ON o.OP_LeadSourceID = ol.LS_ID
	WHERE 
		(DATE(OP_CDate) BETWEEN DATE(startDate) AND DATE(endDate))
		AND IF(custId = 'all',TRUE ,o.OP_CustID = custId)
		AND IF(var_stage = 'all', 1=1, o.OP_StageID = var_stage)
		AND IF(@typeId = 1, TRUE, FALSE)
	ORDER BY 
		CASE
			WHEN groupBy = 'customer' THEN o.OP_CustID
			WHEN groupBy = 'stage' THEN o.OP_StageID
			ELSE DATE(o.OP_CDate)
		END DESC , IF(groupBy = 'all', o.OP_ID, DATE(o.OP_CDate)) DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptOpportunityDetail`;
DELIMITER |
CREATE PROCEDURE `crmRptOpportunityDetail`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN var_stage varchar(255),IN `custId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
		o.OP_ID,
		o.OP_Name,
		DATE_FORMAT(o.OP_CDate, '%d-%b-%Y') 'cDate',
		o.OP_CustID 'custId', 
		cust.custname 'custName',
		od.LocationID 'locationId',
		os.OS_Name 'opStage',
		os.OS_Des 'Probability',
		c.CA_Name 'opCamp',
		ol.LS_Name 'opLeadName',
		od.ClassID 'classId', 
		od.LineNo 'lineNo', 
		od.SalQty 'salQty',
		od.UnitPrice 'unitPrice',
		od.UomID 'uomId',
		od.ClassID 'dClassId',
		(SELECT c.Des FROM tblclass c WHERE c.ClassID = od.ClassID) 'dClassName',
		od.TotalAmt 'totalAmt',  
		od.DisDol 'disDol', 
		od.NetTotalAmt 'netTotalAmt',
		od.STaxDol 'sTaxDol',
		od.VTaxDol 'vTaxDol',
		i.ItemID 'itemId',
		i.ItemName 'itemName',
		i.itemcode 'itemCode',
		(SELECT u.UName FROM tbluser u WHERE u.UID = o.OP_ATo) 'opAssignTo',
		(SELECT u.UName FROM tbluser u WHERE u.UID = o.OP_CBy) 'cBy',
		(SELECT Unit FROM tblcompanyreport LIMIT 1) 'businessUnit'
	FROM crm_opportunity o
	INNER JOIN crm_opportunity_detail od ON o.OP_ID = od.OP_ID
	INNER JOIN tblitem i ON od.ItemID = i.ItemID
	INNER JOIN (SELECT c.custid, c.custname FROM tblcustomer c) AS cust ON cust.custid = o.OP_CustID
	INNER JOIN crm_opportunity_stage os ON o.OP_StageID = os.OS_ID
	LEFT JOIN crm_camp c ON o.OP_CampID = c.CA_ID 
	LEFT JOIN (SELECT cls.*, p.OPID FROM crm_lead_source cls LEFT JOIN crm_opportunity_lead_project p ON LS_ID = LPID) ol ON o.OP_LeadSourceID = ol.LS_ID
	WHERE 
		(DATE(OP_CDate) BETWEEN DATE(startDate) AND DATE(endDate))
		AND IF(custId = 'all',TRUE ,o.OP_CustID = custId)
		AND IF(var_stage = 'all', 1=1, o.OP_StageID = var_stage)
		AND IF(@typeId = 1, TRUE, FALSE)
	ORDER BY o.OP_CDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptProjectList`;
DELIMITER |
CREATE PROCEDURE `crmRptProjectList`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `fromEmp` varchar(255),IN `toEmp` varchar(255),IN `groupBy` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN	
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT
		pl.PL_ID 'id',
		pl.EmpID 'empId',
		COALESCE((SELECT emp.var_name from ame_mt_emp emp WHERE emp.var_id = pl.EmpID),'') 'empName',
		(SELECT PLS_Name FROM crm_projectlist_status pls where pls.PLS_ID = pl.PL_Status) 'status',
		(SELECT PLT_Name FROM crm_projectlist_type plt where plt.PLT_ID = pl.PL_Type) 'type',
		pl.PL_Name 'name',
		pl.PL_Location 'location',
		COALESCE(DATE_FORMAT(pl.PL_CreatedDate, '%d-%b-%Y'),'') 'createdDate',
		COALESCE(DATE_FORMAT(pl.PL_EndDate,'%d-%b-%Y'),'') 'endDate',
		pl.PL_BuildCompleted 'buildCompleted',
		pl.PL_Owner 'owner',
		pl.PL_Remark 'remark',
		CRM_FUN_REPORT_HEADER() businessUnit
	FROM 
		crm_projectlist pl 
	where (DATE(pl.PL_CreatedDate) BETWEEN DATE(startDate) AND DATE(endDate))
		AND IF(fromEmp = 'all', TRUE, pl.EmpID >= fromEmp)
		AND IF(toEmp = 'all', TRUE, pl.EmpID <= toEmp)
		AND IF(@typeId = 1, TRUE, pl.PL_CreatedBy = userId)
	ORDER BY 
		CASE
			WHEN groupBy = 'employee' THEN pl.EmpID
			WHEN groupBy = 'createDate' THEN DATE(pl.PL_CreatedDate)
			ELSE pl.PL_ID
		END DESC,
		CASE
			WHEN groupBy = 'employee' THEN DATE(pl.PL_CreatedDate)
			WHEN groupBy = 'createDate' THEN pl.PL_ID
			ELSE DATE(pl.PL_CreatedDate)
		END DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptProjectListDetails`;
DELIMITER |
CREATE PROCEDURE `crmRptProjectListDetails`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `fromEmp` varchar(255),IN `toEmp` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT
		pl.PL_ID 'id',
		pl.EmpID 'empId',
		(SELECT EmpName from tblemployee WHERE EmpID = pl.EmpID) 'empName',
		(SELECT PLS_Name FROM crm_projectlist_status pls where pls.PLS_ID = pl.PL_Status) 'status',
		(SELECT PLT_Name FROM crm_projectlist_type plt where plt.PLT_ID = pl.PL_Type) 'type',
		pl.PL_Name 'name',
		pl.PL_Location 'location',
		DATE_FORMAT(pl.PL_CreatedDate, '%d-%b-%Y') 'createdDate',
		DATE_FORMAT(pl.PL_EndDate,'%d-%b-%Y') 'endDate',
		pl.PL_BuildCompleted 'buildCompleted',
		pl.PL_Owner 'owner',
		pl.PL_Remark 'remark',
		(SELECT Unit FROM tblcompanyreport LIMIT 1) businessUnit,
		plp.ItemID 'itemId',
		(SELECT i.ItemName FROM tblitem i WHERE i.ItemID = plp.ItemID) 'itemName',
		plp.UomID 'uomId',
		plp.PLP_BOQ 'boq',
		plp.PLP_Qty 'qty',
		plp.PLP_UnitPrice 'unitPrice',
		plp.PLP_PricePer 'pricePer',
		plp.PLP_Balance 'balance',
		DATE_FORMAT(plp.PLP_DateExpToUse, '%d-%b-%Y') 'dateExpToUse',
		plp.PLP_PercentageToBuy 'percentageToBuy',
		plp.PLP_QtyToBuy 'qtyToBuy',
		plp.PLP_QtyToUsed 'qtyToUse',
		plp.PLP_Remark 'proRemark',
		(SELECT plps.PLPS_Name From crm_projectlist_product_status plps WHERE plp.PLP_Status = plps.PLPS_Name) 'proStatusName',
		plp.PLP_TotalBalance 'totalBalance',
		plp.PLP_TotalBalFinished 'totalBalFinished'
	FROM 
		crm_projectlist pl 
		INNER JOIN crm_projectlist_product plp ON plp.PL_ID = pl.PL_ID
	where (DATE(pl.PL_CreatedDate) BETWEEN DATE(startDate) AND DATE(endDate))
		AND IF(fromEmp = 'all', TRUE, pl.EmpID >= fromEmp)
		AND IF(toEmp = 'all', TRUE, pl.EmpID <= toEmp)
		AND IF(@typeId = 1, TRUE, pl.PL_CreatedBy = userId)
	ORDER BY plp.ItemID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptProjectListInfo`;
DELIMITER |
CREATE PROCEDURE `crmRptProjectListInfo`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `fromEmp` varchar(255),IN `toEmp` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT
		pl.PL_ID 'id',
		pl.EmpID 'empId',
		(SELECT EmpName from tblemployee WHERE EmpID = pl.EmpID) 'empName',
		(SELECT PLS_Name FROM crm_projectlist_status pls where pls.PLS_ID = pl.PL_Status) 'status',
		(SELECT PLT_Name FROM crm_projectlist_type plt where plt.PLT_ID = pl.PL_Type) 'type',
		pl.PL_Name 'name',
		pl.PL_Location 'location',
		DATE_FORMAT(pl.PL_CreatedDate, '%d-%b-%Y') 'createdDate',
		DATE_FORMAT(pl.PL_EndDate,'%d-%b-%Y') 'endDate',
		pl.PL_BuildCompleted 'buildCompleted',
		pl.PL_Owner 'owner',
		pl.PL_Remark 'remark',
		(SELECT Unit FROM tblcompanyreport LIMIT 1) businessUnit,
		pld.PLD_ID pldId,
		pld.PLD_MainConstructor 'mainConstructor',
		pld.PLD_Constructor 'constructor',
		pld.PLD_Contact 'contact',
		pld.PLD_PersonInCharge 'personInCharge',
		pld.PLD_Mobile 'mobile'
	FROM 
		crm_projectlist pl 
		INNER JOIN crm_projectlist_details pld ON pld.PL_ID = pl.PL_ID
	where (DATE(pl.PL_CreatedDate) BETWEEN DATE(startDate) AND DATE(endDate))
		AND IF(fromEmp = 'all', TRUE, pl.EmpID >= fromEmp)
		AND IF(toEmp = 'all', TRUE, pl.EmpID <= toEmp)
		AND IF(@typeId = 1, TRUE, pl.PL_CreatedBy = userId)
	ORDER BY pld.PLD_ID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptProjectListStartupFilter`;
DELIMITER |
CREATE PROCEDURE `crmRptProjectListStartupFilter`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT MAX(PL_CreatedDate) maxCreatedDate, MIN(PL_CreatedDate) minCreatedDate FROM crm_projectlist;
	SELECT var_id empId, var_name empName FROM ame_mt_emp WHERE IF(@typeId = 1, TRUE, var_id = CRM_FUN_GET_EMP_ID(userId)) ORDER BY var_id;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptQuotation`;
DELIMITER |
CREATE PROCEDURE `crmRptQuotation`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `fromEmp` varchar(255),IN `toEmp` varchar(255),IN `fromCust` varchar(255),IN `toCust` varchar(255),IN `groupBy` varchar(255),IN `fClass` varchar(255),IN `tClass` varchar(255),IN `v_postStatus` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
			qt.SalID AS saleId, 
			DATE_FORMAT(qt.SalDate, '%d-%b-%Y') as saleDate,
			qt.SalReference reference, 
			qt.postStatus,
			qt.PmtStatus pmtStatus,
			qt.TotalAmt totalAmt,  
			qt.DisInvDol disInvDol, 
			qt.TotalDis totalDis, 
			qt.NetTotalAmt netTotalAmt,
			qt.TotalSTax totalSTax,
			qt.totalVTax totalVTax,
			qt.CustID AS custId, 
			(SELECT CustName FROM tblcustomer WHERE CustID = qt.CustID) custName,
			(SELECT e.EmpName FROM tblemployee e WHERE e.EmpID = qt.EmpID) empName,
			qt.EmpID AS empId,
			qt.ClassID AS classId,
			(SELECT c.Des FROM tblclass c WHERE c.ClassID = qt.ClassID) className,
			qt.ApproveStatus approvedStatus,
			(SELECT Unit FROM tblcompanyreport LIMIT 1) businessUnit
		FROM tblsbquote qt 
		WHERE 
			(DATE(qt.SalDate) BETWEEN DATE(startDate) AND DATE(endDate))
			AND	IF(fromEmp = 'all',true,qt.EmpID >= fromEmp) AND IF(toEmp = 'all',true,qt.EmpID <= toEmp)
			AND	IF(fromCust = 'all',true,qt.CustID >= fromCust) AND IF(toCust = 'all',true,qt.CustID <= toCust)
			AND IF(fClass = 'all',true,qt.ClassID >= fClass) AND IF(tClass = 'all',true,qt.ClassID <= tClass)
			AND	IF(v_postStatus = 'all',qt.PostStatus IN ('Open','Closed'),qt.PostStatus = v_postStatus)
			-- AND IF(@typeId = 1,true,qt.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId))
			AND IF(@typeId = 1,true,qt.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1))
			ORDER BY 
					CASE
						WHEN groupBy = 'Customer' THEN qt.CustID
						WHEN groupBy = 'Employee' THEN qt.EmpID
						WHEN groupBy = 'SaleDate' THEN qt.SalDate
						ELSE qt.SalDate
					END
			DESC,qt.SalID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptQuotationDetails`;
DELIMITER |
CREATE PROCEDURE `crmRptQuotationDetails`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `fromEmp` varchar(255),IN `toEmp` varchar(255),IN `fromCust` varchar(255),IN `toCust` varchar(255),IN `groupBy` varchar(255),IN `fClass` varchar(255),IN `tClass` varchar(255),IN `v_postStatus` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
			qt.SalID AS saleId, 
			DATE_FORMAT(qt.SalDate, '%d-%b-%Y') as saleDate,
			DATE_FORMAT(qt.DueDate, '%d-%b-%Y') as dueDate,
			qt.SalType saleType,
			qt.SalReference reference, 
			qt.postStatus,
			qt.CustID AS custId, 
			(SELECT CustName FROM tblcustomer WHERE CustID = qt.CustID) custName,
			(SELECT e.EmpName FROM tblemployee e WHERE e.EmpID = qt.EmpID) empName,
			qt.EmpID AS empId,
			qt.ClassID AS classId,
			(SELECT c.Des FROM tblclass c WHERE c.ClassID = qt.ClassID) className,
			qt.ApproveStatus approvedStatus,
			qt.LocationID locationId,
			(SELECT Unit FROM tblcompanyreport LIMIT 1) businessUnit,
			qtd.LineNo lineNo,
			qtd.SalQty quantity,
			qtd.UnitPrice unitPrice,
			qtd.UomID uomId,
			qtd.ClassID dClassId,
			(SELECT c.Des FROM tblclass c WHERE c.ClassID = qtd.ClassID) dClassName,
			qtd.TotalAmt totalAmt,  
			qtd.DisDol disDol, 
			qtd.NetTotalAmt netTotalAmt,
			qtd.STaxDol sTaxDol,
			qtd.VTaxDol vTaxDol,
			i.ItemID itemId,
			i.ItemName itemName,
			i.itemcode itemCode
		FROM tblsbquote qt 
			INNER JOIN tblsbquotedetails qtd ON qt.SalID = qtd.SalID
			INNER JOIN tblitem i ON qtd.ItemID = i.ItemID
		WHERE 
			(DATE(qt.SalDate) BETWEEN DATE(startDate) AND DATE(endDate))
			AND	IF(fromEmp = 'all',true,qt.EmpID >= fromEmp) AND IF(toEmp = 'all',true,qt.EmpID <= toEmp)
			AND	IF(fromCust = 'all',true,qt.CustID >= fromCust) AND IF(toCust = 'all',true,qt.CustID <= toCust)
			AND IF(fClass = 'all',true,qt.ClassID >= fClass) AND IF(tClass = 'all',true,qt.ClassID <= tClass)
			AND	IF(v_postStatus = 'all',qt.PostStatus IN ('Open','Closed'),qt.PostStatus = v_postStatus)
			-- AND IF(@typeId = 1,true,qt.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId))
			AND IF(@typeId = 1,true,qt.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1));
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptQuotationFilterStartup`;
DELIMITER |
CREATE PROCEDURE `crmRptQuotationFilterStartup`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT MIN(SalDate) minSaleDate, MAX(SalDate) maxSaleDate FROM tblsbquote;
	SELECT c.CustID 'custId', c.CustName 'custName' FROM tblcustomer c WHERE IF(@typeId = 1,true,c.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1));
	SELECT EmpID 'empId', EmpName 'empName' FROM tblemployee WHERE IF(@typeId = 1,true,EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId));
	SELECT ClassID 'classId', Des 'className' FROM tblclass;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptSaleInv`;
DELIMITER |
CREATE PROCEDURE `crmRptSaleInv`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `fromEmp` varchar(255),IN `toEmp` varchar(255),IN `fromCust` varchar(255),IN `toCust` varchar(255),IN `custId` varchar(255),IN `groupBy` varchar(255),IN `fClass` varchar(255),IN `tClass` varchar(255),IN `v_postStatus` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
			si.SalID AS saleId, 
			DATE_FORMAT(si.SalDate, '%d-%b-%Y') as saleDate,
			si.SalReference reference, 
			si.postStatus,
			COALESCE(si.TotalAmt,0) totalAmt,  
			COALESCE(si.DisInvDol,0) disInvDol, 
			COALESCE(si.TotalDis,0) totalDis, 
			COALESCE(si.NetTotalAmt,0) netTotalAmt,
			COALESCE(si.TotalSTax,0) totalSTax,
			COALESCE(si.totalVTax,0) totalVTax,
			si.CustID AS custId, 
			tblc.CustName custName,
			(SELECT e.EmpName FROM tblemployee e WHERE e.EmpID = si.EmpID) empName,
			si.EmpID AS empId,
			si.ClassID AS classId,
			COALESCE((SELECT c.Des FROM tblclass c WHERE c.ClassID = si.ClassID),"") className,
			(SELECT Unit FROM tblcompanyreport LIMIT 1) businessUnit
		FROM tblsales si INNER JOIN (SELECT c.CustID, c.CustName FROM tblcustomer c) AS tblc ON tblc.CustID = si.CustID
		WHERE 
			(DATE(si.SalDate) BETWEEN DATE(startDate) AND DATE(endDate))
			AND	IF(fromEmp = 'all',true,si.EmpID >= fromEmp) AND IF(toEmp = 'all',true,si.EmpID <= toEmp)
			AND	IF(fromCust = 'all',true,si.CustID >= fromCust) AND IF(toCust = 'all',true,si.CustID <= toCust)
			AND IF(fClass = 'all',true,si.ClassID >= fClass) AND IF(tClass = 'all',true,si.ClassID <= tClass)
			AND	IF(v_postStatus = 'all',si.PostStatus IN ('Open','Posted'),si.PostStatus = v_postStatus)
			-- AND IF(@typeId = 1,true,si.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId))
			AND IF(@typeId = 1,true,si.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1))
			AND IF(custId = 'all',TRUE ,si.CustID = custId)
			AND IF(ISNULL((SELECT T.UID FROM tbluserprofile T WHERE T.UID = userId AND T.APPID = 'LOAD EMPLOYEE')), TRUE, si.CustID IN(SELECT var_cusid FROM tblusercustomer WHERE var_uid = userId))
			ORDER BY 
					CASE
						WHEN groupBy = 'Customer' THEN si.CustID
						WHEN groupBy = 'Employee' THEN si.EmpID
						WHEN groupBy = 'SaleDate' THEN si.SalDate
						ELSE si.SalID
					END
			DESC, IF(groupBy = 'SaleDate',si.SalID,si.SalDate) DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptSaleInvDetails`;
DELIMITER |
CREATE PROCEDURE `crmRptSaleInvDetails`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `fromEmp` varchar(255),IN `toEmp` varchar(255),IN `fromCust` varchar(255),IN `toCust` varchar(255),IN `custId` varchar(255),IN `fClass` varchar(255),IN `tClass` varchar(255),IN `v_postStatus` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
			si.SalID AS saleId, 
			DATE_FORMAT(si.SalDate, '%d-%b-%Y') as saleDate,
			si.SalReference reference, 
			si.postStatus,
			si.CustID AS custId, 
			tblc.CustName custName,
			(SELECT e.EmpName FROM tblemployee e WHERE e.EmpID = si.EmpID) empName,
			si.EmpID AS empId,
			si.ClassID AS classId,
			COALESCE((SELECT c.Des FROM tblclass c WHERE c.ClassID = si.ClassID),"") className,
			DATE_FORMAT(si.DueDate, '%d-%b-%Y') dueDate,
			si.LocationID locationId,
			(SELECT Unit FROM tblcompanyreport LIMIT 1) businessUnit,
			sd.LineNo lineNo,
			sd.SalQty quantity,
			sd.UnitPrice unitPrice,
			sd.UomID uomId,
			sd.ClassID dClassId,
			(SELECT c.Des FROM tblclass c WHERE c.ClassID = sd.ClassID) dClassName,
			COALESCE(sd.TotalAmt, 0) totalAmt,  
			COALESCE(sd.DisDol,0) disDol, 
			COALESCE(sd.NetTotalAmt,0) netTotalAmt,
			COALESCE(sd.STaxDol,0) sTaxDol,
			COALESCE(sd.VTaxDol, 0) vTaxDol,
			tbli.ItemID itemId,
			tbli.ItemName itemName,
			tbli.itemcode itemCode
		FROM tblsales si 
			INNER JOIN (SELECT c.CustID, c.CustName FROM tblcustomer c) AS tblc ON tblc.CustID = si.CustID
			INNER JOIN tblsalesdetails sd ON si.SalID = sd.SalID
			INNER JOIN (SELECT i.ItemID, i.ItemName, i.itemcode FROM tblitem i)tbli ON sd.ItemID = tbli.ItemID 
		WHERE 
			(DATE(si.SalDate) BETWEEN DATE(startDate) AND DATE(endDate))
			AND	IF(fromEmp = 'all',true,si.EmpID >= fromEmp) AND IF(toEmp = 'all',true,si.EmpID <= toEmp)
			AND	IF(fromCust = 'all',true,si.CustID >= fromCust) AND IF(toCust = 'all',true,si.CustID <= toCust)
			AND IF(fClass = 'all',true,si.ClassID >= fClass) AND IF(tClass = 'all',true,si.ClassID <= tClass)
			AND	IF(v_postStatus = 'all',si.PostStatus IN ('Open','Posted'),si.PostStatus = v_postStatus)
			-- AND IF(@typeId = 1,true,si.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId))
			AND IF(@typeId = 1,true,si.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1))
			AND IF(custId = 'all',TRUE ,si.CustID = custId)
			AND IF(ISNULL((SELECT T.UID FROM tbluserprofile T WHERE T.UID = userId AND T.APPID = 'LOAD EMPLOYEE')), TRUE, si.CustID IN(SELECT var_cusid FROM tblusercustomer WHERE var_uid = userId))
			ORDER BY si.SalID DESC, DATE(si.SalDate) DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptSaleOrder`;
DELIMITER |
CREATE PROCEDURE `crmRptSaleOrder`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `fromEmp` varchar(255),IN `toEmp` varchar(255),IN `fromCust` varchar(255),IN `toCust` varchar(255),IN `custId` varchar(255),IN `groupBy` varchar(255),IN `fClass` varchar(255),IN `tClass` varchar(255),IN `v_postStatus` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
			so.SalID AS saleId, 
			DATE_FORMAT(so.SalDate, '%d-%b-%Y') as saleDate,
			so.SalReference reference, 
			so.postStatus,
			so.PmtStatus pmtStatus,
			so.TotalAmt totalAmt,  
			so.DisInvDol disInvDol, 
			so.TotalDis totalDis, 
			so.NetTotalAmt netTotalAmt,
			so.TotalSTax totalSTax,
			so.totalVTax totalVTax,
			so.CustID AS custId, 
			cust.custname custName,
			(SELECT e.EmpName FROM tblemployee e WHERE e.EmpID = so.EmpID) empName,
			so.EmpID AS empId,
			so.ClassID AS classId,
			COALESCE((SELECT c.Des FROM tblclass c WHERE c.ClassID = so.ClassID), '') className,
			so.ApproveStatus approvedStatus,
			(SELECT Unit FROM tblcompanyreport LIMIT 1) businessUnit
		FROM tblsaleorder so INNER JOIN (SELECT c.custid, c.custname FROM tblcustomer c) AS cust ON cust.custid = so.custid
		WHERE 
			(DATE(so.SalDate) BETWEEN DATE(startDate) AND DATE(endDate))
			AND	IF(fromEmp = 'all',true,so.EmpID >= fromEmp) AND IF(toEmp = 'all',true,so.EmpID <= toEmp)
			AND	IF(fromCust = 'all',true,so.CustID >= fromCust) AND IF(toCust = 'all',true,so.CustID <= toCust)
			AND IF(fClass = 'all',true,so.ClassID >= fClass) AND IF(tClass = 'all',true,so.ClassID <= tClass)
			AND	IF(v_postStatus = 'all',so.PostStatus IN ('Open','Closed'),so.PostStatus = v_postStatus)
			-- AND IF(@typeId = 1,true,so.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId))
			AND IF(@typeId = 1,true,so.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1))
			AND IF(custId = 'all',TRUE ,so.CustID = custId)
			AND IF(ISNULL((SELECT T.UID FROM tbluserprofile T WHERE T.UID = userId AND T.APPID = 'LOAD EMPLOYEE')), TRUE, so.CustID IN(SELECT var_cusid FROM tblusercustomer WHERE var_uid = userId))
			ORDER BY 
					CASE
						WHEN groupBy = 'Customer' THEN so.CustID
						WHEN groupBy = 'Employee' THEN so.EmpID
						WHEN groupBy = 'SaleDate' THEN so.SalDate
						ELSE so.SalDate
					END
			DESC,so.SalID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptSaleOrderDetails`;
DELIMITER |
CREATE PROCEDURE `crmRptSaleOrderDetails`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `fromEmp` varchar(255),IN `toEmp` varchar(255),IN `fromCust` varchar(255),IN `toCust` varchar(255),IN `custId` varchar(255),IN `groupBy` varchar(255),IN `fClass` varchar(255),IN `tClass` varchar(255),IN `v_postStatus` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
			so.SalID AS saleId, 
			DATE_FORMAT(so.SalDate, '%d-%b-%Y') as saleDate,
			DATE_FORMAT(so.DueDate, '%d-%b-%Y') as dueDate,
			so.SalType saleType,
			so.SalReference reference, 
			so.postStatus,
			so.CustID AS custId, 
			cust.custname custName,
			(SELECT e.EmpName FROM tblemployee e WHERE e.EmpID = so.EmpID) empName,
			so.EmpID AS empId,
			so.ClassID AS classId,
			(SELECT c.Des FROM tblclass c WHERE c.ClassID = so.ClassID) className,
			so.ApproveStatus approvedStatus,
			so.LocationID locationId,
			(SELECT Unit FROM tblcompanyreport LIMIT 1) businessUnit,
			sod.LineNo lineNo,
			sod.SalQty quantity,
			sod.UnitPrice unitPrice,
			sod.UomID uomId,
			sod.ClassID dClassId,
			(SELECT c.Des FROM tblclass c WHERE c.ClassID = sod.ClassID) dClassName,
			sod.TotalAmt totalAmt,  
			sod.DisDol disDol, 
			sod.NetTotalAmt netTotalAmt,
			sod.STaxDol sTaxDol,
			sod.VTaxDol vTaxDol,
			i.ItemID itemId,
			i.ItemName itemName,
			i.itemcode itemCode
		FROM tblsaleorder so 
			INNER JOIN tblsaleorderdetails sod ON so.SalID = sod.SalID
			INNER JOIN tblitem i ON sod.ItemID = i.ItemID
			INNER JOIN (SELECT c.custid, c.custname FROM tblcustomer c) AS cust ON cust.custid = so.custid
		WHERE 
			(DATE(so.SalDate) BETWEEN DATE(startDate) AND DATE(endDate))
			AND	IF(fromEmp = 'all',true,so.EmpID >= fromEmp) AND IF(toEmp = 'all',true,so.EmpID <= toEmp)
			AND	IF(fromCust = 'all',true,so.CustID >= fromCust) AND IF(toCust = 'all',true,so.CustID <= toCust)
			AND IF(fClass = 'all',true,so.ClassID >= fClass) AND IF(tClass = 'all',true,so.ClassID <= tClass)
			AND	IF(v_postStatus = 'all',so.PostStatus IN ('Open','Closed'),so.PostStatus = v_postStatus)
			-- AND IF(@typeId = 1,true,so.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId))
			AND IF(@typeId = 1,true,so.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1))
			AND IF(custId = 'all',TRUE ,so.CustID = custId)
			AND IF(ISNULL((SELECT T.UID FROM tbluserprofile T WHERE T.UID = userId AND T.APPID = 'LOAD EMPLOYEE')), TRUE, so.CustID IN(SELECT var_cusid FROM tblusercustomer WHERE var_uid = userId));
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptSaleOrderFilterStartup`;
DELIMITER |
CREATE PROCEDURE `crmRptSaleOrderFilterStartup`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT MIN(SalDate) minSaleDate, MAX(SalDate) maxSaleDate FROM tblsaleorder;
	SELECT c.CustID 'custId', c.CustName 'custName' FROM tblcustomer c WHERE IF(@typeId = 1,true,c.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1));
	SELECT EmpID 'empId', EmpName 'empName' FROM tblemployee WHERE IF(@typeId = 1,true,EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId));
	SELECT ClassID 'classId', Des 'className' FROM tblclass;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptSaleReturn`;
DELIMITER |
CREATE PROCEDURE `crmRptSaleReturn`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `fromEmp` varchar(255),IN `toEmp` varchar(255),IN `fromCust` varchar(255),IN `toCust` varchar(255),IN `custId` varchar(255),IN `groupBy` varchar(255),IN `fClass` varchar(255),IN `tClass` varchar(255),IN `v_postStatus` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
			sr.SalID AS saleId, 
			sr.RetID 'retId',
			DATE_FORMAT(sr.SalDate, '%d-%b-%Y') as saleDate,
			sr.SalReference reference, 
			sr.postStatus,
			COALESCE(sr.TotalAmt,0) totalAmt,  
			COALESCE(sr.DisInvDol,0) disrnvDol, 
			COALESCE(sr.TotalDis,0) totalDis, 
			COALESCE(sr.NetTotalAmt,0) netTotalAmt,
			COALESCE(sr.TotalSTax,0) totalSTax,
			COALESCE(sr.totalVTax,0) totalVTax,
			sr.CustID AS custId, 
			tblc.CustName custName,
			(SELECT e.EmpName FROM tblemployee e WHERE e.EmpID = sr.EmpID) empName,
			sr.EmpID AS empId,
			sr.ClassID AS classId,
			COALESCE((SELECT c.Des FROM tblclass c WHERE c.ClassID = sr.ClassID),"") className,
			(SELECT Unit FROM tblcompanyreport LIMIT 1) businessUnit,
			COALESCE((SELECT SUM(sdd.RetQty) FROM tblsalereturndetails sdd WHERE sdd.RetID IN (SELECT s.RetID FROM tblsales_return s WHERE s.SalID = sr.SalID AND s.PostStatus IN ('Open', 'Posted')) AND sdd.ItemID = sd.ItemID), 0) 'retToDate',		
			COALESCE((SELECT md.SalQty FROM tblsalesdetails md WHERE md.SalID = sr.SalID AND md.ItemID = sd.ItemID), 0) 'salQty',
			sd.RetQty 'retQty'
		FROM tblsales_return sr 
			INNER JOIN (SELECT c.CustID, c.CustName FROM tblcustomer c) AS tblc ON tblc.CustID = sr.CustID
			LEFT JOIN tblsalereturndetails sd ON sr.RetID = sd.RetID
		WHERE 
			(DATE(sr.SalDate) BETWEEN DATE(startDate) AND DATE(endDate))
			AND	IF(fromEmp = 'all',true,sr.EmpID >= fromEmp) AND IF(toEmp = 'all',true,sr.EmpID <= toEmp)
			AND	IF(fromCust = 'all',true,sr.CustID >= fromCust) AND IF(toCust = 'all',true,sr.CustID <= toCust)
			AND IF(fClass = 'all',true,sr.ClassID >= fClass) AND IF(tClass = 'all',true,sr.ClassID <= tClass)
			AND	IF(v_postStatus = 'all',sr.PostStatus IN ('Open','Posted'),sr.PostStatus = v_postStatus)
			-- AND IF(@typeId = 1,true,sr.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId))
			AND IF(@typeId = 1,true,sr.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1))
			AND IF(custId = 'all',TRUE ,sr.CustID = custId)
			AND IF(ISNULL((SELECT T.UID FROM tbluserprofile T WHERE T.UID = userId AND T.APPID = 'LOAD EMPLOYEE')), TRUE, sr.CustID IN(SELECT var_cusid FROM tblusercustomer WHERE var_uid = userId))
			ORDER BY 
					CASE
						WHEN groupBy = 'Customer' THEN sr.CustID
						WHEN groupBy = 'Employee' THEN sr.EmpID
						WHEN groupBy = 'SaleDate' THEN DATE(sr.SalDate)
						ELSE sr.RetID
					END
			DESC, IF(groupBy = 'all',DATE(sr.SalDate),sr.RetID) DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptSaleReturnDetails`;
DELIMITER |
CREATE PROCEDURE `crmRptSaleReturnDetails`(IN `startDate` varchar(255),IN `endDate` varchar(255),IN `fromEmp` varchar(255),IN `toEmp` varchar(255),IN `fromCust` varchar(255),IN `toCust` varchar(255),IN `custId` varchar(255),IN `fClass` varchar(255),IN `tClass` varchar(255),IN `v_postStatus` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
		SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
			sr.SalID AS saleId, 
			sr.RetID retId,
			DATE_FORMAT(sr.SalDate, '%d-%b-%Y') as saleDate,
			DATE_FORMAT(sr.DueDate, '%d-%b-%Y') as dueDate,
			sr.SalReference reference, 
			sr.postStatus,
			sr.CustID AS custId, 
			tblc.CustName custName,
			(SELECT e.EmpName FROM tblemployee e WHERE e.EmpID = sr.EmpID) empName,
			sr.EmpID AS empId,
			sr.ClassID AS classId,
			COALESCE((SELECT c.Des FROM tblclass c WHERE c.ClassID = sr.ClassID),"") className,
			(SELECT Unit FROM tblcompanyreport LIMIT 1) businessUnit,
			sd.LineNo lineNo,
			sd.LocationID 'locationId', 
			sd.UomID 'uomId',
			sd.RetQty 'retQty',
			COALESCE((SELECT SUM(sdd.RetQty) FROM tblsalereturndetails sdd WHERE sdd.RetID IN (SELECT s.RetID FROM tblsales_return s WHERE s.SalID = sr.SalID AND s.PostStatus IN ('Open', 'Posted')) AND sdd.ItemID = sd.ItemID), 0) 'retToDate',		
			COALESCE((SELECT md.SalQty FROM tblsalesdetails md WHERE md.SalID = sr.SalID AND md.ItemID = sd.ItemID), 0) 'salQty',		
			sd.UnitPrice 'unitPrice', 
			sd.Factor 'factor',
			sd.ReportPrice 'reportPrice',
			sd.ClassID dClassId,
			(SELECT c.Des FROM tblclass c WHERE c.ClassID = sd.ClassID) dClassName,
			COALESCE(sd.TotalAmt, 0) totalAmt,  
			COALESCE(sd.DisDol,0) disDol, 
			COALESCE(sd.NetTotalAmt,0) netTotalAmt,
			COALESCE(sd.STaxDol,0) sTaxDol,
			COALESCE(sd.VTaxDol, 0) vTaxDol,
			tbli.ItemID itemId,
			tbli.ItemName itemName,
			tbli.itemcode itemCode
		FROM tblsales_return sr 
			INNER JOIN (SELECT c.CustID, c.CustName FROM tblcustomer c) AS tblc ON tblc.CustID = sr.CustID
			LEFT JOIN tblsalereturndetails sd ON sr.RetID = sd.RetID
			INNER JOIN (SELECT i.ItemID, i.ItemName, i.itemcode FROM tblitem i)tbli ON sd.ItemID = tbli.ItemID 
		WHERE 
			(DATE(sr.SalDate) BETWEEN DATE(startDate) AND DATE(endDate))
			AND	IF(fromEmp = 'all',true,sr.EmpID >= fromEmp) AND IF(toEmp = 'all',true,sr.EmpID <= toEmp)
			AND	IF(fromCust = 'all',true,sr.CustID >= fromCust) AND IF(toCust = 'all',true,sr.CustID <= toCust)
			AND IF(fClass = 'all',true,sr.ClassID >= fClass) AND IF(tClass = 'all',true,sr.ClassID <= tClass)
			AND	IF(v_postStatus = 'all',sr.PostStatus IN ('Open','Posted'),sr.PostStatus = v_postStatus)
			-- AND IF(@typeId = 1,true,sr.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId))
			AND IF(@typeId = 1,true,sr.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1))
			AND IF(custId = 'all',TRUE ,sr.CustID = custId)
			AND IF(ISNULL((SELECT T.UID FROM tbluserprofile T WHERE T.UID = userId AND T.APPID = 'LOAD EMPLOYEE')), TRUE, sr.CustID IN(SELECT var_cusid FROM tblusercustomer WHERE var_uid = userId))
			ORDER BY sr.SalID DESC, sr.SalDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptTask`;
DELIMITER |
CREATE PROCEDURE `crmRptTask`(IN `fromDate` varchar(255),IN `toDate` varchar(255),IN `groupBy` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT
		task.TA_ID 'taskId',
		task.TA_Subject 'subject',
		DATE_FORMAT(task.TA_StartDate,'%d-%b-%Y') 'startDate',
		DATE_FORMAT(task.TA_DueDate,'%d-%b-%Y') 'dueDate',
		task.TA_Priority 'priority',
		task.TA_StatusID 'statusId',
		(SELECT TS_Name From crm_task_status WHERE TS_ID = task.TA_StatusID) 'statusName',
		task.TA_RToType 'relatedToModule',
		task.TA_RToID 'relatedToId',
		CRM_FUN_MODULE_BY_RELATED(task.TA_RToType,task.TA_RToID) AS 'relatedToName',
		con.CO_ID 'conId',
		CONCAT(con.CO_Salutation,' ',con.CO_FirstName,' ',con.CO_LastName) 'contact',
		task.TA_ATo 'assignedToId',
		(SELECT ass.var_name FROM ame_user ass WHERE ass.var_id= task.TA_ATo) 'assignedToName',
		task.TA_CBy createBy,
		tblu.var_name 'createByName',
		DATE_FORMAT(task.TA_CDate,'%d-%b-%Y') 'createDate',
		CRM_FUN_REPORT_HEADER() businessUnit
	FROM 
		crm_task task
	LEFT OUTER JOIN (SELECT c.CO_ID, c.CO_Salutation, c.CO_FirstName, c.CO_LastName FROM crm_contact c) con ON task.TA_ContactID = con.CO_ID
	INNER JOIN (SELECT u.var_id, u.var_name FROM ame_user u) tblu ON tblu.var_id = task.TA_CBy
	WHERE DATE(task.TA_CDate) BETWEEN DATE(fromDate) AND DATE(toDate) 
	AND IF(groupBy = 'Module',task.TA_RToType <> '',TRUE)
	AND IF(@typeId = 1,TRUE,(task.TA_CBy = userId OR task.TA_ATo = userId))
	ORDER BY
		CASE	
			WHEN groupBy = 'Module' THEN task.TA_RToType
			WHEN groupBy = 'CreateDate' THEN task.TA_CDate
			ELSE task.TA_ID
		END DESC, IF(groupBy = 'CreateDate',task.TA_ID,task.TA_CDate) DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptTaskStartupFilter`;
DELIMITER |
CREATE PROCEDURE `crmRptTaskStartupFilter`()
    DETERMINISTIC
BEGIN
	SELECT MIN(TA_CDate) minCreateDate, MAX(TA_CDate) maxCreateDate FROM crm_task;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptVisit`;
DELIMITER |
CREATE PROCEDURE `crmRptVisit`(IN startDate varchar(255),IN endDate varchar(255),IN groupBy varchar(255),IN userId varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
	SELECT 
	SC_ID 'sc_Id',
	SC_Repeat 'sc_Repeat',
	SC_Frequency 'sc_Frequency',
	SC_Amount 'sc_Amount',
	SC_Tag 'sc_Tag',
	DATE_FORMAT(SC_StartDate, '%d-%b-%Y %l:%i %p') 'cDate',
	DATE_FORMAT(SC_EndRepeat,'%d-%b-%Y %l:%i %p') 'sc_EndRepeat',
	(SELECT u.UName FROM tbluser u WHERE u.UID = SC_CreateBy) 'cBy',
	(SELECT Unit FROM tblcompanyreport LIMIT 1) 'businessUnit',
	DATE_FORMAT(SC_StartDate, '%d-%b-%Y') 'sc_StartDate'
FROM crm_schedule_master sm
WHERE
	(DATE(SC_StartDate) BETWEEN DATE(startDate) AND DATE(endDate))
	AND IF(@typeId = 1, TRUE, FALSE)
ORDER BY 
	CASE
		WHEN groupBy = 'CreateDate' THEN DATE(SC_StartDate)
		ELSE SC_ID
	END;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptVisitDetails`;
DELIMITER |
CREATE PROCEDURE `crmRptVisitDetails`(IN startDate varchar(255),IN endDate varchar(255),IN emp varchar(255), IN cust varchar(255), IN var_status varchar(255), IN var_type varchar(255), IN var_shop varchar(255), IN groupBy varchar(255),IN userId VARCHAR(255))
    DETERMINISTIC
BEGIN
	SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = CRM_FUN_GET_ROLE_BY_UID(userId);
	SELECT
	sd.SC_ID 'sc_Id',
	sm.SC_Repeat 'sc_Repeat',
	sm.SC_Frequency 'sc_Frequency',
	sm.SC_Amount 'sc_Amount',
	DATE_FORMAT(sm.SC_StartDate, '%d-%b-%Y %l:%i %p') 'sc_CLongDate',
	DATE_FORMAT(sm.SC_StartDate, '%d-%b-%Y') 'sc_CShortDate',
	DATE_FORMAT(sm.SC_EndRepeat, '%d-%b-%Y %l:%i %p') 'sc_EndRepeat',
	(SELECT u.var_name FROM ame_user u WHERE u.var_id = sm.SC_CreateBy) 'sc_CBy',
	sd.VI_ID 'vi_Id',
	sd.SC_Title 'sc_Title',
	DATE_FORMAT(sd.SC_startDate, '%d-%b-%Y %l:%i %p') 'sc_VisitLongDate',
	DATE_FORMAT(sd.SC_startDate, '%d-%b-%Y') 'sc_VisitShortDate',
	CONCAT(sd.SC_Duration, ' mins') 'sc_Duration',
	CONCAT('[', e.var_id ,'] ', e.var_name) 'sc_Employee',
	CONCAT('[', c.var_id ,'] ', c.var_name) 'sc_Customer',
	SUBSTRING_INDEX(SC_Location,'|',-1) 'sc_Location',
	sd.SC_Lat 'sc_Lat',
	sd.SC_Lng 'sc_Lng',
	sd.SC_Shop 'sc_Shop',
	sd.SC_VisitType 'sc_VisitType',
	IF(sd.VI_Status = 'Pending',IF(NOW() <= sd.SC_startDate, 'Pending', 'Missed'),sd.VI_Status) 'vi_Status',
	CRM_FUN_REPORT_HEADER() 'businessUnit'
FROM
	crm_schedule_master sm
RIGHT JOIN crm_schedule_detail sd ON sm.SC_ID = sd.SC_ID
INNER JOIN ame_mt_cus c ON sd.SC_Customer = c.var_id
INNER JOIN ame_mt_emp e ON sd.SC_Employee = e.var_id
	WHERE
		(DATE(sd.SC_startDate) BETWEEN DATE(startDate) AND DATE(endDate))
		AND IF(emp = 'all',TRUE,sd.SC_Employee = emp)
		AND IF(cust = 'all',TRUE,sd.SC_Customer = cust)
		AND IF(var_status = 'all',TRUE,IF(var_status = 'Missed', NOW() > sd.SC_startDate AND sd.VI_Status = 'Pending', sd.VI_Status = var_status))
		AND IF(var_type = 'all',TRUE,sd.SC_VisitType = var_type)
		AND IF(var_shop = 'all',TRUE,sd.SC_Shop = var_shop)
		AND IF(@typeId = 1, TRUE,FALSE)
	ORDER BY
		CASE
			WHEN groupBy = 'visit' THEN sd.SC_ID
			WHEN groupBy = 'employee' THEN sd.SC_Employee
			WHEN groupBy = 'customer' THEN sd.SC_Customer
			WHEN groupBy = 'status' THEN sd.VI_Status
			WHEN groupBy = 'visitType' THEN sd.SC_VisitType
			WHEN groupBy = 'shop' THEN sd.SC_Shop
			WHEN groupBy = 'CreateDate' THEN DATE(sd.SC_startDate)
			ELSE DATE(sd.VI_ID)
		END;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptVisitFilter`;
DELIMITER |
CREATE PROCEDURE `crmRptVisitFilter`(IN rptType varchar(255), IN var_change tinyint, IN userId varchar(255))
    DETERMINISTIC
BEGIN
	-- List Create Date
	IF rptType = 'summary' THEN
		SELECT MIN(c.SC_StartDate) 'minCreateDate', MAX(c.SC_StartDate) 'maxCreateDate' FROM crm_schedule_master c; 
	ELSE
		SELECT MIN(c.SC_startDate) 'minCreateDate', MAX(c.SC_startDate) 'maxCreateDate' FROM crm_schedule_detail c;
	END IF;
	
	IF var_change = 0 THEN
		-- List User Type
		SELECT RM_TypeID INTO @typeId FROM crm_role WHERE RM_ID = (SELECT URoleID FROM tbluser WHERE UID = userId);
		-- List Employee
		SELECT e.EmpID, e.EmpName FROM tblemployee e WHERE IF(@typeId = 1,true,EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId)) ORDER BY e.EmpName;
		-- List Customer
		SELECT c.CustID, c.CustName FROM tblcustomer c WHERE IF(@typeId = 1,true,c.CustID IN (SELECT ec.CustID FROM tblemployeecustomer ec WHERE ec.EmpID = (SELECT ue.EmpID FROM tbluseremployee ue WHERE ue.UID = userId) AND ec.Assigned = 1)) ORDER BY c.CustName;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmRptVisitSaleOrder`;
DELIMITER |
CREATE PROCEDURE `crmRptVisitSaleOrder`(
	IN visitId VARCHAR(255)
)
    DETERMINISTIC
BEGIN
	SELECT
		d.SalID 'saleId',
		COALESCE (SalType, '') 'salType',
		COALESCE (s.classId, '') 'classId',
		COALESCE (Remark, '') 'remark',
		COALESCE (SalReference, '') 'salReference',
		COALESCE (s.PriceCode, '') 'priceCode',
		COALESCE (s.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 (s.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 (s.NetTotalAmt, 0) 'netTotalAmt',
		COALESCE (ShipTo, '') 'shipTo',
		COALESCE ((SELECT shipname FROM tblshipaddress WHERE docid = c.CustID AND shipid = ShipTo),'') 'shipAdd1',
		LineNo AS lineNo,
		ItemID AS itemId,
		COALESCE ((SELECT ItemName FROM tblitem i WHERE i.ItemID = d.ItemID LIMIT 1),'') 'itemName',
		UomID AS uomId,
		d.LocationID AS locationId,
		SalQty AS saleQuantity,
		UnitPrice AS unitPrice,
		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,
		DisInv AS disInv,
		COALESCE (TransDesc, '') description,
		(SELECT ComName FROM tblcompanyreport) 'comEN',
		(SELECT ComNameKh FROM tblcompanyreport) 'comKH'
FROM
	tblsaleorderdetails d
INNER JOIN tblsaleorder s ON s.SalID = d.SalID
LEFT JOIN tblcustomer c ON c.custid = s.custid
WHERE
	s.SalID = (SELECT SaleID FROM crm_schedule_detail WHERE VI_ID = visitId)
ORDER BY LineNo ASC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmSearchSaleRapForMobile`;
DELIMITER |
CREATE PROCEDURE `crmSearchSaleRapForMobile`(IN `str_search` varchar(255),IN `rowNum` int,IN `pageNum` int, in `userId` varchar(255))
    DETERMINISTIC
begin
	declare roleTypeId int default 0;
	declare pages int default 0;
	declare totalPage int default 0;

	select RM_TypeID into roleTypeId from crm_role 
	where RM_ID = (select tbluser.URoleID from tbluser where tbluser.UID = userId);
	set pages = (pageNum - 1) * rowNum;

	if roleTypeId = 1 then

		select count(distinct e.EmpID) into totalPage 
		from tblemployee e inner join tblemployeecustomer ec on e.EmpID = ec.EmpID 
		where (e.EmpID like concat('%', str_search,'%') or e.EmpName like concat('%', str_search,'%')) and ec.Assigned = 1;

		select distinct e.EmpID empId, e.EmpName empName 
		from tblemployee e inner join tblemployeecustomer ec on e.EmpID = ec.EmpID 
		where (e.EmpID like concat('%', str_search,'%') or e.EmpName like concat('%', str_search,'%')) and ec.Assigned = 1 
		limit rowNum offset pages;
	else

		select count(EmpID) into totalPage 
		from tblemployee 
		where (EmpID like concat('%', str_search,'%') or EmpName like concat('%', str_search,'%')) and Inactive = 0 and EmpID = (select ue.EmpID from tbluseremployee ue where ue.UID = userId);

		select EmpID empId, EmpName empName 
		from tblemployee 
		where (EmpID like concat('%', str_search,'%') or EmpName like concat('%', str_search,'%')) and EmpID = (select ue.EmpID from tbluseremployee ue where ue.UID = userId) and Inactive = 0 
		limit rowNum offset pages;
	end if;

	set totalPage = CEIL(totalPage / rowNum);

	SELECT totalPage;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmUpdateAuthorisationApprove`;
DELIMITER |
CREATE PROCEDURE `crmUpdateAuthorisationApprove`(IN UserID varchar(255),IN SProID varchar(255),IN  SProName varchar(255),IN SAuthID varchar(255),IN SAuthGID varchar(255),IN SEmpID varchar(255),IN SAuthStatus varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE EmpID VARCHAR(255) DEFAULT('');
	DECLARE Message VARCHAR(20) DEFAULT('not exist');
	DECLARE L BIGINT DEFAULT(0);
	DECLARE CheckStatus INT DEFAULT(0);
	DECLARE PStatus VARCHAR(255);

	-- Check Can Update and Find Line
	SELECT ap.Auth_Line,
	(IF(ap.Auth_ProcessName="Customer" AND cust.CrmApproval="0",1,
	IF(ap.Auth_ProcessName="Budget Requisition" AND LOWER(br.`ApprovalStatus`) = "requested",1,
  IF(ap.Auth_ProcessName="General Requisition" AND LOWER(gr.`ApprovalStatus`) = "requested",1,
  IF(ap.Auth_ProcessName="Logistic Material Request" AND LOWER(lm.`Status`) = "requested",1,
  IF(ap.Auth_ProcessName="Temporary Credit" AND LOWER(ci.`Status`) = "requested",1,
  IF(ap.Auth_ProcessName="Over Due Date" AND LOWER(od.`Status`) = "requested",1,
  IF(ap.Auth_ProcessName="Material Request" AND LOWER(mr.`Status`) = "requested",1,
  IF(ap.Auth_ProcessName="Expense Request" AND LOWER(er.`Status`) = "requested",1,
  IF(Auth_ProcessName="Sale Order" AND LOWER(sa.ApproveStatus) = "requested",1,
	IF(Auth_ProcessName="Quote" AND LOWER(qu.ApproveStatus) = "requested",1,
	IF(ap.Auth_ProcessName="Logistic Expense Request" AND LOWER(le.`Status`) = "requested",1,0))))))))))))

	INTO L, CheckStatus
	FROM hrm_authorisation_approved ap
	LEFT JOIN crm_customer cust ON ap.Auth_ProcessID = cust.CustID
  LEFT JOIN logistic_material lm ON ap.Auth_ProcessID = lm.EntryNo
	LEFT JOIN tblcustomerissue ci ON ap.Auth_ProcessID = ci.IssueID
  LEFT JOIN tblsaleorder sa ON ap.Auth_ProcessID = sa.SalID
	LEFT JOIN tblcustomeroverdue od ON ap.Auth_ProcessID = od.IssueID
  LEFT JOIN tblsbquote qu ON ap.Auth_ProcessID = qu.SalID
	LEFT JOIN crm_frm_general gr ON ap.Auth_ProcessID = gr.FrmID
	LEFT JOIN crm_frm_budget br ON ap.Auth_ProcessID = br.FrmID
  LEFT JOIN tblmaterialrequest mr ON ap.Auth_ProcessID = mr.EntryNo
  LEFT JOIN tblexpenserequest er ON ap.Auth_ProcessID = er.EntryNo
	LEFT JOIN logistic_expense_request le ON ap.Auth_ProcessID =  le.EntryNo
	WHERE ap.Auth_ProcessID = SProID AND ap.Auth_ProcessName = SProName AND ap.Auth_ID = SAuthID AND ap.Auth_GroupID = SAuthGID AND ap.Auth_EmpID = SEmpID;
	
	-- Find EmpID
	SELECT eu.EmpID INTO EmpID FROM tbluser u LEFT JOIN tbluseremployee eu ON(u.UID = eu.UID) WHERE eu.UID = UserID;

	IF SEmpID = EmpID AND L <> 0 AND CheckStatus = 1 THEN
		UPDATE hrm_authorisation_approved SET Auth_Status = LOWER(SAuthStatus) WHERE Auth_Line = L;
		CALL spHRMAddLog(UserID, "insert", "Authorsation Approve", SProID);

		-- Check Auth When Amount is full
		CALL spHRMGetCheckAuthorisationTranApproved(UserID, SProID, SProName, SAuthID, SAuthGID);
		
		SET Message = 'success';
		CALL hrm_message_param3('1101301', 'AuthApprove', 'update', SAuthStatus, SProName, SProID);

	ELSE

		SET Message = 'not allow';

		CALL hrm_message_param3('1101302', 'AuthApprove', 'notallowed', SAuthStatus, SProName, SProID);

	END IF;
	SELECT Message;
	
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmUserActivitiesList`;
DELIMITER |
CREATE PROCEDURE `crmUserActivitiesList`()
    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 `crmViewCampaignById`;
DELIMITER |
CREATE PROCEDURE `crmViewCampaignById`(IN `campId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	CALL listTasksRelatedToModule(campId);
	SELECT TS_ID taskStatusId, TS_Name taskStatusName FROM crm_task_status;
	CALL listEventsRelatedToModule(campId);
	SELECT LO_ID loId, LO_Name loName FROM crm_location ORDER BY LO_ID DESC;
	CALL listCallsRelatedToModule(campId);
	SELECT CLS_ID callStatusId, CLS_Name callStatusName FROM crm_call_status;
	CALL listMeetingsRelatedToModule(campId);
	SELECT MS_ID statusId, MS_Name statusName FROM crm_meeting_status;
	CALL listCrmParentCampaigns(campId);
	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 = campId 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 OP_ID opId, OP_Name opName,OP_Amt opAmount,  OP_CloseDate opCloseDate, OP_CustID custID, (SELECT CustName FROM tblcustomer WHERE CustID = OP_CustID) custName, OP_StageID stageId, (SELECT OS_Name FROM crm_opportunity_stage WHERE OS_ID = OP_StageID) stageName FROM crm_opportunity WHERE OP_CampID = campId;
	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;
	-- CALL crm_list_collaboration_by_module(campId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmViewCaseById`;
DELIMITER |
CREATE PROCEDURE `crmViewCaseById`(IN `caseId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	CALL listTasksRelatedToModule(caseId);
	SELECT TS_ID taskStatusId, TS_Name taskStatusName FROM crm_task_status;
	CALL listEventsRelatedToModule(caseId);
	SELECT LO_ID loId, LO_Name loName FROM crm_location;
	CALL listCallsRelatedToModule(caseId);
	SELECT CLS_ID callStatusId, CLS_Name callStatusName FROM crm_call_status;
	CALL listMeetingsRelatedToModule(caseId);
	SELECT MS_ID statusId, MS_Name statusName FROM crm_meeting_status;
	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 = caseId 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 CO_ID conID, CO_Salutation conSalutation, CO_FirstName conFirstname, CO_LastName conLastname FROM crm_contact;
	SELECT CS_OriginID originId, CS_Title origiTitle FROM crm_case_origin;
	SELECT CSP_ID priorityId, CSP_Name priorityName FROM crm_case_priority;
	SELECT CSS_ID statusId, CSS_Name statusName FROM crm_case_status;
	SELECT CST_ID caseTypeId, CST_Name caseTypeName FROM crm_case_type;
	SELECT CustID custID, CustName custName, PriceCode priceCode FROM tblcustomer WHERE CrmApproval = 1;
	SELECT ItemID itemId, ItemName itemName FROM tblitem;
	SELECT tbluser.UID userID, tbluser.UName username FROM tbluser INNER JOIN tbluserapp ON tbluser.UID = tbluserapp.UID WHERE tbluserapp.AppID = "CRM" AND tbluser.URoleID NOT IN (SELECT RM_ID FROM crm_role WHERE RM_Name = "CRM_ADMINISTRATOR");
	SELECT A_ID articleId, A_Title articleTitle FROM crm_case_article;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmViewCompetitorById`;
DELIMITER |
CREATE PROCEDURE `crmViewCompetitorById`(IN `contactId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	CALL listTasksRelatedToModule(contactId);
	SELECT TS_ID taskStatusId, TS_Name taskStatusName FROM crm_task_status;
	CALL listEventsRelatedToModule(contactId);
	SELECT LO_ID loId, LO_Name loName FROM crm_location;
	CALL listCallsRelatedToModule(contactId);
	SELECT CLS_ID callStatusId, CLS_Name callStatusName FROM crm_call_status;
	CALL listMeetingsRelatedToModule(contactId);
	SELECT MS_ID statusId, MS_Name statusName FROM crm_meeting_status;
	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 = contactId 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 LS_ID sourceID, LS_Name sourceName FROM crm_lead_source;
	-- CALL listOpportunitiesRelatedToContact(contactId);
	-- 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_contactId = contactId;
	SELECT CO_ID conID, CO_Salutation conSalutation, CO_FirstName conFirstname, CO_LastName conLastname FROM crm_contact; -- list all contact
	-- SELECT CO_ID conID, CO_Salutation conSalutation, CO_FirstName conFirstname, CO_LastName conLastname  FROM crm_contact WHERE CO_ReportTo IS NULL; -- report_to contact
	-- SELECT CustID custID, CustName custName, PriceCode priceCode FROM tblcustomer WHERE CrmApproval = 1;
	SELECT UomID 'uomId' FROM tbluom;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmViewContactById`;
DELIMITER |
CREATE PROCEDURE `crmViewContactById`(IN `contactId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	CALL listTasksRelatedToModule(contactId);
	SELECT TS_ID taskStatusId, TS_Name taskStatusName FROM crm_task_status;
	CALL listEventsRelatedToModule(contactId);
	SELECT LO_ID loId, LO_Name loName FROM crm_location;
	CALL listCallsRelatedToModule(contactId);
	SELECT CLS_ID callStatusId, CLS_Name callStatusName FROM crm_call_status;
	CALL listMeetingsRelatedToModule(contactId);
	SELECT MS_ID statusId, MS_Name statusName FROM crm_meeting_status;
	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 = contactId 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 LS_ID sourceID, LS_Name sourceName FROM crm_lead_source;
	CALL listOpportunitiesRelatedToContact(contactId);
	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_contactId = contactId;
	SELECT CO_ID conID, CO_Salutation conSalutation, CO_FirstName conFirstname, CO_LastName conLastname FROM crm_contact; -- list all contact
	SELECT CO_ID conID, CO_Salutation conSalutation, CO_FirstName conFirstname, CO_LastName conLastname  FROM crm_contact WHERE CO_ReportTo IS NULL; -- report_to contact
	SELECT CustID custID, CustName custName, PriceCode priceCode FROM tblcustomer WHERE CrmApproval = 1;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmViewCustomerById`;
DELIMITER |
CREATE PROCEDURE `crmViewCustomerById`(IN `custId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
/*
	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 `crmViewLeadById`;
DELIMITER |
CREATE PROCEDURE `crmViewLeadById`(IN `leadId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	CALL listTasksRelatedToLead(leadId);
	SELECT TS_ID taskStatusId, TS_Name taskStatusName FROM crm_task_status;
	CALL listEventsRelatedToLead(leadId);
	SELECT LO_ID loId, LO_Name loName FROM crm_location;
	CALL listCallsRelatedToLead(leadId);
	SELECT CLS_ID callStatusId, CLS_Name callStatusName FROM crm_call_status;
	CALL listMeetingsRelatedToLead(leadId);
	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 = leadId 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 CA_ID campID, CA_Name campName FROM crm_camp;
	SELECT I_ID industID, I_Name industName FROM crm_industry;
	SELECT LST_ID statusID, LST_Name statusName FROM crm_lead_status;
	SELECT LS_ID sourceID, LS_Name sourceName FROM crm_lead_source;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crmViewOpportunityById`;
DELIMITER |
CREATE PROCEDURE `crmViewOpportunityById`(IN `opId` varchar(255),IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	CALL listTasksRelatedToOpportunity(opId);
	SELECT TS_ID taskStatusId, TS_Name taskStatusName FROM crm_task_status;
	CALL listEventsRelatedToModule(opId);
	SELECT LO_ID loId, LO_Name loName FROM crm_location;
	CALL listCallsRelatedToOpportunity(opId);
	SELECT CLS_ID callStatusId, CLS_Name callStatusName FROM crm_call_status;
	CALL listMeetingsRelatedToOpportunity(opId);
	SELECT MS_ID statusId, MS_Name statusName FROM crm_meeting_status;
	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 = opId 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 LS_ID sourceID, LS_Name sourceName FROM crm_lead_source;
	SELECT CO_ID conID, CO_Salutation conSalutation, CO_FirstName conFirstname, CO_LastName conLastname FROM crm_contact;
	SELECT CA_ID campID, CA_Name campName FROM crm_camp;
	SELECT PriceCode priceCode, Description des FROM tblpricecode;
	SELECT CustID custID, CustName custName, PriceCode priceCode FROM tblcustomer WHERE CrmApproval = 1;
	SELECT OS_ID osId, OS_Name osName FROM crm_opportunity_stage;
	SELECT OT_ID otId, OT_Name otName FROM crm_opportunity_type;
	SELECT SysCode sysCode, LocationID locationId, Des locationName FROM tbllocation;
	SELECT SysCode sysCode, UomID uomId, Des Des, Remark remark FROM tbluom;
	SELECT ClassID classId, Des des, Inactive inactive, SortOr sortOr FROM tblclass;
	SELECT ItemID itemId, ItemName itemName, UomID uomId FROM tblitem;
	CAll listQuotationRelatedToOpportunity(opId);
	CALL listSaleOrdersRelatedToOpportunity(opId);
	CALL listContactsRelatedToOpportunity(opId);
	CALL listCustomFieldsOfQuotations(opId);
	CALL listCustomFieldsOfSaleorder(opId);
	-- SELECT PL_ID id, PL_Name `name`, PL_EndDate endDate  FROM crm_project_list WHERE LP_ID IN (SELECT LPID FROM crm_opportunity_lead_project WHERE OPID = opId);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_addCompetitorItem`;
DELIMITER |
CREATE PROCEDURE `crm_addCompetitorItem`(IN `arraydelete` varchar(1000),IN `arrayItem` varchar(1000) ,IN `array` varchar(1000))
    DETERMINISTIC
BEGIN
		
		set @sqlDelete = concat("DELETE FROM hbu_competitor_item WHERE COM_ID IN (",arraydelete,") AND ItemID IN (",arrayItem,")");
    PREPARE stmt1 FROM @sqlDelete;
    EXECUTE stmt1;

	  set @sql = concat("INSERT INTO hbu_competitor_item(COM_ID,ItemID,ItemPrice) VALUES ", array);
    PREPARE stmt FROM @sql;
    EXECUTE stmt;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_add_user_activity`;
DELIMITER |
CREATE PROCEDURE `crm_add_user_activity`(var_action varchar(255), var_module varchar(255), var_mId varchar(255), var_uid varchar(255))
    DETERMINISTIC
BEGIN
	INSERT INTO `crm_activity` (`AC_ID`, `AC_Action`, `AC_ModuleName`, `AC_ModuleID`, `AC_ByUser`, `AC_Date`) 
  VALUES (generateAutoId("AC"), var_action, var_module,  var_mId, var_uid, NOW());
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_afc_list_by_group`;
DELIMITER |
CREATE PROCEDURE `crm_afc_list_by_group`(var_group varchar(255))
    DETERMINISTIC
BEGIN
	SELECT AFID 'acfId',Label 'label', AFT 'afType', Description 'description', Rang 'rang'
	FROM crm_optional_field WHERE `Group` = var_group ORDER BY Rang;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_afc_list_by_group_by_custid`;
DELIMITER |
CREATE PROCEDURE `crm_afc_list_by_group_by_custid`(var_group varchar(255),var_custid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT AFID 'acfId',Label 'label', AFT 'afType', Description 'description', Rang 'rang', REPLACE(AFV,"\\r\\n",'') 'afValue'
	FROM crm_optional_field WHERE `Group` = var_group
	;
	SELECT COALESCE(AF1,'') 'acf1',COALESCE(AF2,'') 'acf2',COALESCE(AF3,'') 'acf3',COALESCE(AF4,'') 'acf4',COALESCE(AF5,'') 'acf5',
         COALESCE(AF6,'') 'acf6',COALESCE(AF7,'') 'acf7',COALESCE(AF8,'') 'acf8',COALESCE(AF9,'') 'acf9',COALESCE(AF10,'') 'acf10'
	FROM tblcustomer WHERE CustID = var_custid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_afc_list_by_group_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_afc_list_by_group_by_id`(var_group varchar(255),var_acf varchar(255))
    DETERMINISTIC
BEGIN
	SELECT AFID 'acfId',Label 'label', AFT 'afType', Description 'description', Rang 'rang', AFV 'afValue'
	FROM crm_optional_field WHERE `Group` = var_group AND AFID = var_acf
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_afc_update_by_group_id`;
DELIMITER |
CREATE PROCEDURE `crm_afc_update_by_group_id`(var_group varchar(255),var_acfid varchar(255),var_label varchar(255),var_type varchar(255),var_des varchar(255),var_val varchar(255),var_userid varchar(255))
    DETERMINISTIC
BEGIN
	UPDATE crm_optional_field SET `Label`=var_label, `AFV`=var_val, `AFT`=var_type, `Description`=var_des, `Group`= var_group
	WHERE `AFID`=var_acfid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_approval_quote_sale_order`;
DELIMITER |
CREATE PROCEDURE `crm_approval_quote_sale_order`(in var_obj_id  varchar(255), in var_emp_id varchar(255), in var_pro varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE authId VARCHAR(255) DEFAULT "";
	DECLARE authType VARCHAR(255) DEFAULT "";
	DECLARE re INTEGER DEFAULT 0;

	SET re = (SELECT RE_IsRequire FROM crm_module_require_approval WHERE RE_Module = var_pro 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_emp_id AND ae.Auth_Process = var_pro; 

		IF authType = "Individual" THEN

			IF var_pro = "Sale Order" THEN 
				UPDATE tblsaleorder SET tblsaleorder.SAuthID = authId WHERE tblsaleorder.SalID = var_obj_id;
			ELSE
				UPDATE tblsbquote SET tblsbquote.QAuthID = authId WHERE tblsbquote.SalID = var_obj_id;
			END IF;

			CALL spHRMAddAuthorisationTemp(authId,var_obj_id);
			CALL spHRMAddIAuthorisationApproved(authId, var_obj_id, var_pro);
			

		ELSE

			IF var_pro = "Sale Order" THEN 
				UPDATE tblsaleorder SET tblsaleorder.SAuthID = authId WHERE tblsaleorder.SalID = var_obj_id;
			ELSE
				UPDATE tblsbquote SET tblsbquote.QAuthID = authId WHERE tblsbquote.SalID = var_obj_id;
			END IF;

			CALL spHRMAddAuthorisationTemp(authId,var_obj_id);
			CALL spHRMAddGAuthorisationApproved(authId, var_obj_id, var_pro);
			

		END IF;
		
	ELSE
		IF var_pro  = 'Sale Order' THEN
			UPDATE tblsaleorder SET tblsaleorder.ApproveStatus = 'Approved' WHERE tblsaleorder.SalID = var_obj_id;
		ELSE
			UPDATE tblsbquote SET tblsbquote.ApproveStatus = 'Approved' WHERE tblsbquote.SalID = var_obj_id;
		END IF;
	END IF;



END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_approval_templory`;
DELIMITER |
CREATE PROCEDURE `crm_approval_templory`(in var_obj_id  varchar(255), in var_user_id varchar(255), in var_pro varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE re INTEGER DEFAULT 0;
	SET re = (SELECT RE_IsRequire FROM crm_module_require_approval WHERE RE_Module = var_pro LIMIT 1);
	IF re = 1 THEN
		CALL ATS_PRO_RequestAuthEmp(var_obj_id, var_user_id, var_pro);
	ELSE
			IF var_pro  = 'Over Due Date' THEN
				UPDATE ame_mt_tem_odd SET dat_approved = NOW(), var_status = 'Approved' WHERE var_id =  var_obj_id;
			ELSEIF var_pro  = 'Budget Requisition' THEN
				UPDATE crm_frm_budget SET ApprovalDate = NOW(), ApprovalStatus = 'Approved' WHERE FrmID =  var_obj_id;
			ELSEIF var_pro  = 'General Requisition' THEN
				UPDATE crm_frm_general SET ApprovalDate = NOW(), ApprovalStatus = 'Approved' WHERE FrmID =  var_obj_id;
			ELSEIF var_pro  = 'Temporary Credit' THEN
				UPDATE ame_mt_tem_tc SET dat_approved = NOW(), `var_status` = 'Approved' WHERE var_id =  var_obj_id;
			END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_checkContactName`;
DELIMITER |
CREATE PROCEDURE `crm_checkContactName`(IN `status` varchar(255),IN `firstName` varchar(255),IN `lastName` varchar(255),IN `ID`varchar(255))
    DETERMINISTIC
BEGIN
	IF ID = 'id' THEN 		
		SELECT COUNT(CO_Salutation) as'Count' FROM crm_contact WHERE CO_Salutation = `status` AND CO_FirstName = firstName AND CO_LastName = lastName;	
	ELSE
		SELECT COUNT(CO_Salutation) as'Count' FROM crm_contact WHERE CO_Salutation = `status` AND CO_FirstName = firstName AND CO_LastName = lastName AND CO_ID != ID;
  END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_checkCustomerName`;
DELIMITER |
CREATE PROCEDURE `crm_checkCustomerName`(IN `CuName` varchar(255),IN `ID`varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE countCustApp  INT;
	DECLARE countCustPad  INT;

	IF ID = 'id' THEN 		
		SELECT COUNT(var_name) INTO countCustApp FROM crm_customer WHERE var_name = CuName;
			IF countCustApp <> 0 THEN
				SELECT COUNT(var_name) as "count" FROM crm_customer WHERE var_name = CuName;
			ELSE
				SELECT COUNT(var_name) AS "count" FROM ame_mt_cus WHERE var_name = CuName;		
			END IF;	
	ELSE
		SELECT COUNT(var_name) INTO countCustApp FROM crm_customer WHERE var_name = CuName AND var_id != ID;
			IF countCustApp <> 0 THEN
				SELECT COUNT(var_name) as "count" FROM crm_customer WHERE var_name = CuName AND var_id != ID;
			ELSE
				SELECT COUNT(var_name) AS "count" FROM ame_mt_cus WHERE var_name = CuName AND var_id != ID;		
			END IF;	
 	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_check_master_data`;
DELIMITER |
CREATE PROCEDURE `crm_check_master_data`()
    DETERMINISTIC
BEGIN
	SELECT 'crm_account_type' AS 'TBL', COUNT(*) 'COUNT' FROM crm_account_type
	UNION
	SELECT 'crm_call_status' AS 'TBL', COUNT(*) 'COUNT' FROM crm_call_status;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_clear_data_table`;
DELIMITER |
CREATE PROCEDURE `crm_clear_data_table`()
    DETERMINISTIC
BEGIN

	DELETE FROM crm_activity ;

	DELETE FROM crm_collaboration_details;
	DELETE FROM crm_colllaboration_tags;
	DELETE FROM crm_user_like_collaboration;
	DELETE FROM crm_collaboration;

	DELETE FROM crm_location;
	DELETE FROM crm_event ;
	DELETE FROM crm_note ;
	DELETE FROM crm_meeting ;
	DELETE FROM crm_task ;

	DELETE FROM crm_call ;
	DELETE FROM crm_document ;
	DELETE FROM crm_opportunity_contact ;
	DELETE FROM crm_opportunity_detail ;
	DELETE FROM crm_opportunity_quote ;
	DELETE FROM crm_opportunity_saleorder ;
	DELETE FROM crm_opportunity ;

	DELETE FROM crm_case_article ;
	DELETE FROM crm_case_detail ;
	DELETE FROM crm_case ;


	DELETE FROM crm_contact ;
	DELETE FROM crm_lead ;
	DELETE FROM crm_camp ;

	DELETE FROM crm_config_dashboard ;

	DELETE FROM hbu_competitor_item;
	DELETE FROM hbu_item_customer;
	DELETE FROM hbu_market_survey_details;
	DELETE FROM hbu_market_survey;
  DELETE FROM hbu_competitor;

	DELETE FROM crm_role_detail WHERE RM_RoleID not in('R0001','R0002','R0003');
	DELETE FROM crm_role WHERE RM_ID not in('R0001','R0002','R0003');

	UPDATE crm_numberprefix SET LastID =1;
	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_control_list`;
DELIMITER |
CREATE PROCEDURE `crm_customer_control_list`(var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	SELECT c.var_id 'custID', COALESCE(c.var_name,'') 'custName', c.var_tel1 'tel1', c.var_tel2 'tel2',COALESCE(pc.var_id,'') 'priceCode', COALESCE(pc.var_name,'') 'des' 
	FROM ame_mt_cus c 
	LEFT JOIN ame_mt_pri_cod pc ON pc.var_id = c.var_pricecode
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_creditLimit_1`;
DELIMITER |
CREATE PROCEDURE `crm_customer_creditLimit_1`(CID Varchar(100),InvNo varchar(100))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(IsOverCreditLimit,0) AS C1 , COALESCE(IsOverDueDate,0) AS C2, CAST(COALESCE(TermCreditLimit,0) AS DECIMAL(16,2)) AS 'CreditLimit', COALESCE(CustID,'') AS 'Id', COALESCE(CustName,'') AS 'Name', COALESCE(TermNetDueIn,0) AS 'Term' FROM tblcustomer WHERE CustID = CID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_creditLimit_2`;
DELIMITER |
CREATE PROCEDURE `crm_customer_creditLimit_2`(CID Varchar(100),InvNo varchar(100))
    DETERMINISTIC
BEGIN
	SELECT CAST(COALESCE(SUM(COALESCE(NetTotalAmt,0) - COALESCE(PmtToDate,0)),0) AS DECIMAL(16,2)) AS 'Outstanding' FROM tblsales WHERE CustID = CID AND SalID <> InvNo AND PostStatus IN('Open','Posted');
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_creditLimit_3`;
DELIMITER |
CREATE PROCEDURE `crm_customer_creditLimit_3`(CID Varchar(100),InvNo varchar(100))
    DETERMINISTIC
BEGIN
	SELECT CAST(COALESCE(SUM(COALESCE(IssueAmt,0)),0) AS DECIMAL(16,2)) AS 'TemporaryCredit' FROM tblcustomerissue WHERE CustID = CID AND EndDate >= now();
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_creditLimit_4`;
DELIMITER |
CREATE PROCEDURE `crm_customer_creditLimit_4`(CID Varchar(100),InvNo varchar(100))
    DETERMINISTIC
BEGIN
	SELECT s.SalID AS 'InvoiceNo', s.SalReference AS 'Reference', DATE(s.SalDate) AS 'InvoiceDate', COALESCE(s.NetTotalAmt,0) AS 'TotalAmount',
		COALESCE(s.PmtToDate,0) AS 'PaymenttoDate', COALESCE(s.NetTotalAmt,0) - COALESCE(s.PmtToDate,0) AS 'Outstanding', DATE(s.DueDate) AS 'DueDate',
		IF(DATEDIFF(DATE(DueDate),DATE(NOW())) < 0,"-",DATEDIFF(DATE(DueDate),DATE(NOW()))) AS 'DaysLeft',
		IF(DATEDIFF(DATE(NOW()),DATE(s.DueDate)) < 0,"-",DATEDIFF(DATE(NOW()),DATE(s.DueDate))) AS 'OverDue'
		FROM tblsales s WHERE PostStatus IN('Open','Posted') AND s.CustID = CID ORDER BY s.SalID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_load_address`;
DELIMITER |
CREATE PROCEDURE `crm_customer_load_address`(var_cust varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
		COALESCE(custid,"") 'custID',
		IF(
			COALESCE(longitude,"") <> '' && COALESCE(latitude,"") <> '',
			IF(COALESCE(CustAddress,"") = '', "Bill To Address", CustAddress),
			COALESCE(CustAddress,"")
		) 'custAddress', 
		COALESCE(longitude,"") 'longitude', 
		COALESCE(latitude,"") 'latitude' 
	FROM tblcustomer WHERE custid = var_cust AND (COALESCE(CustAddress,"") <> '' OR (COALESCE(latitude,"") <> '' AND COALESCE(latitude,"") <> ''));
	
	SELECT 
		COALESCE(docid,"") 'custID',
		COALESCE(shipid,"") 'shipId', 
		IF(
			COALESCE(longitude,"") <> '' && COALESCE(latitude,"") <> '', 
			IF(COALESCE(shipname,"") = "", "Ship To Address", shipname), 
			COALESCE(shipname,"")
		) 'custAddress', 
		COALESCE(longitude,"") 'longitude', 
		COALESCE(latitude,"") 'latitude' 
	FROM tblshipaddress WHERE docid = var_cust AND (COALESCE(shipname,"") <> '' OR (COALESCE(latitude,"") <> '' AND COALESCE(latitude,"") <> ''));
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_pending_startup_edit`;
DELIMITER |
CREATE PROCEDURE `crm_customer_pending_startup_edit`(userId varchar(255), custId varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	DECLARE empId varchar(255);
	SELECT COALESCE(var_id,'') 'custGroupId' , COALESCE(var_name,'') 'custGroupName' FROM ame_mt_cus_gro;
	SELECT COALESCE(var_id,'') 'priceCode', COALESCE(var_name,'') 'des' FROM ame_mt_pri_cod;
	SELECT COALESCE(i_id,'') 'industID' , COALESCE(i_name,'') 'industName' FROM crm_industry;	
	SELECT COALESCE(at_id,'') 'accountID',COALESCE(at_name,'') 'accountName'  FROM crm_account_type;
	CALL CRM_PRO_CURRENCY_LOAD();
	SET empId = COALESCE((SELECT var_empid FROM ame_user WHERE var_id = userId),'');
	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 COALESCE(var_id,'') 'empId', COALESCE(var_name,'') 'empName' FROM ame_mt_emp WHERE tin_inactive=0 ORDER BY EmpID;
	ELSE
		SELECT COALESCE(var_id,'') 'empId', COALESCE(var_name,'') 'empName' FROM ame_mt_emp WHERE tin_inactive=0 AND var_id = empId;
	END IF;
	SELECT GROUP_CONCAT(var_empid) 'cur_emps' FROM ame_mt_cus_emp WHERE var_cusid = custId;
	CALL CRM_PRO_CUST_PENDING_GET_BY_ID(custId);
	SELECT CRM_FUN_CONFIG_IMG_PATH() as 'ImagePath';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_relate_order`;
DELIMITER |
CREATE PROCEDURE `crm_customer_relate_order`(var_type varchar(255),var_cid varchar(255))
    DETERMINISTIC
BEGIN
	IF var_type = 'Quotation' THEN
		SELECT var_id 'saleId', dou_net 'amount'  FROM ame_ar_quo WHERE var_cusid = var_cid AND var_status = 'Open';
	ELSE
		SELECT var_id 'saleId', dou_net 'amount'  FROM ame_ar_so WHERE var_cusid = var_cid AND var_status = 'Open';
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_relationship_add`;
DELIMITER |
CREATE PROCEDURE `crm_customer_relationship_add`(var_custid varchar(255), var_rcustid varchar(255), var_rel int)
    DETERMINISTIC
BEGIN
	#Routine body goes here...

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_relationship_delete`;
DELIMITER |
CREATE PROCEDURE `crm_customer_relationship_delete`(var_custid varchar(255),var_rcustid varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_customer_relationship WHERE CustID= var_custid AND RCustID=var_rcustid;
	DELETE FROM crm_customer_relationship WHERE CustID= var_rcustid AND RCustID=var_custid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_relationship_insert`;
DELIMITER |
CREATE PROCEDURE `crm_customer_relationship_insert`(var_custid varchar(255),var_rcustid varchar(255),var_relate varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE relDes VARCHAR(255) DEFAULT "";
	DECLARE var_m VARCHAR(255) DEFAULT "";
	DECLARE var_f VARCHAR(255) DEFAULT "";
	DECLARE var_sex VARCHAR(255) DEFAULT "";
	DELETE FROM crm_customer_relationship WHERE CustID= var_custid AND RCustID=var_rcustid;
	DELETE FROM crm_customer_relationship WHERE CustID= var_rcustid AND RCustID=var_custid;
	SELECT RelDescription,M,F INTO relDes,var_m,var_f FROM crm_relationship_type WHERE RelID = var_relate;
	SET var_sex = COALESCE((SELECT IF(CustSex = NULL,'Male',CustSex)  FROM tblcustomer WHERE CustID = var_rcustid),'Male');
	INSERT INTO crm_customer_relationship(`CustID`, `Relate`, `RCustID`) VALUES (var_custid, relDes, var_rcustid);
	IF var_sex = 'Male' THEN
		INSERT INTO crm_customer_relationship(`CustID`, `Relate`, `RCustID`) VALUES (var_rcustid, var_m, var_custid);
	ELSE
		INSERT INTO crm_customer_relationship(`CustID`, `Relate`, `RCustID`) VALUES (var_rcustid, var_f, var_custid);
	END IF;
	SELECT 'TRUE' AS 'Status';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_relationship_list`;
DELIMITER |
CREATE PROCEDURE `crm_customer_relationship_list`(var_custid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT c.CustID 'custId', COALESCE(c.CustName,'') 'custName', Relate 'relate' 
	FROM crm_customer_relationship cr
	LEFT JOIN tblcustomer c ON c.custid = cr.CustID
	WHERE cr.RCustID = var_custid
	ORDER BY cr.RCustID
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_relationship_startup`;
DELIMITER |
CREATE PROCEDURE `crm_customer_relationship_startup`(var_cust_id varchar(255),var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RelID 'rId', COALESCE(RelDescription,'') 'rName'  FROM crm_relationship_type ORDER BY RelDescription;
	SELECT c.CustID 'custId', COALESCE(c.CustName,'') 'custName', Relate 'relate' 
	FROM crm_customer_relationship cr
	LEFT JOIN tblcustomer c ON c.custid = cr.CustID
	WHERE cr.RCustID = var_cust_id
	ORDER BY cr.RCustID
	;
	SELECT CustID 'custId', COALESCE(CustName, '') 'custName' , COALESCE(CustTel1,'') 'tel1', COALESCE(CustTel2,'') 'tel2'  FROM tblcustomer WHERE CustID <> var_cust_id AND Inactive=0 ORDER BY CustID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_startup_add`;
DELIMITER |
CREATE PROCEDURE `crm_customer_startup_add`(userId varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	DECLARE empId varchar(255);
	SELECT COALESCE(var_id,'') 'custGroupId' , COALESCE(var_name,'') 'custGroupName' FROM ame_mt_cus_gro;
	SELECT COALESCE(var_id,'') 'priceCode', COALESCE(var_name,'') 'des' FROM ame_mt_pri_cod;
	SELECT COALESCE(i_id,'') 'industID' , COALESCE(i_name,'') 'industName' FROM crm_industry;	
	SELECT COALESCE(at_id,'') 'accountID',COALESCE(at_name,'') 'accountName'  FROM crm_account_type;
	CALL CRM_PRO_CURRENCY_LOAD();
	SET empId = COALESCE((SELECT var_empid FROM ame_user WHERE var_id = userId),'');
	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 COALESCE(var_id,'') 'empId', COALESCE(var_name,'') 'empName' FROM ame_mt_emp WHERE tin_inactive=0 ORDER BY EmpID;
	ELSE
		SELECT COALESCE(var_id,'') 'empId', COALESCE(var_name,'') 'empName' FROM ame_mt_emp WHERE tin_inactive=0 AND var_id = empId;
	END IF;
	SELECT empId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_customer_startup_edit`;
DELIMITER |
CREATE PROCEDURE `crm_customer_startup_edit`(userId varchar(255), custId varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE roleType INT DEFAULT 0;
	DECLARE empId varchar(255);
	SELECT COALESCE(var_id,'') 'custGroupId' , COALESCE(var_name,'') 'custGroupName' FROM ame_mt_cus_gro;
	SELECT COALESCE(var_id,'') 'priceCode', COALESCE(var_name,'') 'des' FROM ame_mt_pri_cod;
	SELECT COALESCE(i_id,'') 'industID' , COALESCE(i_name,'') 'industName' FROM crm_industry;	
	SELECT COALESCE(at_id,'') 'accountID',COALESCE(at_name,'') 'accountName'  FROM crm_account_type;
	CALL CRM_PRO_CURRENCY_LOAD();
	SET empId = COALESCE((SELECT var_empid FROM ame_user WHERE var_id = userId),'');
	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 COALESCE(var_id,'') 'empId', COALESCE(var_name,'') 'empName' FROM ame_mt_emp WHERE tin_inactive=0 ORDER BY EmpID;
	ELSE
		SELECT COALESCE(var_id,'') 'empId', COALESCE(var_name,'') 'empName' FROM ame_mt_emp WHERE tin_inactive=0 AND var_id = empId;
	END IF;
	SELECT GROUP_CONCAT(var_empid) 'cur_emps' FROM ame_mt_cus_emp WHERE var_cusid = custId;
	CALL CRM_PRO_CUST_GET_BY_ID(custId);
	SELECT CRM_FUN_CONFIG_IMG_PATH() as 'ImagePath';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_dashboard_list`;
DELIMITER |
CREATE PROCEDURE `crm_dashboard_list`(IN `username` varchar(255))
    DETERMINISTIC
BEGIN
SELECT * FROM crm_meeting;
SELECT * FROM crm_call;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteCallCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteCallCategory`(IN `id` varchar(255),IN `name` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE countSatus INT;
	SELECT COUNT(CL_StatusID) INTO countSatus FROM crm_call WHERE CL_StatusID = id;
	IF countSatus <> 0 THEN
			CALL crm_message("1030",`name`);
	ELSE 
			DELETE FROM crm_call_status WHERE CLS_ID = id;
			CALL crm_message("1029",`name`);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteCampaignCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteCampaignCategory`(IN `status` varchar(255),IN `id` varchar(255),IN `name`varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE countSatus INT;
  DECLARE countType INT;

	IF `status` = 'status' THEN
			SELECT COUNT(CA_StatusID) INTO countSatus FROM crm_camp WHERE CA_StatusID = id;
			IF countSatus <> 0 THEN
					CALL crm_message("1018",`name`);
			ELSE 
					DELETE FROM crm_camp_status WHERE CAS_ID = id;
					CALL crm_message("1017",`name`);
			END IF;
	ELSE 
			SELECT COUNT(CA_TypeID) INTO countType FROM crm_camp WHERE CA_TypeID = id;
			IF countType <> 0 THEN
					CALL crm_message("1020",`name`);
			ELSE 
					DELETE FROM crm_camp_type WHERE CAT_ID  = id;
					CALL crm_message("1019",`name`);
			END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteCaseCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteCaseCategory`(IN `status` varchar(255),IN `id` varchar(255),IN `name`varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE countSatus INT;
  DECLARE countType INT;
	DECLARE countPr INT;

	IF `status` = 'status' THEN
			SELECT COUNT(CS_StatusID) INTO countSatus FROM crm_case WHERE CS_StatusID = id;
			IF countSatus <> 0 THEN
					CALL crm_message("1036",`name`);
			ELSE 
					DELETE FROM crm_case_status WHERE CSS_ID = id;
					CALL crm_message("1035",`name`);
			END IF;
	ELSEIF `status` = 'priority' THEN
			SELECT COUNT(CS_Priority) INTO countPr FROM crm_case WHERE CS_Priority = id;
			IF countPr <> 0 THEN
					CALL crm_message("1040",`name`);
			ELSE 
					DELETE FROM crm_case_priority WHERE CSP_ID = id;
					CALL crm_message("1039",`name`);
			END IF;
	ELSE 
			SELECT COUNT(CS_TypeID) INTO countType FROM crm_case WHERE CS_TypeID = id;
			IF countType <> 0 THEN
					CALL crm_message("1038",`name`);
			ELSE 
					DELETE FROM crm_case_type WHERE CST_ID  = id;
					CALL crm_message("1037",`name`);
			END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteCustomerCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteCustomerCategory`(IN `id` varchar(255),IN `name` varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE countCustApp  INT;
	DECLARE countCust  INT;

		SELECT COUNT(CrmAccountTypeID) INTO countCustApp FROM crm_customer WHERE CrmAccountTypeID = id;
		IF countCustApp = 0 THEN
			SELECT COUNT(CrmAccountTypeID) INTO countCust FROM tblcustomer WHERE CrmAccountTypeID = id;
			IF countCust  = 0 THEN
				DELETE FROM crm_account_type WHERE AT_ID = id;
				CALL crm_message("1023",`name`);
			ELSE
				CALL crm_message("1024",`name`);
			END IF;	
		ELSE
			CALL crm_message("1024",`name`);
		END IF;	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteCustRelateCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteCustRelateCategory`(var_id varchar(255),var_name varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE countSatus INT;
	SELECT COUNT(*) INTO countSatus FROM crm_customer_relationship WHERE Relate = var_name;
	IF countSatus <> 0 THEN
			SELECT  'Used' as 'Action',CONCAT('The customer relationship : ',var_name, ' was used!') AS 'alert';
	ELSE
			DELETE FROM crm_relationship_type WHERE RelID = var_id;
			SELECT  'Deleted' as 'Action',CONCAT('The customer relationship : ',var_name, ' was successfully deleted!') AS 'alert';					
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteLeadCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteLeadCategory`(IN `id` varchar(255),IN `name` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE countSatus INT;
	SELECT COUNT(LA_StatusID) INTO countSatus FROM crm_lead WHERE LA_StatusID = id;
	IF countSatus <> 0 THEN
			CALL crm_message("1022",`name`);
	ELSE 
			DELETE FROM crm_lead_status WHERE LST_ID  = id;
			CALL crm_message("1021",`name`);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteMeetingCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteMeetingCategory`(IN `id` varchar(255),IN `name` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE countSatus INT;
	SELECT COUNT(M_StatusID) INTO countSatus FROM crm_meeting WHERE M_StatusID = id;
	IF countSatus <> 0 THEN
			CALL crm_message("1032",`name`);
	ELSE 
			DELETE FROM crm_meeting_status WHERE MS_ID  = id;
			CALL crm_message("1031",`name`);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteOpportunityCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteOpportunityCategory`(IN `status` varchar(255),IN `id` varchar(255),IN `name`varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE countSatus INT;
  DECLARE countType INT;

	IF `status` = 'type' THEN
			SELECT COUNT(OP_TypeID) INTO countType FROM crm_opportunity WHERE OP_TypeID = id;
			IF countType <> 0 THEN
					CALL crm_message("1026",`name`);
			ELSE 
					DELETE FROM crm_opportunity_type WHERE OT_ID = id;
					CALL crm_message("1025",`name`);
			END IF;
	ELSE 
			SELECT COUNT(OP_StageID) INTO countSatus FROM crm_opportunity WHERE OP_StageID = id;
			IF countSatus <> 0 THEN
					CALL crm_message("1028",`name`);
			ELSE 
					DELETE FROM crm_opportunity_stage WHERE OS_ID  = id;
					CALL crm_message("1027",`name`);
			END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteOtherIndustryCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteOtherIndustryCategory`(IN `id` varchar(255),IN `name` varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE countCustApp  INT;
	DECLARE countCust  INT;
	DECLARE countCustlea  INT;

		SELECT COUNT(CrmIndustID) INTO countCustApp FROM crm_customer WHERE CrmIndustID = id;
		IF countCustApp = 0 THEN
			SELECT COUNT(CrmIndustID) INTO countCust FROM tblcustomer WHERE CrmIndustID = id;
			IF countCust  = 0 THEN
				SELECT COUNT(LA_IndustID) INTO countCustlea FROM crm_lead WHERE LA_IndustID = id;
				IF countCustlea  = 0 THEN
					DELETE FROM crm_industry WHERE I_ID = id;
					CALL crm_message("1041",`name`);
				ELSE
					CALL crm_message("1042",`name`);
				END IF;
			ELSE
				CALL crm_message("1042",`name`);
			END IF;	
		ELSE
			CALL crm_message("1042",`name`);
		END IF;	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteOtherLeadSourceCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteOtherLeadSourceCategory`(IN `id` varchar(255),IN `name` varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE countCustApp  INT;
	DECLARE countCust  INT;
	DECLARE countCustlea  INT;

		SELECT COUNT(CO_LeadSource) INTO countCustApp FROM crm_contact WHERE CO_LeadSource = id;
		IF countCustApp = 0 THEN
			SELECT COUNT(LA_SourceID) INTO countCust FROM crm_lead WHERE LA_SourceID = id;
			IF countCust  = 0 THEN
				SELECT COUNT(OP_LeadSourceID) INTO countCustlea FROM crm_opportunity WHERE OP_LeadSourceID = id;
				IF countCustlea  = 0 THEN
					DELETE FROM crm_lead_source WHERE LS_ID = id;
					CALL crm_message("1043",`name`);
				ELSE
					CALL crm_message("1044",`name`);
				END IF;
			ELSE
				CALL crm_message("1044",`name`);
			END IF;	
		ELSE
			CALL crm_message("1044",`name`);
		END IF;	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteProjectCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteProjectCategory`(IN `status` varchar(255),IN `id` varchar(255),IN `name`varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE countSatus INT;
  DECLARE countType INT;
	IF `status` = 'status' THEN
			SELECT COUNT(pl_status) INTO countSatus FROM crm_projectlist WHERE pl_status = id;
			IF countSatus <> 0 THEN
					CALL crm_message("1018",`name`);
			ELSE 
					DELETE FROM crm_projectlist_status WHERE pls_id = id;
					CALL crm_message("1017",`name`);
			END IF;
	ELSEIF `status` = 'product_status' THEN
			SELECT COUNT(plp_status) INTO countType FROM crm_projectlist_product WHERE plp_status = id;
			IF countType <> 0 THEN
					CALL crm_message("1018",`name`);
			ELSE 
					DELETE FROM crm_projectlist_product_status WHERE plps_id  = id;
					CALL crm_message("1017",`name`);
			END IF;
	ELSE 
			SELECT COUNT(pl_type) INTO countType FROM crm_projectlist WHERE pl_type = id;
			IF countType <> 0 THEN
					CALL crm_message("1020",`name`);
			ELSE 
					DELETE FROM crm_projectlist_type WHERE plt_id  = id;
					CALL crm_message("1019",`name`);
			END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_deleteTaskCategory`;
DELIMITER |
CREATE PROCEDURE `crm_deleteTaskCategory`(IN `id` varchar(255),IN `name` varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE countSatus INT;
	SELECT COUNT(TA_StatusID) INTO countSatus FROM crm_task WHERE TA_StatusID = id;
	IF countSatus <> 0 THEN
			CALL crm_message("1034",`name`);
	ELSE 
			DELETE FROM crm_task_status WHERE TS_ID  = id;
			CALL crm_message("1033",`name`);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_delete_config_dashboard`;
DELIMITER |
CREATE PROCEDURE `crm_delete_config_dashboard`(IN `userId` varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_config_dashboard WHERE UID = userId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_delete_role_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_delete_role_by_id`(IN `roleId` varchar(255))
    DETERMINISTIC
BEGIN
	DELETE  FROM crm_role_detail WHERE RM_RoleID = roleId;
	DELETE  FROM crm_role WHERE RM_ID = roleId;
	UPDATE tbluser SET URoleID = null WHERE URoleID = roleId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_delete_role_detail_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_delete_role_detail_by_id`()
    DETERMINISTIC
BEGIN
	DELETE  FROM crm_role_detail WHERE RM_RoleID is null;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_employee_list`;
DELIMITER |
CREATE PROCEDURE `crm_employee_list`(var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	SELECT var_id 'empId', var_name 'empName' FROM ame_mt_emp WHERE ame_mt_emp.var_id not in(SELECT ame_user.var_empid FROM ame_user WHERE ame_user.var_empid <> null OR ame_user.var_empid <> '');
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_frm_requisition_check_status`;
DELIMITER |
CREATE PROCEDURE `crm_frm_requisition_check_status`(IN var_obj_id varchar(255), var_pro varchar(255))
    DETERMINISTIC
BEGIN
	IF var_pro = 'Budget Requisition' THEN
		SELECT * FROM crm_frm_budget WHERE FrmID = var_obj_id AND ApprovalStatus = 'Requested' AND EditTable = 1;
	ELSEIF var_pro = 'General Requisition' THEN
		SELECT * FROM crm_frm_general WHERE FrmID = var_obj_id AND ApprovalStatus = 'Requested' AND EditTable = 1;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_frm_requisition_list_template`;
DELIMITER |
CREATE PROCEDURE `crm_frm_requisition_list_template`()
    DETERMINISTIC
BEGIN
	SELECT TmpID 'tmpId', TmpName 'tmpName', TmpDescription 'tmpDescription' FROM crm_template_authorization;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `CRM_FUN_MODULE_BY_RELATED`;
DELIMITER |
CREATE PROCEDURE `CRM_FUN_MODULE_BY_RELATED`(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 `crm_get_email_auth`;
DELIMITER |
CREATE PROCEDURE `crm_get_email_auth`(var_pid varchar(255), var_ptype varchar(255),var_status varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_emp VARCHAR(255) DEFAULT "";
	DECLARE var_auth VARCHAR(255) DEFAULT "";
	DECLARE var_userid VARCHAR(255) DEFAULT "";
	DECLARE var_group VARCHAR(255) DEFAULT "";
	IF var_status = 'all' THEN
		IF var_ptype = 'Customer' THEN
			SELECT CBy,CAuthID INTO var_userid,var_auth FROM crm_customer WHERE CustID = var_pid;
			SET var_emp = COALESCE((SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID = (SELECT EmpID FROM tbluseremployee WHERE UID=var_userid LIMIT 1)),'');
			IF var_emp <> '' THEN
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				END IF;
			ELSE
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				END IF;
			END IF;
		ELSEIF var_ptype = 'Over Due Date' THEN
			SELECT CreateBy,ODAuthID INTO var_userid,var_auth FROM tblcustomeroverdue WHERE IssueID = var_pid;
			SET var_emp = COALESCE((SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID = (SELECT EmpID FROM tbluseremployee WHERE UID=var_userid LIMIT 1)),'');
			IF var_emp <> '' THEN
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				END IF;
			ELSE
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				END IF;
			END IF;
		ELSEIF var_ptype = 'Temporary Credit' THEN
			SELECT CreateBy,TCAuthID INTO var_userid,var_auth FROM tblcustomerissue WHERE IssueID = var_pid;
			SET var_emp = COALESCE((SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID = (SELECT EmpID FROM tbluseremployee WHERE UID=var_userid LIMIT 1)),'');
			IF var_emp <> '' THEN
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				END IF;
			ELSE
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				END IF;
			END IF;
		ELSEIF var_ptype = 'Budget Requisition' THEN
			SELECT EmpID,BRAuthID INTO var_emp,var_auth FROM crm_frm_budget WHERE FrmID = var_pid;
			SET var_emp = COALESCE((SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID = var_emp),'');
			IF var_emp <> '' THEN
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				END IF;
			ELSE
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				END IF;
			END IF;
		ELSEIF var_ptype = 'General Requisition' THEN
			SELECT EmpID,GRAuthID INTO var_emp,var_auth FROM crm_frm_general WHERE FrmID = var_pid;
			SET var_emp = COALESCE((SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID = var_emp),'');
			IF var_emp <> '' THEN
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				END IF;
			ELSE
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				END IF;
			END IF;
		ELSEIF var_ptype = 'Material Request' THEN
			SELECT RequestedBy, MRAuthID INTO var_emp,var_auth FROM tblmaterialrequest WHERE EntryNo = var_pid;
			SET var_emp = COALESCE((SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID = var_emp),'');
			IF var_emp <> '' THEN
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				END IF;
			ELSE
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				END IF;
			END IF;
		ELSEIF var_ptype = 'Sale Order' THEN
			SELECT EmpID,SAuthID INTO var_emp,var_auth FROM tblsaleorder WHERE SalID = var_pid;
			SET var_emp = COALESCE((SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID = var_emp),'');
			IF var_emp <> '' THEN
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				END IF;
			ELSE
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				END IF;
			END IF;
		ELSEIF var_ptype = 'Quote' THEN
			SELECT EmpID,QAuthID INTO var_emp,var_auth FROM tblsbquote WHERE SalID = var_pid;
			SET var_emp = COALESCE((SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID = var_emp),'');
			IF var_emp <> '' THEN
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> ''
					UNION 
					SELECT var_emp;
				END IF;
			ELSE
				SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
				IF var_group = 'Group' THEN 
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				ELSE
					SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
					(
						SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
						UNION
						SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
					)
					AND tblemployee.EmpEmail <> '';
				END IF;
			END IF;
		END IF;

	ELSE
-- no requested by

		IF var_ptype = 'Customer' THEN
			SELECT CBy,CAuthID INTO var_userid,var_auth FROM crm_customer WHERE CustID = var_pid;
			SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
			IF var_group = 'Group' THEN 
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			ELSE
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			END IF;
		ELSEIF var_ptype = 'Over Due Date' THEN
			SELECT CreateBy,ODAuthID INTO var_userid,var_auth FROM tblcustomeroverdue WHERE IssueID = var_pid;
			SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
			IF var_group = 'Group' THEN 
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			ELSE
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			END IF;
		ELSEIF var_ptype = 'Temporary Credit' THEN
			SELECT CreateBy,TCAuthID INTO var_userid,var_auth FROM tblcustomerissue WHERE IssueID = var_pid;
			SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
			IF var_group = 'Group' THEN 
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			ELSE
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			END IF;
		ELSEIF var_ptype = 'Budget Requisition' THEN
			SELECT EmpID,BRAuthID INTO var_emp,var_auth FROM crm_frm_budget WHERE FrmID = var_pid;
			SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
			IF var_group = 'Group' THEN 
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			ELSE
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			END IF;
		ELSEIF var_ptype = 'General Requisition' THEN
			SELECT EmpID,GRAuthID INTO var_emp,var_auth FROM crm_frm_general WHERE FrmID = var_pid;
			SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
			IF var_group = 'Group' THEN 
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			ELSE
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			END IF;
		ELSEIF var_ptype = 'Material Request' THEN
			SELECT RequestedBy, MRAuthID INTO var_emp,var_auth FROM tblmaterialrequest WHERE EntryNo = var_pid;
			SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
			IF var_group = 'Group' THEN 
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			ELSE
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			END IF;
		ELSEIF var_ptype = 'Sale Order' THEN
			SELECT EmpID,SAuthID INTO var_emp,var_auth FROM tblsaleorder WHERE SalID = var_pid;
			SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
			IF var_group = 'Group' THEN 
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			ELSE
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			END IF;
		ELSEIF var_ptype = 'Quote' THEN
			SELECT EmpID,QAuthID INTO var_emp,var_auth FROM tblsbquote WHERE SalID = var_pid;
			SET var_group = COALESCE((SELECT hrm_authorisation.Auth_Type FROM hrm_authorisation WHERE hrm_authorisation.Auth_ID=var_auth),'');
			IF var_group = 'Group' THEN 
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_group_detail.AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN (SELECT hrm_authorisation_detail.Auth_GroupID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth)
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			ELSE
				SELECT tblemployee.EmpEmail FROM tblemployee WHERE EmpID IN 
				(
					SELECT hrm_authorisation_detail.Auth_EmpID FROM hrm_authorisation_detail WHERE hrm_authorisation_detail.Auth_ID = var_auth
					UNION
					SELECT Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_ptype AND Auth_ID = var_auth
				)
				AND tblemployee.EmpEmail <> ''
				;
			END IF;
		END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_get_email_employee`;
DELIMITER |
CREATE PROCEDURE `crm_get_email_employee`(var_user VARCHAR(255), var_process VARCHAR(255))
    DETERMINISTIC
BEGIN
	DECLARE var_auth VARCHAR(255) DEFAULT (SELECT Auth_ID FROM	hrm_authorisation_employee WHERE Emp_ID = ( SELECT e.EmpID FROM tbluseremployee e	WHERE UID = var_user ) AND Auth_Process = var_process);
	DECLARE var_group VARCHAR(255) DEFAULT (SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = var_auth);
	-- IF(var_group = '',(SELECT Auth_EmpID FROM hrm_authorisation_detail WHERE Auth_ID = var_auth),(SELECT AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID = var_group));
IF var_group = '' THEN
	SELECT email.*, e.EmpEmail FROM 
	(
		SELECT Auth_ID,Emp_ID FROM hrm_authorisation_employee WHERE Auth_Process = var_process
		UNION
		SELECT Auth_ID,Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_process
		UNION
		SELECT Auth_ID,Auth_EmpID FROM hrm_authorisation_detail WHERE Auth_EmpID <> ''
	) email INNER JOIN tblemployee e ON email. Emp_ID = e.EmpID
	WHERE
		Auth_ID = var_auth
	AND
		EmpEmail <> '';
ELSE
	SELECT email.*, e.EmpEmail FROM 
	(
		SELECT Auth_ID,Emp_ID FROM hrm_authorisation_employee WHERE Auth_Process = var_process
		UNION
		SELECT Auth_ID,Emp_ID FROM hrm_authorisation_watcher WHERE Auth_Process = var_process
		UNION
		SELECT ad.Auth_ID,ag.AuthGroup_EmpID FROM hrm_authorisation_group_detail ag INNER JOIN hrm_authorisation_detail ad ON ad.Auth_GroupID = ag.AuthGroup_ID WHERE ad.Auth_GroupID = var_group
	) email INNER JOIN tblemployee e ON email. Emp_ID = e.EmpID
	WHERE
		Auth_ID = var_auth
	AND
		EmpEmail <> '';
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_hbu_market_share_frm`;
DELIMITER |
CREATE PROCEDURE `crm_hbu_market_share_frm`(IN `msId` varchar(255))
    DETERMINISTIC
BEGIN
	
	SELECT tbl.*, ROUND((tbl.total*100/tbl.totalAll),5) 'percent' FROM (select m.MS_ID 'msId', m.MS_ItemID 'itemId', DATE_FORMAT(m.MS_Date, '%d-%b-%Y') 'surveyDate',(SELECT I.ItemName FROM tblitem I WHERE I.ItemID=m.MS_ItemID) 'itemName', d.COM_ID 'comId', (SELECT c.COM_Name FROM hbu_competitor c WHERE c.COM_ID=d.COM_ID) 'comName', SUM(d.SurveyValue) 'total', (SELECT SUM(SurveyValue) FROM hbu_market_survey_details md  WHERE md.MarketSurveyID = msId) 'totalAll'  
	from hbu_market_survey m
	JOIN hbu_market_survey_details d on m.MS_ID=d.MarketSurveyID
	WHERE MS_ID = msId
	GROUP BY d.COM_ID) as tbl;


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_image_path_load`;
DELIMITER |
CREATE PROCEDURE `crm_image_path_load`()
    DETERMINISTIC
BEGIN
	SELECT ImagePathWeb 'ImagePath' FROM tblconfiguration LIMIT 1;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_item_control_list`;
DELIMITER |
CREATE PROCEDURE `crm_item_control_list`(var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(ItemID,'') 'itemId',COALESCE(ItemName,'') 'itemName', COALESCE(crm_fullname(itemcode,ItemName),'') 'itemName2', 
				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 ShowOnPos = 1
  ORDER BY ItemID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_item_list`;
DELIMITER |
CREATE PROCEDURE `crm_item_list`()
    DETERMINISTIC
BEGIN
	SELECT ItemID 'itemId',ItemName 'itemName' FROM tblitem;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_language_object_add`;
DELIMITER |
CREATE PROCEDURE `crm_language_object_add`(var_langCode varchar(11), var_en varchar(255), var_kh varchar(255),var_cn varchar(255), var_des varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_auto_id VARCHAR(255) DEFAULT generateAutoId("LANG");
	INSERT INTO `crm_language_object` (`LangCode`, `EN`, `KH`, `CN`, `Description`) 
	VALUES (var_auto_id, var_en, var_kh, var_cn, var_des);
	SELECT var_auto_id as 'LN_ID';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_language_object_list`;
DELIMITER |
CREATE PROCEDURE `crm_language_object_list`(var_userid varchar(50))
    DETERMINISTIC
BEGIN
	SELECT LangCode 'langCode', COALESCE(EN,"") 'enLang', COALESCE(KH,"") 'khLang', COALESCE(CN,"") 'cnLang', COALESCE(Description,"") 'description' 
	FROM crm_language_object;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_lead_by_campaign`;
DELIMITER |
CREATE PROCEDURE `crm_lead_by_campaign`(in `campId` varchar(11))
    DETERMINISTIC
BEGIN
	SELECT LA_ID 'leadId', CONCAT(LA_Salutation,' ',LA_FirstName,LA_LastName) 'fullName', LA_StatusID 'statusId', (SELECT LST_Name FROM crm_lead_status WHERE LST_ID=LA_StatusID) 'statusName'     
			, IF(LA_StatusID = 4,(SELECT CONCAT('[',CustID,'] ',CustName) FROM tblcustomer WHERE CustID=LA_CustID),LA_AccountName) 'company', LA_Email 'email', LA_CDate 'createDate', LA_CBy 'createBy'
	FROM crm_lead
	WHERE LA_CA_ID=campId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_listSystemModuleByUser`;
DELIMITER |
CREATE PROCEDURE `crm_listSystemModuleByUser`(IN `userId` varchar(255) ,  IN `module` varchar(255))
    DETERMINISTIC
BEGIN
	
	SELECT m.ModuleID 'moduleId' , m.Remarks 'moduleName', m.`Group` 'groupModule', COALESCE(tbl.RM_Delete, 'NO') 'delete', COALESCE(tbl.RM_Edit, 'NO') 'edit', COALESCE(tbl.RM_Export, 'NO') 'export', COALESCE(tbl.RM_Import, 'NO') 'import', COALESCE(tbl.RM_List, 'NO') 'list',COALESCE(tbl.RM_View, 'NO') 'view',COALESCE(tbl.RM_Access, 'NO') 'access' 
	FROM crm_numberprefix m
	LEFT JOIN (SELECT * from crm_role_detail WHERE RM_RoleID=(select u.var_crm_role from ame_user u WHERE u.var_id = userId) AND RM_ModuleID=module) as tbl on tbl.RM_ModuleID = m.ModuleID
	WHERE m.`Status`=1 AND m.ModuleID=module
	ORDER BY m.`Group`;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_listSystemModulesByRoleId`;
DELIMITER |
CREATE PROCEDURE `crm_listSystemModulesByRoleId`(IN `roleId` varchar(11))
    DETERMINISTIC
BEGIN
DECLARE roleName VARCHAR(255);
DECLARE roleTypeId INTEGER;
DECLARE roleDescription VARCHAR(255);
SELECT rm_name , rm_typeid,rm_des INTO roleName,roleTypeId,roleDescription FROM crm_role WHERE rm_id = roleId;
SELECT roleTypeId 'roleTypeId', roleName 'roleName', roleDescription 'roleDescription', m.ModuleID 'moduleId', m.Remarks 'moduleName', `Group` 'groupModule', COALESCE(tbl.RM_Delete, 'NO') 'delete', COALESCE(tbl.RM_Edit, 'NO') 'edit', COALESCE(tbl.RM_Export, 'NO') 'export', COALESCE(tbl.RM_Import, 'NO') 'import', COALESCE(tbl.RM_List, 'NO') 'list',COALESCE(tbl.RM_View, 'NO') 'view',COALESCE(tbl.RM_Access, 'NO') 'access'
,SUBSTRING(`Group`,1,6) 'groupType'
FROM crm_numberprefix m
LEFT JOIN (SELECT * from crm_role_detail join crm_role on crm_role.RM_ID = crm_role_detail.RM_RoleID WHERE RM_RoleID=roleId) as tbl on tbl.RM_ModuleID = m.ModuleID
WHERE m.`Status`=1
ORDER BY m.`Group`, m.ModuleID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_list_article`;
DELIMITER |
CREATE PROCEDURE `crm_list_article`(var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	SELECT a_id 'articleId', a_title 'articleTitle',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
	ORDER BY a_id DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_list_collaboration_by_module`;
DELIMITER |
CREATE PROCEDURE `crm_list_collaboration_by_module`(IN `moduleId` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
		c.CB_ID colId,
		c.CB_Des colDes,
		DATE_FORMAT(c.CB_CreateDate,'%d/%m/%Y %h:%i %p') colCreateDate,
		c.CB_Own isOwner,
		(SELECT COUNT(LK_ID) FROM crm_user_like_collaboration WHERE LK_CBID = c.CB_ID) 'userLiked',
		c.CB_UID userId,
		(SELECT UName FROM tbluser WHERE UID = c.CB_UID) 'userName'
	FROM crm_collaboration c WHERE c.CB_RToID = moduleId ORDER BY c.CB_CreateDate DESC;

	SELECT 
		cd.CommentID 'commentId',
		cd.`Comment` 'comment',
		DATE_FORMAT(cd.CreateDate,'%d/%m/%Y %h:%i %p') 'createdDate',
		cd.PostID 'postId',
		cd.UID 'userId',
		(SELECT UName FROM tbluser WHERE UID = cd.UID) 'userName'
	FROM crm_collaboration_details cd WHERE cd.PostID IN (SELECT co.CB_ID FROM crm_collaboration co WHERE co.CB_RToID = moduleId);

	SELECT
		lc.LK_ID 'likeId',
		lc.LK_CBID 'postId',
		(SELECT UName FROM tbluser WHERE UID = lc.LK_UID) 'username',
		lc.LK_UID 'userId'
	FROM crm_user_like_collaboration lc WHERE lc.LK_CBID IN (SELECT co.CB_ID FROM crm_collaboration co WHERE co.CB_RToID = moduleId);

	SELECT ct.collapId 'postId', ct.tagId 'tagId', ct.userId 'userId', (SELECT UName FROM tbluser WHERE UID = ct.userId) 'userName' FROM crm_colllaboration_tags ct WHERE ct.collapId IN (SELECT co.CB_ID FROM crm_collaboration co WHERE co.CB_RToID = moduleId);

	CALL crm_list_crm_users();
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_list_crm_users`;
DELIMITER |
CREATE PROCEDURE `crm_list_crm_users`()
    DETERMINISTIC
BEGIN
	# list all user crm
	SELECT u.var_id 'userID', u.var_name 'username', u.tin_inactive 'status', u.var_crm_role 'roleId', r.RM_Name 'roleName' , COALESCE(e.var_id,'') 'empId', COALESCE(e.var_name,'') 'empName'
	FROM ame_user u
	LEFT JOIN ame_user_app ua on ua.var_id=u.var_id
	LEFT JOIN crm_role r on r.RM_ID=u.var_crm_role
	LEFT JOIN ame_mt_emp e ON e.var_id = u.var_empid
	WHERE ua.var_appid = 'CRM' AND u.var_id NOT IN('ADMIN','balancika') 
	ORDER BY u.var_id;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_list_items_by_competitor`;
DELIMITER |
CREATE PROCEDURE `crm_list_items_by_competitor`(var_comid varchar(255),var_status varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COM_ID 'comId', ItemID 'itemId', ItemName 'itemName', ItemCode 'itemCode', Price 'price', getUomByItemID(ItemID, var_status) 'uoms', Description 'description'
	FROM crm_market_survey_competitor_item WHERE COM_ID = var_comid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_list_role_master`;
DELIMITER |
CREATE PROCEDURE `crm_list_role_master`()
    DETERMINISTIC
BEGIN
	SELECT RM_ID 'roleId', RM_Name 'roleName' FROM crm_role WHERE RM_Status=1 ORDER BY RM_Name;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_load_language`;
DELIMITER |
CREATE PROCEDURE `crm_load_language`()
    DETERMINISTIC
BEGIN
	SET SESSION group_concat_max_len = 10000000;
	SELECT CONCAT("{",GROUP_CONCAT(CONCAT("\"",TRIM(COALESCE(LangCode,"")),"\":","[\"",TRIM(COALESCE(EN,"")),"\",\"",TRIM(COALESCE(KH,"")),"\",\"",COALESCE(CN,""),"\"]")),"}") as 'JSON'
	FROM crm_language_object;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_add`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_add`(var_subject varchar(255), var_fd varchar(255), var_td varchar(255), var_des varchar(255), var_status varchar(255), var_puid varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_auto_id VARCHAR(255) DEFAULT generateAutoId("MS");
	INSERT INTO crm_market_survey (`MS_ID`, `MS_Subject`, `MS_StartDate`, `MS_EndDate`, `MS_Description`, `MS_CreateBy`, `MS_CreateDate`,`MS_Status`) 
	VALUES (var_auto_id, var_subject, var_fd, var_td, var_des, var_puid, now(), var_status);
	SELECT var_auto_id as 'MS_ID';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_comment_add`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_comment_add`(var_vid varchar(255), var_mid varchar(255),var_cid varchar(255), var_comment varchar(1000))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_market_survey_comment WHERE (`VI_ID`=var_vid) AND (`MS_ID`=var_mid) AND (`CustID`=var_cid);
	INSERT INTO `crm_market_survey_comment` (`VI_ID`, `MS_ID`, `CustID`, `Description`) VALUES (var_vid, var_mid, var_cid, var_comment);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_competitor_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_competitor_by_id`(var_com varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COM_ID 'comId', COALESCE(COM_Name,'') 'comName', COALESCE(COM_Address,'') 'address', COALESCE(COM_Tel,'') 'phone', COALESCE(COM_Email, '') 'email', COALESCE(COM_Owner,'') 'owner', COALESCE(COM_Status,'') 'status', COALESCE(COM_Des,'') 'description', COM_CreateBy 'cBy', COM_CreateDate 'cDate', COM_ModifiedBy 'mBy', COM_ModifiedDate 'mDate' 
	FROM crm_market_survey_competitor WHERE COM_ID = var_com;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_competitor_item_add`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_competitor_item_add`(var_comid varchar(255), var_item  varchar(255), var_item_code varchar(255), var_des varchar(255), var_price double, var_puid varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_auto_id VARCHAR(255) DEFAULT generateAutoId("COM_ITEM");
	INSERT INTO crm_market_survey_competitor_item (`COM_ID`, `ItemID`, `ItemName`, `ItemCode`, `Description`, `Price`) 
	VALUES (var_comid, var_auto_id, var_item, var_item_code, var_des,var_price);
	SELECT var_auto_id as 'MS_ID';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_competitor_item_delete`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_competitor_item_delete`(var_itemid varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_market_survey_competitor_item_uom WHERE ItemID = var_itemid;
	DELETE FROM crm_market_survey_competitor_item WHERE ItemID = var_itemid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_competitor_item_update`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_competitor_item_update`(var_comid varchar(255),var_itemid varchar(255), var_item  varchar(255), var_item_code varchar(255), var_des varchar(255), var_price double, var_puid varchar(255))
    DETERMINISTIC
BEGIN
	UPDATE crm_market_survey_competitor_item 
	SET `COM_ID` = var_comid, `ItemName` = var_item, `ItemCode` = var_item_code, `Description` = var_des, `Price` = var_price
	WHERE `ItemID` = var_itemid;
	DELETE FROM crm_market_survey_competitor_item_uom WHERE ItemID = var_itemid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_competitor_list_customer`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_competitor_list_customer`(var_comid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT CustID 'custId', CustName 'custName', CustGroupID 'custGroupId', 
		CONCAT(COALESCE(CustTel1,''), ' / ',COALESCE(CustTel2,'')) 'phone', COALESCE(CustContactName, '') 'contact'
	FROM tblcustomer 
	WHERE CustID IN (SELECT sc.CustID 'custId' FROM crm_market_survey_customer sc  WHERE sc.COM_ID = var_comid GROUP BY sc.CustID);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_customer_delete`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_customer_delete`(var_vid varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_market_survey_customer WHERE VI_ID = var_vid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_customer_items`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_customer_items`(var_custid varchar(255), var_fd varchar(255), var_td varchar(255))
    DETERMINISTIC
BEGIN
	SELECT c.ItemID 'itemId', (SELECT ItemName FROM crm_market_survey_competitor_item i WHERE i.ItemID = c.ItemID) 'itemName', c.UomID 'uomId',
			SUM(c.SalQty) 'saleQty', SUM(c.BalanceQty) 'balanceQty', MAX(c.Price) 'maxPrice', MIN(c.Price) 'minPrice'
	FROM crm_market_survey_customer c	
	WHERE c.CustID = var_custid
	GROUP BY c.ItemID
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_delete`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_delete`(var_msid varchar(255))
    DETERMINISTIC
BEGIN
	DELETE FROM crm_market_survey_detail WHERE MS_ID = var_msid ;
	DELETE FROM crm_market_survey WHERE MS_ID = var_msid ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_detail_list`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_detail_list`(var_msid varchar(255), var_vid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT d.MSD_ID as 'msdId', d.COM_ID as 'comId', COALESCE((SELECT c.COM_Name FROM crm_market_survey_competitor c WHERE c.COM_ID = d.COM_ID),'') 'comName' , d.COM_Status 'comStatus', ItemID 'itemId', UomID 'uomId',
			IF (d.COM_Status = 'Owner',(SELECT i.ItemName FROM tblitem i WHERE i.ItemID = d.ItemID),(SELECT i.ItemName FROM crm_market_survey_competitor_item i WHERE i.ItemID = d.ItemID)) 'itemName',
			COALESCE(tbl.CustID, ''), COALESCE(tbl.Price,0) 'price', COALESCE(tbl.SalQty,0) as 'salQty', COALESCE(tbl.BalanceQty,0) 'balaceQty', COALESCE(tbl.Remark,'') 'remark'
	FROM crm_market_survey_detail d
	LEFT JOIN (SELECT * FROM crm_market_survey_customer WHERE VI_ID = var_vid) as tbl on tbl.MSD_ID = d.MSD_ID
	WHERE MS_ID = var_msid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_list`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_list`()
    DETERMINISTIC
BEGIN
	SELECT MS_ID 'msId', MS_Subject 'subject', DATE_FORMAT(MS_StartDate, '%d-%b-%Y') 'startDate', DATE_FORMAT(MS_EndDate, '%d-%b-%Y') 'endDate', MS_Status 'status', MS_CreateBy 'cby', MS_Description 'description' 
	FROM crm_market_survey ORDER BY MS_ID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_list_item_by_competitor`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_list_item_by_competitor`(var_cid varchar(255), var_cs varchar(255))
    DETERMINISTIC
BEGIN
	IF var_cs = "Owner" THEN
		SELECT COALESCE(ItemID,'') 'itemId', COALESCE(ItemName,'') 'itemName', crm_fullname(ItemID,ItemName) 'fullname' , COALESCE(itemcode,'') 'itemCode', COALESCE(itembarcode, '') 'itemBarcode' FROM tblitem WHERE Inactive = 0 and ItemID <> '' AND ItemID is not NULL AND tblitem.`status` = 'Inventory Part'  ORDER BY ItemID;
	ELSE
		SELECT ItemID 'itemId', ItemName 'itemName',crm_fullname(ItemID,ItemName) 'fullname' , '' as 'itemCode', '' as 'itemBarcode' FROM crm_market_survey_competitor_item WHERE COM_ID = var_cid;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_list_uom_by_item`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_list_uom_by_item`(var_cid varchar(255), var_cs varchar(255))
    DETERMINISTIC
BEGIN
	IF var_cs = "Owner" THEN
		SELECT iu.UomID 'uomId' FROM tblitemuom iu WHERE iu.ItemID = var_cid;
	ELSE
		SELECT UomID 'uomId' FROM crm_market_survey_competitor_item_uom WHERE ItemID = var_cid;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_report_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_report_by_id`(var_msid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(COM_ID, 'Grand Total') 'comId', 
				 COALESCE((SELECT COM_Name FROM crm_market_survey_competitor c WHERE c.COM_ID = mc.COM_ID),'') 'comName',
				 SUM(SalQty) 'saleQty',
         SUM(BalanceQty) 'balanceQty',
         MAX(Price) 'maxPrice',
         MIN(Price) 'minPrice'
	FROM crm_market_survey_customer mc
	WHERE mc.MSD_ID IN (SELECT md.MSD_ID FROM crm_market_survey_detail md WHERE md.MS_ID = var_msid)
	GROUP BY COM_ID WITH ROLLUP;
	SELECT var_name1 'comEN', var_name2 'comKH' FROM ame_mt_com;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_report_by_id_export`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_report_by_id_export`(var_msid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(COM_ID, 'Grand Total') 'comId', 
				 COALESCE((SELECT COM_Name FROM crm_market_survey_competitor c WHERE c.COM_ID = mc.COM_ID),'') 'comName',
				 SUM(SalQty) 'saleQty',
         SUM(BalanceQty) 'balanceQty',
         MAX(Price) 'maxPrice',
         MIN(Price) 'minPrice'
	FROM crm_market_survey_customer mc
	WHERE mc.MSD_ID IN (SELECT md.MSD_ID FROM crm_market_survey_detail md WHERE md.MS_ID = var_msid)
	GROUP BY COM_ID WITH ROLLUP;
	SELECT MS_ID 'msId',MS_Subject 'subject', COALESCE(DATE_FORMAT(MS_StartDate, '%d-%b-%Y'), '') 'startDate', COALESCE(DATE_FORMAT(MS_EndDate, '%d-%b-%Y'), '') 'endDate', MS_Status 'status' FROM crm_market_survey WHERE MS_ID = var_msid;	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_startup`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_startup`()
    DETERMINISTIC
BEGIN
	SELECT COM_ID 'comId', COM_Name 'comName', COM_Status 'comStatus' FROM crm_market_survey_competitor;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_startup_with_id`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_startup_with_id`(var_msid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COM_ID 'comId', COM_Name 'comName', COM_Status 'comStatus' FROM crm_market_survey_competitor;
	SELECT MS_ID 'msId', MS_Subject 'subject', DATE_FORMAT(MS_StartDate, '%d-%c-%Y') 'startDate', DATE_FORMAT(MS_EndDate, '%d-%c-%Y') 'endDate', MS_Status 'status', MS_CreateBy 'cby' , MS_Description 'description'
	FROM crm_market_survey WHERE MS_ID = var_msid;
	SELECT MSD_ID,MS_ID, COM_ID as 'comId' , COALESCE((SELECT c.COM_Name FROM crm_market_survey_competitor c WHERE c.COM_ID = msd.COM_ID),'') 'comName' , COM_Status 'comStatus', ItemID 'itemId', UomID 'uomId',
			IF (msd.COM_Status = 'Owner',(SELECT i.ItemName FROM tblitem i WHERE i.ItemID = msd.ItemID),(SELECT i.ItemName FROM crm_market_survey_competitor_item i WHERE i.ItemID = msd.ItemID)) 'itemName'
	FROM crm_market_survey_detail msd
	WHERE MS_ID = var_msid ORDER BY MSD_ID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_market_survey_update`;
DELIMITER |
CREATE PROCEDURE `crm_market_survey_update`(var_msid varchar(255),var_subject varchar(255), var_fd varchar(255), var_td varchar(255), var_des varchar(255), var_status varchar(255), var_puid varchar(255))
    DETERMINISTIC
BEGIN
DELETE FROM crm_market_survey_detail WHERE MS_ID = var_msid ;
UPDATE crm_market_survey 
SET 
    `MS_Subject`=var_subject, 
		`MS_StartDate`=var_fd, 
		`MS_EndDate`=var_td, 
		`MS_Description`=var_des, 
		`MS_ModifiedBy`=var_puid,
		`MS_Status`=var_status
WHERE (`MS_ID`=var_msid);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_material_request_start_up`;
DELIMITER |
CREATE PROCEDURE `crm_material_request_start_up`(var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_empId varchar(255);
	DECLARE var_img_url varchar(255);
	DECLARE var_rt varchar(255);
	DECLARE role_id 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
		select EntryNo 'entryId', Reference 'reference', COALESCE(DATE_FORMAT(EntryDate, '%d-%b-%Y'), '') 'entryDate',COALESCE(DATE_FORMAT(RequiredDate, '%d-%b-%Y'), '') 'requiredDate', `Status` 'status' ,
		RequestedBy 'empId', COALESCE((SELECT EmpName FROM tblemployee WHERE tblemployee.EmpID = RequestedBy),'') empName,
		CustID 'custId', COALESCE((SELECT CustName FROM tblcustomer WHERE tblcustomer.CustID = tblmaterialrequest.CustID), '') 'custName'
		from tblmaterialrequest
		ORDER BY EntryNo DESC
		;
	ELSE
		SET var_empId = COALESCE((SELECT EmpID FROM tbluseremployee WHERE UID = var_user_id),'');
			SELECT IsOnlyRole ,uroleid INTO var_rt,role_id FROM tbluser WHERE UID = var_userId;
			IF var_rt = '1' THEN
				select EntryNo 'entryId', Reference 'reference', COALESCE(DATE_FORMAT(EntryDate, '%d-%b-%Y'), '') 'entryDate',COALESCE(DATE_FORMAT(RequiredDate, '%d-%b-%Y'), '') 'requiredDate', `Status` 'status' ,
							 RequestedBy 'empId', COALESCE((SELECT EmpName FROM tblemployee WHERE tblemployee.EmpID = RequestedBy),'') empName,
							 CustID 'custId', COALESCE((SELECT CustName FROM tblcustomer WHERE tblcustomer.CustID = tblmaterialrequest.CustID), '') 'custName'
				from tblmaterialrequest 
				WHERE RequestedBy IN(SELECT EmpID FROM tbluseremployee ue INNER JOIN (SELECT UID FROM tbluser WHERE uroleid = uroleid) as users ON users.UID=ue.uid)
				ORDER BY EntryNo DESC;
			ELSE
				select EntryNo 'entryId', Reference 'reference', COALESCE(DATE_FORMAT(EntryDate, '%d-%b-%Y'), '') 'entryDate',COALESCE(DATE_FORMAT(RequiredDate, '%d-%b-%Y'), '') 'requiredDate', `Status` 'status' ,
							 RequestedBy 'empId', COALESCE((SELECT EmpName FROM tblemployee WHERE tblemployee.EmpID = RequestedBy),'') empName,
							 CustID 'custId', COALESCE((SELECT CustName FROM tblcustomer WHERE tblcustomer.CustID = tblmaterialrequest.CustID), '') 'custName'
				from tblmaterialrequest 
				WHERE RequestedBy = var_empId 
				ORDER BY EntryNo DESC;	
			END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_material_request_start_up_add`;
DELIMITER |
CREATE PROCEDURE `crm_material_request_start_up_add`(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);
	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;
	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;
	END IF;
	SELECT LocationID 'locationId', Des 'locationName' FROM tbllocation;
	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 ShowOnPos = 1  ORDER BY ItemID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_material_request_start_up_add_item`;
DELIMITER |
CREATE PROCEDURE `crm_material_request_start_up_add_item`(var_itemid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT UomID 'uomId' FROM tblitemuom WHERE ItemID = var_itemid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_dashboard`;
DELIMITER |
CREATE PROCEDURE `crm_mb_dashboard`(var_fd varchar(255), var_td varchar(255), var_puid varchar(255), var_ps varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE typeId varchar(255) DEFAULT (Select RM_TypeID from crm_role where RM_ID = (SELECT URoleID FROM tbluser where UID = var_puid) LIMIT 1);
	DECLARE var_empId VARCHAR(255) DEFAULT (SELECT tbluseremployee.EmpID from tbluseremployee where tbluseremployee.UID = var_puid LIMIT 1);
	DECLARE var_st1 DOUBLE DEFAULT 0;
	DECLARE var_st2 DOUBLE DEFAULT 0;
	DECLARE var_vt1 DOUBLE DEFAULT 0;
	DECLARE var_vt2 DOUBLE DEFAULT 0;
	DECLARE var_sr1 DOUBLE DEFAULT 0;
	DECLARE var_cn1 DOUBLE DEFAULT 0;
	IF typeId = '1' THEN
		SET var_st1 = COALESCE((SELECT SUM(NetTotalAmt) FROM tblsaleorder WHERE DATE(SalDate) BETWEEN var_fd AND var_td AND IF(LOWER(var_ps) = 'all', PostStatus IN('Open','Closed'), PostStatus = var_ps)),0);		
		SET var_cn1 = COALESCE((SELECT SUM(NetTotalAmt) FROM tblcrnote WHERE DATE(CrDate) BETWEEN var_fd AND var_td AND PostStatus = 'Posted'),0);
		SET var_sr1 = COALESCE((SELECT SUM(NetTotalAmt) FROM tblsales_return WHERE DATE(SalDate) BETWEEN var_fd AND var_td AND PostStatus = 'Posted'),0);
	ELSE
		SET var_st1 = COALESCE((SELECT SUM(NetTotalAmt) FROM tblsaleorder WHERE DATE(SalDate) BETWEEN var_fd AND var_td AND IF(LOWER(var_ps) = 'all', PostStatus IN('Open','Closed'), PostStatus = var_ps) AND EmpID = var_empId),0);
		SET var_cn1 = COALESCE((SELECT SUM(NetTotalAmt) FROM tblcrnote WHERE DATE(CrDate) BETWEEN var_fd AND var_td AND PostStatus = 'Posted' AND EmpID = var_empId),0);
		SET var_sr1 = COALESCE((SELECT SUM(NetTotalAmt) FROM tblsales_return WHERE DATE(SalDate) BETWEEN var_fd AND var_td AND PostStatus = 'Posted' AND EmpID = var_empId),0);
	END IF;
	SET var_st2 = crm_get_sales_target(var_empId);
	SET var_vt1 = (SELECT COUNT(*) 'visitTarget'  FROM crm_schedule_detail WHERE SC_Employee = var_empId AND VI_Status IN('Visited with order', 'Visited without order') AND DATE(SC_startDate) BETWEEN var_fd AND var_td);
	SET var_vt2 = (SELECT COUNT(*) 'visitTotal' FROM crm_schedule_detail WHERE SC_Employee = var_empId AND DATE(SC_startDate) BETWEEN var_fd AND var_td);
	
	SELECT CAST(var_vt1 AS DECIMAL(16,2)) 'val1', CAST(var_vt2 AS DECIMAL(16,2)) 'val2';
	SELECT CAST((var_st1-var_cn1-var_sr1) AS DECIMAL(16,2)) 'val1', CAST(var_st2 AS DECIMAL(16,2)) 'val2';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_invoice_prefix`;
DELIMITER |
CREATE PROCEDURE `crm_mb_invoice_prefix`(var_user_id varchar(255), var_key varchar(255))
    DETERMINISTIC
BEGIN
	IF var_key = 'all' THEN
		SELECT CONCAT(var_id,crm_generate_zero(int_length,int_lastid)) 'prefix_val', var_id 'prefix_key' FROM tblnumberprefix_custom WHERE var_type = 'AR-IN' ORDER BY var_id;
	ELSE
		SELECT CONCAT(var_id,crm_generate_zero(int_length,int_lastid)) 'prefix_val', var_id 'prefix_key' FROM tblnumberprefix_custom WHERE var_type = 'AR-IN' AND var_id LIKE CONCAT('%',var_key,'%') ORDER BY var_id;
	END IF;
	SELECT COALESCE((SELECT appid FROM tbluserprofile WHERE uid = var_user_id AND apptype = 'AR-IN'),'') as 'user_prefix';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_list_class`;
DELIMITER |
CREATE PROCEDURE `crm_mb_list_class`(in var_user_id varchar(255), in var_num int, in var_page int,var_search varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SELECT COUNT(ClassID) INTO var_rows 
	FROM tblclass 
	WHERE IF(var_search = 'all',TRUE ,
		(
			ClassID LIKE CONCAT('%',var_search,'%') OR
			Des LIKE CONCAT('%',var_search,'%')
		)
	);
	SELECT COALESCE(ClassID,'') 'classId', COALESCE(Des,'') 'className' 
	FROM tblclass 
	WHERE IF(var_search = 'all',TRUE ,
		(
			ClassID LIKE CONCAT('%',var_search,'%') OR
			Des LIKE CONCAT('%',var_search,'%')
		)
	)
	ORDER BY ClassID
	LIMIT var_num  OFFSET var_off;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_list_customer`;
DELIMITER |
CREATE PROCEDURE `crm_mb_list_customer`(in var_user_id varchar(255), in var_num int, in var_page int)
    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 ;
			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 
			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) ;
			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)
			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_list_location`;
DELIMITER |
CREATE PROCEDURE `crm_mb_list_location`(in var_user_id varchar(255), in var_num int, in var_page int,var_search varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SELECT COUNT(LocationID) INTO var_rows 
	FROM tbllocation 
	WHERE IF(var_search = 'all',TRUE ,
		(
			LocationID LIKE CONCAT('%',var_search,'%') OR
			Des LIKE CONCAT('%',var_search,'%')
		)
	);
	SELECT COALESCE(LocationID,'') 'locationId', COALESCE(Des,'') 'locationName' 
	FROM tbllocation
	WHERE IF(var_search = 'all',TRUE ,
		(
			LocationID LIKE CONCAT('%',var_search,'%') OR
			Des LIKE CONCAT('%',var_search,'%')
		)
	)
	ORDER BY LocationID
	LIMIT var_num  OFFSET var_off;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_list_location_pos`;
DELIMITER |
CREATE PROCEDURE `crm_mb_list_location_pos`(in var_user_id varchar(255), in var_num int, in var_page int,var_search varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SELECT COUNT(LocationID) INTO var_rows 
	FROM tbllocation 
	WHERE IsPOSLoc = 1 AND IF(var_search = 'all',TRUE ,
		(
			LocationID LIKE CONCAT('%',var_search,'%') OR
			Des LIKE CONCAT('%',var_search,'%')
		)
	);
	SELECT DISTINCT COALESCE(l.LocationID,'') 'locationId', COALESCE(l.Des,'') 'locationName' , COALESCE(l.ClassID,'') 'classId', COALESCE(a.AccID,'') 'account'
	FROM tbllocation l
	LEFT JOIN (SELECT * FROM tblaccountset WHERE AccType = 'Location' AND SubGroupID = 'Cash') a ON l.LocationID = a.GroupID
	WHERE IsPOSLoc = 1 AND IF(var_search = 'all',TRUE ,
		(
			LocationID LIKE CONCAT('%',var_search,'%') OR
			Des LIKE CONCAT('%',var_search,'%')
		)
	)
	ORDER BY l.LocationID
	LIMIT var_num  OFFSET var_off;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_list_product_item`;
DELIMITER |
CREATE PROCEDURE `crm_mb_list_product_item`(in var_user_id varchar(255), in var_num int, in var_page int)
    DETERMINISTIC
BEGIN
	DECLARE var_empId varchar(255);
	DECLARE var_rt varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SET var_off = ((var_page-1)*var_num);
	SELECT COUNT(var_id) INTO var_rows FROM ame_mt_ite WHERE tin_inactive = 0 AND tin_no_sal = 0 and var_id <> '' AND var_id is not NULL;
	SELECT COALESCE(var_id,'') 'id', COALESCE(var_name,'') 'name', COALESCE(var_itemcode,'') 'code', COALESCE(var_barcode, '') 'barcode' , COALESCE(var_img , '') 'image' 
	FROM ame_mt_ite 
	WHERE tin_inactive = 0 and var_id <> '' AND var_id is not NULL AND tin_no_sal = 0
	ORDER BY var_id
	LIMIT var_num  OFFSET var_off;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_list_sale_invoice_by_id`;
DELIMITER |
CREATE PROCEDURE `crm_mb_list_sale_invoice_by_id`(var_saleid varchar(255))
    DETERMINISTIC
BEGIN
	SELECT
		s.ItemID 'itemId', COALESCE((SELECT ItemName FROM tblitem i WHERE i.ItemID = s.ItemID LIMIT 1), '') 'itemName', '' as 'itemImage',
		s.LocationID 'locationId', COALESCE((SELECT Des FROM tbllocation l WHERE l.LocationID = s.LocationID LIMIT 1), '') 'locationName',
		s.ClassID 'classId', COALESCE((SELECT Des FROM tblclass c WHERE c.ClassID = s.ClassID LIMIT 1), '') 'className',
		s.UomID 'uomId', s.SalQty 'salQty', 
		COALESCE((SELECT SUM(sd.RetQty) FROM tblsalereturndetails sd WHERE sd.RetID IN (SELECT sr.RetID FROM tblsales_return sr WHERE sr.SalID = var_saleid AND sr.PostStatus IN ('Open', 'Posted')) AND sd.ItemID = s.ItemID), 0) 'retToDate',
		s.UnitPrice 'unitPrice', 0 'retQty', s.Factor 'factor', s.ReportPrice 'reportPrice',
		s.TotalAmt 'totalAmt', s.DisPer 'disPer', s.DisDol 'disDol', s.STaxPer 'sTaxPer', s.STaxDol 'sTaxDol', s.VTaxPer 'vTaxPer', s.VTaxDol 'vTaxDol',s.NetTotalAmt 'netTotalAmt'
	FROM tblsalesdetails s 
	WHERE SalID = var_saleid
	ORDER BY s.LineNo
	;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_list_sale_order`;
DELIMITER |
CREATE PROCEDURE `crm_mb_list_sale_order`(in var_row int , in var_page int, 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 = CRM_FUN_GET_ROLE_BY_UID(var_userId));
	IF typeId = '1' THEN

		SELECT COUNT(so.var_id) INTO var_rows FROM ame_ar_so so where so.var_status = 'Open';

		SELECT COALESCE(S.var_id,'') AS 'EntryNo',S.var_ref 'Reference', S.dat_date 'SalesOrderDate', S.var_empid 'empId', 
       COALESCE(e.var_name, '') AS 'empName', S.var_cusid 'CustomerID', c.var_name 'CustomerName',
			 CAST(COALESCE(S.dou_funnet, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.var_status 'Status', COALESCE(S.var_auth_status,'') 'approvedStatus'
		FROM ame_ar_so S 
		LEFT JOIN ame_mt_cus c ON c.var_id = S.var_cusid
		LEFT JOIN ame_mt_emp e ON e.var_id = S.var_empid
		where S.var_status = 'Open' 
		ORDER BY S.var_id DESC

		LIMIT var_row  OFFSET var_off;

	ELSE

			SELECT COUNT(so.var_id) INTO var_rows FROM ame_ar_so so where so.var_status = 'Open';

		SELECT COALESCE(S.var_id,'') AS 'EntryNo',S.var_ref 'Reference', S.dat_date 'SalesOrderDate', S.var_empid 'empId', 
       COALESCE(e.var_name, '') AS 'empName', S.var_cusid 'CustomerID', c.var_name 'CustomerName',
			 CAST(COALESCE(S.dou_funnet, 0) AS DECIMAL(16, 2)) AS 'TotalAmount', S.var_status 'Status', COALESCE(S.var_auth_status,'') 'approvedStatus'
		FROM ame_ar_so S 
		LEFT JOIN ame_mt_cus c ON c.var_id = S.var_cusid
		LEFT JOIN ame_mt_emp e ON e.var_id = S.var_empid
		where S.var_status = 'Open' AND S.var_empid = CRM_FUN_GET_EMP_ID(var_userId)
		ORDER BY S.var_id DESC

		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_list_visit_customer`;
DELIMITER |
CREATE PROCEDURE `crm_mb_list_visit_customer`(in var_row int, in var_page int, in var_userId varchar(255))
    DETERMINISTIC
BEGIN
	
	DECLARE var_empId varchar(255);
	DECLARE var_rows varchar(255);
	DECLARE var_type INT;
	DECLARE var_off INT;

	SET var_off = ((var_page - 1) * var_row);
	SET var_type = 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_type = 1 THEN

			SELECT count(VI_ID) INTO var_rows FROM crm_schedule_detail WHERE DATE(SC_startDate) BETWEEN '2017-11-24' AND '2017-11-24'; -- WHERE VI_Status = 'Pending'

			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(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 tblcustomer c ON sd.SC_Customer = c.CustID 
			WHERE c.Inactive = 0  AND DATE(SC_startDate) = DATE(now()) -- AND sd.VI_Status = 'Pending'
			ORDER BY SC_startDate ASC

			LIMIT var_row  OFFSET var_off;
	ELSE
			
			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 DATE(SC_startDate) BETWEEN '2017-11-24' AND '2017-11-24'; -- AND SD.VI_Status = 'Pending'

			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(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 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 DATE(SC_startDate) = DATE(now()) -- AND sd.VI_Status = 'Pending'
			ORDER BY SC_startDate ASC
			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_load_customer`;
DELIMITER |
CREATE PROCEDURE `crm_mb_load_customer`(var_userid varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rt varchar(255);
	DECLARE var_empId varchar(255);
	SET SESSION group_concat_max_len:=4294967295;
	SET var_rt = COALESCE((SELECT RM_TypeID FROM crm_role WHERE RM_ID = (select URoleID FROM tbluser WHERE UID = var_userid LIMIT 1)), 0);
	SET var_empId = COALESCE((SELECT EmpID FROM tbluseremployee WHERE UID = var_userid LIMIT 1),'');
	IF var_rt = '1' THEN
		SELECT c.CustID 'custId', COALESCE(c.CustName, '') 'custName' ,COALESCE(CustTel1,'') 'tel1', COALESCE(CustTel2,'') 'tel2', COALESCE(c.PriceCode,'') 'priceCode', COALESCE(c.TermNetDueIn,0) 'termNetDueIn', 
				 COALESCE(c.AID,'') shipId, COALESCE(c.TermCreditLimit,0) 'termCreditLimit', COALESCE(c.TermFormat, '') 'termFormat',
					CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"custId":"',c.CustID, '", "shipId":"', iu.shipid, '", "shipName":"',iu.shipname,'"}')) FROM tblshipaddress iu WHERE iu.docid = c.CustID),']') 'ships'
		FROM tblcustomer c
		WHERE Inactive=0 
		ORDER BY CustID
		;
	ELSE
		SELECT c.CustID 'custId', COALESCE(c.CustName, '') 'custName' ,COALESCE(CustTel1,'') 'tel1', COALESCE(CustTel2,'') 'tel2', COALESCE(c.PriceCode,'') 'priceCode', COALESCE(c.TermNetDueIn,0) 'termNetDueIn', 
				 COALESCE(c.AID,'') shipId, COALESCE(c.TermCreditLimit,0) 'termCreditLimit', COALESCE(c.TermFormat, '') 'termFormat',
					CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"custId":"',c.CustID, '", "shipId":"', iu.shipid, '", "shipName":"',iu.shipname,'"}')) FROM tblshipaddress iu WHERE iu.docid = c.CustID),']') 'ships'
		FROM tblcustomer c
		WHERE Inactive=0 
		AND CustID IN (SELECT CustID from tblemployeecustomer WHERE EmpID = var_empId)
		ORDER BY CustID
		;
	END IF;	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_load_employee`;
DELIMITER |
CREATE PROCEDURE `crm_mb_load_employee`(in var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	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;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_load_invoice_number_prefix`;
DELIMITER |
CREATE PROCEDURE `crm_mb_load_invoice_number_prefix`(var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	SELECT var_id 'prefixId',int_lastid 'lastId' FROM tblnumberprefix_custom WHERE var_type = 'AR-IN-POS' ; #AND var_modid = var_locId LIMIT 1
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_load_item_as_json`;
DELIMITER |
CREATE PROCEDURE `crm_mb_load_item_as_json`()
    DETERMINISTIC
BEGIN
	SET SESSION group_concat_max_len:=4294967295;
	SELECT 
		COALESCE(i.ItemID,'') 'id',
		COALESCE(i.ItemName,'') 'name',
		COALESCE(i.itemcode,'') 'code',
		COALESCE(i.itembarcode, '') 'barcode',
		COALESCE(i.ImagePath , '') 'image', 
		CONCAT(
			'[',
			(
				SELECT 
					GROUP_CONCAT(
						CONCAT(
							'{"itemId":"', tblitempricing.ItemID,
							'", "uomId":"',UomID,
							'","priceAmount":',PriceAmount,
							',"priceCode":"',PriceCode,'"}'
						)
					)
				FROM tblitempricing WHERE tblitempricing.ItemID = i.ItemID
			),
		']'
		) 'uoms'
	FROM tblitem i
	WHERE Inactive = 0 and ItemID <> '' AND ItemID is not NULL AND ShowOnPos = 1 AND ItemID IN (SELECT ItemID
		FROM tblbatchcost
		WHERE LocationID = 'LC2'
		GROUP BY ItemID)
	ORDER BY ItemID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_load_item_data`;
DELIMITER |
CREATE PROCEDURE `crm_mb_load_item_data`()
    DETERMINISTIC
BEGIN
	#Pricing
	SELECT ItemID,UomID,PriceAmount, PriceCode 
	FROM tblitempricing 
	WHERE ItemID IN (
		SELECT ItemID
		FROM tblbatchcost
		WHERE LocationID = 'LC2'
		GROUP BY ItemID
	)
	ORDER BY ItemID,PriceCode,UomID;
		
	#Item
	SELECT bc.ItemID 'itemId',i.ItemName 'itemName',i.itemcode 'code',itembarcode 'barcode',UomID 'uomId', SUM(QtyBalance) 'qtyBalance'
	FROM tblbatchcost bc
	INNER JOIN tblitem i on i.ItemID = bc.ItemID
	WHERE LocationID = 'LC2'
	GROUP BY ItemID
	ORDER BY ItemID;
	
	#Item UOM
	SELECT ItemID 'itemId', UomID uomId, DefSal 'defSal'
	FROM tblitemuom
	WHERE ItemID IN (
		SELECT ItemID
		FROM tblbatchcost
		WHERE LocationID = 'LC2'
		GROUP BY ItemID
	)
	ORDER BY ItemID,UomID;


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_load_item_stock_by_location`;
DELIMITER |
CREATE PROCEDURE `crm_mb_load_item_stock_by_location`(var_loc varchar(255))
    DETERMINISTIC
BEGIN
	SET SESSION group_concat_max_len:=4294967295;
	SELECT bc.ItemID 'itemId',i.ItemName 'itemName',i.itemcode 'code',itembarcode 'barcode',UomID 'uomId', SUM(QtyBalance) 'qtyBalance',COALESCE(i.ImagePath , '') 'image' , 
				 CONCAT('[',(SELECT GROUP_CONCAT(CONCAT('{"itemId":"',iu.ItemID, '", "uomId":"', iu.UomID, '", "defSal":',iu.DefSal, ', "conversion":',iu.Conversion,'}')) FROM tblitemuom iu WHERE iu.ItemID = bc.ItemID),']') 'uoms'
	FROM tblbatchcost bc
	INNER JOIN tblitem i on i.ItemID = bc.ItemID
	WHERE LocationID = var_loc
	GROUP BY ItemID
	ORDER BY ItemID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_load_pricecode`;
DELIMITER |
CREATE PROCEDURE `crm_mb_load_pricecode`()
    DETERMINISTIC
BEGIN
	SELECT COALESCE(PriceCode,'') 'priceCodeId', COALESCE(Description,'') 'priceCodeName'  FROM tblpricecode ORDER BY PriceCode;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_market_survey_detail_list`;
DELIMITER |
CREATE PROCEDURE `crm_mb_market_survey_detail_list`(in var_num int, in var_page int,in var_user_id varchar(255), var_msid varchar(255), var_vid varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SET var_off = ((var_page-1)*var_num);
	SELECT COUNT(*) INTO var_rows FROM crm_market_survey_detail WHERE MS_ID = var_msid;	
	SELECT d.MSD_ID as 'msdId', d.COM_ID as 'comId', COALESCE((SELECT c.COM_Name FROM crm_market_survey_competitor c WHERE c.COM_ID = d.COM_ID),'') 'comName' , d.COM_Status 'comStatus', d.ItemID 'itemId', d.UomID 'uomId',
			IF (d.COM_Status = 'Owner',(SELECT i.ItemName FROM tblitem i WHERE i.ItemID = d.ItemID),(SELECT i.ItemName FROM crm_market_survey_competitor_item i WHERE i.ItemID = d.ItemID)) 'itemName',
			COALESCE(tbl.CustID, '') custId, COALESCE(tbl.Price,null) 'price', COALESCE(tbl.SalQty,null) as 'salQty', COALESCE(tbl.BalanceQty,null) 'balanceQty', COALESCE(tbl.Remark,'') 'remark'
	FROM crm_market_survey_detail d
	LEFT JOIN (SELECT * FROM crm_market_survey_customer WHERE VI_ID = var_vid) as tbl on tbl.itemid = d.itemid
	WHERE d.MS_ID = var_msid
	ORDER BY d.MSD_ID ASC
	LIMIT var_num  OFFSET var_off
	;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_market_survey_detail_list_search_adv`;
DELIMITER |
CREATE PROCEDURE `crm_mb_market_survey_detail_list_search_adv`(var_num int, var_page int,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_rows varchar(255);
	DECLARE var_off INT;
	DECLARE typeId varchar(255) DEFAULT (Select RM_TypeID from crm_role where RM_ID = (SELECT URoleID FROM tbluser where UID = var_user_id) LIMIT 1);
	DECLARE var_empId VARCHAR(255);
	SET var_off = ((var_page-1)*var_num);
	IF typeId = '1' THEN		
		IF var_datefilter = 'all' THEN			
			SELECT COUNT(*) INTO var_rows FROM (
			SELECT DISTINCT s.VI_ID,s.MSD_ID,s.CustID
			FROM crm_market_survey_customer s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE MSD_Type = 0 
			AND IF(var_search = 'all',TRUE, (
			c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.CBy = var_search
			))
			GROUP BY VI_ID
			) as tblmaket
			;
			SELECT SUBSTRING_INDEX(s.MSD_ID, '_', 1) 'msId',s.VI_ID 'viId', s.CustID 'custId', COALESCE(c.CustName,'') 'custName', s.CBy 'cBy', DATE_FORMAT(s.CDate,'%d-%b-%Y %r') 'cDate'
			FROM crm_market_survey_customer s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE MSD_Type = 0 
			AND IF(var_search = 'all',TRUE, (
			c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.CBy = var_search
			))
			GROUP BY VI_ID
			ORDER BY s.CDate DESC
			LIMIT var_num  OFFSET var_off
			;
		ELSE
			SELECT COUNT(*) INTO var_rows FROM (
			SELECT DISTINCT s.VI_ID,s.MSD_ID,s.CustID
			FROM crm_market_survey_customer s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE DATE(s.CDate) BETWEEN var_fd AND var_td AND MSD_Type = 0 
			AND IF(var_search = 'all',TRUE, (
			c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.CBy = var_search
			))
			GROUP BY VI_ID
			) as tblmaket
			;
			SELECT SUBSTRING_INDEX(s.MSD_ID, '_', 1) 'msId',s.VI_ID 'viId', s.CustID 'custId', COALESCE(c.CustName,'') 'custName', s.CBy 'cBy', DATE_FORMAT(s.CDate,'%d-%b-%Y %r') 'cDate'
			FROM crm_market_survey_customer s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE DATE(s.CDate) BETWEEN var_fd AND var_td AND MSD_Type = 0 
			AND IF(var_search = 'all',TRUE, (
			c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.CBy = var_search
			))
			GROUP BY VI_ID
			ORDER BY s.CDate DESC
			LIMIT var_num  OFFSET var_off
			;
		END IF;
	ELSE
		IF var_datefilter = 'all' THEN
			SELECT COUNT(*) INTO var_rows FROM (
			SELECT DISTINCT s.VI_ID,s.MSD_ID,s.CustID
			FROM crm_market_survey_customer s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE s.CBy = var_user_id AND MSD_Type = 0 
			AND IF(var_search = 'all',TRUE, (
			c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.CBy = var_search
			))
			GROUP BY VI_ID
			) as tblmaket
			;
			SELECT SUBSTRING_INDEX(s.MSD_ID, '_', 1) 'msId',s.VI_ID 'viId', s.CustID 'custId', COALESCE(c.CustName,'') 'custName', s.CBy 'cBy', DATE_FORMAT(s.CDate,'%d-%b-%Y %r') 'cDate'
			FROM crm_market_survey_customer s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE s.CBy = var_user_id AND MSD_Type = 0 
			AND IF(var_search = 'all',TRUE, (
			c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.CBy = var_search
			))
			GROUP BY VI_ID
			ORDER BY s.CDate DESC
			LIMIT var_num  OFFSET var_off
			;
		ELSE
			SELECT COUNT(*) INTO var_rows FROM (
			SELECT DISTINCT s.VI_ID,s.MSD_ID,s.CustID
			FROM crm_market_survey_customer s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE s.CBy = var_user_id AND DATE(s.CDate) BETWEEN var_fd AND var_td AND MSD_Type = 0 
			AND IF(var_search = 'all',TRUE, (
			c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.CBy = var_search
			))
			GROUP BY VI_ID
			) as tblmaket
			;
			SELECT SUBSTRING_INDEX(s.MSD_ID, '_', 1) 'msId',s.VI_ID 'viId', s.CustID 'custId', COALESCE(c.CustName,'') 'custName', s.CBy 'cBy', DATE_FORMAT(s.CDate,'%d-%b-%Y %r') 'cDate'
			FROM crm_market_survey_customer s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE s.CBy = var_user_id AND DATE(s.CDate) BETWEEN var_fd AND var_td AND MSD_Type = 0 
			AND IF(var_search = 'all',TRUE, (
			c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.CBy = var_search
			))
			GROUP BY VI_ID
			ORDER BY s.CDate 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_market_survey_list`;
DELIMITER |
CREATE PROCEDURE `crm_mb_market_survey_list`(in var_num 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_num);
	SELECT COUNT(*) INTO var_rows FROM crm_market_survey WHERE MS_Status = 'In Progress';
	SELECT MS_ID 'msId', MS_Subject 'subject', DATE_FORMAT(MS_StartDate, '%d-%b-%Y') 'startDate', DATE_FORMAT(MS_EndDate, '%d-%b-%Y') 'endDate', MS_Status 'status', MS_CreateBy 'cby' 
	FROM crm_market_survey 
	WHERE MS_Status = 'In Progress'
	ORDER BY MS_ID ASC
	LIMIT var_num  OFFSET var_off;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_market_survey_search`;
DELIMITER |
CREATE PROCEDURE `crm_mb_market_survey_search`(in var_num int, in var_page int,in var_user_id varchar(255), var_search varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SET var_off = ((var_page-1)*var_num);
	SELECT COUNT(*) INTO var_rows FROM crm_market_survey WHERE MS_Status = 'In Progress' AND MS_Subject LIKE CONCAT('%', var_search, '%');
	SELECT MS_ID 'msId', MS_Subject 'subject', DATE_FORMAT(MS_StartDate, '%d-%b-%Y') 'startDate', DATE_FORMAT(MS_EndDate, '%d-%b-%Y') 'endDate', MS_Status 'status', MS_CreateBy 'cby' 
	FROM crm_market_survey 
	WHERE MS_Status = 'In Progress' AND MS_Subject LIKE CONCAT('%', var_search, '%')
	ORDER BY MS_ID ASC
	LIMIT var_num  OFFSET var_off;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_material_request_list_search_adv`;
DELIMITER |
CREATE PROCEDURE `crm_mb_material_request_list_search_adv`(var_num int, var_page int,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_rows varchar(255);
	DECLARE var_off INT;
	DECLARE typeId varchar(255) DEFAULT (Select RM_TypeID from crm_role where RM_ID = (SELECT URoleID FROM tbluser where UID = var_user_id) LIMIT 1);
	DECLARE var_empId VARCHAR(255);
	SET var_off = ((var_page-1)*var_num);
	IF typeId = '1' THEN		
		IF var_datefilter = 'all' THEN
			SELECT COUNT(*) INTO var_rows
			FROM tblmaterialrequest m
			LEFT JOIN tblcustomer c ON c.CustID = m.CustID
			WHERE IF(var_search = 'all',TRUE, (
			EntryNo LIKE CONCAT('%',var_search,'%')
			OR Reference LIKE CONCAT('%',var_search,'%')
			OR `Status` LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			))
			;
			SELECT 
				EntryNo 'entryNo', 
				DATE_FORMAT(EntryDate,'%d-%b-%Y') 'entryDate', 
				m.CustID 'custId', 
				COALESCE(c.CustName,'') 'custName',
				m.`Status` 'status', COALESCE(m.edittable,0) 'editable'
			FROM tblmaterialrequest m
			LEFT JOIN tblcustomer c ON c.CustID = m.CustID
			WHERE IF(var_search = 'all',TRUE, (
				m.EntryNo LIKE CONCAT('%',var_search,'%')
				OR m.Reference LIKE CONCAT('%',var_search,'%')
				OR m.`Status` LIKE CONCAT('%',var_search,'%')
				OR c.CustID = var_search
				OR c.CustName LIKE CONCAT('%',var_search,'%')
				))
			ORDER BY m.EntryNo DESC
			LIMIT var_num  OFFSET var_off
			;
		ELSE
			SELECT COUNT(*) INTO var_rows
			FROM tblmaterialrequest m
			LEFT JOIN tblcustomer c ON c.CustID = m.CustID
			WHERE DATE(m.EntryDate) BETWEEN var_fd AND var_td AND IF(var_search = 'all',TRUE, (
			m.EntryNo LIKE CONCAT('%',var_search,'%')
			OR m.Reference LIKE CONCAT('%',var_search,'%')
			OR m.`Status` LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			))
			;
			SELECT 
				EntryNo 'entryNo', 
				DATE_FORMAT(EntryDate,'%d-%b-%Y') 'entryDate', 
				m.CustID 'custId', 
				COALESCE(c.CustName,'') 'custName',
				m.`Status` 'status', COALESCE(m.edittable,0) 'editable'
			FROM tblmaterialrequest m
			LEFT JOIN tblcustomer c ON c.CustID = m.CustID
			WHERE DATE(m.EntryDate) BETWEEN var_fd AND var_td AND IF(var_search = 'all',TRUE, (
				m.EntryNo LIKE CONCAT('%',var_search,'%')
				OR m.Reference LIKE CONCAT('%',var_search,'%')
				OR m.`Status` LIKE CONCAT('%',var_search,'%')
				OR c.CustID = var_search
				OR c.CustName LIKE CONCAT('%',var_search,'%')
				))
			ORDER BY m.EntryNo DESC
			LIMIT var_num  OFFSET var_off
			;
		END IF;
	ELSE
		SET var_empId = (SELECT tbluseremployee.EmpID from tbluseremployee where tbluseremployee.UID = var_user_id LIMIT 1);
		IF var_datefilter = 'all' THEN
			SELECT COUNT(*) INTO var_rows
			FROM tblmaterialrequest m
			LEFT JOIN tblcustomer c ON c.CustID = m.CustID
			WHERE m.RequestedBy = var_empId  AND IF(var_search = 'all',TRUE, (
			EntryNo LIKE CONCAT('%',var_search,'%')
			OR Reference LIKE CONCAT('%',var_search,'%')
			OR `Status` LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			))
			;
			SELECT 
				EntryNo 'entryNo', 
				DATE_FORMAT(EntryDate,'%d-%b-%Y') 'entryDate', 
				m.CustID 'custId', 
				COALESCE(c.CustName,'') 'custName',
				m.`Status` 'status', COALESCE(m.edittable,0) 'editable'
			FROM tblmaterialrequest m
			LEFT JOIN tblcustomer c ON c.CustID = m.CustID
			WHERE m.RequestedBy = var_empId  AND IF(var_search = 'all',TRUE, (
				m.EntryNo LIKE CONCAT('%',var_search,'%')
				OR m.Reference LIKE CONCAT('%',var_search,'%')
				OR m.`Status` LIKE CONCAT('%',var_search,'%')
				OR c.CustID = var_search
				OR c.CustName LIKE CONCAT('%',var_search,'%')
				))
			ORDER BY m.EntryNo DESC
			LIMIT var_num  OFFSET var_off
			;
		ELSE
			SELECT COUNT(*) INTO var_rows
			FROM tblmaterialrequest m
			LEFT JOIN tblcustomer c ON c.CustID = m.CustID
			WHERE m.RequestedBy = var_empId  AND DATE(m.EntryDate) BETWEEN var_fd AND var_td AND IF(var_search = 'all',TRUE, (
			m.EntryNo LIKE CONCAT('%',var_search,'%')
			OR m.Reference LIKE CONCAT('%',var_search,'%')
			OR m.`Status` LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			))
			;
			SELECT 
				EntryNo 'entryNo', 
				DATE_FORMAT(EntryDate,'%d-%b-%Y') 'entryDate', 
				m.CustID 'custId', 
				COALESCE(c.CustName,'') 'custName',
				m.`Status` 'status', COALESCE(m.edittable,0) 'editable'
			FROM tblmaterialrequest m
			LEFT JOIN tblcustomer c ON c.CustID = m.CustID
			WHERE m.RequestedBy = var_empId  AND DATE(m.EntryDate) BETWEEN var_fd AND var_td AND IF(var_search = 'all',TRUE, (
				m.EntryNo LIKE CONCAT('%',var_search,'%')
				OR m.Reference LIKE CONCAT('%',var_search,'%')
				OR m.`Status` LIKE CONCAT('%',var_search,'%')
				OR c.CustID = var_search
				OR c.CustName LIKE CONCAT('%',var_search,'%')
				))
			ORDER BY m.EntryNo 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_receipt_list_search_adv`;
DELIMITER |
CREATE PROCEDURE `crm_mb_receipt_list_search_adv`(var_num int, var_page int,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_rows varchar(255);
	DECLARE var_off INT;
	DECLARE typeId varchar(255) DEFAULT (Select RM_TypeID from crm_role where RM_ID = (SELECT URoleID FROM tbluser where UID = var_user_id) LIMIT 1);
	DECLARE var_empId VARCHAR(255);
	SET var_off = ((var_page-1)*var_num);
	IF typeId = '1' THEN		
		IF var_datefilter = 'all' THEN
			SELECT  COUNT(*) INTO var_rows 
			FROM tblreceipt s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE IF(var_search = 'all',TRUE, (
			RcpID LIKE CONCAT('%',var_search,'%')
			OR RcpReference LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.TotalRcpAmount = var_search))
			;
			SELECT  RcpID 'rcpId',RcpReference 'reference', COALESCE(DATE_FORMAT(s.RcpDate, '%d-%b-%Y'),'') 'rcpDate', s.CustID 'custId', COALESCE(c.CustName,'') 'custName',COALESCE(s.TotalRcpAmount,0) 'rcpTotalAmt'
			FROM tblreceipt s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE IF(var_search = 'all',TRUE, (
			RcpID LIKE CONCAT('%',var_search,'%')
			OR RcpReference LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.TotalRcpAmount = var_search))
			ORDER BY s.RcpID DESC
			LIMIT var_num  OFFSET var_off
			;
		ELSE
			SELECT  COUNT(*) INTO var_rows 
			FROM tblreceipt s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE DATE(s.RcpDate) BETWEEN var_fd AND var_td AND IF(var_search = 'all',TRUE, (
			RcpID LIKE CONCAT('%',var_search,'%')
			OR RcpReference LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.TotalRcpAmount = var_search))
			;
			SELECT  RcpID 'rcpId',RcpReference 'reference', COALESCE(DATE_FORMAT(s.RcpDate, '%d-%b-%Y'),'') 'rcpDate', s.CustID 'custId', COALESCE(c.CustName,'') 'custName',COALESCE(s.TotalRcpAmount,0) 'rcpTotalAmt'
			FROM tblreceipt s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE DATE(s.RcpDate) BETWEEN var_fd AND var_td AND IF(var_search = 'all',TRUE, (
			RcpID LIKE CONCAT('%',var_search,'%')
			OR RcpReference LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.TotalRcpAmount = var_search))
			ORDER BY s.RcpID DESC
			LIMIT var_num  OFFSET var_off
			;
		END IF;
	ELSE
		IF var_datefilter = 'all' THEN
			SELECT  COUNT(*) INTO var_rows 
			FROM tblreceipt s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE s.uidcreate = var_user_id AND IF(var_search = 'all',TRUE, (
			RcpID LIKE CONCAT('%',var_search,'%')
			OR RcpReference LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.TotalRcpAmount = var_search))
			;
			SELECT  RcpID 'rcpId',RcpReference 'reference', COALESCE(DATE_FORMAT(s.RcpDate, '%d-%b-%Y'),'') 'rcpDate', s.CustID 'custId', COALESCE(c.CustName,'') 'custName',COALESCE(s.TotalRcpAmount,0) 'rcpTotalAmt'
			FROM tblreceipt s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE s.uidcreate = var_user_id AND IF(var_search = 'all',TRUE, (
			RcpID LIKE CONCAT('%',var_search,'%')
			OR RcpReference LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.TotalRcpAmount = var_search))
			ORDER BY s.RcpID DESC
			LIMIT var_num  OFFSET var_off
			;
		ELSE
			SELECT  COUNT(*) INTO var_rows 
			FROM tblreceipt s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE DATE(s.RcpDate) BETWEEN var_fd AND var_td AND s.uidcreate = var_user_id AND IF(var_search = 'all',TRUE, (
			RcpID LIKE CONCAT('%',var_search,'%')
			OR RcpReference LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.TotalRcpAmount = var_search))
			;
			SELECT  RcpID 'rcpId',RcpReference 'reference', COALESCE(DATE_FORMAT(s.RcpDate, '%d-%b-%Y'),'') 'rcpDate', s.CustID 'custId', COALESCE(c.CustName,'') 'custName',COALESCE(s.TotalRcpAmount,0) 'rcpTotalAmt'
			FROM tblreceipt s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			WHERE DATE(s.RcpDate) BETWEEN var_fd AND var_td AND s.uidcreate = var_user_id AND IF(var_search = 'all',TRUE, (
			RcpID LIKE CONCAT('%',var_search,'%')
			OR RcpReference LIKE CONCAT('%',var_search,'%')
			OR c.CustID = var_search
			OR c.CustName LIKE CONCAT('%',var_search,'%')
			OR s.TotalRcpAmount = var_search))
			ORDER BY s.RcpID 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_receipt_prefix`;
DELIMITER |
CREATE PROCEDURE `crm_mb_receipt_prefix`(var_user_id varchar(255), var_key varchar(255))
    DETERMINISTIC
BEGIN
	IF var_key = 'all' THEN
		SELECT CONCAT(var_id,crm_generate_zero(int_length,int_lastid)) 'prefix_val', var_id 'prefix_key' FROM tblnumberprefix_custom WHERE var_type = 'AR-PY' ORDER BY var_id;
	ELSE
		SELECT CONCAT(var_id,crm_generate_zero(int_length,int_lastid)) 'prefix_val', var_id 'prefix_key' FROM tblnumberprefix_custom WHERE var_type = 'AR-PY' AND var_id LIKE CONCAT('%',var_key,'%') ORDER BY var_id;
	END IF;
	SELECT COALESCE((SELECT appid FROM tbluserprofile WHERE uid = var_user_id AND apptype = 'AR-PY'),'') as 'user_prefix';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_sale_invoice_list_search_adv`;
DELIMITER |
CREATE PROCEDURE `crm_mb_sale_invoice_list_search_adv`(var_num int, var_page int,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_rows varchar(255);
	DECLARE var_off INT;
	DECLARE typeId varchar(255) DEFAULT (Select RM_TypeID from crm_role where RM_ID = (SELECT URoleID FROM tbluser where UID = var_user_id) LIMIT 1);
	DECLARE var_empId VARCHAR(255);
	SET var_off = ((var_page-1)*var_num);
	IF typeId = '1' THEN		
		IF var_datefilter = 'all' THEN
			SELECT  COUNT(*) INTO var_rows 
			FROM tblsales s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			LEFT JOIN tblemployee e ON e.EmpID = s.EmpID
			WHERE IF(var_search = 'all',TRUE, (
			SalID LIKE CONCAT('%',var_search,'%')
			OR SalReference 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.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 s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			LEFT JOIN tblemployee e ON e.EmpID = s.EmpID
			WHERE IF(var_search = 'all',TRUE, (
			SalID LIKE CONCAT('%',var_search,'%')
			OR SalReference 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.SalID DESC
			LIMIT var_num  OFFSET var_off
			;
		ELSE
			SELECT  COUNT(*) INTO var_rows 
			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_fd AND var_td AND IF(var_search = 'all',TRUE, (
			SalID LIKE CONCAT('%',var_search,'%')
			OR SalReference 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.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 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 IF(var_search = 'all',TRUE, (
			SalID LIKE CONCAT('%',var_search,'%')
			OR SalReference 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.SalID DESC
			LIMIT var_num  OFFSET var_off
			;
		END IF;
	ELSE
		IF var_datefilter = 'all' THEN
			SET var_empId = (SELECT tbluseremployee.EmpID from tbluseremployee where tbluseremployee.UID = var_user_id LIMIT 1);
			SELECT  COUNT(*) INTO var_rows 
			FROM tblsales 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, (
			SalID LIKE CONCAT('%',var_search,'%')
			OR SalReference 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.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 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, (
			SalID LIKE CONCAT('%',var_search,'%')
			OR SalReference 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.SalID 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 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, (
			SalID LIKE CONCAT('%',var_search,'%')
			OR SalReference 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.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 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, (
			SalID LIKE CONCAT('%',var_search,'%')
			OR SalReference 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.SalID 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_sale_invoice_paid_list`;
DELIMITER |
CREATE PROCEDURE `crm_mb_sale_invoice_paid_list`(in var_user_id varchar(255), in var_num int, in var_page int,var_search varchar(255),var_all varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	IF var_all = 'all' THEN
		SELECT COUNT(*) INTO var_rows 
		FROM tbltemp_inv_paidatsales
		WHERE IF(var_search = 'all',TRUE ,
			(
				salid LIKE CONCAT('%',var_search,'%') OR
				rcpid LIKE CONCAT('%',var_search,'%') OR
				discount = var_search OR
				amount = var_search OR
				pmtmethodref LIKE CONCAT('%',var_search,'%') OR
				reference LIKE CONCAT('%',var_search,'%')
			)
		);
		SELECT COALESCE(salid,'') 'saleId', COALESCE(rcpid,'') 'rcpId', COALESCE(accid,'') 'account', COALESCE(discount,0) 'discount',COALESCE(amount,0) 'amount', COALESCE(s.classid,'') 'classId', COALESCE(c.Des,'') 'className',
					 COALESCE(pmtmethod,'') 'pmtMethod', COALESCE(pmtmethodref,'') 'pmtReference', COALESCE(reference,'') 'refernce'
		FROM tbltemp_inv_paidatsales s
		LEFT JOIN tblclass c on c.ClassID = s.classid
		WHERE IF(var_search = 'all',TRUE ,
			(
				salid LIKE CONCAT('%',var_search,'%') OR
				rcpid LIKE CONCAT('%',var_search,'%') OR
				discount = var_search OR
				amount = var_search OR
				pmtmethodref LIKE CONCAT('%',var_search,'%') OR
				reference LIKE CONCAT('%',var_search,'%')
			)
		)
		ORDER BY rcpid DESC,salid DESC
		LIMIT var_num  OFFSET var_off;
		SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
	ELSE
		SELECT COALESCE(salid,'') 'saleId', COALESCE(rcpid,'') 'rcpId', COALESCE(accid,'') 'account', COALESCE(discount,0) 'discount',COALESCE(amount,0) 'amount', COALESCE(s.classid,'') 'classId', COALESCE(c.Des,'') 'className',
				 COALESCE(pmtmethod,'') 'pmtMethod', COALESCE(pmtmethodref,'') 'pmtReference', COALESCE(reference,'') 'refernce'
		FROM tbltemp_inv_paidatsales s
		LEFT JOIN tblclass c on c.ClassID = s.classid
		WHERE salid = var_search AND rcpid = var_all;
	END IF;
END |
DELIMITER ;

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

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_sale_order_list_search_adv`;
DELIMITER |
CREATE PROCEDURE `crm_mb_sale_order_list_search_adv`(var_num int, var_page int,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_rows varchar(255);
	DECLARE var_off INT;
	DECLARE typeId varchar(255) DEFAULT (Select RM_TypeID from crm_role where RM_ID = (SELECT URoleID FROM tbluser where UID = var_user_id) LIMIT 1);
	DECLARE var_empId VARCHAR(255);
	SET var_off = ((var_page-1)*var_num);
	IF typeId = '1' THEN		
		IF var_datefilter = 'all' THEN
			SELECT  COUNT(*) INTO var_rows 
			FROM tblsaleorder s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			LEFT JOIN tblemployee e ON e.EmpID = s.EmpID
			WHERE IF(var_search = 'all',TRUE, (
			s.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.SalID 'EntryNo', COALESCE(s.SalReference,'') 'Reference', COALESCE(DATE_FORMAT(s.SalDate, '%d-%b-%Y'),'') 'SalesOrderDate', s.CustID 'CustomerID', COALESCE(c.CustName,'') 'CustomerName',
					 s.EmpID 'empId', COALESCE(e.EmpName,'') 'empName', CAST(COALESCE(s.NetTotalAmt, 0) AS DECIMAL(16, 2)) 'TotalAmount'
			FROM tblsaleorder s
			LEFT JOIN tblcustomer c ON c.CustID = s.CustID
			LEFT JOIN tblemployee e ON e.EmpID = s.EmpID
			WHERE IF(var_search = 'all',TRUE, (
			s.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.SalID DESC
			LIMIT var_num  OFFSET var_off
			;
		ELSE
			SELECT  COUNT(*) INTO var_rows 
			FROM tblsaleorder 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 IF(var_search = 'all',TRUE, (
			s.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.SalID 'EntryNo', COALESCE(s.SalReference,'') 'Reference', COALESCE(DATE_FORMAT(s.SalDate, '%d-%b-%Y'),'') 'SalesOrderDate', s.CustID 'CustomerID', COALESCE(c.CustName,'') 'CustomerName',
					 s.EmpID 'empId', COALESCE(e.EmpName,'') 'empName', CAST(COALESCE(s.NetTotalAmt, 0) AS DECIMAL(16, 2)) 'TotalAmount'
			FROM tblsaleorder 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 IF(var_search = 'all',TRUE, (
			s.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.SalID DESC
			LIMIT var_num  OFFSET var_off
			;
		END IF;
	ELSE
		IF var_datefilter = 'all' THEN
			SET var_empId = (SELECT tbluseremployee.EmpID from tbluseremployee where tbluseremployee.UID = var_user_id LIMIT 1);
			SELECT  COUNT(*) INTO var_rows 
			FROM tblsaleorder 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, (
			s.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.SalID 'EntryNo', COALESCE(s.SalReference,'') 'Reference', COALESCE(DATE_FORMAT(s.SalDate, '%d-%b-%Y'),'') 'SalesOrderDate', s.CustID 'CustomerID', COALESCE(c.CustName,'') 'CustomerName',
					 s.EmpID 'empId', COALESCE(e.EmpName,'') 'empName', CAST(COALESCE(s.NetTotalAmt, 0) AS DECIMAL(16, 2)) 'TotalAmount'
			FROM tblsaleorder 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, (
			s.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.SalID 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 tblsaleorder 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, (
			s.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.SalID 'EntryNo', COALESCE(s.SalReference,'') 'Reference', COALESCE(DATE_FORMAT(s.SalDate, '%d-%b-%Y'),'') 'SalesOrderDate', s.CustID 'CustomerID', COALESCE(c.CustName,'') 'CustomerName',
					 s.EmpID 'empId', COALESCE(e.EmpName,'') 'empName', CAST(COALESCE(s.NetTotalAmt, 0) AS DECIMAL(16, 2)) 'TotalAmount'
			FROM tblsaleorder 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, (
			s.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.SalID 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_sale_return_list`;
DELIMITER |
CREATE PROCEDURE `crm_mb_sale_return_list`(in var_num int, in var_page int,in var_user_id varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	DECLARE typeId varchar(255) DEFAULT (Select RM_TypeID from crm_role where RM_ID = (SELECT URoleID FROM tbluser where UID = var_user_id) LIMIT 1);
	DECLARE var_empId VARCHAR(255);
	SET var_off = ((var_page-1)*var_num);
	IF typeId = '1' THEN		
		SELECT COUNT(*) INTO var_rows FROM tblsales_return;
		SELECT s.RetID 'retId', s.SalID 'saleId', COALESCE(s.SalReference,'') 'saleReference', COALESCE(DATE_FORMAT(s.SalDate, '%d-%b-%Y'),'') 'saleDate', s.CustID 'custId', COALESCE((SELECT CustName FROM tblcustomer c WHERE c.CustID=s.CustID),'') 'custName',
				 s.EmpID 'empId', COALESCE((SELECT EmpName FROM tblemployee e WHERE e.EmpID=s.EmpID),'') 'empName', COALESCE(s.NetTotalAmt,0) 'netTotalAmt'
		FROM tblsales_return s
		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 WHERE EmpID = var_empId;
		SELECT s.RetID 'retId', s.SalID 'saleId', COALESCE(s.SalReference,'') 'saleReference', COALESCE(DATE_FORMAT(s.SalDate, '%d-%b-%Y'),'') 'saleDate', s.CustID 'custId', COALESCE((SELECT CustName FROM tblcustomer c WHERE c.CustID=s.CustID),'') 'custName',
				 s.EmpID 'empId', COALESCE((SELECT EmpName FROM tblemployee e WHERE e.EmpID=s.EmpID),'') 'empName', COALESCE(s.NetTotalAmt,0) 'netTotalAmt'
		FROM tblsales_return s
		WHERE EmpID = var_empId
		ORDER BY s.RetID DESC
		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_sale_return_list_sale_invoice`;
DELIMITER |
CREATE PROCEDURE `crm_mb_sale_return_list_sale_invoice`(in var_num int, in var_page int,in var_user_id varchar(255), var_cid varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SET var_off = ((var_page-1)*var_num);
	SELECT COUNT(*) INTO var_rows FROM tblsales s WHERE s.PostStatus = 'Posted' AND s.CustID = var_cid ;
	SELECT s.SalID 'saleId', s.SalReference 'saleReference', COALESCE(DATE_FORMAT(s.SalDate, '%d-%b-%Y'),'') 'saleDate' ,s.CustID 'custId', COALESCE((SELECT CustName FROM tblcustomer c WHERE c.CustID=s.CustID),'') 'custName',
				 COALESCE(s.NetTotalAmt,0) 'netTotalAmt', s.PmtStatus 'pmtStatus', s.PostStatus 'postSatus'
	FROM tblsales s WHERE s.PostStatus = 'Posted' AND s.CustID = var_cid
	ORDER BY s.SalID DESC
	LIMIT var_num  OFFSET var_off
	;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_sale_return_list_sale_invoice_search`;
DELIMITER |
CREATE PROCEDURE `crm_mb_sale_return_list_sale_invoice_search`(in var_num int, in var_page int,in var_user_id varchar(255),var_cid varchar(255), var_search varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	SET var_off = ((var_page-1)*var_num);
	SELECT COUNT(*) INTO var_rows FROM tblsales s WHERE s.PostStatus = 'Posted' AND s.CustID = var_cid AND s.SalID LIKE CONCAT('%',var_search,'%') ;
	SELECT s.SalID 'saleId', s.SalReference 'saleReference', COALESCE(DATE_FORMAT(s.SalDate, '%d-%b-%Y'),'') 'saleDate' ,s.CustID 'custId', COALESCE((SELECT CustName FROM tblcustomer c WHERE c.CustID=s.CustID),'') 'custName',
				 COALESCE(s.NetTotalAmt,0) 'netTotalAmt', s.PmtStatus 'pmtStatus', s.PostStatus 'postSatus'
	FROM tblsales s WHERE s.PostStatus = 'Posted' AND s.CustID = var_cid AND s.SalID LIKE CONCAT('%',var_search,'%')
	ORDER BY s.SalID DESC
	LIMIT var_num  OFFSET var_off
	;
	SELECT CEIL(COALESCE(var_rows,0)/var_num) 'totalPage';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `crm_mb_sale_return_list_search`;
DELIMITER |
CREATE PROCEDURE `crm_mb_sale_return_list_search`(in var_num int, in var_page int,in var_user_id varchar(255),var_search varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE var_rows varchar(255);
	DECLARE var_off INT;
	DECLARE typeId varchar(255) DEFAULT (Select RM_TypeID from crm_role where RM_ID = (SELECT URoleID FROM tbluser where UID = var_user_id) LIMIT 1);
	DECLARE var_empId VARCHAR(255);
	SET var_off = ((var_page-1)*var_num);
	IF typeId = '1' THEN		
		SELECT COUNT(*) INTO var_rows FROM tblsales_return WHERE RetID LIKE CONCAT('%',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((SELECT CustName FROM tblcustomer c WHERE c.CustID=s.CustID),'') 'custName',
				 s.EmpID 'empId', COALESCE((SELECT EmpName FROM tblemployee e WHERE e.EmpID=s.EmpID),'') 'empName', COALESCE(s.NetTotalAmt,0) 'netTotalAmt'
		FROM tblsales_return s
		WHERE RetID LIKE CONCAT('%',var_search,'%') OR SalReference LIKE CONCAT('%',var_search,'%') OR SalID LIKE CONCAT('%',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 WHERE RetID LIKE CONCAT('%',var_search,'%') AND EmpID = var_empId AND (SalReference LIKE CONCAT('%',var_search,'%') OR SalID LIKE CONCAT('%',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((SELECT CustName FROM tblcustomer c WHERE c.CustID=s.CustID),'') 'custName',
				 s.EmpID 'empId', COALESCE((SELECT EmpName FROM tblemployee e WHERE e.EmpID=s.EmpID),'') 'empName', COALESCE(s.NetTotalAmt,0) 'netTotalAmt'
		FROM tblsales_return s
		WHERE RetID LIKE CONCAT('%',var_search,'%') AND EmpID = var_empId AND (SalReference LIKE CONCAT('%',var_search,'%') OR SalID LIKE CONCAT('%',var_search,'%'))
		ORDER BY s.RetID DESC
		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_sale_return_list_search_adv`;
DELIMITER |
CREATE PROCEDURE `crm_mb_sale_return_list_search_adv`(var_num int, var_page int,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_rows varchar(255);
	DECLARE var_off INT;
	DECLARE typeId varchar(255) DEFAULT (Select RM_TypeID from crm_role where RM_ID = (SELECT URoleID FROM tbluser where UID = var_user_id) LIMIT 1);
	DECLARE var_empId VARCHAR(255);
	SET var_off = ((var_page-1)*var_num);
	IF typeId = '1' THEN		
		IF var_datefilter = 'all' THEN
			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 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 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
			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 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 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;
	ELSE
		IF var_datefilter = 'all' THEN
			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 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))
			;
