DELIMITER ;

DROP PROCEDURE IF EXISTS `listCrmCaseArticle`;
DELIMITER |
CREATE PROCEDURE `listCrmCaseArticle`()
    DETERMINISTIC
BEGIN
SELECT
*
FROM
crm_case_article a;
END |
DELIMITER ;

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

DROP PROCEDURE IF EXISTS `listCrmContacts`;
DELIMITER |
CREATE PROCEDURE `listCrmContacts`(IN `userId` varchar(50))
    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
con.CO_ID conID,
con.CO_FirstName conFirstName,
con.CO_LastName conLastName,
con.CO_Salutation conSalutation,
con.CO_Phone conPhone,
con.CO_Mobile conMobile,
con.CO_Email conEmail,
con.CO_Title conTitle,
con.CO_Department conDepartment,
con.CO_ATo userId,
(SELECT UName FROM tbluser WHERE UID = con.CO_ATo) username,
con.CO_LeadSource sourceID,
(SELECT LS_Name FROM crm_lead_source WHERE LS_ID = con.CO_LeadSource) sourceName,
con.CO_ReportTo reportToId,
(SELECT CONCAT(CO_Salutation," ",CO_FirstName," ",CO_LastName) FROM crm_contact WHERE CO_ID = con.CO_ReportTo) reportToName,
con.CO_CBy conCreateBy,
(SELECT UName FROM tbluser WHERE UID = con.CO_CBy) conCreateByName,
con.CO_CDate conCreateDate,
con.CO_MBy conModifyBy,
CAST(con.CO_MDate AS date) modifyDate,
con.CO_CustID custID,
(SELECT c.CustName FROM tblcustomer c WHERE c.CustID = con.CO_CustID) custName,
con.CO_IsApproved isApproved
FROM
crm_contact con
ORDER BY con.CO_ID DESC;
ELSE
SELECT
con.CO_ID conID,
con.CO_FirstName conFirstName,
con.CO_LastName conLastName,
con.CO_Salutation conSalutation,
con.CO_Phone conPhone,
con.CO_Mobile conMobile,
con.CO_Email conEmail,
con.CO_Title conTitle,
con.CO_Department conDepartment,
con.CO_ATo userId,
(SELECT UName FROM tbluser WHERE UID = con.CO_ATo) username,
con.CO_LeadSource sourceID,
(SELECT LS_Name FROM crm_lead_source WHERE LS_ID = con.CO_LeadSource) sourceName,
con.CO_ReportTo reportToId,
(SELECT CONCAT(CO_Salutation," ",CO_FirstName," ",CO_LastName) FROM crm_contact WHERE CO_ID = con.CO_ReportTo) reportToName,
con.CO_CBy conCreateBy,
(SELECT UName FROM tbluser WHERE UID = con.CO_CBy) conCreateByName,
con.CO_CDate conCreateDate,
con.CO_MBy conModifyBy,
CAST(con.CO_MDate AS date) modifyDate,
con.CO_CustID custID,
(SELECT c.CustName FROM tblcustomer c WHERE c.CustID = con.CO_CustID) custName,
con.CO_IsApproved isApproved
FROM
crm_contact con
WHERE con.CO_CBy = userId OR con.CO_ATo = userId
ORDER BY con.CO_ID DESC;
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listCrmEvents`;
DELIMITER |
CREATE PROCEDURE `listCrmEvents`(IN `userId` varchar(50))
    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
ev.EV_ID evId,
ev.EV_Name evName,
DATE_FORMAT(ev.EV_StartDate,'%d/%m/%Y %h:%i %p') evStartDate,
DATE_FORMAT(ev.EV_EndDate,'%d/%m/%Y %h:%i %p') evEndDate,
ev.EV_Duration evDuration,
ev.EV_Budget evBudget,
ev.EV_Description evDes,
ev.EV_CBy evCreateBy,
(SELECT UName FROM tbluser WHERE UID = ev.EV_CBy) evCreateByName,
DATE_FORMAT(ev.EV_CDate,'%d/%m/%Y %h:%i %p') evCreateDate,
ev.EV_MBy evModifiedBy,
CAST(ev.EV_MDate AS DATE) evModifiedDate,
ev.EV_RToID AS evRelatedToModuleId,
ev.EV_RToType AS evRelatedToModuleType,
findModuleDetailsByModuleNameAndItsId(ev.EV_RToType,ev.EV_RToID) AS evRelatedName,
lo.LO_ID loId,
lo.LO_Name loName,
us.UID userID,
us.UName username
FROM
crm_event ev
LEFT OUTER JOIN
crm_location lo
ON ev.EV_LocationID = lo.LO_ID
LEFT OUTER JOIN
tbluser us
ON ev.EV_AssignTo = us.UID
ORDER BY ev.EV_ID DESC;
ELSE
SELECT
ev.EV_ID evId,
ev.EV_Name evName,
DATE_FORMAT(ev.EV_StartDate,'%d/%m/%Y %h:%i %p') evStartDate,
DATE_FORMAT(ev.EV_EndDate,'%d/%m/%Y %h:%i %p') evEndDate,
ev.EV_Duration evDuration,
ev.EV_Budget evBudget,
ev.EV_Description evDes,
ev.EV_CBy evCreateBy,
(SELECT UName FROM tbluser WHERE UID = ev.EV_CBy) evCreateByName,
DATE_FORMAT(ev.EV_CDate,'%d/%m/%Y %h:%i %p') evCreateDate,
ev.EV_MBy evModifiedBy,
CAST(ev.EV_MDate AS DATE) evModifiedDate,
ev.EV_RToID AS evRelatedToModuleId,
ev.EV_RToType AS evRelatedToModuleType,
findModuleDetailsByModuleNameAndItsId(ev.EV_RToType,ev.EV_RToID) AS evRelatedName,
lo.LO_ID loId,
lo.LO_Name loName,
us.UID userID,
us.UName username
FROM
crm_event ev
LEFT OUTER JOIN
crm_location lo
ON ev.EV_LocationID = lo.LO_ID
LEFT OUTER JOIN
tbluser us
ON ev.EV_AssignTo = us.UID
WHERE ev.EV_AssignTo = userId OR ev.EV_CBy = userId
ORDER BY ev.EV_ID DESC;
END IF;
END |
DELIMITER ;

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

DROP PROCEDURE IF EXISTS `listCrmMeetings`;
DELIMITER |
CREATE PROCEDURE `listCrmMeetings`(IN `userId` varchar(50))
    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
M.M_ID meetingId,
M.M_Subject meetingSubject,
DATE_FORMAT(M.M_StartDate,'%d/%m/%Y %h:%i %p') meetingStartDate,
DATE_FORMAT(M.M_EndDate,'%d/%m/%Y %h:%i %p') meetingEndDate,
M.M_Duration meetingDuration,
MS.MS_ID statusId, MS.MS_Name statusName,
M.M_RToType meetingRelatedToModuleType,
M.M_RToID meetingRelatedToModuleId,
findModuleDetailsByModuleNameAndItsId(M.M_RToType, M.M_RToID) meetingRelatedToModuleName,
M.M_Location meetingLocation,
M.M_Des meetingDes,
U.UID userID,
U.UName username,
M.M_CBy meetingCreateBy,
(SELECT UName FROM tbluser WHERE UID = M.M_CBy) meetingCreateByName,
DATE_FORMAT(M.M_CDate,'%d/%m/%Y %h:%i %p') meetingCreateDate,
M.M_MBy meetingModifiedBy,
CAST(M.M_MDate AS date) meetingModifiedDate
FROM
crm_meeting M
LEFT OUTER JOIN
crm_meeting_status MS
ON M.M_StatusID = MS.MS_ID
LEFT OUTER JOIN
tbluser U
ON M.M_ATo = U.UID
ORDER BY M.M_ID DESC;
ELSE
SELECT
M.M_ID meetingId,
M.M_Subject meetingSubject,
DATE_FORMAT(M.M_StartDate,'%d/%m/%Y %h:%i %p') meetingStartDate,
DATE_FORMAT(M.M_EndDate,'%d/%m/%Y %h:%i %p') meetingEndDate,
M.M_Duration meetingDuration,
MS.MS_ID statusId, MS.MS_Name statusName,
M.M_RToType meetingRelatedToModuleType,
M.M_RToID meetingRelatedToModuleId,
findModuleDetailsByModuleNameAndItsId(M.M_RToType, M.M_RToID) meetingRelatedToModuleName,
M.M_Location meetingLocation,
M.M_Des meetingDes,
U.UID userID,
U.UName username,
M.M_CBy meetingCreateBy,
(SELECT UName FROM tbluser WHERE UID = M.M_CBy) meetingCreateByName,
DATE_FORMAT(M.M_CDate,'%d/%m/%Y %h:%i %p') meetingCreateDate,
M.M_MBy meetingModifiedBy,
CAST(M.M_MDate AS date) meetingModifiedDate
FROM
crm_meeting M
LEFT OUTER JOIN
crm_meeting_status MS
ON M.M_StatusID = MS.MS_ID
LEFT OUTER JOIN
tbluser U
ON M.M_ATo = U.UID
WHERE M.M_ATo = userId OR M.M_CBy = userId
ORDER BY M.M_ID DESC;
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listCrmOpportunities`;
DELIMITER |
CREATE PROCEDURE `listCrmOpportunities`()
    DETERMINISTIC
BEGIN
SELECT
op.OP_ID as opId,
op.OP_Amt as opAmount,
CAST(op.OP_CloseDate AS date) as opCloseDate,
op.OP_CBy as opCreateBy,
CAST(op.OP_CDate AS date) as opCreateDate,
op.OP_Des as opDes,
op.OP_MBy as opModifyBy,
CAST(op.OP_MDate AS date) as opModifyDate,
op.OP_Name as opName,
op.OP_NextStep as opNextStep,
op.OP_Probability as opProbability,
cust.CustID as custID,
cust.CustName as custName,
user.UID as userID,
user.UName as username,
camp.CA_ID as campID,
camp.CA_Name as campName,
leadsource.LS_ID as sourceID,
leadsource.LS_Name as sourceName,
ops.OS_ID as osId,
ops.OS_Name as osName,
opt.OT_ID as otId,
opt.OT_Name as otName
FROM
crm_opportunity op
INNER JOIN
tblcustomer cust
ON op.OP_CustID=cust.CustID
LEFT OUTER JOIN
tbluser user
ON op.OP_ATo=user.UID
LEFT OUTER JOIN
crm_camp camp
ON op.OP_CampID=camp.CA_ID
LEFT OUTER JOIN
crm_lead_source leadsource
ON op.OP_LeadSourceID=leadsource.LS_ID
INNER JOIN
crm_opportunity_stage ops
ON op.OP_StageID=ops.OS_ID
LEFT OUTER JOIN
crm_opportunity_type opt
ON op.OP_TypeID=opt.OT_ID
WHERE op.OP_IsApproved = 1
ORDER BY op.OP_ID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listCrmParentCampaigns`;
DELIMITER |
CREATE PROCEDURE `listCrmParentCampaigns`(IN `campId` varchar(11))
    DETERMINISTIC
BEGIN
DECLARE childCount INT DEFAULT 0;
SELECT COUNT(CA_ID) INTO childCount FROM crm_camp WHERE CA_ParentID = campId;
IF childCount <= 0 THEN
SELECT CA_ID campID, CA_Name campName
FROM crm_camp WHERE CA_ID <> campId AND CA_ParentID IS NULL OR CA_ParentID = "";
ELSE
SELECT DISTINCT NULL AS campID, NULL AS campName FROM crm_camp;
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listCrmSaleOrder`;
DELIMITER |
CREATE PROCEDURE `listCrmSaleOrder`()
    DETERMINISTIC
BEGIN
SELECT sr.SalID, DATE_FORMAT(sr.SalDate, '%d-%b-%Y') as 'SalDate',DATE_FORMAT(sr.DueDate, '%d-%b-%Y') as 'DueDate',Sr.PostStatus,COALESCE(sr.PmtStatus,'') 'PmtStatus',
COALESCE(sr.TotalAmt,'') 'TotalAmt',  COALESCE(sr.DisInvDol,'') 'DisInvDol', COALESCE(sr.TotalDis ,'') 'TotalDis' , COALESCE( sr.NetTotalAmt ,'') 'NetTotalAmt',
sr.CustID,COALESCE((SELECT CustName from tblcustomer c where c.CustID=sr.CustID),'') 'CustName',
sr.EmpID, COALESCE((SELECT e.EmpName FROM tblemployee e WHERE e.EmpID=sr.EmpID),'') as 'EmpName',
sr.ClassID, COALESCE((SELECT cz.ClassID FROM tblclass cz WHERE cz.ClassID=sr.ClassID),'') as 'ClassName'
FROM tblsaleorder sr
Where sr.PostStatus in ('Open','Posted')
order by sr.SalID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listCustomFieldsOfQuotations`;
DELIMITER |
CREATE PROCEDURE `listCustomFieldsOfQuotations`(IN `opId` varchar(11))
    DETERMINISTIC
BEGIN
SELECT
SalID AS quoteId,
TotalAmt AS totalAmount,
SalDate AS quoteDate,
StartDate AS startDate,
ExpireDate AS expireDate,
emp.EmpID AS empId,
(SELECT EmpName FROM tblemployee WHERE EmpID = sale.EmpID) AS empName
FROM
tblsbquote sale
INNER JOIN
tblemployee emp
ON sale.EmpID = emp.EmpID
WHERE sale.CustID = (SELECT OP_CustID FROM crm_opportunity WHERE OP_ID = opId)
AND sale.SalID NOT IN (SELECT QuotID FROM crm_opportunity_quote);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listCustomFieldsOfSaleorder`;
DELIMITER |
CREATE PROCEDURE `listCustomFieldsOfSaleorder`(IN `opId` varchar(11))
    DETERMINISTIC
BEGIN
SELECT
sale.SalID AS saleId,
sale.TotalAmt AS totalAmount,
sale.SalDate AS saleDate,
sale.DueDate AS dueDate,
sale.EmpID AS empId,
(SELECT EmpName FROM tblemployee WHERE EmpID = sale.EmpID) AS empName
FROM
tblsaleorder sale
WHERE sale.CustID = (SELECT OP_CustID FROM crm_opportunity WHERE OP_ID = opId)
AND sale.SalID NOT IN (SELECT S_O_ID FROM crm_opportunity_saleorder);
END |
DELIMITER ;

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

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

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

DROP PROCEDURE IF EXISTS `listLeadWithSpecificUser`;
DELIMITER |
CREATE PROCEDURE `listLeadWithSpecificUser`(IN `userId` varchar(50))
    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
lead.LA_ID as leadID,
lead.LA_Email as email,
lead.LA_AccountName as accountName,
lead.LA_CBy as createBy,
(SELECT UName FROM tbluser WHERE UID = lead.LA_CBy) 'createByName',
TIMESTAMP(lead.LA_CDate) as createDate,
lead.LA_FirstName as firstName,
lead.LA_LastName as lastName,
lead.LA_Des as description,
lead.LA_MBy as modifyBy,
CAST(lead.LA_MDate AS date) as modifyDate,
lead.LA_Salutation as salutation,
lead.LA_CA_ID as campID,
(SELECT CA_Name FROM crm_camp WHERE CA_ID = lead.LA_CA_ID) as campName,
lead.LA_ATo as assignToUserId,
(SELECT UName FROM tbluser u WHERE u.UID = lead.LA_ATo) as assignToUserName,
lead.LA_IndustID as industID,
(SELECT I_Name FROM crm_industry WHERE I_ID = lead.LA_IndustID) as industName,
lead.LA_SourceID as sourceID,
(SELECT LS_Name FROM crm_lead_source WHERE LS_ID = lead.LA_SourceID) as sourceName,
lead.LA_StatusID as statusID,
(SELECT LST_Name FROM crm_lead_status WHERE LST_ID = lead.LA_StatusID) as statusName
FROM
crm_lead lead
ORDER BY lead.LA_ID DESC;
ELSE
SELECT
lead.LA_ID as leadID,
lead.LA_Email as email,
lead.LA_AccountName as accountName,
lead.LA_CBy as createBy,
lead.LA_Des as description,
(SELECT UName FROM tbluser WHERE UID = lead.LA_CBy) 'createByName',
TIMESTAMP(lead.LA_CDate) as createDate,
lead.LA_FirstName as firstName,
lead.LA_LastName as lastName,
lead.LA_MBy as modifyBy,
CAST(lead.LA_MDate AS date) as modifyDate,
lead.LA_Salutation as salutation,
lead.LA_CA_ID as campID,
(SELECT CA_Name FROM crm_camp WHERE CA_ID = lead.LA_CA_ID) as campName,
lead.LA_ATo as assignToUserId,
(SELECT UName FROM tbluser u WHERE u.UID = lead.LA_ATo) as assignToUserName,
lead.LA_IndustID as industID,
(SELECT I_Name FROM crm_industry WHERE I_ID = lead.LA_IndustID) as industName,
lead.LA_SourceID as sourceID,
(SELECT LS_Name FROM crm_lead_source WHERE LS_ID = lead.LA_SourceID) as sourceName,
lead.LA_StatusID as statusID,
(SELECT LST_Name FROM crm_lead_status WHERE LST_ID = lead.LA_StatusID) as statusName
FROM
crm_lead lead
WHERE lead.LA_ATo = userId OR lead.LA_CBy = userId
ORDER BY lead.LA_ID DESC;
END IF;
END |
DELIMITER ;

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

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

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

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

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

DROP PROCEDURE IF EXISTS `listOpportunitiesRelatedToContact`;
DELIMITER |
CREATE PROCEDURE `listOpportunitiesRelatedToContact`(IN `conId` varchar(11))
    DETERMINISTIC
BEGIN
SELECT
op.OP_ID AS opId,
op.OP_Name AS opName,
op.OP_Amt AS opAmount,
st.OS_ID AS opStageId,
st.OS_Name AS opStageName,
op.OP_CloseDate AS opCloseDate,
cust.CustID AS custID,
cust.CustName AS custName
FROM
crm_opportunity op
INNER JOIN
crm_opportunity_stage st
ON op.OP_StageID = st.OS_ID
INNER JOIN
crm_opportunity_contact opcon
ON op.OP_ID = opcon.OPCON_OPID
LEFT OUTER JOIN
tblcustomer cust
ON op.OP_CustID = cust.CustID
WHERE opcon.OPCON_CONID = conId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listOpportunityWithSpecificUser`;
DELIMITER |
CREATE PROCEDURE `listOpportunityWithSpecificUser`(IN `userId` varchar(50))
    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
op.OP_ID as opId,
op.OP_Amt as opAmount,
TIMESTAMP(op.OP_CloseDate) as opCloseDate,
op.OP_CBy as opCreateBy,
(SELECT UName FROM tbluser WHERE UID = op.OP_CBy) 'opCreateByName',
TIMESTAMP(op.OP_CDate) as opCreateDate,
op.OP_Des as opDes,
op.OP_MBy as opModifyBy,
TIMESTAMP(op.OP_MDate) as opModifyDate,
op.OP_Name as opName,
op.OP_NextStep as opNextStep,
op.OP_Probability as opProbability,
op.OP_CustID as custID,
(SELECT CustName FROM tblcustomer WHERE CustID = op.OP_CustID) as custName,
op.OP_ATo as userID,
(SELECT UName FROM tbluser WHERE UID = op.OP_ATo) as username,
op.OP_CampID as campID,
(SELECT CA_Name FROM crm_camp WHERE CA_ID = op.OP_CampID) as campName,
op.OP_LeadSourceID as sourceID,
(SELECT LS_Name FROM crm_lead_source WHERE LS_ID = op.OP_LeadSourceID) as sourceName,
op.OP_StageID as osId,
(SELECT OS_Name FROM crm_opportunity_stage WHERE OS_ID = op.OP_StageID) as osName,
op.OP_TypeID as otId,
(SELECT OT_Name FROM crm_opportunity_type WHERE OT_ID = op.OP_TypeID) as otName ,
op.OP_IsApproved isApproved
FROM
crm_opportunity op
ORDER BY op.OP_ID DESC;
ELSE
SELECT
op.OP_ID as opId,
op.OP_Amt as opAmount,
TIMESTAMP(op.OP_CloseDate) as opCloseDate,
op.OP_CBy as opCreateBy,
(SELECT UName FROM tbluser WHERE UID = op.OP_CBy) 'opCreateByName',
TIMESTAMP(op.OP_CDate) as opCreateDate,
op.OP_Des as opDes,
op.OP_MBy as opModifyBy,
TIMESTAMP(op.OP_MDate) as opModifyDate,
op.OP_Name as opName,
op.OP_NextStep as opNextStep,
op.OP_Probability as opProbability,
op.OP_CustID as custID,
(SELECT CustName FROM tblcustomer WHERE CustID = op.OP_CustID) as custName,
op.OP_ATo as userID,
(SELECT UName FROM tbluser WHERE UID = op.OP_ATo) as username,
op.OP_CampID as campID,
(SELECT CA_Name FROM crm_camp WHERE CA_ID = op.OP_CampID) as campName,
op.OP_LeadSourceID as sourceID,
(SELECT LS_Name FROM crm_lead_source WHERE LS_ID = op.OP_LeadSourceID) as sourceName,
op.OP_StageID as osId,
(SELECT OS_Name FROM crm_opportunity_stage WHERE OS_ID = op.OP_StageID) as osName,
op.OP_TypeID as otId,
(SELECT OT_Name FROM crm_opportunity_type WHERE OT_ID = op.OP_TypeID) as otName ,
op.OP_IsApproved isApproved
FROM
crm_opportunity op
WHERE op.OP_ATo =  userId OR op.OP_CBy = userId
ORDER BY op.OP_ID DESC;
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listQuotationRelatedToOpportunity`;
DELIMITER |
CREATE PROCEDURE `listQuotationRelatedToOpportunity`(IN `opId` varchar(11))
    DETERMINISTIC
BEGIN
SELECT
quote.SalID quoteId,
quote.TotalAmt totalAmmount,
quote.SalDate quoteDate,
quote.StartDate startDate,
quote.ExpireDate expireDate,
emp.EmpID empId,
emp.EmpName empName,
L_ID opQuoteId
FROM
tblsbquote quote
INNER JOIN
crm_opportunity_quote opquote
ON quote.SalID = opquote.QuotID
LEFT OUTER JOIN
tblemployee emp
ON quote.EmpID = emp.EmpID
WHERE opquote.OP_ID = opId;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listQuotes`;
DELIMITER |
CREATE PROCEDURE `listQuotes`(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
qt.SalID AS saleId,
COALESCE(qt.SalReference, '') 'reference',
COALESCE(qt.Remark,'') 'remark',
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',
c.CustID AS custId,
c.CustName AS custName,
c.CustAddress AS custAddress,
e.EmpName AS empName,
e.EmpID AS empId,
cz.ClassID AS classId,
cz.Des AS className,
qt.ApproveStatus approvedStatus
FROM tblsbquote qt
LEFT OUTER JOIN tblcustomer c
ON c.CustID = qt.CustID
LEFT OUTER JOIN tblemployee e
ON e.EmpID = qt.EmpID
LEFT OUTER JOIN tblclass cz
ON cz.ClassID = qt.ClassID
order by qt.SalID DESC,qt.SalID DESC;
else
SELECT
qt.SalID AS saleId,
COALESCE(qt.SalReference, '') 'reference',
COALESCE(qt.Remark,'') 'remark',
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',
c.CustID AS custId,
c.CustName AS custName,
c.CustAddress AS custAddress,
e.EmpName AS empName,
e.EmpID AS empId,
cz.ClassID AS classId,
cz.Des AS className,
qt.ApproveStatus approvedStatus
FROM tblsbquote qt
LEFT OUTER JOIN tblcustomer c
ON c.CustID = qt.CustID
LEFT OUTER JOIN tblemployee e
ON e.EmpID = qt.EmpID
LEFT OUTER JOIN tblclass cz
ON cz.ClassID = qt.ClassID
where qt.EmpID = (select EmpID from tbluseremployee where uid = userId)
order by qt.SalID DESC,qt.SalID DESC;
end if;
end |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listQuoteStartupPage`;
DELIMITER |
CREATE PROCEDURE `listQuoteStartupPage`()
    DETERMINISTIC
BEGIN
SELECT ClassID, Des AS ClassName FROM tblclass;
SELECT EmpID, EmpName FROM tblemployee;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listSaleOrderById`;
DELIMITER |
CREATE PROCEDURE `listSaleOrderById`(IN `saleId` varchar(255))
    DETERMINISTIC
BEGIN
SELECT sr.SalID,COALESCE(sr.SalType,'') 'SalType', DATE_FORMAT(sr.SalDate, '%d-%b-%Y') as 'SalDate',DATE_FORMAT(sr.DueDate, '%d-%b-%Y') as 'DueDate',COALESCE(sr.Remark,'') 'Remark',COALESCE(sr.PriceCode,'') 'PriceCode',COALESCE(sr.SalReference,'') 'SalReference',  COALESCE(sr.CustID,'') 'CustID', COALESCE(sr.EmpID,'') 'EmpID', COALESCE(sr.ClassID,'') 'ClassID',
COALESCE(sr.TotalAmt,0) 'TotalAmt',  COALESCE(sr.DisInvDol,0) 'DisInvDol',COALESCE(sr.DisInvPer,0) 'DisInvPer',COALESCE( sr.PmtToDate ,0) 'PmtToDate', COALESCE(sr.TotalDis ,0) 'TotalDis' , COALESCE( sr.NetTotalAmt ,0) 'NetTotalAmt', COALESCE(sr.PostStatus,'') 'PostStatus',
COALESCE(sd.ItemID,'') 'ItemID',COALESCE(sd.LocationID,'') 'LocationID',COALESCE(sd.ClassID,'') 'ClassDetailID', COALESCE(sd.UomID,'') 'UomID',COALESCE(sd.SalQty,0) 'SalQty',
COALESCE(sd.UnitPrice,0) 'UP', COALESCE(sd.Factor,0) 'Factor', COALESCE(sd.ReportPrice,'') 'RP', COALESCE(sd.TotalAmt,'') 'TAmt', COALESCE(sd.DisPer,0) 'DisPer', COALESCE(sd.DisDol,0) 'DisDol',
COALESCE(sd.VTaxDol,0) 'VatDol', COALESCE(sd.VTaxPer,0) 'VatPer', COALESCE(sd.STaxDol,0) 'STDol', COALESCE(sd.STaxPer,0) 'STPer', COALESCE(sd.NetTotalAmt,0) 'NetTotalAmtDetail'
,COALESCE(sr.ShipTo,'') 'ShipTo'
FROM tblsaleorder sr
LEFT JOIN tblsaleorderdetails sd on sd.SalID = sr.SalID
Where sr.SalID = saleId
ORDER BY sd.LineNo;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `listSaleOrders`;
DELIMITER |
CREATE PROCEDURE `listSaleOrders`(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
qt.SalID AS saleId,
DATE_FORMAT(qt.SalDate, '%d-%b-%Y') as 'saleDate',
DATE_FORMAT(qt.DueDate, '%d-%b-%Y') as 'dueDate',
qt.SalReference 'reference',
COALESCE(qt.Remark,'') 'remark',
qt.PostStatus,COALESCE(qt.PmtStatus,'') 'pmtStatus',
COALESCE(qt.TotalAmt,'') 'totalAmt',
COALESCE(qt.DisInvDol,'') 'disInvDol',
COALESCE(qt.TotalDis ,'') 'totalDis' ,
COALESCE( qt.NetTotalAmt ,'') 'netTotalAmt',
c.CustID AS custId,
c.CustName AS custName,
c.CustAddress AS custAddress,
e.EmpName AS empName,
e.EmpID AS empId,
cz.ClassID AS classId,
cz.Des AS className,
qt.ApproveStatus approvedStatus
FROM tblsaleorder qt
LEFT OUTER JOIN tblcustomer c
ON c.CustID = qt.CustID
LEFT OUTER JOIN tblemployee e
ON e.EmpID = qt.EmpID
LEFT OUTER JOIN tblclass cz
ON cz.ClassID = qt.ClassID
order by qt.SalDate DESC,qt.SalID DESC;
else
SELECT
qt.SalID AS saleId,
DATE_FORMAT(qt.SalDate, '%d-%b-%Y') as 'saleDate',
DATE_FORMAT(qt.DueDate, '%d-%b-%Y') as 'dueDate',
qt.SalReference 'reference',
COALESCE(qt.Remark,'') 'remark',
qt.PostStatus,COALESCE(qt.PmtStatus,'') 'pmtStatus',
COALESCE(qt.TotalAmt,'') 'totalAmt',
COALESCE(qt.DisInvDol,'') 'disInvDol',
COALESCE(qt.TotalDis ,'') 'totalDis' ,
COALESCE( qt.NetTotalAmt ,'') 'netTotalAmt',
c.CustID AS custId,
c.CustName AS custName,
c.CustAddress AS custAddress,
e.EmpName AS empName,
e.EmpID AS empId,
cz.ClassID AS classId,
cz.Des AS className,
qt.ApproveStatus approvedStatus
FROM tblsaleorder qt
LEFT OUTER JOIN tblcustomer c
ON c.CustID = qt.CustID
LEFT OUTER JOIN tblemployee e
ON e.EmpID = qt.EmpID
LEFT OUTER JOIN tblclass cz
ON cz.ClassID = qt.ClassID
where qt.EmpID = (select EmpID from tbluseremployee where uid = userId)
order by qt.SalDate DESC,qt.SalID DESC;
end if;
END |
DELIMITER ;

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

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

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

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

DROP PROCEDURE IF EXISTS `listTasksRelatedToOpportunity`;
DELIMITER |
CREATE PROCEDURE `listTasksRelatedToOpportunity`(IN `opId` varchar(11))
    DETERMINISTIC
BEGIN
SELECT
task.TA_ID taskId,
task.TA_Subject taskSubject,
CAST(task.TA_StartDate AS DATE) taskStartDate,
CAST(task.TA_DueDate AS DATE) taskDueDate,
task.TA_Priority taskPriority,
tst.TS_ID taskStatusId,
tst.TS_Name taskStatusName,
task.TA_Des taskDes,
con.CO_ID conID,
con.CO_FirstName conFirstname,
con.CO_LastName conLastname,
assignTo.UID userID,
assignTo.UName username,
task.TA_CBy taskCreateBy,
CAST(task.TA_CDate AS DATE) taskCreateDate,
task.TA_MBy taskModifiedBy,
CAST(task.TA_MDate AS DATE) taskModifiedDate
FROM
crm_task task
INNER JOIN
crm_task_status tst
ON task.TA_StatusID = tst.TS_ID
LEFT OUTER JOIN
crm_contact con
ON task.TA_ContactID = con.CO_ID
LEFT OUTER JOIN
tbluser assignTo
ON task.TA_ATo = assignTo.UID
INNER JOIN
crm_opportunity op
ON op.OP_ID = TA_RToID
WHERE op.OP_ID = opId
ORDER BY task.TA_CDate DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `loadCrmDashboardForSpecificUser`;
DELIMITER |
CREATE PROCEDURE `loadCrmDashboardForSpecificUser`(IN `userId` varchar(50))
    DETERMINISTIC
BEGIN
CALL CRM_PRO_MEETING_LIST(userId);
/*----------------End Meeting--------------------*/
CALL CRM_PRO_TASK_LIST(userId);
/*------------End Task---------------------*/
CALL CRM_PRO_CALL_LIST(userId);
/*-------------End Call---------------------*/
CALL CRM_PRO_NOTE_LIST(userId);
/*------------------End Note------------------*/
CALL CRM_PRO_EVENT_LIST(userId);
/*-------------------End Event------------------*/
CALL CRM_PRO_LEAD_LIST(userId);
/*-----------------End Lead---------------------*/
CALL CRM_PRO_CAMP_LIST(userId);
/*---------------End Campaign--------------------*/
CALL CRM_PRO_CASE_LIST(userId);
/*-------------------End Case-------------------*/
CALL CRM_PRO_CUSTOMER_LIST(userId);
/*---------------End Customer---------------------*/
CALL CRM_PRO_CONTACT_LIST(userId);
/*---------------End Contact----------------------*/
CALL CRM_PRO_QUOTE_LIST(userId);
/*--------------End Quotation-----------------------*/
CALL CRM_PRO_SALE_ORDER_LIST(userId);
/*----------------End SaleOrder----------------------*/
CALL CRM_PRO_OPP_LIST(userId);
/*-----------------End Opportunity-------------------*/
SELECT m.ModuleID moduleId,m.Remarks moduleName ,COALESCE(c.`Status`,0) status, COALESCE(c.OrderBy,0) orderBy, SUBSTRING(`Group`,1,6) groupType FROM crm_numberprefix m
LEFT JOIN (SELECT * FROM crm_config_dashboard cd WHERE cd.UID=userId) c on c.ModuleID=m.ModuleID
WHERE m.`Status` = 1 AND m.`Group` <> 'Administrator' AND m.Hide = 0
ORDER BY c.OrderBy DESC, m.`Group`;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_LOAD_CUS`;
DELIMITER |
CREATE PROCEDURE `POS_LOAD_CUS`()
    DETERMINISTIC
BEGIN
SELECT
COALESCE(c.var_id,'') AS 'CustID',
COALESCE(c.var_name,'') AS 'CustName',
COALESCE(c.var_pricecode,'') AS 'PriceCode',
COALESCE(c.var_cur,'') AS 'Cur',
COALESCE(c.var_tel1,'') AS 'Tel1',
COALESCE(c.var_tel2,'') AS 'Tel2'
FROM ame_mt_cus c;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_DIALOG_AR_IN`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_DIALOG_AR_IN`(int_offset int(11),tin_count tinyint(1),var_column varchar(200), var_range varchar(100), dat_df date, dat_dt date, P1 varchar(100))
    DETERMINISTIC
BEGIN
		DECLARE int_index INTEGER DEFAULT -1;
		DECLARE int_page INTEGER DEFAULT 0;
		DECLARE P_BET VARCHAR(250) DEFAULT "";
		DECLARE P_DEC_AMT_FUN INTEGER DEFAULT 2;
		BEGIN DECLARE C1 CURSOR FOR SELECT T.int_amt FROM ame_sys_decimal T WHERE T.var_id = (SELECT T2.var_id FROM ame_mt_cur T2 WHERE T2.tin_default = 1);OPEN C1;IF FOUND_ROWS() > 0 THEN FETCH C1 INTO P_DEC_AMT_FUN; END IF;CLOSE C1;END;
		CASE var_range
		WHEN "RANGE" THEN
				SET P_BET = CONCAT(" AND (DATE(T.dat_date) BETWEEN '", dat_df,"' AND '", dat_dt,"')");
		WHEN "TODAY" THEN
				SET P_BET = CONCAT(" AND DATE(T.dat_date) = DATE('", NOW(), "')");
		WHEN "THIS PERIOD" THEN
				SET P_BET = CONCAT(" AND MONTH(T.dat_date) = MONTH('", NOW(), "')");
		WHEN "THIS YEAR" THEN
				SET P_BET = CONCAT(" AND YEAR(T.dat_date) = YEAR('", NOW(), "')");
		ELSE
				SET P_BET = CONCAT(" AND TRUE");
		END CASE;
		SET @SQL_EXC = "";
		SET @SQL_CON = "";
		CASE UPPER(var_column)
		WHEN "ALL" THEN SET @SQL_CON = CONCAT("(T.var_id LIKE '%", P1,"%' OR T.var_ref LIKE '%", P1,"%' OR T.var_desc LIKE '%", P1,"%') ", P_BET);
		WHEN "REFERENCE" THEN SET @SQL_CON = CONCAT("T.var_ref LIKE '%", P1,"%'", P_BET);
		WHEN "REMARK" THEN SET @SQL_CON = CONCAT("T.var_desc LIKE '%", P1,"%'", P_BET);
		ELSE SET @SQL_CON = CONCAT("T.var_id LIKE '%", P1,"%'", P_BET);
		END CASE;
		CASE int_offset
		WHEN -1 THEN
				SET @R = -1;
				SELECT COALESCE(T.R, 0) FROM (SELECT @R := @R + 1 AS R, T.var_id FROM pos_ar_in T ORDER BY T.var_id) T WHERE T.var_id = P1;
		ELSE
				SET @SQL_SEL = CONCAT("SELECT T.var_id AS 'Entry No', T.var_type AS 'Type', DATE(T.dat_date) AS 'Date', COALESCE(T.var_ref, '') AS 'Reference', T.var_cusid AS 'Customer Id', T1.var_name AS 'Customer Name', T.var_status AS 'Status', T.var_desc AS 'Remark', CAST(T.dou_funnet AS DECIMAL(16, ",P_DEC_AMT_FUN,")) AS 'Total Amount' FROM pos_ar_in T LEFT JOIN ame_mt_cus T1 ON T.var_cusid = T1.var_id");
				CASE tin_count
				WHEN 1 THEN # LOAD FORM
						SET @R = -1;
						SELECT COALESCE(T.R, 0) INTO int_index FROM (SELECT @R := @R + 1 AS R, T.var_id FROM pos_ar_in T ORDER BY T.var_id) T WHERE T.var_id = P1;
						WHILE int_index >= 100 DO
								SET int_page = int_page + 1;
								SET int_index = int_index - 100;
						END WHILE;
						SELECT int_index AS RowIndex, int_page + 1 AS Page;
						SET @SQL_EXC = CONCAT(@SQL_SEL," ORDER BY T.var_id LIMIT 100 OFFSET ",(int_page * 100));
				WHEN 2 THEN # SEARCH
						SELECT 0 AS RowIndex, 1 AS Page;
						SET @SQL_EXC = CONCAT(@SQL_SEL," WHERE (",@SQL_CON,") ORDER BY T.var_id LIMIT 100 OFFSET ", int_offset);
				WHEN 3 THEN # PAGINATION (FIRST, PREVIOUS, NEXT)
						SELECT 0 AS RowIndex, 1 AS Page;
						SET @SQL_EXC = CONCAT(@SQL_SEL," WHERE (",@SQL_CON,") ORDER BY T.var_id LIMIT 100 OFFSET ", IF(int_offset <= 0,0,(int_offset * 100) - 100));
				WHEN 4 THEN  # PAGINATION (LAST)
						BEGIN
								SET @PAGE = 0;
								SET @SQL_EXC = CONCAT("SELECT COUNT(T.var_id) / 100 INTO @PAGE FROM pos_ar_in T"," WHERE (",@SQL_CON,")");
								PREPARE STM FROM @SQL_EXC;
								EXECUTE STM;
								DEALLOCATE PREPARE STM;
								IF @PAGE <= 1 THEN
										SET @PAGE = 1;
								ELSE
										IF CEIL(@PAGE) = @PAGE THEN
												SET @PAGE = TRUNCATE(@PAGE,0);
										ELSE
												SET @PAGE = TRUNCATE(@PAGE + 1,0);
										END IF;	
								END IF;
								SELECT 0 AS RowIndex, @PAGE AS Page;
						END;
						SET @SQL_EXC = CONCAT(@SQL_SEL," WHERE (",@SQL_CON,") LIMIT 100 OFFSET ",IF(@PAGE <= 0,0,TRUNCATE(@PAGE * 100,0) - 100));
				ELSE
						SET @DONOTHING = NULL;
				END CASE;	
				PREPARE STM FROM @SQL_EXC;
				EXECUTE STM;
				DEALLOCATE PREPARE STM;	
		END CASE;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_DIALOG_MT_PMT_MET`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_DIALOG_MT_PMT_MET`(int_offset int(11),tin_count tinyint(1),var_column varchar(200),p1 varchar(200),p2 varchar(200))
    DETERMINISTIC
BEGIN
		DECLARE var_inact VARCHAR(100) DEFAULT '';
		DECLARE var_inact_opterator VARCHAR(100) DEFAULT '';
		DECLARE int_index INTEGER DEFAULT -1;
		DECLARE int_page INTEGER DEFAULT 0;
		SET @SQL_EXC = "";
		SET @SQL_CON = "";
		IF p2 = "TRUE" THEN
				SET var_inact = " T.tin_inactive = 0 ";SET var_inact_opterator = " T.tin_inactive = 0 AND ";
		ELSE
				SET var_inact = " TRUE ";SET var_inact_opterator = " TRUE AND ";
		END IF;
		CASE UPPER(var_column)
		WHEN "ALL" THEN SET @SQL_CON = CONCAT("(T.var_id LIKE '%",p1,"%' OR T.var_name LIKE '%",p1,"%' OR T.var_desc LIKE '%",p1,"%')");
		WHEN "PAYMENT METHOD CODE" THEN SET @SQL_CON = CONCAT("T.var_id LIKE '%",p1,"%'");
		WHEN "PAYMENT METHOD NAME" THEN SET @SQL_CON = CONCAT("T.var_name LIKE '%",p1,"%'");
		WHEN "REMARK" THEN SET @SQL_CON = CONCAT("T.var_desc LIKE '%",p1,"%'");
		ELSE SET @SQL_CON = CONCAT("T.var_id LIKE '%",p1,"%'");
		END CASE;
		CASE int_offset
		WHEN -1 THEN
				SELECT COALESCE(T.R, 0) FROM (SELECT @R := @R + 1 AS R, var_id FROM ame_mt_loc WHERE IF(p2 = 'TRUE', tin_inactive = 0,TRUE)) T LEFT JOIN (SELECT @R := -1 AS R) T1 ON T.R = T1.R WHERE T.var_id  = p1;
		ELSE
				SET @SQL_SEL = "SELECT COALESCE(T.var_id,'') AS 'Payment Method Code',
															 COALESCE(T.var_name,'') AS 'Payment Method Name',
															 COALESCE(T.var_cur,'') AS 'Currency',
															 COALESCE((SELECT T1.var_accid FROM ame_mt_acc_set T1 WHERE T1.var_type = 'POS-PMT-MET' AND T1.var_groupid = T.var_id LIMIT 1),'') AS 'Payment Account ID',
															 COALESCE(T.int_sort,0) AS 'Sort Order',
															 COALESCE(T.var_desc,'') AS 'Remark',
															 COALESCE(T.tin_inactive,0) AS 'Inactive' 
															 FROM pos_pay_met T";
				CASE tin_count
				WHEN 1 THEN # LOAD FORM
						SELECT COALESCE(T.R, 0) INTO int_index FROM (SELECT @R := @R + 1 AS R, var_id FROM pos_pay_met WHERE IF(p2 = 'TRUE', tin_inactive = 0,TRUE)) T LEFT JOIN (SELECT @R := -1 AS R) T1 ON T.R = T1.R WHERE T.var_id  = p1;
						WHILE int_index >= 100 DO
						SET int_page = int_page + 1;
						SET int_index = int_index - 100;
						END WHILE;
						SELECT int_index AS RowIndex, int_page + 1 AS Page;
						SET @SQL_EXC = CONCAT(@SQL_SEL," WHERE ",var_inact," LIMIT 100 OFFSET ",(int_page * 100));
				WHEN 2 THEN # SEARCH
						SELECT 0 AS RowIndex, 1 AS Page;
						SET @SQL_EXC = CONCAT(@SQL_SEL," WHERE ",var_inact_opterator," (",@SQL_CON,") LIMIT 100 OFFSET ",int_offset);
				WHEN 3 THEN # PAGINATION (FIRST, PREVIOUS, NEXT)
						SELECT 0 AS RowIndex, 1 AS Page;
						SET @SQL_EXC = CONCAT(@SQL_SEL," WHERE ",var_inact_opterator," (",@SQL_CON,") LIMIT 100 OFFSET ",IF(int_offset <= 0,0,(int_offset * 100) - 100));
				WHEN 4 THEN  # PAGINATION (LAST)
						BEGIN
								SET @PAGE = 0;
								SET @SQL_EXC = CONCAT("SELECT COUNT(T.var_id) / 100 INTO @PAGE FROM pos_pay_met T"," WHERE ",var_inact_opterator," (",@SQL_CON,")");
								PREPARE STM FROM @SQL_EXC;
								EXECUTE STM;
								DEALLOCATE PREPARE STM;
								IF @PAGE <= 1 THEN
										SET @PAGE = 1;
								ELSE
										IF CEIL(@PAGE) = @PAGE THEN
												SET @PAGE = TRUNCATE(@PAGE,0);
										ELSE
												SET @PAGE = TRUNCATE(@PAGE + 1,0);
										END IF;
								END IF;
								SELECT 0 AS RowIndex, @PAGE AS Page;
						END;
						SET @SQL_EXC = CONCAT(@SQL_SEL," WHERE ",var_inact_opterator," (",@SQL_CON,") LIMIT 100 OFFSET ",IF(@PAGE <= 0,0,TRUNCATE(@PAGE * 100,0) - 100));
				ELSE
						SET @DONOTHING = NULL;
				END CASE;
				PREPARE STM FROM @SQL_EXC;
				EXECUTE STM;
				DEALLOCATE PREPARE STM;
		END CASE;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_GET_USER`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_GET_USER`(IN P1 varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
	COALESCE(u.var_id,'') AS 'UID',
	COALESCE(u.var_name,'') AS 'UName',
	COALESCE(u.var_pwd,'') AS 'PWD',
	COALESCE(up.var_appid,'') AS 'APP',
	COALESCE(u.var_empid,'') AS 'EmpID',
	COALESCE(e.var_name,'') AS 'EmpName'
	FROM ame_user u INNER JOIN ame_user_app up ON u.var_id = up.var_id INNER JOIN ame_mt_emp e ON u.var_empid = e.var_id
	WHERE up.var_appid IN ('POS','POS ADMIN') AND u.var_id = P1;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_LOAD_CUS`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_LOAD_CUS`(IN V_Pa varchar(255),IN SearchType varchar(255))
    DETERMINISTIC
BEGIN
	SET @COND = "";
	SET @sql1 =
	"SELECT
	COALESCE(c.var_id,'') AS `CustID`,
	COALESCE(c.var_name,'') AS `CustName`,
	COALESCE(c.var_pricecode,'') AS `PriceCode`,
	COALESCE(c.var_cur,'') AS `Cur`,
	COALESCE(c.var_tel1,'') AS `Tel1`,
	COALESCE(c.var_tel2,'') AS `Tel2`
	FROM ame_mt_cus c ";
	CASE SearchType
	WHEN 'all' THEN SET @COND = CONCAT(" WHERE c.var_id LIKE '%",V_Pa,"%' OR c.var_name LIKE '%",V_Pa,"%' OR c.var_tel1 LIKE '%",V_Pa,"%' OR c.var_tel2 LIKE '%",V_Pa,"%'");
	WHEN 'custid' THEN SET @COND = CONCAT(" WHERE c.var_id LIKE '%",V_Pa,"%'");
	WHEN 'custname' THEN SET @COND = CONCAT(" WHERE c.var_name LIKE '%",V_Pa,"%'");
	WHEN 'tel' THEN SET @COND = CONCAT(" WHERE c.var_tel1 LIKE '%",V_Pa,"%' OR c.var_tel2 LIKE '%",V_Pa,"%'");
	ELSE SET @COND = "";
	END CASE;
	SET @sql1 = CONCAT(@sql1,@COND," ORDER BY c.var_id");
	PREPARE STM FROM @sql1;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_load_emp`;
DELIMITER |
CREATE PROCEDURE `pos_pro_load_emp`(IN var_Type varchar(255),IN var_Text varchar(255),var_LocationID varchar(255))
    DETERMINISTIC
BEGIN

	IF var_Type = "All" THEN
		SELECT 		
		COALESCE(e.var_id,'') AS EmpID,
		COALESCE(e.var_name,'') AS EmpName,
		COALESCE(e.var_cardid,'') AS EmpICNo,
		COALESCE(e.var_tel1,'') AS Tel1,
		COALESCE(e.var_tel2,'') AS Tel2  
		FROM ame_mt_emp e WHERE (e.var_id LIKE var_Text OR e.var_name LIKE var_Text OR e.var_tel1 LIKE var_Text OR e.var_tel2 LIKE var_Text) AND IF(LOWER(var_LocationID) = 'all',TRUE,TRUE);
	ELSEIF var_Type = "EmpID" THEN
		SELECT 
		COALESCE(e.var_id,'') AS EmpID,
		COALESCE(e.var_name,'') AS EmpName,
		COALESCE(e.var_cardid,'') AS EmpICNo,
		COALESCE(e.var_tel1,'') AS Tel1,
		COALESCE(e.var_tel2,'') AS Tel2  
		FROM ame_mt_emp e WHERE e.var_id LIKE var_Text AND IF(LOWER(var_LocationID) = 'all',TRUE,TRUE);
	ELSEIF var_Type = "EmpName" THEN
		SELECT 
		COALESCE(e.var_id,'') AS EmpID,
		COALESCE(e.var_name,'') AS EmpName,
		COALESCE(e.var_cardid,'') AS EmpICNo,
		COALESCE(e.var_tel1,'') AS Tel1,
		COALESCE(e.var_tel2,'') AS Tel2 
		FROM ame_mt_emp e WHERE e.var_name LIKE var_Text AND IF(LOWER(var_LocationID) = 'all',TRUE,TRUE);
	ELSEIF var_Type = "Tel" THEN
		SELECT 
		COALESCE(e.var_id,'') AS EmpID,
		COALESCE(e.var_name,'') AS EmpName,
		COALESCE(e.var_cardid,'') AS EmpICNo,
		COALESCE(e.var_tel1,'') AS Tel1,
		COALESCE(e.var_tel2,'') AS Tel2 
		FROM ame_mt_emp e WHERE (e.var_tel1 LIKE var_Text OR e.var_tel2 LIKE var_Text) AND IF(LOWER(var_LocationID) = 'all',TRUE,TRUE);
	ELSEIF var_Type = "Leave" THEN
		SELECT 
		COALESCE(e.var_id,'') AS EmpID,
		COALESCE(e.var_name,'') AS EmpName,
		COALESCE(e.var_cardid,'') AS EmpICNo,
		COALESCE(e.var_tel1,'') AS Tel1,
		COALESCE(e.var_tel2,'') AS Tel2 
		FROM ame_mt_emp e WHERE (e.var_cardid = var_Text OR e.var_id = var_Text) AND IF(LOWER(var_LocationID) = 'all',TRUE,TRUE) ORDER BY e.var_id;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_load_inv`;
DELIMITER |
CREATE PROCEDURE `pos_pro_load_inv`(IN FDate varchar(255),TDate varchar(255),IN var_LocationID varchar(255),IN var_MachineID varchar(255),IN var_EmpID varchar(255),var_SalID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT distinct 
	s.var_id AS SalID,
	s.dat_date AS SalDate,
	COALESCE(e.var_name,'') AS EmpName,
  '' AS StationName,
  s.dou_net AS NetTotalAmt,
  var_status AS PostStatus,
	s.var_shiftid AS shiftno
	FROM pos_ar_in s INNER JOIN pos_ar_in_det sd on s.var_id = sd.var_id
	LEFT JOIN ame_mt_emp e ON e.var_id = s.var_empid
  WHERE (DATE(s.dat_date) BETWEEN FDate AND TDate)
	AND s.var_id LIKE var_SalID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_LOAD_ITE`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_LOAD_ITE`(IN var_Type varchar(255),IN var_Value varchar(255),IN var_PriceCode varchar(255),IN var_LocationID varchar(255),IN var_CustID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Cur VARCHAR(255) DEFAULT "";
	DECLARE IMG VARCHAR(255) DEFAULT "";
	DECLARE VAT DOUBLE DEFAULT 0.0;
	DECLARE STAX DOUBLE DEFAULT 0.0;
	SELECT COALESCE(c.var_cur,'') INTO Cur FROM ame_mt_cus c WHERE c.var_id = var_CustID LIMIT 1;
	SELECT COALESCE(t.dou_vat,0),COALESCE(t.dou_stax,0) INTO VAT,STAX FROM pos_tax t;
	SELECT CONCAT(COALESCE(REPLACE(c.var_name,"\\","\\\\"),''),"\\\\MT_ITE\\\\") INTO IMG FROM ame_sys_config c WHERE c.var_id = 'IMG_PATH' LIMIT 1;
	SET @Con = "";
	IF LOWER(var_Type) = 'all' THEN
		SET @Con = CONCAT(" AND (i.var_id LIKE '%",var_Value,"%' OR i.var_name LIKE '%",var_Value,"%' OR i.var_itemcode LIKE '%",var_Value,"%' OR i.var_barcode LIKE '%",var_Value,"%')");
	ELSEIF LOWER(var_Type) = 'itemid' THEN
		SET @Con = CONCAT(" AND i.var_id LIKE '%",var_Value,"%'");
	ELSEIF LOWER(var_Type) = 'itemname' THEN
		SET @Con = CONCAT(" AND i.var_name LIKE '%",var_Value,"%'");
	ELSEIF LOWER(var_Type) = 'qrcode' THEN
		SET @Con = CONCAT(" AND i.var_itemcode LIKE '%",var_Value,"%'");
	ELSEIF LOWER(var_Type) = 'barcode' THEN
		SET @Con = CONCAT(" AND i.var_barcode LIKE '%",var_Value,"%'");
	ELSEIF LOWER(var_Type) = 'scan' THEN
		SET @Con = CONCAT(" AND i.var_itemcode = '",var_Value,"' OR i.var_barcode = '",var_Value,"'");
	END IF;
	SET @SQL = CONCAT("SELECT
		COALESCE(i.var_id,'') AS ItemID,
		COALESCE(i.var_itemcode,'') AS ProductCode,
		COALESCE(i.var_name,'') AS ItemName,
		COALESCE(iu.var_uomid,'') AS UomID,
		COALESCE(i.var_barcode,'') AS BarCode,
		COALESCE(ip.dou_price,0) AS PriceAmount,
		0 AS Discount,
		COALESCE((SELECT SUM(b.dou_qty) FROM ame_sl_ic_batch b WHERE b.var_locid = '",var_LocationID,"' AND b.var_itemid = i.var_id),0) AS CurrentStock,
		IF(COALESCE(i.tin_vat,0) = 1,",VAT,",0) AS VAT,
		0 AS STax,
		CONCAT('",IMG,"',COALESCE(i.var_img,'')) AS ImagePath,
		0 AS ServiceCharge
		FROM ame_mt_ite i LEFT JOIN ame_mt_ite_uom iu ON i.var_id = iu.var_id 
		LEFT JOIN ame_mt_ite_pri ip ON iu.var_id = ip.var_id AND iu.var_uomid = ip.var_uomid AND ip.var_pricecode = '",var_PriceCode,"' AND ip.var_cur = '",Cur,"'
		WHERE i.tin_inactive = 0 AND i.tin_no_sal = 0 ",@Con,"
		ORDER BY i.var_id,iu.var_uomid");
	#SELECT @SQL;
	PREPARE St FROM @SQL;
	EXECUTE St;
	DEALLOCATE PREPARE St;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_Load_ItemSoldByShift`;
DELIMITER |
CREATE PROCEDURE `pos_pro_Load_ItemSoldByShift`(IN `int_ShiftNo` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT
	sd.var_itemid AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	sd.var_uomid AS UOMID,
	SUM(COALESCE(sd.dou_qty,0)) AS Qty,
	SUM(COALESCE(sd.dou_sub,0)) AS TotalAmt,
	SUM(COALESCE(sd.dou_disdol,0)) AS DisDol,
	SUM(COALESCE(sd.dou_taxdol,0)) AS TaxDol,
	SUM(COALESCE(0,0)) AS ServiceChargeDol,
	SUM(COALESCE(sd.dou_net,0)) AS NetTotalAmt
	FROM pos_ar_in_det sd
	INNER JOIN pos_ar_in s ON s.var_id = sd.var_id AND s.var_shiftid = int_ShiftNo AND s.var_status IN ('Open','Posted')
	LEFT JOIN ame_mt_ite i ON i.var_id = sd.var_itemid
	GROUP BY sd.var_itemid,sd.var_uomid ORDER BY sd.var_itemid,sd.var_uomid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_load_item_nodisc`;
DELIMITER |
CREATE PROCEDURE `pos_pro_load_item_nodisc`()
    DETERMINISTIC
BEGIN
	SELECT COALESCE(i.var_id,'') AS ItemID FROM ame_mt_ite i WHERE COALESCE(i.tin_no_disc,0) = 1;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_LOAD_LOC`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_LOAD_LOC`(IN var_Type varchar(255),IN var_Value varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Con VARCHAR(255) DEFAULT "";
	IF LOWER(var_Type) = 'all' THEN
		SET Con = CONCAT(" AND (L.var_id LIKE \'%",var_Value,"%\' OR L.var_name LIKE \'%",var_Value,"%\' OR L.var_addr LIKE \'%",var_Value,"%\' OR L.var_desc LIKE \'%",var_Value,"%\')");
	ELSEIF LOWER(var_Type) = 'location id' THEN
		SET Con = CONCAT(" AND L.var_id LIKE \'%",var_Value,"%\'");
	ELSEIF LOWER(var_Type) = 'location name' THEN
		SET Con = CONCAT(" AND L.var_name LIKE \'%",var_Value,"%\'");
	ELSEIF LOWER(var_Type) = 'address' THEN
		SET Con = CONCAT(" AND L.var_addr LIKE \'%",var_Value,"%\'");
	ELSEIF LOWER(var_Type) = 'remark' THEN
		SET Con = CONCAT(" AND L.var_desc LIKE \'%",var_Value,"%\'");
	END IF;
	SET @SQL = CONCAT("
	SELECT 
	COALESCE(L.var_id,'') AS 'LocID',
	COALESCE(L.var_name,'') AS 'LocName',
	COALESCE(L.var_addr,'') AS 'Address',
	COALESCE(L.var_desc,'') AS 'DESC'
	FROM ame_mt_loc L WHERE COALESCE(L.tin_inactive,0) = 0 AND COALESCE(L.tin_posloc,0) = 1 ",Con," ORDER BY L.var_id");
	PREPARE St FROM @SQL;
	EXECUTE St;
	DEALLOCATE PREPARE St;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_Load_SaleDetails_ForVoid`;
DELIMITER |
CREATE PROCEDURE `pos_pro_Load_SaleDetails_ForVoid`(IN `var_SalID` varchar(255))
    DETERMINISTIC
BEGIN
SELECT
COALESCE(s.var_id,'') AS SalID,
COALESCE(sd.int_line,0) AS LineNo,
COALESCE(i.var_name,'') AS ItemName,
COALESCE(sd.dou_qty,0) AS SalQty,
COALESCE(sd.var_uomid,'') AS UOMID,
COALESCE(sd.dou_net,0) AS NetTotalAmt
FROM pos_ar_in s
INNER JOIN pos_ar_in_det sd ON s.var_id = sd.var_id
INNER JOIN ame_mt_ite i ON sd.var_itemid = i.var_id
WHERE s.var_id = var_SalID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_Load_SaleInShift`;
DELIMITER |
CREATE PROCEDURE `pos_pro_Load_SaleInShift`(IN `int_ShiftNo` varchar(255))
    DETERMINISTIC
BEGIN
SELECT
COALESCE(s.var_id,'') AS SalID,
s.dat_date AS SalDate,
COALESCE(s.var_type,'') SalType,
COALESCE((SELECT e.var_name FROM ame_mt_emp e WHERE e.var_id = s.var_empid LIMIT 1),'') AS EmpName,
COALESCE((SELECT c.var_id FROM ame_mt_cus c WHERE c.var_id = s.var_cusid),'') AS CustName,
COALESCE(s.dou_net,0) AS NetTotalAmt
FROM pos_ar_in s
WHERE s.var_shiftid = int_ShiftNo AND s.var_status IN ('Open','Posted');
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_Load_Sale_ForVoid`;
DELIMITER |
CREATE PROCEDURE `pos_pro_Load_Sale_ForVoid`(IN `var_MachineID` varchar(255),IN `var_EmpID` varchar(255),IN `int_ShiftNo` varchar(255),IN `FDate` varchar(255),IN `TDate` varchar(255),IN `var_SalID` varchar(255))
    DETERMINISTIC
BEGIN
SELECT
COALESCE(s.var_id,'') AS SalID,
s.dat_date AS SalDate,
COALESCE(s.var_type,'') AS SalType,
COALESCE((SELECT e.var_name FROM ame_mt_emp e WHERE e.var_id = s.var_empid LIMIT 1),'') AS EmpName,
COALESCE((SELECT c.var_name FROM ame_mt_cus c WHERE c.var_id = s.var_cusid),'') AS CustName,
COALESCE(s.dou_net,0) AS NetTotalAmt
FROM pos_ar_in s
WHERE (DATE(s.dat_date) BETWEEN DATE(FDate) AND DATE(TDate)) 
AND s.var_id LIKE var_SalID
AND s.var_status = 'Open' ;
/*
AND MachineID = var_MachineID 
AND EmpID = var_EmpID 
AND s.ShiftNo = int_ShiftNo;
*/
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_load_shift`;
DELIMITER |
CREATE PROCEDURE `pos_pro_load_shift`(IN P1 varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
	COALESCE(sh.var_id,'') AS ShiftID,
	COALESCE(sh.var_macid,'') AS MacID,
	COALESCE(sh.var_locid,'') AS var_locid,
	COALESCE(sh.var_status,'') AS `Status`,
	COALESCE(sh.var_uid_in,'') AS UID_IN,
	COALESCE((SELECT e.var_name FROM ame_mt_emp e WHERE e.var_id = sh.var_uid_in LIMIT 1),'') AS UName_IN,
	sh.dat_in,
	COALESCE(sh.dou_in_usd,0) AS dou_in_usd,
	COALESCE(sh.dou_in_khr,0) AS dou_in_khr,
	COALESCE(sh.dou_in_total,0) AS dou_in_total,
	COALESCE(sh.var_uid_out,'') AS var_uid_out,
	COALESCE((SELECT e.var_name FROM ame_mt_emp e WHERE e.var_id = sh.var_uid_out LIMIT 1),'') AS UName_OUT,
	sh.dat_out,
	COALESCE(sh.dou_exrate,0) AS dou_exrate,
	COALESCE(sh.dou_d1,0) AS dou_d1,
	COALESCE(sh.dou_d2,0) AS dou_d2,
	COALESCE(sh.dou_d5,0) AS dou_d5,
	COALESCE(sh.dou_d10,0) AS dou_d10,
	COALESCE(sh.dou_d20,0) AS dou_d20,
	COALESCE(sh.dou_d50,0) AS dou_d50,
	COALESCE(sh.dou_d100,0) AS dou_d100,
	COALESCE(sh.dou_d_total,0) AS dou_d_total,
	COALESCE(sh.dou_r100,0) AS dou_r100,
	COALESCE(sh.dou_r200,0) AS dou_r200,
	COALESCE(sh.dou_r500,0) AS dou_r500,
	COALESCE(sh.dou_r1000,0) AS dou_r1000,
	COALESCE(sh.dou_r2000,0) AS dou_r2000,
	COALESCE(sh.dou_r5000,0) AS dou_r5000,
	COALESCE(sh.dou_r10000,0) AS dou_r10000,
	COALESCE(sh.dou_r20000,0) AS dou_r20000,
	COALESCE(sh.dou_r50000,0) AS dou_r50000,
	COALESCE(sh.dou_r100000,0) AS dou_r100000,
	COALESCE(sh.dou_r_total,0) AS dou_r_total,
	COALESCE(sh.dou_out_total,0) AS dou_out_total,
	COALESCE(SUM(s.dou_sub),0) AS INV_GROSS_SALE,
	COALESCE(SUM(s.dou_disdol),0) AS INV_DISDOL,
	COALESCE(SUM(s.dou_taxdol),0) AS INV_VAT,
	COALESCE(SUM(s.dou_net),0) AS INV_NET,
	(SELECT COUNT(s.var_id) FROM pos_ar_in s WHERE s.var_shiftid = sh.var_id AND s.var_status IN ('Open','Posted')) AS Count_Inv,
	(SELECT COUNT(s.var_id) FROM pos_ar_in s WHERE s.var_shiftid = sh.var_id AND s.var_status NOT IN ('Open','Posted')) AS Count_Void,
	COALESCE(sh.dou_in_total,0) + SUM(s.dou_net) AS GRAND_IN,
	COALESCE(sh.dou_out_total,0) AS GRAND_OUT,
	COALESCE(sh.dou_out_total,0) -(COALESCE(sh.dou_in_total,0) + SUM(s.dou_net)) AS dou_dif
	FROM pos_shift sh LEFT JOIN pos_ar_in s ON sh.var_id = s.var_shiftid AND s.var_status IN ('Open','Posted') WHERE sh.var_id = P1
	GROUP BY sh.var_id;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_Load_ShiftHist`;
DELIMITER |
CREATE PROCEDURE `pos_pro_Load_ShiftHist`(IN `int_ShiftNo` varchar(255))
    DETERMINISTIC
BEGIN
	SELECT
	'ADD' AS EditType,s.dat_date AS edtdate,COALESCE(s.dou_addusd,0) AS USD,COALESCE(s.dou_addkhr,0) AS KHR,COALESCE(s.var_desc,'') AS Description
	FROM pos_shift_his s WHERE s.var_shiftid = int_ShiftNo AND (s.dou_addusd > 0 OR s.dou_addkhr > 0)
	UNION ALL
	SELECT
	'TAKE' AS EditType,s.dat_date AS edtdate,COALESCE(s.dou_takeusd,0) TakeUSD,COALESCE(s.dou_takekhr,0) TakeKHR,COALESCE(s.var_desc,'') AS Description
	FROM pos_shift_his s WHERE s.var_shiftid = int_ShiftNo AND (s.dou_takeusd > 0 OR s.dou_takekhr > 0);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_load_shift_pay_met`;
DELIMITER |
CREATE PROCEDURE `pos_pro_load_shift_pay_met`(IN LocID varchar(255),IN LANG_ID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
	COALESCE(t.var_id,'') AS `ID`,
	COALESCE(t.var_name,'') AS `Name`,
	COALESCE(t.var_cur,'') AS `Currency`,
	COALESCE(t.int_sort,0) AS `Sort`,
	COALESCE(c.var_symbol,'') AS `Cur_Symbol`,
	COALESCE(c.var_name,'') AS `CurName`,
	COALESCE(r.dou_rate,0) AS `Rate`
	FROM pos_pay_met t  
	INNER JOIN ame_mt_cur c ON t.var_cur = c.var_id
	LEFT JOIN ame_mt_cur_rate r ON c.var_id = r.var_id
	WHERE COALESCE(t.tin_inactive,0) = 0
	ORDER BY t.int_sort,t.var_id;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_POST_AR_IN_1`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_POST_AR_IN_1`(P1 varchar(100), P2 varchar(100), P3 int(11), P4 int(11), P5 int(11), P6 int(11))
    DETERMINISTIC
BEGIN
		DECLARE P_COUNT_PAID INTEGER DEFAULT 0;
		DECLARE P_JID INTEGER DEFAULT 0;
		DECLARE P_LINE_JE INTEGER DEFAULT 0;
		DECLARE P_NUM_IC INTEGER DEFAULT 0;
		DECLARE P_TYPE VARCHAR(100) DEFAULT "";
		DECLARE P_CUS VARCHAR(100) DEFAULT "";
		DECLARE P_EMP VARCHAR(100) DEFAULT "";
		DECLARE P_CLA VARCHAR(100) DEFAULT "";
		DECLARE P_REF VARCHAR(100) DEFAULT "";
		DECLARE P_DESC VARCHAR(2000) DEFAULT "";
		DECLARE P_ACC_NUM VARCHAR(100) DEFAULT "";
		DECLARE P_ACC_AR VARCHAR(100) DEFAULT "";
		DECLARE P_PRICE_CODE VARCHAR(100) DEFAULT "";
		DECLARE P_LOC_M VARCHAR(100) DEFAULT "";
		DECLARE P_BAL DOUBLE DEFAULT 0.0;
		DECLARE P_DISC DOUBLE DEFAULT 0.0;
		DECLARE P_VAT DOUBLE DEFAULT 0.0;
		DECLARE P_WHT DOUBLE DEFAULT 0.0;
		DECLARE P_SVC DOUBLE DEFAULT 0.0;
		DECLARE P_CHA DOUBLE DEFAULT 0.0;
		DECLARE P_DATE DATETIME;

		DECLARE P_CUR VARCHAR(100) DEFAULT "";
		DECLARE P_RATE DOUBLE DEFAULT 1.0;
		DECLARE P_FUN_BAL DOUBLE DEFAULT 0.0;
		DECLARE P_FUN_VAT DOUBLE DEFAULT 0.0;
		DECLARE P_FUN_WHT DOUBLE DEFAULT 0.0;
		DECLARE P_FUN_SVC DOUBLE DEFAULT 0.0;
		DECLARE P_FUN_DISC DOUBLE DEFAULT 0.0;

		DECLARE P_DEC_QTY INTEGER DEFAULT 0;
		DECLARE P_DEC_COST_FOR INTEGER DEFAULT 6;
		DECLARE P_DEC_PRICE_FOR INTEGER DEFAULT 6;
		DECLARE P_DEC_AMT_FOR INTEGER DEFAULT 2;
		DECLARE P_DEC_COST_FUN INTEGER DEFAULT 6;
		DECLARE P_DEC_PRICE_FUN INTEGER DEFAULT 6;
		DECLARE P_DEC_AMT_FUN INTEGER DEFAULT 2;
		
		# DECIMAL FUNCTIONAL CURRENCY
		BEGIN DECLARE C1 CURSOR FOR SELECT T.int_qty, T.int_cost, T.int_price, T.int_amt FROM ame_sys_decimal T WHERE T.var_id = (SELECT T2.var_id FROM ame_mt_cur T2 WHERE T2.tin_default = 1);OPEN C1;IF FOUND_ROWS() > 0 THEN FETCH C1 INTO P_DEC_QTY, P_DEC_COST_FUN, P_DEC_PRICE_FUN, P_DEC_AMT_FUN; END IF;CLOSE C1;END;
		
		IF P6 = -1 THEN SET P_JID = AME_FUN_NEW_JE_NUM(); ELSE SET P_JID = P6; END IF;
		IF P5 = -1 THEN SET P_NUM_IC = AME_FUN_NEW_SL_IC_HIS_NUM(); ELSE SET P_NUM_IC = P5; END IF;
		BEGIN
				SELECT T1.dat_date,T1.var_type, T1.var_ref, T1.var_cusid, T1.var_empid, T1.var_desc, T1.var_pricecode, T1.dou_disdol, T1.dou_taxdol, T1.dou_taxdol1,T1.dou_svcdol, T1.dou_net, T1.var_cur, T1.dou_rate, T1.dou_funnet, T1.dou_fundisdol, T1.dou_funtaxdol, T1.dou_funtaxdol1, T1.dou_funsvcdol, T1.var_locid, T1.dou_change
				INTO   P_DATE     ,P_TYPE     , P_REF     , P_CUS       , P_EMP       , P_DESC     , P_PRICE_CODE    , P_DISC       , P_VAT        , P_WHT         ,P_SVC        , P_BAL     , P_CUR     , P_RATE     , P_FUN_BAL    , P_FUN_DISC      , P_FUN_VAT       , P_FUN_WHT        , P_FUN_SVC       , P_LOC_M     , P_CHA FROM pos_ar_in T1 WHERE T1.var_id = P1;
				# DECIMAL FOREIGN CURRENCY
				BEGIN DECLARE C1 CURSOR FOR SELECT T1.int_amt FROM ame_sys_decimal T1 WHERE T1.var_id = P_CUR; OPEN C1; IF FOUND_ROWS() > 0 THEN FETCH C1 INTO P_DEC_AMT_FOR; END IF;CLOSE C1;END;
				# Payment
				IF P_BAL <> 0 THEN
					BEGIN
						DECLARE P_SETID VARCHAR(255) DEFAULT "";
						DECLARE P_SETNAME VARCHAR(255) DEFAULT "";
						DECLARE P_PMT DOUBLE DEFAULT 0.0;
						DECLARE P_FUN_PMT DOUBLE DEFAULT 0.0;
						DECLARE TEMP_NET DOUBLE DEFAULT 0.0;
						DECLARE D2 INTEGER DEFAULT 0;
						DEClARE C2 CURSOR FOR SELECT T1.var_setid,T2.var_name,T1.dou_total,T1.dou_funtotal FROM pos_ar_in_pay_met T1 LEFT JOIN pos_pay_met T2 ON T1.var_setid = T2.var_id WHERE T1.var_salid = P1 ORDER BY T1.var_setid;
						DECLARE CONTINUE HANDLER FOR NOT FOUND SET D2 = 1;
						SET TEMP_NET = P_BAL;
						OPEN C2;
							L2: LOOP FETCH C2 INTO P_SETID,P_SETNAME,P_PMT,P_FUN_PMT;
								IF D2 = 1 OR TEMP_NET = 0 THEN LEAVE L2; END IF;
								IF TEMP_NET >= P_PMT THEN
									SET TEMP_NET = TEMP_NET - P_PMT;
								ELSE
									SET P_PMT = TEMP_NET;
									SET P_FUN_PMT = AME_FUN_ROUND(P_PMT * P_RATE,P_DEC_AMT_FUN);
									SET TEMP_NET = 0;
								END IF;
								SET P_ACC_NUM = AME_FUN_ACC("POS-PMT-MET", P_SETID, "DEFAULT");
								SET P_LINE_JE = P_LINE_JE + 1;
								CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, "", IF(COALESCE(P_DESC, "") = "", P_SETNAME, CONCAT("[",P_SETNAME,"] ", P_DESC)), "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, P_PMT, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "POS-PMT-MET", P_CUR, P_RATE, P_FUN_PMT);
							END LOOP L2;
						CLOSE C2;
					END;
				END IF;
				# DISCOUNT
				IF P_DISC <> 0 THEN
						SET P_ACC_NUM = AME_FUN_ACC("DISC-AR-IN", "DEFAULT", "DEFAULT");
						SET P_LINE_JE = P_LINE_JE + 1;
						CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, "", "Discount", "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, P_DISC, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "DISC", P_CUR, P_RATE, P_FUN_DISC);
				END IF;
				# VAT
				IF P_VAT <> 0 THEN
						SET P_ACC_NUM = AME_FUN_ACC("TAX-VAT-OUT", "DEFAULT", "DEFAULT");
						SET P_LINE_JE = P_LINE_JE + 1;
						CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, "", "VAT", "Cr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, -P_VAT, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "VAT", P_CUR, P_RATE, -P_FUN_VAT);
				END IF;
				# SCT
				IF P_WHT <> 0 THEN
						SET P_ACC_NUM = AME_FUN_ACC("TAX-SCT", "DEFAULT", "DEFAULT");
						SET P_LINE_JE = P_LINE_JE + 1;
						CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, "", "SCT", "Cr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, -P_WHT, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "SCT", P_CUR, P_RATE, -P_FUN_WHT);
				END IF;	
				# Service Charge
				IF P_SVC <> 0 THEN
						SET P_ACC_NUM = AME_FUN_ACC("POS-SVC", "DEFAULT", "DEFAULT");
						SET P_LINE_JE = P_LINE_JE + 1;
						CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, "", "SVC", "Cr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, -P_WHT, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "SCT", P_CUR, P_RATE, -P_FUN_SVC);
				END IF;	
		END;
		BEGIN
				DECLARE D2 INTEGER DEFAULT 0;
				DECLARE P_COUNT_PAID INTEGER DEFAULT 0;
				DECLARE P_BAT_NUM INTEGER DEFAULT 0;
				DECLARE P_LINE INTEGER DEFAULT 0;
				DECLARE P_LINE_FRM INTEGER DEFAULT 0;
				DECLARE P_ACC_IC VARCHAR(100) DEFAULT "";
				DECLARE P_ACC_COGS VARCHAR(100) DEFAULT "";
				DECLARE P_ACC_DISC VARCHAR(100) DEFAULT "";
				DECLARE P_DESC_DET VARCHAR(2000) DEFAULT "";
				DECLARE P_LOC VARCHAR(2000) DEFAULT "";
				DECLARE P_ITEM VARCHAR(100) DEFAULT "";
				DECLARE P_UOM VARCHAR(100) DEFAULT "";
				DECLARE P_QTY DOUBLE DEFAULT 0.0;
				DECLARE P_PRICE DOUBLE DEFAULT 0.0;
				DECLARE P_REVENUE DOUBLE DEFAULT 0.0;
				DECLARE P_FOC DOUBLE DEFAULT 0.0;
				DEClARE C2 CURSOR FOR SELECT T1.int_line, T1.var_itemid, T1.var_uomid, IF(COALESCE(T1.var_desc, '') = '', T1.var_itemid, CONCAT('[', T1.var_itemid,'] ', T1.var_desc)), AME_FUN_ROUND(dou_qty + dou_foc, P_DEC_QTY), T1.dou_price, T1.dou_foc FROM pos_ar_in_det AS T1 WHERE T1.var_id = P1 ORDER BY T1.int_line;
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET D2 = 1;
				SET @T_FOC = 0;
				OPEN C2;
						L2: LOOP FETCH C2 INTO P_LINE_FRM, P_ITEM, P_UOM, P_DESC_DET, P_QTY, P_PRICE, P_FOC;
								IF D2 = 1 THEN LEAVE L2; END IF;
								# REVENUE
								SET P_REVENUE = AME_FUN_ROUND(P_QTY * P_PRICE, P_DEC_AMT_FOR);
								IF P_REVENUE <> 0 THEN
										SET P_ACC_NUM = AME_FUN_ACC("REVENUE", P_ITEM, "NA");
										SET P_LINE_JE = P_LINE_JE + 1;
										IF P_REVENUE >= 0 THEN
												CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, "", "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, P_ITEM, IF(COALESCE(P_DESC_DET, "") = "", "Revenue", CONCAT("[Revenue] ", P_DESC_DET)), "Cr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, -P_REVENUE, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "REVENUE", P_CUR, P_RATE, -AME_FUN_ROUND(P_REVENUE * P_RATE, P_DEC_AMT_FUN));
										ELSE
												CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, "", "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, P_ITEM, IF(COALESCE(P_DESC_DET, "") = "", "Revenue", CONCAT("[Revenue] ", P_DESC_DET)), "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, -P_REVENUE, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "REVENUE", P_CUR, P_RATE, -AME_FUN_ROUND(P_REVENUE * P_RATE, P_DEC_AMT_FUN));
										END IF;	
								END IF;
								SET @CON = AME_FUN_ITEM_CON(P_ITEM, P_UOM);
								SET @T_FOC = AME_FUN_ROUND(@T_FOC + AME_FUN_ROUND(P_FOC * P_PRICE, P_DEC_AMT_FOR), P_DEC_AMT_FOR);
								SET P_LOC = P_LOC_M;
								CASE AME_FUN_ITEM_TYPE(P_ITEM)
								WHEN "Inventory Part" THEN
										BEGIN
												DECLARE D3 INTEGER DEFAULT 0.0;
												DECLARE P_QTY_BAL DOUBLE DEFAULT 0.0;
												DECLARE P_QTY_SOLD DOUBLE DEFAULT 0.0;
												DECLARE P_QTY_BATCH DOUBLE DEFAULT 0.0;
												DECLARE P_COST DOUBLE DEFAULT 0.0;
												DECLARE P_AC1 DOUBLE DEFAULT 0.0;
												DECLARE P_AC2 DOUBLE DEFAULT 0.0;
												DECLARE P_AC3 DOUBLE DEFAULT 0.0;
												DECLARE P_AC4 DOUBLE DEFAULT 0.0;
												DECLARE P_AC5 DOUBLE DEFAULT 0.0;
												DECLARE P_TCOST DOUBLE DEFAULT 0.0;
												DECLARE P_TAC1 DOUBLE DEFAULT 0.0;
												DECLARE P_TAC2 DOUBLE DEFAULT 0.0;
												DECLARE P_TAC3 DOUBLE DEFAULT 0.0;
												DECLARE P_TAC4 DOUBLE DEFAULT 0.0;
												DECLARE P_TAC5 DOUBLE DEFAULT 0.0;
												DEClARE C3 CURSOR FOR SELECT T.int_batchno, T.dou_qty, 
												AME_FUN_ROUND(T.dou_druc - T.dou_cruc, P_DEC_COST_FUN), AME_FUN_ROUND(T.dou_drac1 - T.dou_crac1, P_DEC_COST_FUN), AME_FUN_ROUND(T.dou_drac2 - T.dou_crac2, P_DEC_COST_FUN), AME_FUN_ROUND(T.dou_drac3 - T.dou_crac3, P_DEC_COST_FUN), AME_FUN_ROUND(T.dou_drac4 - T.dou_crac4, P_DEC_COST_FUN), AME_FUN_ROUND(T.dou_drac5 - T.dou_crac5, P_DEC_COST_FUN)
												FROM ame_sl_ic_batch AS T WHERE T.var_itemid = P_ITEM AND T.var_locid = P_LOC AND T.dou_qty > 0 ORDER BY T.`int_batchno`;
												DECLARE CONTINUE HANDLER FOR NOT FOUND SET D3 = 1;
												SET P_QTY_BATCH = AME_FUN_ROUND(P_QTY * @CON, P_DEC_QTY);
												OPEN C3;
														L3:LOOP FETCH C3 INTO P_BAT_NUM, P_QTY_BAL, P_COST, P_AC1, P_AC2, P_AC3, P_AC4, P_AC5;
																IF D3 = 1 THEN LEAVE L3; END IF;
																IF P_QTY_BATCH >= P_QTY_BAL Then
																		SET P_QTY_SOLD = P_QTY_BAL;
																		SET P_QTY_BATCH = AME_FUN_ROUND(P_QTY_BATCH - P_QTY_BAL, P_DEC_QTY);
																ELSE
																		SET P_QTY_SOLD = P_QTY_BATCH;
																		SET P_QTY_BATCH = 0;
																END IF;
																# COSTING
																SET @UC = AME_FUN_ROUND(P_QTY_SOLD * (P_COST / P_QTY_BAL), P_DEC_COST_FUN);
																SET @AC1 = AME_FUN_ROUND(P_QTY_SOLD * (P_AC1 / P_QTY_BAL), P_DEC_COST_FUN);
																SET @AC2 = AME_FUN_ROUND(P_QTY_SOLD * (P_AC2 / P_QTY_BAL), P_DEC_COST_FUN);
																SET @AC3 = AME_FUN_ROUND(P_QTY_SOLD * (P_AC3 / P_QTY_BAL), P_DEC_COST_FUN);
																SET @AC4 = AME_FUN_ROUND(P_QTY_SOLD * (P_AC4 / P_QTY_BAL), P_DEC_COST_FUN);
																SET @AC5 = AME_FUN_ROUND(P_QTY_SOLD * (P_AC5 / P_QTY_BAL), P_DEC_COST_FUN);
																
																SET P_TCOST = AME_FUN_ROUND(P_TCOST + @UC, P_DEC_COST_FUN);
																SET P_TAC1 = AME_FUN_ROUND(P_TAC1 + @AC1, P_DEC_COST_FUN);
																SET P_TAC2 = AME_FUN_ROUND(P_TAC2 + @AC2, P_DEC_COST_FUN);
																SET P_TAC3 = AME_FUN_ROUND(P_TAC3 + @AC3, P_DEC_COST_FUN);
																SET P_TAC4 = AME_FUN_ROUND(P_TAC4 + @AC4, P_DEC_COST_FUN);
																SET P_TAC5 = AME_FUN_ROUND(P_TAC5 + @AC5, P_DEC_COST_FUN);

																SET P_LINE = P_LINE + 1;
																CALL AME_PRO_UPDATE_SL_IC_BAT(P_LOC, P_ITEM, P_BAT_NUM, P_QTY_SOLD, @UC, @AC1, @AC2, @AC3, @AC4, @AC5, "Cr", P_DEC_QTY, P_DEC_COST_FUN);
																CALL AME_PRO_UPDATE_SL_IC(P_LOC, P_ITEM, P_BAT_NUM, P_DATE, P_QTY_SOLD, @UC, @AC1, @AC2, @AC3, @AC4, @AC5, "Cr", P_DEC_QTY, P_DEC_COST_FUN);
																CALL AME_PRO_UPDATE_SL_IC_HIS(P_LOC, P_ITEM, P_BAT_NUM, P_DATE, -P_QTY_SOLD, -@UC, -@AC1, -@AC2, -@AC3, -@AC4, -@AC5, P_NUM_IC, P_LINE, "POS-AR-IN", P_TYPE, P1, AME_FUN_VEN_BATCH(P_BAT_NUM, P_LOC, P_ITEM), P_CUS, P_EMP, P_CLA, P_REF, P_DESC, P_DESC_DET, P_CUR, P_RATE, -AME_FUN_ROUND(P_FOC * @CON, P_DEC_QTY), P_JID);
																IF P_QTY_BATCH = 0 THEN LEAVE L3; END IF;
														END LOOP L3;
												CLOSE C3;
												SET @TC_FOR = 0;
												SET P_TCOST = AME_FUN_ROUND(P_TCOST, P_DEC_AMT_FUN);
												SET P_TAC1 = AME_FUN_ROUND(P_TAC1, P_DEC_AMT_FUN);
												SET P_TAC2 = AME_FUN_ROUND(P_TAC2, P_DEC_AMT_FUN);
												SET P_TAC3 = AME_FUN_ROUND(P_TAC3, P_DEC_AMT_FUN);
												SET P_TAC4 = AME_FUN_ROUND(P_TAC4, P_DEC_AMT_FUN);
												SET P_TAC5 = AME_FUN_ROUND(P_TAC5, P_DEC_AMT_FUN);
												# COGS
												IF P_TCOST <> 0 THEN
														SET @UC_FOR = AME_FUN_ROUND(P_TCOST / P_RATE, P_DEC_AMT_FOR);
														SET @TC_FOR = AME_FUN_ROUND(@TC_FOR + @UC_FOR, P_DEC_AMT_FOR);
														SET P_ACC_NUM = AME_FUN_ACC("COGS", P_ITEM, "NA");
														SET P_LINE_JE = P_LINE_JE + 1;
														CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, P_ITEM, CONCAT("[COGS] ", P_ITEM), "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, @UC_FOR, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "COGS", P_CUR, P_RATE, P_TCOST);
												END IF;
												# COGS AC1
												IF P_TAC1 <> 0 THEN
														SET @UC_FOR = AME_FUN_ROUND(P_TAC1 / P_RATE, P_DEC_AMT_FOR);
														SET @TC_FOR = AME_FUN_ROUND(@TC_FOR + @UC_FOR, P_DEC_AMT_FOR);
														SET P_ACC_NUM = AME_FUN_ACC("COGS-AC1", P_ITEM, "AC1");
														SET P_LINE_JE = P_LINE_JE + 1;
														CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, P_ITEM, CONCAT("[", AME_FUN_ADDI_COST("AC1"), "] ", P_ITEM), "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, @UC_FOR, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "AC1", P_CUR, P_RATE, P_TAC1);
												END IF;
												# COGS AC2
												IF P_TAC2 <> 0 THEN
														SET @UC_FOR = AME_FUN_ROUND(P_TAC2 * P_RATE, P_DEC_AMT_FOR);
														SET @TC_FOR = AME_FUN_ROUND(@TC_FOR + @UC_FOR, P_DEC_AMT_FOR);
														SET P_ACC_NUM = AME_FUN_ACC("COGS-AC2", P_ITEM, "AC2");
														SET P_LINE_JE = P_LINE_JE + 1;
														CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, P_ITEM, CONCAT("[", AME_FUN_ADDI_COST("AC2"), "] ", P_ITEM), "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, @UC_FOR, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "AC2", P_CUR, P_RATE, P_TAC2);
												END IF;
												# COGS AC3
												IF P_TAC3 <> 0 THEN
														SET @UC_FOR = AME_FUN_ROUND(P_TAC3 * P_RATE, P_DEC_AMT_FOR);
														SET @TC_FOR = AME_FUN_ROUND(@TC_FOR + @UC_FOR, P_DEC_AMT_FOR);
														SET P_ACC_NUM = AME_FUN_ACC("COGS-AC3", P_ITEM, "AC3");
														SET P_LINE_JE = P_LINE_JE + 1;
														CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, P_ITEM, CONCAT("[", AME_FUN_ADDI_COST("AC3"), "] ", P_ITEM), "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, @UC_FOR, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "AC3", P_CUR, P_RATE, P_TAC3);
												END IF;
												# COGS AC4
												IF P_TAC4 <> 0 THEN
														SET @UC_FOR = AME_FUN_ROUND(P_TAC4 * P_RATE, P_DEC_AMT_FOR);
														SET @TC_FOR = AME_FUN_ROUND(@TC_FOR + @UC_FOR, P_DEC_AMT_FOR);
														SET P_ACC_NUM = AME_FUN_ACC("COGS-AC4", P_ITEM, "AC4");
														SET P_LINE_JE = P_LINE_JE + 1;
														CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, P_ITEM, CONCAT("[", AME_FUN_ADDI_COST("AC4"), "] ", P_ITEM), "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, @UC_FOR, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "AC4", P_CUR, P_RATE, P_TAC4);
												END IF;
												# COGS AC5
												IF P_TAC5 <> 0 THEN
														SET @UC_FOR = AME_FUN_ROUND(P_TAC5 * P_RATE, P_DEC_AMT_FOR);
														SET @TC_FOR = AME_FUN_ROUND(@TC_FOR + @UC_FOR, P_DEC_AMT_FOR);
														SET P_ACC_NUM = AME_FUN_ACC("COGS-AC5", P_ITEM, "AC5");
														SET P_LINE_JE = P_LINE_JE + 1;
														CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, P_ITEM, CONCAT("[", AME_FUN_ADDI_COST("AC5"), "] ", P_ITEM), "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, @UC_FOR, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "AC5", P_CUR, P_RATE, P_TAC5);
												END IF;
												# ASSET
												SET @TC = AME_FUN_ROUND(P_TCOST + P_TAC1 + P_TAC2 + P_TAC3 + P_TAC4 + P_TAC5, P_DEC_AMT_FUN);
												IF @TC <> 0 THEN
														SET P_ACC_NUM = AME_FUN_ACC("IC", P_ITEM, "NA");
														SET P_LINE_JE = P_LINE_JE + 1;
														CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, "", P_CUS, P_ITEM, CONCAT("[Inventory] ", P_ITEM), "Cr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, -@TC_FOR, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "IC", P_CUR, P_RATE, -@TC);
												END IF;
												UPDATE pos_ar_in_det T1 SET T1.dou_uc = P_TCOST, T1.dou_ac1 = P_TAC1, T1.dou_ac2 = P_TAC2, T1.dou_ac3 = P_TAC3, T1.dou_ac4 = P_TAC4, T1.dou_ac5 = P_TAC5 WHERE T1.var_id = P1 AND T1.int_line = P_LINE_FRM;
										END;
								WHEN "Inventory Assembly" THEN
										SET @Donothing = NULL;
								ELSE
										SET @Donothing = NULL;
								END CASE;
						END LOOP L2;
				CLOSE C2;
				# ACC. FOC
				IF @T_FOC <> 0 THEN
						SET P_ACC_NUM = AME_FUN_ACC("FOC-AR-IN", "DEFAULT", "DEFAULT");
						SET P_LINE_JE = P_LINE_JE + 1;
						CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, P_CUS, "", "", "FOC", "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, @T_FOC, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "FOC", P_CUR, P_RATE, @T_FOC * P_RATE);
				END IF;
				# ACC. DIFFERENCE EXCHANGE RATE
				SET @P_DIFF_FOR = -AME_FUN_ROUND(AME_FUN_TOTAL_JE_DIFF_FOR(P_JID), P_DEC_AMT_FOR);
				IF @P_DIFF_FOR > 0  THEN
						SET P_ACC_NUM = AME_FUN_ACC("GAINLOSS-ROU", "DEFAULT", "DEFAULT");
						SET P_LINE_JE = P_LINE_JE + 1;
						CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, P_CUS, "", "", "Gain/Loss on Rounding Difference", "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, @P_DIFF_FOR, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "EXC-RATE", P_CUR, P_RATE, @P_DIFF);
				ELSEIF @P_DIFF_FOR < 0 THEN
						SET P_ACC_NUM = AME_FUN_ACC("GAINLOSS-ROU", "DEFAULT", "DEFAULT");
						SET P_LINE_JE = P_LINE_JE + 1;
						CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, P_CUS, "", "", "Gain/Loss on Rounding Difference", "Cr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, @P_DIFF_FOR, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "EXC-RATE", P_CUR, P_RATE, @P_DIFF);
				END IF;
				SET @P_DIFF = -AME_FUN_ROUND(AME_FUN_TOTAL_JE_DIFF(P_JID), P_DEC_AMT_FUN);
				IF @P_DIFF > 0 THEN
						SET P_ACC_NUM = AME_FUN_ACC("GAINLOSS-ROU", "DEFAULT", "DEFAULT");
						SET P_LINE_JE = P_LINE_JE + 1;
						CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, P_CUS, "", "", "Gain/Loss on Rounding Difference", "Dr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, 0, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "EXC-RATE", P_CUR, P_RATE, @P_DIFF);
				ELSEIF @P_DIFF < 0 THEN
						SET P_ACC_NUM = AME_FUN_ACC("GAINLOSS-ROU", "DEFAULT", "DEFAULT");
						SET P_LINE_JE = P_LINE_JE + 1;
						CALL AME_PRO_UPDATE_GL_JE_DET(P_JID, P_LINE_JE, P_ACC_NUM, P_CLA, "POS-AR-IN", P_TYPE, P1, P_REF, P_EMP, P_CUS, "", "", "Gain/Loss on Rounding Difference", "Cr", "", "", "", P_PRICE_CODE, "", P_DATE, P_DATE, P_DATE, 0, P_DEC_AMT_FOR, "", "", "", "", "", "", NULL, NULL, "EXC-RATE", P_CUR, P_RATE, @P_DIFF);
				END IF;
				CALL AME_PRO_UPDATE_GL_JE(P_JID, P_TYPE, P1, P_REF, P_DESC, P2, P_DATE, "", "POS-AR-IN", "VAT", P_VAT, P_VAT * P_RATE, P_CUR, P_RATE, P_DEC_AMT_FOR, P_DEC_AMT_FUN);
				UPDATE pos_ar_in SET var_status = 'Posted', int_jid = P_JID, var_post = P2, dat_post = NOW() WHERE var_id = P1;
		END;
		# AUTO POST GL
		IF AME_FUN_POST_ONE_TIME() = 1 THEN IF AME_FUN_VALID_GL_JE(P1) = 0 THEN CALL AME_PRO_POST_GL_JE_1(P_JID, P2); END IF; END IF;	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_POST_AR_IN_2`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_POST_AR_IN_2`(P1 varchar(100), P2 varchar(100), P3 tinyint(1))
    DETERMINISTIC
BEGIN
		DECLARE P_JID INTEGER DEFAULT -1;
		DECLARE P_JID_POST INTEGER DEFAULT -1;
		DECLARE P_NUM_AR INTEGER DEFAULT -1;
		DECLARE P_NUM_IC INTEGER DEFAULT -1;
		DECLARE P_DATE DATETIME;
		DECLARE P_CUS VARCHAR(100) DEFAULT "";

		DECLARE P_CUR VARCHAR(100) DEFAULT "";
		DECLARE P_BAL DOUBLE DEFAULT 0.0;
		DECLARE P_BAL_FUN DOUBLE DEFAULT 0.0;
		DECLARE P_DEC_QTY INTEGER DEFAULT 5;
		DECLARE P_DEC_COST_FOR INTEGER DEFAULT 6;
		DECLARE P_DEC_AMT_FOR INTEGER DEFAULT 2;
		DECLARE P_DEC_COST_FUN INTEGER DEFAULT 6;
		DECLARE P_DEC_AMT_FUN INTEGER DEFAULT 2;
		# DECIMAL FUNCTIONAL CURRENCY
		BEGIN DECLARE C1 CURSOR FOR SELECT T.int_qty, T.int_cost, T.int_amt FROM ame_sys_decimal T WHERE T.var_id = (SELECT T2.var_id FROM ame_mt_cur T2 WHERE T2.tin_default = 1);OPEN C1;IF FOUND_ROWS() > 0 THEN FETCH C1 INTO P_DEC_QTY, P_DEC_COST_FUN, P_DEC_AMT_FUN; END IF;CLOSE C1;END;
		# Get Sales Date
		BEGIN DECLARE C1 CURSOR FOR SELECT T.dat_date FROM pos_ar_in T WHERE T.var_id = P1;OPEN C1;IF FOUND_ROWS() > 0 THEN FETCH C1 INTO P_DATE; END IF;CLOSE C1;END;
		# SUB LEDGER IC
		BEGIN
				DECLARE D1 INTEGER DEFAULT 0;
				DECLARE P_ITEM VARCHAR(100) DEFAULT '';
				DECLARE P_LOC VARCHAR(100) DEFAULT '';
				DECLARE P_UOM VARCHAR(100) DEFAULT '';
				DECLARE P_QTY DOUBLE DEFAULT 0;
				DECLARE P_UC DOUBLE DEFAULT 0;
				DECLARE P_AC1 DOUBLE DEFAULT 0;
				DECLARE P_AC2 DOUBLE DEFAULT 0;
				DECLARE P_AC3 DOUBLE DEFAULT 0;
				DECLARE P_AC4 DOUBLE DEFAULT 0;
				DECLARE P_AC5 DOUBLE DEFAULT 0;
				DECLARE P_BAT_NUM INTEGER DEFAULT 0;
				DEClARE C1 CURSOR FOR SELECT T1.int_id, T1.var_locid, T1.var_itemid, T1.int_batchno, T1.dou_qty, 
				T1.dou_uc, T1.dou_ac1, T1.dou_ac2, T1.dou_ac3, T1.dou_ac4, T1.dou_ac5
				FROM ame_sl_ic_his AS T1 WHERE T1.var_modid = 'POS-AR-IN' AND T1.var_docid = P1 ORDER BY T1.int_line;
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET D1 = 1;
				OPEN C1;
						L1: LOOP FETCH C1 INTO  P_NUM_IC, P_LOC, P_ITEM, P_BAT_NUM, P_QTY, P_UC, P_AC1, P_AC2, P_AC3, P_AC4, P_AC5;
								IF D1 = 1 THEN LEAVE L1; END IF;
								CALL AME_PRO_UPDATE_SL_IC_BAT(P_LOC, P_ITEM, P_BAT_NUM, P_QTY, P_UC, P_AC1, P_AC2, P_AC3, P_AC4, P_AC5, "Cr", P_DEC_QTY, P_DEC_COST_FUN);
								CALL AME_PRO_UPDATE_SL_IC(P_LOC, P_ITEM, P_BAT_NUM, P_DATE, P_QTY, P_UC, P_AC1, P_AC2, P_AC3, P_AC4, P_AC5, "Cr", P_DEC_QTY, P_DEC_COST_FUN);
						END LOOP L1;
				CLOSE C1;
				DELETE FROM ame_sl_ic_his WHERE var_modid = 'POS-AR-IN' AND var_docid = P1;
		END;
		# DELETE OLD POST GL
		SELECT COUNT(T1.int_jid) INTO P_JID_POST FROM ame_gl_je T1 WHERE T1.int_jid = P_JID AND T1.var_status = 'Posted';
		IF P_JID_POST > 0 THEN CALL AME_PRO_POST_GL_JE_2(P_JID, P2, 0);END IF;
		DELETE FROM ame_gl_je WHERE int_jid = P_JID;DELETE FROM ame_gl_je_det WHERE int_jid = P_JID;
		IF P3 = 1 THEN
				CALL AME_PRO_POST_AR_IN_1(P1, P2, P3, P_NUM_AR, P_NUM_IC, P_JID);
		END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_rep_inv1`;
DELIMITER |
CREATE PROCEDURE `pos_pro_rep_inv1`(IN InvID varchar(255))
    DETERMINISTIC
BEGIN
SELECT
COALESCE(ps.var_id,'') as PSSalID,
ps.dat_date as PSSalDate,
COALESCE(ps.dou_disper,0) as PSDiscountPercent,
COALESCE(ps.dou_disdol,0) as PSDiscountDollar,
COALESCE(ps.dou_net,0) as PSNetTotalAmt,
COALESCE(0,0) as PSReceiveAmtUSD,
COALESCE(0,0) as PSReceiveAmtKHR,
COALESCE(0,0) as PSReceiveAmtCard,
COALESCE(0,0) as PSReceiveAR,
COALESCE(0,0) as PSOtherSetAmt,
COALESCE(ps.dou_change,0) as PSChangeAmt,
COALESCE(ps.dou_rate_khr,1) as PSExRate,
COALESCE(ps.var_desc,'') as PSRemark,
COALESCE(psd.int_line,0) as PSDLineNo,
COALESCE(psd.dou_qty,0) as PSDSalQty,
COALESCE(psd.dou_price,0) as PSDUnitPrice,
COALESCE(psd.dou_disper,0) AS PSDDiscountPercent,
COALESCE(psd.dou_disdol,0) as PSDDiscountDollar,
COALESCE(psd.dou_taxper,0) AS PSDTaxPercent,
COALESCE(psd.dou_taxdol,0) as PSDTaxDollar,
COALESCE(psd.dou_net,0) as PSDNetTotalAmt,
COALESCE(l.var_tel1,'') as LLTel1,
COALESCE(l.var_tel2,'') as LLTel2,
COALESCE(l.var_inv_logo,'') as LLogo,
COALESCE(l.var_wifi,'') as LWifi,
COALESCE(c.var_name,'') as CustName,
COALESCE(e.var_name,'') as EmpName,
COALESCE(i.var_name,'') as ItemName,
'' AS OpenItemDes,
COALESCE(l.var_inv_footer,'') as RcptFooter,
COALESCE(l.var_addr,'') as LAddr,
COALESCE(l.var_name,'') as LName,
COALESCE(l.var_name_kh,'') as LNameKH,
'' AS StationID,
'' AS StationName,
ps.dat_from AS StartTime,
ps.dat_to AS EndTime,
COALESCE(psd.var_uomid,'') AS UOMID,
COALESCE(ps.var_type,'') AS SalType,
0 AS ServiceChargePer,
0 AS ServiceChargeDol,
COALESCE(psd.dou_sub,0) AS TotalAmt,
COALESCE(ps.dou_sub,0) AS S_Sub,
0 AS Tips,
'' AS opt_EmpName
FROM pos_ar_in ps LEFT JOIN pos_ar_in_det psd on ps.var_id = psd.var_id
LEFT JOIN ame_mt_loc l on l.var_id = ps.var_locid
LEFT JOIN ame_mt_ite i ON i.var_id = psd.var_itemid
LEFT JOIN ame_mt_cus c ON c.var_id = ps.var_cusid
LEFT JOIN ame_mt_emp e ON e.var_id = ps.var_empid
WHERE ps.var_id = InvID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D001_D1`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D001_D1`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all'
	SET @ORDERBY = " ORDER BY s.dat_date,sd.var_id,sd.int_line ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	s.dat_date AS SalDate,
	COALESCE(s.var_id,'') AS SalID,
	COALESCE(c.var_name,'') AS CustName,
	COALESCE(s.var_locid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	COALESCE(sd.int_line,0) AS LineNo,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.dou_qty,0) AS SalQty,
	COALESCE(sd.var_uomid,'') AS UOMID,
	COALESCE(sd.dou_price,0) AS UnitPrice,
	COALESCE(sd.dou_sub,0) AS TotalAmt,
	COALESCE(sd.dou_disdol,0) AS DiscountDollar,
	COALESCE(sd.dou_taxdol,0) AS TaxDollar,
	COALESCE(0,0) AS ServiceChargeDol,
	COALESCE(sd.dou_net,0) AS NetTotalAmt,
	COALESCE(0,0) AS tips,
	COALESCE(s.dou_net,0) AS InvNetTotalAmt,
	COALESCE(s.var_status,'') AS PostStatus
	FROM pos_ar_in s INNER JOIN pos_ar_in_det sd ON sd.var_id = s.var_id 
	LEFT JOIN ame_mt_cus c ON s.var_cusid = c.var_id 
	LEFT JOIN ame_mt_ite i ON sd.var_itemid = i.var_id 
	LEFT JOIN ame_mt_loc l ON sd.var_locid = l.var_id
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL,@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D001_M1`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D001_M1`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all'
	SET @ORDERBY = " ORDER BY s.dat_date,s.var_id ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	s.dat_date AS SalDate,
	COALESCE(s.var_id,'') AS SalID,
	COALESCE(c.var_name,'') AS CustName,
	COALESCE(SUM(sd.dou_sub),0) AS TotalAmt,
	COALESCE(SUM(sd.dou_disdol),0) AS DiscountDollar,
	COALESCE(SUM(sd.dou_taxdol),0) AS TaxDollar,
	COALESCE(SUM(0),0) AS ServiceChargeDol,
	0 AS Tips,
	COALESCE(s.dou_net,0) AS NetTotalAmt,
	COALESCE(s.var_locid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	COALESCE(s.dou_paid,0) AS TotalReceiveAmtUSD,
	0 AS ReceiveAmtCard,
	0 AS ReceiveAR,
	0 AS ReceiveAmtTotal,
	COALESCE(s.dou_change,0) AS ChangeAmt,
	COALESCE(s.var_status,'') AS PostStatus,
	0 AS OtherSetAmt
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd ON s.var_id = sd.var_id 
	LEFT JOIN ame_mt_cus c on s.var_cusid = c.var_id 
	LEFT JOIN ame_mt_loc l on s.var_locid = l.var_id 
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY s.var_id ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D002_M1`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D002_M1`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY s.var_locid,DATE(s.dat_date) ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_locid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	DATE(s.dat_date) AS SalDate,
	COUNT(s.var_id) AS InvCount,
	COALESCE(SUM(sd.dou_sub),0) AS TotalAmt,
	COALESCE(SUM(sd.dou_disdol),0) AS ItemDis,
	COALESCE(SUM(sd.dou_sub),0) - COALESCE(SUM(sd.dou_disdol),0) AS NET_EXC_VAT,
	COALESCE(SUM(sd.dou_taxdol),0) AS TaxDollar,
	0 AS SERVICE_CHARGE,
	0 AS TIPS,
	COALESCE(SUM(s.dou_net),0) AS NetTotalAmt
	FROM pos_ar_in s INNER JOIN 
	(SELECT 
	sdd.var_id, 
	COALESCE(SUM(sdd.dou_sub),0) AS dou_sub,
	COALESCE(SUM(sdd.dou_disdol),0) AS dou_disdol,
	COALESCE(SUM(sdd.dou_taxdol),0) AS dou_taxdol 
	FROM pos_ar_in_det sdd GROUP BY sdd.var_id) 
	sd ON s.var_id = sd.var_id
	LEFT JOIN ame_mt_loc l ON s.var_locid = l.var_id
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY s.var_locid,DATE(s.dat_date) ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D002_M2`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D002_M2`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY s.var_empid,DATE(s.dat_date) ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_empid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	DATE(s.dat_date) AS SalDate,
	COUNT(s.var_id) AS InvCount,
	COALESCE(SUM(sd.dou_sub),0) AS TotalAmt,
	COALESCE(SUM(sd.dou_disdol),0) AS ItemDis,
	COALESCE(SUM(sd.dou_sub),0) - COALESCE(SUM(sd.dou_disdol),0) AS NET_EXC_VAT,
	COALESCE(SUM(sd.dou_taxdol),0) AS TaxDollar,
	0 AS SERVICE_CHARGE,
	0 AS TIPS,
	COALESCE(SUM(s.dou_net),0) AS NetTotalAmt
	FROM pos_ar_in s INNER JOIN 
	(SELECT 
	sdd.var_id, 
	COALESCE(SUM(sdd.dou_sub),0) AS dou_sub,
	COALESCE(SUM(sdd.dou_disdol),0) AS dou_disdol,
	COALESCE(SUM(sdd.dou_taxdol),0) AS dou_taxdol 
	FROM pos_ar_in_det sdd GROUP BY sdd.var_id) 
	sd ON s.var_id = sd.var_id
	LEFT JOIN ame_mt_emp l ON s.var_empid = l.var_id
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY s.var_empid,DATE(s.dat_date) ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D002_M3`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D002_M3`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " ORDER BY s.var_cusid,DATE(s.dat_date) ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_cusid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	DATE(s.dat_date) AS SalDate,
	COUNT(s.var_id) AS InvCount,
	COALESCE(SUM(sd.dou_sub),0) AS TotalAmt,
	COALESCE(SUM(sd.dou_disdol),0) AS ItemDis,
	COALESCE(SUM(sd.dou_sub),0) - COALESCE(SUM(sd.dou_disdol),0) AS NET_EXC_VAT,
	COALESCE(SUM(sd.dou_taxdol),0) AS TaxDollar,
	0 AS SERVICE_CHARGE,
	0 AS TIPS,
	COALESCE(SUM(s.dou_net),0) AS NetTotalAmt
	FROM pos_ar_in s INNER JOIN 
	(SELECT 
	sdd.var_id, 
	COALESCE(SUM(sdd.dou_sub),0) AS dou_sub,
	COALESCE(SUM(sdd.dou_disdol),0) AS dou_disdol,
	COALESCE(SUM(sdd.dou_taxdol),0) AS dou_taxdol 
	FROM pos_ar_in_det sdd GROUP BY sdd.var_id) 
	sd ON s.var_id = sd.var_id
	LEFT JOIN ame_mt_cus l ON s.var_cusid = l.var_id
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY s.var_cusid,DATE(s.dat_date) ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D003_M1`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D003_M1`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY s.var_locid,DATE(s.dat_date) ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_locid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	DATE(s.dat_date) AS SalDate,
	COUNT(s.var_id) AS InvCount,
	COALESCE(SUM(sd.dou_sub),0) AS TotalAmt,
	COALESCE(SUM(sd.dou_disdol),0) AS ItemDis,
	COALESCE(SUM(sd.dou_sub),0) - COALESCE(SUM(sd.dou_disdol),0) AS NET_EXC_VAT,
	COALESCE(SUM(sd.dou_taxdol),0) AS TaxDollar,
	0 AS SERVICE_CHARGE,
	0 AS TIPS,
	COALESCE(SUM(s.dou_net),0) AS NetTotalAmt
	FROM pos_ar_in s INNER JOIN 
	(SELECT 
	sdd.var_id, 
	COALESCE(SUM(sdd.dou_sub),0) AS dou_sub,
	COALESCE(SUM(sdd.dou_disdol),0) AS dou_disdol,
	COALESCE(SUM(sdd.dou_taxdol),0) AS dou_taxdol 
	FROM pos_ar_in_det sdd GROUP BY sdd.var_id) 
	sd ON s.var_id = sd.var_id
	LEFT JOIN ame_mt_loc l ON s.var_locid = l.var_id
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY s.var_locid,YEAR(s.dat_date),MONTH(s.dat_date) ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D003_M2`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D003_M2`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY s.var_empid,DATE(s.dat_date) ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_empid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	DATE(s.dat_date) AS SalDate,
	COUNT(s.var_id) AS InvCount,
	COALESCE(SUM(sd.dou_sub),0) AS TotalAmt,
	COALESCE(SUM(sd.dou_disdol),0) AS ItemDis,
	COALESCE(SUM(sd.dou_sub),0) - COALESCE(SUM(sd.dou_disdol),0) AS NET_EXC_VAT,
	COALESCE(SUM(sd.dou_taxdol),0) AS TaxDollar,
	0 AS SERVICE_CHARGE,
	0 AS TIPS,
	COALESCE(SUM(s.dou_net),0) AS NetTotalAmt
	FROM pos_ar_in s INNER JOIN 
	(SELECT 
	sdd.var_id, 
	COALESCE(SUM(sdd.dou_sub),0) AS dou_sub,
	COALESCE(SUM(sdd.dou_disdol),0) AS dou_disdol,
	COALESCE(SUM(sdd.dou_taxdol),0) AS dou_taxdol 
	FROM pos_ar_in_det sdd GROUP BY sdd.var_id) 
	sd ON s.var_id = sd.var_id
	LEFT JOIN ame_mt_emp l ON s.var_empid = l.var_id
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY s.var_empid,YEAR(s.dat_date),MONTH(s.dat_date) ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D003_M3`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D003_M3`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " ORDER BY s.var_cusid,DATE(s.dat_date) ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_cusid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	DATE(s.dat_date) AS SalDate,
	COUNT(s.var_id) AS InvCount,
	COALESCE(SUM(sd.dou_sub),0) AS TotalAmt,
	COALESCE(SUM(sd.dou_disdol),0) AS ItemDis,
	COALESCE(SUM(sd.dou_sub),0) - COALESCE(SUM(sd.dou_disdol),0) AS NET_EXC_VAT,
	COALESCE(SUM(sd.dou_taxdol),0) AS TaxDollar,
	0 AS SERVICE_CHARGE,
	0 AS TIPS,
	COALESCE(SUM(s.dou_net),0) AS NetTotalAmt
	FROM pos_ar_in s INNER JOIN 
	(SELECT 
	sdd.var_id, 
	COALESCE(SUM(sdd.dou_sub),0) AS dou_sub,
	COALESCE(SUM(sdd.dou_disdol),0) AS dou_disdol,
	COALESCE(SUM(sdd.dou_taxdol),0) AS dou_taxdol 
	FROM pos_ar_in_det sdd GROUP BY sdd.var_id) 
	sd ON s.var_id = sd.var_id
	LEFT JOIN ame_mt_cus l ON s.var_cusid = l.var_id
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY s.var_cusid,YEAR(s.dat_date),MONTH(s.dat_date) ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D004_D1`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D004_D1`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100),P12 varchar(100),P13 varchar(100),P14 varchar(100),P15 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY COALESCE(i.var_groupid,''),COALESCE(sd.var_itemid,''),s.dat_date ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_id,'') AS SalID,
	s.dat_date AS SalDate,
	COALESCE(s.var_empid,'') AS EmpID,
	COALESCE(e.var_name,'') AS EmpName,
	IF(COALESCE(i.var_groupid,'') = '','Ungroup',COALESCE(i.var_groupid,'')) AS itemgroupid,
	COALESCE(ip.var_name,'') AS itemgroupname,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.var_uomid,'') AS UOMID,
	DATE(s.dat_date) as SAL_DATE,
	COALESCE(sd.dou_qty,0) AS SAL_QTY,
	COALESCE(sd.dou_sub,0) AS SAL_AMT,
	COALESCE(sd.dou_disdol,0) AS DIS_ITEM,
	COALESCE(sd.dou_sub,0) - COALESCE(sd.dou_disdol,0) AS NET_EXC_VAT,
	COALESCE(sd.dou_taxdol,0) AS TAX,
	COALESCE(sd.dou_net,0) AS NET_AMT,
	0 AS SERVICE_CHARGE
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd on s.var_id = sd.var_id 
	LEFT JOIN	ame_mt_ite i on i.var_id = sd.var_itemid
	LEFT JOIN ame_mt_ite_gro ip ON ip.var_id = i.var_groupid
	LEFT JOIN ame_mt_emp e ON e.var_id = s.var_empid
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "')
	AND
	IF('", P12, "' = 'ALL', TRUE, i.var_groupid >= '", P12, "')
	AND
	IF('", P13, "' = 'ALL', TRUE, i.var_groupid <= '", P13, "')
	AND
	IF('", P14, "' = 'ALL', TRUE, sd.var_itemid >= '", P14, "')
	AND
	IF('", P15, "' = 'ALL', TRUE, sd.var_itemid <= '", P15, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL,@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D004_D2`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D004_D2`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100),P12 varchar(100),P13 varchar(100),P14 varchar(100),P15 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY COALESCE(s.var_locid,''),COALESCE(sd.var_itemid,''),s.dat_date ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_id,'') AS SalID,
	s.dat_date AS SalDate,
	COALESCE(s.var_empid,'') AS EmpID,
	COALESCE(e.var_name,'') AS EmpName,
	COALESCE(s.var_locid,'') AS itemgroupid,
	COALESCE(ip.var_name,'') AS itemgroupname,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.var_uomid,'') AS UOMID,
	DATE(s.dat_date) as SAL_DATE,
	COALESCE(sd.dou_qty,0) AS SAL_QTY,
	COALESCE(sd.dou_sub,0) AS SAL_AMT,
	COALESCE(sd.dou_disdol,0) AS DIS_ITEM,
	COALESCE(sd.dou_sub,0) - COALESCE(sd.dou_disdol,0) AS NET_EXC_VAT,
	COALESCE(sd.dou_taxdol,0) AS TAX,
	COALESCE(sd.dou_net,0) AS NET_AMT,
	0 AS SERVICE_CHARGE
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd on s.var_id = sd.var_id 
	LEFT JOIN	ame_mt_ite i on i.var_id = sd.var_itemid
	LEFT JOIN ame_mt_loc ip ON ip.var_id = s.var_locid
	LEFT JOIN ame_mt_emp e ON e.var_id = s.var_empid
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "')
	AND
	IF('", P12, "' = 'ALL', TRUE, i.var_groupid >= '", P12, "')
	AND
	IF('", P13, "' = 'ALL', TRUE, i.var_groupid <= '", P13, "')
	AND
	IF('", P14, "' = 'ALL', TRUE, sd.var_itemid >= '", P14, "')
	AND
	IF('", P15, "' = 'ALL', TRUE, sd.var_itemid <= '", P15, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL,@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D004_D3`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D004_D3`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100),P12 varchar(100),P13 varchar(100),P14 varchar(100),P15 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY COALESCE(s.var_empid,''),COALESCE(sd.var_itemid,''),s.dat_date ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_id,'') AS SalID,
	s.dat_date AS SalDate,
	COALESCE(s.var_locid,'') AS LocID,
	COALESCE(l.var_name,'') AS LocName,
	COALESCE(s.var_empid,'') AS itemgroupid,
	COALESCE(e.var_name,'') AS itemgroupname,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.var_uomid,'') AS UOMID,
	DATE(s.dat_date) as SAL_DATE,
	COALESCE(sd.dou_qty,0) AS SAL_QTY,
	COALESCE(sd.dou_sub,0) AS SAL_AMT,
	COALESCE(sd.dou_disdol,0) AS DIS_ITEM,
	COALESCE(sd.dou_sub,0) - COALESCE(sd.dou_disdol,0) AS NET_EXC_VAT,
	COALESCE(sd.dou_taxdol,0) AS TAX,
	COALESCE(sd.dou_net,0) AS NET_AMT,
	0 AS SERVICE_CHARGE
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd on s.var_id = sd.var_id 
	LEFT JOIN	ame_mt_ite i on i.var_id = sd.var_itemid
	LEFT JOIN ame_mt_loc l ON l.var_id = s.var_locid
	LEFT JOIN ame_mt_emp e ON e.var_id = s.var_empid
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "')
	AND
	IF('", P12, "' = 'ALL', TRUE, i.var_groupid >= '", P12, "')
	AND
	IF('", P13, "' = 'ALL', TRUE, i.var_groupid <= '", P13, "')
	AND
	IF('", P14, "' = 'ALL', TRUE, sd.var_itemid >= '", P14, "')
	AND
	IF('", P15, "' = 'ALL', TRUE, sd.var_itemid <= '", P15, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL,@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D004_D4`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D004_D4`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100),P12 varchar(100),P13 varchar(100),P14 varchar(100),P15 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY COALESCE(s.var_cusid,''),COALESCE(sd.var_itemid,''),s.dat_date ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_id,'') AS SalID,
	s.dat_date AS SalDate,
	COALESCE(s.var_empid,'') AS EmpID,
	COALESCE(e.var_name,'') AS EmpName,
	COALESCE(s.var_cusid,'') AS itemgroupid,
	COALESCE(c.var_name,'') AS itemgroupname,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.var_uomid,'') AS UOMID,
	DATE(s.dat_date) as SAL_DATE,
	COALESCE(sd.dou_qty,0) AS SAL_QTY,
	COALESCE(sd.dou_sub,0) AS SAL_AMT,
	COALESCE(sd.dou_disdol,0) AS DIS_ITEM,
	COALESCE(sd.dou_sub,0) - COALESCE(sd.dou_disdol,0) AS NET_EXC_VAT,
	COALESCE(sd.dou_taxdol,0) AS TAX,
	COALESCE(sd.dou_net,0) AS NET_AMT,
	0 AS SERVICE_CHARGE
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd on s.var_id = sd.var_id 
	LEFT JOIN	ame_mt_ite i on i.var_id = sd.var_itemid
	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
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "')
	AND
	IF('", P12, "' = 'ALL', TRUE, i.var_groupid >= '", P12, "')
	AND
	IF('", P13, "' = 'ALL', TRUE, i.var_groupid <= '", P13, "')
	AND
	IF('", P14, "' = 'ALL', TRUE, sd.var_itemid >= '", P14, "')
	AND
	IF('", P15, "' = 'ALL', TRUE, sd.var_itemid <= '", P15, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL,@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D004_M1`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D004_M1`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100),P12 varchar(100),P13 varchar(100),P14 varchar(100),P15 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY COALESCE(i.var_groupid,''),COALESCE(sd.var_itemid,''),COALESCE(sd.var_uomid,'') ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	IF(COALESCE(i.var_groupid,'') = '','Ungroup',COALESCE(i.var_groupid,'')) AS itemgroupid,
	COALESCE(ip.var_name,'') AS itemgroupname,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.var_uomid,'') AS UOMID,
	DATE(s.dat_date) as SAL_DATE,
	COALESCE(SUM(sd.dou_qty),0) AS SAL_QTY,
	COALESCE(SUM(sd.dou_sub),0) AS SAL_AMT,
	COALESCE(SUM(sd.dou_disdol),0) AS DIS_ITEM,
	COALESCE(SUM(sd.dou_sub),0) - COALESCE(SUM(sd.dou_disdol),0) AS NET_EXC_VAT,
	COALESCE(SUM(sd.dou_taxdol),0) AS TAX,
	COALESCE(SUM(sd.dou_net),0) AS NET_AMT,
	0 AS SERVICE_CHARGE
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd on s.var_id = sd.var_id 
	LEFT JOIN	ame_mt_ite i on i.var_id = sd.var_itemid
	LEFT JOIN ame_mt_ite_gro ip ON ip.var_id = i.var_groupid
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "')
	AND
	IF('", P12, "' = 'ALL', TRUE, i.var_groupid >= '", P12, "')
	AND
	IF('", P13, "' = 'ALL', TRUE, i.var_groupid <= '", P13, "')
	AND
	IF('", P14, "' = 'ALL', TRUE, sd.var_itemid >= '", P14, "')
	AND
	IF('", P15, "' = 'ALL', TRUE, sd.var_itemid <= '", P15, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY COALESCE(i.var_groupid,''),COALESCE(sd.var_itemid,''),COALESCE(sd.var_uomid,'') ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D004_M2`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D004_M2`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100),P12 varchar(100),P13 varchar(100),P14 varchar(100),P15 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY COALESCE(S.var_locid,''),COALESCE(sd.var_itemid,''),COALESCE(sd.var_uomid,'') ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_locid,'') AS itemgroupid,
	COALESCE(ip.var_name,'') AS itemgroupname,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.var_uomid,'') AS UOMID,
	DATE(s.dat_date) as SAL_DATE,
	COALESCE(SUM(sd.dou_qty),0) AS SAL_QTY,
	COALESCE(SUM(sd.dou_sub),0) AS SAL_AMT,
	COALESCE(SUM(sd.dou_disdol),0) AS DIS_ITEM,
	COALESCE(SUM(sd.dou_sub),0) - COALESCE(SUM(sd.dou_disdol),0) AS NET_EXC_VAT,
	COALESCE(SUM(sd.dou_taxdol),0) AS TAX,
	COALESCE(SUM(sd.dou_net),0) AS NET_AMT,
	0 AS SERVICE_CHARGE
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd on s.var_id = sd.var_id 
	LEFT JOIN	ame_mt_ite i on i.var_id = sd.var_itemid
	LEFT JOIN ame_mt_loc ip ON ip.var_id = s.var_locid
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "')
	AND
	IF('", P12, "' = 'ALL', TRUE, i.var_groupid >= '", P12, "')
	AND
	IF('", P13, "' = 'ALL', TRUE, i.var_groupid <= '", P13, "')
	AND
	IF('", P14, "' = 'ALL', TRUE, sd.var_itemid >= '", P14, "')
	AND
	IF('", P15, "' = 'ALL', TRUE, sd.var_itemid <= '", P15, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY COALESCE(S.var_locid,''),COALESCE(sd.var_itemid,''),COALESCE(sd.var_uomid,'') ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D004_M3`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D004_M3`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100),P12 varchar(100),P13 varchar(100),P14 varchar(100),P15 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY COALESCE(S.var_empid,''),COALESCE(sd.var_itemid,''),COALESCE(sd.var_uomid,'') ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_empid,'') AS itemgroupid,
	COALESCE(ip.var_name,'') AS itemgroupname,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.var_uomid,'') AS UOMID,
	DATE(s.dat_date) as SAL_DATE,
	COALESCE(SUM(sd.dou_qty),0) AS SAL_QTY,
	COALESCE(SUM(sd.dou_sub),0) AS SAL_AMT,
	COALESCE(SUM(sd.dou_disdol),0) AS DIS_ITEM,
	COALESCE(SUM(sd.dou_sub),0) - COALESCE(SUM(sd.dou_disdol),0) AS NET_EXC_VAT,
	COALESCE(SUM(sd.dou_taxdol),0) AS TAX,
	COALESCE(SUM(sd.dou_net),0) AS NET_AMT,
	0 AS SERVICE_CHARGE
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd on s.var_id = sd.var_id 
	LEFT JOIN	ame_mt_ite i on i.var_id = sd.var_itemid
	LEFT JOIN ame_mt_emp ip ON ip.var_id = s.var_empid
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "')
	AND
	IF('", P12, "' = 'ALL', TRUE, i.var_groupid >= '", P12, "')
	AND
	IF('", P13, "' = 'ALL', TRUE, i.var_groupid <= '", P13, "')
	AND
	IF('", P14, "' = 'ALL', TRUE, sd.var_itemid >= '", P14, "')
	AND
	IF('", P15, "' = 'ALL', TRUE, sd.var_itemid <= '", P15, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY COALESCE(S.var_empid,''),COALESCE(sd.var_itemid,''),COALESCE(sd.var_uomid,'') ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D004_M4`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D004_M4`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100),P12 varchar(100),P13 varchar(100),P14 varchar(100),P15 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " 	ORDER BY COALESCE(S.var_cusid,''),COALESCE(sd.var_itemid,''),COALESCE(sd.var_uomid,'') ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	COALESCE(s.var_cusid,'') AS itemgroupid,
	COALESCE(c.var_name,'') AS itemgroupname,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.var_uomid,'') AS UOMID,
	DATE(s.dat_date) as SAL_DATE,
	COALESCE(SUM(sd.dou_qty),0) AS SAL_QTY,
	COALESCE(SUM(sd.dou_sub),0) AS SAL_AMT,
	COALESCE(SUM(sd.dou_disdol),0) AS DIS_ITEM,
	COALESCE(SUM(sd.dou_sub),0) - COALESCE(SUM(sd.dou_disdol),0) AS NET_EXC_VAT,
	COALESCE(SUM(sd.dou_taxdol),0) AS TAX,
	COALESCE(SUM(sd.dou_net),0) AS NET_AMT,
	0 AS SERVICE_CHARGE
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd on s.var_id = sd.var_id 
	LEFT JOIN	ame_mt_ite i on i.var_id = sd.var_itemid
	LEFT JOIN ame_mt_cus c ON c.var_id = s.var_cusid
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "')
	AND
	IF('", P12, "' = 'ALL', TRUE, i.var_groupid >= '", P12, "')
	AND
	IF('", P13, "' = 'ALL', TRUE, i.var_groupid <= '", P13, "')
	AND
	IF('", P14, "' = 'ALL', TRUE, sd.var_itemid >= '", P14, "')
	AND
	IF('", P15, "' = 'ALL', TRUE, sd.var_itemid <= '", P15, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY COALESCE(S.var_cusid,''),COALESCE(sd.var_itemid,''),COALESCE(sd.var_uomid,'') ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D005_D1`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D005_D1`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all'
	SET @ORDERBY = " ORDER BY s.dat_date,sd.var_id,sd.int_line ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	s.dat_date AS SalDate,
	COALESCE(s.var_id,'') AS SalID,
	COALESCE(c.var_name,'') AS CustName,
	COALESCE(s.var_locid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	COALESCE(sd.int_line,0) AS LineNo,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.dou_qty,0) AS SalQty,
	COALESCE(sd.var_uomid,'') AS UOMID,
	COALESCE(sd.dou_price,0) AS UnitPrice,
	COALESCE(sd.dou_sub,0) AS TotalAmt,
	COALESCE(sd.dou_disdol,0) AS DiscountDollar,
	COALESCE(sd.dou_taxdol,0) AS TaxDollar,
	COALESCE(0,0) AS ServiceChargeDol,
	COALESCE(sd.dou_net,0) AS NetTotalAmt,
	COALESCE(0,0) AS tips,
	COALESCE(s.dou_net,0) AS InvNetTotalAmt,
	COALESCE(s.var_status,'') AS PostStatus
	FROM pos_ar_in s INNER JOIN pos_ar_in_det sd ON sd.var_id = s.var_id 
	LEFT JOIN ame_mt_cus c ON s.var_cusid = c.var_id 
	LEFT JOIN ame_mt_ite i ON sd.var_itemid = i.var_id 
	LEFT JOIN ame_mt_loc l ON sd.var_locid = l.var_id
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL,@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D005_D2`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D005_D2`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all','all','all','all','all'
	SET @ORDERBY = " ORDER BY s.dat_date,sd.var_id,sd.int_line ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	s.dat_date AS SalDate,
	COALESCE(s.var_id,'') AS SalID,
	COALESCE(c.var_name,'') AS CustName,
	COALESCE(s.var_empid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	COALESCE(sd.int_line,0) AS LineNo,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.dou_qty,0) AS SalQty,
	COALESCE(sd.var_uomid,'') AS UOMID,
	COALESCE(sd.dou_price,0) AS UnitPrice,
	COALESCE(sd.dou_sub,0) AS TotalAmt,
	COALESCE(sd.dou_disdol,0) AS DiscountDollar,
	COALESCE(sd.dou_taxdol,0) AS TaxDollar,
	COALESCE(0,0) AS ServiceChargeDol,
	COALESCE(sd.dou_net,0) AS NetTotalAmt,
	COALESCE(0,0) AS tips,
	COALESCE(s.dou_net,0) AS InvNetTotalAmt,
	COALESCE(s.var_status,'') AS PostStatus
	FROM pos_ar_in s INNER JOIN pos_ar_in_det sd ON sd.var_id = s.var_id 
	LEFT JOIN ame_mt_cus c ON s.var_cusid = c.var_id 
	LEFT JOIN ame_mt_ite i ON sd.var_itemid = i.var_id 
	LEFT JOIN ame_mt_emp l ON s.var_empid = l.var_id
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL,@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D005_D3`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D005_D3`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all'
	SET @ORDERBY = " ORDER BY s.dat_date,sd.var_id,sd.int_line ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	s.dat_date AS SalDate,
	COALESCE(s.var_id,'') AS SalID,
	COALESCE(e.var_name,'') AS EmpName,
	COALESCE(s.var_cusid,'') AS LocationID,
	COALESCE(c.var_name,'') AS Des,
	COALESCE(sd.int_line,0) AS LineNo,
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name,'') AS ItemName,
	COALESCE(i.var_itemcode,'') AS QRCode,
	COALESCE(sd.dou_qty,0) AS SalQty,
	COALESCE(sd.var_uomid,'') AS UOMID,
	COALESCE(sd.dou_price,0) AS UnitPrice,
	COALESCE(sd.dou_sub,0) AS TotalAmt,
	COALESCE(sd.dou_disdol,0) AS DiscountDollar,
	COALESCE(sd.dou_taxdol,0) AS TaxDollar,
	COALESCE(0,0) AS ServiceChargeDol,
	COALESCE(sd.dou_net,0) AS NetTotalAmt,
	COALESCE(0,0) AS tips,
	COALESCE(s.dou_net,0) AS InvNetTotalAmt,
	COALESCE(s.var_status,'') AS PostStatus
	FROM pos_ar_in s INNER JOIN pos_ar_in_det sd ON sd.var_id = s.var_id 
	LEFT JOIN ame_mt_cus c ON s.var_cusid = c.var_id 
	LEFT JOIN ame_mt_ite i ON sd.var_itemid = i.var_id 
	LEFT JOIN ame_mt_emp e ON s.var_empid = e.var_id
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL,@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D005_M1`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D005_M1`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all'
	SET @ORDERBY = " ORDER BY s.dat_date,s.var_id ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	s.dat_date AS SalDate,
	COALESCE(s.var_id,'') AS SalID,
	COALESCE(c.var_name,'') AS CustName,
	COALESCE(SUM(sd.dou_sub),0) AS TotalAmt,
	COALESCE(SUM(sd.dou_disdol),0) AS DiscountDollar,
	COALESCE(SUM(sd.dou_taxdol),0) AS TaxDollar,
	COALESCE(SUM(0),0) AS ServiceChargeDol,
	0 AS Tips,
	COALESCE(s.dou_net,0) AS NetTotalAmt,
	COALESCE(s.var_locid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	COALESCE(s.dou_paid,0) AS TotalReceiveAmtUSD,
	0 AS ReceiveAmtCard,
	0 AS ReceiveAR,
	0 AS ReceiveAmtTotal,
	COALESCE(s.dou_change,0) AS ChangeAmt,
	COALESCE(s.var_status,'') AS PostStatus,
	0 AS OtherSetAmt
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd ON s.var_id = sd.var_id 
	LEFT JOIN ame_mt_cus c on s.var_cusid = c.var_id 
	LEFT JOIN ame_mt_loc l on s.var_locid = l.var_id 
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY s.var_id ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D005_M2`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D005_M2`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all'
	SET @ORDERBY = " ORDER BY s.dat_date,s.var_id ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	s.dat_date AS SalDate,
	COALESCE(s.var_id,'') AS SalID,
	COALESCE(c.var_name,'') AS CustName,
	COALESCE(SUM(sd.dou_sub),0) AS TotalAmt,
	COALESCE(SUM(sd.dou_disdol),0) AS DiscountDollar,
	COALESCE(SUM(sd.dou_taxdol),0) AS TaxDollar,
	COALESCE(SUM(0),0) AS ServiceChargeDol,
	0 AS Tips,
	COALESCE(s.dou_net,0) AS NetTotalAmt,
	COALESCE(s.var_empid,'') AS LocationID,
	COALESCE(l.var_name,'') AS Des,
	COALESCE(s.dou_paid,0) AS TotalReceiveAmtUSD,
	0 AS ReceiveAmtCard,
	0 AS ReceiveAR,
	0 AS ReceiveAmtTotal,
	COALESCE(s.dou_change,0) AS ChangeAmt,
	COALESCE(s.var_status,'') AS PostStatus,
	0 AS OtherSetAmt
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd ON s.var_id = sd.var_id 
	LEFT JOIN ame_mt_cus c on s.var_cusid = c.var_id 
	LEFT JOIN ame_mt_emp l on s.var_empid = l.var_id 
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY s.var_id ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_REP_RPT_M006D005_M3`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_REP_RPT_M006D005_M3`(D1 varchar(100),D2 varchar(100),D3 varchar(100),D4 varchar(100),D5 varchar(100),P1 varchar(100),P2 datetime,P3 datetime,P4 varchar(100),P5 varchar(100),P6 varchar(100),P7 varchar(100),P8 varchar(100),P9 varchar(100),P10 varchar(100),P11 varchar(100))
    DETERMINISTIC
BEGIN
	#'','','','','','ALL','2018-06-06','2016-06-06','all','all','all','all'
	SET @ORDERBY = " ORDER BY s.dat_date,s.var_id ";
	SET @DETAIL = CONCAT( 
	"SELECT 
	s.dat_date AS SalDate,
	COALESCE(s.var_id,'') AS SalID,
	COALESCE(e.var_name,'') AS EmpName,
	COALESCE(SUM(sd.dou_sub),0) AS TotalAmt,
	COALESCE(SUM(sd.dou_disdol),0) AS DiscountDollar,
	COALESCE(SUM(sd.dou_taxdol),0) AS TaxDollar,
	COALESCE(SUM(0),0) AS ServiceChargeDol,
	0 AS Tips,
	COALESCE(s.dou_net,0) AS NetTotalAmt,
	COALESCE(s.var_cusid,'') AS LocationID,
	COALESCE(c.var_name,'') AS Des,
	COALESCE(s.dou_paid,0) AS TotalReceiveAmtUSD,
	0 AS ReceiveAmtCard,
	0 AS ReceiveAR,
	0 AS ReceiveAmtTotal,
	COALESCE(s.dou_change,0) AS ChangeAmt,
	COALESCE(s.var_status,'') AS PostStatus,
	0 AS OtherSetAmt
	FROM pos_ar_in s 
	INNER JOIN pos_ar_in_det sd ON s.var_id = sd.var_id 
	LEFT JOIN ame_mt_cus c on s.var_cusid = c.var_id 
	LEFT JOIN ame_mt_emp e on s.var_empid = e.var_id 
	WHERE
	(CASE
	WHEN '", P1, "' = 'ALL' THEN TRUE
	WHEN '", P1, "' = 'THIS TODAY' THEN DATE(s.dat_date) = DATE(NOW())
	WHEN '", P1, "' = 'THIS PERIOD' THEN MONTH(s.dat_date) = MONTH('", P2, "')
	WHEN '", P1, "' = 'THIS YEAR' THEN YEAR(s.dat_date) = YEAR('", P2, "')
	ELSE DATE(s.dat_date) BETWEEN DATE('", P2, "') AND DATE('", P3, "') END) 
	AND
	IF('", P4, "' = 'ALL', TRUE, s.var_type = '", P4, "')
	AND
	IF('", P5, "' = 'ALL', s.var_status IN ('Open','Posted'), s.var_status = '", P5, "') 
	AND
	IF('", P6, "' = 'ALL', TRUE, s.var_locid >= '", P6, "')
	AND
	IF('", P7, "' = 'ALL', TRUE, s.var_locid <= '", P7, "')
	AND
	IF('", P8, "' = 'ALL', TRUE, s.var_empid >= '", P8, "')
	AND
	IF('", P9, "' = 'ALL', TRUE, s.var_empid <= '", P9, "')
	AND
	IF('", P10, "' = 'ALL', TRUE, s.var_cusid >= '", P10, "')
	AND
	IF('", P11, "' = 'ALL', TRUE, s.var_cusid <= '", P11, "') ");
	SET @SQL_EXC = CONCAT(@DETAIL," GROUP BY s.var_id ",@ORDERBY);
	#SELECT @SQL_EXC;

	PREPARE STM FROM @SQL_EXC;
	EXECUTE STM;
	DEALLOCATE PREPARE STM;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_rep_sale_by_shift`;
DELIMITER |
CREATE PROCEDURE `pos_pro_rep_sale_by_shift`(IN P1 varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
	COALESCE(sd.var_id,'') AS SalID,
	COALESCE(sd.var_shiftid,'') AS ShiftNo,
	COALESCE(sd.dou_sub,0) AS TotalAmt,
	COALESCE(sd.dou_disdol,0) AS DiscountDollar,
	COALESCE(sd.dou_taxdol,0) AS TaxDollar,
	0 AS ServiceChargeDol,
	COALESCE(sd.dou_net,0) AS NetTotalAmt,
	COALESCE(sd.dou_paid,0) AS ReceiveAmtTotal,
	COALESCE(sd.dou_change,0) AS ChangeAmt,
	s.dat_in AS indatetime,
	s.dat_out AS outdatetime
	FROM pos_ar_in sd
	LEFT JOIN pos_shift s ON sd.var_shiftid = s.var_id
	WHERE sd.var_shiftid = P1 AND sd.var_status IN ('Open','Posted')
	ORDER BY SalID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_rep_sale_by_shift_his`;
DELIMITER |
CREATE PROCEDURE `pos_pro_rep_sale_by_shift_his`(IN P1 varchar(255))
    DETERMINISTIC
BEGIN
	SELECT
	'ADD' AS EditType,sh.dat_date AS edtdate,COALESCE(sh.dou_addusd,0) AS USD,COALESCE(sh.dou_addkhr,0) AS KHR,COALESCE(sh.var_desc,'') Description,s.dat_in AS indatetime,s.dat_out AS outdatetime
	FROM pos_shift_his sh JOIN pos_shift s ON sh.var_shiftid = s.var_id
	WHERE sh.var_shiftid = P1 AND (sh.dou_addusd > 0 OR sh.dou_addkhr > 0)
	UNION ALL
	SELECT
	'TAKE' AS EditType,sh.dat_date AS edtdate,COALESCE(sh.dou_takeusd,0) AS USD,COALESCE(sh.dou_takekhr,0) AS KHR,COALESCE(sh.var_desc,'') Description,s.dat_in AS indatetime,s.dat_out AS outdatetime
	FROM pos_shift_his sh JOIN pos_shift s ON sh.var_shiftid = s.var_id
	WHERE sh.var_shiftid = P1 AND (sh.dou_takeusd > 0 OR sh.dou_takekhr > 0)
	ORDER BY EditType,edtdate;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_rep_sale_by_shift_item`;
DELIMITER |
CREATE PROCEDURE `pos_pro_rep_sale_by_shift_item`(IN P1 varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
	COALESCE(sd.var_itemid,'') AS ItemID,
	COALESCE(i.var_name) AS ItemName,
	'' AS openitemdes,
	sd.var_uomid,
	SUM(COALESCE(sd.dou_qty,0)) AS Qty,
	SUM(COALESCE(sd.dou_sub,0)) AS TotalAmt,
	SUM(COALESCE(sd.dou_disdol,0)) AS DisDol,
	SUM(COALESCE(sd.dou_taxdol,0)) AS TaxDol,
	SUM(COALESCE(0,0)) AS ServiceChargeDol,
	SUM(COALESCE(sd.dou_net,0)) AS NetTotalAmt,
	sst.dat_in AS indatetime,
	sst.dat_out AS outdatetime,
	COALESCE(ip.var_id,'') AS ItemGroupID,
	COALESCE(ip.var_name,'') AS ItemGroupName
	FROM pos_ar_in_det sd 
	JOIN pos_ar_in s ON s.var_id = sd.var_id AND s.var_shiftid = P1
	JOIN pos_shift sst ON sst.var_id = s.var_shiftid
	LEFT JOIN ame_mt_ite i ON i.var_id = sd.var_itemid
	LEFT JOIN ame_mt_ite_gro ip ON ip.var_id = i.var_groupid
	GROUP BY sd.var_itemid,sd.var_uomid
	ORDER BY ip.var_id,sd.var_itemid,sd.var_uomid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_rep_set`;
DELIMITER |
CREATE PROCEDURE `pos_pro_rep_set`(IN InvID varchar(255))
    DETERMINISTIC
BEGIN
SELECT 
REPLACE(GROUP_CONCAT(COALESCE(ps.var_name,'') SEPARATOR ';'),';','\n') AS var_name,
REPLACE(GROUP_CONCAT(CONCAT(COALESCE(c.var_symbol,'')," ",FORMAT(COALESCE(s.dou_amt,0),IF(COALESCE(c.var_symbol,'') = '៛',0,2))) SEPARATOR ';'),';','\n') dou_amt,
REPLACE(GROUP_CONCAT(COALESCE(s.dou_rate,0) SEPARATOR ';'),';','\n') AS dou_rate
FROM pos_ar_in_pay_met s INNER JOIN pos_pay_met ps ON s.var_setid = ps.var_id INNER JOIN ame_mt_cur c ON s.var_cur = c.var_id
WHERE s.var_salid = InvID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_rep_shift`;
DELIMITER |
CREATE PROCEDURE `pos_pro_rep_shift`(IN P1 varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 
	COALESCE(sh.var_id,'') AS ShiftID,
	COALESCE(sh.var_macid,'') AS MacID,
	COALESCE(sh.var_locid,'') AS var_locid,
	COALESCE(sh.var_status,'') AS `Status`,
	COALESCE(sh.var_uid_in,'') AS UID_IN,
	COALESCE((SELECT e.var_name FROM ame_mt_emp e WHERE e.var_id = sh.var_uid_in LIMIT 1),'') AS UName_IN,
	sh.dat_in,
	COALESCE(sh.dou_in_usd,0) AS dou_in_usd,
	COALESCE(sh.dou_in_khr,0) AS dou_in_khr,
	COALESCE(sh.dou_in_total,0) AS dou_in_total,
	COALESCE(sh.var_uid_out,'') AS var_uid_out,
	COALESCE((SELECT e.var_name FROM ame_mt_emp e WHERE e.var_id = sh.var_uid_out LIMIT 1),'') AS UName_OUT,
	sh.dat_out,
	COALESCE(sh.dou_exrate,0) AS dou_exrate,
	COALESCE(sh.dou_d1,0) AS dou_d1,
	COALESCE(sh.dou_d2,0) AS dou_d2,
	COALESCE(sh.dou_d5,0) AS dou_d5,
	COALESCE(sh.dou_d10,0) AS dou_d10,
	COALESCE(sh.dou_d20,0) AS dou_d20,
	COALESCE(sh.dou_d50,0) AS dou_d50,
	COALESCE(sh.dou_d100,0) AS dou_d100,
	COALESCE(sh.dou_d_total,0) AS dou_d_total,
	COALESCE(sh.dou_r100,0) AS dou_r100,
	COALESCE(sh.dou_r200,0) AS dou_r200,
	COALESCE(sh.dou_r500,0) AS dou_r500,
	COALESCE(sh.dou_r1000,0) AS dou_r1000,
	COALESCE(sh.dou_r2000,0) AS dou_r2000,
	COALESCE(sh.dou_r5000,0) AS dou_r5000,
	COALESCE(sh.dou_r10000,0) AS dou_r10000,
	COALESCE(sh.dou_r20000,0) AS dou_r20000,
	COALESCE(sh.dou_r50000,0) AS dou_r50000,
	COALESCE(sh.dou_r100000,0) AS dou_r100000,
	COALESCE(sh.dou_r_total,0) AS dou_r_total,
	COALESCE(sh.dou_out_total,0) AS dou_out_total,
	COALESCE(SUM(s.dou_sub),0) AS INV_GROSS_SALE,
	COALESCE(SUM(s.dou_disdol),0) AS INV_DISDOL,
	COALESCE(SUM(s.dou_taxdol),0) AS INV_VAT,
	COALESCE(SUM(s.dou_net),0) AS INV_NET,
	(SELECT COUNT(s.var_id) FROM pos_ar_in s WHERE s.var_shiftid = sh.var_id AND s.var_status IN ('Open','Posted')) AS Count_Inv,
	(SELECT COUNT(s.var_id) FROM pos_ar_in s WHERE s.var_shiftid = sh.var_id AND s.var_status NOT IN ('Open','Posted')) AS Count_Void,
	l.var_inv_logo,
	l.var_name
	FROM pos_shift sh LEFT JOIN pos_ar_in s ON sh.var_id = s.var_shiftid AND s.var_status IN ('Open','Posted')
	LEFT JOIN ame_mt_loc l ON sh.var_locid = l.var_id
	WHERE sh.var_id = P1
	GROUP BY sh.var_id;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_return_inv`;
DELIMITER |
CREATE PROCEDURE `pos_pro_return_inv`(IN var_SalID varchar(255),IN var_StationID varchar(255),IN int_BillNo int(11))
    DETERMINISTIC
BEGIN
	INSERT INTO pos_temp_order
	(stationid,
	lineno,
	itemid,
	ItemCode,
	itemname,
	salqty,
	uomid,
	unitprice,
	totalamt,
	discountpercent,
	discountdollar,
	nettotalamtbeforetax,
	staxpercent,
	staxdollar,
	vatpercent,
	vatdollar,
	taxdollar,
	nettotalamtaftertax,
	qtysendtokitchen,
	isrentalitem,
	billnum,
	openitemdes,
	servicechargeper,
	servicechargedol,
	BundleSalID,
	ItemBundleID,
	UOMBundleID)
	SELECT
	var_StationID,
	sd.int_line,
	sd.var_itemid,
	i.var_itemcode,
	i.var_name,
	-sd.dou_qty,
	sd.var_uomid,
	sd.dou_price,
	-sd.dou_sub,
	sd.dou_disper,
	-sd.dou_disdol,
	-(sd.dou_sub - sd.dou_disdol),
	sd.dou_taxper1,
	-sd.dou_taxdol1,
	sd.dou_taxper,
	-sd.dou_taxdol,
	-(sd.dou_taxdol + sd.dou_taxdol1),
	-sd.dou_net,
	0,
	0,
	int_BillNo,
	i.var_name,
	0,
	0,
	'',
	'',
	''
	FROM pos_ar_in_det sd
	LEFT JOIN ame_mt_ite i on sd.var_itemid = i.var_id
	WHERE sd.var_id = var_SalID;
	CALL POS_SelectStation_Item(var_StationID);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `pos_pro_search_shift`;
DELIMITER |
CREATE PROCEDURE `pos_pro_search_shift`(IN P1 varchar(255),IN FDate datetime,IN TDate datetime,IN var_LocationID varchar(255),IN var_MachineID varchar(255))
    DETERMINISTIC
BEGIN
	#'%%','2017-01-01','2018-12-01','L003','D0A7FE32'
	SELECT 
	COALESCE(sh.var_id,'') AS shiftNo,
	COALESCE((SELECT e.var_name FROM ame_mt_emp e WHERE e.var_id = sh.var_uid_in LIMIT 1),'') AS InUserName,
	sh.dat_in AS inDateTime,
	COALESCE(sh.dou_in_total,0) AS cashInAmt,
	COALESCE((SELECT e.var_name FROM ame_mt_emp e WHERE e.var_id = sh.var_uid_out LIMIT 1),'') AS OutUserName,
	sh.dat_out AS outDateTime,
	COALESCE(sh.dou_out_total,0) AS cashOutAmt,
	(SELECT COUNT(s.var_id) FROM pos_ar_in s WHERE s.var_shiftid = sh.var_id AND s.var_status IN ('Open','Posted')) AS invCount,
	(SELECT COUNT(s.var_id) FROM pos_ar_in s WHERE s.var_shiftid = sh.var_id AND s.var_status NOT IN ('Open','Posted')) AS VoidCount,
	COALESCE(SUM(s.dou_net),0) AS SaleAmount
	FROM pos_shift sh LEFT JOIN pos_ar_in s ON sh.var_id = s.var_shiftid AND s.var_status IN ('Open','Posted')
	WHERE sh.var_id LIKE P1
	AND DATE(sh.dat_in) BETWEEN DATE(FDate) AND TDate
	AND sh.var_locid = var_LocationID
	AND sh.var_macid = var_MachineID 
	GROUP BY sh.var_id;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_PRO_SYS_LOAD_LANG`;
DELIMITER |
CREATE PROCEDURE `POS_PRO_SYS_LOAD_LANG`(IN var_FormName varchar(255))
    DETERMINISTIC
BEGIN
	SELECT
	COALESCE(L.keyword,'') AS keyword,
	COALESCE(L.formname,'') AS formname,
	COALESCE(L1.ENG,'') AS ENG,
	COALESCE(L1.KH,'') AS KH,
	COALESCE(L1.CHI,'') AS CHI,
	COALESCE(L.Img,'') AS Img
	FROM
	pos_sys_form_lang L LEFT JOIN pos_sys_lang_det L1 ON L.LangID = L1.LangID
	WHERE L.formname = var_FormName;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `POS_SelectStation_Item`;
DELIMITER |
CREATE PROCEDURE `POS_SelectStation_Item`(IN var_StationID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT
	COALESCE(o.stationid,'') AS stationid,
	COALESCE(o.lineno,1) AS lineno,
	COALESCE(o.itemid,'') AS itemid,
	COALESCE(o.ItemCode,'') AS ItemCode,
	COALESCE(o.itemname,'') AS itemname,
	COALESCE(o.salqty,0) AS salqty,
	COALESCE(o.uomid,'') AS uomid,
	COALESCE(o.unitprice,0) AS unitprice,
	COALESCE(o.totalamt,0) AS totalamt,
	COALESCE(o.discountpercent,0) AS discountpercent,
	COALESCE(o.discountdollar,0) AS discountdollar,
	COALESCE(o.nettotalamtbeforetax,0) AS nettotalamtbeforetax,
	COALESCE(o.staxpercent,0) AS staxpercent,
	COALESCE(o.staxdollar,0) AS staxdollar,
	COALESCE(o.vatpercent,0) AS vatpercent,
	COALESCE(o.vatdollar,0) AS vatdollar,
	COALESCE(o.taxdollar,0) AS taxdollar,
	COALESCE(o.nettotalamtaftertax,0) AS nettotalamtaftertax,
	COALESCE(o.qtysendtokitchen,0) AS qtysendtokitchen,
	COALESCE(o.isrentalitem,0) AS isrentalitem,
	COALESCE(o.billnum,1) AS billnum,
	COALESCE(o.openitemdes,'') AS openitemdes,
	COALESCE(o.servicechargeper,0) AS servicechargeper,
	COALESCE(o.servicechargedol,0) AS servicechargedol,
	COALESCE(o.BundleSalID,'') AS BundleSalID,
	COALESCE(o.ItemBundleID,'') AS ItemBundleID,
	COALESCE(o.UOMBundleID,'') AS UOMBundleID,
	COALESCE(o.Sort,0) AS Sort
	FROM pos_temp_order o
	WHERE o.stationid = var_StationID
	ORDER BY o.lineno;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `reportMarketingExecLeadsByCampaigns`;
DELIMITER |
CREATE PROCEDURE `reportMarketingExecLeadsByCampaigns`()
    DETERMINISTIC
BEGIN
	SELECT 
		camp.CA_ID AS campId,
		camp.CA_Name AS campName,
		CONCAT(lead.LA_Salutation," ",lead.LA_FirstName," ",lead.LA_LastName) AS leadName,
		lead.LA_AccountName AS company,
		lead.LA_State AS state,
		lead.LA_Email AS email,
		st.LST_Name AS leadStatus,
		CAST(lead.LA_CDate AS DATE) AS createdDate,
		lead.LA_CBy AS createdBy
		FROM 
			crm_lead lead 
			INNER JOIN 
				crm_camp camp
					ON lead.LA_CA_ID = camp.CA_ID
			INNER JOIN 
				crm_lead_status st
					ON st.LST_ID = lead.LA_StatusID
			ORDER BY camp.CA_ID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `reportMarketingExecLeadsByIndustry`;
DELIMITER |
CREATE PROCEDURE `reportMarketingExecLeadsByIndustry`()
    DETERMINISTIC
BEGIN
	SELECT I_Name AS industry, (SELECT COUNT(LA_ID) FROM crm_lead WHERE LA_IndustID = I_ID) AS count FROM crm_industry;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `reportMarketingExecLeadTrendsByStatus`;
DELIMITER |
CREATE PROCEDURE `reportMarketingExecLeadTrendsByStatus`()
    DETERMINISTIC
BEGIN
	SELECT DISTINCT
	DATE(LA_CDate) AS createdDate,
	(
		SELECT
			COUNT(l.LA_ID)
		FROM
			crm_lead l
		WHERE
			DATE(l.LA_CDate) = DATE(ll.LA_CDate)
		AND l.LA_StatusID = 1
	) AS 'New',
	(
		SELECT
			COUNT(l.LA_ID)
		FROM
			crm_lead l
		WHERE
			DATE(l.LA_CDate) = DATE(ll.LA_CDate)
		AND l.LA_StatusID = 2
	) AS 'Assigned',
	(
		SELECT
			COUNT(l.LA_ID)
		FROM
			crm_lead l
		WHERE
			DATE(l.LA_CDate) = DATE(ll.LA_CDate)
		AND l.LA_StatusID = 3
	) AS 'In Process',
	(
		SELECT
			COUNT(l.LA_ID)
		FROM
			crm_lead l
		WHERE
			DATE(l.LA_CDate) = DATE(ll.LA_CDate)
		AND l.LA_StatusID = 4
	) AS 'Converted',
	(
		SELECT
			COUNT(l.LA_ID)
		FROM
			crm_lead l
		WHERE
			DATE(l.LA_CDate) = DATE(ll.LA_CDate)
		AND l.LA_StatusID = 5
	) AS 'Dead'
FROM
	crm_lead ll;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `reportMarketingLeadsExecBySource`;
DELIMITER |
CREATE PROCEDURE `reportMarketingLeadsExecBySource`()
    DETERMINISTIC
BEGIN
	SELECT DISTINCT
	sou.LS_Name AS leadSource,
	DATE(l.LA_CDate) AS createdDate,
	(
		SELECT
			COUNT(ll.LA_ID)
		FROM
			crm_lead ll
		WHERE
			ll.LA_CDate = l.LA_CDate
		AND ll.LA_SourceID = sou.LS_ID
	) AS recordCount
FROM
	crm_lead_source sou
INNER JOIN crm_lead l ON sou.LS_ID = l.LA_SourceID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddAllowance`;
DELIMITER |
CREATE PROCEDURE `spHRMAddAllowance`(userid varchar(255),SName varchar(255),SValue text,SValue2 text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE tz VARCHAR(20) DEFAULT('');

	IF SValue != "" THEN

		SELECT COUNT(*) INTO CheckExist FROM hrm_payroll_allowance WHERE LOWER(Allowance_Name) = SName;

			IF CheckExist <= 0 THEN

				CALL spHRMGetNumberPrefix("Allowance", ID);
	
				SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_allowance(Allowance_ID,Allowance_Name,Allowance_PayType,Allowance_PayAmount) VALUES ", SValue, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				IF SValue2 != "" THEN
					SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';

					SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_allowance_history(Allowance_ID,Allowance_Date,Allowance_PayType,Allowance_PayAmount) VALUES ", SValue2, ";");
					SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
					SET @SQL1 = REPLACE(@SQL1, 'Temp_Now',DATE_FORMAT(convert_tz(now(), @@session.time_zone, tz), '%Y-%m-%d'));
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;
				END IF;

				CALL spHRMUpdateNumberPrefix("Allowance");

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Allowance', ID);

				SELECT ID;

				CALL hrm_message('1100101', 'Allowance', 'create', ID);

			ELSE
				SET ID = "exist";
				SELECT ID;
				CALL hrm_message('1100104', 'Allowance', 'exist', SName);
			END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddAttendanceNormal`;
DELIMITER |
CREATE PROCEDURE `spHRMAddAttendanceNormal`(SEmpID varchar(255),ShiftID varchar(255), FP_ID varchar(255), FP_Date Date, FP_Punch1 Time, FP_Punch2 Time, FP_Punch3 Time, FP_Punch4 Time, FP_Punch5 Time, FP_Punch6 Time, FP_Punch7 Time, FP_Punch8 Time, FP_Punch9 Time, FP_Punch10 Time)
    DETERMINISTIC
BEGIN
		DECLARE Shift_ID VARCHAR(255);
		DECLARE Shift_Day VARCHAR(255);
		DECLARE Shift_TotalWorkHour FLOAT DEFAULT(0);
		DECLARE Shift_TimeIn1 TIME;
		DECLARE Shift_TimeInPeriod1 TIME;
		DECLARE Shift_TimeOut1 TIME;
		DECLARE Shift_TimeOutPeriod1 TIME;
		DECLARE Shift_TimeIn2 TIME;
		DECLARE Shift_TimeInPeriod2 TIME;
		DECLARE Shift_TimeOut2 TIME;
		DECLARE Shift_TimeOutPeriod2 TIME;
		DECLARE Shift_TimeIn3 TIME;
		DECLARE Shift_TimeInPeriod3 TIME;
		DECLARE Shift_TimeOut3 TIME;
		DECLARE Shift_TimeOutPeriod3 TIME;
		DECLARE Shift_TimeIn4 TIME;
		DECLARE Shift_TimeInPeriod4 TIME;
		DECLARE Shift_TimeOut4 TIME;
		DECLARE Shift_TimeOutPeriod4 TIME;
		DECLARE Shift_TimeIn5 TIME;
		DECLARE Shift_TimeInPeriod5 TIME;
		DECLARE Shift_TimeOut5 TIME;
		DECLARE Shift_TimeOutPeriod5 TIME;
		DECLARE Shift_TimeInOvertime TIME;
		DECLARE Shift_TimeOutOvertime TIME;

		DECLARE Shift_TimeIn1LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut1LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn2LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut2LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn3LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut3LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn4LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut4LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn5LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut5LateAmt INT DEFAULT(0);

		DECLARE CheckExist TINYINT DEFAULT(0);

		DECLARE TotalCheckLate TINYINT DEFAULT(0);
		DECLARE TotalCheckLateDuration TIME DEFAULT('00:00:00');
		DECLARE TotalcheckLateDurationDeduct TIME DEFAULT('00:00:00');

		DECLARE CheckLateIn1 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn1 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn1 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn2 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn2 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn2 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn3 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn3 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn3 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn4 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn4 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn4 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn5 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn5 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn5 TIME DEFAULT('00:00:00');

		DECLARE CheckLateOut1 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut1 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut1 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut2 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut2 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut2 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut3 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut3 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut3 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut4 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut4 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut4 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut5 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut5 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut5 TIME DEFAULT('00:00:00');

		DECLARE LeaveDurationStatus VARCHAR(255) DEFAULT('');
		DECLARE LeaveDurationInOut1 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut2 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut3 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut4 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut5 TIME DEFAULT('00:00:00');

		DECLARE CheckOutLeave VARCHAR(255) DEFAULT('');
		DECLARE CheckOutLeaveInOut VARCHAR(255) DEFAULT('');

		DECLARE CheckAb TINYINT DEFAULT(0);
		DECLARE checkAbDurationDeduct TIME DEFAULT('00:00:00');
		DECLARE CheckL TINYINT DEFAULT(0);
		DECLARE S VARCHAR(255) DEFAULT('');

		DECLARE In1 TIME DEFAULT('00:00:00');
		DECLARE In2 TIME DEFAULT('00:00:00');
		DECLARE In3 TIME DEFAULT('00:00:00');
		DECLARE In4 TIME DEFAULT('00:00:00');
		DECLARE In5 TIME DEFAULT('00:00:00');
		DECLARE Out1 TIME DEFAULT('00:00:00');
		DECLARE Out2 TIME DEFAULT('00:00:00');
		DECLARE Out3 TIME DEFAULT('00:00:00');
		DECLARE Out4 TIME DEFAULT('00:00:00');
		DECLARE Out5 TIME DEFAULT('00:00:00');
		DECLARE OverIn TIME DEFAULT('00:00:00');
		DECLARE OverOut TIME DEFAULT('00:00:00');
		DECLARE O1 TIME DEFAULT('00:00:00');
		DECLARE O2 TIME DEFAULT('00:00:00');
		DECLARE WorkHour INT DEFAULT(0);

		DECLARE TimeBreak1 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak2 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak3 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak4 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak5 VARCHAR(255) DEFAULT('');

		
		SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TotalWorkHour,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,wd.Shift_TimeIn1LateDuration,wd.Shift_TimeOut1LateDuration,wd.Shift_TimeIn2LateDuration,wd.Shift_TimeOut2LateDuration,wd.Shift_TimeIn3LateDuration,wd.Shift_TimeOut3LateDuration,wd.Shift_TimeIn4LateDuration,wd.Shift_TimeOut4LateDuration,wd.Shift_TimeIn5LateDuration,wd.Shift_TimeOut5LateDuration,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 INTO Shift_ID, Shift_Day, Shift_TotalWorkHour, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime, Shift_TimeIn1LateAmt, Shift_TimeOut1LateAmt, Shift_TimeIn2LateAmt, Shift_TimeOut2LateAmt, Shift_TimeIn3LateAmt, Shift_TimeOut3LateAmt, Shift_TimeIn4LateAmt, Shift_TimeOut4LateAmt, Shift_TimeIn5LateAmt, Shift_TimeOut5LateAmt, TimeBreak1, TimeBreak2, TimeBreak3, TimeBreak4, TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = ShiftID AND LOWER(wd.Shift_Day) = LOWER(DAYNAME(FP_DATE)); 

		SELECT COUNT(*) INTO CheckExist FROM  hrm_timesheet_attendance att WHERE att.Att_FPID = FP_ID AND att.Att_Date = FP_Date;
		IF CheckExist > 0 THEN
			SELECT Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_Status,Att_LeaveDurationInOut1,Att_LeaveDurationInOut2,Att_LeaveDurationInOut3,Att_LeaveDurationInOut4,Att_LeaveDurationInOut5,Att_LeaveDurationStatus,Att_OutLeave,Att_OutLeaveInOut INTO FP_ID,FP_Date,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,S,LeaveDurationInOut1,LeaveDurationInOut2,LeaveDurationInOut3,LeaveDurationInOut4,LeaveDurationInOut5,LeaveDurationStatus,CheckOutLeave,CheckOutLeaveInOut FROM hrm_timesheet_attendance att WHERE att.Att_FPID = FP_ID AND att.Att_Date = FP_Date;
		END IF;

				-- Punch1
				IF FP_Punch1 <> '00:00:00' AND FP_Punch1 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch1, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch1;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch1;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch1 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch1;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch1 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch1 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch1 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch1 AND Shift_TimeInPeriod2 >= FP_Punch1 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch1 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch1 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch1 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch1 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch1 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch1 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch1 AND Shift_TimeInPeriod3 >= FP_Punch1 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch1 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch1 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch1 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch1 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch1 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch1 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch1 AND Shift_TimeInPeriod4 >= FP_Punch1 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch1 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch1 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch1 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch1 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch1;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch1 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch1;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch1 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch1 AND Shift_TimeInPeriod5 >= FP_Punch1 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch1 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch1 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch1 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch1 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch1 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch1 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch1;
					ELSEIF Shift_TimeInOvertime <= FP_Punch1 AND Shift_TimeOutOvertime >= FP_Punch1 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch1;
					ELSEIF Shift_TimeInOvertime <= FP_Punch1 AND Shift_TimeOutOvertime >= FP_Punch1 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch1;
					ELSEIF O1 = '00:00:00' AND FP_Punch1 != In1 AND FP_Punch1 != Out1 AND FP_Punch1 != In2 AND FP_Punch1 != Out2 AND FP_Punch1 != In3 AND FP_Punch1 != Out3 AND FP_Punch1 != In4 AND FP_Punch1 != Out4 AND FP_Punch1 != In5 AND FP_Punch1 != Out5 THEN
						SET O1 = FP_Punch1;
					ELSEIF O2 = '00:00:00' AND FP_Punch1 != In1 AND FP_Punch1 != Out1 AND FP_Punch1 != In2 AND FP_Punch1 != Out2 AND FP_Punch1 != In3 AND FP_Punch1 != Out3 AND FP_Punch1 != In4 AND FP_Punch1 != Out4 AND FP_Punch1 != In5 AND FP_Punch1 != Out5 THEN
						SET O2 = FP_Punch1;
					END IF;
				END IF;
				
				-- Punch2
				IF FP_Punch2 > FP_Punch1 AND FP_Punch2 <> '00:00:00' AND FP_Punch2 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch2, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch2;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch2;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch2 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch2;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch2 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch2 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch2 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch2;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch2 AND Shift_TimeInPeriod2 >= FP_Punch2 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch2 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch2;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch2 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch2 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch2 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch2 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch2 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch2 AND Shift_TimeInPeriod3 >= FP_Punch2 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch2 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch2 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch2 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch2 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch2 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch2 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch2 AND Shift_TimeInPeriod4 >= FP_Punch2 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch2 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch2 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch2 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch2 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch2;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch2 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch2;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch2 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch2 AND Shift_TimeInPeriod5 >= FP_Punch2 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch2 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch2 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch2 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch2 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch2 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch2 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch2;
					ELSEIF Shift_TimeInOvertime <= FP_Punch2 AND Shift_TimeOutOvertime >= FP_Punch2 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch2;
					ELSEIF Shift_TimeInOvertime <= FP_Punch2 AND Shift_TimeOutOvertime >= FP_Punch2 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch2;
					ELSEIF O1 = '00:00:00' AND FP_Punch2 != In1 AND FP_Punch2 != Out1 AND FP_Punch2 != In2 AND FP_Punch2 != Out2 AND FP_Punch2 != In3 AND FP_Punch2 != Out3 AND FP_Punch2 != In4 AND FP_Punch2 != Out4 AND FP_Punch2 != In5 AND FP_Punch2 != Out5 THEN
						SET O1 = FP_Punch2;
					ELSEIF O2 = '00:00:00' AND FP_Punch2 != In1 AND FP_Punch2 != Out1 AND FP_Punch2 != In2 AND FP_Punch2 != Out2 AND FP_Punch2 != In3 AND FP_Punch2 != Out3 AND FP_Punch2 != In4 AND FP_Punch2 != Out4 AND FP_Punch2 != In5 AND FP_Punch2 != Out5 THEN
						SET O2 = FP_Punch2;
					END IF;
				END IF;

				-- Punch3
				IF FP_Punch3 > FP_Punch2 AND FP_Punch3 <> '00:00:00' AND FP_Punch3 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch3, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch3;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch3;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch3 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch3;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch3 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch3 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch3 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch3;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch3 AND Shift_TimeInPeriod2 >= FP_Punch3 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch3 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch3;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch3 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch3 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch3 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch3 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch3 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch3 AND Shift_TimeInPeriod3 >= FP_Punch3 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch3 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch3 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch3 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch3 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch3 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch3 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch3 AND Shift_TimeInPeriod4 >= FP_Punch3 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch3 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch3 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch3 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch3 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch3;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch3 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch3;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch3 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch3 AND Shift_TimeInPeriod5 >= FP_Punch3 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch3 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch3 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch3 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch3 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch3 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch3 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch3;
					ELSEIF Shift_TimeInOvertime <= FP_Punch3 AND Shift_TimeOutOvertime >= FP_Punch3 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch3;
					ELSEIF Shift_TimeInOvertime <= FP_Punch3 AND Shift_TimeOutOvertime >= FP_Punch3 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch3;
					ELSEIF O1 = '00:00:00' AND FP_Punch3 != In1 AND FP_Punch3 != Out1 AND FP_Punch3 != In2 AND FP_Punch3 != Out2 AND FP_Punch3 != In3 AND FP_Punch3 != Out3 AND FP_Punch3 != In4 AND FP_Punch3 != Out4 AND FP_Punch3 != In5 AND FP_Punch3 != Out5 THEN
						SET O1 = FP_Punch3;
					ELSEIF O2 = '00:00:00' AND FP_Punch3 != In1 AND FP_Punch3 != Out1 AND FP_Punch3 != In2 AND FP_Punch3 != Out2 AND FP_Punch3 != In3 AND FP_Punch3 != Out3 AND FP_Punch3 != In4 AND FP_Punch3 != Out4 AND FP_Punch3 != In5 AND FP_Punch3 != Out5 THEN
						SET O2 = FP_Punch3;
					END IF;
				END IF;

				-- Punch4
				IF FP_Punch4 > FP_Punch3 AND FP_Punch4 <> '00:00:00' AND FP_Punch4 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch4, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch4;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch4;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch4 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch4;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch4 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch4 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch4 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch4;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch4 AND Shift_TimeInPeriod2 >= FP_Punch4 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch4 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch4;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch4 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch4 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch4 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch4 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch4 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch4 AND Shift_TimeInPeriod3 >= FP_Punch4 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch4 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch4 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch4 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch4 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch4 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch4 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch4 AND Shift_TimeInPeriod4 >= FP_Punch4 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch4 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch4 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch4 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch4 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch4;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch4 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch4;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch4 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch4 AND Shift_TimeInPeriod5 >= FP_Punch4 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch4 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch4 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch4 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch4 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch4 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch4 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch4;
					ELSEIF Shift_TimeInOvertime <= FP_Punch4 AND Shift_TimeOutOvertime >= FP_Punch4 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch4;
					ELSEIF Shift_TimeInOvertime <= FP_Punch4 AND Shift_TimeOutOvertime >= FP_Punch4 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch4;
					ELSEIF O1 = '00:00:00' AND FP_Punch4 != In1 AND FP_Punch4 != Out1 AND FP_Punch4 != In2 AND FP_Punch4 != Out2 AND FP_Punch4 != In3 AND FP_Punch4 != Out3 AND FP_Punch4 != In4 AND FP_Punch4 != Out4 AND FP_Punch4 != In5 AND FP_Punch4 != Out5 THEN
						SET O1 = FP_Punch4;
					ELSEIF O2 = '00:00:00' AND FP_Punch4 != In1 AND FP_Punch4 != Out1 AND FP_Punch4 != In2 AND FP_Punch4 != Out2 AND FP_Punch4 != In3 AND FP_Punch4 != Out3 AND FP_Punch4 != In4 AND FP_Punch4 != Out4 AND FP_Punch4 != In5 AND FP_Punch4 != Out5 THEN
						SET O2 = FP_Punch4;
					END IF;
				END IF;

				-- Punch5
				IF FP_Punch5 > FP_Punch4 AND FP_Punch5 <> '00:00:00' AND FP_Punch5 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch5, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch5;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch5;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch5 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch5;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch5 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch5 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch5 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch5;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch5 AND Shift_TimeInPeriod2 >= FP_Punch5 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch5 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch5;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch5 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch5 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch5 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch5 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch5 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch5 AND Shift_TimeInPeriod3 >= FP_Punch5 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch5 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch5 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch5 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch5 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch5 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch5 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch5 AND Shift_TimeInPeriod4 >= FP_Punch5 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch5 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch5 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch5 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch5 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch5;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch5 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch5;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch5 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch5 AND Shift_TimeInPeriod5 >= FP_Punch5 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch5 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch5 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch5 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch5 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch5 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch5 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch5;
					ELSEIF Shift_TimeInOvertime <= FP_Punch5 AND Shift_TimeOutOvertime >= FP_Punch5 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch5;
					ELSEIF Shift_TimeInOvertime <= FP_Punch5 AND Shift_TimeOutOvertime >= FP_Punch5 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch5;
					ELSEIF O1 = '00:00:00' AND FP_Punch5 != In1 AND FP_Punch5 != Out1 AND FP_Punch5 != In2 AND FP_Punch5 != Out2 AND FP_Punch5 != In3 AND FP_Punch5 != Out3 AND FP_Punch5 != In4 AND FP_Punch5 != Out4 AND FP_Punch5 != In5 AND FP_Punch5 != Out5 THEN
						SET O1 = FP_Punch5;
					ELSEIF O2 = '00:00:00' AND FP_Punch5 != In1 AND FP_Punch5 != Out1 AND FP_Punch5 != In2 AND FP_Punch5 != Out2 AND FP_Punch5 != In3 AND FP_Punch5 != Out3 AND FP_Punch5 != In4 AND FP_Punch5 != Out4 AND FP_Punch5 != In5 AND FP_Punch5 != Out5 THEN
						SET O2 = FP_Punch5;
					END IF;
				END IF;

				-- Punch6
				IF FP_Punch6 > FP_Punch5 AND FP_Punch6 <> '00:00:00' AND FP_Punch6 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch6, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch6;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch6;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch6 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch6;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch6 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch6 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch6 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch6;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch6 AND Shift_TimeInPeriod2 >= FP_Punch6 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch6 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch6;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch6 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch6 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch6 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch6 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch6 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch6 AND Shift_TimeInPeriod3 >= FP_Punch6 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch6 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch6 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch6 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch6 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch6 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch6 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch6 AND Shift_TimeInPeriod4 >= FP_Punch6 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch6 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch6 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch6 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch6 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch6;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch6 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch6;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch6 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch6 AND Shift_TimeInPeriod5 >= FP_Punch6 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch6 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch6 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch6 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch6 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch6 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch6 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch6;
					ELSEIF Shift_TimeInOvertime <= FP_Punch6 AND Shift_TimeOutOvertime >= FP_Punch6 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch6;
					ELSEIF Shift_TimeInOvertime <= FP_Punch6 AND Shift_TimeOutOvertime >= FP_Punch6 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch6;
					ELSEIF O1 = '00:00:00' AND FP_Punch6 != In1 AND FP_Punch6 != Out1 AND FP_Punch6 != In2 AND FP_Punch6 != Out2 AND FP_Punch6 != In3 AND FP_Punch6 != Out3 AND FP_Punch6 != In4 AND FP_Punch6 != Out4 AND FP_Punch6 != In5 AND FP_Punch6 != Out5 THEN
						SET O1 = FP_Punch6;
					ELSEIF O2 = '00:00:00' AND FP_Punch6 != In1 AND FP_Punch6 != Out1 AND FP_Punch6 != In2 AND FP_Punch6 != Out2 AND FP_Punch6 != In3 AND FP_Punch6 != Out3 AND FP_Punch6 != In4 AND FP_Punch6 != Out4 AND FP_Punch6 != In5 AND FP_Punch6 != Out5 THEN
						SET O2 = FP_Punch6;
					END IF;
				END IF;

				-- Punch7
				IF FP_Punch7 > FP_Punch6 AND FP_Punch7 <> '00:00:00' AND FP_Punch7 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch7, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch7;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch7;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch7 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch7;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch7 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch7 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch7 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch7;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch7 AND Shift_TimeInPeriod2 >= FP_Punch7 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch7 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch7;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch7 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch7 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch7 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch7 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch7 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch7 AND Shift_TimeInPeriod3 >= FP_Punch7 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch7 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch7 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch7 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch7 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch7 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch7 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch7 AND Shift_TimeInPeriod4 >= FP_Punch7 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch7 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch7 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch7 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch7 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch7;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch7 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch7;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch7 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch7 AND Shift_TimeInPeriod5 >= FP_Punch7 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch7 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch7 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch7 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch7 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch7 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch7 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch7;
					ELSEIF Shift_TimeInOvertime <= FP_Punch7 AND Shift_TimeOutOvertime >= FP_Punch7 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch7;
					ELSEIF Shift_TimeInOvertime <= FP_Punch7 AND Shift_TimeOutOvertime >= FP_Punch7 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch7;
					ELSEIF O1 = '00:00:00' AND FP_Punch7 != In1 AND FP_Punch7 != Out1 AND FP_Punch7 != In2 AND FP_Punch7 != Out2 AND FP_Punch7 != In3 AND FP_Punch7 != Out3 AND FP_Punch7 != In4 AND FP_Punch7 != Out4 AND FP_Punch7 != In5 AND FP_Punch7 != Out5 THEN
						SET O1 = FP_Punch7;
					ELSEIF O2 = '00:00:00' AND FP_Punch7 != In1 AND FP_Punch7 != Out1 AND FP_Punch7 != In2 AND FP_Punch7 != Out2 AND FP_Punch7 != In3 AND FP_Punch7 != Out3 AND FP_Punch7 != In4 AND FP_Punch7 != Out4 AND FP_Punch7 != In5 AND FP_Punch7 != Out5 THEN
						SET O2 = FP_Punch7;
					END IF;
				END IF;

				-- Punch8
				IF FP_Punch8 > FP_Punch7 AND FP_Punch8 <> '00:00:00' AND FP_Punch8 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch8, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch8;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch8;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch8 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch8;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch8 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch8 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch8 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch8;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch8 AND Shift_TimeInPeriod2 >= FP_Punch8 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch8 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch8;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch8 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch8 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch8 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch8 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch8 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch8 AND Shift_TimeInPeriod3 >= FP_Punch8 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch8 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch8 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch8 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch8 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch8 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch8 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch8 AND Shift_TimeInPeriod4 >= FP_Punch8 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch8 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch8 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch8 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch8 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch8;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch8 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch8;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch8 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch8 AND Shift_TimeInPeriod5 >= FP_Punch8 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch8 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch8 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch8 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch8 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch8 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch8 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch8;
					ELSEIF Shift_TimeInOvertime <= FP_Punch8 AND Shift_TimeOutOvertime >= FP_Punch8 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch8;
					ELSEIF Shift_TimeInOvertime <= FP_Punch8 AND Shift_TimeOutOvertime >= FP_Punch8 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch8;
					ELSEIF O1 = '00:00:00' AND FP_Punch8 != In1 AND FP_Punch8 != Out1 AND FP_Punch8 != In2 AND FP_Punch8 != Out2 AND FP_Punch8 != In3 AND FP_Punch8 != Out3 AND FP_Punch8 != In4 AND FP_Punch8 != Out4 AND FP_Punch8 != In5 AND FP_Punch8 != Out5 THEN
						SET O1 = FP_Punch8;
					ELSEIF O2 = '00:00:00' AND FP_Punch8 != In1 AND FP_Punch8 != Out1 AND FP_Punch8 != In2 AND FP_Punch8 != Out2 AND FP_Punch8 != In3 AND FP_Punch8 != Out3 AND FP_Punch8 != In4 AND FP_Punch8 != Out4 AND FP_Punch8 != In5 AND FP_Punch8 != Out5 THEN
						SET O2 = FP_Punch8;
					END IF;
				END IF;

				-- Punch9
				IF FP_Punch9 > FP_Punch8 AND FP_Punch9 <> '00:00:00' AND FP_Punch9 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch9, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch9;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch9;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch9 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch9;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch9 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch9 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch9 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch9;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch9 AND Shift_TimeInPeriod2 >= FP_Punch9 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch9 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch9;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch9 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch9 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch9 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch9 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch9 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch9 AND Shift_TimeInPeriod3 >= FP_Punch9 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch9 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch9 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch9 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch9 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch9 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch9 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch9 AND Shift_TimeInPeriod4 >= FP_Punch9 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch9 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch9 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch9 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch9 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch9;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch9 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch9;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch9 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch9 AND Shift_TimeInPeriod5 >= FP_Punch9 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch9 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch9 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch9 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch9 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch9 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch9 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch9;
					ELSEIF Shift_TimeInOvertime <= FP_Punch9 AND Shift_TimeOutOvertime >= FP_Punch9 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch9;
					ELSEIF Shift_TimeInOvertime <= FP_Punch9 AND Shift_TimeOutOvertime >= FP_Punch9 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch9;
					ELSEIF O1 = '00:00:00' AND FP_Punch9 != In1 AND FP_Punch9 != Out1 AND FP_Punch9 != In2 AND FP_Punch9 != Out2 AND FP_Punch9 != In3 AND FP_Punch9 != Out3 AND FP_Punch9 != In4 AND FP_Punch9 != Out4 AND FP_Punch9 != In5 AND FP_Punch9 != Out5 THEN
						SET O1 = FP_Punch9;
					ELSEIF O2 = '00:00:00' AND FP_Punch9 != In1 AND FP_Punch9 != Out1 AND FP_Punch9 != In2 AND FP_Punch9 != Out2 AND FP_Punch9 != In3 AND FP_Punch9 != Out3 AND FP_Punch9 != In4 AND FP_Punch9 != Out4 AND FP_Punch9 != In5 AND FP_Punch9 != Out5 THEN
						SET O2 = FP_Punch9;
					END IF;
				END IF;

				-- Punch10
				IF FP_Punch10 > FP_Punch9 AND FP_Punch10 <> '00:00:00' AND FP_Punch10 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch10, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch10;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch10;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch10 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch10;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch10 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch10 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch10 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch10;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch10 AND Shift_TimeInPeriod2 >= FP_Punch10 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch10 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch10;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch10 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch10 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch10 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch10 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch10 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch10 AND Shift_TimeInPeriod3 >= FP_Punch10 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch10 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch10 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch10 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch10 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch10 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch10 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch10 AND Shift_TimeInPeriod4 >= FP_Punch10 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch10 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch10 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch10 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch10 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch10;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch10 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch10;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch10 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch10 AND Shift_TimeInPeriod5 >= FP_Punch10 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch10 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch10 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch10 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch10 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch10 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch10 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch10;
					ELSEIF Shift_TimeInOvertime <= FP_Punch10 AND Shift_TimeOutOvertime >= FP_Punch10 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch10;
					ELSEIF Shift_TimeInOvertime <= FP_Punch10 AND Shift_TimeOutOvertime >= FP_Punch10 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch10;
					ELSEIF O1 = '00:00:00' AND FP_Punch10 != In1 AND FP_Punch10 != Out1 AND FP_Punch10 != In2 AND FP_Punch10 != Out2 AND FP_Punch10 != In3 AND FP_Punch10 != Out3 AND FP_Punch10 != In4 AND FP_Punch10 != Out4 AND FP_Punch10 != In5 AND FP_Punch10 != Out5 THEN
						SET O1 = FP_Punch10;
					ELSEIF O2 = '00:00:00' AND FP_Punch10 != In1 AND FP_Punch10 != Out1 AND FP_Punch10 != In2 AND FP_Punch10 != Out2 AND FP_Punch10 != In3 AND FP_Punch10 != Out3 AND FP_Punch10 != In4 AND FP_Punch10 != Out4 AND FP_Punch10 != In5 AND FP_Punch10 != Out5 THEN
						SET O2 = FP_Punch10;
					END IF;
				END IF;

			-- Check Late
			IF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 < In1 AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= In1 AND In1 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In1%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In1,Shift_TimeInPeriod1), In1, TimeBreak1, 'TimeIn') > LeaveDurationInOut1 THEN
						SET CheckLateIn1 = 1;
						SET CheckLateDurationIn1 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In1,Shift_TimeInPeriod1),LeaveDurationInOut1), In1, TimeBreak1, 'TimeIn');
						SET checkLateDurationDeductIn1 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn1);
					END IF;
				ELSE
					SET CheckLateIn1 = 1;
					SET CheckLateDurationIn1 = fnHRMCheckBreakTime(TIMEDIFF(In1,Shift_TimeInPeriod1), In1, TimeBreak1, 'TimeIn');
					SET checkLateDurationDeductIn1 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn1);
				END IF;
			END IF;

			IF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 > Out1 AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= Out1 AND In1 <> '00:00:00' AND Out1 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out1%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod1, Out1), Out1, TimeBreak1, 'TimeOut') > LeaveDurationInOut1 THEN
						SET CheckLateOut1 = 1;
						SET CheckLateDurationOut1 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod1, Out1),LeaveDurationInOut1), Out1, TimeBreak1, 'TimeOut');
						SET checkLateDurationDeductOut1 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut1);
					END IF;
				ELSE
					SET CheckLateOut1 = 1;
					SET CheckLateDurationOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod1, Out1), Out1, TimeBreak1, 'TimeOut');
					SET checkLateDurationDeductOut1 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut1);
				END IF;
			END IF;
		
			IF Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 < In2 AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= In2 AND In2 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In2%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In2,Shift_TimeInPeriod2), In2, TimeBreak2, 'TimeIn') > LeaveDurationInOut2 THEN
						SET CheckLateIn2 = 1;
						SET CheckLateDurationIn2 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In2,Shift_TimeInPeriod2),LeaveDurationInOut2), In2, TimeBreak2, 'TimeIn');
						SET checkLateDurationDeductIn2 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn2);
					END IF;
				ELSE
					SET CheckLateIn2 = 1;
					SET CheckLateDurationIn2 = fnHRMCheckBreakTime(TIMEDIFF(In2,Shift_TimeInPeriod2), In2, TimeBreak2, 'TimeIn');
					SET checkLateDurationDeductIn2 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn2);
				END IF;
			END IF;

			IF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 > Out2 AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= Out2 AND In2 <> '00:00:00' AND Out2 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out2%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod2, Out2), Out2, TimeBreak2, 'TimeOut') > LeaveDurationInOut2 THEN
						SET CheckLateOut2 = 1;
						SET CheckLateDurationOut2 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod2, Out2),LeaveDurationInOut2), Out2, TimeBreak2, 'TimeOut');
						SET checkLateDurationDeductOut2 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut2);
					END IF;
				ELSE
					SET CheckLateOut2 = 1;
					SET CheckLateDurationOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod2, Out2), Out2, TimeBreak2, 'TimeOut');
					SET checkLateDurationDeductOut2 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut2);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 < In3 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= In3 AND In3 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In3%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In3,Shift_TimeInPeriod3), In3, TimeBreak3, 'TimeIn') > LeaveDurationInOut3 THEN
						SET CheckLateIn3 = 1;
						SET CheckLateDurationIn3 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In3,Shift_TimeInPeriod3),LeaveDurationInOut3), In3, TimeBreak3, 'TimeIn');
						SET checkLateDurationDeductIn3 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn3);
					END IF;
				ELSE
					SET CheckLateIn3 = 1;
					SET CheckLateDurationIn3 = fnHRMCheckBreakTime(TIMEDIFF(In3,Shift_TimeInPeriod3), In3, TimeBreak3, 'TimeIn');
					SET checkLateDurationDeductIn3 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn3);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 > Out3 AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= Out3 AND In3 <> '00:00:00' AND Out3 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out3%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod3, Out3), Out3, TimeBreak3, 'TimeOut') > LeaveDurationInOut3 THEN
						SET CheckLateOut3 = 1;
						SET CheckLateDurationOut3 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod3, Out3),LeaveDurationInOut3), Out3, TimeBreak3, 'TimeOut');
						SET checkLateDurationDeductOut3 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut3);
					END IF;
				ELSE
					SET CheckLateOut3 = 1;
					SET CheckLateDurationOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod3, Out3), Out3, TimeBreak3, 'TimeOut');
					SET checkLateDurationDeductOut3 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut3);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 < In4 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= In4 AND In4 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In4%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In4,Shift_TimeInPeriod4), In4, TimeBreak4, 'TimeIn') > LeaveDurationInOut4 THEN
						SET CheckLateIn4 = 1;
						SET CheckLateDurationIn4 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In4,Shift_TimeInPeriod4),LeaveDurationInOut4), In4, TimeBreak4, 'TimeIn');
						SET checkLateDurationDeductIn4 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn4);
					END IF;
				ELSE
					SET CheckLateIn4 = 1;
					SET CheckLateDurationIn4 = fnHRMCheckBreakTime(TIMEDIFF(In4,Shift_TimeInPeriod4), In4, TimeBreak4, 'TimeIn');
					SET checkLateDurationDeductIn4 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn4);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 > Out4 AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= Out4 AND In4 <> '00:00:00' AND Out4 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out4%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod4, Out4), Out4, TimeBreak4, 'TimeOut') > LeaveDurationInOut4 THEN
						SET CheckLateOut4 = 1;
						SET CheckLateDurationOut4 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod4, Out4),LeaveDurationInOut4), Out4, TimeBreak4, 'TimeOut');
						SET checkLateDurationDeductOut4 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut4);
					END IF;
				ELSE
					SET CheckLateOut4 = 1;
					SET CheckLateDurationOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod4, Out4), Out4, TimeBreak4, 'TimeOut');
					SET checkLateDurationDeductOut4 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut4);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 < In5 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= In5 AND In5 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In5%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In5,Shift_TimeInPeriod5), In5, TimeBreak5, 'TimeIn') > LeaveDurationInOut5 THEN
						SET CheckLateIn5 = 1;
						SET CheckLateDurationIn5 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In5,Shift_TimeInPeriod5),LeaveDurationInOut5), In5, TimeBreak5, 'TimeIn');
						SET checkLateDurationDeductIn5 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn5);
					END IF;
				ELSE
					SET CheckLateIn5 = 1;
					SET CheckLateDurationIn5 = fnHRMCheckBreakTime(TIMEDIFF(In5,Shift_TimeInPeriod5), In5, TimeBreak5, 'TimeIn');
					SET checkLateDurationDeductIn5 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn5);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 > Out5 AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= Out5 AND In5 <> '00:00:00' AND Out5 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out5%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod5, Out5), Out5, TimeBreak5, 'TimeOut') > LeaveDurationInOut5 THEN
						SET CheckLateOut5 = 1;
						SET CheckLateDurationOut5 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod5, Out5),LeaveDurationInOut5), Out5, TimeBreak5, 'TimeOut');
						SET checkLateDurationDeductOut5 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut5);
					END IF;
				ELSE
					SET CheckLateOut5 = 1;
					SET CheckLateDurationOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod5, Out5), Out5, TimeBreak5, 'TimeOut');
					SET checkLateDurationDeductOut5 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut5);	
				END IF;		
			END IF;

			IF S IS NULL THEN
				SET S = '';
			END IF;
			
			IF S <> 'HO' AND S <> 'B' THEN
				
				-- Check AB
				IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND (In1 = '00:00:00' OR Out1 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct, fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1,Shift_TimeIn1), '00:00:00', TimeBreak1, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn1 = '00:00:00' AND CheckLateDurationOut1 = '00:00:00' AND LeaveDurationInOut1 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut1);
					END IF;

					SET CheckLateIn1 = 0;
					SET CheckLateDurationIn1 = '00:00:00';
					SET checkLateDurationDeductIn1 = '00:00:00';
					SET CheckLateOut1 = 0;
					SET CheckLateDurationOut1 = '00:00:00';
					SET checkLateDurationDeductOut1 = '00:00:00';
					
				END IF;
				IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND (In2 = '00:00:00' OR Out2 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct, fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2,Shift_TimeIn2), '00:00:00', TimeBreak2, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn2 = '00:00:00' AND CheckLateDurationOut2 = '00:00:00' AND LeaveDurationInOut2 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut2);
					END IF;

					SET CheckLateIn2 = 0;
					SET CheckLateDurationIn2 = '00:00:00';
					SET checkLateDurationDeductIn2 = '00:00:00';
					SET CheckLateOut2 = 0;
					SET CheckLateDurationOut2 = '00:00:00';
					SET checkLateDurationDeductOut2 = '00:00:00';
				END IF;
				IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND (In3 = '00:00:00' OR Out3 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3,Shift_TimeIn3), '00:00:00', TimeBreak3, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn3 = '00:00:00' AND CheckLateDurationOut3 = '00:00:00' AND LeaveDurationInOut3 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut3);
					END IF;

					SET CheckLateIn3 = 0;
					SET CheckLateDurationIn3 = '00:00:00';
					SET checkLateDurationDeductIn3 = '00:00:00';
					SET CheckLateOut3 = 0;
					SET CheckLateDurationOut3 = '00:00:00';
					SET checkLateDurationDeductOut3 = '00:00:00';
				END IF;
				IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND (In4 = '00:00:00' OR Out4 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4,Shift_TimeIn4), '00:00:00', TimeBreak4, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn4 = '00:00:00' AND CheckLateDurationOut4 = '00:00:00' AND LeaveDurationInOut4 = '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut4);
					END IF;

					SET CheckLateIn4 = 0;
					SET CheckLateDurationIn4 = '00:00:00';
					SET checkLateDurationDeductIn4 = '00:00:00';
					SET CheckLateOut4 = 0;
					SET CheckLateDurationOut4 = '00:00:00';
					SET checkLateDurationDeductOut4 = '00:00:00';
				END IF;
				IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND (In5 = '00:00:00' OR Out5 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5,Shift_TimeIn5), '00:00:00', TimeBreak5, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn5 = '00:00:00' AND CheckLateDurationOut5 = '00:00:00' AND LeaveDurationInOut5 = '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut5);
					END IF;

					SET CheckLateIn5 = 0;
					SET CheckLateDurationIn5 = '00:00:00';
					SET checkLateDurationDeductIn5 = '00:00:00';
					SET CheckLateOut5 = 0;
					SET CheckLateDurationOut5 = '00:00:00';
					SET checkLateDurationDeductOut5 = '00:00:00';
				END IF;
		
				IF fnHRMTimeToFloat(checkAbDurationDeduct) > Shift_TotalWorkHour THEN
					SET checkAbDurationDeduct = CONCAT(FLOOR(Shift_TotalWorkHour),':',(Shift_TotalWorkHour -FLOOR(Shift_TotalWorkHour))*60, ':00');
				END IF;
				
				-- Check Leave
				IF CheckOutLeave <> "" THEN
					SET CheckL = CheckL + 1;
				ELSEIF In1 = '00:00:01' OR LeaveDurationInOut1 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out1 = '00:00:01' OR LeaveDurationInOut1 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;	
				ELSEIF In2 = '00:00:01' OR LeaveDurationInOut2 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out2 = '00:00:01' OR LeaveDurationInOut2 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In3 = '00:00:01' OR LeaveDurationInOut3 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out3 = '00:00:01' OR LeaveDurationInOut3 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In4 = '00:00:01' OR LeaveDurationInOut4 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out4 = '00:00:01' OR LeaveDurationInOut4 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In5 = '00:00:01' OR LeaveDurationInOut5 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out5 = '00:00:01' OR LeaveDurationInOut5 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF O1 = '00:00:01' THEN
					SET CheckL = CheckL + 1;
				ELSEIF O2 = '00:00:01' THEN
					SET CheckL = CheckL + 1; 
				END IF;

				-- Check Work Hour
				IF In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out1,In1));
				END IF;
				IF In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out2,In2));
				END IF;
				IF In3 <> '00:00:00' AND In3 <> '00:00:01' AND Out3 <> '00:00:00' AND Out3 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out3,In3));
				END IF;
				IF In4 <> '00:00:00' AND In4 <> '00:00:01' AND Out4 <> '00:00:00' AND Out4 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out4,In4));
				END IF;
				IF In5 <> '00:00:00' AND In5 <> '00:00:01' AND Out5 <> '00:00:00' AND Out5 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out5,In5));
				END IF;
				IF WorkHour > Shift_TotalWorkHour THEN
					SET WorkHour = Shift_TotalWorkHour;
				END IF;

				SET TotalCheckLate = TotalCheckLate + CheckLateIn1 + CheckLateOut1 + CheckLateIn2 + CheckLateOut2 + CheckLateIn3 + CheckLateOut3 + CheckLateIn4 + CheckLateOut4 + CheckLateIn5 + CheckLateOut5;

				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn1);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut1);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn2);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut2);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn3);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut3);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn4);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut4);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn5);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut5);

				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn1);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut1);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn2);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut2);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn3);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut3);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn4);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut4);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn5);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut5);

				-- Check Negative AB & Late
				IF checkAbDurationDeduct <= '00:00:00' THEN
					SET checkAbDurationDeduct = '00:00:00';
					SET CheckAb = 0;
				END IF;
				IF TotalCheckLateDuration <= '00:00:00' THEN
					SET TotalCheckLateDuration = '00:00:00';
					SET TotalCheckLateDurationDeduct = '00:00:00';
					SET TotalCheckLate = 0;
				END IF;


				IF TotalCheckLate >0 AND CheckAb >0 AND CheckL > 0 THEN
					SET S = 'LA/AB/LE';
				ELSEIF TotalCheckLate >0 AND CheckAb >0 AND CheckL <= 0 THEN
					SET S = 'LA/AB';
				ELSEIF TotalCheckLate >0 AND CheckAb <= 0 AND CheckL > 0 THEN
					SET S = 'LA/LE';
				ELSEIF TotalCheckLate <= 0 AND CheckAb >0 AND CheckL > 0 THEN
					SET S = 'AB/LE';
				ELSEIF TotalCheckLate >0 AND CheckAb <= 0 AND CheckL <= 0 THEN
					SET S = 'LA';
				ELSEIF TotalCheckLate <=0 AND CheckAb > 0 AND CheckL <= 0 THEN
					SET S = 'AB';
				ELSEIF TotalCheckLate <=0 AND CheckAb <= 0 AND CheckL > 0 THEN
					SET S = 'LE';
				ELSE 
					SET S = 'P';
				END IF;

				IF In1 = '00:00:00' AND Out1 = '00:00:00' AND In2 = '00:00:00' AND Out2 = '00:00:00' AND In3 = '00:00:00' AND Out3 = '00:00:00' AND In4 = '00:00:00' AND Out4 = '00:00:00' AND In5 = '00:00:00' AND Out5 = '00:00:00' AND S = 'P' THEN
					SET S = 'B';
				END IF;

			END IF;

				IF CheckExist	> 0 THEN
					UPDATE hrm_timesheet_attendance SET Att_In1=In1,Att_Out1=Out1,Att_In2=In2,Att_Out2=Out2,Att_In3=In3,Att_Out3=Out3,Att_In4=In4,Att_Out4=Out4,Att_In5=In5,Att_Out5=Out5,Att_OvertimeIn=OverIn,Att_OvertimeOut=OverOut,Att_Other1=O1,Att_Other2=O2,Att_LateAmount=TotalCheckLate,Att_ABAmount=CheckAb,Att_Status=S,Att_RStatus=S,Att_WorkHour=WorkHour, Att_LateDuration=TotalCheckLateDuration, Att_LateDurationDeduct = TotalcheckLateDurationDeduct, Att_ABDurationDeduct = checkAbDurationDeduct WHERE Att_FPID=FP_ID AND Att_Date=FP_Date;
				ELSE
					INSERT INTO hrm_timesheet_attendance(Att_EmpID,Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_LateAmount,Att_ABAmount,Att_Status,Att_RStatus,Att_WorkHour,Att_LateDuration,Att_LateDurationDeduct,Att_ABDurationDeduct) VALUES (SEmpID,FP_ID,FP_Date,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,TotalCheckLate,CheckAb,S,S,WorkHour,TotalCheckLateDuration,TotalcheckLateDurationDeduct,checkAbDurationDeduct);
				END IF;
				#SELECT SEmpID,FP_ID,FP_Date,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,CheckLate,CheckAb,S,S,WorkHour,CheckLateDuration,checkLateDurationDeduct,checkAbDurationDeduct;
				#INSERT INTO hrm_emp_grade VALUES(CONCAT(FP_Punch1, FP_Punch2, FP_Punch3, FP_Punch4, FP_Punch5, FP_Punch6, FP_Punch7, FP_Punch8, FP_Punch9, FP_Punch10));
				#INSERT INTO hrm_emp_grade VALUES(CONCAT(SEmpID,FP_ID,FP_Date,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,CheckLate,CheckAb,S,S,WorkHour,CheckLateDuration,checkLateDurationDeduct,checkAbDurationDeduct));
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddAttendanceRoster`;
DELIMITER |
CREATE PROCEDURE `spHRMAddAttendanceRoster`(SEmpID varchar(255), ShiftID varchar(255), FP_ID varchar(255), FP_Date Date, FP_Punch1 Time, FP_Punch2 Time, FP_Punch3 Time, FP_Punch4 Time, FP_Punch5 Time, FP_Punch6 Time, FP_Punch7 Time, FP_Punch8 Time, FP_Punch9 Time, FP_Punch10 Time)
    DETERMINISTIC
BEGIN
		DECLARE Shift_ID VARCHAR(255);
		DECLARE Shift_Day VARCHAR(255);
		DECLARE Shift_TotalWorkHour FLOAT DEFAULT(0);
		DECLARE Shift_TimeIn1 TIME;
		DECLARE Shift_TimeInPeriod1 TIME;
		DECLARE Shift_TimeOut1 TIME;
		DECLARE Shift_TimeOutPeriod1 TIME;
		DECLARE Shift_TimeIn2 TIME;
		DECLARE Shift_TimeInPeriod2 TIME;
		DECLARE Shift_TimeOut2 TIME;
		DECLARE Shift_TimeOutPeriod2 TIME;
		DECLARE Shift_TimeIn3 TIME;
		DECLARE Shift_TimeInPeriod3 TIME;
		DECLARE Shift_TimeOut3 TIME;
		DECLARE Shift_TimeOutPeriod3 TIME;
		DECLARE Shift_TimeIn4 TIME;
		DECLARE Shift_TimeInPeriod4 TIME;
		DECLARE Shift_TimeOut4 TIME;
		DECLARE Shift_TimeOutPeriod4 TIME;
		DECLARE Shift_TimeIn5 TIME;
		DECLARE Shift_TimeInPeriod5 TIME;
		DECLARE Shift_TimeOut5 TIME;
		DECLARE Shift_TimeOutPeriod5 TIME;
		DECLARE Shift_TimeInOvertime TIME;
		DECLARE Shift_TimeOutOvertime TIME;

		DECLARE Shift_TimeIn1LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut1LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn2LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut2LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn3LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut3LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn4LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut4LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn5LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut5LateAmt INT DEFAULT(0);

		DECLARE CheckExist TINYINT DEFAULT(0);

		DECLARE TotalCheckLate TINYINT DEFAULT(0);
		DECLARE TotalCheckLateDuration TIME DEFAULT('00:00:00');
		DECLARE TotalcheckLateDurationDeduct TIME DEFAULT('00:00:00');

		DECLARE CheckLateIn1 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn1 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn1 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn2 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn2 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn2 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn3 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn3 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn3 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn4 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn4 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn4 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn5 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn5 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn5 TIME DEFAULT('00:00:00');

		DECLARE CheckLateOut1 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut1 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut1 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut2 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut2 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut2 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut3 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut3 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut3 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut4 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut4 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut4 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut5 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut5 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut5 TIME DEFAULT('00:00:00');

		DECLARE LeaveDurationStatus VARCHAR(255) DEFAULT('');
		DECLARE LeaveDurationInOut1 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut2 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut3 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut4 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut5 TIME DEFAULT('00:00:00');

		DECLARE CheckOutLeave VARCHAR(255) DEFAULT('');
		DECLARE CheckOutLeaveInOut VARCHAR(255) DEFAULT('');

		DECLARE checkAbDurationDeduct TIME DEFAULT('00:00:00');
		DECLARE CheckAb TINYINT DEFAULT(0);
		DECLARE CheckL TINYINT DEFAULT(0);
		DECLARE S VARCHAR(255) DEFAULT('');

		DECLARE In1 TIME DEFAULT('00:00:00');
		DECLARE In2 TIME DEFAULT('00:00:00');
		DECLARE In3 TIME DEFAULT('00:00:00');
		DECLARE In4 TIME DEFAULT('00:00:00');
		DECLARE In5 TIME DEFAULT('00:00:00');
		DECLARE Out1 TIME DEFAULT('00:00:00');
		DECLARE Out2 TIME DEFAULT('00:00:00');
		DECLARE Out3 TIME DEFAULT('00:00:00');
		DECLARE Out4 TIME DEFAULT('00:00:00');
		DECLARE Out5 TIME DEFAULT('00:00:00');
		DECLARE OverIn TIME DEFAULT('00:00:00');
		DECLARE OverOut TIME DEFAULT('00:00:00');
		DECLARE O1 TIME DEFAULT('00:00:00');
		DECLARE O2 TIME DEFAULT('00:00:00');
		DECLARE WorkHour INT DEFAULT(0);

		DECLARE TimeBreak1 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak2 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak3 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak4 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak5 VARCHAR(255) DEFAULT('');

		
		SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TotalWorkHour,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,wd.Shift_TimeIn1LateDuration,wd.Shift_TimeOut1LateDuration,wd.Shift_TimeIn2LateDuration,wd.Shift_TimeOut2LateDuration,wd.Shift_TimeIn3LateDuration,wd.Shift_TimeOut3LateDuration,wd.Shift_TimeIn4LateDuration,wd.Shift_TimeOut4LateDuration,wd.Shift_TimeIn5LateDuration,wd.Shift_TimeOut5LateDuration,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 INTO Shift_ID, Shift_Day, Shift_TotalWorkHour, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime, Shift_TimeIn1LateAmt, Shift_TimeOut1LateAmt, Shift_TimeIn2LateAmt, Shift_TimeOut2LateAmt, Shift_TimeIn3LateAmt, Shift_TimeOut3LateAmt, Shift_TimeIn4LateAmt, Shift_TimeOut4LateAmt, Shift_TimeIn5LateAmt, Shift_TimeOut5LateAmt, TimeBreak1, TimeBreak2, TimeBreak3, TimeBreak4, TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = ShiftID LIMIT 1 OFFSET 1; 
		
		SELECT COUNT(*) INTO CheckExist FROM  hrm_timesheet_attendance att WHERE att.Att_FPID = FP_ID AND att.Att_Date = FP_Date;
		IF CheckExist > 0 THEN
			SELECT Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_Status,Att_LeaveDurationInOut1,Att_LeaveDurationInOut2,Att_LeaveDurationInOut3,Att_LeaveDurationInOut4,Att_LeaveDurationInOut5,Att_LeaveDurationStatus,Att_OutLeave,Att_OutLeaveInOut INTO FP_ID,FP_Date,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,S,LeaveDurationInOut1,LeaveDurationInOut2,LeaveDurationInOut3,LeaveDurationInOut4,LeaveDurationInOut5,LeaveDurationStatus,CheckOutLeave,CheckOutLeaveInOut FROM hrm_timesheet_attendance att WHERE att.Att_FPID = FP_ID AND att.Att_Date = FP_Date;
		END IF;
				
				-- Punch1
				IF FP_Punch1 <> '00:00:00' AND FP_Punch1 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch1, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch1;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch1;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch1 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch1;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch1 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch1 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch1 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch1 AND Shift_TimeInPeriod2 >= FP_Punch1 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch1 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch1 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch1 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch1 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch1 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch1 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch1 AND Shift_TimeInPeriod3 >= FP_Punch1 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch1 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch1 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch1 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch1 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch1 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch1 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch1 AND Shift_TimeInPeriod4 >= FP_Punch1 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch1 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch1 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch1 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch1 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch1;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch1 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch1;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch1 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch1 AND Shift_TimeInPeriod5 >= FP_Punch1 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch1 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch1;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch1 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch1 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch1 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch1 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch1;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch1 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch1;
					ELSEIF Shift_TimeInOvertime <= FP_Punch1 AND Shift_TimeOutOvertime >= FP_Punch1 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch1;
					ELSEIF Shift_TimeInOvertime <= FP_Punch1 AND Shift_TimeOutOvertime >= FP_Punch1 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch1;
					ELSEIF O1 = '00:00:00' AND FP_Punch1 != In1 AND FP_Punch1 != Out1 AND FP_Punch1 != In2 AND FP_Punch1 != Out2 AND FP_Punch1 != In3 AND FP_Punch1 != Out3 AND FP_Punch1 != In4 AND FP_Punch1 != Out4 AND FP_Punch1 != In5 AND FP_Punch1 != Out5 THEN
						SET O1 = FP_Punch1;
					ELSEIF O2 = '00:00:00' AND FP_Punch1 != In1 AND FP_Punch1 != Out1 AND FP_Punch1 != In2 AND FP_Punch1 != Out2 AND FP_Punch1 != In3 AND FP_Punch1 != Out3 AND FP_Punch1 != In4 AND FP_Punch1 != Out4 AND FP_Punch1 != In5 AND FP_Punch1 != Out5 THEN
						SET O2 = FP_Punch1;
					END IF;
				END IF;
				
				-- Punch2
				IF FP_Punch2 > FP_Punch1 AND FP_Punch2 <> '00:00:00' AND FP_Punch2 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch2, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch2;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch2;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch2 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch2;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch2 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch2 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch2 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch2;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch2 AND Shift_TimeInPeriod2 >= FP_Punch2 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch2 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch2;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch2 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch2 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch2 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch2 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch2 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch2 AND Shift_TimeInPeriod3 >= FP_Punch2 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch2 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch2 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch2 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch2 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch2 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch2 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch2 AND Shift_TimeInPeriod4 >= FP_Punch2 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch2 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch2 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch2 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch2 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch2;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch2 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch2;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch2 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch2 AND Shift_TimeInPeriod5 >= FP_Punch2 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch2 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch2;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch2 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch2 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch2 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch2 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch2;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch2 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch2;
					ELSEIF Shift_TimeInOvertime <= FP_Punch2 AND Shift_TimeOutOvertime >= FP_Punch2 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch2;
					ELSEIF Shift_TimeInOvertime <= FP_Punch2 AND Shift_TimeOutOvertime >= FP_Punch2 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch2;
					ELSEIF O1 = '00:00:00' AND FP_Punch2 != In1 AND FP_Punch2 != Out1 AND FP_Punch2 != In2 AND FP_Punch2 != Out2 AND FP_Punch2 != In3 AND FP_Punch2 != Out3 AND FP_Punch2 != In4 AND FP_Punch2 != Out4 AND FP_Punch2 != In5 AND FP_Punch2 != Out5 THEN
						SET O1 = FP_Punch2;
					ELSEIF O2 = '00:00:00' AND FP_Punch2 != In1 AND FP_Punch2 != Out1 AND FP_Punch2 != In2 AND FP_Punch2 != Out2 AND FP_Punch2 != In3 AND FP_Punch2 != Out3 AND FP_Punch2 != In4 AND FP_Punch2 != Out4 AND FP_Punch2 != In5 AND FP_Punch2 != Out5 THEN
						SET O2 = FP_Punch2;
					END IF;
				END IF;

				-- Punch3
				IF FP_Punch3 > FP_Punch2 AND FP_Punch3 <> '00:00:00' AND FP_Punch3 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch3, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch3;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch3;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch3 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch3;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch3 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch3 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch3 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch3;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch3 AND Shift_TimeInPeriod2 >= FP_Punch3 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch3 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch3;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch3 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch3 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch3 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch3 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch3 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch3 AND Shift_TimeInPeriod3 >= FP_Punch3 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch3 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch3 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch3 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch3 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch3 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch3 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch3 AND Shift_TimeInPeriod4 >= FP_Punch3 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch3 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch3 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch3 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch3 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch3;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch3 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch3;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch3 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch3 AND Shift_TimeInPeriod5 >= FP_Punch3 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch3 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch3;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch3 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch3 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch3 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch3 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch3;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch3 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch3;
					ELSEIF Shift_TimeInOvertime <= FP_Punch3 AND Shift_TimeOutOvertime >= FP_Punch3 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch3;
					ELSEIF Shift_TimeInOvertime <= FP_Punch3 AND Shift_TimeOutOvertime >= FP_Punch3 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch3;
					ELSEIF O1 = '00:00:00' AND FP_Punch3 != In1 AND FP_Punch3 != Out1 AND FP_Punch3 != In2 AND FP_Punch3 != Out2 AND FP_Punch3 != In3 AND FP_Punch3 != Out3 AND FP_Punch3 != In4 AND FP_Punch3 != Out4 AND FP_Punch3 != In5 AND FP_Punch3 != Out5 THEN
						SET O1 = FP_Punch3;
					ELSEIF O2 = '00:00:00' AND FP_Punch3 != In1 AND FP_Punch3 != Out1 AND FP_Punch3 != In2 AND FP_Punch3 != Out2 AND FP_Punch3 != In3 AND FP_Punch3 != Out3 AND FP_Punch3 != In4 AND FP_Punch3 != Out4 AND FP_Punch3 != In5 AND FP_Punch3 != Out5 THEN
						SET O2 = FP_Punch3;
					END IF;
				END IF;

				-- Punch4
				IF FP_Punch4 > FP_Punch3 AND FP_Punch4 <> '00:00:00' AND FP_Punch4 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch4, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch4;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch4;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch4 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch4;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch4 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch4 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch4 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch4;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch4 AND Shift_TimeInPeriod2 >= FP_Punch4 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch4 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch4;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch4 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch4 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch4 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch4 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch4 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch4 AND Shift_TimeInPeriod3 >= FP_Punch4 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch4 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch4 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch4 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch4 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch4 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch4 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch4 AND Shift_TimeInPeriod4 >= FP_Punch4 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch4 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch4 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch4 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch4 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch4;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch4 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch4;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch4 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch4 AND Shift_TimeInPeriod5 >= FP_Punch4 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch4 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch4;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch4 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch4 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch4 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch4 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch4;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch4 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch4;
					ELSEIF Shift_TimeInOvertime <= FP_Punch4 AND Shift_TimeOutOvertime >= FP_Punch4 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch4;
					ELSEIF Shift_TimeInOvertime <= FP_Punch4 AND Shift_TimeOutOvertime >= FP_Punch4 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch4;
					ELSEIF O1 = '00:00:00' AND FP_Punch4 != In1 AND FP_Punch4 != Out1 AND FP_Punch4 != In2 AND FP_Punch4 != Out2 AND FP_Punch4 != In3 AND FP_Punch4 != Out3 AND FP_Punch4 != In4 AND FP_Punch4 != Out4 AND FP_Punch4 != In5 AND FP_Punch4 != Out5 THEN
						SET O1 = FP_Punch4;
					ELSEIF O2 = '00:00:00' AND FP_Punch4 != In1 AND FP_Punch4 != Out1 AND FP_Punch4 != In2 AND FP_Punch4 != Out2 AND FP_Punch4 != In3 AND FP_Punch4 != Out3 AND FP_Punch4 != In4 AND FP_Punch4 != Out4 AND FP_Punch4 != In5 AND FP_Punch4 != Out5 THEN
						SET O2 = FP_Punch4;
					END IF;
				END IF;

				-- Punch5
				IF FP_Punch5 > FP_Punch4 AND FP_Punch5 <> '00:00:00' AND FP_Punch5 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch5, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch5;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch5;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch5 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch5;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch5 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch5 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch5 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch5;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch5 AND Shift_TimeInPeriod2 >= FP_Punch5 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch5 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch5;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch5 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch5 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch5 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch5 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch5 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch5 AND Shift_TimeInPeriod3 >= FP_Punch5 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch5 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch5 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch5 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch5 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch5 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch5 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch5 AND Shift_TimeInPeriod4 >= FP_Punch5 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch5 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch5 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch5 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch5 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch5;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch5 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch5;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch5 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch5 AND Shift_TimeInPeriod5 >= FP_Punch5 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch5 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch5;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch5 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch5 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch5 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch5 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch5;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch5 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch5;
					ELSEIF Shift_TimeInOvertime <= FP_Punch5 AND Shift_TimeOutOvertime >= FP_Punch5 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch5;
					ELSEIF Shift_TimeInOvertime <= FP_Punch5 AND Shift_TimeOutOvertime >= FP_Punch5 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch5;
					ELSEIF O1 = '00:00:00' AND FP_Punch5 != In1 AND FP_Punch5 != Out1 AND FP_Punch5 != In2 AND FP_Punch5 != Out2 AND FP_Punch5 != In3 AND FP_Punch5 != Out3 AND FP_Punch5 != In4 AND FP_Punch5 != Out4 AND FP_Punch5 != In5 AND FP_Punch5 != Out5 THEN
						SET O1 = FP_Punch5;
					ELSEIF O2 = '00:00:00' AND FP_Punch5 != In1 AND FP_Punch5 != Out1 AND FP_Punch5 != In2 AND FP_Punch5 != Out2 AND FP_Punch5 != In3 AND FP_Punch5 != Out3 AND FP_Punch5 != In4 AND FP_Punch5 != Out4 AND FP_Punch5 != In5 AND FP_Punch5 != Out5 THEN
						SET O2 = FP_Punch5;
					END IF;
				END IF;

				-- Punch6
				IF FP_Punch6 > FP_Punch5 AND FP_Punch6 <> '00:00:00' AND FP_Punch6 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch6, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch6;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch6;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch6 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch6;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch6 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch6 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch6 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch6;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch6 AND Shift_TimeInPeriod2 >= FP_Punch6 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch6 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch6;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch6 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch6 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch6 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch6 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch6 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch6 AND Shift_TimeInPeriod3 >= FP_Punch6 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch6 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch6 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch6 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch6 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch6 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch6 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch6 AND Shift_TimeInPeriod4 >= FP_Punch6 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch6 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch6 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch6 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch6 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch6;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch6 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch6;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch6 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch6 AND Shift_TimeInPeriod5 >= FP_Punch6 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch6 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch6;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch6 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch6 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch6 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch6 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch6;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch6 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch6;
					ELSEIF Shift_TimeInOvertime <= FP_Punch6 AND Shift_TimeOutOvertime >= FP_Punch6 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch6;
					ELSEIF Shift_TimeInOvertime <= FP_Punch6 AND Shift_TimeOutOvertime >= FP_Punch6 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch6;
					ELSEIF O1 = '00:00:00' AND FP_Punch6 != In1 AND FP_Punch6 != Out1 AND FP_Punch6 != In2 AND FP_Punch6 != Out2 AND FP_Punch6 != In3 AND FP_Punch6 != Out3 AND FP_Punch6 != In4 AND FP_Punch6 != Out4 AND FP_Punch6 != In5 AND FP_Punch6 != Out5 THEN
						SET O1 = FP_Punch6;
					ELSEIF O2 = '00:00:00' AND FP_Punch6 != In1 AND FP_Punch6 != Out1 AND FP_Punch6 != In2 AND FP_Punch6 != Out2 AND FP_Punch6 != In3 AND FP_Punch6 != Out3 AND FP_Punch6 != In4 AND FP_Punch6 != Out4 AND FP_Punch6 != In5 AND FP_Punch6 != Out5 THEN
						SET O2 = FP_Punch6;
					END IF;
				END IF;

				-- Punch7
				IF FP_Punch7 > FP_Punch6 AND FP_Punch7 <> '00:00:00' AND FP_Punch7 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch7, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch7;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch7;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch7 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch7;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch7 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch7 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch7 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch7;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch7 AND Shift_TimeInPeriod2 >= FP_Punch7 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch7 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch7;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch7 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch7 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch7 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch7 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch7 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch7 AND Shift_TimeInPeriod3 >= FP_Punch7 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch7 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch7 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch7 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch7 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch7 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch7 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch7 AND Shift_TimeInPeriod4 >= FP_Punch7 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch7 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch7 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch7 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch7 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch7;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch7 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch7;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch7 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch7 AND Shift_TimeInPeriod5 >= FP_Punch7 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch7 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch7;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch7 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch7 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch7 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch7 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch7;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch7 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch7;
					ELSEIF Shift_TimeInOvertime <= FP_Punch7 AND Shift_TimeOutOvertime >= FP_Punch7 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch7;
					ELSEIF Shift_TimeInOvertime <= FP_Punch7 AND Shift_TimeOutOvertime >= FP_Punch7 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch7;
					ELSEIF O1 = '00:00:00' AND FP_Punch7 != In1 AND FP_Punch7 != Out1 AND FP_Punch7 != In2 AND FP_Punch7 != Out2 AND FP_Punch7 != In3 AND FP_Punch7 != Out3 AND FP_Punch7 != In4 AND FP_Punch7 != Out4 AND FP_Punch7 != In5 AND FP_Punch7 != Out5 THEN
						SET O1 = FP_Punch7;
					ELSEIF O2 = '00:00:00' AND FP_Punch7 != In1 AND FP_Punch7 != Out1 AND FP_Punch7 != In2 AND FP_Punch7 != Out2 AND FP_Punch7 != In3 AND FP_Punch7 != Out3 AND FP_Punch7 != In4 AND FP_Punch7 != Out4 AND FP_Punch7 != In5 AND FP_Punch7 != Out5 THEN
						SET O2 = FP_Punch7;
					END IF;
				END IF;

				-- Punch8
				IF FP_Punch8 > FP_Punch7 AND FP_Punch8 <> '00:00:00' AND FP_Punch8 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch8, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch8;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch8;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch8 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch8;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch8 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch8 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch8 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch8;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch8 AND Shift_TimeInPeriod2 >= FP_Punch8 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch8 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch8;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch8 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch8 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch8 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch8 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch8 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch8 AND Shift_TimeInPeriod3 >= FP_Punch8 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch8 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch8 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch8 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch8 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch8 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch8 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch8 AND Shift_TimeInPeriod4 >= FP_Punch8 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch8 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch8 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch8 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch8 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch8;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch8 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch8;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch8 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch8 AND Shift_TimeInPeriod5 >= FP_Punch8 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch8 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch8;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch8 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch8 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch8 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch8 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch8;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch8 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch8;
					ELSEIF Shift_TimeInOvertime <= FP_Punch8 AND Shift_TimeOutOvertime >= FP_Punch8 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch8;
					ELSEIF Shift_TimeInOvertime <= FP_Punch8 AND Shift_TimeOutOvertime >= FP_Punch8 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch8;
					ELSEIF O1 = '00:00:00' AND FP_Punch8 != In1 AND FP_Punch8 != Out1 AND FP_Punch8 != In2 AND FP_Punch8 != Out2 AND FP_Punch8 != In3 AND FP_Punch8 != Out3 AND FP_Punch8 != In4 AND FP_Punch8 != Out4 AND FP_Punch8 != In5 AND FP_Punch8 != Out5 THEN
						SET O1 = FP_Punch8;
					ELSEIF O2 = '00:00:00' AND FP_Punch8 != In1 AND FP_Punch8 != Out1 AND FP_Punch8 != In2 AND FP_Punch8 != Out2 AND FP_Punch8 != In3 AND FP_Punch8 != Out3 AND FP_Punch8 != In4 AND FP_Punch8 != Out4 AND FP_Punch8 != In5 AND FP_Punch8 != Out5 THEN
						SET O2 = FP_Punch8;
					END IF;
				END IF;

				-- Punch9
				IF FP_Punch9 > FP_Punch8 AND FP_Punch9 <> '00:00:00' AND FP_Punch9 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch9, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch9;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch9;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch9 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch9;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch9 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch9 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch9 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch9;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch9 AND Shift_TimeInPeriod2 >= FP_Punch9 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch9 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch9;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch9 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch9 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch9 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch9 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch9 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch9 AND Shift_TimeInPeriod3 >= FP_Punch9 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch9 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch9 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch9 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch9 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch9 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch9 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch9 AND Shift_TimeInPeriod4 >= FP_Punch9 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch9 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch9 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch9 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch9 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch9;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch9 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch9;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch9 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch9 AND Shift_TimeInPeriod5 >= FP_Punch9 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch9 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch9;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch9 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch9 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch9 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch9 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch9;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch9 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch9;
					ELSEIF Shift_TimeInOvertime <= FP_Punch9 AND Shift_TimeOutOvertime >= FP_Punch9 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch9;
					ELSEIF Shift_TimeInOvertime <= FP_Punch9 AND Shift_TimeOutOvertime >= FP_Punch9 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch9;
					ELSEIF O1 = '00:00:00' AND FP_Punch9 != In1 AND FP_Punch9 != Out1 AND FP_Punch9 != In2 AND FP_Punch9 != Out2 AND FP_Punch9 != In3 AND FP_Punch9 != Out3 AND FP_Punch9 != In4 AND FP_Punch9 != Out4 AND FP_Punch9 != In5 AND FP_Punch9 != Out5 THEN
						SET O1 = FP_Punch9;
					ELSEIF O2 = '00:00:00' AND FP_Punch9 != In1 AND FP_Punch9 != Out1 AND FP_Punch9 != In2 AND FP_Punch9 != Out2 AND FP_Punch9 != In3 AND FP_Punch9 != Out3 AND FP_Punch9 != In4 AND FP_Punch9 != Out4 AND FP_Punch9 != In5 AND FP_Punch9 != Out5 THEN
						SET O2 = FP_Punch9;
					END IF;
				END IF;

				-- Punch10
				IF FP_Punch10 > FP_Punch9 AND FP_Punch10 <> '00:00:00' AND FP_Punch10 NOT IN(In1, Out1, In2, Out2, In3, Out3, In4, Out4, In5, Out5, O1, O2) THEN
					IF fnHRMCheckOutLeave(FP_Punch10, CheckOutLeave) > 0 THEN
						IF O1 = '00:00:00' THEN
							SET O1 = FP_Punch10;
						ELSEIF O2 = '00:00:00' THEN
							SET O2 = FP_Punch10;
						ELSE
							SET CheckOutLeaveInOut = CONCAT(CheckOutLeaveInOut,FP_Punch1,';');
						END IF;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 >= FP_Punch10 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch10;
					ELSEIF Shift_TimeInPeriod1 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= FP_Punch10 AND In1 = '00:00:00' THEN
						SET In1 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch10 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod1 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= FP_Punch10 AND In1 <> '00:00:00' AND Out1 = '00:00:00' THEN
						SET Out1 = FP_Punch10;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch10 AND Shift_TimeInPeriod2 >= FP_Punch10 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 >= FP_Punch10 AND In2 = '00:00:00' AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch10;
					ELSEIF ( Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeOutPeriod1 <= FP_Punch10 AND  ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= FP_Punch10 AND In2 = '00:00:00' AND Out1 <> '00:00:00') OR (Shift_TimeInPeriod2 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt*60)) >= FP_Punch10 AND Out1 = '00:00:00') THEN
						SET In2 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch10 AND In2 <> '00:00:00' AND Out2 = '00:00:00'  THEN
						SET Out2 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod2 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= FP_Punch10 AND In2 <> '00:00:00' AND Out2 = '00:00:00' THEN
						SET Out2 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch10 AND Shift_TimeInPeriod3 >= FP_Punch10 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 >= FP_Punch10 AND In3 = '00:00:00' AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeOutPeriod2 <= FP_Punch10 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= FP_Punch10 AND In3 = '00:00:00' AND Out2 <> '00:00:00') OR (Shift_TimeInPeriod3 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt*60)) >= FP_Punch10 AND Out2 = '00:00:00') THEN
						SET In3 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch10 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod3 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= FP_Punch10 AND In3 <> '00:00:00' AND Out3 = '00:00:00' THEN
						SET Out3 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch10 AND Shift_TimeInPeriod4 >= FP_Punch10 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 >= FP_Punch10 AND In4 = '00:00:00' AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeOutPeriod3 <= FP_Punch10 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= FP_Punch10 AND In4 = '00:00:00' AND Out3 <> '00:00:00') OR (Shift_TimeInPeriod4 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt*60)) >= FP_Punch10 AND Out3 = '00:00:00') THEN
						SET In4 = FP_Punch10;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch10 AND In4 <> '00:00:00' AND Out4 = '00:00:00'  THEN
						SET Out4 = FP_Punch10;
					ELSEIF  Shift_TimeOutPeriod4 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= FP_Punch10 AND In4 <> '00:00:00' AND Out4 = '00:00:00' THEN
						SET Out4 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch10 AND Shift_TimeInPeriod5 >= FP_Punch10 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 >= FP_Punch10 AND In5 = '00:00:00' AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch10;
					ELSEIF (Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeOutPeriod4 <= FP_Punch10 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= FP_Punch10 AND In5 = '00:00:00' AND Out4 <> '00:00:00') OR (Shift_TimeInPeriod5 != "00:00:00" AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt*60)) >= FP_Punch10 AND Out4 = '00:00:00') THEN
						SET In5 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 <= FP_Punch10 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch10;
					ELSEIF Shift_TimeOutPeriod5 != "00:00:00" AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= FP_Punch10 AND In5 <> '00:00:00' AND Out5 = '00:00:00' THEN
						SET Out5 = FP_Punch10;
					ELSEIF Shift_TimeInOvertime <= FP_Punch10 AND Shift_TimeOutOvertime >= FP_Punch10 AND OverIn = '00:00:00'  THEN
						SET OverIn = FP_Punch10;
					ELSEIF Shift_TimeInOvertime <= FP_Punch10 AND Shift_TimeOutOvertime >= FP_Punch10 AND OverOut = '00:00:00' AND OverIn <> '00:00:00'  THEN
						SET OverOut = FP_Punch10;
					ELSEIF O1 = '00:00:00' AND FP_Punch10 != In1 AND FP_Punch10 != Out1 AND FP_Punch10 != In2 AND FP_Punch10 != Out2 AND FP_Punch10 != In3 AND FP_Punch10 != Out3 AND FP_Punch10 != In4 AND FP_Punch10 != Out4 AND FP_Punch10 != In5 AND FP_Punch10 != Out5 THEN
						SET O1 = FP_Punch10;
					ELSEIF O2 = '00:00:00' AND FP_Punch10 != In1 AND FP_Punch10 != Out1 AND FP_Punch10 != In2 AND FP_Punch10 != Out2 AND FP_Punch10 != In3 AND FP_Punch10 != Out3 AND FP_Punch10 != In4 AND FP_Punch10 != Out4 AND FP_Punch10 != In5 AND FP_Punch10 != Out5 THEN
						SET O2 = FP_Punch10;
					END IF;
				END IF;

			-- Check Late
			IF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 < In1 AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= In1 AND In1 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In1%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In1,Shift_TimeInPeriod1), In1, TimeBreak1, 'TimeIn') > LeaveDurationInOut1 THEN
						SET CheckLateIn1 = 1;
						SET CheckLateDurationIn1 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In1,Shift_TimeInPeriod1),LeaveDurationInOut1), In1, TimeBreak1, 'TimeIn');
						SET checkLateDurationDeductIn1 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn1);
					END IF;
				ELSE
					SET CheckLateIn1 = 1;
					SET CheckLateDurationIn1 = fnHRMCheckBreakTime(TIMEDIFF(In1,Shift_TimeInPeriod1), In1, TimeBreak1, 'TimeIn');
					SET checkLateDurationDeductIn1 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn1);
				END IF;
			END IF;

			IF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 > Out1 AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= Out1 AND In1 <> '00:00:00' AND Out1 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out1%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod1, Out1), Out1, TimeBreak1, 'TimeOut') > LeaveDurationInOut1 THEN
						SET CheckLateOut1 = 1;
						SET CheckLateDurationOut1 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod1, Out1),LeaveDurationInOut1), Out1, TimeBreak1, 'TimeOut');
						SET checkLateDurationDeductOut1 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut1);
					END IF;
				ELSE
					SET CheckLateOut1 = 1;
					SET CheckLateDurationOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod1, Out1), Out1, TimeBreak1, 'TimeOut');
					SET checkLateDurationDeductOut1 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut1);
				END IF;
			END IF;
		
			IF Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 < In2 AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= In2 AND In2 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In2%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In2,Shift_TimeInPeriod2), In2, TimeBreak2, 'TimeIn') > LeaveDurationInOut2 THEN
						SET CheckLateIn2 = 1;
						SET CheckLateDurationIn2 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In2,Shift_TimeInPeriod2),LeaveDurationInOut2), In2, TimeBreak2, 'TimeIn');
						SET checkLateDurationDeductIn2 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn2);
					END IF;
				ELSE
					SET CheckLateIn2 = 1;
					SET CheckLateDurationIn2 = fnHRMCheckBreakTime(TIMEDIFF(In2,Shift_TimeInPeriod2), In2, TimeBreak2, 'TimeIn');
					SET checkLateDurationDeductIn2 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn2);
				END IF;
			END IF;

			IF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 > Out2 AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= Out2 AND In2 <> '00:00:00' AND Out2 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out2%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod2, Out2), Out2, TimeBreak2, 'TimeOut') > LeaveDurationInOut2 THEN
						SET CheckLateOut2 = 1;
						SET CheckLateDurationOut2 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod2, Out2),LeaveDurationInOut2), Out2, TimeBreak2, 'TimeOut');
						SET checkLateDurationDeductOut2 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut2);
					END IF;
				ELSE
					SET CheckLateOut2 = 1;
					SET CheckLateDurationOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod2, Out2), Out2, TimeBreak2, 'TimeOut');
					SET checkLateDurationDeductOut2 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut2);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 < In3 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= In3 AND In3 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In3%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In3,Shift_TimeInPeriod3), In3, TimeBreak3, 'TimeIn') > LeaveDurationInOut3 THEN
						SET CheckLateIn3 = 1;
						SET CheckLateDurationIn3 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In3,Shift_TimeInPeriod3),LeaveDurationInOut3), In3, TimeBreak3, 'TimeIn');
						SET checkLateDurationDeductIn3 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn3);
					END IF;
				ELSE
					SET CheckLateIn3 = 1;
					SET CheckLateDurationIn3 = fnHRMCheckBreakTime(TIMEDIFF(In3,Shift_TimeInPeriod3), In3, TimeBreak3, 'TimeIn');
					SET checkLateDurationDeductIn3 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn3);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 > Out3 AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= Out3 AND In3 <> '00:00:00' AND Out3 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out3%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod3, Out3), Out3, TimeBreak3, 'TimeOut') > LeaveDurationInOut3 THEN
						SET CheckLateOut3 = 1;
						SET CheckLateDurationOut3 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod3, Out3),LeaveDurationInOut3), Out3, TimeBreak3, 'TimeOut');
						SET checkLateDurationDeductOut3 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut3);
					END IF;
				ELSE
					SET CheckLateOut3 = 1;
					SET CheckLateDurationOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod3, Out3), Out3, TimeBreak3, 'TimeOut');
					SET checkLateDurationDeductOut3 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut3);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 < In4 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= In4 AND In4 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In4%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In4,Shift_TimeInPeriod4), In4, TimeBreak4, 'TimeIn') > LeaveDurationInOut4 THEN
						SET CheckLateIn4 = 1;
						SET CheckLateDurationIn4 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In4,Shift_TimeInPeriod4),LeaveDurationInOut4), In4, TimeBreak4, 'TimeIn');
						SET checkLateDurationDeductIn4 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn4);
					END IF;
				ELSE
					SET CheckLateIn4 = 1;
					SET CheckLateDurationIn4 = fnHRMCheckBreakTime(TIMEDIFF(In4,Shift_TimeInPeriod4), In4, TimeBreak4, 'TimeIn');
					SET checkLateDurationDeductIn4 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn4);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 > Out4 AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= Out4 AND In4 <> '00:00:00' AND Out4 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out4%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod4, Out4), Out4, TimeBreak4, 'TimeOut') > LeaveDurationInOut4 THEN
						SET CheckLateOut4 = 1;
						SET CheckLateDurationOut4 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod4, Out4),LeaveDurationInOut4), Out4, TimeBreak4, 'TimeOut');
						SET checkLateDurationDeductOut4 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut4);
					END IF;
				ELSE
					SET CheckLateOut4 = 1;
					SET CheckLateDurationOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod4, Out4), Out4, TimeBreak4, 'TimeOut');
					SET checkLateDurationDeductOut4 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut4);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 < In5 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= In5 AND In5 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In5%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In5,Shift_TimeInPeriod5), In5, TimeBreak5, 'TimeIn') > LeaveDurationInOut5 THEN
						SET CheckLateIn5 = 1;
						SET CheckLateDurationIn5 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In5,Shift_TimeInPeriod5),LeaveDurationInOut5), In5, TimeBreak5, 'TimeIn');
						SET checkLateDurationDeductIn5 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn5);
					END IF;
				ELSE
					SET CheckLateIn5 = 1;
					SET CheckLateDurationIn5 = fnHRMCheckBreakTime(TIMEDIFF(In5,Shift_TimeInPeriod5), In5, TimeBreak5, 'TimeIn');
					SET checkLateDurationDeductIn5 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn5);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 > Out5 AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= Out5 AND In5 <> '00:00:00' AND Out5 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out5%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod5, Out5), Out5, TimeBreak5, 'TimeOut') > LeaveDurationInOut5 THEN
						SET CheckLateOut5 = 1;
						SET CheckLateDurationOut5 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod5, Out5),LeaveDurationInOut5), Out5, TimeBreak5, 'TimeOut');
						SET checkLateDurationDeductOut5 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut5);
					END IF;
				ELSE
					SET CheckLateOut5 = 1;
					SET CheckLateDurationOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod5, Out5), Out5, TimeBreak5, 'TimeOut');
					SET checkLateDurationDeductOut5 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut5);	
				END IF;		
			END IF;

			IF S IS NULL THEN
				SET S = '';
			END IF;
			
			IF S <> 'HO' AND S <> 'B' THEN
				
				-- Check AB
				IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND (In1 = '00:00:00' OR Out1 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct, fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1,Shift_TimeIn1), '00:00:00', TimeBreak1, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn1 = '00:00:00' AND CheckLateDurationOut1 = '00:00:00' AND LeaveDurationInOut1 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut1);
					END IF;

					SET CheckLateIn1 = 0;
					SET CheckLateDurationIn1 = '00:00:00';
					SET checkLateDurationDeductIn1 = '00:00:00';
					SET CheckLateOut1 = 0;
					SET CheckLateDurationOut1 = '00:00:00';
					SET checkLateDurationDeductOut1 = '00:00:00';
					
				END IF;
				IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND (In2 = '00:00:00' OR Out2 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct, fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2,Shift_TimeIn2), '00:00:00', TimeBreak2, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn2 = '00:00:00' AND CheckLateDurationOut2 = '00:00:00' AND LeaveDurationInOut2 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut2);
					END IF;

					SET CheckLateIn2 = 0;
					SET CheckLateDurationIn2 = '00:00:00';
					SET checkLateDurationDeductIn2 = '00:00:00';
					SET CheckLateOut2 = 0;
					SET CheckLateDurationOut2 = '00:00:00';
					SET checkLateDurationDeductOut2 = '00:00:00';
				END IF;
				IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND (In3 = '00:00:00' OR Out3 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3,Shift_TimeIn3), '00:00:00', TimeBreak3, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn3 = '00:00:00' AND CheckLateDurationOut3 = '00:00:00' AND LeaveDurationInOut3 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut3);
					END IF;

					SET CheckLateIn3 = 0;
					SET CheckLateDurationIn3 = '00:00:00';
					SET checkLateDurationDeductIn3 = '00:00:00';
					SET CheckLateOut3 = 0;
					SET CheckLateDurationOut3 = '00:00:00';
					SET checkLateDurationDeductOut3 = '00:00:00';
				END IF;
				IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND (In4 = '00:00:00' OR Out4 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4,Shift_TimeIn4), '00:00:00', TimeBreak4, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn4 = '00:00:00' AND CheckLateDurationOut4 = '00:00:00' AND LeaveDurationInOut4 = '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut4);
					END IF;

					SET CheckLateIn4 = 0;
					SET CheckLateDurationIn4 = '00:00:00';
					SET checkLateDurationDeductIn4 = '00:00:00';
					SET CheckLateOut4 = 0;
					SET CheckLateDurationOut4 = '00:00:00';
					SET checkLateDurationDeductOut4 = '00:00:00';
				END IF;
				IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND (In5 = '00:00:00' OR Out5 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5,Shift_TimeIn5), '00:00:00', TimeBreak5, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn5 = '00:00:00' AND CheckLateDurationOut5 = '00:00:00' AND LeaveDurationInOut5 = '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut5);
					END IF;

					SET CheckLateIn5 = 0;
					SET CheckLateDurationIn5 = '00:00:00';
					SET checkLateDurationDeductIn5 = '00:00:00';
					SET CheckLateOut5 = 0;
					SET CheckLateDurationOut5 = '00:00:00';
					SET checkLateDurationDeductOut5 = '00:00:00';
				END IF;
		
				IF fnHRMTimeToFloat(checkAbDurationDeduct) > Shift_TotalWorkHour THEN
					SET checkAbDurationDeduct = CONCAT(FLOOR(Shift_TotalWorkHour),':',(Shift_TotalWorkHour -FLOOR(Shift_TotalWorkHour))*60, ':00');
				END IF;
				
				-- Check Leave
				IF CheckOutLeave <> "" THEN
					SET CheckL = CheckL + 1;
				ELSEIF In1 = '00:00:01' OR LeaveDurationInOut1 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out1 = '00:00:01' OR LeaveDurationInOut1 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;	
				ELSEIF In2 = '00:00:01' OR LeaveDurationInOut2 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out2 = '00:00:01' OR LeaveDurationInOut2 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In3 = '00:00:01' OR LeaveDurationInOut3 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out3 = '00:00:01' OR LeaveDurationInOut3 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In4 = '00:00:01' OR LeaveDurationInOut4 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out4 = '00:00:01' OR LeaveDurationInOut4 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In5 = '00:00:01' OR LeaveDurationInOut5 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out5 = '00:00:01' OR LeaveDurationInOut5 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF O1 = '00:00:01' THEN
					SET CheckL = CheckL + 1;
				ELSEIF O2 = '00:00:01' THEN
					SET CheckL = CheckL + 1; 
				END IF;

				-- Check Work Hour
				IF In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out1,IN1));
				END IF;
				IF In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out2,IN2));
				END IF;
				IF In3 <> '00:00:00' AND In3 <> '00:00:01' AND Out3 <> '00:00:00' AND Out3 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out3,IN3));
				END IF;
				IF In4 <> '00:00:00' AND In4 <> '00:00:01' AND Out4 <> '00:00:00' AND Out4 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out4,IN4));
				END IF;
				IF In5 <> '00:00:00' AND In5 <> '00:00:01' AND Out5 <> '00:00:00' AND Out5 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out5,IN5));
				END IF;
				IF WorkHour > Shift_TotalWorkHour THEN
					SET WorkHour = Shift_TotalWorkHour;
				END IF;

				SET TotalCheckLate = TotalCheckLate + CheckLateIn1 + CheckLateOut1 + CheckLateIn2 + CheckLateOut2 + CheckLateIn3 + CheckLateOut3 + CheckLateIn4 + CheckLateOut4 + CheckLateIn5 + CheckLateOut5;

				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn1);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut1);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn2);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut2);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn3);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut3);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn4);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut4);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn5);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut5);

				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn1);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut1);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn2);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut2);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn3);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut3);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn4);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut4);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn5);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut5);

				-- Check Negative AB & Late
				IF checkAbDurationDeduct <= '00:00:00' THEN
					SET checkAbDurationDeduct = '00:00:00';
					SET CheckAb = 0;
				END IF;
				IF TotalCheckLateDuration <= '00:00:00' THEN
					SET TotalCheckLateDuration = '00:00:00';
					SET TotalCheckLateDurationDeduct = '00:00:00';
					SET TotalCheckLate = 0;
				END IF;


				IF TotalCheckLate >0 AND CheckAb >0 AND CheckL > 0 THEN
					SET S = 'LA/AB/LE';
				ELSEIF TotalCheckLate >0 AND CheckAb >0 AND CheckL <= 0 THEN
					SET S = 'LA/AB';
				ELSEIF TotalCheckLate >0 AND CheckAb <= 0 AND CheckL > 0 THEN
					SET S = 'LA/LE';
				ELSEIF TotalCheckLate <= 0 AND CheckAb >0 AND CheckL > 0 THEN
					SET S = 'AB/LE';
				ELSEIF TotalCheckLate >0 AND CheckAb <= 0 AND CheckL <= 0 THEN
					SET S = 'LA';
				ELSEIF TotalCheckLate <=0 AND CheckAb > 0 AND CheckL <= 0 THEN
					SET S = 'AB';
				ELSEIF TotalCheckLate <=0 AND CheckAb <= 0 AND CheckL > 0 THEN
					SET S = 'LE';
				ELSE 
					SET S = 'P';
				END IF;

				IF In1 = '00:00:00' AND Out1 = '00:00:00' AND In2 = '00:00:00' AND Out2 = '00:00:00' AND In3 = '00:00:00' AND Out3 = '00:00:00' AND In4 = '00:00:00' AND Out4 = '00:00:00' AND In5 = '00:00:00' AND Out5 = '00:00:00' AND S = 'P' THEN
					SET S = 'B';
				END IF;

			END IF;

				IF CheckExist	> 0 THEN
					UPDATE hrm_timesheet_attendance SET Att_In1=In1,Att_Out1=Out1,Att_In2=In2,Att_Out2=Out2,Att_In3=In3,Att_Out3=Out3,Att_In4=In4,Att_Out4=Out4,Att_In5=In5,Att_Out5=Out5,Att_OvertimeIn=OverIn,Att_OvertimeOut=OverOut,Att_Other1=O1,Att_Other2=O2,Att_LateAmount=TotalCheckLate,Att_ABAmount=CheckAb,Att_Status=S,Att_RStatus=S,Att_WorkHour=WorkHour, Att_LateDuration=TotalCheckLateDuration, Att_LateDurationDeduct = TotalcheckLateDurationDeduct, Att_ABDurationDeduct = checkAbDurationDeduct WHERE Att_FPID=FP_ID AND Att_Date=FP_Date;
				ELSE
					INSERT INTO hrm_timesheet_attendance(Att_EmpID,Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_LateAmount,Att_ABAmount,Att_Status,Att_RStatus,Att_WorkHour,Att_LateDuration,Att_LateDurationDeduct,Att_ABDurationDeduct) VALUES (SEmpID,FP_ID,FP_Date,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,TotalCheckLate,CheckAb,S,S,WorkHour,TotalCheckLateDuration,TotalcheckLateDurationDeduct,checkAbDurationDeduct);
				END IF;
				
				#INSERT INTO hrm_emp_grade VALUES(CONCAT(FP_Punch1, FP_Punch2, FP_Punch3, FP_Punch4, FP_Punch5, FP_Punch6, FP_Punch7, FP_Punch8, FP_Punch9, FP_Punch10));
				#INSERT INTO hrm_emp_grade VALUES(CONCAT(SEmpID,FP_ID,FP_Date,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,CheckLate,CheckAb,S,S,WorkHour,CheckLateDuration,checkLateDurationDeduct,checkAbDurationDeduct));				
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddAuthorisation`;
DELIMITER |
CREATE PROCEDURE `spHRMAddAuthorisation`(userid varchar(255), AuthName varchar(255), Auth text, AuthDetail text, AuthType varchar(255),AuthAmount int, AuthRAmount int, AuthGroupID varchar(255), AuthGroupAmount varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE CheckGroupAmount TINYINT DEFAULT(0);
	DECLARE TempGroupAmount INT DEFAULT(0);
	DECLARE TempGroupID VARCHAR(255) DEFAULT('');

	-- Check Group Amount And Auth Amount
	IF LOWER(AuthType) = 'group' THEN
		myloop1: WHILE (LOCATE(',', AuthGroupID) > 0)
		DO
			SET @value = LEFT(AuthGroupID, LOCATE(',',AuthGroupID) - 1);    
			SET AuthGroupID = SUBSTRING(AuthGroupID, LOCATE(',',AuthGroupID) + 1);
			IF @value != "" THEN
				myloop2: WHILE (LOCATE(',', AuthGroupAmount) > 0)
				DO
					SET @value1 = LEFT(AuthGroupAmount, LOCATE(',',AuthGroupAmount) - 1);    
					SET AuthGroupAmount = SUBSTRING(AuthGroupAmount, LOCATE(',',AuthGroupAmount) + 1);
					IF @value1 != "" THEN
						SET TempGroupID = @value;
						SET TempGroupAmount = @value1;
						SELECT IF(COUNT(*) < TempGroupAmount, 1, 0) INTO CheckGroupAmount FROM hrm_authorisation_group_detail WHERE AuthGroup_ID = @value;
						LEAVE myloop2;
					END IF;
				END WHILE;
				IF CheckGroupAmount >0 THEN
					LEAVE myloop1;
				END IF;
			END IF;
		END WHILE;
	END IF;


	IF Auth != "" AND ((LOWER(AuthType) = 'individual' AND AuthAmount <= AuthRAmount) OR (LOWER(AuthType) = 'group' AND CheckGroupAmount <= 0)) THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_authorisation WHERE LOWER(Auth_Name) = AuthName;
		IF CheckExist <= 0 THEN
			CALL spHRMGetNumberPrefix("Auth", ID);
			SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation(Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount) VALUES ", Auth, "; ");
			SET @SQL1 = REPLACE(@SQL1, 'TempAuth_ID', ID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		
			CALL spHRMUpdateNumberPrefix("Auth");

			CALL spHRMAddLog(userid, "insert", "Authorisation", ID);

			DELETE FROM hrm_authorisation_detail WHERE Auth_ID = ID;
			IF AuthDetail != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_detail(Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount) VALUES ", AuthDetail, ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempAuth_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
			END IF;

			SELECT ID;
			CALL hrm_message('1101401', 'Auth', 'create', ID);

		ELSE
			SET ID = "exist";
			SELECT ID;
			CALL hrm_message('1101404', 'Auth', 'exist', AuthName);
		END IF;
	ELSE
		SET ID = "not allowed";
		SELECT ID;
		IF LOWER(AuthType) = 'individual' THEN
			CALL hrm_message('1101406', 'Auth', 'notallowed', AuthAmount);
		ELSE
			CALL hrm_message_param3('1101407', 'Auth', 'notallowed', TempGroupID, TempGroupAmount, '');
		END IF;
		
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddAuthorisationGroup`;
DELIMITER |
CREATE PROCEDURE `spHRMAddAuthorisationGroup`(userid varchar(255), AuthGroupName varchar(255), AuthGroup text, AuthGroupDetail text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF AuthGroup != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_authorisation_group WHERE LOWER(AuthGroup_Name) = AuthGroupName;
		IF CheckExist <= 0 THEN
			CALL spHRMGetNumberPrefix("AuthGroup", ID);
			SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_group(AuthGroup_ID,AuthGroup_Name,AuthGroup_Description) VALUES ", AuthGroup, "; ");
			SET @SQL1 = REPLACE(@SQL1, 'TempAuth_ID', ID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		
			CALL spHRMUpdateNumberPrefix("AuthGroup");

			CALL spHRMAddLog(userid, "insert", "AuthorisationGroup", ID);

			DELETE FROM hrm_authorisation_group_detail WHERE AuthGroup_ID = ID;
			IF AuthGroupDetail != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_group_detail(AuthGroup_ID,AuthGroup_EmpID) VALUES ", AuthGroupDetail, ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempAuth_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
			END IF;

			SELECT ID;
			CALL hrm_message('1101501', 'AuthGroup', 'create', ID);
		ELSE
			SET ID = "exist";
			SELECT ID;
			CALL hrm_message('1101504', 'AuthGroup', 'exist', AuthGroupName);
		END IF;
		
	END IF;
END |
DELIMITER ;

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

	DELETE FROM hrm_authorisation_temp WHERE Auth_TranID = TranID; -- AND Auth_ID = AuthID;
	INSERT INTO hrm_authorisation_temp(Auth_TranID,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount) 
																		(SELECT TranID,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount FROM hrm_authorisation WHERE Auth_ID = AuthID);

	DELETE FROM hrm_authorisation_detail_temp WHERE Auth_TranID = TranID; -- AND Auth_ID = AuthID;
	INSERT INTO hrm_authorisation_detail_temp(Auth_TranID,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount) 
																					(SELECT TranID,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount FROM hrm_authorisation_detail WHERE Auth_ID = AuthID);

	DELETE FROM hrm_authorisation_group_temp WHERE Auth_TranID = TranID;-- AND AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID);
	INSERT INTO hrm_authorisation_group_temp(Auth_TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description) (SELECT TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description FROM hrm_authorisation_group WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	DELETE FROM hrm_authorisation_group_detail_temp WHERE Auth_TranID = TranID;-- AND AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID);
	INSERT INTO hrm_authorisation_group_detail_temp(Auth_TranID,AuthGroup_ID,AuthGroup_EmpID) (SELECT TranID,AuthGroup_ID,AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

END |
DELIMITER ;

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

	DECLARE D1 INTEGER DEFAULT 0;
	DECLARE AuthID VARCHAR(100) DEFAULT '';
	DECLARE TranID VARCHAR(100) DEFAULT '';
	DECLARE C1 CURSOR FOR SELECT DISTINCT(Auth_ProcessID), Auth_ID FROM hrm_authorisation_approved;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET D1 = 1;
	OPEN C1;
			L1: LOOP FETCH C1 INTO TranID, AuthID;
					IF D1 = 1 THEN LEAVE L1; END IF;

					DELETE FROM hrm_authorisation_temp WHERE Auth_TranID = TranID; -- AND Auth_ID = AuthID;
					INSERT INTO hrm_authorisation_temp(Auth_TranID,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount) 
																						(SELECT TranID,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount FROM hrm_authorisation WHERE Auth_ID = AuthID);

					DELETE FROM hrm_authorisation_detail_temp WHERE Auth_TranID = TranID; -- AND Auth_ID = AuthID;
					INSERT INTO hrm_authorisation_detail_temp(Auth_TranID,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount) 
																									(SELECT TranID,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount FROM hrm_authorisation_detail WHERE Auth_ID = AuthID);

					DELETE FROM hrm_authorisation_group_temp WHERE Auth_TranID = TranID;-- AND AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID);
					INSERT INTO hrm_authorisation_group_temp(Auth_TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description) (SELECT TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description FROM hrm_authorisation_group WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

					DELETE FROM hrm_authorisation_group_detail_temp WHERE Auth_TranID = TranID;-- AND AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID);
					INSERT INTO hrm_authorisation_group_detail_temp(Auth_TranID,AuthGroup_ID,AuthGroup_EmpID) (SELECT TranID,AuthGroup_ID,AuthGroup_EmpID FROM hrm_authorisation_group_detail WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));
			
			END LOOP L1;
	CLOSE C1;

	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddAutoFP`;
DELIMITER |
CREATE PROCEDURE `spHRMAddAutoFP`(userid varchar(255),SName varchar(255),SValue text, SValueDetail text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE exist INT DEFAULT(0);

	SELECT COUNT(*) INTO exist FROM hrm_timesheet_auto_fingerprint WHERE LOWER(AutoFP_ShiftID) = SName;

	IF SValue != "" AND exist <=0 THEN	
				CALL spHRMGetNumberPrefix("AutoFP", ID);
	
				SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_auto_fingerprint(AutoFP_ID,AutoFP_ShiftID) VALUES ", SValue, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_auto_finger_detail(AutoFP_ID,AutoFP_Day,AutoFP_In1,AutoFP_Out1,AutoFP_In2,AutoFP_Out2,AutoFP_In3,AutoFP_Out3,AutoFP_In4,AutoFP_Out4,AutoFP_In5,AutoFP_Out5) VALUES ", SValueDetail, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				CALL spHRMUpdateNumberPrefix("AutoFP");

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Autofp', ID);

				SELECT ID;
				CALL hrm_message('1102201', 'AutoFP', 'create', ID);

	ELSE
		SET ID = "exist";
		SELECT ID;
		CALL hrm_message('1102204', 'AutoFp', 'exist', SName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddBonus`;
DELIMITER |
CREATE PROCEDURE `spHRMAddBonus`(userid varchar(255),SValue text, SValueDetail text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);

	IF SValue != "" THEN	
				CALL spHRMGetNumberPrefix("Bonus", ID);
	
				SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_bonus(Bonus_ID,Bonus_Date,Bonus_Reason,Bonus_Description) VALUES ", SValue, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_bonus_detail(Bonus_ID,Bonus_EmpID,Bonus_PayType,Bonus_PayAmount) VALUES ", SValueDetail, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				CALL spHRMUpdateNumberPrefix("Bonus");

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Bonus', ID);

				SELECT ID;
				CALL hrm_message('1100201', 'Bonus', 'create', ID);

	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddCurrency`;
DELIMITER |
CREATE PROCEDURE `spHRMAddCurrency`(userid varchar(255),CName varchar(255),CValue text, CValue2 text,SDefault int)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	IF CValue != "" THEN

		SELECT COUNT(*) INTO CheckExist FROM hrm_payroll_currency WHERE LOWER(Currency_Name) = CName;

			IF CheckExist <= 0 THEN

				CALL spHRMGetNumberPrefix("Currency", ID);

				IF SDefault = 1 THEN
					UPDATE hrm_payroll_currency SET Currency_Default = 0;
				END IF;
	
				SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_currency(Currency_ID,Currency_Name,Currency_Placing,Currency_Rate,Currency_Description,Currency_Default) VALUES ", CValue, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
				IF CValue2 != "" THEN
					SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_currency_history(Currency_ID,Currency_Name,Currency_Date,Currency_Rate) VALUES ", CValue2, ";");
					SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;
				END IF;

				CALL spHRMUpdateNumberPrefix("Currency");

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Currency', ID);

				SELECT ID;

				CALL hrm_message('1100001', 'Currency', 'create', ID);
				

			ELSE
				SET ID = "exist";
				SELECT ID;
				CALL hrm_message('1100004', 'Currency', 'exist', CName);
			END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddDayoff`;
DELIMITER |
CREATE PROCEDURE `spHRMAddDayoff`(userid varchar(255),SEmpID varchar(255),SDate Date,SValue text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE AuthID VARCHAR(255) DEFAULT("");
	DECLARE AuthType VARCHAR(255) DEFAULT("");
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");
	DECLARE CheckAllowLimited TINYINT DEFAULT(0);
	DECLARE CheckAmount TINYINT DEFAULT(0);
	
	SELECT Setting_Value INTO CheckAllowLimited FROM hrm_setting WHERE Setting_Type = "Dayoff" AND Setting_Name = "Dayoff_Monthly_Amount";

	SELECT COUNT(*) INTO CheckAmount FROM hrm_timesheet_dayoff WHERE Dayoff_EmpID = SEmpID AND MONTH(Dayoff_Date) = MONTH(SDate) AND YEAR(Dayoff_Date) = YEAR(SDate) AND Dayoff_Status <> 'rejected';
	IF SValue != "" AND CheckAmount <= CheckAllowLimited THEN

			-- Check Auth Allow or not
			SELECT Setting_Value INTO CheckAuth FROM hrm_setting WHERE Setting_Type = "Authorisation" AND Setting_Name = "Authorisation_Dayoff";

			IF CheckAuth = "1" THEN
			
				-- find Auth ID
				SELECT Auth_ID INTO AuthID FROM hrm_authorisation_employee WHERE Emp_ID = SEmpID AND Auth_Process = 'Dayoff';
				IF AuthID = "" THEN
					SELECT Setting_Value INTO AuthID FROM hrm_setting WHERE Setting_Name = 'Dayoff' AND Setting_Type = 'Authorisation';
				END IF;
				IF AuthID != "" THEN

							CALL spHRMGetNumberPrefix("Dayoff", ID);
	
							SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_dayoff(Dayoff_ID,Dayoff_Date,Dayoff_EmpID,Dayoff_Description,Dayoff_Status,Dayoff_AuthID) VALUES ", SValue, ";");
							SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
							SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'requested');	
							SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', AuthID);
							PREPARE St FROM @SQL1;
							EXECUTE St;
							DEALLOCATE PREPARE St;

							CALL spHRMUpdateNumberPrefix("Dayoff");

							INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Dayoff', ID);

							SELECT Auth_Type INTO AuthType FROM hrm_authorisation WHERE Auth_ID = AuthID;
				
							IF AuthType = "Individual" THEN
								CALL spHRMAddIAuthorisationApproved(AuthID, ID, 'Dayoff');
							ELSE
								CALL spHRMAddGAuthorisationApproved(AuthID, ID, 'Dayoff');
							END IF;
							CALL spHRMAddAuthorisationTemp(AuthID,ID); 
							SELECT ID;
							CALL hrm_message('1101701', 'Dayoff', 'create', ID);
				ELSE
					SET ID = "no authorisation";
					SELECT ID;
					CALL hrm_message('1101706', 'Dayoff', 'auth', SEmpID);
				END IF;

			ELSE

						CALL spHRMGetNumberPrefix("Dayoff", ID);
	
						SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_dayoff(Dayoff_ID,Dayoff_Date,Dayoff_EmpID,Dayoff_Description,Dayoff_Status,Dayoff_AuthID) VALUES ", SValue, ";");
						SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
						SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'approved');
						SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', AuthID);
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						-- Check Attendance
						CALL spHRMAttendanceLeaveFullDay(SEmpID, SDate, SDate);

						CALL spHRMUpdateNumberPrefix("Dayoff");
						INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Dayoff', ID);
						SELECT ID;
						CALL hrm_message('1101701', 'Dayoff', 'create', ID);
			END IF;
	ELSE
		SET ID = "not allow";
		SELECT ID;
		CALL hrm_message('1101707', 'Dayoff', 'notallowed', SDate);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddDeduction`;
DELIMITER |
CREATE PROCEDURE `spHRMAddDeduction`(userid varchar(255),SEmpID varchar(255),SValue text, SValue2 text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE AuthType VARCHAR(255) DEFAULT("");
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");
	DECLARE CheckOvertime int DEFAULT(0);

	IF SValue != "" THEN

			SELECT Setting_Value INTO CheckAuth FROM hrm_setting WHERE Setting_Type = "Authorisation" AND Setting_Name = "Authorisation_Deduction";

			IF CheckAuth = "1" THEN

				SELECT Auth_ID INTO CheckExist FROM hrm_authorisation_employee WHERE Emp_ID = SEmpID AND Auth_Process = 'Deduction';
				IF CheckExist = "" THEN
					SELECT Setting_Value INTO CheckExist FROM hrm_setting WHERE Setting_Name = 'Deduction' AND Setting_Type = 'Authorisation';
				END IF;

				IF CheckExist != "" THEN
					CALL spHRMGetNumberPrefix("Deduction", ID);
	
					SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_deduction(Deduction_ID,Deduction_EmpID,Deduction_Date,Deduction_Reason,Deduction_Amount,Deduction_Description,Deduction_Status,Deduction_AuthID) VALUES ", SValue, ";");
					SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
					SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'requested');
					SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', CheckExist);
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_deduction_detail(dd_id,dd_empid,dd_date,dd_amount,dd_status,dd_line) VALUES ", SValue2, ";");
					SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
					SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'Open');
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					CALL spHRMUpdateNumberPrefix("Deduction");

					INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Deduction', ID);

					SELECT Auth_Type INTO AuthType FROM hrm_authorisation WHERE Auth_ID = CheckExist;
				
					IF AuthType = "Individual" THEN
						CALL spHRMAddIAuthorisationApproved(CheckExist, ID, 'Deduction');
					ELSE
						CALL spHRMAddGAuthorisationApproved(CheckExist, ID, 'Deduction');
					END IF;
					CALL spHRMAddAuthorisationTemp(CheckExist,ID); 
					SELECT ID;
					CALL hrm_message('1100301', 'Deduction', 'create', ID);
				ELSE
					SET ID = "no authorisation";
					SELECT ID;
					CALL hrm_message('1100306', 'Deduction', 'auth', SEmpID);
				END IF;

			ELSE
				CALL spHRMGetNumberPrefix("Deduction", ID);
	
				SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_deduction(Deduction_ID,Deduction_EmpID,Deduction_Date,Deduction_Reason,Deduction_Amount,Deduction_Description,Deduction_Status,Deduction_AuthID) VALUES ", SValue, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'approved');
				SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', '');
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_deduction_detail(dd_id,dd_empid,dd_date,dd_amount,dd_status,dd_line) VALUES ", SValue2, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'Open');
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				CALL spHRMUpdateNumberPrefix("Deduction");
				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Deduction', ID);
				SELECT ID;
				CALL hrm_message('1100301', 'Deduction', 'create', ID);
			END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployee`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployee`(userid varchar(255),employee text,socialcommunication text, skill text,language text,education text,experience text,family text,contact text,training text,attachment text,membership text,insurance text,users text, userName varchar(255), SuserAssign varchar(255),CategoryName varchar(255), ContractTypeName text, LanguageName text, MembershipTypeName text, NationalityName varchar(255), NationalsName varchar(255), SchoolName text, SocialCommunicationName text, EmpStatus varchar(255), EmpType varchar(255), EmpCountry varchar(255), EmpPermanentCountry varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE EmpID VARCHAR(255) DEFAULT('');
	DECLARE Num LONG DEFAULT(0);
	DECLARE N INT DEFAULT(0);
	DECLARE SUID VARCHAR(255) DEFAULT('');
	DECLARE RoleESS VARCHAR(255) DEFAULT('');
	DECLARE TempEmpID VARCHAR(255) DEFAULT('');

	SET TempEmpID = EmpID;


	SELECT var_id,int_lastid,int_length INTO EmpID, Num, N FROM  ame_sys_prefix WHERE var_modid = 'MT-EMP';
	SET EmpID = CONCAT(EmpID, '',LPAD(CONCAT(Num,''),N,'0'));

	IF employee != "" THEN
		SET @SQL1 = CONCAT("INSERT INTO ame_mt_emp(var_id,var_name,var_name_other,var_hrm_salutation,var_hrm_sex,var_hrm_marital_status,dat_hrm_dob,var_cardid,var_hrm_nssfid,var_hrm_passportid,dat_hrm_visaexpire,var_tel1,var_tel2,var_hrm_home_tel,var_hrm_company_tel,var_hrm_emergency_person_name,var_hrm_emergency_relationship,var_hrm_emergency_tel,var_email,var_hrm_company_email,var_web,var_addr,var_hrm_address_kh,var_posid,var_img,var_hrm_status,dat_hrm_date,var_hrm_supervisor,dat_hrm_contact_date,var_hrm_grade,var_hrm_type,var_hrm_category,var_hrm_department_id,var_hrm_branch_id,var_hrm_nationality,var_hrm_nationals,var_hrm_bank_id,var_hrm_account_no,var_hrm_shift_type,var_hrm_shift_id,tin_hrm_allow_login,tin_hrm_notification_email,dat_hrm_joindate,var_addr1,var_addr2,var_addr3,var_addr5,var_addr4,var_addr6,var_hrm_state,var_addr7,var_hrm_permanent_address,var_hrm_permanent_home_no,var_hrm_permanent_street,var_hrm_permanent_village,var_hrm_permanent_district,var_hrm_permanent_commune,var_hrm_permanent_city,var_hrm_permanent_state,var_hrm_permanent_country,var_hrm_description,var_hrm_fpid,var_hrm_internal_id,tin_hrm_late_deduction,tin_hrm_probation,dat_hrm_enddateprobation,dat_hrm_date_status) VALUES('", EmpID, "',", employee, "); ");
		PREPARE St FROM @SQL1;
		EXECUTE St;
		DEALLOCATE PREPARE St;

		UPDATE ame_sys_prefix SET int_lastid = Num+1 WHERE var_modid = 'MT-EMP';

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Employee', EmpID);
		
		SELECT EmpID AS 'EmpID';
	
		CALL hrm_message('1104501', 'Employee', 'create', EmpID);

		DELETE FROM hrm_employee_social_communication WHERE Emp_ID = EmpID;
		IF socialcommunication != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_employee_social_communication(Emp_ID,SocialCommunication,SocialCommunication_Value) VALUES ", socialcommunication, ";");
			SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;

		DELETE FROM hrm_employee_skill WHERE Emp_ID = EmpID;
		IF skill != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_employee_skill(Emp_ID,Skill_Name,Skill_Level,Skill_Description) VALUES ", skill , ";");
			SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;

		DELETE FROM hrm_employee_language WHERE Emp_ID = EmpID;
		IF language != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_employee_language(Emp_ID,Language,Language_ReadLevel,Language_WriteLevel,Language_SpeakLevel,Language_UnderstandLevel,Language_Type) VALUES ", language , ";");
			SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;

		DELETE FROM hrm_employee_education WHERE Emp_ID = EmpID;
		IF education != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_employee_education(Emp_ID,Edu_Name,Edu_StartDate,Edu_EndDate,Edu_Degree,Edu_School,Edu_Major,Edu_Description,Edu_Attachfile) VALUES ", education , ";");
			SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;

		DELETE FROM hrm_employee_experience WHERE Emp_ID = EmpID;
		IF experience != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_employee_experience(Emp_ID,Ex_Position,Ex_Company,Ex_StartDate,Ex_EndDate,Ex_Description) VALUES ", experience , ";");
			SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;

		DELETE FROM hrm_employee_family WHERE Emp_ID = EmpID;
		IF family != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_employee_family(Emp_ID,Fam_Name,Fam_NameKh,Fam_DOB,Fam_Relative,Fam_Occupation,Fam_Tel,Fam_TaxDeduct) VALUES ", family , ";");
			SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;

		DELETE FROM hrm_employee_contract WHERE Emp_ID = EmpID;
		IF contact != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_employee_contract(Emp_ID,Con_Name,Con_Type,Con_StartDate,Con_EndDate,Con_Description,Con_EmpPosition,Con_EmpType,Con_EmpCategory,Con_EmpGrade,Con_EmpBranchID,Con_EmpDepartmentID,Con_AttachFile) VALUES ", contact , ";");
			SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
		END IF;
		
		DELETE FROM hrm_employee_training WHERE Emp_ID = EmpID;
		IF training != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_employee_training(Emp_ID,Train_InstituteName,Train_Certificate,Train_Course,Train_StartDate,Train_EndDate,Train_Description,Train_AttachFile) VALUES ", training , ";");
			SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
		END IF;
		
		DELETE FROM hrm_employee_attachment WHERE Emp_ID = EmpID;
		IF attachment != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_employee_attachment(Emp_ID,Att_FileName,Att_FilePath) VALUES ", attachment , ";");
			SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
		END IF;

		DELETE FROM hrm_employee_membership WHERE Emp_ID = EmpID;
		IF membership != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_employee_membership(Emp_ID,Mem_Name,Mem_Institute,Mem_GrantedOn,Mem_ValidThru,Mem_Type,Mem_Description,Mem_Attachfile) VALUES ", membership , ";");
			SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
		END IF;

		DELETE FROM hrm_employee_insurance WHERE Emp_ID = EmpID;
		IF insurance != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_employee_insurance(Emp_ID,Ins_InsuranceID,Ins_StartDate,Ins_ExpireDate,Ins_Description,Ins_SumInsured,Ins_Premium) VALUES ", insurance , ";");
			SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
		END IF;

		SELECT Setting_Value INTO RoleESS FROM hrm_setting WHERE Setting_Name = 'ESS_Role' AND Setting_Type = 'User';
		SELECT e.var_id INTO SUID FROM ame_user e WHERE e.var_empid = EmpID;
		DELETE FROM ame_user WHERE var_id = SUID;
		IF users != "" THEN
			SET @SQL1 = CONCAT("INSERT INTO ame_user(var_id,var_name,var_pwd,var_hrm_utype,var_hrm_role,var_empid) VALUES ", users , ";");
			SET @SQL1 = REPLACE(@SQL1, 'Temp_RoleESS', RoleESS);
			SET @SQL1 = REPLACE(@SQL1, 'Temp_EmpID', EmpID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			INSERT INTO ame_user_app(var_id,var_appid) VALUES(userName, 'HRM');
		END IF;
		IF SuserAssign !="" THEN
			UPDATE ame_user SET var_empid = EmpID WHERE var_id = SuserAssign;
			DELETE FROM ame_user_app WHERE var_id = SuserAssign AND var_appid = 'HRM';
			INSERT INTO ame_user_app(var_id,var_appid) VALUES(SuserAssign, 'HRM');
		END IF;

		IF CategoryName != "" THEN
			CALL spHRMAddEmployeeCategory(userid, CategoryName, CONCAT("('",CategoryName,"')"), 0);
		END IF;
		IF ContractTypeName != "" THEN
			WHILE (LOCATE(',', ContractTypeName) > 0)
			DO
        SET @value = LEFT(ContractTypeName, LOCATE(',',ContractTypeName) - 1);    
        SET ContractTypeName = SUBSTRING(ContractTypeName, LOCATE(',',ContractTypeName) + 1);
				IF @value != "" THEN
					CALL spHRMAddEmployeeContractType(userid, @value, CONCAT("('",@value,"')"), 0);
				END IF;
			END WHILE;
		END IF;
		IF LanguageName != "" THEN
			WHILE (LOCATE(',', LanguageName) > 0)
			DO
        SET @value = LEFT(LanguageName, LOCATE(',',LanguageName) - 1);    
        SET LanguageName = SUBSTRING(LanguageName, LOCATE(',',LanguageName) + 1);
				IF @value != "" THEN
					CALL spHRMAddEmployeeLanguage(userid, @value, CONCAT("('",@value,"')"), 0);
				END IF;
			END WHILE;
		END IF;
		IF MembershipTypeName != "" THEN
			WHILE (LOCATE(',', MembershipTypeName) > 0)
			DO
        SET @value = LEFT(MembershipTypeName, LOCATE(',',MembershipTypeName) - 1);    
        SET MembershipTypeName = SUBSTRING(MembershipTypeName, LOCATE(',',MembershipTypeName) + 1);
				IF @value != "" THEN
					CALL spHRMAddEmployeeMembershipType(userid, @value, CONCAT("('",@value,"')"), 0);
				END IF;
			END WHILE;
		END IF;
		IF NationalityName != "" THEN
			CALL spHRMAddEmployeeNationality(userid, NationalityName, CONCAT("('",NationalityName,"')"), 0);
		END IF;
		IF NationalsName != "" THEN
			CALL spHRMAddEmployeeNationals(userid, NationalsName, CONCAT("('",NationalsName,"')"), 0);
		END IF;
		IF SchoolName != "" THEN
			WHILE (LOCATE(',', SchoolName) > 0)
			DO
        SET @value = LEFT(SchoolName, LOCATE(',',SchoolName) - 1);    
        SET SchoolName = SUBSTRING(SchoolName, LOCATE(',',SchoolName) + 1);
				IF @value != "" THEN
					CALL spHRMAddEmployeeSchool(userid, @value, CONCAT("('",@value,"')"), 0);
				END IF;
			END WHILE;
		END IF;
		IF SocialCommunicationName != "" THEN
			WHILE (LOCATE(',', SocialCommunicationName) > 0)
			DO
        SET @value = LEFT(SocialCommunicationName, LOCATE(',',SocialCommunicationName) - 1);    
        SET SocialCommunicationName = SUBSTRING(SocialCommunicationName, LOCATE(',',SocialCommunicationName) + 1);
				IF @value != "" THEN
					CALL spHRMAddEmployeeSocialCommunication(userid, @value, CONCAT("('",@value,"')"), 0);
				END IF;
			END WHILE;
		END IF;
		IF EmpStatus != "" THEN
			CALL spHRMAddEmployeeStatus(userid, EmpStatus, CONCAT("('", EmpStatus,"')"), 0);
		END IF;
		IF EmpType != "" THEN
			CALL spHRMAddEmployeeType(userid, EmpType, CONCAT("('", EmpType,"')"), 0);
		END IF;
		IF EmpCountry != "" THEN
			CALL spHRMAddEmployeeCountry(userid, EmpCountry, CONCAT("('", EmpCountry,"')"), 0);
		END IF;
		IF EmpPermanentCountry != "" THEN
			CALL spHRMAddEmployeeCountry(userid, EmpPermanentCountry, CONCAT("('", EmpPermanentCountry,"')"), 0);
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeAllowance`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeAllowance`(userid varchar(255),ID varchar(255),SValue text, SID2 varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckExist INT DEFAULT(0);
	IF SValue != "" THEN
				-- DELETE FROM hrm_payroll_allowance_employee WHERE Allowance_EmpID = ID;
				SELECT COUNT(*) INTO CheckExist FROM hrm_payroll_allowance_employee WHERE Allowance_EmpID = ID AND Allowance_ID = SID2;
				IF CheckExist <= 0 THEN
					SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_allowance_employee(Allowance_EmpID,Allowance_ID) VALUES ", SValue, ";");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					CALL spHRMAddLog(userid, 'insert', 'Employee Allowance', CONCAT(ID, ', ', SID2));

					SELECT ID;
					CALL hrm_message('1100401', 'EmpAllowance', 'create', SID2);
				ELSE
					SET ID = 'exist';
					SELECT ID;
					CALL hrm_message('1100404', 'EmpAllowance', 'existed', SID2);
				END IF;					

	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeAuthorisation`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeAuthorisation`(userid varchar(255), EmpID varchar(255), SProcess varchar(255), EmployeeAuth text)
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE Exist INT DEFAULT(0);
	
	SELECT COUNT(*) INTO Exist FROM hrm_authorisation_employee WHERE Emp_ID=EmpID AND Auth_Process=SProcess;

	IF EmployeeAuth != "" AND Exist <= 0  THEN
		SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_employee(Emp_ID,Auth_Process,Auth_ID) VALUES ", EmployeeAuth, ";");
		PREPARE St FROM @SQL1;
		EXECUTE St;
		DEALLOCATE PREPARE St;

		CALL spHRMAddLog(userid, "insert", "EmployeeAuthorisation", EmpID);
	
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1102401', 'EmpAuth', 'create', EmpID);
	ELSE
		SET Message = "exist";
		SELECT Message;
		CALL hrm_message('1102404', 'EmpAuth', 'exist', SProcess);
	END IF;
		
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeBank`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeBank`(userid varchar(255),bankName varchar(255),bank text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	IF bank != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_bank WHERE LOWER(Bank_Name) = bankName;

		IF CheckExist <= 0 THEN
			CALL spHRMGetNumberPrefix("Bank", ID);
		
			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_bank(Bank_ID,Bank_Name,Bank_Description) VALUES ", bank, ";");
			SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeBank', ID);
			CALL spHRMUpdateNumberPrefix("Bank");
			SELECT ID;
			
			CALL hrm_message('1102501', 'Bank', 'create', ID);
		ELSE
			SET ID = "exist";
			SELECT ID;
			CALL hrm_message('1102504', 'Bank', 'exist', bankName);
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeBranch`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeBranch`(userid varchar(255),branchName varchar(255),branch text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	IF branch != "" THEN

		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_branch WHERE LOWER(Branch_Name) = branchName;

			IF CheckExist <= 0 THEN

				CALL spHRMGetNumberPrefix("Branch", ID);
	
				SET @SQL1 = CONCAT("INSERT INTO hrm_emp_branch(Branch_ID,Branch_Name,Branch_Tel,Branch_Description,Branch_Address,Branch_HomeNo,Branch_Street,Branch_Village,Branch_District,Branch_Commune,Branch_City,Branch_State,Branch_Country) VALUES ", branch, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				CALL spHRMUpdateNumberPrefix("Branch");

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeBranch', ID);

				SELECT ID;
				CALL hrm_message('1102601', 'Branch', 'create', ID);
			ELSE
				SET ID = "exist";
				SELECT ID;
				CALL hrm_message('1102604', 'Branch', 'exist', ID);
			END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeCategory`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeCategory`(userid varchar(255),categoryName varchar(255),category text,showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	

	IF category != "" THEN

		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_category WHERE LOWER(Category_Name) = categoryName;

		IF CheckExist <= 0 THEN

			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_category(Category_Name) VALUES ", category, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeCategory', categoryName);
			IF showing = 1 THEN
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1102701', 'Category', 'create', CategoryName);
			END IF;
		ELSE
			IF showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1102704', 'Category', 'exist', CategoryName);
			END IF;
		END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeContractType`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeContractType`(userid varchar(255),contractTypeName varchar(255),contractType text,Showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	IF contractType != "" THEN

		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_contract_type WHERE LOWER(ContractType_Name) = contractTypeName;

		IF CheckExist <= 0 THEN

			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_contract_type(ContractType_Name) VALUES ", contractType, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeContractType', contractTypeName);
			IF Showing = 1 THEN
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1102801', 'ContractType', 'create', contractTypeName);
			END IF;
		ELSE
			IF Showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1102804', 'ContractType', 'exist', contractTypeName);
			END IF;
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeCountry`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeCountry`(userid varchar(255),CountryName varchar(255),Country text,showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	

	IF Country != "" THEN

		SELECT COUNT(*) INTO CheckExist FROM hrm_location_country WHERE LOWER(Country_Name) = CountryName;

		IF CheckExist <= 0 THEN

			SET @SQL1 = CONCAT("INSERT INTO hrm_location_country(Country_Name) VALUES ", Country, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Country', CountryName);
			IF showing = 1 THEN
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1104201', 'Country', 'create', CountryName);
			END IF;
		ELSE
			IF showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1104204', 'Country', 'exist', CountryName);
			END IF;
		END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeDepartment`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeDepartment`(userid varchar(255),departmentName varchar(255),department text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	IF department != "" THEN

		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_department WHERE LOWER(Department_Name) = departmentName;

		IF CheckExist <= 0 THEN

			CALL spHRMGetNumberPrefix("Department", ID);

			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_department(Department_ID,Department_Name,Department_Description,Department_Parent) VALUES ", department, ";");
			SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			CALL spHRMUpdateNumberPrefix("Department");

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeDepartment', ID);

			SELECT ID;
			CALL hrm_message('1103201', 'Department', 'create', ID);
		ELSE

			SET ID = "exist";
			SELECT ID;
			CALL hrm_message('1103204', 'Department', 'create', departmentName);
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeGrade`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeGrade`(userid varchar(255),SName varchar(255),SValue text, Showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF SValue != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_grade WHERE LOWER(Grade_Name) = SName;

		IF CheckExist <= 0 THEN

			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_grade(Grade_Name) VALUES ", SValue, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeGrade', SName);

			IF Showing = 1 THEN
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1104601', 'Grade', 'create', SName);
			END IF;
		ELSE
			IF Showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1104604', 'Grade', 'exist', SName);
			END IF;
		END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeInsurance`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeInsurance`(userid varchar(255),InsuranceName varchar(255),Insurance text, InsuranceType varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	IF Insurance != "" THEN

				CALL spHRMGetNumberPrefix("Insurance", ID);
	
				SET @SQL1 = CONCAT("INSERT INTO hrm_emp_insurance(Insurance_ID,Insurance_Name,Insurance_Company,Insurance_Type,Insurance_Description) VALUES ", Insurance, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				CALL spHRMUpdateNumberPrefix("Insurance");

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeInsurance', ID);

				IF InsuranceType != "" THEN
					CALL spHRMAddEmployeeInsuranceType(userid, InsuranceType, CONCAT("('", InsuranceType,"')"), 0);
				END IF;

				SELECT ID;
				CALL hrm_message('1103601', 'Insurance', 'create', ID);

	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeInsuranceType`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeInsuranceType`(userid varchar(255),InsuranceTypeName varchar(255),InsuranceType text, Showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF InsuranceType != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_insurance_type WHERE LOWER(InsuranceType_Name) = InsuranceTypeName;

		IF CheckExist <= 0 THEN
			
			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_insurance_type(InsuranceType_Name) VALUES ", InsuranceType, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeInsuranceType', InsuranceTypeName);

			IF Showing = 1 THEN
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1103701', 'InsuranceType', 'create', InsuranceTypeName);
			END IF;
		ELSE
			IF Showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1103704', 'InsuranceType', 'create', InsuranceTypeName);
			END IF;
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeLanguage`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeLanguage`(userid varchar(255),LanguageName varchar(255),Languages text, Showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF Languages != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_language WHERE LOWER(Language_Name) = LanguageName;

		IF CheckExist <= 0 THEN
			
			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_language(Language_Name) VALUES ", Languages, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeLanguage', LanguageName);
			
			IF Showing = 1 THEN
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1103401', 'Language', 'create', LanguageName);
			END IF;
		ELSE
			IF Showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1103404', 'Language', 'exist', LanguageName);
			END IF;
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeLeaveType`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeLeaveType`(userid varchar(255),ID varchar(255),SValue text,STypeID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckExist INT DEFAULT(0);
	IF SValue != "" THEN
				-- DELETE FROM hrm_timesheet_leave_type_employee WHERE Leave_EmpID = ID;
			SELECT COUNT(*) INTO CheckExist FROM hrm_timesheet_leave_type_employee WHERE Leave_EmpID = ID AND Leave_TypeID = STypeID;
			IF CheckExist <= 0 THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_leave_type_employee(Leave_EmpID,Leave_TypeID) VALUES ", SValue, ";");
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Employee Leave Type', ID);
				SET ID = 'success';
				CALL hrm_message('1101101', 'EmpLeaveType', 'create', STypeID);
				SELECT ID;
			ELSE
				SET ID = 'exist';
				SELECT ID;
				CALL hrm_message('1101104', 'EmpLeaveType', 'exist', STypeID);
			END IF;

	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeLevel`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeLevel`(userid varchar(255),LevelName varchar(255),Levels text)
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF Levels != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_level WHERE LOWER(Level_Name) = LevelName;

		IF CheckExist <= 0 THEN
			
			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_level(Level_Name) VALUES ", Levels, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeLevel', LevelName);

			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1103501', 'Level', 'create', LevelName);
		ELSE
			SET Message = "exist";
			SELECT Message;
			CALL hrm_message('1103504', 'Level', 'exist', LevelName);
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeMembershipType`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeMembershipType`(userid varchar(255),MembershipTypeName varchar(255),MembershipType text, Showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF MembershipType != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_membership_type WHERE LOWER(MembershipType_Name) = MembershipTypeName;

		IF CheckExist <= 0 THEN
			
			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_membership_type(MembershipType_Name) VALUES ", MembershipType, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeMembershipType', MembershipTypeName);
			
			IF Showing = 1 THEN
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1103301', 'MemberShipType', 'create', MembershipTypeName);
			END IF;
		ELSE
			IF Showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1103304', 'MemberShipType', 'exist', MembershipTypeName);
			END IF;
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeNationality`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeNationality`(userid varchar(255),NationalityName varchar(255),Nationality text, Showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF Nationality != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_nationality WHERE LOWER(Nationnality_Name) = NationalityName;

		IF CheckExist <= 0 THEN
			
			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_nationality(Nationnality_Name) VALUES ", Nationality, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeNationality', NationalityName);

			IF Showing = 1 THEN
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1103901', 'Nationality', 'create', NationalityName);
			END IF;
		ELSE
			IF Showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1103904', 'Nationality', 'exist', NationalityName);
			END IF;
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeNationals`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeNationals`(userid varchar(255),NationalsName varchar(255),Nationals text, Showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF Nationals != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_nationals WHERE LOWER(Nationals_Name) = NationalsName;

		IF CheckExist <= 0 THEN
			
			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_nationals(Nationals_Name) VALUES ", Nationals, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeNationals', NationalsName);

			IF Showing = 1 THEN
				SET Message = "success";
