USE `Ratemanagement3`;

set sql_mode='';

INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1345, 'Translate.All', 1, 9);

INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('Translate.index', 'TranslateController.index', 1, 'System', NULL, '2018-05-07 14:38:17.000', '2018-05-07 14:38:17.000', 1345);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('Translate.*', 'TranslateController.*', 1, 'System', NULL, '2018-05-07 14:38:17.000', '2018-05-07 14:38:17.000', 1345);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('Translate.changeLanguage', 'TranslateController.changeLanguage', 1, 'System', NULL, '2018-05-07 14:38:17.000', '2018-05-07 14:38:17.000', 1345);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('Translate.search_ajax_datagrid', 'TranslateController.search_ajax_datagrid', 1, 'System', NULL, '2018-05-07 14:38:17.000', '2018-05-07 14:38:17.000', 1345);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('Translate.process_multipalUpdate', 'TranslateController.process_multipalUpdate', 1, 'System', NULL, '2018-05-07 14:38:17.000', '2018-05-07 14:38:17.000', 1345);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('Translate.process_singleDelete', 'TranslateController.process_singleDelete', 1, 'System', NULL, '2018-05-07 14:38:17.000', '2018-05-07 14:38:17.000', 1345);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('Translate.exports', 'TranslateController.exports', 1, 'System', NULL, '2018-05-07 14:38:17.000', '2018-05-07 14:38:17.000', 1345);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('Translate.new_system_name', 'TranslateController.new_system_name', 1, 'System', NULL, '2018-05-07 14:38:17.000', '2018-05-07 14:38:17.000', 1345);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('Translate.refresh_label', 'TranslateController.refresh_label', 1, 'System', NULL, '2018-05-07 14:38:17.000', '2018-05-07 14:38:17.000', 1345);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('Translate.datatable_Label', 'TranslateController.datatable_Label', 1, 'System', NULL, '2018-05-07 14:38:17.000', '2018-05-07 14:38:17.000', 1345);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('Translate.process_singleUpdate', 'TranslateController.process_singleUpdate', 1, 'System', NULL, '2018-05-07 14:38:17.000', '2018-05-07 14:38:17.000', 1345);


ALTER TABLE `tblFileUploadTemplate`
	CHANGE COLUMN `Options` `Options` TEXT NULL DEFAULT NULL COLLATE 'utf8_unicode_ci' AFTER `Title`;

ALTER TABLE `tblRateRule`
ADD COLUMN `Order` INT(11) NULL AFTER `ModifiedBy`;

UPDATE tblRateRule SET `Order` = RateRuleId;

ALTER TABLE `tblAccountBilling`
	ADD COLUMN `LastChargeDate` DATE NULL DEFAULT NULL AFTER `NextInvoiceDate`,
	ADD COLUMN `NextChargeDate` DATE NULL DEFAULT NULL AFTER `LastChargeDate`;
	
UPDATE tblAccountBilling SET LastChargeDate=LastInvoiceDate,NextChargeDate=DATE_ADD(NextInvoiceDate, INTERVAL -1 DAY);

CREATE TABLE IF NOT EXISTS `tblAccountDetails` (
	`AccountDetailID` INT(11) NOT NULL AUTO_INCREMENT,
	`AccountID` INT(11) NOT NULL,
	`CustomerPaymentAdd` INT(11) NULL DEFAULT '0',
	`customerpanelpassword` LONGTEXT NULL COLLATE 'utf8_unicode_ci',
	`DisplayRates` INT(11) NULL DEFAULT '0',
	`ResellerOwner` INT(11) NULL DEFAULT '0',
	PRIMARY KEY (`AccountDetailID`),
	UNIQUE INDEX `UI_AccountID` (`AccountID`),
	INDEX `IX_AccountID` (`AccountID`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
;

INSERT INTO `tblCronJobCommand` ( `CompanyID`, `GatewayID`, `Title`, `Command`, `Settings`, `Status`, `created_at`, `created_by`) VALUES (1, 4, 'Reseller PBX CDR', 'resellerpbxaccountusage', '[[{"title":"Start Date","type":"text","datepicker":"","value":"","name":"StartDate"},{"title":"End Date","type":"text","value":"","datepicker":"","name":"EndDate"},{"title":"Threshold Time (Minute)","type":"text","value":"","name":"ThresholdTime"},{"title":"Success Email","type":"text","value":"","name":"SuccessEmail"},{"title":"Error Email","type":"text","value":"","name":"ErrorEmail"}]]', 1, '2018-03-13 15:00:00', 'RateManagementSystem');
INSERT INTO `tblCompanyConfiguration` (`CompanyID`, `Key`, `Value`) VALUES (1, 'PBX_RESELLER_CRONJOB', '{"StartDate":"","EndDate":"","ThresholdTime":"120","SuccessEmail":"","ErrorEmail":"","JobTime":"MINUTE","JobInterval":"10","JobDay":["SUN","MON","TUE","WED","THU","FRI","SAT"],"JobStartTime":"12:00:00 AM","CompanyGatewayID":""}');

INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1333, 'CustomersRates.Create', 1, 3);

INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('CustomersRates.create', 'CustomersRatesController.create', 1, 'Vasim Seta', NULL, '2018-04-13 09:37:36.000', '2018-04-13 09:37:36.000', 1333);

ALTER TABLE `tblCustomerRate`
	ADD COLUMN `CreatedBy` VARCHAR(50) NULL DEFAULT NULL AFTER `CreatedDate`,
	ADD COLUMN `EndDate` DATE NULL DEFAULT NULL AFTER `EffectiveDate`;

ALTER TABLE `tblRateSheetDetails`
	ADD COLUMN `EndDate` DATETIME NULL AFTER `EffectiveDate`;

RENAME TABLE `tblCustomerRateArchive` TO `tblCustomerRateArchive_old`;
CREATE TABLE IF NOT EXISTS `tblCustomerRateArchive` (
  `CustomerRateArchiveID` int(11) NOT NULL AUTO_INCREMENT,
  `CustomerRateID` int(11) DEFAULT NULL,
  `AccountId` int(11) NOT NULL,
  `TrunkID` int(11) NOT NULL,
  `RateId` int(11) NOT NULL,
  `Rate` decimal(18,6) NOT NULL DEFAULT '0.000000',
  `EffectiveDate` datetime NOT NULL,
  `EndDate` datetime DEFAULT NULL,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
  `created_by` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `updated_by` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Interval1` int(11) DEFAULT NULL,
  `IntervalN` int(11) DEFAULT NULL,
  `ConnectionFee` decimal(18,6) DEFAULT NULL,
  `RoutinePlan` int(11) DEFAULT NULL,
  `Notes` varchar(500) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`CustomerRateArchiveID`),
  KEY `CustomerRateID` (`CustomerRateID`),
  KEY `AccountId` (`AccountId`),
  KEY `TrunkID` (`TrunkID`),
  KEY `RateId` (`RateId`),
  KEY `EffectiveDate` (`EffectiveDate`),
  KEY `EndDate` (`EndDate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `tblCompanyConfiguration` (`CompanyID`, `Key`, `Value`) VALUES ('1', 'AUTO_SIPPY_ACCOUNT_IMPORT_INTERVAL', '360');

INSERT IGNORE INTO `tblGateway` (`GatewayID`, `Title`, `Name`, `Status`, `CreatedBy`, `created_at`, `ModifiedBy`, `updated_at`) VALUES (7, 'FTP', 'FTP', 1, 'RateManagementSystem', '2017-04-21 12:20:01', NULL, '2017-04-21 12:20:01');
UPDATE `tblGateway` SET `Status`  = 1 WHERE `Name` = 'FTP';
SELECT GatewayID INTO @FTPGatewayID  FROM tblGateway WHERE `Name` = 'FTP';
DELETE FROM tblGatewayConfig WHERE `GatewayID` = @FTPGatewayID;
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Rate Format', 'RateFormat', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Authentication Rule', 'NameFormat', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'CDR ReRate', 'RateCDR', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Rerate Method', 'RateMethod', 1, '2017-06-09 00:00:00', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Rerate Method Value', 'SpecifyRate', 1, '2017-06-09 00:00:00', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'CLI Translation Rule', 'CLITranslationRule', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'FTP Host IP', 'host', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Protocol Type', 'protocol_type', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Port', 'port', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'SSL', 'ssl', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Passive Mode', 'passive_mode', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'User Name', 'username', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Password', 'password', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Key', 'key', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Key Phrase', 'keyphrase', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'FTP CDR Download Path', 'cdr_folder', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'CLD Translation Rule', 'CLDTranslationRule', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Billing Time', 'BillingTime', 1, '2017-04-14 15:59:25', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'Prefix Translation Rule', 'PrefixTranslationRule', 1, '2017-06-09 00:00:00', 'RateManagementSystem', NULL, NULL);
INSERT INTO `tblGatewayConfig` ( `GatewayID`, `Title`, `Name`, `Status`, `Created_at`, `CreatedBy`, `updated_at`, `ModifiedBy`) VALUES ( @FTPGatewayID, 'File Name Rule', 'FileNameRule', 1, '2017-06-09 00:00:00', 'RateManagementSystem', NULL, NULL);

ALTER TABLE `tblRateRuleMargin`
	ADD COLUMN `FixedValue` DECIMAL(18,6) NULL AFTER `AddMargin`;

INSERT INTO `tblIntegration` (`CompanyId`, `Title`, `Slug`, `ParentID`, `MultiOption`) VALUES (1, 'PeleCard', 'pelecard', 4, 'N');

INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1332, 'RateUpload.All', 1, 5);

INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.missingMethod', 'RateUploadController.missingMethod', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:01.000', '2018-03-27 17:44:01.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.getAllowedActions', 'RateUploadController.getAllowedActions', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:01.000', '2018-03-27 17:44:01.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.get', 'RateUploadController.get', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:01.000', '2018-03-27 17:44:01.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.destroy', 'RateUploadController.destroy', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:01.000', '2018-03-27 17:44:01.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.update', 'RateUploadController.update', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:01.000', '2018-03-27 17:44:01.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.edit', 'RateUploadController.edit', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:01.000', '2018-03-27 17:44:01.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.show', 'RateUploadController.show', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:01.000', '2018-03-27 17:44:01.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.store', 'RateUploadController.store', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:01.000', '2018-03-27 17:44:01.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.create', 'RateUploadController.create', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:01.000', '2018-03-27 17:44:01.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.*', 'RateUploadController.*', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.index', 'RateUploadController.index', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.getUploadTemplates', 'RateUploadController.getUploadTemplates', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.getTrunk', 'RateUploadController.getTrunk', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.checkUpload', 'RateUploadController.checkUpload', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.ajaxfilegrid', 'RateUploadController.ajaxfilegrid', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.storeTemplate', 'RateUploadController.storeTemplate', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.reviewRatesExports', 'RateUploadController.reviewRatesExports', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.getReviewRates', 'RateUploadController.getReviewRates', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.reviewRates', 'RateUploadController.reviewRates', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.updateTempReviewRates', 'RateUploadController.updateTempReviewRates', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('RateUpload.getSheetNamesFromExcel', 'RateUploadController.getSheetNamesFromExcel', 1, 'Sumera Saeed', NULL, '2018-03-27 17:44:00.000', '2018-03-27 17:44:00.000', 1332);

ALTER TABLE `tblRateTableRate`
	ADD COLUMN `EndDate` DATE NULL AFTER `EffectiveDate`;


CREATE TABLE IF NOT EXISTS `tblRateTableRateChangeLog` (
  `RateTableRateChangeLogID` int(11) NOT NULL AUTO_INCREMENT,
  `TempRateTableRateID` int(11) NOT NULL DEFAULT '0',
  `RateTableRateID` int(11) DEFAULT NULL,
  `RateTableId` int(11) DEFAULT NULL,
  `RateId` int(11) DEFAULT NULL,
  `Code` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Description` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Rate` decimal(18,6) DEFAULT NULL,
  `EffectiveDate` datetime DEFAULT NULL,
  `EndDate` datetime DEFAULT NULL,
  `Interval1` int(11) DEFAULT NULL,
  `IntervalN` int(11) DEFAULT NULL,
  `ConnectionFee` decimal(18,6) DEFAULT NULL,
  `Action` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ProcessID` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `created_at` datetime DEFAULT NULL,
  PRIMARY KEY (`RateTableRateChangeLogID`),
  KEY `IX_tblRateTableRateChangeLog_RateTableRateID` (`RateTableRateID`),
  KEY `IX_tblRateTableRateChangeLog_ProcessID` (`ProcessID`),
  KEY `RateId` (`RateId`),
  KEY `EffectiveDate` (`EffectiveDate`),
  KEY `Code` (`Code`),
  KEY `Action` (`Action`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE IF NOT EXISTS `tblTempRateTableRate` (
  `TempRateTableRateID` int(11) NOT NULL AUTO_INCREMENT,
  `CodeDeckId` int(11) DEFAULT NULL,
  `CountryCode` varchar(500) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Code` text COLLATE utf8_unicode_ci NOT NULL,
  `Description` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `Rate` decimal(18,6) NOT NULL DEFAULT '0.000000',
  `EffectiveDate` datetime NOT NULL,
  `EndDate` datetime DEFAULT NULL,
  `Change` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ProcessId` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `Preference` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ConnectionFee` decimal(18,6) DEFAULT NULL,
  `Interval1` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `IntervalN` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Forbidden` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `DialStringPrefix` varchar(500) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`TempRateTableRateID`),
  KEY `IX_tblTempRateTableRateProcessID` (`ProcessId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


CREATE TABLE IF NOT EXISTS `tblRateTableRateArchive` (
  `RateTableRateArchiveID` int(11) NOT NULL AUTO_INCREMENT,
  `RateTableRateID` int(11) DEFAULT NULL,
  `RateTableId` int(11) NOT NULL,
  `RateId` int(11) NOT NULL,
  `Rate` decimal(18,6) NOT NULL DEFAULT '0.000000',
  `EffectiveDate` datetime NOT NULL,
  `EndDate` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
  `created_by` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `updated_by` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Interval1` int(11) DEFAULT NULL,
  `IntervalN` int(11) DEFAULT NULL,
  `ConnectionFee` decimal(18,6) DEFAULT NULL,
  `Notes` varchar(500) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`RateTableRateArchiveID`),
  KEY `RateTableRateID` (`RateTableRateID`),
  KEY `RateTableId` (`RateTableId`),
  KEY `RateId` (`RateId`),
  KEY `EffectiveDate` (`EffectiveDate`),
  KEY `EndDate` (`EndDate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


CREATE TABLE IF NOT EXISTS `tblFileUploadTemplateType` (
  `FileUploadTemplateTypeID` int(11) NOT NULL AUTO_INCREMENT,
  `TemplateType` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `Title` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `UploadDir` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `created_at` datetime DEFAULT NULL,
  `created_by` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Status` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`FileUploadTemplateTypeID`),
  UNIQUE KEY `IXUnique_TemplateType` (`TemplateType`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `tblFileUploadTemplateType` (`FileUploadTemplateTypeID`, `TemplateType`, `Title`, `UploadDir`, `created_at`, `created_by`, `Status`) VALUES
	(1, 'CDR', 'CDR', 'CDR_UPLOAD', '2018-04-24 13:59:54', 'Vasim Seta', 1),
	(2, 'VendorCDR', 'Vendor CDR', 'CDR_UPLOAD', '2018-04-24 13:59:54', 'Vasim Seta', 1),
	(3, 'Account', 'Account', 'ACCOUNT_DOCUMENT', '2018-04-24 13:59:54', 'Vasim Seta', 1),
	(4, 'Leads', 'Leads', 'ACCOUNT_DOCUMENT', '2018-04-24 13:59:54', 'Vasim Seta', 1),
	(5, 'DialString', 'DialString', 'DIALSTRING_UPLOAD', '2018-04-24 13:59:54', 'Vasim Seta', 1),
	(6, 'IPs', 'IPs', 'IP_UPLOAD', '2018-04-24 13:59:54', 'Vasim Seta', 1),
	(7, 'Item', 'Item', 'ITEM_UPLOAD', '2018-04-24 13:59:54', 'Vasim Seta', 1),
	(8, 'VendorRate', 'Vendor Rate', 'VENDOR_UPLOAD', '2018-04-24 13:59:54', 'Vasim Seta', 1),
	(9, 'Payment', 'Payment', 'PAYMENT_UPLOAD', '2018-04-24 13:59:54', 'Vasim Seta', 1),
	(10, 'RatetableRate', 'Ratetable Rate', 'RATETABLE_UPLOAD', '2018-04-24 13:59:54', 'Vasim Seta', 1),
	(11, 'CustomerRate', 'Customer Rate', 'CUSTOMER_UPLOAD', '2018-04-24 13:59:54', 'Vasim Seta', 0);

ALTER TABLE `tblFileUploadTemplate`
	CHANGE COLUMN `Type` `FileUploadTemplateTypeID` TINYINT(3) UNSIGNED NULL DEFAULT NULL AFTER `FileUploadTemplateID`;
	
ALTER TABLE `tblBillingClass`
	ADD COLUMN `RoundChargesCDR` INT(11) NULL DEFAULT '2' AFTER `RoundChargesAmount`;	
	
CREATE TABLE IF NOT EXISTS `tblAutoImport` (
  `AutoImportID` int(11) NOT NULL AUTO_INCREMENT,
  `JobID` int(11) NOT NULL DEFAULT '0',
  `CompanyID` int(11) NOT NULL DEFAULT '0',
  `AccountName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `To` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `From` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CC` varchar(300) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AccountID` int(11) NOT NULL DEFAULT '0',
  `Subject` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Description` longtext COLLATE utf8_unicode_ci NOT NULL,
  `MessageId` text COLLATE utf8_unicode_ci NOT NULL,
  `MailDateTime` datetime NOT NULL,
  `Attachment` text COLLATE utf8_unicode_ci,
  `created_at` datetime DEFAULT NULL,
  `created_by` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `updated_by` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`AutoImportID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE IF NOT EXISTS `tblAutoImportInboxSetting` (
  `AutoImportInboxSettingID` int(11) NOT NULL AUTO_INCREMENT,
  `CompanyID` int(11) NOT NULL DEFAULT '0',
  `port` int(11) DEFAULT NULL,
  `host` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `IsSSL` tinyint(1) DEFAULT NULL,
  `username` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `password` varchar(300) COLLATE utf8_unicode_ci DEFAULT NULL,
  `emailNotificationOnSuccess` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `emailNotificationOnFail` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `SendCopyToAccount` enum('Y','N') COLLATE utf8_unicode_ci DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`AutoImportInboxSettingID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


CREATE TABLE IF NOT EXISTS `tblAutoImportSetting` (
  `AutoImportSettingID` int(11) NOT NULL AUTO_INCREMENT,
  `CompanyID` int(11) NOT NULL DEFAULT '0',
  `Type` tinyint(1) NOT NULL COMMENT '1=Vendor,2=RateTable',
  `TypePKID` int(11) DEFAULT NULL COMMENT 'Type:1 = AccountID ,Type:2 = VendorID',
  `TrunkID` int(11) DEFAULT NULL,
  `ImportFileTempleteID` int(11) DEFAULT NULL,
  `Subject` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `FileName` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `SendorEmail` varchar(300) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `created_by` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `updated_by` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`AutoImportSettingID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;	

INSERT INTO `tblCronJobCommand` ( `CompanyID`, `GatewayID`, `Title`, `Command`, `Settings`, `Status`, `created_at`, `created_by`) VALUES ( 1, NULL, 'Read Email for AutoRateImport', 'reademailsautoimport', '[[{"title":"Threshold Time (Minute)","type":"text","value":"","name":"ThresholdTime"},{"title":"Success Email","type":"text","value":"","name":"SuccessEmail"},{"title":"Error Email","type":"text","value":"","name":"ErrorEmail"}]]', 1, NULL, NULL);

ALTER TABLE `tblAccount`
ADD COLUMN `LanguageID` INT(11) NULL DEFAULT '43' AFTER `CurrencyId`;

ALTER TABLE `tblTicketGroups`
ADD COLUMN `LanguageID` INT(11) NULL DEFAULT '43' AFTER `CompanyID`;

ALTER TABLE `tblEmailTemplate`
ADD COLUMN `LanguageID` INT(11) NULL DEFAULT '43' AFTER `CompanyID`;


CREATE TABLE IF NOT EXISTS `tblLanguage` (
	`LanguageID` int(11) NOT NULL AUTO_INCREMENT,
	`ISOCode` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
	`Language` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
	`flag` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
	`is_rtl` enum('Y','N') COLLATE utf8_unicode_ci DEFAULT 'N',
	PRIMARY KEY (`LanguageID`),
	UNIQUE KEY `ISO_Code` (`ISOCode`)
) ENGINE=InnoDB AUTO_INCREMENT=193 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


INSERT INTO `tblLanguage` (`LanguageID`, `ISOCode`, `Language`, `flag`, `is_rtl`) VALUES
	(1, 'ab', 'Abkhazian', NULL, 'N'),
	(2, 'aa', 'Afar', NULL, 'N'),
	(3, 'af', 'Afrikaans', NULL, 'N'),
	(4, 'ak', 'Akan', NULL, 'N'),
	(5, 'sq', 'Albanian', NULL, 'N'),
	(6, 'am', 'Amharic', NULL, 'N'),
	(7, 'ar', 'Arabic', 'sa.png', 'N'),
	(8, 'an', 'Aragonese', NULL, 'N'),
	(9, 'hy', 'Armenian', NULL, 'N'),
	(10, 'as', 'Assamese', NULL, 'N'),
	(11, 'av', 'Avaric', NULL, 'N'),
	(12, 'ae', 'Avestan', NULL, 'N'),
	(13, 'ay', 'Aymara', NULL, 'N'),
	(14, 'az', 'Azerbaijani', NULL, 'N'),
	(15, 'bm', 'Bambara', NULL, 'N'),
	(16, 'ba', 'Bashkir', NULL, 'N'),
	(17, 'eu', 'Basque', NULL, 'N'),
	(18, 'be', 'Belarusian', NULL, 'N'),
	(19, 'bn', 'Bengali(Bangla)', NULL, 'N'),
	(20, 'bh', 'Bihari', NULL, 'N'),
	(21, 'bi', 'Bislama', NULL, 'N'),
	(22, 'bs', 'Bosnian', NULL, 'N'),
	(23, 'br', 'Breton', NULL, 'N'),
	(24, 'bg', 'Bulgarian', NULL, 'N'),
	(25, 'my', 'Burmese', NULL, 'N'),
	(26, 'ca', 'Catalan', NULL, 'N'),
	(27, 'ch', 'Chamorro', NULL, 'N'),
	(28, 'ce', 'Chechen', NULL, 'N'),
	(29, 'ny', 'Chichewa,Chewa,Nyanja', NULL, 'N'),
	(30, 'zh', 'Chinese', NULL, 'N'),
	(31, 'zh-Hans', 'Chinese(Simplified)', NULL, 'N'),
	(32, 'zh-Hant', 'Chinese(Traditional)', NULL, 'N'),
	(33, 'cv', 'Chuvash', NULL, 'N'),
	(34, 'kw', 'Cornish', NULL, 'N'),
	(35, 'co', 'Corsican', NULL, 'N'),
	(36, 'cr', 'Cree', NULL, 'N'),
	(37, 'hr', 'Croatian', NULL, 'N'),
	(38, 'cs', 'Czech', NULL, 'N'),
	(39, 'da', 'Danish', NULL, 'N'),
	(40, 'dv', 'Divehi,Dhivehi,Maldivian', NULL, 'N'),
	(41, 'nl', 'Dutch', NULL, 'N'),
	(42, 'dz', 'Dzongkha', NULL, 'N'),
	(43, 'en', 'English', 'gb.png', 'N'),
	(44, 'eo', 'Esperanto', NULL, 'N'),
	(45, 'et', 'Estonian', NULL, 'N'),
	(46, 'ee', 'Ewe', NULL, 'N'),
	(47, 'fo', 'Faroese', NULL, 'N'),
	(48, 'fj', 'Fijian', NULL, 'N'),
	(49, 'fi', 'Finnish', NULL, 'N'),
	(50, 'fr', 'French', NULL, 'N'),
	(51, 'ff', 'Fula,Fulah,Pulaar,Pular', NULL, 'N'),
	(52, 'gl', 'Galician', NULL, 'N'),
	(53, 'gd', 'Gaelic(Scottish)', NULL, 'N'),
	(54, 'gv', 'Gaelic(Manx)', NULL, 'N'),
	(55, 'ka', 'Georgian', NULL, 'N'),
	(56, 'de', 'German', NULL, 'N'),
	(57, 'el', 'Greek', NULL, 'N'),
	(59, 'gn', 'Guarani', NULL, 'N'),
	(60, 'gu', 'Gujarati', NULL, 'N'),
	(61, 'ht', 'HaitianCreole', NULL, 'N'),
	(62, 'ha', 'Hausa', NULL, 'N'),
	(63, 'he', 'Hebrew', 'il.png', 'Y'),
	(64, 'hz', 'Herero', NULL, 'N'),
	(65, 'hi', 'Hindi', NULL, 'N'),
	(66, 'ho', 'HiriMotu', NULL, 'N'),
	(67, 'hu', 'Hungarian', NULL, 'N'),
	(68, 'is', 'Icelandic', NULL, 'N'),
	(69, 'io', 'Ido', NULL, 'N'),
	(70, 'ig', 'Igbo', NULL, 'N'),
	(71, 'id', 'Indonesian', NULL, 'N'),
	(72, 'ia', 'Interlingua', NULL, 'N'),
	(73, 'ie', 'Interlingue', NULL, 'N'),
	(74, 'iu', 'Inuktitut', NULL, 'N'),
	(75, 'ik', 'Inupiak', NULL, 'N'),
	(76, 'ga', 'Irish', NULL, 'N'),
	(77, 'it', 'Italian', NULL, 'N'),
	(78, 'ja', 'Japanese', NULL, 'N'),
	(79, 'jv', 'Javanese', NULL, 'N'),
	(80, 'kl', 'Kalaallisut,Greenlandic', NULL, 'N'),
	(81, 'kn', 'Kannada', NULL, 'N'),
	(82, 'kr', 'Kanuri', NULL, 'N'),
	(83, 'ks', 'Kashmiri', NULL, 'N'),
	(84, 'kk', 'Kazakh', NULL, 'N'),
	(85, 'km', 'Khmer', NULL, 'N'),
	(86, 'ki', 'Kikuyu', NULL, 'N'),
	(87, 'rw', 'Kinyarwanda(Rwanda)', NULL, 'N'),
	(88, 'rn', 'Kirundi', NULL, 'N'),
	(89, 'ky', 'Kyrgyz', NULL, 'N'),
	(90, 'kv', 'Komi', NULL, 'N'),
	(91, 'kg', 'Kongo', NULL, 'N'),
	(92, 'ko', 'Korean', NULL, 'N'),
	(93, 'ku', 'Kurdish', NULL, 'N'),
	(94, 'kj', 'Kwanyama', NULL, 'N'),
	(95, 'lo', 'Lao', NULL, 'N'),
	(96, 'la', 'Latin', NULL, 'N'),
	(97, 'lv', 'Latvian(Lettish)', NULL, 'N'),
	(98, 'li', 'Limburgish(Limburger)', NULL, 'N'),
	(99, 'ln', 'Lingala', NULL, 'N'),
	(100, 'lt', 'Lithuanian', NULL, 'N'),
	(101, 'lu', 'Luga-Katanga', NULL, 'N'),
	(102, 'lg', 'Luganda,Ganda', NULL, 'N'),
	(103, 'lb', 'Luxembourgish', NULL, 'N'),
	(105, 'mk', 'Macedonian', NULL, 'N'),
	(106, 'mg', 'Malagasy', NULL, 'N'),
	(107, 'ms', 'Malay', NULL, 'N'),
	(108, 'ml', 'Malayalam', NULL, 'N'),
	(109, 'mt', 'Maltese', NULL, 'N'),
	(110, 'mi', 'Maori', NULL, 'N'),
	(111, 'mr', 'Marathi', NULL, 'N'),
	(112, 'mh', 'Marshallese', NULL, 'N'),
	(113, 'mo', 'Moldavian', NULL, 'N'),
	(114, 'mn', 'Mongolian', NULL, 'N'),
	(115, 'na', 'Nauru', NULL, 'N'),
	(116, 'nv', 'Navajo', NULL, 'N'),
	(117, 'ng', 'Ndonga', NULL, 'N'),
	(118, 'nd', 'NorthernNdebele', NULL, 'N'),
	(119, 'ne', 'Nepali', NULL, 'N'),
	(120, 'no', 'Norwegian', NULL, 'N'),
	(121, 'nb', 'Norwegianbokmål', NULL, 'N'),
	(122, 'nn', 'Norwegiannynorsk', NULL, 'N'),
	(124, 'oc', 'Occitan', NULL, 'N'),
	(125, 'oj', 'Ojibwe', NULL, 'N'),
	(126, 'cu', 'OldChurchSlavonic,OldBulgarian', NULL, 'N'),
	(127, 'or', 'Oriya', NULL, 'N'),
	(128, 'om', 'Oromo(AfaanOromo)', NULL, 'N'),
	(129, 'os', 'Ossetian', NULL, 'N'),
	(130, 'pi', 'Pāli', NULL, 'N'),
	(131, 'ps', 'Pashto,Pushto', NULL, 'N'),
	(132, 'fa', 'Persian(Farsi)', NULL, 'N'),
	(133, 'pl', 'Polish', NULL, 'N'),
	(134, 'pt', 'Portuguese', NULL, 'N'),
	(135, 'pa', 'Punjabi(Eastern)', NULL, 'N'),
	(136, 'qu', 'Quechua', NULL, 'N'),
	(137, 'rm', 'Romansh', NULL, 'N'),
	(138, 'ro', 'Romanian', NULL, 'N'),
	(139, 'ru', 'Russian', NULL, 'N'),
	(140, 'se', 'Sami', NULL, 'N'),
	(141, 'sm', 'Samoan', NULL, 'N'),
	(142, 'sg', 'Sango', NULL, 'N'),
	(143, 'sa', 'Sanskrit', NULL, 'N'),
	(144, 'sc', 'Sardinian', NULL, 'N'),
	(145, 'sr', 'Serbian', NULL, 'N'),
	(146, 'sh', 'Serbo-Croatian', NULL, 'N'),
	(147, 'st', 'Sesotho', NULL, 'N'),
	(148, 'tn', 'Setswana', NULL, 'N'),
	(149, 'sn', 'Shona', NULL, 'N'),
	(150, 'ii', 'Sichuan Yi, Nuosu', NULL, 'N'),
	(151, 'sd', 'Sindhi', NULL, 'N'),
	(152, 'si', 'Sinhalese', NULL, 'N'),
	(154, 'sk', 'Slovak', NULL, 'N'),
	(155, 'sl', 'Slovenian', NULL, 'N'),
	(156, 'so', 'Somali', NULL, 'N'),
	(157, 'nr', 'SouthernNdebele', NULL, 'N'),
	(158, 'es', 'Spanish', 'es.png', 'N'),
	(159, 'su', 'Sundanese', NULL, 'N'),
	(160, 'sw', 'Swahili(Kiswahili)', NULL, 'N'),
	(161, 'ss', 'Swati, Siswati', NULL, 'N'),
	(162, 'sv', 'Swedish', NULL, 'N'),
	(163, 'tl', 'Tagalog', NULL, 'N'),
	(164, 'ty', 'Tahitian', NULL, 'N'),
	(165, 'tg', 'Tajik', NULL, 'N'),
	(166, 'ta', 'Tamil', NULL, 'N'),
	(167, 'tt', 'Tatar', NULL, 'N'),
	(168, 'te', 'Telugu', NULL, 'N'),
	(169, 'th', 'Thai', NULL, 'N'),
	(170, 'bo', 'Tibetan', NULL, 'N'),
	(171, 'ti', 'Tigrinya', NULL, 'N'),
	(172, 'to', 'Tonga', NULL, 'N'),
	(173, 'ts', 'Tsonga', NULL, 'N'),
	(174, 'tr', 'Turkish', NULL, 'N'),
	(175, 'tk', 'Turkmen', NULL, 'N'),
	(176, 'tw', 'Twi', NULL, 'N'),
	(177, 'ug', 'Uyghur', NULL, 'N'),
	(178, 'uk', 'Ukrainian', NULL, 'N'),
	(179, 'ur', 'Urdu', 'pk.png', 'Y'),
	(180, 'uz', 'Uzbek', NULL, 'N'),
	(181, 've', 'Venda', NULL, 'N'),
	(182, 'vi', 'Vietnamese', NULL, 'N'),
	(183, 'vo', 'Volapük', NULL, 'N'),
	(184, 'wa', 'Wallon', NULL, 'N'),
	(185, 'cy', 'Welsh', NULL, 'N'),
	(186, 'wo', 'Wolof', NULL, 'N'),
	(187, 'fy', 'WesternFrisian', NULL, 'N'),
	(188, 'xh', 'Xhosa', NULL, 'N'),
	(189, 'yi', 'Yiddish', NULL, 'N'),
	(190, 'yo', 'Yoruba', NULL, 'N'),
	(191, 'za', 'Zhuang,Chuang', NULL, 'N'),
	(192, 'zu', 'Zulu', NULL, 'N');


CREATE TABLE IF NOT EXISTS `tblTranslation` (
  `TranslationID` int(11) NOT NULL AUTO_INCREMENT,
  `LanguageID` int(11) DEFAULT NULL,
  `Language` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Translation` longtext COLLATE utf8_unicode_ci,
  `created_at` datetime DEFAULT NULL,
  `created_by` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `updated_by` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`TranslationID`)
)
	COLLATE='utf8_unicode_ci'
	ENGINE=InnoDB
	AUTO_INCREMENT=1
;

-- add English Lables
INSERT INTO `tblTranslation` ( `LanguageID`, `Language`, `Translation`, `created_at`, `created_by`, `updated_at`, `updated_by`) VALUES ( 43, 'English', '{"BUTTON_ACTIVATE_CAPTION":"Activate","BUTTON_ACTIVE_CAPTION":"Active","BUTTON_ADD_CAPTION":"Add New","BUTTON_APPROVE_CAPTION":"Approve","BUTTON_BACK_CAPTION":"Back","BUTTON_BROWSE_CAPTION":"Browse","BUTTON_CLOSE_CAPTION":"Close","BUTTON_DEACTIVATE_CAPTION":"Deactivate","BUTTON_DELETE_CAPTION":"Delete","BUTTON_DOWNLOAD_CAPTION":"Download","BUTTON_EDIT_CAPTION":"Edit","BUTTON_EXPORT_CAPTION":"Export","BUTTON_EXPORT_CSV_CAPTION":"CSV","BUTTON_EXPORT_EXCEL_CAPTION":"EXCEL","BUTTON_IMPORTCSV_CAPTION":"Import","BUTTON_INACTIVE_CAPTION":"Inactive","BUTTON_LOADING_CAPTION":"Loading...","BUTTON_LOGIN_CAPTION":"Login","BUTTON_NO_CAPTION":"No","BUTTON_OFF_CAPTION":"OFF","BUTTON_ON_CAPTION":"ON","BUTTON_PAY_CAPTION":"Pay","BUTTON_PAY_NOW_CAPTION":"Pay Now","BUTTON_REJECT_CAPTION":"Reject","BUTTON_SAVE_CAPTION":"Save","BUTTON_SEARCH_CAPTION":"Search","BUTTON_SEND_CAPTION":"Send","BUTTON_UPDATE_CAPTION":"Update","BUTTON_UPLOAD_CAPTION":"Upload","BUTTON_VIEW_CAPTION":"View","BUTTON_YES_CAPTION":"Yes","CUST_PANEL_BREADCRUMB_HOME":"Home","CUST_PANEL_FILTER_TITLE":"Filter","CUST_PANEL_HEAER_EDIT_PROFILE":"Edit Profile","CUST_PANEL_HEAER_LOGOUT":"Log Out","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_FILTER_FIELD_END_DATE":"End Date","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_FILTER_FIELD_START_DATE":"Start Date","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_DISPUTE_FIELD_AC_NAME":"Account Name","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_DISPUTE_FIELD_ATTACHMENT":"Attachment","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_DISPUTE_FIELD_CREATED_BY":"Created By","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_DISPUTE_FIELD_CREATED_DATE":"Created Date","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_DISPUTE_FIELD_DISPUTE_AMOUNT":"Dispute Amount","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_DISPUTE_FIELD_INVOICE_NUMBER":"Invoice Number","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_DISPUTE_FIELD_INVOICE_TYPE":"Invoice Type","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_DISPUTE_FIELD_NOTES":"Notes","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_DISPUTE_FIELD_STATUS":"Status","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_DISPUTE_TITLE":"Dispute","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_VIEW_PAYMENT_FIELD_ACTION":"Action","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_VIEW_PAYMENT_FIELD_AMOUNT":"Amount","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_VIEW_PAYMENT_FIELD_INVOICE":"Invoice","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_VIEW_PAYMENT_FIELD_NOTES":"Notes","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_VIEW_PAYMENT_FIELD_PAYMENT_DATE":"Payment Date","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_VIEW_PAYMENT_FIELD_PAYMENT_METHOD":"Payment Method","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_MODAL_VIEW_PAYMENT_TITLE":"View Payment","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_TBL_AMOUNT":"AMOUNT","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_TBL_BALANCE_AFTER_OFFSET":"BALANCE AFTER OFFSET:","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_TBL_BALANCE_BROUGHT_FORWARD":"BALANCE BROUGHT FORWARD: ","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_TBL_DATE":"DATE","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_TBL_INVOICE":"INVOICE","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_TBL_NO":"NO","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_TBL_NO_DATA":"No data available in table","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_TBL_PAYMENT":"PAYMENT","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_TBL_PENDING_DISPUTE":"PENDING DISPUTE","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_TBL_PERIOD":"PERIOD","CUST_PANEL_PAGE_ACCOUNT_STATEMENT_TITLE":"Statement of Account","CUST_PANEL_PAGE_ANALYSIS_DDL_LISTTYPE_LBL_MONTHLY":"Monthly","CUST_PANEL_PAGE_ANALYSIS_DDL_LISTTYPE_LBL_WEEKLY":"Weekly","CUST_PANEL_PAGE_ANALYSIS_DDL_LISTTYPE_LBL_YEARLY":"Yearly","CUST_PANEL_PAGE_ANALYSIS_DDL_PINEXT_LBL_BY_EXTENSION":"By Extension","CUST_PANEL_PAGE_ANALYSIS_DDL_PINEXT_LBL_BY_PINCODE":"By Pincode","CUST_PANEL_PAGE_ANALYSIS_DDL_TYPE_LBL_BY_COST":"By Cost","CUST_PANEL_PAGE_ANALYSIS_DDL_TYPE_LBL_BY_DURATION":"By Duration","CUST_PANEL_PAGE_ANALYSIS_FILTER_FIELD_COUNTRY":"Country","CUST_PANEL_PAGE_ANALYSIS_FILTER_FIELD_END_DATE":"End Date","CUST_PANEL_PAGE_ANALYSIS_FILTER_FIELD_PREFIX":"Prefix","CUST_PANEL_PAGE_ANALYSIS_FILTER_FIELD_START_DATE":"Start date","CUST_PANEL_PAGE_ANALYSIS_FILTER_FIELD_TIMEZONE":"TimeZone","CUST_PANEL_PAGE_ANALYSIS_FILTER_FIELD_TRUNK":"Trunk","CUST_PANEL_PAGE_ANALYSIS_FILTER_FIELD_TYPE":"Type","CUST_PANEL_PAGE_ANALYSIS_HEADER_ANALYSIS_DATA_LBL_TOTAL_CALLS":"Total Calls","CUST_PANEL_PAGE_ANALYSIS_HEADER_ANALYSIS_DATA_LBL_TOTAL_MINUTES":"Total Minutes","CUST_PANEL_PAGE_ANALYSIS_HEADER_ANALYSIS_DATA_LBL_TOTAL_SALES":"Total Sales","CUST_PANEL_PAGE_ANALYSIS_HEADING_EXTENSIONS":"Top Extensions","CUST_PANEL_PAGE_ANALYSIS_HEADING_EXTENSIONS_REPORT":"Top Extensions Detail Report","CUST_PANEL_PAGE_ANALYSIS_HEADING_INVOICES_&_EXPENSES":"Invoices & Expenses","CUST_PANEL_PAGE_ANALYSIS_HEADING_INVOICES_&_EXPENSES_LBL_PAYMENT_RECEIVED":"Payment Received:","CUST_PANEL_PAGE_ANALYSIS_HEADING_INVOICES_&_EXPENSES_LBL_TOTAL_INVOICE":"Total Invoice:","CUST_PANEL_PAGE_ANALYSIS_HEADING_INVOICES_&_EXPENSES_LBL_TOTAL_OUTSTANDING":"Total Outstanding:","CUST_PANEL_PAGE_ANALYSIS_HEADING_PINCODE":"Top Pincodes","CUST_PANEL_PAGE_ANALYSIS_HEADING_PINCODE_REPORT":"Top Pincodes Detail Report","CUST_PANEL_PAGE_ANALYSIS_HEADING_PIN_GRID":"Pincodes Detail Report","CUST_PANEL_PAGE_ANALYSIS_INVOICE_BUTTON_INVOICE_RECEIVED":"Invoice Received","CUST_PANEL_PAGE_ANALYSIS_INVOICE_BUTTON_INVOICE_SENT":"Invoice Sent","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_ACCOUNT_BALANCE":"Account Balance","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_DUE_AMOUNT":"Due Amount","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_LOCUTORIOS_BALANCE":"Locutorios Total Balance","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_MOR_BALANCE":"MOR Total Balance","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_OUTSTANDING_PRIOD":"Outstanding For Selected Period","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_OVERDUE_AMOUNT":"Overdue Amount","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_PAYMENT_RECEIVED":"Payments Received","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_PAYMENT_SENT":"Payments Sent","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_PENDING_DISPUTE":"Pending Dispute","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_PENDING_ESTIMATE":"Pending Eastimate","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_TOTAL_INVOICE_RECEIVED":"Invoice Received","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_TOTAL_INVOICE_SENT":"Invoice Sent for selected period","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_TOTAL_OUTSTANDING":"Total Outstanding","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_TOTAL_PAYABLE":"Total Payable","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_TOTAL_RECEIVABLE":"Total Receivable","CUST_PANEL_PAGE_ANALYSIS_INVOICE_LBL_UNBILLED_AMOUNT":"Unbilled Amount","CUST_PANEL_PAGE_ANALYSIS_LBL_CALL_COST":"Call Cost","CUST_PANEL_PAGE_ANALYSIS_LBL_CALL_COUNT":"Call Count","CUST_PANEL_PAGE_ANALYSIS_LBL_CALL_MINUTES":"Call Minutes","CUST_PANEL_PAGE_ANALYSIS_MODAL_PAYMENT_RECEIVED_TBL_AC_NAME":"Account Name","CUST_PANEL_PAGE_ANALYSIS_MODAL_PAYMENT_RECEIVED_TBL_AMOUNT":"Amount","CUST_PANEL_PAGE_ANALYSIS_MODAL_PAYMENT_RECEIVED_TBL_CREATEDBY":"CreatedBy","CUST_PANEL_PAGE_ANALYSIS_MODAL_PAYMENT_RECEIVED_TBL_INVOICE_NO":"Invoice No","CUST_PANEL_PAGE_ANALYSIS_MODAL_PAYMENT_RECEIVED_TBL_NOTES":"Notes","CUST_PANEL_PAGE_ANALYSIS_MODAL_PAYMENT_RECEIVED_TBL_PAYMENT_DATE":"Payment Date","CUST_PANEL_PAGE_ANALYSIS_MODAL_PAYMENT_RECEIVED_TITLE":"Payment Received","CUST_PANEL_PAGE_ANALYSIS_MODAL_TOTAL_INVOICES_TBL_AC_NAME":"Account Name","CUST_PANEL_PAGE_ANALYSIS_MODAL_TOTAL_INVOICES_TBL_GRAND_TOTAL":"Grand Total","CUST_PANEL_PAGE_ANALYSIS_MODAL_TOTAL_INVOICES_TBL_INVOICE_NUMBER":"Invoice Number","CUST_PANEL_PAGE_ANALYSIS_MODAL_TOTAL_INVOICES_TBL_ISSUE_DATE":"Issue Date","CUST_PANEL_PAGE_ANALYSIS_MODAL_TOTAL_INVOICES_TBL_PAID_OS":"Paid\\/OS","CUST_PANEL_PAGE_ANALYSIS_MODAL_TOTAL_INVOICES_TBL_PERIOD":"Period","CUST_PANEL_PAGE_ANALYSIS_MODAL_TOTAL_INVOICES_TBL_STATUS":"Status","CUST_PANEL_PAGE_ANALYSIS_MODAL_TOTAL_INVOICES_TITLE":"Total Invoices","CUST_PANEL_PAGE_ANALYSIS_PIN_GRID_TBL_DESTINATION_NUMBER":"Destination Number","CUST_PANEL_PAGE_ANALYSIS_PIN_GRID_TBL_NUMBER_OF_TIMES_DIALED":"Number of Times Dialed","CUST_PANEL_PAGE_ANALYSIS_PIN_GRID_TBL_TOTAL_COST":"Total Cost","CUST_PANEL_PAGE_ANALYSIS_TAB_CUSTOMER_TITLE":"Customer","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_BREAK_LBL_BY_DESTINATION_BREAK_CALL_COST":"By Destination Break - Call Cost.","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_BREAK_LBL_BY_DESTINATION_BREAK_CALL_COUNT":"By Destination Break - Call Count.","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_BREAK_LBL_BY_DESTINATION_BREAK_CALL_MINUTES":"By Destination Break - Call Minutes.","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_BREAK_TBL_ACD":"ACD (mm:ss)","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_BREAK_TBL_ASR":"ASR (%)","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_BREAK_TBL_BILLED_DURATION_MIN":"Billed Duration (Min.)","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_BREAK_TBL_CHARGED_AMOUNT":"Charged Amount","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_BREAK_TBL_DESTINATION_BREAK":"Destination Break","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_BREAK_TBL_MARGIN":"Margin","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_BREAK_TBL_NO_OF_CALLS":"No. of Calls","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_BREAK_TITLE":"Destination Break","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_LBL_BY_DESTINATION_CALL_COST":"By Destination - Call Cost.","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_LBL_BY_DESTINATION_CALL_COUNT":"By Destination - Call Count.","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_LBL_BY_DESTINATION_CALL_MINUTES":"By Destination - Call Minutes.","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_TBL_ACD":"ACD (mm:ss)","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_TBL_ASR":"ASR (%)","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_TBL_BILLED_DURATION_MIN":"Billed Duration (Min.)","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_TBL_CHARGED_AMOUNT":"Charged Amount","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_TBL_COUNTRY":"Country","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_TBL_MARGIN":"Margin","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_TBL_NO_OF_CALLS":"No. of Calls","CUST_PANEL_PAGE_ANALYSIS_TAB_DESTINATION_TITLE":"Destination","CUST_PANEL_PAGE_ANALYSIS_TAB_LONGEST_DURATIONS_CALLS_TITLE":"Longest Durations Calls","CUST_PANEL_PAGE_ANALYSIS_TAB_MOST_DIALLED_NUMBER_TITLE":"Most Dialled Number","CUST_PANEL_PAGE_ANALYSIS_TAB_MOST_EXPENSIVE_CALLS_TITLE":"Most Expensive Calls","CUST_PANEL_PAGE_ANALYSIS_TAB_PREFIX_LBL_BY_PREFIX_CALL_COST":"By Prefix - Call Cost.","CUST_PANEL_PAGE_ANALYSIS_TAB_PREFIX_LBL_BY_PREFIX_CALL_COUNT":"By Prefix - Call Count.","CUST_PANEL_PAGE_ANALYSIS_TAB_PREFIX_LBL_BY_PREFIX_CALL_MINUTES":"By Prefix - Call Minutes.","CUST_PANEL_PAGE_ANALYSIS_TAB_PREFIX_TBL_ACD":"ACD (mm:ss)","CUST_PANEL_PAGE_ANALYSIS_TAB_PREFIX_TBL_ASR":"ASR (%)","CUST_PANEL_PAGE_ANALYSIS_TAB_PREFIX_TBL_BILLED_DURATION_MIN":"Billed Duration (Min.)","CUST_PANEL_PAGE_ANALYSIS_TAB_PREFIX_TBL_CHARGED_AMOUNT":"Charged Amount","CUST_PANEL_PAGE_ANALYSIS_TAB_PREFIX_TBL_MARGIN":"Margin","CUST_PANEL_PAGE_ANALYSIS_TAB_PREFIX_TBL_NO_OF_CALLS":"No. of Calls","CUST_PANEL_PAGE_ANALYSIS_TAB_PREFIX_TBL_PREFIX":"Prefix","CUST_PANEL_PAGE_ANALYSIS_TAB_PREFIX_TITLE":"Prefix","CUST_PANEL_PAGE_ANALYSIS_TAB_TRUNK_LBL_BY_TRUNK_CALL_COST":"By Trunk - Call Cost.","CUST_PANEL_PAGE_ANALYSIS_TAB_TRUNK_LBL_BY_TRUNK_CALL_COUNT":"By Trunk - Call Count.","CUST_PANEL_PAGE_ANALYSIS_TAB_TRUNK_LBL_BY_TRUNK_CALL_MINUTES":"By Trunk - Call Minutes.","CUST_PANEL_PAGE_ANALYSIS_TAB_TRUNK_TBL_ACD":"ACD (mm:ss)","CUST_PANEL_PAGE_ANALYSIS_TAB_TRUNK_TBL_ASR":"ASR (%)","CUST_PANEL_PAGE_ANALYSIS_TAB_TRUNK_TBL_BILLED_DURATION_MIN":"Billed Duration (Min.)","CUST_PANEL_PAGE_ANALYSIS_TAB_TRUNK_TBL_CHARGED_AMOUNT":"Charged Amount","CUST_PANEL_PAGE_ANALYSIS_TAB_TRUNK_TBL_MARGIN":"Margin","CUST_PANEL_PAGE_ANALYSIS_TAB_TRUNK_TBL_NO_OF_CALLS":"No. of Calls","CUST_PANEL_PAGE_ANALYSIS_TAB_TRUNK_TBL_TRUNK":"Trunk","CUST_PANEL_PAGE_ANALYSIS_TAB_TRUNK_TITLE":"Trunk","CUST_PANEL_PAGE_ANALYSIS_TAB_VENDOR_TITLE":"Vendor","CUST_PANEL_PAGE_CDR_FILTER_FIELD_CDR_TYPE":"CDR Type","CUST_PANEL_PAGE_CDR_FILTER_FIELD_CDR_TYPE_DLL_BOTH":"Both","CUST_PANEL_PAGE_CDR_FILTER_FIELD_CDR_TYPE_DLL_INBOUND":"Inbound","CUST_PANEL_PAGE_CDR_FILTER_FIELD_CDR_TYPE_DLL_OUTBOUND":"Outbound","CUST_PANEL_PAGE_CDR_FILTER_FIELD_CLD":"CLD","CUST_PANEL_PAGE_CDR_FILTER_FIELD_CLI":"CLI","CUST_PANEL_PAGE_CDR_FILTER_FIELD_END_DATE":"End Date","CUST_PANEL_PAGE_CDR_FILTER_FIELD_PREFIX":"Prefix","CUST_PANEL_PAGE_CDR_FILTER_FIELD_SHOW":"Show","CUST_PANEL_PAGE_CDR_FILTER_FIELD_SHOW_DDL_NON_ZERO_COST":"Non Zero Cost","CUST_PANEL_PAGE_CDR_FILTER_FIELD_SHOW_DDL_ZERO_COST":"Zero Cost","CUST_PANEL_PAGE_CDR_FILTER_FIELD_START_DATE":"Start Date","CUST_PANEL_PAGE_CDR_FILTER_FIELD_TRUNK":"Trunk","CUST_PANEL_PAGE_CDR_FILTER_FIELD_TRUNK_DLL_OTHER":"Other","CUST_PANEL_PAGE_CDR_TBL_AC_NAME":"Account Name","CUST_PANEL_PAGE_CDR_TBL_AVG_RATE_MIN":"Avg. Rate\\/Min","CUST_PANEL_PAGE_CDR_TBL_BILLED_DURATION_SEC":"Billed Duration (sec)","CUST_PANEL_PAGE_CDR_TBL_CLD":"CLD","CUST_PANEL_PAGE_CDR_TBL_CLI":"CLI","CUST_PANEL_PAGE_CDR_TBL_CONNECT_TIME":"Connect Time","CUST_PANEL_PAGE_CDR_TBL_COST":"Cost","CUST_PANEL_PAGE_CDR_TBL_DISCONNECT_TIME":"Disconnect Time","CUST_PANEL_PAGE_CDR_TBL_PREFIX":"Prefix","CUST_PANEL_PAGE_CDR_TBL_TRUNK":"Trunk","CUST_PANEL_PAGE_CDR_TITLE":"CDR","CUST_PANEL_PAGE_CREDIT_CARD_FIELD_CARD_TYPE":"Card Type*","CUST_PANEL_PAGE_CREDIT_CARD_FIELD_CREDIT_CARD_NUMBER":"Credit Card Number *","CUST_PANEL_PAGE_CREDIT_CARD_FIELD_CVV_NUMBER":"CVV Number*","CUST_PANEL_PAGE_CREDIT_CARD_FIELD_EXPIRY_DATE":"Expiry Date *","CUST_PANEL_PAGE_CREDIT_CARD_FIELD_NAME_ON_CARD":"Name on card*","CUST_PANEL_PAGE_CREDIT_CARD_HEADING":"Credit Card Detail","CUST_PANEL_PAGE_CUSTOMERS_RATES_MSG_NO_INBOUND_RATE_TABLE_ASSIGN":"No Inbound Rate table assign","CUST_PANEL_PAGE_CUSTOMERS_RATES_MSG_PLEASE_SELECT_A_TRUNK":"Please Select a Trunk","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_INBOUND_RATE_TITLE":"Inbound Rate","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_FILTER_FIELD_CODE":"Code","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_FILTER_FIELD_COUNTRY":"Country","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_FILTER_FIELD_DESCRIPTION":"Description","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_FILTER_FIELD_EFFECTIVE":"Effective","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_FILTER_FIELD_EFFECTIVE_DLL_FUTURE":"Future","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_FILTER_FIELD_EFFECTIVE_DLL_NOW":"Now","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_FILTER_FIELD_ROUTING_PLAN":"Routing Plan","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_FILTER_FIELD_TRUNK":"Trunk","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_FILTER_SEARCH_TITLE":"Search","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_TBL_CODE":"Code","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_TBL_CONNECTION_FEE":"Connection Fee","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_TBL_DESCRIPTION":"Description","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_TBL_EFFECTIVE_DATE":"Effective Date","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_TBL_INTERVAL_1":"Interval 1","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_TBL_INTERVAL_N":"Interval N","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_TBL_RATE":"Rate","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_TBL_ROUTING_PLAN":"Routing plan","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_OUTBOUND_RATE_TITLE":"Outbound Rate","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_SERVICE_RATE_FILTER_FIELD_RATE_TYPE":"Rate Type","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_SERVICE_RATE_FILTER_FIELD_SERVICE":"Service","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_SERVICE_RATE_TITLE":"Service Rate","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_SETTINGS_TAB_OUTGOING_TBL_PREFIX":"Prefix","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_SETTINGS_TAB_OUTGOING_TBL_TRUNK":"Trunk","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_SETTINGS_TAB_OUTGOING_TITLE":"Outgoing","CUST_PANEL_PAGE_CUSTOMERS_RATES_TAB_SETTINGS_TITLE":"Settings","CUST_PANEL_PAGE_EDIT_PROFILE_TITLE":"Edit Profile","CUST_PANEL_PAGE_INVOICE_BANK_AC_TBL_CREATED_DATE":"Created Date","CUST_PANEL_PAGE_INVOICE_BANK_AC_TBL_DEFAULT":"Default","CUST_PANEL_PAGE_INVOICE_BANK_AC_TBL_PAYMENT_METHOD":"Payment Method","CUST_PANEL_PAGE_INVOICE_BANK_AC_TBL_TITLE":"Title","CUST_PANEL_PAGE_INVOICE_BUTTON_PAY_NOW":"Pay Now","CUST_PANEL_PAGE_INVOICE_BUTTON_PAY_NOW_CONFIRM_MSG":"Are you sure you want to pay selected invoices?","CUST_PANEL_PAGE_INVOICE_BUTTON_PAY_NOW_ERROR_MSG":"please select invoice from one Account","CUST_PANEL_PAGE_INVOICE_CVIEW_BUTTON_DOWNLOAD_USAGE":"Download Usage","CUST_PANEL_PAGE_INVOICE_CVIEW_BUTTON_PRINT_INVOICE":"Print Invoice","CUST_PANEL_PAGE_INVOICE_CVIEW_LBL_DUE":"DUE","CUST_PANEL_PAGE_INVOICE_CVIEW_LBL_PAID":"Paid","CUST_PANEL_PAGE_INVOICE_CVIEW_MSG_ERROR_LOADING_INVOICE":"Error loading Invoice, Its need to regenerate.","CUST_PANEL_PAGE_INVOICE_FILTER_FIELD_END_DATE":"Issue Date End","CUST_PANEL_PAGE_INVOICE_FILTER_FIELD_HIDE_ZERO":"Hide Zero Value","CUST_PANEL_PAGE_INVOICE_FILTER_FIELD_NUMBER":"Number","CUST_PANEL_PAGE_INVOICE_FILTER_FIELD_OVERDUE":"Overdue","CUST_PANEL_PAGE_INVOICE_FILTER_FIELD_START_DATE":"Issue Date Start","CUST_PANEL_PAGE_INVOICE_FILTER_FIELD_TYPE":"Type","CUST_PANEL_PAGE_INVOICE_FILTER_FIELD_TYPE_DDL_BOTH":"Both","CUST_PANEL_PAGE_INVOICE_FILTER_FIELD_TYPE_DDL_INVOICE_RECEIVED":"Invoice Received","CUST_PANEL_PAGE_INVOICE_FILTER_FIELD_TYPE_DDL_INVOICE_SENT":"Invoice sent","CUST_PANEL_PAGE_INVOICE_MODAL_PAY_NOW_ACTIVECARD_CONFIRM_MSG":"Are you sure you want to Active the Card?","CUST_PANEL_PAGE_INVOICE_MODAL_PAY_NOW_DISABLECARD_CONFIRM_MSG":"Are you sure you want to Disable the Card?","CUST_PANEL_PAGE_INVOICE_MODAL_PAY_NOW_LBL_TOTAL_PAYMENT":"Total Payment","CUST_PANEL_PAGE_INVOICE_MODAL_PAY_NOW_MSG_TOTAL_OUTSTANDING_IS_LESS_OR_EQUAL_TO_ZERO":"Total outstanding is less or equal to zero","CUST_PANEL_PAGE_INVOICE_MODAL_PAY_NOW_TBL_CREATED_DATE":"Created Date","CUST_PANEL_PAGE_INVOICE_MODAL_PAY_NOW_TBL_DEFAULT":"Default","CUST_PANEL_PAGE_INVOICE_MODAL_PAY_NOW_TBL_PAYMENT_METHOD":"Payment Method","CUST_PANEL_PAGE_INVOICE_MODAL_PAY_NOW_TBL_STATUS":"Status","CUST_PANEL_PAGE_INVOICE_MODAL_PAY_NOW_TBL_TITLE":"Title","CUST_PANEL_PAGE_INVOICE_MODAL_PAY_NOW_TITLE":"Pay Now","CUST_PANEL_PAGE_INVOICE_MODAL_PRINT_INVOICE_TITLE":"Print","CUST_PANEL_PAGE_INVOICE_MODAL_VIEW_INVOICE_FIELD_ACCOUNT_NAME":"Account Name","CUST_PANEL_PAGE_INVOICE_MODAL_VIEW_INVOICE_FIELD_DESCRIPTION":"Description","CUST_PANEL_PAGE_INVOICE_MODAL_VIEW_INVOICE_FIELD_END_DATE":"End Date","CUST_PANEL_PAGE_INVOICE_MODAL_VIEW_INVOICE_FIELD_GRAND_TOTAL":"Grand Total","CUST_PANEL_PAGE_INVOICE_MODAL_VIEW_INVOICE_FIELD_INVOICE_NUMBER":"Invoice Number","CUST_PANEL_PAGE_INVOICE_MODAL_VIEW_INVOICE_FIELD_ISSUE_DATE":"Issue Date","CUST_PANEL_PAGE_INVOICE_MODAL_VIEW_INVOICE_FIELD_START_DATE":"Start Date","CUST_PANEL_PAGE_INVOICE_MODAL_VIEW_INVOICE_TITLE":"View Invoice","CUST_PANEL_PAGE_INVOICE_PDF_LBL_DUE_DATE":"Due Date:","CUST_PANEL_PAGE_INVOICE_PDF_LBL_FROM":"From","CUST_PANEL_PAGE_INVOICE_PDF_LBL_INVOICE_DATE":"Invoice Date:","CUST_PANEL_PAGE_INVOICE_PDF_LBL_INVOICE_FROM":"Invoice From","CUST_PANEL_PAGE_INVOICE_PDF_LBL_INVOICE_NO":"Invoice No:","CUST_PANEL_PAGE_INVOICE_PDF_LBL_INVOICE_PERIOD":"Invoice Period:","CUST_PANEL_PAGE_INVOICE_PDF_LBL_INVOICE_TO":"Invoice To:","CUST_PANEL_PAGE_INVOICE_PDF_LBL_MANAGEMENT_REPORT":"Management Report","CUST_PANEL_PAGE_INVOICE_PDF_LBL_USAGE":"Usage","CUST_PANEL_PAGE_INVOICE_PDF_TBL_ADDITIONAL":"Additional","CUST_PANEL_PAGE_INVOICE_PDF_TBL_BILLED_DURATION":"Billed Duration","CUST_PANEL_PAGE_INVOICE_PDF_TBL_BROUGHT_FORWARD":"Brought Forward","CUST_PANEL_PAGE_INVOICE_PDF_TBL_CALLS":"Calls","CUST_PANEL_PAGE_INVOICE_PDF_TBL_CHARGE":"Charge","CUST_PANEL_PAGE_INVOICE_PDF_TBL_DATE":"Date","CUST_PANEL_PAGE_INVOICE_PDF_TBL_DATE_FROM":"Date From","CUST_PANEL_PAGE_INVOICE_PDF_TBL_DATE_TO":"Date To","CUST_PANEL_PAGE_INVOICE_PDF_TBL_DESCRIPTION":"Description","CUST_PANEL_PAGE_INVOICE_PDF_TBL_DISCOUNT":"Discount","CUST_PANEL_PAGE_INVOICE_PDF_TBL_DURATION":"Duration","CUST_PANEL_PAGE_INVOICE_PDF_TBL_GRAND_TOTAL":"Grand Total","CUST_PANEL_PAGE_INVOICE_PDF_TBL_LINE_TOTAL":"Line Total","CUST_PANEL_PAGE_INVOICE_PDF_TBL_MINS":"Mins","CUST_PANEL_PAGE_INVOICE_PDF_TBL_PRICE":"Price","CUST_PANEL_PAGE_INVOICE_PDF_TBL_QUANTITY":"Quantity","CUST_PANEL_PAGE_INVOICE_PDF_TBL_RECURRING":"Recurring","CUST_PANEL_PAGE_INVOICE_PDF_TBL_SUB_TOTAL":"Sub Total","CUST_PANEL_PAGE_INVOICE_PDF_TBL_TITLE":"Title","CUST_PANEL_PAGE_INVOICE_PDF_TBL_TO":"To","CUST_PANEL_PAGE_INVOICE_PDF_TBL_TOTAL_DUE":"Total Due","CUST_PANEL_PAGE_INVOICE_PDF_TBL_USAGE":"Usage","CUST_PANEL_PAGE_INVOICE_TBL_AC_NAME":"Account Name","CUST_PANEL_PAGE_INVOICE_TBL_GRAND_TOTAL":"Grand Total","CUST_PANEL_PAGE_INVOICE_TBL_INVOICE_NUMBER":"Invoice Number","CUST_PANEL_PAGE_INVOICE_TBL_INVOICE_STATUS":"Invoice Status","CUST_PANEL_PAGE_INVOICE_TBL_ISSUE_DATE":"Issue Date","CUST_PANEL_PAGE_INVOICE_TBL_PAID_OS":"Paid\\/OS","CUST_PANEL_PAGE_INVOICE_TITLE":"Invoice","CUST_PANEL_PAGE_LOGIN_HEADING_INVALID_LOGIN_MSG":"Enter correct login and password.","CUST_PANEL_PAGE_LOGIN_HEADING_INVALID_LOGIN_TITLE":"Invalid login","CUST_PANEL_PAGE_LOGIN_LBL_LOGIN_MSG":"Dear user, Please login below!","CUST_PANEL_PAGE_LOGIN_MSG_LOGGING_PROCESS":"logging in...","CUST_PANEL_PAGE_MONITOR_HEADING_TRAFFIC_BY_REGION":"Traffic By Region","CUST_PANEL_PAGE_MONITOR_MODAL_TRAFFIC_BY_PREFIX_TBL_ACD":"ACD (mm:ss)","CUST_PANEL_PAGE_MONITOR_MODAL_TRAFFIC_BY_PREFIX_TBL_ASR_IN_PERCENTAGE":"ASR (%)","CUST_PANEL_PAGE_MONITOR_MODAL_TRAFFIC_BY_PREFIX_TBL_BILLED_DURATION_MIN":"Billed Duration (Min.)","CUST_PANEL_PAGE_MONITOR_MODAL_TRAFFIC_BY_PREFIX_TBL_CHARGED_AMOUNT":"Charged Amount","CUST_PANEL_PAGE_MONITOR_MODAL_TRAFFIC_BY_PREFIX_TBL_MARGIN":"Margin","CUST_PANEL_PAGE_MONITOR_MODAL_TRAFFIC_BY_PREFIX_TBL_MARGIN_IN_PERCENTAGE":"Margin (%)","CUST_PANEL_PAGE_MONITOR_MODAL_TRAFFIC_BY_PREFIX_TBL_NO_OF_CALLS":"No. of Calls","CUST_PANEL_PAGE_MONITOR_MODAL_TRAFFIC_BY_PREFIX_TBL_PREFIX":"Prefix","CUST_PANEL_PAGE_MONITOR_MODAL_TRAFFIC_BY_PREFIX_TITLE":"Traffic By Prefix","CUST_PANEL_PAGE_MONITOR_RIGHT_SIDE_ACCOUNT_MANAGER":"Account Manager","CUST_PANEL_PAGE_MONITOR_RIGHT_SIDE_ACCOUNT_MANAGER_EMAIL":"Email","CUST_PANEL_PAGE_MONITOR_RIGHT_SIDE_ACCOUNT_MANAGER_NAME":"Name","CUST_PANEL_PAGE_MONITOR_RIGHT_SIDE_MINUTES":"Minutes","CUST_PANEL_PAGE_MONITOR_RIGHT_SIDE_SALES":"Sales","CUST_PANEL_PAGE_MONITOR_RIGHT_SIDE_TODAY_MINUTES":"Minutes","CUST_PANEL_PAGE_MONITOR_RIGHT_SIDE_TODAY_MINUTES_BY_HOUR":"Today Minutes by hour","CUST_PANEL_PAGE_MONITOR_RIGHT_SIDE_TODAY_SALES_BY_HOUR":"Today Sales by hour","CUST_PANEL_PAGE_MONITOR_TAB_DESTINATION_BREAK_LBL_TOP_DESTINATION_BREAK_CALL_COST":"Top 10 Destination Break - Call Cost.","CUST_PANEL_PAGE_MONITOR_TAB_DESTINATION_BREAK_LBL_TOP_DESTINATION_BREAK_CALL_COUNT":"Top 10 Destination Break - Call Count.","CUST_PANEL_PAGE_MONITOR_TAB_DESTINATION_BREAK_LBL_TOP_DESTINATION_BREAK_CALL_MINUTES":"Top 10 Destination Break - Call Minutes.","CUST_PANEL_PAGE_MONITOR_TAB_DESTINATION_BREAK_TITLE":"Destination Break","CUST_PANEL_PAGE_MONITOR_TAB_DESTINATION_LBL_TOP_DESTINATION_CALL_COST":"Top 10 Destination - Call Cost.","CUST_PANEL_PAGE_MONITOR_TAB_DESTINATION_LBL_TOP_DESTINATION_CALL_COUNT":"Top 10 Destination - Call Count.","CUST_PANEL_PAGE_MONITOR_TAB_DESTINATION_LBL_TOP_DESTINATION_CALL_MINUTES":"Top 10 Destination - Call Minutes.","CUST_PANEL_PAGE_MONITOR_TAB_DESTINATION_TITLE":"Destination","CUST_PANEL_PAGE_MONITOR_TAB_LONGEST_DURATIONS_CALLS_TBL_DURATION_SEC":"Duration(Sec)","CUST_PANEL_PAGE_MONITOR_TAB_LONGEST_DURATIONS_CALLS_TBL_NUMBER":"Number","CUST_PANEL_PAGE_MONITOR_TAB_LONGEST_DURATIONS_CALLS_TITLE":"Longest Durations Calls","CUST_PANEL_PAGE_MONITOR_TAB_MOST_DIALLED_NUMBER_TBL_NUMBER":"Number","CUST_PANEL_PAGE_MONITOR_TAB_MOST_DIALLED_NUMBER_TBL_NUMBER_OF_TIMES_DIALLED":"Number of Times Dialled","CUST_PANEL_PAGE_MONITOR_TAB_MOST_DIALLED_NUMBER_TBL_TOTAL_TALK_TIME_SEC":"Total Talk time (sec)","CUST_PANEL_PAGE_MONITOR_TAB_MOST_DIALLED_NUMBER_TITLE":"Most Dialled Number","CUST_PANEL_PAGE_MONITOR_TAB_MOST_EXPENSIVE_CALLS_TBL_COST":"Cost","CUST_PANEL_PAGE_MONITOR_TAB_MOST_EXPENSIVE_CALLS_TBL_DURATION_SEC":"Duration(Sec)","CUST_PANEL_PAGE_MONITOR_TAB_MOST_EXPENSIVE_CALLS_TBL_NUMBER":"Number","CUST_PANEL_PAGE_MONITOR_TAB_MOST_EXPENSIVE_CALLS_TITLE":"Most Expensive Calls","CUST_PANEL_PAGE_MONITOR_TAB_PREFIX_TITLE":"Prefix","CUST_PANEL_PAGE_MONITOR_TAB_PREFIX_TOP_PREFIX_CALL_COST":"Top 10 Prefix - Call Cost.","CUST_PANEL_PAGE_MONITOR_TAB_PREFIX_TOP_PREFIX_CALL_COUNT":"Top 10 Prefix - Call Count.","CUST_PANEL_PAGE_MONITOR_TAB_PREFIX_TOP_PREFIX_CALL_MINUTES":"Top 10 Prefix - Call Minutes.","CUST_PANEL_PAGE_MONITOR_TAB_TRUNK_TITLE":"Trunk","CUST_PANEL_PAGE_MONITOR_TAB_TRUNK_TOP_TRUNK_CALL_COST":"Top 10 Trunks - Call Cost.","CUST_PANEL_PAGE_MONITOR_TAB_TRUNK_TOP_TRUNK_CALL_COUNT":"Top 10 Trunks - Call Count.","CUST_PANEL_PAGE_MONITOR_TAB_TRUNK_TOP_TRUNK_CALL_MINUTES":"Top 10 Trunks - Call Minutes.","CUST_PANEL_PAGE_MOVEMENT_REPORT_FILTER_FIELD_END_DATE":"End Date","CUST_PANEL_PAGE_MOVEMENT_REPORT_FILTER_FIELD_START_DATE":"Start Date","CUST_PANEL_PAGE_MOVEMENT_REPORT_TBL_BALANCE":"Balance","CUST_PANEL_PAGE_MOVEMENT_REPORT_TBL_CONSUMPTION":"Consumption","CUST_PANEL_PAGE_MOVEMENT_REPORT_TBL_DATE":"Date","CUST_PANEL_PAGE_MOVEMENT_REPORT_TBL_PAYMENTS":"Payments","CUST_PANEL_PAGE_MOVEMENT_REPORT_TBL_TOTAL":"Total","CUST_PANEL_PAGE_MOVEMENT_REPORT_TITLE":"Movement Report","CUST_PANEL_PAGE_NEW_TICKET_DETAIL_HEADER":"Ticket Detail","CUST_PANEL_PAGE_NEW_TICKET_TITLE":"New Ticket","CUST_PANEL_PAGE_NOTICEBOARD_MSG_NO_UPDATES_FOUND":"No Updates Found.","CUST_PANEL_PAGE_NOTICEBOARD_MSG_UPDATED":"Updated","CUST_PANEL_PAGE_NOTIFICATIONS_BUTTON_ADD_NEW":"Add New","CUST_PANEL_PAGE_NOTIFICATIONS_MODAL_ADD_MONITORING_FIELD_ACTIVE":"Active","CUST_PANEL_PAGE_NOTIFICATIONS_MODAL_ADD_MONITORING_FIELD_BUSINESS_HOUR_FROM":"Business Hour From","CUST_PANEL_PAGE_NOTIFICATIONS_MODAL_ADD_MONITORING_FIELD_BUSINESS_HOUR_TO":"Business Hour To","CUST_PANEL_PAGE_NOTIFICATIONS_MODAL_ADD_MONITORING_FIELD_MAX_COST":"Max. Cost","CUST_PANEL_PAGE_NOTIFICATIONS_MODAL_ADD_MONITORING_FIELD_MAX_DURATION_SEC":"Max. Duration(sec.)","CUST_PANEL_PAGE_NOTIFICATIONS_MODAL_ADD_MONITORING_FIELD_NAME":"Name","CUST_PANEL_PAGE_NOTIFICATIONS_MODAL_ADD_MONITORING_FIELD_SEND_COPY_TO":"Send Copy To","CUST_PANEL_PAGE_NOTIFICATIONS_MODAL_ADD_MONITORING_FIELD_TYPE":"Type","CUST_PANEL_PAGE_NOTIFICATIONS_MODAL_ADD_MONITORING_TITLE":"Add Monitoring","CUST_PANEL_PAGE_NOTIFICATIONS_MODAL_EDIT_MONITORING_TITLE":"Edit Monitoring","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_ACCOUNT_IS_REQUIRED":"Account is required.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_ALERTTYPE_IS_ALREADY_TAKEN":"AlertType is already taken.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_AT_LEAST_ONE_BLACKLIST_DESTINATION_IS_REQUIRED":"At least one blacklist destination is required.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_CLOSE_TIME_IS_REQUIRED":"Close Time is required.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_COST_IS_REQUIRED":"Cost is required.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_DURATION_IS_REQUIRED":"Duration is required.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_EMAIL_ADDRESS_IS_REQUIRED":"Email Address is required.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_LATEST_UPDATES":"Latest Updates!","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_NOTIFICATION_SUCCESSFULLY_CREATED":"Notification Successfully Created","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_NOTIFICATION_SUCCESSFULLY_DELETED":"Notification Successfully Deleted","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_NOTIFICATION_SUCCESSFULLY_UPDATED":"Notification Successfully Updated","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_OPEN_TIME_IS_REQUIRED":"Open Time is required.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_PROBLEM_CREATING_NOTIFICATION":"Problem Creating Notification.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_PROBLEM_DELETING_NOTIFICATION":"Problem Deleting Notification.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_PROBLEM_UPDATING_NOTIFICATION":"Problem Updating Notification.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_QOS_ALERT_INTERVAL_IS_REQUIRED":"Qos Alert Interval is required.","CUST_PANEL_PAGE_NOTIFICATIONS_MSG_QOS_ALERT_TIME_IS_REQUIRED":"Qos Alert Time is required.","CUST_PANEL_PAGE_NOTIFICATIONS_TAB_MONITORING":"Monitoring","CUST_PANEL_PAGE_NOTIFICATIONS_TBL_LAST_UPDATED":"Last Updated","CUST_PANEL_PAGE_NOTIFICATIONS_TBL_NAME":"Name","CUST_PANEL_PAGE_NOTIFICATIONS_TBL_STATUS":"Status","CUST_PANEL_PAGE_NOTIFICATIONS_TBL_TYPE":"Type","CUST_PANEL_PAGE_NOTIFICATIONS_TBL_UPDATED_BY":"Updated By","CUST_PANEL_PAGE_NOTIFICATIONS_TITLE":"Notifications","CUST_PANEL_PAGE_PAYMENTS_BUTTON_ADD_NEW":"Add New","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_ACTION":"Action","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_ACTION_DDL_PAYMENT_IN":"Payment In","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_ACTION_DDL_PAYMENT_OUT":"Payment out","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_END_DATE":"End Date","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_INVOICE_NO":"Invoice No","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_PAYMENT_METHOD":"Payment Method","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_PAYMENT_METHOD_DDL_BANK_TRANSFER":"BANK TRANSFER","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_PAYMENT_METHOD_DDL_CASH":"CASH","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_PAYMENT_METHOD_DDL_CHEQUE":"CHEQUE","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_PAYMENT_METHOD_DDL_CREDIT_CARD":"CREDIT CARD","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_PAYMENT_METHOD_DDL_PAYPAL":"PAYPAL","CUST_PANEL_PAGE_PAYMENTS_FILTER_FIELD_START_DATE":"Start Date","CUST_PANEL_PAGE_PAYMENTS_MODAL_ADD_PAYMENT_TITLE":"Add New Payment","CUST_PANEL_PAGE_PAYMENTS_MODAL_EDIT_PAYMENT_FIELD_ACTION":"Action *","CUST_PANEL_PAGE_PAYMENTS_MODAL_EDIT_PAYMENT_FIELD_AMOUNT":"Amount *","CUST_PANEL_PAGE_PAYMENTS_MODAL_EDIT_PAYMENT_FIELD_INVOICE":"Invoice No","CUST_PANEL_PAGE_PAYMENTS_MODAL_EDIT_PAYMENT_FIELD_NOTES":"Notes","CUST_PANEL_PAGE_PAYMENTS_MODAL_EDIT_PAYMENT_FIELD_PAYMENT_DATE":"Payment Date *","CUST_PANEL_PAGE_PAYMENTS_MODAL_EDIT_PAYMENT_FIELD_PAYMENT_METHOD":"Payment Method *","CUST_PANEL_PAGE_PAYMENTS_MODAL_EDIT_PAYMENT_FIELD_PROOF_UPLOAD_EXTENSION":"Upload (.pdf, .jpg, .png, .gif)","CUST_PANEL_PAGE_PAYMENTS_MODAL_PAYMENT_NOTES_FIELD_NOTES":"Notes","CUST_PANEL_PAGE_PAYMENTS_MODAL_PAYMENT_NOTES_TITLE":"Payment Notes","CUST_PANEL_PAGE_PAYMENTS_MODAL_VIEW_PAYMENT_FIELD_ACTION":"Action","CUST_PANEL_PAGE_PAYMENTS_MODAL_VIEW_PAYMENT_FIELD_AC_NAME":"Account Name","CUST_PANEL_PAGE_PAYMENTS_MODAL_VIEW_PAYMENT_FIELD_AMOUNT":"Amount","CUST_PANEL_PAGE_PAYMENTS_MODAL_VIEW_PAYMENT_FIELD_INVOICE":"Invoice No","CUST_PANEL_PAGE_PAYMENTS_MODAL_VIEW_PAYMENT_FIELD_NOTES":"Notes","CUST_PANEL_PAGE_PAYMENTS_MODAL_VIEW_PAYMENT_FIELD_PAYMENT_DATE":"Payment Date","CUST_PANEL_PAGE_PAYMENTS_MODAL_VIEW_PAYMENT_FIELD_PAYMENT_METHOD":"Payment Method","CUST_PANEL_PAGE_PAYMENTS_MODAL_VIEW_PAYMENT_TITLE":"View Payment","CUST_PANEL_PAGE_PAYMENTS_MSG_PAYMENT_SUCCESSFULLY_UPDATED":"payment Successfully Updated","CUST_PANEL_PAGE_PAYMENTS_MSG_PROBLEM_CREATING_PAYMENT":"Problem Creating Payment.","CUST_PANEL_PAGE_PAYMENTS_MSG_YOU_HAVE_NOT_PERMISSION_TO_APPROVE_OR_REJECT":"You have not permission to Approve or reject","CUST_PANEL_PAGE_PAYMENTS_TBL_AMOUNT":"Amount","CUST_PANEL_PAGE_PAYMENTS_TBL_INVOICE_NO":"Invoice No","CUST_PANEL_PAGE_PAYMENTS_TBL_PAYMENT_DATE":"Payment Date","CUST_PANEL_PAGE_PAYMENTS_TBL_STATUS":"Status","CUST_PANEL_PAGE_PAYMENTS_TBL_TYPE":"Type","CUST_PANEL_PAGE_PAYMENTS_TITLE":"Payments","CUST_PANEL_PAGE_PAYMENT_METHOD_MSG_PAYMENT_METHOD_NOT_INTEGRATED":"Payment Method Not Integrated","CUST_PANEL_PAGE_PAYMENT_METHOD_MSG_PAYMENT_METHOD_PROFILE_SUCCESSFULLY_UPDATED":"Payment Method Profile Successfully Updated","CUST_PANEL_PAGE_PAYMENT_METHOD_MSG_PROBLEM_UPDATING_PAYMENT_METHOD_PROFILE":"Problem Updating Payment Method Profile.","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_BUTTON_ADD_BANK_ACCOUNT":"Add Bank Account","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_BUTTON_ADD_NEW":"Add New","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_BUTTON_SET_DEFAULT":"Set Default","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_BUTTON_SET_DEFAULT_CARD_MSG":"Are you sure you want to set Default this Card?","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_BUTTON_SET_DEFAULT_MSG_PAYMENT_METHOD_PROFILE_SUCCESSFULLY_UPDATED":"Payment Method Profile Successfully Updated","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_BUTTON_SET_DEFAULT_MSG_PROBLEM_UPDATING_PAYMENT_METHOD_PROFILE":"Problem Updating Payment Method Profile.","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_BUTTON_VERIFY":"Verify","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_BANK_AC_FIELD_AC_HOLDER_NAME":"Account Holder Name*","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_BANK_AC_FIELD_AC_HOLDER_TYPE":"Account Holder Type*","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_BANK_AC_FIELD_AC_NUMBER":"Account Number *","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_BANK_AC_FIELD_ROUTING_NUMBER":"Routing Number*","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_BANK_AC_FIELD_TITLE":"Title","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_BANK_AC_TITLE":"Add Bank Account","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_CARD_FIELD_CARD_TYPE":"Card Type*","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_CARD_FIELD_CREDIT_CARD_NUMBER":"Credit Card Number *","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_CARD_FIELD_CVV_NUMBER":"CVV Number*","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_CARD_FIELD_EXPIRY_DATE":"Expiry Date *","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_CARD_FIELD_NAME_ON_CARD":"Name on card*","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_CARD_FIELD_TITLE":"Title","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_CARD_MSG_PAYMENT_GATEWAY_NOT_SETUP":"Payment Gateway not setup","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_CARD_MSG_PLEASE_SELECT_PAYMENT_GATEWAY":"Please Select Payment Gateway","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_ADD_NEW_CARD_TITLE":"Add New Card","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_SAGEPAY_ADD_NEW_BANK_AC_FIELD_AC_HOLDER_TYPE":"Account Holder Type*","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_SAGEPAY_ADD_NEW_BANK_AC_FIELD_AC_NAME":"Bank Account Name*","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_SAGEPAY_ADD_NEW_BANK_AC_FIELD_AC_NUMBER":"Account Number *","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_SAGEPAY_ADD_NEW_BANK_AC_FIELD_BRANCH_CODE":"Branch Code*","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_SAGEPAY_ADD_NEW_BANK_AC_FIELD_SAGEPAY_AC_NAME":"Account Name(Sage Pay System) *","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_SAGEPAY_ADD_NEW_BANK_AC_FIELD_TITLE":"Title","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_SAGEPAY_ADD_NEW_BANK_AC_TITLE":"Add Bank Account","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_VERIFY_BANK_AC_FIELD_MICRO_DEPOSIT1":"Micro Deposit 1*","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_VERIFY_BANK_AC_FIELD_MICRO_DEPOSIT1_MSG":"You can verify your customer\\u2019s routing and account numbers by sending their account two micro-deposits. Two small deposits will be made to their account. The transfers can take 3-4 business days to appear on their account. Once they\\u2019ve been received by the customer, the amounts for each deposit will need to be provided to you by the customer to verify that they have access to their account statement.","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_VERIFY_BANK_AC_FIELD_MICRO_DEPOSIT2":"Micro Deposit 2*","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_VERIFY_BANK_AC_FIELD_MICRO_DEPOSIT2_MSG":"You can verify your customer\\u2019s routing and account numbers by sending their account two micro-deposits. Two small deposits will be made to their account. The transfers can take 3-4 business days to appear on their account. Once they\\u2019ve been received by the customer, the amounts for each deposit will need to be provided to you by the customer to verify that they have access to their account statement.","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_VERIFY_BANK_AC_LBL_MICRO_DEPOSIT":"Micro Deposit","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_VERIFY_BANK_AC_MSG1":"* Both Deposit amounts in cents","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_VERIFY_BANK_AC_MSG2":"* For live payments you have upto 10 tries to verify bank account after that bank account is unverifiable","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MODAL_VERIFY_BANK_AC_TITLE":"Verify Bank Account","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MSG_CARD_ACTIVE_DEACTIVE_FAILED":"Problem Updating Card.","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MSG_CARD_ACTIVE_DEACTIVE_SUCCESSFULLY":"Card Successfully Updated","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MSG_PAYMENT_GATEWAY_NOT_SETUP":"Payment Gateway not setup","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MSG_PAYMENT_SUCCESSFULLY_CREATED":"Payment Successfully Created","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MSG_PROBLEM_CREATING_PAYMENT":"Problem Creating Payment.","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_MSG_SAGE_DIRECT_DEBIT_NOT_SETUP_CORRECTLY":"Sage Direct Debit not setup correctly","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_TBL_ACTIVE_CARD_MSG":"Are you sure you want to Active the Card?","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_TBL_CREATED_DATE":"Created Date","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_TBL_DEFAULT":"Default","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_TBL_DISABLE_CARD_MSG":"Are you sure you want to Disable the Card?","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_TBL_PAYMENT_METHOD":"Payment Method","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_TBL_STATUS":"Status","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_TBL_TITLE":"Title","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_TBL_VERIFY":"Verify","CUST_PANEL_PAGE_PAYMENT_METHOD_PROFILES_TITLE":"Payment Method Profiles","CUST_PANEL_PAGE_PROFILE_HEADING_ACCOUNT_DETAILS":"Account Details","CUST_PANEL_PAGE_PROFILE_HEADING_VIEW_ACCOUNT":"View Account","CUST_PANEL_PAGE_PROFILE_MSG_ACCOUNT_SUCCESSFULLY_UPDATED":"Account Successfully Updated","CUST_PANEL_PAGE_PROFILE_MSG_PROBLEM_UPDATING_ACCOUNT":"Problem Updating Account.","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_ACCOUNT_NAME":"*Account Name","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_ACCOUNT_OWNER":"Account Owner","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_AC_NUMBER":"Account Number","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_BILLING_EMAIL":"Billing Email","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_CURRENCY":"Currency","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_CUSTOMER":"Customer","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_DESCRIPTION":"Description","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_EMPLOYEE":"Employee","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_FAX":"Fax","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_FIRST_NAME":"First Name","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_LAST_NAME":"Last Name","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_OWNERSHIP":"Ownership","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_PASSWORD":"Password","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_PHONE":"Phone","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_PICTURE":"Picture","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_STATUS":"Status","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_TIMEZONE":"Timezone","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_VAT_NUMBER":"VAT Number","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_VENDOR":"Vendor","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_LBL_WEBSITE":"Website","CUST_PANEL_PAGE_PROFILE_TAB_AC_DETAILS_TITLE":"Account Details","CUST_PANEL_PAGE_PROFILE_TAB_ADDRESS_INFORMATION_LBL_ADDRESS_LINE_1":"Address Line 1","CUST_PANEL_PAGE_PROFILE_TAB_ADDRESS_INFORMATION_LBL_ADDRESS_LINE_2":"Address Line 2","CUST_PANEL_PAGE_PROFILE_TAB_ADDRESS_INFORMATION_LBL_ADDRESS_LINE_3":"Address Line 3","CUST_PANEL_PAGE_PROFILE_TAB_ADDRESS_INFORMATION_LBL_CITY":"City","CUST_PANEL_PAGE_PROFILE_TAB_ADDRESS_INFORMATION_LBL_COUNTRY":"*Country","CUST_PANEL_PAGE_PROFILE_TAB_ADDRESS_INFORMATION_LBL_POST_ZIP_CODE":"Post\\/Zip Code","CUST_PANEL_PAGE_PROFILE_TAB_ADDRESS_INFORMATION_TITLE":"Address Information","CUST_PANEL_PAGE_PROFILE_TAB_BILLING_LBL_BILLING_TIMEZONE":"Billing Timezone*","CUST_PANEL_PAGE_PROFILE_TAB_BILLING_LBL_BILLING_TYPE":"Billing Type*","CUST_PANEL_PAGE_PROFILE_TAB_BILLING_LBL_TAX_RATE":"Tax Rate","CUST_PANEL_PAGE_PROFILE_TAB_BILLING_TITLE":"Billing","CUST_PANEL_PAGE_PROFILE_TAB_CONTACTS_TBL_CONTACT_NAME":"Contact Name","CUST_PANEL_PAGE_PROFILE_TAB_CONTACTS_TBL_EMAIL":"Email","CUST_PANEL_PAGE_PROFILE_TAB_CONTACTS_TBL_PHONE":"Phone","CUST_PANEL_PAGE_PROFILE_TAB_CONTACTS_TITLE":"Contacts","CUST_PANEL_PAGE_PROFILE_TAB_PAYMENT_INFORMATION_LBL_PAYMENT_DETAILS":"Payment Details","CUST_PANEL_PAGE_PROFILE_TAB_PAYMENT_INFORMATION_LBL_PAYMENT_METHOD":"Payment Method","CUST_PANEL_PAGE_PROFILE_TAB_PAYMENT_INFORMATION_TITLE":"Payment Information","CUST_PANEL_PAGE_PROFILE_TBL_FILE_NAME":"File Name","CUST_PANEL_PAGE_PROFILE_TITLE":"Profile","CUST_PANEL_PAGE_RATES_FILTER_FIELD_DESCRIPTION":"Description","CUST_PANEL_PAGE_RATES_FILTER_FIELD_PREFIX":"Prefix","CUST_PANEL_PAGE_RATES_TBL_CONNECTION_FEE":"Connection Fee","CUST_PANEL_PAGE_RATES_TBL_EFFECTIVE_DATE":"Effective Date","CUST_PANEL_PAGE_RATES_TBL_INTERVAL_1":"Interval 1","CUST_PANEL_PAGE_RATES_TBL_INTERVAL_N":"Interval N","CUST_PANEL_PAGE_RATES_TBL_NAME":"Name","CUST_PANEL_PAGE_RATES_TBL_PREFIX":"Prefix","CUST_PANEL_PAGE_RATES_TBL_RATE":"Rate","CUST_PANEL_PAGE_RATES_TITLE":"Rates","CUST_PANEL_PAGE_TICKETS_ADD_TICKET":"Ticket","CUST_PANEL_PAGE_TICKETS_BUTTON_ADD_NEW":"Add New","CUST_PANEL_PAGE_TICKETS_DETAIL_TAB_REQUESTER_INFO":"Requester Info","CUST_PANEL_PAGE_TICKETS_DETAIL_TAB_TICKET_PROPERTIES":"Ticket Properties","CUST_PANEL_PAGE_TICKETS_DETAIL_TITLE":"Detail","CUST_PANEL_PAGE_TICKETS_FILTER_FIELD_PRIORITY":"Priority","CUST_PANEL_PAGE_TICKETS_FILTER_FIELD_SEARCH":"Search","CUST_PANEL_PAGE_TICKETS_FILTER_FIELD_STATUS":"Status","CUST_PANEL_PAGE_TICKETS_MODAL_TICKET_EMAIL_ACTION_TITLE":"Ticket","CUST_PANEL_PAGE_TICKETS_MSG_FILE_ALREADY_SELECTED":"file already selected.","CUST_PANEL_PAGE_TICKETS_MSG_FILE_TYPE_NOT_ALLOWED":"file type not allowed.","CUST_PANEL_PAGE_TICKETS_MSG_MAX_FILE_SIZE_ERROR":"Filet is too large, Maximum file size :","CUST_PANEL_PAGE_TICKETS_TABLE_SORTED_BY":"Sorted by","CUST_PANEL_PAGE_TICKETS_TABLE_SORTED_BY_COLUMNS_ASCENDING":"Ascending","CUST_PANEL_PAGE_TICKETS_TABLE_SORTED_BY_COLUMNS_CREATED_AT":"Date Created","CUST_PANEL_PAGE_TICKETS_TABLE_SORTED_BY_COLUMNS_DESCENDING":"Descending","CUST_PANEL_PAGE_TICKETS_TABLE_SORTED_BY_COLUMNS_STATUS":"status","CUST_PANEL_PAGE_TICKETS_TABLE_SORTED_BY_COLUMNS_SUBJECT":"subject","CUST_PANEL_PAGE_TICKETS_TABLE_SORTED_BY_COLUMNS_UPDATED_AT":"Last Modified","CUST_PANEL_PAGE_TICKETS_TAB_CREATED":"Created:","CUST_PANEL_PAGE_TICKETS_TAB_PRIORITY":"Priority:","CUST_PANEL_PAGE_TICKETS_TAB_REQUESTER":"Requester:","CUST_PANEL_PAGE_TICKETS_TAB_SHORTNAME":"ShortName","CUST_PANEL_PAGE_TICKETS_TAB_STATUS":"Status:","CUST_PANEL_PAGE_TICKETS_TITLE":"Tickets","CUST_PANEL_PAGE_TICKETS_TOOLTIP_NEXT_TICKET":"Next Ticket","CUST_PANEL_PAGE_TICKETS_TOOLTIP_PREVIOUS_TICKET":"Previous Ticket","CUST_PANEL_PAGE_TICKETS_TOOLTIP_REPLY":"Reply","CUST_PANEL_PAGE_TICKET_FIELDS_1":"Requester1","CUST_PANEL_PAGE_TICKET_FIELDS_2":"Subject","CUST_PANEL_PAGE_TICKET_FIELDS_3":"Type","CUST_PANEL_PAGE_TICKET_FIELDS_3_VALUE_11":"NEON","CUST_PANEL_PAGE_TICKET_FIELDS_3_VALUE_7":"Other","CUST_PANEL_PAGE_TICKET_FIELDS_4":"Status","CUST_PANEL_PAGE_TICKET_FIELDS_4_VALUE_13":"Being Processed","CUST_PANEL_PAGE_TICKET_FIELDS_4_VALUE_14":"Awaiting your Reply","CUST_PANEL_PAGE_TICKET_FIELDS_4_VALUE_15":"This ticket has been Resolved","CUST_PANEL_PAGE_TICKET_FIELDS_4_VALUE_16":"This ticket has been Closed","CUST_PANEL_PAGE_TICKET_FIELDS_4_VALUE_17":"This ticket has been All Un Resolved","CUST_PANEL_PAGE_TICKET_FIELDS_4_VALUE_18":"Awaiting your Reply","CUST_PANEL_PAGE_TICKET_FIELDS_4_VALUE_19":"Being Processed","CUST_PANEL_PAGE_TICKET_FIELDS_5":"Priority","CUST_PANEL_PAGE_TICKET_FIELDS_6":"Neon First Group","CUST_PANEL_PAGE_TICKET_FIELDS_7":"Assigned to","CUST_PANEL_PAGE_TICKET_FIELDS_8":"Description","CUST_PANEL_PAGE_TICKET_FIELDS_PRIORITY_VAL_HIGH":"High","CUST_PANEL_PAGE_TICKET_FIELDS_PRIORITY_VAL_LOW":"Low","CUST_PANEL_PAGE_TICKET_FIELDS_PRIORITY_VAL_MEDIUM":"Medium","CUST_PANEL_PAGE_TICKET_FIELDS_PRIORITY_VAL_URGENT":"Urgent","CUST_PANEL_SIDENAV_MENU_ANALYSIS":"Analysis","CUST_PANEL_SIDENAV_MENU_BILLING":"Billing","CUST_PANEL_SIDENAV_MENU_BILLING__ACCOUNT_STATEMENT":"Account Statement","CUST_PANEL_SIDENAV_MENU_BILLING__ANALYSIS":"Analysis","CUST_PANEL_SIDENAV_MENU_BILLING__CRD":"CDR","CUST_PANEL_SIDENAV_MENU_BILLING__INVOICES":"Invoices","CUST_PANEL_SIDENAV_MENU_BILLING__PAYMENTS":"Payments","CUST_PANEL_SIDENAV_MENU_BILLING__PAYMENT_METHOD_PROFILES":"Payment Method Profiles","CUST_PANEL_SIDENAV_MENU_COMMERCIAL":"Commercial","CUST_PANEL_SIDENAV_MENU_DASHBOARD":"Dashboard","CUST_PANEL_SIDENAV_MENU_MOVEMENT_REPORT":"Movement Report","CUST_PANEL_SIDENAV_MENU_NOTICE_BOARD":"Notice Board","CUST_PANEL_SIDENAV_MENU_NOTIFICATIONS":"Notifications","CUST_PANEL_SIDENAV_MENU_PROFILE":"Profile","CUST_PANEL_SIDENAV_MENU_RATES":"Rates","CUST_PANEL_SIDENAV_MENU_TICKET_MANAGEMENT":"Ticket Management","CUST_PANEL_SIDENAV_MENU_TICKET_MANAGEMENT__TICKET":"Ticket","DATATABLE_PROCESSING":"Processing...","DROPDOWN_OPTION_ALL":"All","DROPDOWN_OPTION_SELECT":"Select","HTTP_STATUS_400_MSG":"Bad Request","HTTP_STATUS_403_MSG":"Forbidden","HTTP_STATUS_404_MSG":"Not Found","HTTP_STATUS_408_MSG":"Request Timeout","HTTP_STATUS_410_MSG":"Gone","HTTP_STATUS_500_MSG":"Oops Something went wrong please contact your system administrator","HTTP_STATUS_503_MSG":"Service Unavailable","HTTP_STATUS_504_MSG":"Gateway Timeout","MAIL_LBL_ATTACHMENTS":"Attachments","MAIL_LBL_BCC":"bcc","MAIL_LBL_CC":"cc","MAIL_LBL_FROM":"From","MAIL_LBL_MESSAGE":"Message","MAIL_LBL_REPLIED":"replied","MAIL_LBL_SUBJECT":"Subject","MAIL_LBL_TO":"to","MESSAGE_ADD_AN_ATTACHMENT":"Add an attachment\\u2026","MESSAGE_ARE_YOU_SURE":"Are you Sure?","MESSAGE_ATTACHMENTS_DELETE_SUCCESSFULLY":"Attachments delete successfully","MESSAGE_CONTENT_LOADION":"Content is loading...","MESSAGE_DATA_NOT_AVAILABLE":"No Data","MESSAGE_FAILED_TO_UPLOAD_FILE":"Failed to upload file.","MESSAGE_FIELD_IS_REQUIRED":"field is required","MESSAGE_NO_RESULT_FOUND":"No Result Found","MESSAGE_PLEASE_SUBMIT_REQUIRED_FIELDS":"Please submit required fields.","MESSAGE_PROBLEM_DELETING_EXCEPTION":"Problem Deleting. Exception:","MESSAGE_RECORD_NOT_FOUND":"Record Not Found","MESSAGE_SELECT_END_DATE":"Please Select a End date","MESSAGE_SELECT_START_DATE":"Please Select a Start date","MESSAGE_SOME_PROBLEM_OCCURRED":"Some problem occurred.","MESSAGE_SUCCESSFULLY_UPDATED":"Successfully Updated","PAGE_DASHBOARD_DATA_WORLDMAP_LBL_ACD":"ACD:","PAGE_DASHBOARD_DATA_WORLDMAP_LBL_ASR":"ASR:","PAGE_DASHBOARD_DATA_WORLDMAP_LBL_CALLS":"Calls:","PAGE_DASHBOARD_DATA_WORLDMAP_LBL_COST":"Cost:","PAGE_DASHBOARD_DATA_WORLDMAP_LBL_MARGIN":"Margin(%):","PAGE_DASHBOARD_DATA_WORLDMAP_LBL_MINUTES":"Minutes:","PAGE_DASHBOARD_DATA_WORLDMAP_LBL_TOTAL_MARGIN":"TotalMargin:","PAGE_INVOICE_MSG_ACCOUNT_PROFILE_NOT_SET":"Account Profile not set","PAGE_INVOICE_MSG_INVOICE_NOT_FOUND":"Invoice not found","PAGE_NOTIFICATIONS_FIELD_CALL_MONITOR_CUSTOMER_ALERT_TYPE_DDL_CALL_AFTER_BUSINESS_HOUR":"Call After Business Hour","PAGE_NOTIFICATIONS_FIELD_CALL_MONITOR_CUSTOMER_ALERT_TYPE_DDL_EXPENSIVE_CALLS":"Expensive Calls","PAGE_NOTIFICATIONS_FIELD_CALL_MONITOR_CUSTOMER_ALERT_TYPE_DDL_LONGEST_CALL":"Longest Call","PAGE_PAYMENT_FIELD_CREDIT_CARD_TYPE_DDL_AMERICAN_EXPRESS":"American Express","PAGE_PAYMENT_FIELD_CREDIT_CARD_TYPE_DDL_AUSTRALIAN_BANKCARD":"Australian BankCard","PAGE_PAYMENT_FIELD_CREDIT_CARD_TYPE_DDL_DINERS_CLUB":"Diners Club","PAGE_PAYMENT_FIELD_CREDIT_CARD_TYPE_DDL_DISCOVER":"Discover","PAGE_PAYMENT_FIELD_CREDIT_CARD_TYPE_DDL_JCB":"JCB","PAGE_PAYMENT_FIELD_CREDIT_CARD_TYPE_DDL_MASTERCARD":"MasterCard","PAGE_PAYMENT_FIELD_CREDIT_CARD_TYPE_DDL_VISA":"Visa","PAGE_TICKET_MSG_EMAIL_MESSAGE_REQUIRED":"The email message field is required","PAGE_TICKET_MSG_EMAIL_RECIPIENT_REQUIRED":"The email recipient is required","PAGE_TICKET_MSG_EMAIL_SUBJECT_REQUIRED":"The email Subject is required","PAGE_TICKET_MSG_FAILED_TO_UPDATED_DUE_DATE":"Failed To Updated Due Date.","PAGE_TICKET_MSG_INVALID_TICKET":"invalid Ticket.","PAGE_TICKET_MSG_NOTE_SUCCESSFULLY_CREATED":"Note Successfully Created","PAGE_TICKET_MSG_PROBLEM_SENDING_EMAIL":"Problem Sending Email","PAGE_TICKET_MSG_PROVIDE_VALID_INTEGER_VALUE":"Provide Valid Integer Value.","PAGE_TICKET_MSG_TICKET_NOT_FOUND":"Ticket not found.","PAGE_TICKET_MSG_TICKET_SUCCESSFULLY_CLOSED":"Ticket Successfully Closed","PAGE_TICKET_MSG_TICKET_SUCCESSFULLY_CREATED":"Ticket Successfully Created","PAGE_TICKET_MSG_TICKET_SUCCESSFULLY_DELETED":"Ticket Successfully Deleted","PAGE_TICKET_MSG_TICKET_SUCCESSFULLY_UPDATED":"Ticket Successfully Updated","PAGE_TICKET_MSG_YOU_HAVE_NOT_ACCESS_TO_UPDATE_THIS_TICKET":"You have not access to update this ticket","PAGE_WIDGETS_DATA_REPORT_TBL_ACCOUNT":"Account","PAGE_WIDGETS_DATA_REPORT_TBL_ACD":"ACD (mm:ss)","PAGE_WIDGETS_DATA_REPORT_TBL_ASR_IN_PERCENTAGE":"ASR (%)","PAGE_WIDGETS_DATA_REPORT_TBL_CALLS":"Calls","PAGE_WIDGETS_DATA_REPORT_TBL_COST":"Cost","PAGE_WIDGETS_DATA_REPORT_TBL_DESCRIPTION":"Description","PAGE_WIDGETS_DATA_REPORT_TBL_DESTINATION":"Destination","PAGE_WIDGETS_DATA_REPORT_TBL_GATEWAY":"Gateway","PAGE_WIDGETS_DATA_REPORT_TBL_MARGIN":"Margin","PAGE_WIDGETS_DATA_REPORT_TBL_MARGIN_IN_PERCENTAGE":"Margin (%)","PAGE_WIDGETS_DATA_REPORT_TBL_MINUTES":"Minutes","PAGE_WIDGETS_DATA_REPORT_TBL_PREFIX":"Prefix","PAGE_WIDGETS_DATA_REPORT_TBL_TRUNK":"Trunk","PAYMENT_MSG_BANK_ACCOUNT_NOT_VERIFIED":"Bank Account not verified.","PAYMENT_MSG_BOTH_MICRODEPOSIT_REQUIRED":"Both MicroDeposit Required.","PAYMENT_MSG_CUSTOMER_PROFILE_CREATED_ON_AUTHORIZE_NET":"Customer profile created on authorize.net","PAYMENT_MSG_CUSTOMER_PROFILE_DELETED_ON_AUTHORIZE_NET":"Customer profile deleted on authorize.net","PAYMENT_MSG_ENTER_VALID_CARD_NUMBER":"Please enter valid card number","PAYMENT_MSG_MONTH_MUST_BE_AFTER":"Month must be after ","PAYMENT_MSG_NOT_DELETE_DEFAULT_PROFILE":"You can not delete default profile. Please set as default an other profile first.","PAYMENT_MSG_NO_ACCOUNT_COUNTRY_AVAILABLE":"No account country available","PAYMENT_MSG_NO_ACCOUNT_CURRENCY_AVAILABLE":"No account currency available","PAYMENT_MSG_PAYMENT_METHOD_PROFILE_DELETED":"Payment Method Profile Successfully deleted. Profile deleted too.","PAYMENT_MSG_PAYMENT_METHOD_PROFILE_DELETED_AUTHORIZE_NET":"Payment Method Profile Successfully deleted","PAYMENT_MSG_PAYMENT_METHOD_PROFILE_SUCCESSFULLY_CREATED":"Payment Method Profile Successfully Created","PAYMENT_MSG_PAYMENT_PROFILE_CREATED_ON_AUTHORIZE_NET":"Payment profile created on authorize.net","PAYMENT_MSG_PAYMENT_PROFILE_DELETED_ON_AUTHORIZE_NET":"Payment profile deleted on authorize.net","PAYMENT_MSG_PROBLEM_CREATING_IN_VERIFY":"Problem creating in verify","PAYMENT_MSG_PROBLEM_CREATING_PAYMENT_METHOD_PROFILE":"Problem creating Payment Method Profile","PAYMENT_MSG_PROBLEM_DELETING_PAYMENT_METHOD_PROFILE":"Problem deleting Payment Method Profile.","PAYMENT_MSG_PROBLEM_SAVING_PAYMENT_METHOD_PROFILE":"Problem Saving Payment Method Profile.","PAYMENT_MSG_SHIPPING_ADDRESS_CREATED_ON_AUTHORIZE_NET":"Shipping Address created on authorize.net","PAYMENT_MSG_SHIPPING_ADDRESS_DELETED_ON_AUTHORIZE_NET":"Shipping Address deleted on authorize.net","PAYMENT_MSG_SHIPPING_ADDRESS_UPDATED_ON_AUTHORIZE_NET":"Shipping Address updated on authorize.net","PAYMENT_STRIPEACH_MSG_VERIFICATION_STATUS_IS":"verification status is ","PLACEHOLDER_EMAIL":"Email","PLACEHOLDER_PASSWORD":"Password","TABLE_COLUMN_ACTION":"Action","TABLE_LBL_FILTERED_FROM_MAX_TOTAL_RECORD":"(filtered from _MAX_ total records)","TABLE_LBL_RECORDS_PER_PAGE":"_MENU_ records per page","TABLE_LBL_SEARCH":"Search:","TABLE_LBL_SHOWING_EMPTY_RECORDS":"Showing 0 to 0 of 0 records","TABLE_LBL_SHOWING_RECORDS":"Showing _START_ to _END_ of _TOTAL_ records","TABLE_TOTAL":"TOTAL","THEMES_BHAVIN1NEON_SOFTCOM_FOOTERTEXT":"\\u00a9 2018 Reseller Code Desk","THEMES_BHAVIN1NEON_SOFTCOM_LOGIN_MSG":"Reseller Login","THEMES_BHAVIN1NEON_SOFTCOM_TITLE":"Reseller","THEMES_BHAVIN2NEON_SOFTCOM_FOOTERTEXT":"\\u00a9 2018 Xyz Reseller Code Desk","THEMES_BHAVIN2NEON_SOFTCOM_LOGIN_MSG":"Xyz Reseller Login","THEMES_BHAVIN2NEON_SOFTCOM_TITLE":"Xyz Reseller","THEMES_STAGINGNEON_SOFTCOM_FOOTERTEXT":"\\u00a9 2018 Staging Code Desk","THEMES_STAGINGNEON_SOFTCOM_LOGIN_MSG":"Welcome to the Flexible VoIP Customer Portal <br> By using this website you agree to our Terms and Conditions at http:\\/\\/www.flexiblevoip.com\\/terms.html. ","THEMES_STAGINGNEON_SOFTCOM_TITLE":"Staging"}', '2017-11-09 16:06:40', NULL, '2018-04-27 09:33:58', NULL);


INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1331, 'AccountSubscription.Add', 1, 3);
INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1330, 'AccountSubscription.Edit', 1, 3);
INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1329, 'AccountSubscription.Delete', 1, 3);
INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1328, 'AccountSubscription.View', 1, 3);
INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1327, 'AccountSubscription.All', 1, 3);

INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.*', 'AccountSubscriptionController.*', 1, 'Sumera Khan', NULL, '2017-05-30 09:53:27.000', '2017-05-30 09:53:27.000', 1327);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.ajax_datagrid', 'AccountSubscriptionController.ajax_datagrid', 1, 'Sumera Saeed', NULL, '2015-11-28 09:37:35.000', '2015-11-28 09:37:35.000', 1328);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.ajax_datagrid', 'AccountSubscriptionController.ajax_datagrid', 1, 'Sumera Saeed', NULL, '2015-11-28 09:37:35.000', '2015-11-28 09:37:35.000', 1328);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.ajax_datagrid_page', 'AccountSubscriptionController.ajax_datagrid_page', 1, 'Sumera Khan', NULL, '2017-05-30 09:53:27.000', '2017-05-30 09:53:27.000', 1328);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.delete', 'AccountSubscriptionController.delete', 1, 'Sumera Saeed', NULL, '2015-11-28 09:37:35.000', '2015-11-28 09:37:35.000', 1329);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.delete', 'AccountSubscriptionController.delete', 1, 'Sumera Saeed', NULL, '2015-11-28 09:37:35.000', '2015-11-28 09:37:35.000', 1329);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.GetAccountSubscriptions', 'AccountSubscriptionController.GetAccountSubscriptions', 1, 'Sumera Khan', NULL, '2017-05-30 09:53:27.000', '2017-05-30 09:53:27.000', 1328);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.main', 'AccountSubscriptionController.main', 1, 'Sumera Khan', NULL, '2017-05-30 09:53:27.000', '2017-05-30 09:53:27.000', 1328);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.store', 'AccountSubscriptionController.store', 1, 'Sumera Saeed', NULL, '2015-11-28 09:37:35.000', '2015-11-28 09:37:35.000', 1331);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.store', 'AccountSubscriptionController.store', 1, 'Sumera Saeed', NULL, '2015-11-28 09:37:35.000', '2015-11-28 09:37:35.000', 1331);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.update', 'AccountSubscriptionController.update', 1, 'Sumera Saeed', NULL, '2015-11-28 09:37:35.000', '2015-11-28 09:37:35.000', 1330);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ('AccountSubscription.update', 'AccountSubscriptionController.update', 1, 'Sumera Saeed', NULL, '2015-11-28 09:37:35.000', '2015-11-28 09:37:35.000', 1330);

INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1334, 'AutoImport.All', 1, 5);
INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1335, 'AutoImport.View', 1, 5);
INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1336, 'AutoRateImport.All', 1, 5);
INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1337, 'AutoRateImport.View', 1, 5);
INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1338, 'AutoRateImport.Add', 1, 5);
INSERT INTO `tblResourceCategories` (`ResourceCategoryID`, `ResourceCategoryName`, `CompanyID`, `CategoryGroupID`) VALUES (1339, 'AutoRateImport.Delete', 1, 5);

INSERT INTO `tblResource` ( `ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoImport.*', 'AutoImportController.*', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1334);
INSERT INTO `tblResource` ( `ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoImport.index', 'AutoImportController.index', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1335);
INSERT INTO `tblResource` ( `ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoImport.GetemailReadById', 'AutoImportController.GetemailReadById', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1335);
INSERT INTO `tblResource` ( `ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoImport.ajax_datagrid', 'AutoImportController.ajax_datagrid', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1335);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoRateImport.*', 'AutoRateImportController.*', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1336);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoRateImport.ratetableSetting', 'AutoRateImportController.ratetableSetting', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1337);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoRateImport.index', 'AutoRateImportController.index', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1337);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoRateImport.ajax_datagrid', 'AutoRateImportController.ajax_datagrid', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1337);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoRateImport.accountSetting', 'AutoRateImportController.accountSetting', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1337);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoRateImport.inboxSettingStoreAndUpdate', 'AutoRateImportController.inboxSettingStoreAndUpdate', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1338);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoRateImport.accountSettingStore', 'AutoRateImportController.accountSettingStore', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1338);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoRateImport.RateTableSettingStore', 'AutoRateImportController.RateTableSettingStore', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1338);
INSERT INTO `tblResource` (`ResourceName`, `ResourceValue`, `CompanyID`, `CreatedBy`, `ModifiedBy`, `created_at`, `updated_at`, `CategoryID`) VALUES ( 'AutoRateImport.Delete', 'AutoRateImportController.Delete', 1, 'vishal jagani', NULL, '2018-04-25 14:51:44.000', '2018-04-25 14:51:44.000', 1339);

DROP PROCEDURE IF EXISTS `prc_applyRateTableTomultipleAccByService`;
DELIMITER //
CREATE PROCEDURE `prc_applyRateTableTomultipleAccByService`(
	IN `p_companyid` INT,
	IN `p_AccountIds` TEXT,
	IN `p_InboundRateTable` INT,
	IN `p_OutboundRateTable` INT,
	IN `p_CreatedBy` VARCHAR(100),
	IN `p_InBoundRateTableChecked` VARCHAR(5),
	IN `p_OutBoundRateTableChecked` VARCHAR(5),
	IN `p_checkedAll` VARCHAR(1),
	IN `p_select_serviceId` INT,
	IN `p_select_currency` INT,
	IN `p_select_ratetableid` INT,
	IN `p_select_accounts` TEXT
)
BEGIN

		SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
		
		DROP TEMPORARY TABLE IF EXISTS tmp_service_check;
				CREATE TEMPORARY TABLE tmp_service_check (
					ServiceID INT ,
					AccountID INT,
					CompanyID INT
				);
		
		
		DROP TEMPORARY TABLE IF EXISTS tmp_service;
				CREATE TEMPORARY TABLE tmp_service (
					ServiceID INT ,
					AccountID INT,
					CompanyID INT
				);
		
		DROP TEMPORARY TABLE IF EXISTS tmp_service_already;
				CREATE TEMPORARY TABLE tmp_service_already (
					CompanyID INT ,
					AccountID INT,
					ServiceID INT ,
					RateTableID INT,
					InRateTableName VARCHAR(100),
					Type INT
				);
		
		DROP TEMPORARY TABLE IF EXISTS tmp_tarrif;
				CREATE TEMPORARY TABLE tmp_tarrif (
					CompanyID INT ,
					AccountID INT,
					ServiceID INT ,
					RateTableID INT,
					InRateTableName VARCHAR(100),
					Type INT
				);
				

			IF (p_checkedAll = 'N') 
			THEN 
						
						/* Update As per selected acconut */
						
								
						DROP TEMPORARY TABLE IF EXISTS temp_acc_trunk;
							CREATE TEMPORARY TABLE temp_acc_trunk (
								Account_Service text,
								AccountID INT,
								ServiceID INT
						);
						DROP TEMPORARY TABLE IF EXISTS tmp_seprateAccountandService;
							CREATE TEMPORARY TABLE tmp_seprateAccountandService (
								Account_Service text,
								AccountID INT,
								ServiceID INT
						);
						
						/* Insert all comma seprate account with trunk in Account_Trunk field from Parameter "p_AccountIds" like 
						( Account_Trunk  AccountID   TrunkID
						  5009_7           NULL      NULL
						  5009_3           NULL      NULL
						  5009_5           NULL      NULL
						) */							
						set @sql = concat("insert into temp_acc_trunk (Account_Service) values ('", replace(( select distinct p_AccountIds as data), ",", "'),('"),"');");
						prepare stmt1 from @sql;
						execute stmt1;	
						
						
		
						/* Spit(_) Account with trunk field in AccountID and TrunkID like and insert into table (tmp_seprateAccountandTrunk)
							Account_Trunk  AccountID   TrunkID
						   5009_7           5009      7
						   5009_3           5009      3
						   5009_5           5009      5
						*/							
						insert into tmp_seprateAccountandService (Account_Service,AccountID,ServiceID)
						SELECT   Account_Service , SUBSTRING_INDEX(Account_Service,'_',1) AS AccountID , SUBSTRING_INDEX(Account_Service,'_',-1) AS ServiceID FROM temp_acc_trunk;
						
						-- select * from tmp_seprateAccountandService;
						
						
						insert into tmp_service_already (ServiceID,AccountID,CompanyID)  						                     
						select 
						ServiceID,
						AccountID,
						p_companyid as CompanyID
						from tmp_seprateAccountandService sep_acc ;
						
						-- select * from tmp_service_already;
						
						
						
						 if(p_InBoundRateTableChecked = 'on') THEN
								
								/* Insert OR Update RateTable Inbound Ratetable */
								
							   update tblAccountTariff t
								inner join tmp_service_already act on t.CompanyID=act.CompanyID AND t.ServiceID=act.ServiceID AND t.AccountID=act.AccountID
								set t.RateTableID=p_InboundRateTable,t.updated_at=NOW()
								where t.`Type`=2 AND t.ServiceID=act.ServiceID; 
								
								               		
								insert into tmp_tarrif (CompanyID,AccountID,ServiceID,RateTableID,Type)
								select distinct
								p_companyid as CompanyID,
								t.AccountID as AccountID,
								t.ServiceID as ServiceID,
								p_InboundRateTable as RateTableID,
								2 as Type
								from tmp_service_already t 
								left join tblAccountTariff on t.AccountID = tblAccountTariff.AccountID  AND tblAccountTariff.ServiceID=t.ServiceID
								where tblAccountTariff.AccountTariffID is null ;
								
								
								insert into tblAccountTariff (CompanyID,AccountID,ServiceID,RateTableID,Type,created_at)
								select distinct
								p_companyid as CompanyID,
								AccountID as AccountID,
								ServiceID,
								p_InboundRateTable as RateTableID,
								2 as Type,
								NOW() as created_at
								from tmp_tarrif;
							
							
						 END IF;
		
		
						 if(p_OutBoundRateTableChecked = 'on') THEN
						
								/* Insert OR Update RateTable OutBound Ratetable */
							
								update tblAccountTariff t
								inner join tmp_service_already act on t.CompanyID=act.CompanyID AND t.ServiceID=act.ServiceID AND t.AccountID=act.AccountID
								set t.RateTableID=p_OutboundRateTable,t.updated_at=NOW()
								where t.`Type`=1 AND t.ServiceID=act.ServiceID;
								
						
									
								
								insert into tmp_tarrif (CompanyID,AccountID,ServiceID,RateTableID,Type)
								select distinct
								p_companyid as CompanyID,
								t.AccountID as AccountID,
								t.ServiceID as ServiceID,
								p_OutboundRateTable as RateTableID,
								1 as Type
								from tmp_service_already t 
								left join tblAccountTariff on t.AccountID = tblAccountTariff.AccountID  AND tblAccountTariff.ServiceID=t.ServiceID AND tblAccountTariff.`Type`=1
								where tblAccountTariff.AccountTariffID is null ;
								
								select * from tmp_tarrif;
								
								insert into tblAccountTariff (CompanyID,AccountID,ServiceID,RateTableID,Type,created_at)
								select distinct
								p_companyid as CompanyID,
								AccountID as AccountID,
								ServiceID,
								p_OutboundRateTable as RateTableID,
								1 as Type,
								NOW() as created_at
								from tmp_tarrif;
							
							
						 END IF; 
						
						
						
						
			ELSE
			
			
			
			
				
					/* Upload or insert All Accounts as per filter like selectall( All pages ) */
						
					DROP TEMPORARY TABLE IF EXISTS tmp_allaccountByfilter;
							CREATE TEMPORARY TABLE tmp_allaccountByfilter (
								AccountID INT,
								ServiceID INT
						);
						
					 insert into tmp_allaccountByfilter (AccountID,ServiceID)						
							select distinct a.AccountID as AccountID,s.ServiceID as ServiceID
							from  tblAccount a 
							left join tblAccountService ass  on a.AccountID=ass.AccountID
							left join tblService s on ass.ServiceID=s.ServiceID				
							left join tblAccountTariff att on a.AccountID = att.AccountID AND s.ServiceID = att.ServiceID 								
							where 
							CASE 
								  WHEN (p_select_serviceId > 0 AND p_select_ratetableid > 0) THEN				
							
										att.RateTableID=p_select_ratetableid AND ass.ServiceID=p_select_serviceId AND a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1
							
								  WHEN (p_select_serviceId > 0) THEN				
										ass.ServiceID=p_select_serviceId AND a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1
										
								  WHEN (p_select_ratetableid > 0) THEN
								      a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1
								  		
							     ELSE
								   	a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1	
							END
							AND  (p_select_accounts='' OR FIND_IN_SET(a.AccountID,p_select_accounts) != 0 ) AND  a.CurrencyId=p_select_currency	;
						
					select * from tmp_allaccountByfilter;
									
						
						
						insert into tmp_service_already (ServiceID,AccountID,CompanyID)  						                     
						select 
						ServiceID,
						AccountID,
						p_companyid as CompanyID
						from tmp_allaccountByfilter sep_acc ;
						
						-- select * from tmp_service_already;
								
						
						
						if(p_InBoundRateTableChecked =  'on') THEN
							
								
							   update tblAccountTariff t
								inner join tmp_service_already act on t.CompanyID=act.CompanyID AND t.ServiceID=act.ServiceID AND t.AccountID=act.AccountID
								set t.RateTableID=p_InboundRateTable,t.updated_at=NOW()
								where t.`Type`=2 AND t.ServiceID=act.ServiceID; 
								
								               		
								insert into tmp_tarrif (CompanyID,AccountID,ServiceID,RateTableID,Type)
								select distinct
								p_companyid as CompanyID,
								t.AccountID as AccountID,
								t.ServiceID as ServiceID,
								p_InboundRateTable as RateTableID,
								2 as Type
								from tmp_service_already t 
								left join tblAccountTariff on t.AccountID = tblAccountTariff.AccountID  AND tblAccountTariff.ServiceID=t.ServiceID
								inner join tmp_allaccountByfilter af on t.AccountID= af.AccountID
								where tblAccountTariff.AccountTariffID is null ;
								
								
								insert into tblAccountTariff (CompanyID,AccountID,ServiceID,RateTableID,Type,created_at)
								select distinct
								p_companyid as CompanyID,
								AccountID as AccountID,
								ServiceID,
								p_InboundRateTable as RateTableID,
								2 as Type,
								NOW() as created_at
								from tmp_tarrif;
							
							
						END IF;
		
		
						if(p_OutBoundRateTableChecked = 'on') THEN
							
								update tblAccountTariff t
								inner join tmp_service_already act on t.CompanyID=act.CompanyID AND t.ServiceID=act.ServiceID AND t.AccountID=act.AccountID
								set t.RateTableID=p_OutboundRateTable,t.updated_at=NOW()
								where t.`Type`=1 AND t.ServiceID=act.ServiceID;
								
						
									
								
								insert into tmp_tarrif (CompanyID,AccountID,ServiceID,RateTableID,Type)
								select distinct
								p_companyid as CompanyID,
								t.AccountID as AccountID,
								t.ServiceID as ServiceID,
								p_OutboundRateTable as RateTableID,
								1 as Type
								from tmp_service_already t 
								left join tblAccountTariff on t.AccountID = tblAccountTariff.AccountID  AND tblAccountTariff.ServiceID=t.ServiceID AND tblAccountTariff.`Type`=1
								inner join tmp_allaccountByfilter af on t.AccountID= af.AccountID
								where tblAccountTariff.AccountTariffID is null ;
								
								select * from tmp_tarrif;
								
								insert into tblAccountTariff (CompanyID,AccountID,ServiceID,RateTableID,Type,created_at)
								select distinct
								p_companyid as CompanyID,
								AccountID as AccountID,
								ServiceID,
								p_OutboundRateTable as RateTableID,
								1 as Type,
								NOW() as created_at
								from tmp_tarrif;
							
							
						 END IF; 
					
					 
					
					
					
					
					
					
					
			END IF;
		
		
                        
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_applyRateTableTomultipleAccByTrunk`;
DELIMITER //
CREATE PROCEDURE `prc_applyRateTableTomultipleAccByTrunk`(
	IN `p_companyid` INT,
	IN `p_AccountIds` TEXT,
	IN `p_ratetableId` INT,
	IN `p_CreatedBy` VARCHAR(100),
	IN `p_checkedAll` VARCHAR(1),
	IN `p_select_trunkId` INT,
	IN `p_select_currency` INT,
	IN `p_select_ratetableid` INT,
	IN `p_select_accounts` TEXT

)
ThisSP:BEGIN

	DECLARE v_codeDeckId int;
	DECLARE v_rowCount_ INT;
	DECLARE v_pointer_ INT;	
	DECLARE v_AccountID_ INT;
	DECLARE v_TrunkID_ INT;
	DECLARE v_RateTableID_ INT;
	DECLARE v_Old_CodeDeckID_ INT;
	DECLARE v_Action_ INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT CodeDeckId INTO v_codeDeckId FROM  tblRateTable WHERE RateTableId = p_ratetableId;

	DROP TEMPORARY TABLE IF EXISTS tmp;
		CREATE TEMPORARY TABLE tmp (
			RowID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
			CustomerTrunkID INT ,
			CompanyID INT ,
			AccountID INT,
			TrunkID INT ,
			RateTableID INT,
			CodeDeckID INT,
			CreatedBy VARCHAR(100)
	);
	
	DROP TEMPORARY TABLE IF EXISTS tmp_insert;
		CREATE TEMPORARY TABLE tmp_insert (
			CompanyID INT ,
			AccountID INT,
			TrunkID INT ,
			RateTableID INT,
			CreatedBy VARCHAR(100)
	);
		
			
         IF ( p_checkedAll = 'Y')  THEN
         
         	
				
					DROP TEMPORARY TABLE IF EXISTS tmp_allaccountByfilter;
						CREATE TEMPORARY TABLE tmp_allaccountByfilter (
							AccountID INT,
							RateTableID INT,
							TrunkID INT 
					);
         
					/* Get All Acount by filter (p_select_trunkId,p_select_currency,p_select_ratetableid,p_select_accounts)  */
				
						insert into tmp_allaccountByfilter (AccountID,RateTableID,TrunkID)					
						select distinct a.AccountID,r.RateTableId,t.TrunkID from tblAccount a
									join tblTrunk t
									left join tblCustomerTrunk ct on a.AccountID=ct.AccountID AND t.TrunkID=ct.TrunkID								
									left join tblRateTable r on ct.RateTableID=r.RateTableId
									where 
									CASE 
										WHEN (p_select_ratetableid > 0 AND p_select_trunkId > 0) THEN
										    r.TrunkID=p_select_trunkId AND r.RateTableId=p_select_ratetableid AND a.CompanyId=p_companyid  
										    
										WHEN (p_select_trunkId > 0) THEN
											 t.TrunkID=p_select_trunkId AND a.CompanyId=p_companyid 
										 
									   WHEN (p_select_ratetableid > 0) THEN
										    r.RateTableId=p_select_ratetableid AND a.CompanyId=p_companyid 
									   ELSE						
											 a.CompanyId=p_companyid				
										
									END
									AND (p_select_accounts='' OR FIND_IN_SET(a.AccountID,p_select_accounts) != 0 )
									AND a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1
									AND a.CurrencyId=p_select_currency AND t.`Status`=1;								
								
					-- select * from tmp_allaccountByfilter;
					
					insert into tmp (CustomerTrunkID,AccountID,TrunkID,RateTableID,CodeDeckID)
					select distinct ct.CustomerTrunkID,a.AccountID,taf.TrunkID,ct.RateTableID,r.CodeDeckId
					from tblAccount a
					join tblTrunk t
					left join tblCustomerTrunk ct on a.AccountID=ct.AccountID AND t.TrunkID=ct.TrunkID								
					left join tblRateTable r on ct.RateTableID=r.RateTableId
					right join tmp_allaccountByfilter taf on a.AccountID=taf.AccountID
					where a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1 AND t.TrunkID=taf.TrunkID;
					
					select * from  tmp;
					 
					select * from  tmp where CustomerTrunkID IS NULL;
					select * from  tmp where CustomerTrunkID IS NOT NULL;
												
			
					
					
			ELSE
			
				
							/* Start the selected Account ratetable apply */
			
			
			
							DROP TEMPORARY TABLE IF EXISTS temp_acc_trunk;
								CREATE TEMPORARY TABLE temp_acc_trunk (
									Account_Trunk text,
									AccountID INT,
									TrunkID INT
							);
							DROP TEMPORARY TABLE IF EXISTS tmp_seprateAccountandTrunk;
								CREATE TEMPORARY TABLE tmp_seprateAccountandTrunk (
									Account_Trunk text,
									AccountID INT,
									TrunkID INT
							);
							
							/* Insert all comma seprate account with trunk in Account_Trunk field from Parameter "p_AccountIds" like 
							( Account_Trunk  AccountID   TrunkID
							  5009_7           NULL      NULL
							  5009_3           NULL      NULL
							  5009_5           NULL      NULL
							) */							
							set @sql = concat("insert into temp_acc_trunk (Account_Trunk) values ('", replace(( select distinct p_AccountIds as data), ",", "'),('"),"');");
							prepare stmt1 from @sql;
							execute stmt1;	
							
							
			
							/* Spit(_) Account with trunk field in AccountID and TrunkID like and insert into table (tmp_seprateAccountandTrunk)
								Account_Trunk  AccountID   TrunkID
							   5009_7           5009      7
							   5009_3           5009      3
							   5009_5           5009      5
							*/							
							insert into tmp_seprateAccountandTrunk (Account_Trunk,AccountID,TrunkID)
							SELECT   Account_Trunk , SUBSTRING_INDEX(Account_Trunk,'_',1) AS AccountID , SUBSTRING_INDEX(Account_Trunk,'_',-1) AS TrunkID FROM temp_acc_trunk;
							
							
							insert into tmp (CustomerTrunkID,AccountID,TrunkID,RateTableID,CodeDeckID)
							select distinct ct.CustomerTrunkID,a.AccountID,taf.TrunkID,ct.RateTableID,r.CodeDeckId
							from tblAccount a
							join tblTrunk t
							left join tblCustomerTrunk ct on a.AccountID=ct.AccountID AND t.TrunkID=ct.TrunkID								
							left join tblRateTable r on ct.RateTableID=r.RateTableId
							right join tmp_seprateAccountandTrunk taf on a.AccountID=taf.AccountID
							where a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1 AND t.TrunkID=taf.TrunkID;
							
															
				
							
			END IF;
			

			-- archive rate table rate by vasim seta starts -- V-4.17
			SET v_pointer_ = 1;
			SET v_rowCount_ = (SELECT COUNT(*) FROM tmp);
			
			WHILE v_pointer_ <= v_rowCount_
			DO
				SELECT AccountID,TrunkID,RateTableID,CodeDeckID INTO v_AccountID_,v_TrunkID_,v_RateTableID_,v_Old_CodeDeckID_ FROM tmp t WHERE t.RowID = v_pointer_;
				
				IF(v_codeDeckId = v_Old_CodeDeckID_)
				THEN
					SET v_Action_ = 2; -- change ratetable - will archive only ratetable rate
				ELSE
					SET v_Action_ = 1; -- change codedeck - will archive both ratetable rate and customer rate
				END IF;
				
				CALL prc_ChangeCodeDeckRateTable(v_AccountID_,v_TrunkID_,v_RateTableID_,p_CreatedBy, v_Action_);
				
				SET v_pointer_ = v_pointer_ + 1;
			END WHILE;			
			-- archive rate table rate by vasim seta ends -- V-4.17
			
			
			/*DELETE ct FROM tblCustomerRate ct
			inner join tmp on ct.TrunkID = tmp.TrunkID AND ct.CustomerID=tmp.AccountID;*/
			
		
			
			insert into tblCustomerTrunk (AccountID,RateTableID,CodeDeckId,CompanyID,TrunkID,IncludePrefix,RoutinePlanStatus,UseInBilling,Status,CreatedBy)
			select 
			sep_acc.AccountID,
			p_ratetableId as RateTableID,
			v_codeDeckId as CodeDeckId,
			p_companyid as CompanyID,
			sep_acc.TrunkID as TrunkID,
			0 as IncludePrefix,
			0 as RoutinePlanStatus,
			0 as UseInBilling,
			1 as Status,			
			p_CreatedBy as CreatedBy
			from tmp sep_acc
			left join tblCustomerTrunk ct on sep_acc.TrunkID = ct.TrunkID AND sep_acc.AccountID = ct.AccountID
			where sep_acc.CustomerTrunkID IS NULL;
			
			
			
			update tblCustomerTrunk 
			right join tmp sep_tmp on tblCustomerTrunk.AccountID=sep_tmp.AccountID AND tblCustomerTrunk.TrunkID=sep_tmp.TrunkID
			set tblCustomerTrunk.RateTableID=p_ratetableId,tblCustomerTrunk.CodeDeckId=v_codeDeckId,tblCustomerTrunk.`Status`=1, ModifiedBy=p_CreatedBy
			where  tblCustomerTrunk.CustomerTrunkID IS NOT NULL;	
								
		  
		    

						

SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_ArchiveOldCustomerRate`;
DELIMITER //
CREATE PROCEDURE `prc_ArchiveOldCustomerRate`(
	IN `p_AccountIds` LONGTEXT,
	IN `p_TrunkIds` LONGTEXT,
	IN `p_DeletedBy` VARCHAR(50)
)
BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	/* SET EndDate of current time to older rates */
	-- for example there are 3 rates, today's date is 2018-04-11
	-- 1. Code 	Rate 	EffectiveDate
	-- 1. 91 	0.1 	2018-04-09
	-- 2. 91 	0.2 	2018-04-10
	-- 3. 91 	0.3 	2018-04-11
	/* Then it will delete 2018-04-09 and 2018-04-10 date's rate */
	UPDATE
		tblCustomerRate cr
	INNER JOIN tblCustomerRate cr2
		ON cr2.CustomerID = cr.CustomerID
		AND cr2.TrunkID = cr.TrunkID
		AND cr2.RateID = cr.RateID
	SET
		cr.EndDate=NOW()
	WHERE
		FIND_IN_SET(cr.CustomerID,p_AccountIds) != 0 AND FIND_IN_SET(cr.TrunkID,p_TrunkIds) != 0 AND cr.EffectiveDate <= NOW() AND
		FIND_IN_SET(cr2.CustomerID,p_AccountIds) != 0 AND FIND_IN_SET(cr2.TrunkID,p_TrunkIds) != 0 AND cr2.EffectiveDate <= NOW() AND
		cr.EffectiveDate < cr2.EffectiveDate;


	/*1. Move Rates which EndDate <= now() */

	INSERT INTO tblCustomerRateArchive
	SELECT DISTINCT  null , -- Primary Key column
		`CustomerRateID`,
		`CustomerID`,
		`TrunkID`,
		`RateId`,
		`Rate`,
		`EffectiveDate`,
		IFNULL(`EndDate`,date(now())) as EndDate,
		now() as `created_at`,
		p_DeletedBy AS `created_by`,
		`LastModifiedDate`,
		`LastModifiedBy`,
		`Interval1`,
		`IntervalN`,
		`ConnectionFee`,
		`RoutinePlan`,
		concat('Ends Today rates @ ' , now() ) as `Notes`
	FROM
		tblCustomerRate
	WHERE
		FIND_IN_SET(CustomerID,p_AccountIds) != 0 AND FIND_IN_SET(TrunkID,p_TrunkIds) != 0 AND EndDate <= NOW();


	DELETE  cr
	FROM tblCustomerRate cr
	inner join tblCustomerRateArchive cra
	on cr.CustomerRateID = cra.CustomerRateID
	WHERE  FIND_IN_SET(cr.CustomerID,p_AccountIds) != 0 AND FIND_IN_SET(cr.TrunkID,p_TrunkIds) != 0;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_ArchiveOldRateTableRate`;
DELIMITER //
CREATE PROCEDURE `prc_ArchiveOldRateTableRate`(
	IN `p_RateTableIds` longtext,
	IN `p_DeletedBy` TEXT
)
BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	/* SET EndDate of current time to older rates */
	-- for example there are 3 rates, today's date is 2018-04-11
	-- 1. Code 	Rate 	EffectiveDate
	-- 1. 91 	0.1 	2018-04-09
	-- 2. 91 	0.2 	2018-04-10
	-- 3. 91 	0.3 	2018-04-11
	/* Then it will delete 2018-04-09 and 2018-04-10 date's rate */
	UPDATE
		tblRateTableRate rtr
	INNER JOIN tblRateTableRate rtr2
		ON rtr2.RateTableId = rtr.RateTableId
		AND rtr2.RateID = rtr.RateID
	SET
		rtr.EndDate=NOW()
	WHERE
		FIND_IN_SET(rtr.RateTableId,p_RateTableIds) != 0 AND rtr.EffectiveDate <= NOW() AND
		FIND_IN_SET(rtr2.RateTableId,p_RateTableIds) != 0 AND rtr2.EffectiveDate <= NOW() AND
		rtr.EffectiveDate < rtr2.EffectiveDate AND rtr.RateTableRateID != rtr2.RateTableRateID;

	/*1. Move Rates which EndDate <= now() */

	INSERT INTO tblRateTableRateArchive
	SELECT DISTINCT  null , -- Primary Key column
		`RateTableRateID`,
		`RateTableId`,
		`RateId`,
		`Rate`,
		`EffectiveDate`,
		IFNULL(`EndDate`,date(now())) as EndDate,
		`updated_at`,
		now() as `created_at`,
		p_DeletedBy AS `created_by`,
		`ModifiedBy`,
		`Interval1`,
		`IntervalN`,
		`ConnectionFee`,
		concat('Ends Today rates @ ' , now() ) as `Notes`
	FROM tblRateTableRate
	WHERE  FIND_IN_SET(RateTableId,p_RateTableIds) != 0 AND EndDate <= NOW();

	/*
	IF (FOUND_ROWS() > 0) THEN
	select concat(FOUND_ROWS() ," Ends Today rates" ) ;
	END IF;
	*/

	DELETE  vr
	FROM tblRateTableRate vr
	inner join tblRateTableRateArchive vra
		on vr.RateTableRateID = vra.RateTableRateID
	WHERE  FIND_IN_SET(vr.RateTableId,p_RateTableIds) != 0;

	/*  IF (FOUND_ROWS() > 0) THEN
	select concat(FOUND_ROWS() ," sane rate " ) ;
	END IF;
	*/

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_ChangeCodeDeckRateTable`;
DELIMITER //
CREATE PROCEDURE `prc_ChangeCodeDeckRateTable`(
	IN `p_AccountID` INT,
	IN `p_TrunkID` INT,
	IN `p_RateTableID` INT,
	IN `p_DeletedBy` VARCHAR(50),
	IN `p_Action` INT
)
ThisSP:BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	-- p_Action = 1 = change codedeck = when change codedeck then archive both customer and ratetable rates
	-- p_Action = 2 = change ratetable = when change ratetable then archive only ratetable rates

	IF p_Action = 1
	THEN
		-- set ratetableid = 0, no rate table assign to trunk
		UPDATE
			tblCustomerTrunk
		SET
			RateTableID = 0
		WHERE
			AccountID = p_AccountID AND TrunkID = p_TrunkID;

		-- archive all customer rate against this account and trunk
		UPDATE
			tblCustomerRate
		SET
			EndDate = DATE(NOW())
		WHERE
			CustomerID = p_AccountID AND TrunkID = p_TrunkID;

		-- archive Customer Rates
		call prc_ArchiveOldCustomerRate (p_AccountID,p_TrunkID,p_DeletedBy);
	END IF;

	-- archive RateTable Rates
	INSERT INTO tblCustomerRateArchive
	(
		`AccountId`,
		`TrunkID`,
		`RateId`,
		`Rate`,
		`EffectiveDate`,
		`EndDate`,
		`created_at`,
		`created_by`,
		`updated_at`,
		`updated_by`,
		`Interval1`,
		`IntervalN`,
		`ConnectionFee`,
		`Notes`
	)
	SELECT
		p_AccountID AS `AccountId`,
		p_TrunkID AS `TrunkID`,
		`RateID`,
		`Rate`,
		`EffectiveDate`,
		DATE(NOW()) AS `EndDate`,
		DATE(NOW()) AS `created_at`,
		p_DeletedBy AS `created_by`,
		`updated_at`,
		`ModifiedBy`,
		`Interval1`,
		`IntervalN`,
		`ConnectionFee`,
		concat('Ends Today rates @ ' , now() ) as `Notes`
	FROM
		tblRateTableRate
	WHERE
		RateTableID = p_RateTableID;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_checkSippyAutoAccountImportJobInterval`;
DELIMITER //
CREATE PROCEDURE `prc_checkSippyAutoAccountImportJobInterval`(
	IN `p_CompanyID` INT,
	IN `p_CurrentTime` DATETIME

)
BEGIN


	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	-- get after how many minutes next auto account import job to run.
	select value into @Interval from tblCompanyConfiguration where CompanyID = p_CompanyID AND `Key` = 'AUTO_SIPPY_ACCOUNT_IMPORT_INTERVAL';

	IF @Interval  > 0 THEN

		select DATE_ADD(created_at , INTERVAL @Interval MINUTE) into @NextRunTime from
		(
			select created_at from tblJob j
			inner join tblJobType t on j.JobTypeID = t.JobTypeID AND t.Code = 'MGA' -- Missing Gateway Account
			/*where j.CreatedBy = 'System'*/
			order by created_at desc limit 1
		) tmp	;

		IF @NextRunTime is not null AND @NextRunTime <= p_CurrentTime THEN

			select '1' as result , 'Run' as message;

		ELSE

			select '0' as result , concat( 'Wait till ' , @NextRunTime ) as message;

		END IF ;

	ELSE

		select '0' as result, 'Interval is not set' as message;


	END IF ;


	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;


END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_CloneRateRuleInRateGenerator`;
DELIMITER //
CREATE PROCEDURE `prc_CloneRateRuleInRateGenerator`(
	IN `p_RateRuleID` INT,
	IN `p_CreatedBy` VARCHAR(100)
)
BEGIN
		select max(`Order`) into @max_order from tblRateRule 		where RateGeneratorId  = (		select RateGeneratorId 		from tblRateRule 		where RateRuleID  = p_RateRuleID	limit 1) ;

		insert into tblRateRule
		(	RateGeneratorId,	Code,	Description, `Order`,	created_at,	CreatedBy)
		select
				RateGeneratorId,	Code,	Description, (@max_order+1) , 	now(),	p_CreatedBy
		from tblRateRule
		where RateRuleID  = p_RateRuleID;

		select LAST_INSERT_ID() into @NewRateRuleID;

		insert into tblRateRuleSource
		(	RateRuleId,AccountId,created_at,CreatedBy )
		select
				@NewRateRuleID,AccountId,	now(), p_CreatedBy
		from tblRateRuleSource
		where RateRuleID  = p_RateRuleID;

		insert into tblRateRuleMargin
		(	RateRuleId,MinRate,MaxRate,AddMargin,FixedValue,created_at,CreatedBy )
		select
				@NewRateRuleID,MinRate,MaxRate,AddMargin,FixedValue,now(),p_CreatedBy
		from tblRateRuleMargin
		where RateRuleID  = p_RateRuleID;

		select @NewRateRuleID as RateRuleID;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_copyResellerData`;
DELIMITER //
CREATE PROCEDURE `prc_copyResellerData`(
	IN `p_companyid` INT,
	IN `p_resellerids` TEXT,
	IN `p_is_product` INT,
	IN `p_product` TEXT,
	IN `p_is_subscription` INT,
	IN `p_subscription` TEXT,
	IN `p_is_trunk` INT,
	IN `p_trunk` TEXT
)
BEGIN
	DECLARE v_resellerId_ INT; 
	DECLARE v_pointer_ INT ;
	DECLARE v_rowCount_ INT ; 	
	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		
		GET DIAGNOSTICS CONDITION 1
		@p2 = MESSAGE_TEXT;
	
		SELECT @p2 as Message;
		
	END;		

	SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
	
		DROP TEMPORARY TABLE IF EXISTS tmp_currency;
		CREATE TEMPORARY TABLE tmp_currency (
			`ResellerCompanyID` INT,
			`CompanyId` INT,
			`Code` VARCHAR(50),
			`CurrencyID` INT,
			`NewCurrencyID` INT
		) ENGINE=InnoDB;	
				
		DROP TEMPORARY TABLE IF EXISTS tmp_product;
		CREATE TEMPORARY TABLE tmp_product (
			`ResellerCompanyID` INT,
			`CompanyId` INT,
			`Name` VARCHAR(50),
			`Code` VARCHAR(50),
			`Description` LONGTEXT,
			`Amount` DECIMAL(18,2),
			`Active` TINYINT(3) UNSIGNED,
			`Note` LONGTEXT,
			INDEX tmp_product_ResellerCompanyID (`ResellerCompanyID`),
			INDEX tmp_product_Code (`Code`)
	  	);			
				
		DROP TEMPORARY TABLE IF EXISTS tmp_BillingSubscription;
		CREATE TEMPORARY TABLE tmp_BillingSubscription (
				`ResellerCompanyID` INT,
				`CompanyID` INT(11),
				`Name` VARCHAR(50),
				`Description` LONGTEXT,
				`InvoiceLineDescription` VARCHAR(250),
				`ActivationFee` DECIMAL(18,2),						
				`CurrencyID` INT(11),
				`AnnuallyFee` DECIMAL(18,2),
				`QuarterlyFee` DECIMAL(18,2),
				`MonthlyFee` DECIMAL(18,2),
				`WeeklyFee` DECIMAL(18,2),
				`DailyFee` DECIMAL(18,2),
				`Advance` TINYINT(3) UNSIGNED,
				INDEX tmp_BillingSubscription_ResellerCompanyID (`ResellerCompanyID`),
				INDEX tmp_BillingSubscription_Name (`Name`)
		);	

		DROP TEMPORARY TABLE IF EXISTS tmp_Trunk;
		CREATE TEMPORARY TABLE tmp_Trunk (
				`ResellerCompanyID` INT,
				`Trunk` VARCHAR(50),
				`CompanyId` INT(11),
				`RatePrefix` VARCHAR(50),
				`AreaPrefix` VARCHAR(50),
				`Prefix` VARCHAR(50),
				`Status` TINYINT(1),
				INDEX tmp_Trunk_ResellerCompanyID (`ResellerCompanyID`),
				INDEX tmp_Trunk_TrunkName (`Trunk`)
			);	
			
			
		DROP TEMPORARY TABLE IF EXISTS tmp_resellers;
		CREATE TEMPORARY TABLE tmp_resellers (
			`CompanyID` INT,
			`ResellerID` INT,
			`ResellerCompanyID` INT,
			`AccountID` INT,
			`RowNo` INT,
			INDEX tmp_resellers_ResellerID (`ResellerID`),
			INDEX tmp_resellers_ResellerCompanyID (`ResellerCompanyID`),
			INDEX tmp_resellers_RowNo (`RowNo`)
		);			
				
				INSERT INTO tmp_resellers
				SELECT
					CompanyID,
					ResellerID,
					ChildCompanyID as ResellerCompanyID,
					AccountID,
					@row_num := @row_num+1 AS RowID
				FROM tblReseller,(SELECT @row_num := 0) x
				WHERE CompanyID = p_companyid
					  AND FIND_IN_SET(ResellerID,p_resellerids);
				
					
		SET v_pointer_ = 1;
		SET v_rowCount_ = (SELECT COUNT(distinct ResellerCompanyID ) FROM tmp_resellers);
					
		WHILE v_pointer_ <= v_rowCount_
		DO
					
					SET v_resellerId_ = (SELECT ResellerCompanyID FROM tmp_resellers rr WHERE rr.RowNo = v_pointer_);			
					
							/*
							INSERT INTO	tmp_currency(ResellerCompanyID,CompanyId,Code,CurrencyID)	
							SELECT v_resellerId_ as ResellerCompanyID,p_companyid as CompanyId,Code, CurrencyId FROM `tblCurrency` WHERE CompanyId	= p_companyid;	
							
							UPDATE tmp_currency tc LEFT JOIN tblCurrency c ON tc.Code=c.Code AND tc.ResellerCompanyID = v_resellerId_ AND c.CompanyId = v_resellerId_
									set NewCurrencyID = c.CurrencyId
							WHERE c.CurrencyId IS NOT NULL;		*/
					
					IF p_is_product =1
					THEN	
					
						INSERT INTO tmp_product(ResellerCompanyID,CompanyId,Name,Code,Description,Amount,Active,Note)
						SELECT DISTINCT v_resellerId_ as ResellerCompanyID,p_companyid as `CompanyId`,Name,Code,Description,Amount,Active,Note
							FROM RMBilling3.tblProduct
						WHERE CompanyId = p_companyid AND FIND_IN_SET(ProductID,p_product);
					
					END IF;
					
					IF p_is_subscription = 1
					THEN
					
						INSERT INTO tmp_BillingSubscription(`ResellerCompanyID`,`CompanyID`,Name,Description,InvoiceLineDescription,ActivationFee,CurrencyID,AnnuallyFee,QuarterlyFee,MonthlyFee,WeeklyFee,DailyFee,Advance)
						SELECT DISTINCT v_resellerId_ as ResellerCompanyID, `CompanyID`,Name,Description,InvoiceLineDescription,ActivationFee,CurrencyID,AnnuallyFee,QuarterlyFee,MonthlyFee,WeeklyFee,DailyFee,Advance
						FROM RMBilling3.tblBillingSubscription
						WHERE CompanyID = p_companyid AND FIND_IN_SET(SubscriptionID,p_subscription);
					
					END IF;
					
					/*
					IF p_is_trunk = 1
					THEN
					
					INSERT INTO tmp_Trunk(ResellerCompanyID,Trunk,CompanyId,RatePrefix,AreaPrefix,`Prefix`,Status)
							SELECT DISTINCT v_resellerId_ as ResellerCompanyID,Trunk,CompanyId,RatePrefix,AreaPrefix,`Prefix`,Status
								FROM tblTrunk
							WHERE CompanyId = p_companyid AND FIND_IN_SET(TrunkID,p_trunk);
							
					END IF;		*/
					
					 SET v_pointer_ = v_pointer_ + 1;			 
			
		END WHILE;
			
		
		IF p_is_product =1
		THEN	
					INSERT INTO RMBilling3.tblProduct (CompanyId,Name,Code,Description,Amount,Active,Note,CreatedBy,ModifiedBy,created_at,updated_at)
					SELECT DISTINCT tp.ResellerCompanyID as `CompanyId`,tp.Name,tp.Code,tp.Description,tp.Amount,tp.Active,tp.Note,'system' as CreatedBy,'system' as ModifiedBy,NOW(),NOW()
						FROM tmp_product tp 
							LEFT JOIN RMBilling3.tblProduct p
							ON tp.ResellerCompanyID = p.CompanyId
							AND tp.Code=p.Code
					WHERE p.ProductID IS NULL;		
		
		END IF;
		

		
		IF p_is_subscription = 1
		THEN
				
				INSERT INTO RMBilling3.tblBillingSubscription(`CompanyID`,Name,Description,InvoiceLineDescription,ActivationFee,CurrencyID,AnnuallyFee,QuarterlyFee,MonthlyFee,WeeklyFee,DailyFee,Advance,created_at,updated_at,ModifiedBy,CreatedBy)
				SELECT DISTINCT tb.ResellerCompanyID as `CompanyID`,tb.Name,tb.Description,tb.InvoiceLineDescription,tb.ActivationFee,CurrencyID,tb.AnnuallyFee,tb.QuarterlyFee,tb.MonthlyFee,tb.WeeklyFee,tb.DailyFee,tb.Advance,Now(),Now(),'system' as ModifiedBy,'system' as CreatedBy 
					FROM tmp_BillingSubscription tb 
						LEFT JOIN RMBilling3.tblBillingSubscription b
						ON tb.ResellerCompanyID = b.CompanyID
						AND tb.Name = b.Name
				WHERE b.SubscriptionID IS NULL;
		
		END IF;
		/*
		IF p_is_trunk =1
		THEN

				INSERT INTO tblTrunk (Trunk,CompanyId,RatePrefix,AreaPrefix,`Prefix`,Status,created_at,updated_at)
				SELECT DISTINCT tt.Trunk, tt.ResellerCompanyID as `CompanyId`,tt.RatePrefix,tt.AreaPrefix,tt.`Prefix`,tt.Status,Now(),Now()
				FROM tmp_Trunk tt
					LEFT JOIN tblTrunk tr ON tt.ResellerCompanyID = tr.CompanyId AND tt.Trunk = tr.Trunk
				WHERE tr.TrunkID IS NULL;
		
		END IF; */
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_CronJobGenerateM2Sheet`;
DELIMITER //
CREATE PROCEDURE `prc_CronJobGenerateM2Sheet`(
	IN `p_CustomerID` INT ,
	IN `p_trunks` VARCHAR(200) ,
	IN `p_Effective` VARCHAR(50),
	IN `p_CustomDate` DATE
)
BEGIN

	-- get customer rates
	CALL vwCustomerRate(p_CustomerID,p_Trunks,p_Effective,p_CustomDate);

		SELECT DISTINCT
	       Description  as `Destination`,
		   Code as `Prefix`,
		   Rate as `Rate(USD)`,
		   ConnectionFee as `Connection Fee(USD)`,
		   Interval1 as `Increment`,
		   IntervalN as `Minimal Time`,
		   '0:00:00 'as `Start Time`,
		   '23:59:59' as `End Time`,
		   '' as `Week Day`,
		   EffectiveDate  as `Effective from`,
			RoutinePlanName as `Routing through`
     FROM tmp_customerrateall_ ;

		SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_CronJobGenerateMorSheet`;
DELIMITER //
CREATE PROCEDURE `prc_CronJobGenerateMorSheet`(
	IN `p_CustomerID` INT ,
	IN `p_trunks` VARCHAR(200) ,
	IN `p_Effective` VARCHAR(50),
	IN `p_CustomDate` DATE
)
BEGIN

	-- get customer rates
	CALL vwCustomerRate(p_CustomerID,p_Trunks,p_Effective,p_CustomDate);

    DROP TEMPORARY TABLE IF EXISTS tmp_morrateall_;
    CREATE TEMPORARY TABLE tmp_morrateall_ (
        RateID INT,
        Country VARCHAR(155),
        CountryCode VARCHAR(50),
        Code VARCHAR(50),
        Description VARCHAR(200),
        Interval1 INT,
        IntervalN INT,
        ConnectionFee DECIMAL(18, 6),
        RoutinePlanName VARCHAR(50),
        Rate DECIMAL(18, 6),
        EffectiveDate DATE,
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        CustomerRateId INT,
        TrunkID INT,
        RateTableRateId INT,
        IncludePrefix TINYINT,
        Prefix VARCHAR(50),
        RatePrefix VARCHAR(50),
        AreaPrefix VARCHAR(50),
        SubCode VARCHAR(50)
    );

    INSERT INTO tmp_morrateall_
     SELECT
		  tc.RateID,
	  	  c.Country,
		  c.ISO3,
		  tc.Code,
		  tc.Description,
		  tc.Interval1,
        tc.IntervalN,
        tc.ConnectionFee,
        tc.RoutinePlanName,
        tc.Rate,
        tc.EffectiveDate,
        tc.LastModifiedDate,
        tc.LastModifiedBy,
        tc.CustomerRateId,
        tc.TrunkID,
        tc.RateTableRateId,
        tc.IncludePrefix,
        tc.Prefix,
        tc.RatePrefix,
        tc.AreaPrefix,
        'FIX' as `SubCode`
	  	 FROM tmp_customerrateall_ tc
	  			 INNER JOIN tblRate r ON tc.RateID = r.RateID
				 LEFT JOIN tblCountry c ON r.CountryID = c.CountryID
					;

	  UPDATE tmp_morrateall_
	  			SET SubCode='MOB'
	  			WHERE Description LIKE '%Mobile%';


		SELECT DISTINCT
	      Country as `Direction` ,
	      Description  as `Destination`,
		   Code as `Prefix`,
		   SubCode as `Subcode`,
		   CountryCode as `Country code`,
		   Rate as `Rate(EUR)`,
		   ConnectionFee as `Connection Fee(EUR)`,
		   Interval1 as `Increment`,
		   IntervalN as `Minimal Time`,
		   '0:00:00 'as `Start Time`,
		   '23:59:59' as `End Time`,
		   '' as `Week Day`
     FROM tmp_morrateall_;

		SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_CustomerBulkRateInsert`;
DELIMITER //
CREATE PROCEDURE `prc_CustomerBulkRateInsert`(
	IN `p_AccountIdList` LONGTEXT ,
	IN `p_TrunkId` INT ,
	IN `p_CodeDeckId` int,
	IN `p_code` VARCHAR(50) ,
	IN `p_description` VARCHAR(200) ,
	IN `p_CountryId` INT ,
	IN `p_CompanyId` INT ,
	IN `p_Rate` DECIMAL(18, 6) ,
	IN `p_ConnectionFee` DECIMAL(18, 6) ,
	IN `p_EffectiveDate` DATETIME ,
	IN `p_EndDate` DATETIME ,
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_RoutinePlan` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
BEGIN

 	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	INSERT  INTO tblCustomerRate
	(
		RateID ,
		CustomerID ,
		TrunkID ,
		Rate ,
		ConnectionFee,
		EffectiveDate ,
		EndDate ,
		Interval1,
		IntervalN ,
		RoutinePlan,
		CreatedDate ,
		LastModifiedBy ,
		LastModifiedDate
	)
	SELECT
		r.RateID ,
		r.AccountId ,
		p_TrunkId ,
		p_Rate ,
		p_ConnectionFee,
		p_EffectiveDate ,
		p_EndDate ,
		p_Interval1,
		p_IntervalN,
		RoutinePlan,
		NOW() ,
		p_ModifiedBy ,
		NOW()
	FROM
	(
		SELECT
			RateID,Code,AccountId,CompanyID,CodeDeckId,Description,CountryID,RoutinePlan
		FROM
			tblRate ,
			(
				SELECT
					a.AccountId,
					CASE WHEN ctr.TrunkID IS NOT NULL
					THEN p_RoutinePlan
					ELSE NULL
					END AS RoutinePlan
				FROM tblAccount a
				INNER JOIN tblCustomerTrunk
					ON TrunkID = p_TrunkId
					AND a.AccountID    = tblCustomerTrunk.AccountID
					AND tblCustomerTrunk.Status = 1
				LEFT JOIN tblCustomerTrunk ctr
					ON ctr.TrunkID = p_TrunkId
					AND ctr.AccountID = a.AccountID
					AND ctr.RoutinePlanStatus = 1
				WHERE
					FIND_IN_SET(a.AccountID,p_AccountIdList) != 0
			) a
	) r
	LEFT OUTER JOIN
	(
		SELECT DISTINCT
			RateID ,
			c.CustomerID as AccountId ,
			c.TrunkID,
			c.EffectiveDate
		FROM
			tblCustomerRate c
		INNER JOIN tblCustomerTrunk
			ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
		WHERE
			FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0 AND c.TrunkID = p_TrunkId
	) cr ON r.RateID = cr.RateID
		AND r.AccountId = cr.AccountId
		AND r.CompanyID = p_CompanyId
		and cr.EffectiveDate = p_EffectiveDate
	WHERE
		r.CompanyID = p_CompanyId
		AND r.CodeDeckId=p_CodeDeckId
		AND ( ( p_code IS NULL ) OR ( p_code IS NOT NULL AND r.Code LIKE REPLACE(p_code,'*', '%')))
		AND ( ( p_description IS NULL ) OR ( p_description IS NOT NULL AND r.Description LIKE REPLACE(p_description,'*', '%')))
		AND ( ( p_CountryId IS NULL )  OR ( p_CountryId IS NOT NULL AND r.CountryID = p_CountryId ) )
		AND cr.RateID IS NULL;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_CustomerBulkRateUpdate`;
DELIMITER //
CREATE PROCEDURE `prc_CustomerBulkRateUpdate`(
	IN `p_AccountIdList` LONGTEXT ,
	IN `p_TrunkId` INT ,
	IN `p_CodeDeckId` int,
	IN `p_code` VARCHAR(50) ,
	IN `p_description` VARCHAR(200) ,
	IN `p_CountryId` INT ,
	IN `p_CompanyId` INT ,
	IN `p_Effective` VARCHAR(50),
	IN `p_CustomDate` DATE,
	IN `p_Rate` DECIMAL(18, 6) ,
	IN `p_ConnectionFee` DECIMAL(18, 6) ,
	IN `p_EffectiveDate` DATETIME ,
	IN `p_EndDate` DATETIME ,
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_RoutinePlan` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
BEGIN

 	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates_;
    CREATE TEMPORARY TABLE tmp_CustomerRates_ (
        CustomerRateID INT,
        RateID INT,
        CustomerID INT,
        Interval1 INT,
        IntervalN  INT,
        Rate DECIMAL(18, 6),
        PreviousRate DECIMAL(18, 6),
        ConnectionFee DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        CreatedDate DATETIME,
        CreatedBy VARCHAR(50),
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        TrunkID INT,
        RoutinePlan INT,
        INDEX tmp_CustomerRates__CustomerRateID (`CustomerRateID`)/*,
        INDEX tmp_CustomerRates__RateID (`RateID`),
        INDEX tmp_CustomerRates__TrunkID (`TrunkID`),
        INDEX tmp_CustomerRates__EffectiveDate (`EffectiveDate`)*/
    );

	-- insert rates in temp table which needs to update (based on grid filter)
	INSERT INTO tmp_CustomerRates_
	(
		CustomerRateID,
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		RoutinePlan
	)
	SELECT
		tblCustomerRate.CustomerRateID,
		tblCustomerRate.RateID,
		tblCustomerRate.CustomerID,
		p_Interval1 AS Interval1,
		p_IntervalN AS IntervalN,
		p_Rate AS Rate,
		tblCustomerRate.PreviousRate,
		p_ConnectionFee AS ConnectionFee,
		tblCustomerRate.EffectiveDate,
		tblCustomerRate.EndDate,
		tblCustomerRate.CreatedDate,
		tblCustomerRate.CreatedBy,
		NOW() AS LastModifiedDate,
		p_ModifiedBy AS LastModifiedBy,
		tblCustomerRate.TrunkID,
		tblCustomerRate.RoutinePlan
	FROM
		tblCustomerRate
	INNER JOIN (
		SELECT c.CustomerRateID,
			c.EffectiveDate,
			CASE WHEN ctr.TrunkID IS NOT NULL
			THEN p_RoutinePlan
			ELSE NULL
			END AS RoutinePlan
		FROM   tblCustomerRate c
		INNER JOIN tblCustomerTrunk
			ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
		INNER JOIN tblRate r
			ON c.RateID = r.RateID and r.CodeDeckId=p_CodeDeckId
		LEFT JOIN tblCustomerTrunk ctr
			ON ctr.TrunkID = c.TrunkID
			AND ctr.AccountID = c.CustomerID
			AND ctr.RoutinePlanStatus = 1
		WHERE  ( ( p_code IS NULL ) OR ( p_code IS NOT NULL AND r.Code LIKE REPLACE(p_code,'*', '%')))
			AND ( ( p_description IS NULL ) OR ( p_description IS NOT NULL AND r.Description LIKE REPLACE(p_description,'*', '%')))
			AND ( ( p_CountryId IS NULL )  OR ( p_CountryId IS NOT NULL AND r.CountryID = p_CountryId ) )
			AND
			(
				( p_Effective = 'Now' AND c.EffectiveDate <= NOW() )
				OR
				( p_Effective = 'Future' AND c.EffectiveDate > NOW() )
				OR
				( p_Effective = 'CustomDate' AND c.EffectiveDate <= p_CustomDate AND (c.EndDate IS NULL OR c.EndDate > p_CustomDate) )
				OR
				p_Effective = 'All'
			)
			AND c.TrunkID = p_TrunkId
			AND FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0
	) cr ON cr.CustomerRateID = tblCustomerRate.CustomerRateID; -- and cr.EffectiveDate = p_EffectiveDate;

	-- if custom date then remove duplicate rates of earlier date
	-- for examle custom date is 2018-05-03 today's date is 2018-05-01 and there are 2 rates available for 1 code
	-- Code	Date
	-- 1204	2018-05-01
	-- 1204	2018-05-03
	-- then it will delete 2018-05-01 from temp table and keeps only 2018-05-03 rate to update
	IF p_Effective = 'CustomDate'
	THEN
		DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates_2_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates_2_ AS (SELECT * FROM tmp_CustomerRates_);

		DELETE
			n1
		FROM
			tmp_CustomerRates_ n1,
			tmp_CustomerRates_2_ n2
		WHERE
			n1.EffectiveDate < n2.EffectiveDate AND
			n1.RateID = n2.RateID AND
			n1.CustomerID = n2.CustomerID AND
			(
				(p_Effective = 'CustomDate' AND n1.EffectiveDate <= p_CustomDate AND n2.EffectiveDate <= p_CustomDate)
				OR
				(p_Effective != 'CustomDate' AND n1.EffectiveDate <= NOW() AND n2.EffectiveDate <= NOW())
			);
	END IF;

	-- update EndDate to Archive rates which needs to update
	UPDATE
		tblCustomerRate cr
	JOIN
		tmp_CustomerRates_ temp ON cr.CustomerRateID=temp.CustomerRateID
	SET
		cr.EndDate = NOW();

	-- archive rates which rates' EndDate < NOW()
	CALL prc_ArchiveOldCustomerRate(p_AccountIdList, p_TrunkId, p_ModifiedBy);

	-- insert rates in tblCustomerRate with updated values
	INSERT INTO tblCustomerRate
	(
		CustomerRateID,
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		RoutinePlan
	)
	SELECT
		NULL, -- primary key
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		RoutinePlan
	FROM
		tmp_CustomerRates_;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_CustomerRateClear`;
DELIMITER //
CREATE PROCEDURE `prc_CustomerRateClear`(
	IN `p_AccountIdList` LONGTEXT,
	IN `p_TrunkId` INT,
	IN `p_CodeDeckId` int,
	IN `p_CustomerRateId` LONGTEXT,
	IN `p_code` VARCHAR(50),
	IN `p_description` VARCHAR(200),
	IN `p_CountryId` INT,
	IN `p_CompanyId` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	/*delete tblCustomerRate
	from tblCustomerRate
	INNER JOIN (
		SELECT c.CustomerRateID
		FROM   tblCustomerRate c
		INNER JOIN tblCustomerTrunk
			ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
		INNER JOIN tblRate r
			ON c.RateID = r.RateID and r.CodeDeckId=p_CodeDeckId
		WHERE c.TrunkID = p_TrunkId
			AND FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0
			AND ( ( p_code IS NULL ) OR ( p_code IS NOT NULL AND r.Code LIKE REPLACE(p_code,'*', '%')))
			AND ( ( p_description IS NULL ) OR ( p_description IS NOT NULL AND r.Description LIKE REPLACE(p_description,'*', '%')))
			AND ( ( p_CountryId IS NULL )  OR ( p_CountryId IS NOT NULL AND r.CountryID = p_CountryId ) )
	) cr ON cr.CustomerRateID = tblCustomerRate.CustomerRateID;*/

	UPDATE
		tblCustomerRate
	INNER JOIN (
		SELECT
			c.CustomerRateID
		FROM
			tblCustomerRate c
		INNER JOIN tblCustomerTrunk
			ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
		INNER JOIN tblRate r
			ON c.RateID = r.RateID and r.CodeDeckId=p_CodeDeckId
		WHERE
			c.TrunkID = p_TrunkId AND
			( -- if single or selected rates delete
			  p_CustomerRateId IS NOT NULL AND
        FIND_IN_SET(c.CustomerRateId,p_CustomerRateId) != 0
      )
			OR
			( -- if bulk rates delete
				p_CustomerRateId IS NULL AND
				FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0  AND
				( ( p_code IS NULL ) OR ( p_code IS NOT NULL AND r.Code LIKE REPLACE(p_code,'*', '%'))) AND
				( ( p_description IS NULL ) OR ( p_description IS NOT NULL AND r.Description LIKE REPLACE(p_description,'*', '%'))) AND
				( ( p_CountryId IS NULL )  OR ( p_CountryId IS NOT NULL AND r.CountryID = p_CountryId ) )
			)
	) cr ON cr.CustomerRateID = tblCustomerRate.CustomerRateID
	SET
		tblCustomerRate.EndDate=NOW();

	CALL prc_ArchiveOldCustomerRate(p_AccountIdList,p_TrunkId,p_ModifiedBy);

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_CustomerRateInsert`;
DELIMITER //
CREATE PROCEDURE `prc_CustomerRateInsert`(
	IN `p_CompanyId` INT,
	IN `p_AccountIdList` LONGTEXT ,
	IN `p_TrunkId` VARCHAR(100) ,
	IN `p_RateIDList` LONGTEXT,
	IN `p_Rate` DECIMAL(18, 6) ,
	IN `p_ConnectionFee` DECIMAL(18, 6) ,
	IN `p_EffectiveDate` DATETIME ,
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_RoutinePlan` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
ThisSP:BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	INSERT  INTO tblCustomerRate
	(
		RateID ,
		CustomerID ,
		TrunkID ,
		Rate ,
		ConnectionFee,
		EffectiveDate ,
		EndDate,
		Interval1,
		IntervalN ,
		RoutinePlan,
		CreatedDate ,
		LastModifiedBy ,
		LastModifiedDate
	)
	SELECT
		r.RateID,
		r.AccountId ,
		p_TrunkId ,
		p_Rate ,
		p_ConnectionFee,
		p_EffectiveDate ,
		NULL AS EndDate,
		p_Interval1,
		p_IntervalN,
		RoutinePlan,
		NOW() ,
		p_ModifiedBy ,
		NOW()
	FROM
	(
		SELECT
			tblRate.RateID ,
			a.AccountId,
			tblRate.CompanyID,
			RoutinePlan
		FROM
			tblRate ,
			(
				SELECT
					a.AccountId,
					CASE WHEN ctr.TrunkID IS NOT NULL
					THEN p_RoutinePlan
					ELSE 0
					END AS RoutinePlan
				FROM
					tblAccount a
				INNER JOIN tblCustomerTrunk ON TrunkID = p_TrunkId
					AND a.AccountId = tblCustomerTrunk.AccountID
					AND tblCustomerTrunk.Status = 1
				LEFT JOIN tblCustomerTrunk ctr
					ON ctr.TrunkID = p_TrunkId
					AND ctr.AccountID = a.AccountID
					AND ctr.RoutinePlanStatus = 1
				WHERE  FIND_IN_SET(a.AccountID,p_AccountIdList) != 0
			) a
		WHERE FIND_IN_SET(tblRate.RateID,p_RateIDList) != 0
	) r
	LEFT JOIN
	(
		SELECT DISTINCT
			c.RateID,
			c.CustomerID as AccountId ,
			c.TrunkID,
			c.EffectiveDate
		FROM
			tblCustomerRate c
		INNER JOIN tblCustomerTrunk ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
		WHERE FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0 AND c.TrunkID = p_TrunkId
	) cr ON r.RateID = cr.RateID
		AND r.AccountId = cr.AccountId
		AND r.CompanyID = p_CompanyId
		and cr.EffectiveDate = p_EffectiveDate
	WHERE
		r.CompanyID = p_CompanyId
		and cr.RateID is NULL;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_CustomerRateUpdate`;
DELIMITER //
CREATE PROCEDURE `prc_CustomerRateUpdate`(
	IN `p_AccountIdList` LONGTEXT ,
	IN `p_TrunkId` VARCHAR(100) ,
	IN `p_CustomerRateIDList` LONGTEXT,
	IN `p_Rate` DECIMAL(18, 6) ,
	IN `p_ConnectionFee` DECIMAL(18, 6) ,
	IN `p_EffectiveDate` DATETIME ,
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_RoutinePlan` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
ThisSP:BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates_;
    CREATE TEMPORARY TABLE tmp_CustomerRates_ (
        CustomerRateID INT,
        RateID INT,
        CustomerID INT,
        Interval1 INT,
        IntervalN  INT,
        Rate DECIMAL(18, 6),
        PreviousRate DECIMAL(18, 6),
        ConnectionFee DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        CreatedDate DATETIME,
        CreatedBy VARCHAR(50),
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        TrunkID INT,
        RoutinePlan INT,
        INDEX tmp_CustomerRates__CustomerRateID (`CustomerRateID`)/*,
        INDEX tmp_CustomerRates__RateID (`RateID`),
        INDEX tmp_CustomerRates__TrunkID (`TrunkID`),
        INDEX tmp_CustomerRates__EffectiveDate (`EffectiveDate`)*/
    );

	-- if p_EffectiveDate null means multiple rates update
	-- and if multiple rates update then we don't allow to change EffectiveDate
	-- we only allow EffectiveDate change when single edit

	-- insert rates in temp table which needs to update
	INSERT INTO tmp_CustomerRates_
	(
		CustomerRateID,
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		RoutinePlan
	)
	SELECT
		cr.CustomerRateID,
		cr.RateID,
		cr.CustomerID,
		p_Interval1 AS Interval1,
		p_IntervalN AS IntervalN,
		p_Rate AS Rate,
		cr.PreviousRate,
		p_ConnectionFee AS ConnectionFee,
		IFNULL(p_EffectiveDate,cr.EffectiveDate) AS EffectiveDate, -- if p_EffectiveDate null take exiting EffectiveDate
		cr.EndDate,
		cr.CreatedDate,
		cr.CreatedBy,
		NOW() AS LastModifiedDate,
		p_ModifiedBy AS LastModifiedBy,
		cr.TrunkID,
		CASE WHEN ctr.TrunkID IS NOT NULL
		THEN p_RoutinePlan
		ELSE NULL
		END AS RoutinePlan
	FROM
		tblCustomerRate cr
	LEFT JOIN tblCustomerTrunk ctr
		ON ctr.TrunkID = cr.TrunkID
		AND ctr.AccountID = cr.CustomerID
		AND ctr.RoutinePlanStatus = 1
	LEFT JOIN
	(
		SELECT
			RateID,CustomerID
		FROM
			tblCustomerRate
		WHERE
			EffectiveDate = p_EffectiveDate AND
			FIND_IN_SET(tblCustomerRate.CustomerRateID,p_CustomerRateIDList) = 0
	) crc ON crc.RateID=cr.RateID AND crc.CustomerID=cr.CustomerID
	WHERE
		FIND_IN_SET(cr.CustomerRateID,p_CustomerRateIDList) != 0 AND crc.RateID IS NULL;

	-- update EndDate to Archive rates which needs to update
	UPDATE
		tblCustomerRate cr
	JOIN
		tmp_CustomerRates_ temp ON cr.CustomerRateID=temp.CustomerRateID
	SET
		cr.EndDate = NOW();

	-- archive rates which rates' EndDate < NOW()
	CALL prc_ArchiveOldCustomerRate(p_AccountIdList, p_TrunkId, p_ModifiedBy);

	-- insert rates in tblCustomerRate with updated values
	INSERT INTO tblCustomerRate
	(
		CustomerRateID,
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		RoutinePlan
	)
	SELECT
		NULL, -- primary key
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		RoutinePlan
	FROM
		tmp_CustomerRates_;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_CustomerRateUpdateBySelectedRateId`;
DELIMITER //
CREATE PROCEDURE `prc_CustomerRateUpdateBySelectedRateId`(
	IN `p_CompanyId` INT,
	IN `p_AccountIdList` LONGTEXT ,
	IN `p_RateIDList` LONGTEXT ,
	IN `p_TrunkId` VARCHAR(100) ,
	IN `p_Rate` DECIMAL(18, 6) ,
	IN `p_ConnectionFee` DECIMAL(18, 6) ,
	IN `p_EffectiveDate` DATETIME ,
	IN `p_EndDate` DATETIME,
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_RoutinePlan` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
ThisSP:BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	UPDATE  tblCustomerRate
	INNER JOIN (
		SELECT
			c.CustomerRateID,c.EffectiveDate,
			CASE WHEN ctr.TrunkID IS NOT NULL
			THEN p_RoutinePlan
			ELSE 0
			END AS RoutinePlan
		FROM
			tblCustomerRate c
		INNER JOIN tblCustomerTrunk ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
			AND c.EffectiveDate = p_EffectiveDate
		LEFT JOIN tblCustomerTrunk ctr
			ON ctr.TrunkID = c.TrunkID
			AND ctr.AccountID = c.CustomerID
			AND ctr.RoutinePlanStatus = 1
	) cr ON cr.CustomerRateID = tblCustomerRate.CustomerRateID and cr.EffectiveDate = p_EffectiveDate
	SET
		/*tblCustomerRate.PreviousRate = Rate ,
		tblCustomerRate.Rate = p_Rate ,
		tblCustomerRate.ConnectionFee = p_ConnectionFee,
		tblCustomerRate.EffectiveDate = p_EffectiveDate ,
		tblCustomerRate.Interval1 = p_Interval1,
		tblCustomerRate.IntervalN = p_IntervalN,
		tblCustomerRate.RoutinePlan = cr.RoutinePlan,*/
		tblCustomerRate.LastModifiedBy = p_ModifiedBy ,
		tblCustomerRate.LastModifiedDate = NOW(),
		tblCustomerRate.EndDate = NOW()
	WHERE tblCustomerRate.TrunkID = p_TrunkId
		AND FIND_IN_SET(tblCustomerRate.RateID,p_RateIDList) != 0
		AND FIND_IN_SET(tblCustomerRate.CustomerID,p_AccountIdList) != 0;

   CALL prc_ArchiveOldCustomerRate(p_AccountIdList, p_TrunkId, p_ModifiedBy);

        INSERT  INTO tblCustomerRate
                ( RateID ,
                  CustomerID ,
                  TrunkID ,
                  Rate ,
					   ConnectionFee,
                  EffectiveDate ,
                  EndDate,
                  Interval1,
				  		IntervalN ,
				  		RoutinePlan,
                  CreatedDate ,
                  LastModifiedBy ,
                  LastModifiedDate
                )
                SELECT  r.RateID,
                        r.AccountId ,
                        p_TrunkId ,
                        p_Rate ,
								p_ConnectionFee,
                        p_EffectiveDate ,
                        p_EndDate,
                        p_Interval1,
					    		p_IntervalN,
								RoutinePlan,
                        NOW() ,
                        p_ModifiedBy ,
                        NOW()
                FROM    ( SELECT    tblRate.RateID ,
                                    a.AccountId,
                                    tblRate.CompanyID,
									RoutinePlan
                          FROM      tblRate ,
                                    ( SELECT  a.AccountId,
													CASE WHEN ctr.TrunkID IS NOT NULL
														THEN p_RoutinePlan
														ELSE 0
													END AS RoutinePlan
                                      FROM tblAccount a
												  INNER JOIN tblCustomerTrunk ON TrunkID = p_TrunkId
                                      		AND a.AccountId = tblCustomerTrunk.AccountID
                                          AND tblCustomerTrunk.Status = 1
												LEFT JOIN tblCustomerTrunk ctr
													ON ctr.TrunkID = p_TrunkId
													AND ctr.AccountID = a.AccountID
													AND ctr.RoutinePlanStatus = 1
												WHERE  FIND_IN_SET(a.AccountID,p_AccountIdList) != 0
                                    ) a
                          WHERE FIND_IN_SET(tblRate.RateID,p_RateIDList) != 0
                        ) r
                        LEFT JOIN ( SELECT DISTINCT
                                                    c.RateID,
                                                    c.CustomerID as AccountId ,
                                                    c.TrunkID,
                                                    c.EffectiveDate
                                          FROM      tblCustomerRate c
                                                    INNER JOIN tblCustomerTrunk ON tblCustomerTrunk.TrunkID = c.TrunkID
                                                              AND tblCustomerTrunk.AccountID = c.CustomerID
                                                              AND tblCustomerTrunk.Status = 1
                                          WHERE FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0 AND c.TrunkID = p_TrunkId
                                        ) cr ON r.RateID = cr.RateID
                                                AND r.AccountId = cr.AccountId
                                                AND r.CompanyID = p_CompanyId
                                                and cr.EffectiveDate = p_EffectiveDate
                WHERE
                 r.CompanyID = p_CompanyId
                 and cr.RateID is NULL;

 --  	CALL prc_ArchiveOldCustomerRate(p_AccountIdList, p_TrunkId, p_ModifiedBy);

      SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_editpreference`;
DELIMITER //
CREATE PROCEDURE `prc_editpreference`(
	IN `p_groupby` VARCHAR(50),
	IN `p_preference` INT,
	IN `p_accountId` INT,
	IN `p_trunk` INT,
	IN `p_rowcode` INT,
	IN `p_codedeckId` INT,
	IN `p_description` VARCHAR(200),
	IN `p_username` VARCHAR(50)



)
BEGIN

	DECLARE v_description VARCHAR(200);
	DECLARE v_vendorPreferenceId int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	
	DROP TEMPORARY TABLE IF EXISTS tmp_pref0;
	CREATE TEMPORARY TABLE tmp_pref0(	
		RateId INT
	);	
	
	DROP TEMPORARY TABLE IF EXISTS tmp_pref1;
	CREATE TEMPORARY TABLE tmp_pref1(	
		VendorPreferenceID INT,
		Preference INT
	);	
		
		IF p_groupby = 'description' THEN
		
				IF p_preference = 0 THEN
				
					INSERT INTO tmp_pref0
						select RateId
						FROM (
						select vr.RateId
							 from tblVendorRate vr
							 	 inner join tblRate r
								   on vr.RateId=r.RateID 
						    where vr.AccountId = p_accountId AND vr.TrunkID=p_trunk AND r.Description = p_description) tbl;
						    
					
						INSERT INTO tmp_pref1
						select VendorPreferenceID,Preference
						FROM (
						select vp.VendorPreferenceID,vp.Preference
							 from tblVendorPreference vp
							 	 inner join tmp_pref0 tmp0
								   on vp.RateId=tmp0.RateID 
						    where vp.AccountId = p_accountId AND vp.TrunkID=p_trunk) tbl1;
						
						select max(Preference) as Preference from tmp_pref1;				
						
				ELSE
				
				
					INSERT INTO tmp_pref0
						select RateId
						FROM (
						select vr.RateId
							 from tblVendorRate vr
							 	 inner join tblRate r
								   on vr.RateId=r.RateID 
						    where vr.AccountId = p_accountId AND vr.TrunkID=p_trunk AND r.Description = p_description) tbl;
						    
					/* Update preference */
					 UPDATE tblVendorPreference 
						INNER JOIN tmp_pref0 temp 
							ON tblVendorPreference.RateId = temp.RateID
						SET tblVendorPreference.Preference = p_preference,created_at=NOW(),CreatedBy=p_username
						WHERE tblVendorPreference.AccountId = p_accountId AND tblVendorPreference.TrunkID = p_trunk ;
						
					 /* insert preference if not in tblVendorPreference */		
					 insert into tblVendorPreference (AccountId,Preference,RateID,TrunkID,CreatedBy,created_at)    
						    select p_accountId as AccountId, p_preference as Preference,tmp0.RateID as RateId,p_trunk as TrunkID ,p_username as CreatedBy,NOW() as created_at
							 from  tmp_pref0 tmp0
							 	 left join tblVendorPreference vp
								   on vp.RateId=tmp0.RateID 
								   AND vp.AccountId = p_accountId AND vp.TrunkID=p_trunk
						    where  vp.VendorPreferenceID IS NULL;
		
								
				END IF;
		ELSE
				
				IF p_preference = 0 THEN
				
						select distinct vp.Preference
							 from tblVendorRate vr
							 	 inner join tblRate r
								   on vr.RateId=r.RateID 
								 inner join tblVendorPreference vp
								   on r.RateID=vp.RateId
						    where vp.AccountId = p_accountId AND vr.TrunkID=p_trunk AND r.Code = p_rowcode;									
						
				ELSE
					
					
					
						INSERT INTO tmp_pref0
						select RateId
						FROM (
						select vr.RateId
							 from tblVendorRate vr
							 	 inner join tblRate r
								   on vr.RateId=r.RateID 
						    where vr.AccountId = p_accountId AND vr.TrunkID=p_trunk AND r.Code = p_rowcode) tbl;
						    
					/* Update preference */
					 UPDATE tblVendorPreference 
						INNER JOIN tmp_pref0 temp 
							ON tblVendorPreference.RateId = temp.RateID
						SET tblVendorPreference.Preference = p_preference,created_at=NOW(),CreatedBy=p_username
						WHERE tblVendorPreference.AccountId = p_accountId AND tblVendorPreference.TrunkID = p_trunk ;
						
					 /* insert preference if not in tblVendorPreference */		
					 insert into tblVendorPreference (AccountId,Preference,RateID,TrunkID,CreatedBy,created_at)    
						    select p_accountId as AccountId, p_preference as Preference,tmp0.RateID as RateId,p_trunk as TrunkID ,p_username as CreatedBy,NOW() as created_at
							 from  tmp_pref0 tmp0
							 	 left join tblVendorPreference vp
								   on vp.RateId=tmp0.RateID 
								   AND vp.AccountId = p_accountId AND vp.TrunkID=p_trunk
						    where  vp.VendorPreferenceID IS NULL;
						    
					
								
				END IF;
		
		END IF;
		
			 

		
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_GetAccountLogs`;
DELIMITER //
CREATE PROCEDURE `prc_GetAccountLogs`(
	IN `p_CompanyID` int,
	IN `p_userID` int ,
	IN `p_AccountID` int ,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5)
)
BEGIN
	DECLARE v_OffSet_ int;
	DECLARE v_Round_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	SELECT * FROM
	(
		(
			SELECT
				d.ColumnName,
				CASE
					WHEN (d.ColumnName='accountgateway') THEN
						GROUP_CONCAT(DISTINCT cgo.Title)
					WHEN (d.ColumnName='IsCustomer' AND d.OldValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsCustomer' AND d.OldValue=1) THEN
						'YES'
					WHEN (d.ColumnName='IsVendor' AND d.OldValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsVendor' AND d.OldValue=1) THEN
						'YES'
					ELSE
						d.OldValue
				END AS OldValue,
				CASE
					WHEN (d.ColumnName='accountgateway') THEN
						GROUP_CONCAT(DISTINCT cgn.Title)
					WHEN (d.ColumnName='IsCustomer' AND d.NewValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsCustomer' AND d.NewValue=1) THEN
						'YES'
					WHEN (d.ColumnName='IsVendor' AND d.NewValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsVendor' AND d.NewValue=1) THEN
						'YES'
					ELSE
						d.NewValue
				END AS NewValue,
				d.created_at,
				d.created_by
			FROM tblAuditDetails AS d
			LEFT JOIN tblAuditHeader AS h
				ON h.AuditHeaderID = d.AuditHeaderID
			LEFT JOIN tblAccount AS a
				ON h.ParentColumnID = a.AccountID
			LEFT JOIN tblCompanyGateway AS cgo
				ON FIND_IN_SET(cgo.CompanyGatewayID,d.OldValue)
			LEFT JOIN tblCompanyGateway AS cgn
				ON FIND_IN_SET(cgn.CompanyGatewayID,d.NewValue)
			WHERE   
				h.Type = 'account' AND 
				h.ParentColumnName = 'AccountID' AND 
				h.ParentColumnID = p_AccountID AND 
				a.AccountID = p_AccountID
			GROUP BY
				d.AuditDetailID,d.OldValue,d.NewValue
		)
		
		UNION
		
		(
			SELECT
				d.ColumnName,
				d.OldValue AS OldValue,
				d.NewValue AS NewValue,
				d.created_at,
				d.created_by
			FROM tblAuditDetails AS d
			LEFT JOIN tblAuditHeader AS h
				ON h.AuditHeaderID = d.AuditHeaderID
			LEFT JOIN tblAccountBilling AS ab
				ON h.ParentColumnID = ab.AccountBillingID	
			LEFT JOIN tblAccount AS a
				ON ab.AccountID = a.AccountID
			WHERE   
				h.Type = 'accountbilling' AND 
				h.ParentColumnName = 'AccountBillingID' AND 
				ab.AccountID = p_AccountID
			GROUP BY
				d.AuditDetailID,d.OldValue,d.NewValue
		)
		
		UNION
		
		(
			SELECT
				IF(d2.ColumnName="CustomerAuthValue","Customer IP","Vendor IP"),
				d2.OldValue AS OldValue,
				d2.NewValue AS NewValue,
				d2.created_at,
				d2.created_by
			FROM tblAuditDetails AS d2
			LEFT JOIN tblAuditHeader AS h2
				ON h2.AuditHeaderID = d2.AuditHeaderID
			LEFT JOIN tblAccountAuthenticate AS aa
				ON aa.AccountAuthenticateID=h2.ParentColumnID
			LEFT JOIN tblAccount AS a2
				ON aa.AccountID = a2.AccountID
			WHERE   
				h2.Type = 'accountip' AND 
				h2.ParentColumnName = 'AccountAuthenticateID' AND 
				a2.AccountID = p_AccountID
			GROUP BY
				d2.AuditDetailID,d2.OldValue,d2.NewValue
		)
	) mix

	ORDER BY
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ColumnNameDESC') THEN mix.ColumnName
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ColumnNameASC') THEN mix.ColumnName
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN mix.created_at
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN mix.created_at
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_byDESC') THEN mix.created_by
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_byASC') THEN mix.created_by
		END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;

	SELECT 
		COUNT(*) AS totalcount
	FROM
	(
		(
			SELECT
				d.ColumnName,
				CASE
					WHEN (d.ColumnName='accountgateway') THEN
						GROUP_CONCAT(DISTINCT cgo.Title)
					WHEN (d.ColumnName='IsCustomer' AND d.OldValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsCustomer' AND d.OldValue=1) THEN
						'YES'
					WHEN (d.ColumnName='IsVendor' AND d.OldValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsVendor' AND d.OldValue=1) THEN
						'YES'
					ELSE
						d.OldValue
				END AS OldValue,
				CASE
					WHEN (d.ColumnName='accountgateway') THEN
						GROUP_CONCAT(DISTINCT cgn.Title)
					WHEN (d.ColumnName='IsCustomer' AND d.NewValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsCustomer' AND d.NewValue=1) THEN
						'YES'
					WHEN (d.ColumnName='IsVendor' AND d.NewValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsVendor' AND d.NewValue=1) THEN
						'YES'
					ELSE
						d.NewValue
				END AS NewValue,
				d.created_at,
				d.created_by
			FROM tblAuditDetails AS d
			LEFT JOIN tblAuditHeader AS h
				ON h.AuditHeaderID = d.AuditHeaderID
			LEFT JOIN tblAccount AS a
				ON h.ParentColumnID = a.AccountID
			LEFT JOIN tblCompanyGateway AS cgo
				ON FIND_IN_SET(cgo.CompanyGatewayID,d.OldValue)
			LEFT JOIN tblCompanyGateway AS cgn
				ON FIND_IN_SET(cgn.CompanyGatewayID,d.NewValue)
			WHERE   
				h.Type = 'account' AND 
				h.ParentColumnName = 'AccountID' AND 
				h.ParentColumnID = p_AccountID AND 
				a.AccountID = p_AccountID
			GROUP BY
				d.AuditDetailID,d.OldValue,d.NewValue
		)
		
		UNION
		
		(
			SELECT
				d.ColumnName,
				d.OldValue AS OldValue,
				d.NewValue AS NewValue,
				d.created_at,
				d.created_by
			FROM tblAuditDetails AS d
			LEFT JOIN tblAuditHeader AS h
				ON h.AuditHeaderID = d.AuditHeaderID
			LEFT JOIN tblAccountBilling AS ab
				ON h.ParentColumnID = ab.AccountBillingID	
			LEFT JOIN tblAccount AS a
				ON ab.AccountID = a.AccountID
			WHERE   
				h.Type = 'accountbilling' AND 
				h.ParentColumnName = 'AccountBillingID' AND 
				ab.AccountID = p_AccountID
			GROUP BY
				d.AuditDetailID,d.OldValue,d.NewValue
		)
		
		UNION
		
		(
			SELECT
				d2.ColumnName,
				d2.OldValue AS OldValue,
				d2.NewValue AS NewValue,
				d2.created_at,
				d2.created_by
			FROM tblAuditDetails AS d2
			LEFT JOIN tblAuditHeader AS h2
				ON h2.AuditHeaderID = d2.AuditHeaderID
			LEFT JOIN tblAccountAuthenticate AS aa
				ON aa.AccountAuthenticateID=h2.ParentColumnID
			LEFT JOIN tblAccount AS a2
				ON aa.AccountID = a2.AccountID
			WHERE   
				h2.Type = 'accountip' AND 
				h2.ParentColumnName = 'AccountAuthenticateID' AND 
				a2.AccountID = p_AccountID
			GROUP BY
				d2.AuditDetailID,d2.OldValue,d2.NewValue
		)
	) totalcount;
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_GetAccounts`;
DELIMITER //
CREATE PROCEDURE `prc_GetAccounts`(
	IN `p_CompanyID` int,
	IN `p_userID` int ,
	IN `p_IsVendor` int ,
	IN `p_isCustomer` int ,
	IN `p_isReseller` INT,
	IN `p_ResellerID` INT,
	IN `p_activeStatus` int,
	IN `p_VerificationStatus` int,
	IN `p_AccountNo` VARCHAR(100),
	IN `p_ContactName` VARCHAR(50),
	IN `p_AccountName` VARCHAR(50),
	IN `p_tags` VARCHAR(50),
	IN `p_IPCLI` VARCHAR(50),
	IN `p_low_balance` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN
	DECLARE v_OffSet_ int;
	DECLARE v_Round_ int;
	DECLARE v_raccountids TEXT;
	DECLARE v_resellercompanyid int;
	SET v_raccountids = '';
	SET v_resellercompanyid = 0;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	IF p_ResellerID > 0
	THEN
		DROP TEMPORARY TABLE IF EXISTS tmp_reselleraccounts_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_reselleraccounts_(
			AccountID int
		);
	
		INSERT INTO tmp_reselleraccounts_
		SELECT AccountID FROM tblAccountDetails WHERE ResellerOwner=p_ResellerID
		UNION
		SELECT AccountID FROM tblReseller WHERE ResellerID=p_ResellerID;
		
		SELECT ChildCompanyID INTO v_resellercompanyid FROM tblReseller WHERE ResellerID=p_ResellerID;		
	
		SELECT IFNULL(GROUP_CONCAT(AccountID),'') INTO v_raccountids FROM tmp_reselleraccounts_;
		
	END IF;

	IF p_isExport = 0
	THEN

		SELECT
			tblAccount.AccountID,
			tblAccount.Number,
			tblAccount.AccountName,
			CONCAT(tblAccount.FirstName,' ',tblAccount.LastName) as Ownername,
			tblAccount.Phone,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.SOAOffset,0),v_Round_)) as OutStandingAmount,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.UnbilledAmount,0),v_Round_) - ROUND(COALESCE(abc.VendorUnbilledAmount,0),v_Round_)) as UnbilledAmount,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.PermanentCredit,0),v_Round_)) as PermanentCredit,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.BalanceAmount,0),v_Round_)) as AccountExposure,
			tblAccount.Email,
			tblAccount.IsCustomer,
			tblAccount.IsVendor,
			tblAccount.VerificationStatus,
			tblAccount.Address1,
			tblAccount.Address2,
			tblAccount.Address3,
			tblAccount.City,
			tblAccount.Country,
			tblAccount.PostCode,
			tblAccount.Picture,
			IF ( (CASE WHEN abc.BalanceThreshold LIKE '%p' THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit ELSE abc.BalanceThreshold END) < abc.BalanceAmount AND abc.BalanceThreshold <> 0 ,1,0) as BalanceWarning,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.UnbilledAmount,0),v_Round_)) as CUA,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.VendorUnbilledAmount,0),v_Round_)) as VUA,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.BalanceAmount,0),v_Round_)) as AE,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,IF(ROUND(COALESCE(abc.PermanentCredit,0),v_Round_) - ROUND(COALESCE(abc.BalanceAmount,0),v_Round_)<0,0,ROUND(COALESCE(abc.PermanentCredit,0),v_Round_) - ROUND(COALESCE(abc.BalanceAmount,0),v_Round_))) as ACL,
			abc.BalanceThreshold,
			tblAccount.Blocked
		FROM tblAccount
		LEFT JOIN tblAccountBalance abc
			ON abc.AccountID = tblAccount.AccountID
		LEFT JOIN tblUser
			ON tblAccount.Owner = tblUser.UserID
		LEFT JOIN tblContact
			ON tblContact.Owner=tblAccount.AccountID
		LEFT JOIN tblAccountAuthenticate
			ON tblAccountAuthenticate.AccountID = tblAccount.AccountID
		LEFT JOIN tblCLIRateTable
			ON tblCLIRateTable.AccountID = tblAccount.AccountID
		WHERE  -- tblAccount.CompanyID = p_CompanyID AND
			 tblAccount.AccountType = 1
			AND tblAccount.Status = p_activeStatus
			AND tblAccount.VerificationStatus = p_VerificationStatus
			AND (p_userID = 0 OR tblAccount.Owner = p_userID)
			AND ((p_IsVendor = 0 OR tblAccount.IsVendor = 1))
			AND ((p_isCustomer = 0 OR tblAccount.IsCustomer = 1))
			AND ((p_isReseller = 0 OR tblAccount.IsReseller = 1))
			AND (p_ResellerID = 0 OR tblAccount.CompanyID = v_resellercompanyid)
			AND ((p_AccountNo = '' OR tblAccount.Number LIKE p_AccountNo))
			AND ((p_AccountName = '' OR tblAccount.AccountName LIKE Concat('%',p_AccountName,'%')))
			AND ((p_IPCLI = '' OR tblCLIRateTable.CLI LIKE CONCAT('%',p_IPCLI,'%') OR CONCAT(IFNULL(tblAccountAuthenticate.CustomerAuthValue,''),',',IFNULL(tblAccountAuthenticate.VendorAuthValue,'')) LIKE CONCAT('%',p_IPCLI,'%')))
			AND ((p_tags = '' OR tblAccount.tags LIKE Concat(p_tags,'%')))
			AND ((p_ContactName = '' OR (CONCAT(IFNULL(tblContact.FirstName,'') ,' ', IFNULL(tblContact.LastName,''))) LIKE CONCAT('%',p_ContactName,'%')))
			AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND (CASE WHEN abc.BalanceThreshold LIKE '%p' THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit ELSE abc.BalanceThreshold END) < abc.BalanceAmount) )
		GROUP BY tblAccount.AccountID
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN tblAccount.AccountName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN tblAccount.AccountName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NumberDESC') THEN tblAccount.Number
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NumberASC') THEN tblAccount.Number
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OwnernameDESC') THEN tblUser.FirstName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OwnernameASC') THEN tblUser.FirstName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PhoneDESC') THEN tblAccount.Phone
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PhoneASC') THEN tblAccount.Phone
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutStandingAmountDESC') THEN abc.SOAOffset
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutStandingAmountASC') THEN abc.SOAOffset
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PermanentCreditDESC') THEN abc.PermanentCredit
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PermanentCreditASC') THEN abc.PermanentCredit
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UnbilledAmountDESC') THEN (ROUND(COALESCE(abc.UnbilledAmount,0),v_Round_) - ROUND(COALESCE(abc.VendorUnbilledAmount,0),v_Round_))
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UnbilledAmountASC') THEN (ROUND(COALESCE(abc.UnbilledAmount,0),v_Round_) - ROUND(COALESCE(abc.VendorUnbilledAmount,0),v_Round_))
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EmailDESC') THEN tblAccount.Email
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EmailASC') THEN tblAccount.Email
			END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(DISTINCT tblAccount.AccountID) AS totalcount
		FROM tblAccount
		LEFT JOIN tblAccountBalance abc
			ON abc.AccountID = tblAccount.AccountID
		LEFT JOIN tblUser
			ON tblAccount.Owner = tblUser.UserID
		LEFT JOIN tblContact
			ON tblContact.Owner=tblAccount.AccountID
		LEFT JOIN tblAccountAuthenticate
			ON tblAccountAuthenticate.AccountID = tblAccount.AccountID
		LEFT JOIN tblCLIRateTable
			ON tblCLIRateTable.AccountID = tblAccount.AccountID
		WHERE --  tblAccount.CompanyID = p_CompanyID AND
			 tblAccount.AccountType = 1
			AND tblAccount.Status = p_activeStatus
			AND tblAccount.VerificationStatus = p_VerificationStatus
			AND (p_userID = 0 OR tblAccount.Owner = p_userID)
			AND ((p_IsVendor = 0 OR tblAccount.IsVendor = 1))
			AND ((p_isCustomer = 0 OR tblAccount.IsCustomer = 1))
			AND ((p_isReseller = 0 OR tblAccount.IsReseller = 1))
			AND (p_ResellerID = 0 OR tblAccount.CompanyID = v_resellercompanyid)
			AND ((p_AccountNo = '' OR tblAccount.Number LIKE p_AccountNo))
			AND ((p_AccountName = '' OR tblAccount.AccountName LIKE Concat('%',p_AccountName,'%')))
			AND ((p_IPCLI = '' OR tblCLIRateTable.CLI LIKE CONCAT('%',p_IPCLI,'%') OR CONCAT(IFNULL(tblAccountAuthenticate.CustomerAuthValue,''),',',IFNULL(tblAccountAuthenticate.VendorAuthValue,'')) LIKE CONCAT('%',p_IPCLI,'%')))
			AND ((p_tags = '' OR tblAccount.tags LIKE Concat(p_tags,'%')))
			AND ((p_ContactName = '' OR (CONCAT(IFNULL(tblContact.FirstName,'') ,' ', IFNULL(tblContact.LastName,''))) LIKE CONCAT('%',p_ContactName,'%')))
			AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND (CASE WHEN abc.BalanceThreshold LIKE '%p' THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit ELSE abc.BalanceThreshold END) < abc.BalanceAmount) );

	END IF;
	IF p_isExport = 1
	THEN
		SELECT
			tblAccount.Number as NO,
			tblAccount.AccountName,
			CONCAT(tblAccount.FirstName,' ',tblAccount.LastName) as Name,
			tblAccount.Phone,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.SOAOffset,0),v_Round_)) as 'OutStanding',
			tblAccount.Email,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.UnbilledAmount,0),v_Round_)  - ROUND(COALESCE(abc.VendorUnbilledAmount,0),v_Round_)) as 'Unbilled Amount',
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.PermanentCredit,0),v_Round_)) as 'Credit Limit',
			CONCAT(tblUser.FirstName,' ',tblUser.LastName) as 'Account Owner',
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.BalanceAmount,0),v_Round_)) as AccountExposure
		FROM tblAccount
		LEFT JOIN tblAccountBalance abc
			ON abc.AccountID = tblAccount.AccountID
		LEFT JOIN tblUser
			ON tblAccount.Owner = tblUser.UserID
		LEFT JOIN tblContact
			ON tblContact.Owner=tblAccount.AccountID
		LEFT JOIN tblAccountAuthenticate
			ON tblAccountAuthenticate.AccountID = tblAccount.AccountID
		LEFT JOIN tblCLIRateTable
			ON tblCLIRateTable.AccountID = tblAccount.AccountID
		WHERE   tblAccount.CompanyID = p_CompanyID
			AND tblAccount.AccountType = 1
			AND tblAccount.Status = p_activeStatus
			AND tblAccount.VerificationStatus = p_VerificationStatus
			AND (p_userID = 0 OR tblAccount.Owner = p_userID)
			AND ((p_IsVendor = 0 OR tblAccount.IsVendor = 1))
			AND ((p_isCustomer = 0 OR tblAccount.IsCustomer = 1))
			AND ((p_isReseller = 0 OR tblAccount.IsReseller = 1))
			AND (p_ResellerID = 0 OR tblAccount.CompanyID = v_resellercompanyid)
			AND ((p_AccountNo = '' OR tblAccount.Number LIKE p_AccountNo))
			AND ((p_AccountName = '' OR tblAccount.AccountName LIKE Concat('%',p_AccountName,'%')))
			AND ((p_IPCLI = '' OR tblCLIRateTable.CLI LIKE CONCAT('%',p_IPCLI,'%') OR CONCAT(IFNULL(tblAccountAuthenticate.CustomerAuthValue,''),',',IFNULL(tblAccountAuthenticate.VendorAuthValue,'')) LIKE CONCAT('%',p_IPCLI,'%')))
			AND ((p_tags = '' OR tblAccount.tags LIKE Concat(p_tags,'%')))
			AND ((p_ContactName = '' OR (CONCAT(IFNULL(tblContact.FirstName,'') ,' ', IFNULL(tblContact.LastName,''))) LIKE CONCAT('%',p_ContactName,'%')))
			AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND (CASE WHEN abc.BalanceThreshold LIKE '%p' THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit ELSE abc.BalanceThreshold END) < abc.BalanceAmount) )
		GROUP BY tblAccount.AccountID;
	END IF;
	IF p_isExport = 2
	THEN
		SELECT
			tblAccount.AccountID,
			tblAccount.AccountName
		FROM tblAccount
		LEFT JOIN tblAccountBalance abc
			ON abc.AccountID = tblAccount.AccountID
		LEFT JOIN tblUser
			ON tblAccount.Owner = tblUser.UserID
		LEFT JOIN tblContact
			ON tblContact.Owner=tblAccount.AccountID
		LEFT JOIN tblAccountAuthenticate
			ON tblAccountAuthenticate.AccountID = tblAccount.AccountID
		LEFT JOIN tblCLIRateTable
			ON tblCLIRateTable.AccountID = tblAccount.AccountID
		WHERE   tblAccount.CompanyID = p_CompanyID
			AND tblAccount.AccountType = 1
			AND tblAccount.Status = p_activeStatus
			AND tblAccount.VerificationStatus = p_VerificationStatus
			AND (p_userID = 0 OR tblAccount.Owner = p_userID)
			AND ((p_IsVendor = 0 OR tblAccount.IsVendor = 1))
			AND ((p_isCustomer = 0 OR tblAccount.IsCustomer = 1))
			AND ((p_isReseller = 0 OR tblAccount.IsReseller = 1))
			AND (p_ResellerID = 0 OR tblAccount.CompanyID = v_resellercompanyid)
			AND ((p_AccountNo = '' OR tblAccount.Number LIKE p_AccountNo))
			AND ((p_AccountName = '' OR tblAccount.AccountName LIKE Concat('%',p_AccountName,'%')))
			AND ((p_IPCLI = '' OR tblCLIRateTable.CLI LIKE CONCAT('%',p_IPCLI,'%') OR CONCAT(IFNULL(tblAccountAuthenticate.CustomerAuthValue,''),',',IFNULL(tblAccountAuthenticate.VendorAuthValue,'')) LIKE CONCAT('%',p_IPCLI,'%')))
			AND ((p_tags = '' OR tblAccount.tags LIKE Concat(p_tags,'%')))
			AND ((p_ContactName = '' OR (CONCAT(IFNULL(tblContact.FirstName,'') ,' ', IFNULL(tblContact.LastName,''))) LIKE CONCAT('%',p_ContactName,'%')))
			AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND (CASE WHEN abc.BalanceThreshold LIKE '%p' THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit ELSE abc.BalanceThreshold END) < abc.BalanceAmount) )
		GROUP BY tblAccount.AccountID;
	END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_getAutoImportMail`;
DELIMITER //
CREATE PROCEDURE `prc_getAutoImportMail`(
	IN `p_jobType` INT,
	IN `p_jobStatus` INT,
	IN `p_CompanyID` INT,
	IN `p_search` TEXT,
	IN `p_AccountID` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN

	DECLARE v_OffSet_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

					IF (p_isExport = 0) THEN


							select IFNULL(jt.Title, 'Not Match') as jobType,
							CONCAT(  a.Subject, '<br>', a.AccountName, '<br>', a.`From` )  AS header,
							a.created_at,a.JobID,IFNULL(js.Title, 'Not Match') as jobstatus,a.AutoImportID, a.AccountID, IFNULL(ac.AccountName, '') from tblAutoImport a
							left join tblJob j on a.JobID=j.JobID
							left join tblJobType jt on j.JobTypeID = jt.JobTypeID
							left join tblJobStatus js on j.JobStatusID=js.JobStatusID
							left join tblAccount ac on a.AccountID=ac.AccountID
							where
								CASE
									WHEN (p_jobType > 0) THEN
										jt.JobTypeID = p_jobType AND a.CompanyID=p_CompanyID
									WHEN (p_jobStatus > 0) THEN
										js.JobStatusID = p_jobStatus AND a.CompanyID=p_CompanyID
									WHEN (p_search <> '') THEN
										    (  a.Subject LIKE CONCAT('%',p_search,'%')  OR a.JobID LIKE CONCAT('%',p_search,'%') )  AND a.CompanyID=p_CompanyID
								   ELSE
										a.CompanyID=p_CompanyID
								END
								AND ( p_AccountID = 0 OR a.AccountID=p_AccountID )
								ORDER BY
								  CASE WHEN p_lSortCol = 'Type' AND p_SortOrder = 'desc' THEN jobType END DESC,
								  CASE WHEN p_lSortCol = 'Type' THEN jobType END,
								  CASE WHEN p_lSortCol = 'Header' AND p_SortOrder = 'desc' THEN header END DESC,
								  CASE WHEN p_lSortCol = 'Header' THEN header END,
								  CASE WHEN p_lSortCol = 'Created' AND p_SortOrder = 'desc' THEN a.created_at END DESC,
								  CASE WHEN p_lSortCol = 'Created' THEN a.created_at END,
								  CASE WHEN p_lSortCol = 'Status' AND p_SortOrder = 'desc' THEN jobstatus END DESC,
								  CASE WHEN p_lSortCol = 'Status' THEN jobstatus END,
								  CASE WHEN p_lSortCol = 'JobId' AND p_SortOrder = 'desc' THEN a.JobID END DESC,
								  CASE WHEN p_lSortCol = 'JobId' THEN a.JobID END

							LIMIT p_RowspPage OFFSET v_OffSet_;

					ELSE


							select IFNULL(jt.Title, 'Not Match') as jobType,
							CONCAT(  a.Subject, '<br>', a.AccountName, '<br>', a.`From` )  AS header,
							a.created_at,a.JobID,IFNULL(js.Title, 'Not Match') as jobstatus,a.AutoImportID, a.AccountID, IFNULL(ac.AccountName, '') from tblAutoImport a
							left join tblJob j on a.JobID=j.JobID
							left join tblJobType jt on j.JobTypeID = jt.JobTypeID
							left join tblJobStatus js on j.JobStatusID=js.JobStatusID
							left join tblAccount ac on a.AccountID=ac.AccountID
							where
								CASE
									WHEN (p_jobType > 0) THEN
										jt.JobTypeID = p_jobType AND a.CompanyID=p_CompanyID
									WHEN (p_jobStatus > 0) THEN
										js.JobStatusID = p_jobStatus AND a.CompanyID=p_CompanyID
									WHEN (p_search <> '') THEN
										    (  a.Subject LIKE CONCAT('%',p_search,'%')  OR a.JobID LIKE CONCAT('%',p_search,'%') )  AND a.CompanyID=p_CompanyID
								   ELSE
										a.CompanyID=p_CompanyID
								END
								ORDER BY
								  CASE WHEN p_lSortCol = 'Type' AND p_SortOrder = 'desc' THEN jobType END DESC,
								  CASE WHEN p_lSortCol = 'Type' THEN jobType END,
								  CASE WHEN p_lSortCol = 'Header' AND p_SortOrder = 'desc' THEN header END DESC,
								  CASE WHEN p_lSortCol = 'Header' THEN header END,
								  CASE WHEN p_lSortCol = 'Created' AND p_SortOrder = 'desc' THEN a.created_at END DESC,
								  CASE WHEN p_lSortCol = 'Created' THEN a.created_at END,
								  CASE WHEN p_lSortCol = 'Status' AND p_SortOrder = 'desc' THEN jobstatus END DESC,
								  CASE WHEN p_lSortCol = 'Status' THEN jobstatus END,
								  CASE WHEN p_lSortCol = 'JobId' AND p_SortOrder = 'desc' THEN a.JobID END DESC,
								  CASE WHEN p_lSortCol = 'JobId' THEN a.JobID END
							;


					END IF;



					select COUNT(*) AS `totalcount` from tblAutoImport a
							left join tblJob j on a.JobID=j.JobID
							left join tblJobType jt on j.JobTypeID = jt.JobTypeID
							left join tblJobStatus js on j.JobStatusID=js.JobStatusID
							left join tblAccount ac on a.AccountID=ac.AccountID
							where 
								CASE 
									WHEN (p_jobType > 0) THEN
										jt.JobTypeID = p_jobType AND a.CompanyID=p_CompanyID
									WHEN (p_jobStatus > 0) THEN
										js.JobStatusID = p_jobStatus AND a.CompanyID=p_CompanyID
									WHEN (p_search <> '') THEN
										    (  a.Subject LIKE CONCAT('%',p_search,'%')  OR a.JobID LIKE CONCAT('%',p_search,'%') )  AND a.CompanyID=p_CompanyID
								   ELSE
										a.CompanyID=p_CompanyID				
								END
							LIMIT p_RowspPage OFFSET v_OffSet_;
		
		
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_getAutoImportSetting_AccountAndRateTable`;
DELIMITER //
CREATE PROCEDURE `prc_getAutoImportSetting_AccountAndRateTable`(
	IN `p_SettingType` INT,
	IN `p_CompanyID` INT,
	IN `p_TrunkID` INT,
	IN `p_typePKID` INT,
	IN `p_search` TEXT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT


)
BEGIN

	DECLARE v_OffSet_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	
	
	IF (p_SettingType = 1 ) THEN  -- Account Setting
		
					IF (p_isExport = 0) THEN
							
								
							select a.AccountName,t.Trunk , ut.Title,Subject,FileName,SendorEmail,a.AccountID,t.TrunkID,ut.FileUploadTemplateID,AutoImportSettingID from tblAutoImportSetting as s
							inner join tblTrunk as t on s.TrunkID=t.TrunkID
							inner join tblAccount as a on a.AccountID=s.TypePKID
							inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
							
							where 
								  CASE 
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0 AND p_search <> '') THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
										WHEN (p_TrunkID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
									   WHEN (p_typePKID > 0) THEN
										    s.TypePKID = p_typePKID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
										WHEN (p_search <> '') THEN
										     (  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 1				    				    
										     
										    
										ELSE						
											 s.CompanyID = p_CompanyID AND s.`Type`= 1
										
									END
									
								ORDER BY
								  CASE WHEN p_lSortCol = 'AccountName' AND p_SortOrder = 'desc' THEN a.AccountName END DESC,
								  CASE WHEN p_lSortCol = 'AccountName' THEN a.AccountName END,
								  CASE WHEN p_lSortCol = 'Trunk' AND p_SortOrder = 'desc' THEN t.Trunk END DESC,
								  CASE WHEN p_lSortCol = 'Trunk' THEN t.Trunk END,
								  CASE WHEN p_lSortCol = 'Import File Templete' AND p_SortOrder = 'desc' THEN ut.Title END DESC,
								  CASE WHEN p_lSortCol = 'Import File Templete' THEN ut.Title END,
								  CASE WHEN p_lSortCol = 'Subject Match' AND p_SortOrder = 'desc' THEN Subject END DESC,
								  CASE WHEN p_lSortCol = 'Subject Match' THEN Subject END,
								  CASE WHEN p_lSortCol = 'Filename Match' AND p_SortOrder = 'desc' THEN FileName END DESC,
								  CASE WHEN p_lSortCol = 'Filename Match' THEN FileName END,
								  CASE WHEN p_lSortCol = 'Sendor Match' AND p_SortOrder = 'desc' THEN SendorEmail END DESC,
								  CASE WHEN p_lSortCol = 'Sendor Match' THEN SendorEmail END

													
							LIMIT p_RowspPage OFFSET v_OffSet_;
							
					ELSE
							
							
							select a.AccountName,t.Trunk , ut.Title,Subject,SendorEmail,FileName from tblAutoImportSetting as s
							inner join tblTrunk as t on s.TrunkID=t.TrunkID
							inner join tblAccount as a on a.AccountID=s.TypePKID
							inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
							
							where 
								  CASE 
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0 AND p_search <> '') THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
										WHEN (p_TrunkID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
									   WHEN (p_typePKID > 0) THEN
										    s.TypePKID = p_typePKID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
										WHEN (p_search <> '') THEN

										    (  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 1				    				    
										ELSE						
											 s.CompanyID = p_CompanyID AND s.`Type`= 1
										
									END	
								ORDER BY
								  CASE WHEN p_lSortCol = 'AccountName' AND p_SortOrder = 'desc' THEN a.AccountName END DESC,
								  CASE WHEN p_lSortCol = 'AccountName' THEN a.AccountName END,
								  CASE WHEN p_lSortCol = 'Trunk' AND p_SortOrder = 'desc' THEN t.Trunk END DESC,
								  CASE WHEN p_lSortCol = 'Trunk' THEN t.Trunk END,
								  CASE WHEN p_lSortCol = 'Import File Templete' AND p_SortOrder = 'desc' THEN ut.Title END DESC,
								  CASE WHEN p_lSortCol = 'Import File Templete' THEN ut.Title END,
								  CASE WHEN p_lSortCol = 'Subject Match' AND p_SortOrder = 'desc' THEN Subject END DESC,
								  CASE WHEN p_lSortCol = 'Subject Match' THEN Subject END,
								  CASE WHEN p_lSortCol = 'Filename Match' AND p_SortOrder = 'desc' THEN FileName END DESC,
								  CASE WHEN p_lSortCol = 'Filename Match' THEN FileName END,
								  CASE WHEN p_lSortCol = 'Sendor Match' AND p_SortOrder = 'desc' THEN SendorEmail END DESC,
								  CASE WHEN p_lSortCol = 'Sendor Match' THEN SendorEmail END
							;			
							
							
					END IF;
		
	
		select COUNT(*) AS `totalcount` from tblAutoImportSetting as s
		inner join tblTrunk as t on s.TrunkID=t.TrunkID
		inner join tblAccount as a on a.AccountID=s.TypePKID
		inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
		where 
								  CASE 
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0 AND p_search <> '') THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
										WHEN (p_TrunkID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
									   WHEN (p_typePKID > 0) THEN
										    s.TypePKID = p_typePKID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
										WHEN (p_search <> '') THEN			    				    
										    (  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 1				    				    
										ELSE						
											 s.CompanyID = p_CompanyID AND s.`Type`= 1
										
									END	
							;		
			
	END IF;
	
	
	
	IF (p_SettingType = 2 ) THEN  -- RateTable Setting
		
		IF (p_isExport = 0) THEN
				
					
				select r.RateTableName,ut.Title,Subject,FileName,SendorEmail,r.RateTableId,ut.FileUploadTemplateID,AutoImportSettingID from tblAutoImportSetting as s
				inner join tblRateTable as r on s.TypePKID = r.RateTableId
				inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
				
				where 
					  CASE 
					  		WHEN (p_typePKID > 0 AND p_search <> '') THEN
							     s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
					  		WHEN (p_typePKID > 0) THEN
							     s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
							WHEN (p_search <> '') THEN

							    (  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 2				    				    
							ELSE						
								 s.CompanyID = p_CompanyID AND s.`Type`= 2
							
						END	
					ORDER BY
					  CASE WHEN p_lSortCol = 'RateTable' AND p_SortOrder = 'desc' THEN r.RateTableName END DESC,
					  CASE WHEN p_lSortCol = 'RateTable' THEN r.RateTableName END,
					  CASE WHEN p_lSortCol = 'Import File Template' AND p_SortOrder = 'desc' THEN ut.Title END DESC,
					  CASE WHEN p_lSortCol = 'Import File Template' THEN ut.Title END,
					  CASE WHEN p_lSortCol = 'Subject Match' AND p_SortOrder = 'desc' THEN Subject END DESC,
					  CASE WHEN p_lSortCol = 'Subject Match' THEN Subject END,
					  CASE WHEN p_lSortCol = 'Filename Match' AND p_SortOrder = 'desc' THEN FileName END DESC,
					  CASE WHEN p_lSortCol = 'Filename Match' THEN FileName END,	
					  CASE WHEN p_lSortCol = 'Sender Match' AND p_SortOrder = 'desc' THEN SendorEmail END DESC,
					  CASE WHEN p_lSortCol = 'Sender Match' THEN SendorEmail END
					  
				LIMIT p_RowspPage OFFSET v_OffSet_;
				
		ELSE
				
				
				select r.RateTableName,ut.Title,Subject,SendorEmail,FileName from tblAutoImportSetting as s
				inner join tblRateTable as r on s.TypePKID = r.RateTableId
				inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
				
				where 
					  CASE 
					  		WHEN (p_typePKID > 0 AND p_search <> '') THEN
							     s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
					  		WHEN (p_typePKID > 0) THEN
							     s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
							WHEN (p_search <> '') THEN

							    (  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 2				    				    
							ELSE						
								 s.CompanyID = p_CompanyID AND s.`Type`= 2
							
						END	
					ORDER BY
					  CASE WHEN p_lSortCol = 'RateTable' AND p_SortOrder = 'desc' THEN r.RateTableName END DESC,
					  CASE WHEN p_lSortCol = 'RateTable' THEN r.RateTableName END,
					  CASE WHEN p_lSortCol = 'Import File Template' AND p_SortOrder = 'desc' THEN ut.Title END DESC,
					  CASE WHEN p_lSortCol = 'Import File Template' THEN ut.Title END,
					  CASE WHEN p_lSortCol = 'Subject Match' AND p_SortOrder = 'desc' THEN Subject END DESC,
					  CASE WHEN p_lSortCol = 'Subject Match' THEN Subject END,
					  CASE WHEN p_lSortCol = 'Filename Match' AND p_SortOrder = 'desc' THEN FileName END DESC,
					  CASE WHEN p_lSortCol = 'Filename Match' THEN FileName END,	
					  CASE WHEN p_lSortCol = 'Sender Match' AND p_SortOrder = 'desc' THEN SendorEmail END DESC,
					  CASE WHEN p_lSortCol = 'Sender Match' THEN SendorEmail END
				;
				
		END IF;
		
	
		select COUNT(*) AS `totalcount` from tblAutoImportSetting as s
				inner join tblRateTable as r on s.TypePKID = r.RateTableId
				inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
				
				where 
					  CASE 
					  		WHEN (p_typePKID > 0 AND p_search <> '') THEN
							     s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
					  		WHEN (p_typePKID > 0) THEN
							     s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
							WHEN (p_search <> '') THEN
								(  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 2
							ELSE						
								 s.CompanyID = p_CompanyID AND s.`Type`= 2
							
						END	
				;
		

		
			
	END IF;

	
	
	
		
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_GetCustomerRate`;
DELIMITER //
CREATE PROCEDURE `prc_GetCustomerRate`(
	IN `p_companyid` INT,
	IN `p_AccountID` INT,
	IN `p_trunkID` INT,
	IN `p_contryID` INT,
	IN `p_code` VARCHAR(50),
	IN `p_description` VARCHAR(50),
	IN `p_Effective` VARCHAR(50),
	IN `p_CustomDate` DATE,
	IN `p_effectedRates` INT,
	IN `p_RoutinePlan` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN
   DECLARE v_codedeckid_ INT;
   DECLARE v_ratetableid_ INT;
   DECLARE v_RateTableAssignDate_ DATETIME;
   DECLARE v_NewA2ZAssign_ INT;
   DECLARE v_OffSet_ int;
   DECLARE v_IncludePrefix_ INT;
   DECLARE v_Prefix_ VARCHAR(50);
   DECLARE v_RatePrefix_ VARCHAR(50);
   DECLARE v_AreaPrefix_ VARCHAR(50);

   -- set custome date = current date if custom date is past date
   IF(p_CustomDate < DATE(NOW()))
	THEN
		SET p_CustomDate=DATE(NOW());
	END IF;

   SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
   SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

    SELECT
        CodeDeckId,
        RateTableID,
        RateTableAssignDate,IncludePrefix INTO v_codedeckid_, v_ratetableid_, v_RateTableAssignDate_,v_IncludePrefix_
    FROM tblCustomerTrunk
    WHERE CompanyID = p_companyid
    AND tblCustomerTrunk.TrunkID = p_trunkID
    AND tblCustomerTrunk.AccountID = p_AccountID
    AND tblCustomerTrunk.Status = 1;

    SELECT
        Prefix,RatePrefix,AreaPrefix INTO v_Prefix_,v_RatePrefix_,v_AreaPrefix_
    FROM tblTrunk
    WHERE CompanyID = p_companyid
    AND tblTrunk.TrunkID = p_trunkID
    AND tblTrunk.Status = 1;



    DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates_;
    CREATE TEMPORARY TABLE tmp_CustomerRates_ (
        RateID INT,
        Interval1 INT,
        IntervalN  INT,
        Rate DECIMAL(18, 6),
        ConnectionFee DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        CustomerRateId INT,
        RateTableRateID INT,
        TrunkID INT,
        RoutinePlan INT,
        INDEX tmp_CustomerRates__RateID (`RateID`),
        INDEX tmp_CustomerRates__TrunkID (`TrunkID`),
        INDEX tmp_CustomerRates__EffectiveDate (`EffectiveDate`)
    );
    DROP TEMPORARY TABLE IF EXISTS tmp_RateTableRate_;
    CREATE TEMPORARY TABLE tmp_RateTableRate_ (
        RateID INT,
        Interval1 INT,
        IntervalN INT,
        Rate DECIMAL(18, 6),
        ConnectionFee DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        CustomerRateId INT,
        RateTableRateID INT,
        TrunkID INT,
        INDEX tmp_RateTableRate__RateID (`RateID`),
        INDEX tmp_RateTableRate__TrunkID (`TrunkID`),
        INDEX tmp_RateTableRate__EffectiveDate (`EffectiveDate`)

    );

    DROP TEMPORARY TABLE IF EXISTS tmp_customerrate_;
    CREATE TEMPORARY TABLE tmp_customerrate_ (
        RateID INT,
        Code VARCHAR(50),
        Description VARCHAR(200),
        Interval1 INT,
        IntervalN INT,
        ConnectionFee DECIMAL(18, 6),
        RoutinePlanName VARCHAR(50),
        Rate DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        CustomerRateId INT,
        TrunkID INT,
        RateTableRateId INT,
        IncludePrefix TINYINT,
        Prefix VARCHAR(50),
        RatePrefix VARCHAR(50),
        AreaPrefix VARCHAR(50)
    );


    INSERT INTO tmp_CustomerRates_

            SELECT
                tblCustomerRate.RateID,
                tblCustomerRate.Interval1,
                tblCustomerRate.IntervalN,

                tblCustomerRate.Rate,
                tblCustomerRate.ConnectionFee,
                tblCustomerRate.EffectiveDate,
                tblCustomerRate.EndDate,
                tblCustomerRate.LastModifiedDate,
                tblCustomerRate.LastModifiedBy,
                tblCustomerRate.CustomerRateId,
                NULL AS RateTableRateID,
                p_trunkID as TrunkID,
                tblCustomerRate.RoutinePlan

            FROM tblCustomerRate
            INNER JOIN tblRate
                ON tblCustomerRate.RateID = tblRate.RateID
            WHERE (p_contryID IS NULL OR tblRate.CountryID = p_contryID)
            AND (p_code IS NULL OR Code LIKE REPLACE(p_code, '*', '%'))
            AND (p_description IS NULL OR tblRate.Description LIKE REPLACE(p_description, '*', '%'))
            AND (tblRate.CompanyID = p_companyid)
            AND tblRate.CodeDeckId = v_codedeckid_
            AND tblCustomerRate.TrunkID = p_trunkID
            AND (p_RoutinePlan = 0 or tblCustomerRate.RoutinePlan = p_RoutinePlan)
            AND CustomerID = p_AccountID

            ORDER BY
                tblCustomerRate.TrunkId, tblCustomerRate.CustomerId,tblCustomerRate.RateID,tblCustomerRate.EffectiveDate DESC;







	 	DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates4_;
			CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates4_ as (select * from tmp_CustomerRates_);
			DELETE n1 FROM tmp_CustomerRates_ n1, tmp_CustomerRates4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate
			AND n1.TrunkID = n2.TrunkID
			AND  n1.RateID = n2.RateID
			AND
			(
				(p_Effective = 'CustomDate' AND n1.EffectiveDate <= p_CustomDate AND n2.EffectiveDate <= p_CustomDate)
				OR
				(p_Effective != 'CustomDate' AND n1.EffectiveDate <= NOW() AND n2.EffectiveDate <= NOW())
			);

	 	DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates2_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates2_ as (select * from tmp_CustomerRates_);
		DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates3_;
	   CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates3_ as (select * from tmp_CustomerRates_);
	   DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates5_;
	   CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates5_ as (select * from tmp_CustomerRates_);

	   ALTER TABLE tmp_CustomerRates2_ ADD  INDEX tmp_CustomerRatesRateID (`RateID`);
	   ALTER TABLE tmp_CustomerRates3_ ADD  INDEX tmp_CustomerRatesRateID (`RateID`);
	   ALTER TABLE tmp_CustomerRates5_ ADD  INDEX tmp_CustomerRatesRateID (`RateID`);

	   ALTER TABLE tmp_CustomerRates2_ ADD  INDEX tmp_CustomerRatesEffectiveDate (`EffectiveDate`);
	   ALTER TABLE tmp_CustomerRates3_ ADD  INDEX tmp_CustomerRatesEffectiveDate (`EffectiveDate`);
	   ALTER TABLE tmp_CustomerRates5_ ADD  INDEX tmp_CustomerRatesEffectiveDate (`EffectiveDate`);

    INSERT INTO tmp_RateTableRate_
            SELECT
                tblRateTableRate.RateID,
                tblRateTableRate.Interval1,
                tblRateTableRate.IntervalN,
                tblRateTableRate.Rate,
                tblRateTableRate.ConnectionFee,

      			 tblRateTableRate.EffectiveDate,
      			 tblRateTableRate.EndDate,
                NULL AS LastModifiedDate,
                NULL AS LastModifiedBy,
                NULL AS CustomerRateId,
                tblRateTableRate.RateTableRateID,
                p_trunkID as TrunkID
            FROM tblRateTableRate
            INNER JOIN tblRate
                ON tblRateTableRate.RateID = tblRate.RateID
            WHERE (p_contryID IS NULL OR tblRate.CountryID = p_contryID)
            AND (p_code IS NULL OR Code LIKE REPLACE(p_code, '*', '%'))
            AND (p_description IS NULL OR tblRate.Description LIKE REPLACE(p_description, '*', '%'))
            AND (tblRate.CompanyID = p_companyid)
            AND tblRate.CodeDeckId = v_codedeckid_
            AND RateTableID = v_ratetableid_
            AND (
						(
							(SELECT count(*) from tmp_CustomerRates2_ cr where cr.RateID = tblRateTableRate.RateID) >0
							AND tblRateTableRate.EffectiveDate <
								( SELECT MIN(cr.EffectiveDate)
                          FROM tmp_CustomerRates_ as cr
                          WHERE cr.RateID = tblRateTableRate.RateID
								)
							AND (SELECT count(*) from tmp_CustomerRates5_ cr where cr.RateID = tblRateTableRate.RateID AND cr.EffectiveDate <= NOW() ) = 0
						)
						or  (  SELECT count(*) from tmp_CustomerRates3_ cr where cr.RateID = tblRateTableRate.RateID ) = 0
					)

                ORDER BY tblRateTableRate.RateTableId,tblRateTableRate.RateID,tblRateTableRate.effectivedate DESC;




		  DROP TEMPORARY TABLE IF EXISTS tmp_RateTableRate4_;
		  CREATE TEMPORARY TABLE IF NOT EXISTS tmp_RateTableRate4_ as (select * from tmp_RateTableRate_);
        DELETE n1 FROM tmp_RateTableRate_ n1, tmp_RateTableRate4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate
	 	  AND n1.TrunkID = n2.TrunkID
		  AND  n1.RateID = n2.RateID
		  AND
			(
				(p_Effective = 'CustomDate' AND n1.EffectiveDate <= p_CustomDate AND n2.EffectiveDate <= p_CustomDate)
				OR
				(p_Effective != 'CustomDate' AND n1.EffectiveDate <= NOW() AND n2.EffectiveDate <= NOW())
			);





		  INSERT INTO tmp_customerrate_
        SELECT
        			 r.RateID,
                r.Code,
                r.Description,
                CASE WHEN allRates.Interval1 IS NULL
                THEN
                    r.Interval1
                ELSE
                    allRates.Interval1
                END as Interval1,
                CASE WHEN allRates.IntervalN IS NULL
                THEN
                    r.IntervalN
                ELSE
                    allRates.IntervalN
                END  IntervalN,
                allRates.ConnectionFee,
                allRates.RoutinePlanName,
                allRates.Rate,
                allRates.EffectiveDate,
                allRates.EndDate,
                allRates.LastModifiedDate,
                allRates.LastModifiedBy,
                allRates.CustomerRateId,
                p_trunkID as TrunkID,
                allRates.RateTableRateId,
					v_IncludePrefix_ as IncludePrefix ,
   	         CASE  WHEN tblTrunk.TrunkID is not null
               THEN
               	tblTrunk.Prefix
               ELSE
               	v_Prefix_
					END AS Prefix,
					CASE  WHEN tblTrunk.TrunkID is not null
               THEN
               	tblTrunk.RatePrefix
               ELSE
               	v_RatePrefix_
					END AS RatePrefix,
					CASE  WHEN tblTrunk.TrunkID is not null
               THEN
               	tblTrunk.AreaPrefix
               ELSE
               	v_AreaPrefix_
					END AS AreaPrefix
        FROM tblRate r
        LEFT JOIN (SELECT
                CustomerRates.RateID,
                CustomerRates.Interval1,
                CustomerRates.IntervalN,
                tblTrunk.Trunk as RoutinePlanName,
                CustomerRates.ConnectionFee,
                CustomerRates.Rate,
                CustomerRates.EffectiveDate,
                CustomerRates.EndDate,
                CustomerRates.LastModifiedDate,
                CustomerRates.LastModifiedBy,
                CustomerRates.CustomerRateId,
                NULL AS RateTableRateID,
                p_trunkID as TrunkID,
                RoutinePlan
            FROM tmp_CustomerRates_ CustomerRates
            LEFT JOIN tblTrunk on tblTrunk.TrunkID = CustomerRates.RoutinePlan
            WHERE
                (
					 	( p_Effective = 'Now' AND CustomerRates.EffectiveDate <= NOW() )
					 	OR
					 	( p_Effective = 'Future' AND CustomerRates.EffectiveDate > NOW() )
						OR
						( p_Effective = 'CustomDate' AND CustomerRates.EffectiveDate <= p_CustomDate AND (CustomerRates.EndDate IS NULL OR CustomerRates.EndDate > p_CustomDate) )
					 	OR
						p_Effective = 'All'
					 )


            UNION ALL

            SELECT
            DISTINCT
                rtr.RateID,
                rtr.Interval1,
                rtr.IntervalN,
                NULL,
                rtr.ConnectionFee,
                rtr.Rate,
                rtr.EffectiveDate,
                rtr.EndDate,
                NULL,
                NULL,
                NULL AS CustomerRateId,
                rtr.RateTableRateID,
                p_trunkID as TrunkID,
                NULL AS RoutinePlan
            FROM tmp_RateTableRate_ AS rtr
            LEFT JOIN tmp_CustomerRates2_ as cr
                ON cr.RateID = rtr.RateID AND
						 (
						 	( p_Effective = 'Now' AND cr.EffectiveDate <= NOW() )
						 	OR
						 	( p_Effective = 'Future' AND cr.EffectiveDate > NOW())
						 	OR
							( p_Effective = 'CustomDate' AND cr.EffectiveDate <= p_CustomDate AND (cr.EndDate IS NULL OR cr.EndDate > p_CustomDate) )
						 	OR
							 p_Effective = 'All'
						 )
            WHERE (
                (
                    p_Effective = 'Now' AND rtr.EffectiveDate <= NOW()
                    AND (
                            (cr.RateID IS NULL)
                            OR
                            (cr.RateID IS NOT NULL AND rtr.RateTableRateID IS NULL)
                        )

                )
                OR
                ( p_Effective = 'Future' AND rtr.EffectiveDate > NOW()
                    AND (
                            (cr.RateID IS NULL)
                            OR
                            (
                                cr.RateID IS NOT NULL AND rtr.EffectiveDate < (
                                                                                SELECT IFNULL(MIN(crr.EffectiveDate), rtr.EffectiveDate)
                                                                                FROM tmp_CustomerRates3_ as crr
                                                                                WHERE crr.RateID = rtr.RateID
                                                                                )
                            )
                        )
                )
				OR
				(
					p_Effective = 'CustomDate' AND rtr.EffectiveDate <= p_CustomDate AND (rtr.EndDate IS NULL OR rtr.EndDate > p_CustomDate)
					AND (
                            (cr.RateID IS NULL)
                            OR
                            (cr.RateID IS NOT NULL AND rtr.RateTableRateID IS NULL)
                        )
				)
            OR p_Effective = 'All'

            )

				) allRates
            ON allRates.RateID = r.RateID
         LEFT JOIN tblTrunk on tblTrunk.TrunkID = RoutinePlan
        WHERE (p_contryID IS NULL OR r.CountryID = p_contryID)
        AND (p_code IS NULL OR Code LIKE REPLACE(p_code, '*', '%'))
        AND (p_description IS NULL OR r.Description LIKE REPLACE(p_description, '*', '%'))
        AND (r.CompanyID = p_companyid)
        AND r.CodeDeckId = v_codedeckid_
        AND  ((p_effectedRates = 1 AND Rate IS NOT NULL) OR  (p_effectedRates = 0));




    IF p_isExport = 0
    THEN


         SELECT
                RateID,
                Code,
                Description,
                Interval1,
                IntervalN,
                ConnectionFee,
                RoutinePlanName,
                Rate,
                EffectiveDate,
                EndDate,
                LastModifiedDate,
                LastModifiedBy,
                CustomerRateId,
                TrunkID,
                RateTableRateId
            FROM tmp_customerrate_
            ORDER BY
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN Rate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN Rate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN Interval1
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN Interval1
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN IntervalN
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN IntervalN
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ConnectionFee
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ConnectionFee
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN EffectiveDate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN EffectiveDate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN EndDate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN EndDate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'LastModifiedDateDESC') THEN LastModifiedDate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'LastModifiedDateASC') THEN LastModifiedDate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'LastModifiedByDESC') THEN LastModifiedBy
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'LastModifiedByASC') THEN LastModifiedBy
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CustomerRateIdDESC') THEN CustomerRateId
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CustomerRateIdASC') THEN CustomerRateId
                END ASC
            LIMIT p_RowspPage OFFSET v_OffSet_;

        SELECT
            COUNT(RateID) AS totalcount
        FROM tmp_customerrate_;

    END IF;

    IF p_isExport = 1
    THEN

          select
            Code,
            Description,
            Interval1,
            IntervalN,
            ConnectionFee,
            Rate,
            EffectiveDate,
            LastModifiedDate,
            LastModifiedBy from tmp_customerrate_;

    END IF;


	IF p_isExport = 2
    THEN

          select
            Code,
            Description,
            Interval1,
            IntervalN,
            ConnectionFee,
            Rate,
            EffectiveDate from tmp_customerrate_;

    END IF;


    SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_GetCustomerRatesArchiveGrid`;
DELIMITER //
CREATE PROCEDURE `prc_GetCustomerRatesArchiveGrid`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` INT,
	IN `p_Codes` LONGTEXT
)
BEGIN
	SELECT
	--	cra.CustomerRateArchiveID,
	--	cra.CustomerRateID,
	--	cra.AccountID,
		r.Code,
		r.Description,
		IFNULL(cra.ConnectionFee,'') AS ConnectionFee,
		CASE WHEN cra.Interval1 IS NOT NULL THEN cra.Interval1 ELSE r.Interval1 END AS Interval1,
		CASE WHEN cra.IntervalN IS NOT NULL THEN cra.IntervalN ELSE r.IntervalN END AS IntervalN,
		cra.Rate,
		cra.EffectiveDate,
		IFNULL(cra.EndDate,'') AS EndDate,
		IFNULL(cra.created_at,'') AS ModifiedDate,
		IFNULL(cra.created_by,'') AS ModifiedBy
	FROM
		tblCustomerRateArchive cra
	JOIN
		tblRate r ON r.RateID=cra.RateId
	WHERE
		r.CompanyID = p_CompanyID AND
		cra.AccountId = p_AccountID AND
		FIND_IN_SET (r.Code, p_Codes) != 0
	ORDER BY
		cra.EffectiveDate DESC, cra.created_at DESC;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_getDiscontinuedCustomerRateGrid`;
DELIMITER //
CREATE PROCEDURE `prc_getDiscontinuedCustomerRateGrid`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` INT,
	IN `p_TrunkID` INT,
	IN `p_CountryID` INT,
	IN `p_Code` VARCHAR(50),
	IN `p_Description` VARCHAR(50),
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRate_;
	CREATE TEMPORARY TABLE tmp_CustomerRate_ (
		RateID INT,
		Code VARCHAR(50),
		Description VARCHAR(200),
		Interval1 INT,
		IntervalN INT,
		ConnectionFee VARCHAR(50),
		RoutinePlanName VARCHAR(50),
		Rate DECIMAL(18, 6),
		EffectiveDate DATE,
		EndDate DATE,
		updated_at DATETIME,
		updated_by VARCHAR(50),
		CustomerRateID INT,
		TrunkID INT,
        RateTableRateId INT,
		INDEX tmp_CustomerRate_RateID (`Code`)
	);

	INSERT INTO tmp_CustomerRate_
	SELECT
		cra.RateId,
		r.Code,
		r.Description,
		CASE WHEN cra.Interval1 IS NOT NULL THEN cra.Interval1 ELSE r.Interval1 END AS Interval1,
		CASE WHEN cra.IntervalN IS NOT NULL THEN cra.IntervalN ELSE r.IntervalN END AS IntervalN,
		'' AS ConnectionFee,
		cra.RoutinePlan AS RoutinePlanName,
		cra.Rate,
		cra.EffectiveDate,
		cra.EndDate,
		cra.created_at AS updated_at,
		cra.created_by AS updated_by,
		cra.CustomerRateID,
		p_trunkID AS TrunkID,
		NULL AS RateTableRateID
	FROM
		tblCustomerRateArchive cra
	JOIN
		tblRate r ON r.RateID=cra.RateId
	LEFT JOIN
		tblCustomerRate cr ON cr.CustomerID = cra.AccountId AND cr.TrunkID = cra.TrunkID AND cr.RateId = cra.RateId
	WHERE
		r.CompanyID = p_CompanyID AND
		cra.TrunkID = p_TrunkID AND
		cra.AccountId = p_AccountID AND
		(p_CountryID IS NULL OR r.CountryID = p_CountryID) AND
		(p_code IS NULL OR r.Code LIKE REPLACE(p_code, '*', '%')) AND
		(p_description IS NULL OR r.Description LIKE REPLACE(p_description, '*', '%')) AND
		cr.CustomerRateID is NULL;

	IF p_isExport = 0
	THEN
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRate2_ as (select * from tmp_CustomerRate_);
		DELETE
			n1
		FROM
			tmp_CustomerRate_ n1, tmp_CustomerRate2_ n2
		WHERE
			n1.Code = n2.Code AND n1.CustomerRateID < n2.CustomerRateID;

		SELECT
			RateID,
			Code,
			Description,
			Interval1,
			IntervalN,
			ConnectionFee,
			RoutinePlanName,
			Rate,
			EffectiveDate,
			EndDate,
			updated_at,
			updated_by,
			CustomerRateId,
			TrunkID,
			RateTableRateId
		FROM
			tmp_CustomerRate_
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN Rate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN Rate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ConnectionFee
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ConnectionFee
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN Interval1
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN Interval1
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN IntervalN
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN IntervalN
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN EffectiveDate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN EffectiveDate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN EndDate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN EndDate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atDESC') THEN updated_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atASC') THEN updated_at
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byDESC') THEN updated_by
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byASC') THEN updated_by
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CustomerRateIDDESC') THEN CustomerRateID
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CustomerRateIDASC') THEN CustomerRateID
			END ASC
		LIMIT
			p_RowspPage
			OFFSET
			v_OffSet_;

		SELECT
			COUNT(code) AS totalcount
		FROM tmp_CustomerRate_;

	END IF;

	IF p_isExport = 1
	THEN
		SELECT
			Code,
			Description,
			Rate,
			EffectiveDate,
			EndDate,
			updated_at AS `Modified Date`,
			updated_by AS `Modified By`
		FROM tmp_CustomerRate_;
	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_getDiscontinuedRateTableRateGrid`;
DELIMITER //
CREATE PROCEDURE `prc_getDiscontinuedRateTableRateGrid`(
	IN `p_CompanyID` INT,
	IN `p_RateTableID` INT,
	IN `p_CountryID` INT,
	IN `p_Code` VARCHAR(50),
	IN `p_Description` VARCHAR(50),
	IN `p_View` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	SET SESSION GROUP_CONCAT_MAX_LEN = 1000000; -- group_concat limit bydefault is 1024, so we have increase it

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	DROP TEMPORARY TABLE IF EXISTS tmp_RateTableRate_;
	CREATE TEMPORARY TABLE tmp_RateTableRate_ (
		RateTableRateID INT,
		Code VARCHAR(50),
		Description VARCHAR(200),
		Interval1 INT,
		IntervalN INT,
		ConnectionFee VARCHAR(50),
		PreviousRate DECIMAL(18, 6),
		Rate DECIMAL(18, 6),
		EffectiveDate DATE,
		EndDate DATE,
		updated_at DATETIME,
		updated_by VARCHAR(50),
		INDEX tmp_RateTableRate_RateID (`Code`)
	);

	INSERT INTO tmp_RateTableRate_
	SELECT
		vra.RateTableRateID,
		r.Code,
		r.Description,
		CASE WHEN vra.Interval1 IS NOT NULL THEN vra.Interval1 ELSE r.Interval1 END AS Interval1,
		CASE WHEN vra.IntervalN IS NOT NULL THEN vra.IntervalN ELSE r.IntervalN END AS IntervalN,
		'' AS ConnectionFee,
		null AS PreviousRate,
		vra.Rate,
		vra.EffectiveDate,
		vra.EndDate,
		vra.created_at AS updated_at,
		vra.created_by AS updated_by
	FROM
		tblRateTableRateArchive vra
	JOIN
		tblRate r ON r.RateID=vra.RateId
	LEFT JOIN
		tblRateTableRate vr ON vr.RateTableId = vra.RateTableId AND vr.RateId = vra.RateId
	WHERE
		r.CompanyID = p_CompanyID AND
		vra.RateTableId = p_RateTableID AND
		(p_CountryID IS NULL OR r.CountryID = p_CountryID) AND
		(p_code IS NULL OR r.Code LIKE REPLACE(p_code, '*', '%')) AND
		(p_description IS NULL OR r.Description LIKE REPLACE(p_description, '*', '%')) AND
		vr.RateTableRateID is NULL;

	IF p_isExport = 0
	THEN
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_RateTableRate2_ as (select * from tmp_RateTableRate_);
		DELETE
			n1
		FROM
			tmp_RateTableRate_ n1, tmp_RateTableRate2_ n2
		WHERE
			n1.Code = n2.Code AND n1.RateTableRateID < n2.RateTableRateID;

		IF p_view = 1
		THEN
			SELECT
				RateTableRateID,
				Code,
				Description,
				Interval1,
				IntervalN,
				ConnectionFee,
				PreviousRate,
				Rate,
				EffectiveDate,
				EndDate,
				updated_at,
				updated_by
			FROM
				tmp_RateTableRate_
			ORDER BY
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN Rate
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN Rate
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ConnectionFee
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ConnectionFee
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN Interval1
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN Interval1
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN IntervalN
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN IntervalN
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN EffectiveDate
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN EffectiveDate
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN EndDate
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN EndDate
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atDESC') THEN updated_at
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atASC') THEN updated_at
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byDESC') THEN updated_by
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byASC') THEN updated_by
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDDESC') THEN RateTableRateID
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDASC') THEN RateTableRateID
				END ASC
			LIMIT
				p_RowspPage
			OFFSET
				v_OffSet_;

			SELECT
				COUNT(code) AS totalcount
			FROM tmp_RateTableRate_;

		ELSE

			SELECT
				group_concat(RateTableRateID) AS RateTableRateID,
				group_concat(Code),
				Description,
				ConnectionFee,
				Interval1,
				IntervalN,
				ANY_VALUE(PreviousRate),
				Rate,
				EffectiveDate,
				EndDate,
				MAX(updated_at),
				MAX(updated_by)
			FROM
				tmp_RateTableRate_
			GROUP BY
				Description, Interval1, Intervaln, ConnectionFee, Rate, EffectiveDate, EndDate
			ORDER BY
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN ANY_VALUE(Description)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN ANY_VALUE(Description)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN ANY_VALUE(Rate)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN ANY_VALUE(Rate)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ANY_VALUE(ConnectionFee)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ANY_VALUE(ConnectionFee)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN ANY_VALUE(Interval1)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN ANY_VALUE(Interval1)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN ANY_VALUE(IntervalN)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN ANY_VALUE(IntervalN)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN ANY_VALUE(EffectiveDate)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN ANY_VALUE(EffectiveDate)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN ANY_VALUE(EndDate)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN ANY_VALUE(EndDate)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atDESC') THEN ANY_VALUE(updated_at)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atASC') THEN ANY_VALUE(updated_at)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byDESC') THEN ANY_VALUE(updated_by)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byASC') THEN ANY_VALUE(updated_by)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDDESC') THEN ANY_VALUE(RateTableRateID)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDASC') THEN ANY_VALUE(RateTableRateID)
				END ASC
			LIMIT
				p_RowspPage
			OFFSET
				v_OffSet_;


			SELECT COUNT(*) AS `totalcount`
			FROM (
				SELECT
	            Description
	        	FROM tmp_RateTableRate_
					GROUP BY Description, Interval1, Intervaln, ConnectionFee, Rate, EffectiveDate, EndDate
			) totalcount;

		END IF;

	END IF;

	IF p_isExport = 1
	THEN
		SELECT
			Code,
			Description,
			Rate,
			EffectiveDate,
			EndDate,
			updated_at AS `Modified Date`,
			updated_by AS `Modified By`
		FROM tmp_RateTableRate_;
	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_GetFileUploadTemplates`;
DELIMITER //
CREATE PROCEDURE `prc_GetFileUploadTemplates`(
	IN `p_CompanyID` INT,
	IN `p_Title` VARCHAR(255),
	IN `p_Type` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_IsExport` INT
)
BEGIN
	DECLARE v_OffSet_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	IF p_IsExport = 0
	THEN
		SELECT
			t.`Title` AS TemplateName,
			tt.`Title` AS TemplateType,
			t.`created_at`,
			t.`FileUploadTemplateID`
		FROM
			tblFileUploadTemplate t
		LEFT JOIN
			tblFileUploadTemplateType tt ON t.FileUploadTemplateTypeID=tt.FileUploadTemplateTypeID
		WHERE
			t.CompanyID = p_CompanyID AND
			(p_Title IS NULL OR t.Title LIKE REPLACE(p_Title, '*', '%')) AND
			(p_Type IS NULL OR t.FileUploadTemplateTypeID = p_Type)
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleASC') THEN t.Title
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleDESC') THEN t.Title
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TypeASC') THEN tt.Title
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TypeDESC') THEN tt.Title
			END DESC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		-- total counts for datatable
		SELECT
			COUNT(t.Title) AS totalcount
		FROM
			tblFileUploadTemplate t
		LEFT JOIN
			tblFileUploadTemplateType tt ON t.FileUploadTemplateTypeID=tt.FileUploadTemplateTypeID
		WHERE
			t.CompanyID = p_CompanyID AND
			(p_Title IS NULL OR t.Title LIKE REPLACE(p_Title, '*', '%')) AND
			(p_Type IS NULL OR t.FileUploadTemplateTypeID = p_Type);

	END IF;

	IF p_IsExport = 1
	THEN
		SELECT
			t.`Title` AS TemplateName,
			tt.`Title` AS TemplateType,
			t.`created_at`
		FROM
			tblFileUploadTemplate t
		LEFT JOIN
			tblFileUploadTemplateType tt ON t.FileUploadTemplateTypeID=tt.FileUploadTemplateTypeID
		WHERE
			t.CompanyID = p_CompanyID;
	END IF;

END//
DELIMITER ;

DROP PROCEDURE IF EXISTS `prc_getRateTableByAccount`;
DELIMITER //
CREATE PROCEDURE `prc_getRateTableByAccount`(
	IN `p_companyid` INT,
	IN `p_level` VARCHAR(1),
	IN `p_trunkid` INT,
	IN `p_currency` INT,
	IN `p_ratetableId` INT,
	IN `p_AccountIds` TEXT,
	IN `p_services` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT


)
BEGIN

			DECLARE v_OffSet_ int;

			SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

			SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
			
			DROP TEMPORARY TABLE IF EXISTS tmp_in;
					CREATE TEMPORARY TABLE tmp_in (
						CompanyID INT ,
						AccountID INT,
						ServiceID INT ,
						RateTableID INT,
						InBoundRateTableName VARCHAR(100),
						Type INT
					);
					
			DROP TEMPORARY TABLE IF EXISTS tmp_out;
					CREATE TEMPORARY TABLE tmp_out (
						CompanyID INT ,
						AccountID INT,
						ServiceID INT ,
						RateTableID INT,
						OutBoundRateTableName VARCHAR(100),
						Type INT
					);

			DROP TEMPORARY TABLE IF EXISTS tmp_acc2;
					CREATE TEMPORARY TABLE tmp_acc2 (
						CompanyID INT ,
						AccountID INT,
						ServiceID INT ,
						RateTableID INT,
						Type INT,
						InBountRateTableID INT,
						OutBountRateTableID INT
					);

			DROP TEMPORARY TABLE IF EXISTS tmp_AccountServiceRateTable;
					CREATE TEMPORARY TABLE tmp_AccountServiceRateTable (
						AccountID INT,
						AccountName VARCHAR(100) ,
						InBoundRateTableName VARCHAR(100),			
						OutBoundRateTableName VARCHAR(100),	
						ServiceName VARCHAR(200),				
						ServiceID INT ,
						CurrencyId INT,	
						InBountRateTableID INT,
						OutBountRateTableID INT
						
					);

	/*
		p_level = 'S'  -- Service 
		p_level = 'T'  -- Trunk 
		
			*/
			
			IF (p_level="S") 
			THEN
			 
			 	/*
				Get service wise rate table 
			*/
			
			/*
			
			1. Get account with service 
			2. update service Inbound
			3  update service outbound
			4  update rate table name 
			
			*/
			 	-- 1
				insert into tmp_AccountServiceRateTable (AccountID,AccountName,ServiceName,ServiceID,CurrencyId)
				select distinct a.AccountID,a.AccountName,s.ServiceName,ass.ServiceID,a.CurrencyId 
				from  tblAccount a 
				left join tblAccountService ass  on a.AccountID=ass.AccountID
				left join tblService s on ass.ServiceID=s.ServiceID
				where a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1 AND s.`Status`=1;
			
				 
				-- 2  (Type 2 = Inbound Update)
			 
				update tmp_AccountServiceRateTable ft 
				left join tblAccountTariff att on ft.AccountID = att.AccountID AND ft.ServiceID = att.ServiceID 
				set ft.InBountRateTableID=att.RateTableID
				where att.`Type`=2 AND att.AccountTariffID is not null  ;
				
				
				-- 3 (Type 1 = Outbound Update)
				update tmp_AccountServiceRateTable ft 
				left join tblAccountTariff att on ft.AccountID = att.AccountID AND ft.ServiceID = att.ServiceID 
				set ft.OutBountRateTableID=att.RateTableID
				where att.`Type`=1 AND att.AccountTariffID is not null  ;
				
				 
				-- 4  Update Rate TAble name
				update tmp_AccountServiceRateTable ft 
				inner join tblRateTable rt on ft.InBountRateTableID=rt.RateTableId
				set ft.InBoundRateTableName=rt.RateTableName;
		 	 
		 	 
				update tmp_AccountServiceRateTable ft 
				inner join tblRateTable rt on ft.OutBountRateTableID=rt.RateTableId
				set ft.OutBoundRateTableName=rt.RateTableName;
				
					IF p_isExport = 0
					THEN 
					
						select *  from tmp_AccountServiceRateTable ft
						where
								  CASE 
										WHEN (p_ratetableId > 0 AND p_services > 0) THEN
										    ft.ServiceID=p_services AND (ft.InBountRateTableID=p_ratetableId OR ft.OutBountRateTableID=p_ratetableId)
										    
										WHEN (p_services > 0) THEN
											 ft.ServiceID=p_services 
										 
									   WHEN (p_ratetableId > 0) THEN
										    (InBountRateTableID=p_ratetableId OR ft.OutBountRateTableID=p_ratetableId)
									   ELSE						
											 ft.AccountName IS NOT NULL 																
									END									 
								 AND  (p_AccountIds='' OR FIND_IN_SET(ft.AccountID,p_AccountIds) != 0 )	AND ft.CurrencyId=p_currency				 
						
						 ORDER BY
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN AccountName
						 END ASC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN AccountName
						 END DESC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'InBoundRateTableNameASC') THEN InBoundRateTableName
						 END ASC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'InBoundRateTableNameDESC') THEN InBoundRateTableName
						 END DESC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutBoundRateTableNameASC') THEN OutBoundRateTableName
						 END ASC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutBoundRateTableNameDESC') THEN OutBoundRateTableName
						 END DESC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ServiceNameASC') THEN ServiceName
						 END ASC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ServiceNameDESC') THEN ServiceName
						 END DESC
						 
						 				 
						LIMIT p_RowspPage OFFSET v_OffSet_; 
					 
						
						
						SELECT COUNT(*) AS `totalcount` FROM tmp_AccountServiceRateTable ft
						where
								  CASE 
										WHEN (p_ratetableId > 0 AND p_services > 0) THEN
										    ft.ServiceID=p_services AND (ft.InBountRateTableID=p_ratetableId OR ft.OutBountRateTableID=p_ratetableId)
										    
										WHEN (p_services > 0) THEN
											 ft.ServiceID=p_services 
										 
									   WHEN (p_ratetableId > 0) THEN
										    (InBountRateTableID=p_ratetableId OR ft.OutBountRateTableID=p_ratetableId)
									   ELSE						
											 ft.AccountName IS NOT NULL 																
									END									 
								 AND  (p_AccountIds='' OR FIND_IN_SET(ft.AccountID,p_AccountIds) != 0 ) AND ft.CurrencyId=p_currency;
				
					 
				   ELSE 
					
						select AccountName,InBoundRateTableName,OutBoundRateTableName,ServiceName  from tmp_AccountServiceRateTable ft
						where
								  CASE 
										WHEN (p_ratetableId > 0 AND p_services > 0) THEN
										    ft.ServiceID=p_services AND (ft.InBountRateTableID=p_ratetableId OR ft.OutBountRateTableID=p_ratetableId)
										    
										WHEN (p_services > 0) THEN
											 ft.ServiceID=p_services 
										 
									   WHEN (p_ratetableId > 0) THEN
										    (InBountRateTableID=p_ratetableId OR ft.OutBountRateTableID=p_ratetableId)
									   ELSE						
											 ft.AccountName IS NOT NULL 																
									END									 
								 AND  (p_AccountIds='' OR FIND_IN_SET(ft.AccountID,p_AccountIds) != 0 )	AND ft.CurrencyId=p_currency				 
						
						 ORDER BY
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN AccountName
						 END ASC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN AccountName
						 END DESC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'InBoundRateTableNameASC') THEN InBoundRateTableName
						 END ASC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'InBoundRateTableNameDESC') THEN InBoundRateTableName
						 END DESC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutBoundRateTableNameASC') THEN OutBoundRateTableName
						 END ASC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutBoundRateTableNameDESC') THEN OutBoundRateTableName
						 END DESC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ServiceNameASC') THEN ServiceName
						 END ASC,
						 CASE
								WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ServiceNameDESC') THEN ServiceName
						 END DESC
						 ;
					
					END IF;
			
				
					
			ELSE
			
			/*
			Get trunk wise rate table 
			*/
					/*
					select a.AccountID,a.AccountName,t.CustomerTrunkID,t.TrunkID from 
					tblAccount a
					left join tblCustomerTrunk t on t.AccountID=a.AccountID
					where a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1; */

					IF p_isExport = 0
					THEN 
						

					
								select distinct a.AccountID,a.AccountName,r.RateTableName,t.Trunk,r.RateTableId,t.TrunkID,ct.`Status` from tblAccount a
								join tblTrunk t
								left join tblCustomerTrunk ct on a.AccountID=ct.AccountID AND t.TrunkID=ct.TrunkID								
								left join tblRateTable r on ct.RateTableID=r.RateTableId
								
								where 
								CASE 
									WHEN (p_ratetableId > 0 AND p_trunkid > 0) THEN
									    r.TrunkID=p_trunkid AND
										 r.RateTableId=p_ratetableId AND
									    a.CompanyId=p_companyid 
									    
									WHEN (p_trunkid > 0) THEN
										 t.TrunkID=p_trunkid AND
										 a.CompanyId=p_companyid 
									 
								   WHEN (p_ratetableId > 0) THEN
									    r.RateTableId=p_ratetableId AND
									    a.CompanyId=p_companyid 
								   ELSE						
										 a.CompanyId=p_companyid 					
									
								END
								AND (p_AccountIds='' OR FIND_IN_SET(a.AccountID,p_AccountIds) != 0 )
								AND a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1
								AND a.CurrencyId=p_currency AND t.`Status`=1
								
								ORDER BY	
													
								CASE
									WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN AccountName
								END ASC,
								CASE
											WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN AccountName
								END DESC,
								CASE
									WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'InBoundRateTableNameASC') THEN r.RateTableName
								END ASC,
								CASE
											WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'InBoundRateTableNameDESC') THEN r.RateTableName
								END DESC,
								CASE
									WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutRateTableNameASC') THEN t.Trunk
								END ASC,
								CASE
											WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutRateTableNameDESC') THEN t.Trunk
								END DESC , r.RateTableName DESC , t.Trunk ASC
														 
								LIMIT p_RowspPage OFFSET v_OffSet_;
							
								
								
								
								select  COUNT(*) AS `totalcount` from  tblAccount a
								join tblTrunk t
								left join tblCustomerTrunk ct on a.AccountID=ct.AccountID AND t.TrunkID=ct.TrunkID								
								left join tblRateTable r on ct.RateTableID=r.RateTableId
								
								where 
								CASE 
									WHEN (p_ratetableId > 0 AND p_trunkid > 0) THEN
									    r.TrunkID=p_trunkid AND
										 r.RateTableId=p_ratetableId AND
									    a.CompanyId=p_companyid AND a.IsCustomer=1 
									    
									WHEN (p_trunkid > 0) THEN
										 t.TrunkID=p_trunkid AND
										 a.CompanyId=p_companyid AND a.IsCustomer=1 
									 
								   WHEN (p_ratetableId > 0) THEN
									    r.RateTableId=p_ratetableId AND
									    a.CompanyId=p_companyid AND a.IsCustomer=1
								   ELSE						
										 a.CompanyId=p_companyid AND a.IsCustomer=1 					
									
								END
								AND (p_AccountIds='' OR FIND_IN_SET(a.AccountID,p_AccountIds) != 0 )
								AND a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1
								AND a.CurrencyId=p_currency  AND t.`Status`=1 ;
								 
								
							
								
								
					ELSE
					
								
								select distinct a.AccountName,r.RateTableName,t.Trunk, 
								CASE WHEN (ct.`Status`=1) THEN 'Active' ELSE 'Inactive' END As Statuss from tblAccount a
								join tblTrunk t
								left join tblCustomerTrunk ct on a.AccountID=ct.AccountID AND t.TrunkID=ct.TrunkID								
								left join tblRateTable r on ct.RateTableID=r.RateTableId
								where 
								CASE 
									WHEN (p_ratetableId > 0 AND p_trunkid > 0) THEN
									    r.TrunkID=p_trunkid AND
										 r.RateTableId=p_ratetableId AND
									    a.CompanyId=p_companyid  
									    
									WHEN (p_trunkid > 0) THEN
										 r.TrunkID=p_trunkid AND
										 a.CompanyId=p_companyid 
									 
								   WHEN (p_ratetableId > 0) THEN
									    r.RateTableId=p_ratetableId AND
									    a.CompanyId=p_companyid 
								   ELSE						
										 a.CompanyId=p_companyid				
									
								END
								AND (p_AccountIds='' OR FIND_IN_SET(a.AccountID,p_AccountIds) != 0 )
								AND a.IsCustomer=1 AND a.`Status`=1 AND a.AccountType=1
								AND a.CurrencyId=p_currency AND t.`Status`=1
								
								ORDER BY						
								CASE
									WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN AccountName
								END ASC,
								CASE
											WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN AccountName
								END DESC,
								CASE
									WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'InBoundRateTableNameASC') THEN r.RateTableName
								END ASC,
								CASE
											WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'InBoundRateTableNameDESC') THEN r.RateTableName
								END DESC,
								CASE
									WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutBoundRateTableNameASC') THEN t.Trunk
								END ASC,
								CASE
											WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutBoundRateTableNameDESC') THEN t.Trunk 
								END DESC
								;
								
								
					END IF;				
						
											
					
			END IF;

SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_GetRateTableRate`;
DELIMITER //
CREATE PROCEDURE `prc_GetRateTableRate`(
	IN `p_companyid` INT,
	IN `p_RateTableId` INT,
	IN `p_trunkID` INT,
	IN `p_contryID` INT,
	IN `p_code` VARCHAR(50),
	IN `p_description` VARCHAR(50),
	IN `p_effective` VARCHAR(50),
	IN `p_view` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	SET SESSION GROUP_CONCAT_MAX_LEN = 1000000; -- group_concat limit bydefault is 1024, so we have increase it
--	SET sql_mode = '';
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	DROP TEMPORARY TABLE IF EXISTS tmp_RateTableRate_;
   CREATE TEMPORARY TABLE tmp_RateTableRate_ (
        ID INT,
        Code VARCHAR(50),
        Description VARCHAR(200),
        Interval1 INT,
        IntervalN INT,
		  ConnectionFee DECIMAL(18, 6),
        PreviousRate DECIMAL(18, 6),
        Rate DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        updated_at DATETIME,
        ModifiedBy VARCHAR(50),
        RateTableRateID INT,
        RateID INT,
        INDEX tmp_RateTableRate_RateID (`RateID`)
    );



    INSERT INTO tmp_RateTableRate_
    SELECT
        RateTableRateID AS ID,
        Code,
        Description,
        ifnull(tblRateTableRate.Interval1,1) as Interval1,
        ifnull(tblRateTableRate.IntervalN,1) as IntervalN,
		  tblRateTableRate.ConnectionFee,
        null as PreviousRate,
        IFNULL(tblRateTableRate.Rate, 0) as Rate,
        IFNULL(tblRateTableRate.EffectiveDate, NOW()) as EffectiveDate,
        tblRateTableRate.EndDate,
        tblRateTableRate.updated_at,
        tblRateTableRate.ModifiedBy,
        RateTableRateID,
        tblRate.RateID
    FROM tblRate
    LEFT JOIN tblRateTableRate
        ON tblRateTableRate.RateID = tblRate.RateID
        AND tblRateTableRate.RateTableId = p_RateTableId
    INNER JOIN tblRateTable
        ON tblRateTable.RateTableId = tblRateTableRate.RateTableId
    WHERE		(tblRate.CompanyID = p_companyid)
		AND (p_contryID is null OR CountryID = p_contryID)
		AND (p_code is null OR Code LIKE REPLACE(p_code, '*', '%'))
		AND (p_description is null OR Description LIKE REPLACE(p_description, '*', '%'))
		AND TrunkID = p_trunkID
		AND (
			p_effective = 'All'
		OR (p_effective = 'Now' AND EffectiveDate <= NOW() )
		OR (p_effective = 'Future' AND EffectiveDate > NOW())
			);

	  IF p_effective = 'Now'
		THEN
		   CREATE TEMPORARY TABLE IF NOT EXISTS tmp_RateTableRate4_ as (select * from tmp_RateTableRate_);
         DELETE n1 FROM tmp_RateTableRate_ n1, tmp_RateTableRate4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate
		   AND  n1.RateID = n2.RateID;
		END IF;

	-- update Previous Rates
	UPDATE
		tmp_RateTableRate_ tr
	SET
		PreviousRate = (SELECT Rate FROM tblRateTableRate WHERE RateTableID=p_RateTableId AND RateID=tr.RateID AND Code=tr.Code AND EffectiveDate<tr.EffectiveDate ORDER BY EffectiveDate DESC,RateTableRateID DESC LIMIT 1);

	UPDATE
		tmp_RateTableRate_ tr
	SET
		PreviousRate = (SELECT Rate FROM tblRateTableRateArchive WHERE RateTableID=p_RateTableId AND RateID=tr.RateID AND Code=tr.Code AND EffectiveDate<tr.EffectiveDate ORDER BY EffectiveDate DESC,RateTableRateID DESC LIMIT 1)
	WHERE
		PreviousRate is null;

    IF p_isExport = 0
    THEN

		IF p_view = 1
		THEN
       	SELECT * FROM tmp_RateTableRate_
					ORDER BY CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PreviousRateDESC') THEN PreviousRate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PreviousRateASC') THEN PreviousRate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN Rate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN Rate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN Interval1
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN Interval1
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN Interval1
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN Interval1
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN EffectiveDate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN EffectiveDate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN EndDate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN EndDate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atDESC') THEN updated_at
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atASC') THEN updated_at
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byDESC') THEN ModifiedBy
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byASC') THEN ModifiedBy
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDDESC') THEN RateTableRateID
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDASC') THEN RateTableRateID
                END ASC,
				    CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ConnectionFee
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ConnectionFee
                END ASC
			LIMIT p_RowspPage OFFSET v_OffSet_;

			SELECT
            COUNT(RateID) AS totalcount
        	FROM tmp_RateTableRate_;

		ELSE
			SELECT group_concat(ID) AS ID, group_concat(Code) AS Code,ANY_VALUE(Description),ANY_VALUE(Interval1),ANY_VALUE(Intervaln),ANY_VALUE(ConnectionFee),ANY_VALUE(PreviousRate),ANY_VALUE(Rate),ANY_VALUE(EffectiveDate),ANY_VALUE(EndDate),MAX(updated_at) AS updated_at,MAX(ModifiedBy) AS ModifiedBy,group_concat(ID) AS RateTableRateID,group_concat(RateID) AS RateID FROM tmp_RateTableRate_
					GROUP BY Description, Interval1, Intervaln, ConnectionFee, Rate, EffectiveDate
					ORDER BY
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN ANY_VALUE(Description)
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN ANY_VALUE(Description)
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PreviousRateDESC') THEN ANY_VALUE(PreviousRate)
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PreviousRateASC') THEN ANY_VALUE(PreviousRate)
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN ANY_VALUE(Rate)
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN ANY_VALUE(Rate)
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN ANY_VALUE(Interval1)
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN ANY_VALUE(Interval1)
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN ANY_VALUE(Interval1)
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN ANY_VALUE(Interval1)
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN ANY_VALUE(EffectiveDate)
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN ANY_VALUE(EffectiveDate)
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN ANY_VALUE(EndDate)
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN ANY_VALUE(EndDate)
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atDESC') THEN ANY_VALUE(updated_at)
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atASC') THEN ANY_VALUE(updated_at)
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byDESC') THEN ANY_VALUE(ModifiedBy)
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byASC') THEN ANY_VALUE(ModifiedBy)
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDDESC') THEN ANY_VALUE(RateTableRateID)
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDASC') THEN ANY_VALUE(RateTableRateID)
                END ASC,
				    CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ANY_VALUE(ConnectionFee)
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ANY_VALUE(ConnectionFee)
                END ASC
			LIMIT p_RowspPage OFFSET v_OffSet_;

			SELECT COUNT(*) AS `totalcount`
			FROM (
				SELECT
	            Description
	        	FROM tmp_RateTableRate_
					GROUP BY Description, Interval1, Intervaln, ConnectionFee, Rate, EffectiveDate
			) totalcount;


		END IF;

    END IF;

    IF p_isExport = 1
    THEN

        SELECT
            Code,
            Description,
            Interval1,
            IntervalN,
            ConnectionFee,
            PreviousRate,
            Rate,
            EffectiveDate,
            updated_at,
            ModifiedBy

        FROM   tmp_RateTableRate_;


    END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_GetRateTableRatesArchiveGrid`;
DELIMITER //
CREATE PROCEDURE `prc_GetRateTableRatesArchiveGrid`(
	IN `p_CompanyID` INT,
	IN `p_RateTableID` INT,
	IN `p_Codes` LONGTEXT,
	IN `p_View` INT
)
BEGIN

	SET SESSION GROUP_CONCAT_MAX_LEN = 1000000; -- group_concat limit bydefault is 1024, so we have increase it
	
	DROP TEMPORARY TABLE IF EXISTS tmp_RateTableRate_;
   CREATE TEMPORARY TABLE tmp_RateTableRate_ (
        Code VARCHAR(50),
        Description VARCHAR(200),
        Interval1 INT,
        IntervalN INT,
		  ConnectionFee VARCHAR(50),
        PreviousRate DECIMAL(18, 6),
        Rate DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        updated_at DATETIME,
        ModifiedBy VARCHAR(50)
   );

	IF p_View = 1
	THEN
		INSERT INTO tmp_RateTableRate_ (
			Code,
		  	Description,
		  	Interval1,
		  	IntervalN,
		  	ConnectionFee,
--		  	PreviousRate,
		  	Rate,
		  	EffectiveDate,
		  	EndDate,
		  	updated_at,
		  	ModifiedBy
		)
	   SELECT
			r.Code,
			r.Description,
			CASE WHEN vra.Interval1 IS NOT NULL THEN vra.Interval1 ELSE r.Interval1 END AS Interval1,
			CASE WHEN vra.IntervalN IS NOT NULL THEN vra.IntervalN ELSE r.IntervalN END AS IntervalN,
			IFNULL(vra.ConnectionFee,'') AS ConnectionFee,
			vra.Rate,
			vra.EffectiveDate,
			IFNULL(vra.EndDate,'') AS EndDate,
			IFNULL(vra.created_at,'') AS ModifiedDate,
			IFNULL(vra.created_by,'') AS ModifiedBy
		FROM
			tblRateTableRateArchive vra
		JOIN
			tblRate r ON r.RateID=vra.RateId
		WHERE
			r.CompanyID = p_CompanyID AND
			vra.RateTableId = p_RateTableID AND
			FIND_IN_SET (r.Code, p_Codes) != 0
		ORDER BY
			vra.EffectiveDate DESC, vra.created_at DESC;
	ELSE
		INSERT INTO tmp_RateTableRate_ (
			Code,
		  	Description,
		  	Interval1,
		  	IntervalN,
		  	ConnectionFee,
--		  	PreviousRate,
		  	Rate,
		  	EffectiveDate,
		  	EndDate,
		  	updated_at,
		  	ModifiedBy
		)
	   SELECT
			GROUP_CONCAT(r.Code),
			r.Description,
			CASE WHEN vra.Interval1 IS NOT NULL THEN vra.Interval1 ELSE r.Interval1 END AS Interval1,
			CASE WHEN vra.IntervalN IS NOT NULL THEN vra.IntervalN ELSE r.IntervalN END AS IntervalN,
			IFNULL(vra.ConnectionFee,'') AS ConnectionFee,
			vra.Rate,
			vra.EffectiveDate,
			IFNULL(vra.EndDate,'') AS EndDate,
			IFNULL(MAX(vra.created_at),'') AS ModifiedDate,
			IFNULL(MAX(vra.created_by),'') AS ModifiedBy
		FROM
			tblRateTableRateArchive vra
		JOIN
			tblRate r ON r.RateID=vra.RateId
		WHERE
			r.CompanyID = p_CompanyID AND
			vra.RateTableId = p_RateTableID AND
			FIND_IN_SET (r.Code, p_Codes) != 0
		GROUP BY
			Description, Interval1, Intervaln, ConnectionFee, Rate, EffectiveDate, EndDate
		ORDER BY
			vra.EffectiveDate DESC, MAX(vra.created_at) DESC;
	END IF;

	SELECT
		Code,
		Description,
		Interval1,
		IntervalN,
		ConnectionFee,
		Rate,
		EffectiveDate,
		EndDate,
		IFNULL(updated_at,'') AS ModifiedDate,
		IFNULL(ModifiedBy,'') AS ModifiedBy
	FROM tmp_RateTableRate_;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_getReviewRateTableRates`;
DELIMITER //
CREATE PROCEDURE `prc_getReviewRateTableRates`(
	IN `p_ProcessID` VARCHAR(50),
	IN `p_Action` VARCHAR(50),
	IN `p_Code` VARCHAR(50),
	IN `p_Description` VARCHAR(50),
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN
	DECLARE v_OffSet_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	IF p_isExport = 0
	THEN
		SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

		SELECT
			distinct
			IF(p_Action='Deleted',RateTableRateID,TempRateTableRateID) AS RateTableRateID,
			`Code`,`Description`,`Rate`,`EffectiveDate`,`EndDate`,`ConnectionFee`,`Interval1`,`IntervalN`
		FROM
			tblRateTableRateChangeLog
		WHERE
			ProcessID = p_ProcessID AND Action = p_Action
			AND
			(p_Code IS NULL OR p_Code = '' OR Code LIKE REPLACE(p_Code, '*', '%'))
			AND
			(p_Description IS NULL OR p_Description = '' OR Description LIKE REPLACE(p_Description, '*', '%'))
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN Rate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN Rate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN EffectiveDate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN EffectiveDate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN EndDate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN EndDate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ConnectionFee
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ConnectionFee
			END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(*) AS totalcount
		FROM
			tblRateTableRateChangeLog
		WHERE
			ProcessID = p_ProcessID AND Action = p_Action
			AND
			(p_Code IS NULL OR p_Code = '' OR Code LIKE REPLACE(p_Code, '*', '%'))
			AND
			(p_Description IS NULL OR p_Description = '' OR Description LIKE REPLACE(p_Description, '*', '%'));
	END IF;

	IF p_isExport = 1
	THEN
		SELECT
			distinct
			`Code`,`Description`,`Rate`,`EffectiveDate`,`EndDate`,`ConnectionFee`,`Interval1`,`IntervalN`
		FROM
			tblRateTableRateChangeLog
		WHERE
			ProcessID = p_ProcessID AND Action = p_Action
			AND
			(p_Code IS NULL OR p_Code = '' OR Code LIKE REPLACE(p_Code, '*', '%'))
			AND
			(p_Description IS NULL OR p_Description = '' OR Description LIKE REPLACE(p_Description, '*', '%'));
	END IF;


	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_GetVendorCodes`;
DELIMITER //
CREATE PROCEDURE `prc_GetVendorCodes`(IN `p_companyid` INT , IN `p_trunkID` INT, IN `p_contryID` VARCHAR(50) , IN `p_code` VARCHAR(50), IN `p_PageNumber` INT , IN `p_RowspPage` INT , IN `p_lSortCol` NVARCHAR(50) , IN `p_SortOrder` NVARCHAR(5) , IN `p_isExport` INT)
BEGIN

	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
        
        IF p_isExport = 0	
		  THEN
		  
		 	 SELECT  RateID,Code FROM(
                                SELECT distinct tblRate.Code as RateID
                                    ,tblRate.Code
                                FROM      tblRate                              
                                WHERE ( tblRate.CompanyID = p_companyid )
                                AND ( p_contryID  = '' OR  FIND_IN_SET(tblRate.CountryID,p_contryID) != 0  )
                                AND ( p_code = '' OR Code LIKE REPLACE(p_code,'*', '%') )
                            ) AS TBL2
            ORDER BY
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
                END ASC
				LIMIT p_RowspPage OFFSET v_OffSet_;    
  
				
				      
                                      
                    
    
		
		
		 Select Count(*) AS totalcount
      FROM
      (
      
            SELECT distinct tblRate.Code 
                                FROM      tblRate                              
                                WHERE ( tblRate.CompanyID = p_companyid )
                                AND ( p_contryID  = '' OR  FIND_IN_SET(tblRate.CountryID,p_contryID) != 0  )
                                AND ( p_code = '' OR Code LIKE REPLACE(p_code,'*', '%') )
		)	AS tbl ;
                    
    END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; 
       
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_GetVendorRatesArchiveGrid`;
DELIMITER //
CREATE PROCEDURE `prc_GetVendorRatesArchiveGrid`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` INT,
	IN `p_Codes` LONGTEXT
)
BEGIN
	SELECT
	--	vra.VendorRateArchiveID,
	--	vra.VendorRateID,
	--	vra.AccountID,
		r.Code,
		r.Description,
		IFNULL(vra.ConnectionFee,'') AS ConnectionFee,
		CASE WHEN vra.Interval1 IS NOT NULL THEN vra.Interval1 ELSE r.Interval1 END AS Interval1,
		CASE WHEN vra.IntervalN IS NOT NULL THEN vra.IntervalN ELSE r.IntervalN END AS IntervalN,
		vra.Rate,
		vra.EffectiveDate,
		IFNULL(vra.EndDate,'') AS EndDate,
		IFNULL(vra.created_at,'') AS ModifiedDate,
		IFNULL(vra.created_by,'') AS ModifiedBy
	FROM
		tblVendorRateArchive vra
	JOIN
		tblRate r ON r.RateID=vra.RateId
	WHERE
		r.CompanyID = p_CompanyID AND
		vra.AccountId = p_AccountID AND
		FIND_IN_SET (r.Code, p_Codes) != 0
	ORDER BY
		vra.EffectiveDate DESC, vra.created_at DESC;
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_ImportSettingMatch`;
DELIMITER //
CREATE PROCEDURE `prc_ImportSettingMatch`(
	IN `p_companyID` INT,
	IN `p_FromEmail` TEXT,
	IN `p_subject` TEXT


,
	IN `p_filenames` TEXT

)
test:BEGIN
	
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
		DROP TEMPORARY TABLE IF EXISTS tmp_matchRecord;
		CREATE TEMPORARY TABLE tmp_matchRecord(
			`AutoImportSettingID` INT(11),
			`CompanyID` INT(11) DEFAULT '0',
			`Type` TINYINT(1),
			`TypePKID` INT(11),
			`TrunkID` INT(11),
			`ImportFileTempleteID` INT(11),
			`Subject` VARCHAR(255),
			`FileName` VARCHAR(255),
			`SendorEmail` TEXT,
			`options` TEXT
		);
		
		DROP TEMPORARY TABLE IF EXISTS tmp_receivedFiles;
		CREATE TEMPORARY TABLE tmp_receivedFiles(	
			`fileID` INT(11) AUTO_INCREMENT,
			`receivedFilename` text,
			PRIMARY KEY (`fileID`)
		);	
		
		DROP TEMPORARY TABLE IF EXISTS tmp_matchFileLangth;
		CREATE TEMPORARY TABLE tmp_matchFileLangth(
			`lognFileName` TEXT,
			`sortFileName` TEXT,
			`matchlength` INT(11)
		);
		
		  DROP TEMPORARY TABLE IF EXISTS tmp_finalMatch;
		CREATE TEMPORARY TABLE tmp_finalMatch(
			`AutoImportSettingID` INT(11),
			`CompanyID` INT(11) DEFAULT '0',
			`Type` TINYINT(1),
			`TypePKID` INT(11),
			`TrunkID` INT(11),
			`ImportFileTempleteID` INT(11),
			`Subject` VARCHAR(255),
			`FileName` VARCHAR(255),
			`SendorEmail` TEXT,
			`options` TEXT,
			`lognFileName` TEXT,
			`matchlength` INT(11)
		);
		
		SET @values = CONCAT('("', REPLACE(p_filenames, ',', '"), ("'), '")');
		SET @insert = CONCAT('INSERT INTO tmp_receivedFiles(receivedFilename) VALUES', @values); 
		PREPARE stmt FROM @insert;
		EXECUTE stmt;
		DEALLOCATE PREPARE stmt;
		
		insert tmp_matchRecord (AutoImportSettingID, CompanyID, Type, TypePKID, TrunkID, ImportFileTempleteID, Subject, FileName, SendorEmail, options)
					SELECT AutoImportSettingID, acimp.CompanyID, TYPE, TypePKID, TrunkID, acimp.ImportFileTempleteID, Subject, FileName, SendorEmail, TEMPLATE.Options
					FROM tblAutoImportSetting AS acimp
					INNER JOIN tblFileUploadTemplate AS TEMPLATE ON acimp.ImportFileTempleteID =TEMPLATE.FileUploadTemplateID
					WHERE 
					(FIND_IN_SET(LOWER(p_FromEmail), LOWER(SendorEmail)) OR FIND_IN_SET(CONCAT('*@', SUBSTRING_INDEX(LOWER(p_FromEmail),'@',-1)), LOWER(SendorEmail)))
					and 
					lower(p_subject) LIKE CONCAT('%', lower(Subject), '%')
					order by FileName desc;

		insert tmp_matchFileLangth
			select t1.receivedFilename as lognFileName, MAX(t2.FileName) as sortFileName, length(MAX(t2.FileName)) AS matchlength from tmp_receivedFiles t1 
			right join tmp_matchRecord t2 ON t1.receivedFilename like concat('%',t2.FileName,'%')
			where t1.receivedFilename is not null
			group by t1.receivedFilename
			order by matchlength desc;
		  

		  insert tmp_finalMatch 
		select tmp_matchRecord.*, tmp_matchFileLangth.lognFileName, tmp_matchFileLangth.matchlength from tmp_matchRecord inner join tmp_matchFileLangth on sortFileName=FileName;

	  DROP TEMPORARY TABLE IF EXISTS tmp_finalMatch2;
		CREATE TEMPORARY TABLE tmp_finalMatch2 as ( select * from tmp_finalMatch);
	
		select * from tmp_finalMatch where FileName in( select FileName from tmp_finalMatch2 group by FileName having count(FileName)=1 );
		
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
	
END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_insertResellerData`;
DELIMITER //
CREATE PROCEDURE `prc_insertResellerData`(
	IN `p_companyid` INT,
	IN `p_childcompanyid` INT,
	IN `p_accountname` VARCHAR(100),
	IN `p_firstname` VARCHAR(100),
	IN `p_lastname` VARCHAR(100),
	IN `p_accountid` INT,
	IN `p_email` VARCHAR(100),
	IN `p_password` TEXT,
	IN `p_is_product` INT,
	IN `p_product` TEXT,
	IN `p_is_subscription` INT,
	IN `p_subscription` TEXT,
	IN `p_is_trunk` INT,
	IN `p_trunk` TEXT,
	IN `p_allowwhitelabel` INT
)
BEGIN

	DECLARE companycodedeckid int;
	DECLARE resellercodedeckid int;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		GET DIAGNOSTICS CONDITION 1
		@p2 = MESSAGE_TEXT;
		SELECT @p2 as Message;
		-- ROLLBACK;
	END;		

	SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

	DROP TEMPORARY TABLE IF EXISTS tmp_currency;
	CREATE TEMPORARY TABLE tmp_currency (
		`CompanyId` INT,
		`Code` VARCHAR(50),
		`CurrencyID` INT,
		`NewCurrencyID` INT
	) ENGINE=InnoDB;

	-- START TRANSACTION;

	INSERT INTO	tblUser(CompanyID,FirstName,LastName,EmailAddress,password,AdminUser,updated_at,created_at,created_by,Status,JobNotification)	
	SELECT p_childcompanyid as CompanyID,p_firstname as FirstName,p_lastname as LastName , p_email as EmailAddress,p_password as password, 1 as AdminUser, Now(),Now(),'system' as created_by, '1' as Status, '1' as JobNotification;

	INSERT INTO tblEmailTemplate (CompanyID,TemplateName,Subject,TemplateBody,created_at,CreatedBy,updated_at,`Type`,EmailFrom,StaticType,SystemType,Status,StatusDisabled,TicketTemplate)
	SELECT DISTINCT p_childcompanyid as `CompanyID`,TemplateName,Subject,TemplateBody,NOW(),'system' as CreatedBy,NOW(),`Type`, p_email as `EmailFrom`,StaticType,SystemType,Status,StatusDisabled,TicketTemplate	
	FROM tblEmailTemplate
	WHERE StaticType=1 AND CompanyID = p_companyid ;

	INSERT INTO tblCompanyConfiguration (`CompanyID`,`Key`,`Value`)
	SELECT DISTINCT p_childcompanyid as `CompanyID`,`Key`,`Value`	
	FROM tblCompanyConfiguration
	WHERE CompanyID = p_companyid;

	INSERT INTO tblCronJobCommand (`CompanyID`,GatewayID,Title,Command,Settings,Status,created_at,created_by)
	SELECT DISTINCT p_childcompanyid as `CompanyID`,GatewayID,Title,Command,Settings,Status,created_at,created_by	
	FROM tblCronJobCommand
	WHERE CompanyID = p_companyid;

	INSERT INTO tblTaxRate (CompanyId,Title,Amount,TaxType,FlatStatus,Status,created_at,updated_at)
	SELECT DISTINCT p_childcompanyid as `CompanyId`,Title,Amount,TaxType,FlatStatus,Status,NOW(),NOW()
	FROM tblTaxRate
	WHERE CompanyId = p_companyid;

	/*
	INSERT INTO tblCurrency (CompanyId,Code,Description,Status,created_at,updated_at,Symbol)
	SELECT DISTINCT p_childcompanyid as `CompanyId` ,Code,Description,Status,NOW(),NOW(),Symbol
	FROM tblCurrency
	WHERE CompanyId = p_companyid; */

	IF p_is_product =1
	THEN	

		INSERT INTO RMBilling3.tblProduct (CompanyId,Name,Code,Description,Amount,Active,Note,CreatedBy,ModifiedBy,created_at,updated_at)
		SELECT DISTINCT p_childcompanyid as `CompanyId`,Name,Code,Description,Amount,Active,Note,'system' as CreatedBy,'system' as ModifiedBy,NOW(),NOW()
		FROM RMBilling3.tblProduct
		WHERE CompanyId = p_companyid AND FIND_IN_SET(ProductID,p_product);

	END IF;

	IF p_is_subscription = 1
	THEN

		/*
		INSERT INTO	tmp_currency(CompanyId,Code,CurrencyID)	
		SELECT p_companyid as CompanyId,Code, CurrencyId FROM `tblCurrency` WHERE CompanyId	= p_companyid;	

		UPDATE tmp_currency tc LEFT JOIN tblCurrency c ON tc.Code=c.Code AND c.CompanyId = p_childcompanyid
		set NewCurrencyID = c.CurrencyId
		WHERE c.CurrencyId IS NOT NULL;

		*/

		INSERT INTO RMBilling3.tblBillingSubscription(`CompanyID`,Name,Description,InvoiceLineDescription,ActivationFee,created_at,updated_at,ModifiedBy,CreatedBy,CurrencyID,AnnuallyFee,QuarterlyFee,MonthlyFee,WeeklyFee,DailyFee,Advance)
		SELECT DISTINCT p_childcompanyid as `CompanyID`,Name,Description,InvoiceLineDescription,ActivationFee,created_at,updated_at,ModifiedBy,CreatedBy,CurrencyID,AnnuallyFee,QuarterlyFee,MonthlyFee,WeeklyFee,DailyFee,Advance
		FROM RMBilling3.tblBillingSubscription
		WHERE CompanyID = p_companyid AND FIND_IN_SET(SubscriptionID,p_subscription);

	END IF;

	/*
	IF p_is_trunk =1
	THEN

	INSERT INTO tblTrunk (Trunk,CompanyId,RatePrefix,AreaPrefix,`Prefix`,Status,created_at,updated_at)
	SELECT DISTINCT Trunk, p_childcompanyid as `CompanyId`,RatePrefix,AreaPrefix,`Prefix`,Status,NOW(),NOW()
	FROM tblTrunk
	WHERE CompanyId = p_companyid AND FIND_IN_SET(TrunkID,p_trunk);

	END IF;
	*/

	INSERT INTO tblReseller(ResellerName,CompanyID,ChildCompanyID,AccountID,FirstName,LastName,Email,Password,Status,AllowWhiteLabel,created_at,updated_at,created_by)
	SELECT p_accountname as ResellerName,p_companyid as CompanyID,p_childcompanyid as ChildCompanyID,p_accountid as AccountID,p_firstname as FirstName,p_lastname as LastName,p_email as Email,p_password as Password,'1' as Status,p_allowwhitelabel as AllowWhiteLabel,Now(),Now(),'system' as created_by;

	INSERT INTO tblCompanySetting(`CompanyID`,`Key`,`Value`)
	SELECT p_childcompanyid as `CompanyID`,`Key`,`Value` 
	FROM tblCompanySetting
	WHERE CompanyID = p_companyid AND `Key`='RoundChargesAmount';

	SELECT CodeDeckId INTO companycodedeckid  FROM tblCodeDeck WHERE CompanyId=p_companyid AND DefaultCodedeck=1;

	IF companycodedeckid > 0 THEN
		INSERT INTO tblCodeDeck (CompanyId, CodeDeckName, created_at, CreatedBy, updated_at, ModifiedBy, `Type`, DefaultCodedeck) 
		VALUES (p_childcompanyid, 'Default Codedeck', Now(), 'Dev', Now(), NULL, NULL, 1);

		SELECT CodeDeckId INTO resellercodedeckid  FROM tblCodeDeck WHERE CompanyId=p_childcompanyid AND DefaultCodedeck=1;

		INSERT INTO tblRate(CountryID,CompanyID,CodeDeckId,Code,Description,Interval1,IntervalN,created_at)
		SELECT CountryID,p_childcompanyid as CompanyID,resellercodedeckid as CodeDeckId,Code,Description,Interval1,IntervalN,Now() as created_at FROM tblRate where CodeDeckId=companycodedeckid;


	END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_lcrBlockUnblock`;
DELIMITER //
CREATE PROCEDURE `prc_lcrBlockUnblock`(
	IN `p_companyId` INT,
	IN `p_groupby` VARCHAR(200),
	IN `p_blockId` INT,
	IN `p_preference` INT,
	IN `p_accountId` INT,
	IN `p_trunk` INT,
	IN `p_rowcode` VARCHAR(50),
	IN `p_codedeckId` INT,
	IN `p_description` VARCHAR(200),
	IN `p_username` VARCHAR(50)



,
	IN `p_action` VARCHAR(50),
	IN `p_countryBlockingID` INT


)
BEGIN

   DECLARE v_countryID INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	DROP TEMPORARY TABLE IF EXISTS tmp_block0;
	CREATE TEMPORARY TABLE tmp_block0(	
		RateId INT(11)
	);	
	
		IF(p_action = '') THEN 
		
				IF p_groupby = 'description' THEN
						
						
						INSERT INTO tmp_block0
								select RateId
								FROM (
								select vr.RateId
									 from tblVendorRate vr
								 	 inner join tblRate r on vr.RateId=r.RateID 
								    where vr.AccountId = p_accountId AND vr.TrunkID=p_trunk AND r.Description = p_description) tbl;
						
									 	
							IF (p_blockId = 0) THEN
							
								/* insert into Vendor Blocking by description */								 
								 insert into tblVendorBlocking (AccountId,RateId,TrunkID,BlockedBy,BlockedDate)    
									    select p_accountId as AccountId, tmp0.RateID as RateId,p_trunk as TrunkID ,p_username as BlockedBy,NOW() as BlockedDate
										 from  tmp_block0 tmp0
										 	 left join tblVendorBlocking vb
											   on vb.RateId=tmp0.RateID 
											   AND vb.AccountId = p_accountId AND vb.TrunkID=p_trunk
									    where  vb.VendorBlockingId IS NULL;
							ELSE 
								select * from tmp_block0;
								/* Delete from Vendor Blocking by description  */
							
								DELETE vb
								FROM tblVendorBlocking vb
								INNER JOIN tmp_block0 t
								  ON vb.RateId = t.RateID
								WHERE vb.AccountId = p_accountId AND vb.TrunkID = p_trunk ; 
		
							END IF;	
							 
								    
								    
								    
				ELSE
					  				
						INSERT INTO tmp_block0
								select RateId
								FROM (						
								select vr.RateId
									 from tblVendorRate vr
								 	 inner join tblRate r on vr.RateId=r.RateID 
								    where vr.AccountId = p_accountId AND vr.TrunkID=p_trunk AND r.Code = p_rowcode) tbl;
									 
						
						IF	(select COUNT(*)
									 from tblVendorRate vr
									 	 inner join tblRate r
										   on vr.RateId=r.RateID 
										 inner join tblVendorBlocking vb
										   on r.RateID=vb.RateId
								    where vb.AccountId = p_accountId AND vr.TrunkID=p_trunk AND r.Code = p_rowcode)	= 0		
						THEN 
						
						
							 insert into tblVendorBlocking (AccountId,RateId,TrunkID,BlockedBy)    
							    select p_accountId as AccountId,tmp0.RateID as RateId,p_trunk as TrunkID ,p_username as BlockedBy
								 from  tmp_block0 tmp0
								 	 left join tblVendorBlocking vb
									   on vb.RateId=tmp0.RateID 
									   AND vb.AccountId = p_accountId AND vb.TrunkID=p_trunk
							    where  vb.VendorBlockingId IS NULL;
							    
							    
						ELSE
							    
							    DELETE FROM `tblVendorBlocking`
								   WHERE VendorBlockingId = p_blockId ;
								/* DELETE FROM `tblVendorBlocking`
								   WHERE AccountId = p_accountId
								    AND TrunkID = p_trunk AND RateId = (select RateId from tmp_block0);*/
								    
								    
						END IF;
						
				
				END IF;
	
		ELSE
		
			   /* Country Blocking Code Start */
			   if(p_action ='country_block')
				  THEN
		
						  IF p_groupby = 'description' THEN	
								  select distinct CountryID into v_countryID from tblRate where Code=p_rowcode AND tblRate.Description=p_description AND tblRate.CountryID is not null AND tblRate.CountryID!=0 AND tblRate.CompanyID=p_companyId;
						  ELSE
								  select distinct CountryID into v_countryID from tblRate where Code=p_rowcode AND tblRate.CountryID is not null AND tblRate.CountryID!=0 AND tblRate.CompanyID=p_companyId;
						  END IF;
								  
							  
							  INSERT INTO tblVendorBlocking
							  (
									 `AccountId`
									 ,CountryId
									 ,`TrunkID`
									 ,`BlockedBy`
							  ) 
							  SELECT  
								p_accountId as AccountId
								,tblCountry.CountryID as CountryId
								,p_trunk as TrunkID
								,p_username as BlockedBy
								FROM    tblCountry
								LEFT JOIN tblVendorBlocking ON tblVendorBlocking.CountryId = tblCountry.CountryID AND TrunkID = p_trunk AND AccountId = p_accountId
								WHERE  tblCountry.CountryID=v_countryID  AND tblVendorBlocking.VendorBlockingId is null; 
											  
				  END IF;
				  
				  if(p_action ='country_unblock')
				  THEN
				  
				  	delete  from tblVendorBlocking 
					WHERE  AccountId = p_accountId AND TrunkID = p_trunk AND ( p_countryBlockingID ='' OR FIND_IN_SET(CountryId, p_countryBlockingID) );
							
				
				  END IF;
			   /* Country Blocking Code End */
	    END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;

DROP PROCEDURE IF EXISTS `prc_RateTableRateInsertUpdate`;
DELIMITER //
CREATE PROCEDURE `prc_RateTableRateInsertUpdate`(
	IN `p_CompanyID` INT,
	IN `p_RateTableRateID` LONGTEXT,
	IN `p_RateTableId` INT ,
	IN `p_Rate` DECIMAL(18, 6) ,
	IN `p_EffectiveDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_ModifiedBy` VARCHAR(50),
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_ConnectionFee` DECIMAL(18, 6),
	IN `p_Critearea` INT,
	IN `p_Critearea_TrunkID` INT,
	IN `p_Critearea_CountryID` INT,
	IN `p_Critearea_Code` VARCHAR(50),
	IN `p_Critearea_Description` VARCHAR(50),
	IN `p_Critearea_Effective` VARCHAR(50),
	IN `p_Update_EffectiveDate` INT,
	IN `p_Update_EndDate` INT,
	IN `p_Update_Rate` INT,
	IN `p_Update_Interval1` INT,
	IN `p_Update_IntervalN` INT,
	IN `p_Update_ConnectionFee` INT,
	IN `p_Action` INT
)
ThisSP:BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

    DROP TEMPORARY TABLE IF EXISTS tmp_Update_RateTable_;
    CREATE TEMPORARY TABLE tmp_Update_RateTable_ (
      RateID INT,
      EffectiveDate DATE,
      RateTableRateID INT
    );

    DROP TEMPORARY TABLE IF EXISTS tmp_Insert_RateTable_;
    CREATE TEMPORARY TABLE tmp_Insert_RateTable_ (
      RateID INT,
      EffectiveDate DATE,
      RateTableRateID INT
    );

    DROP TEMPORARY TABLE IF EXISTS tmp_all_RateId_;
    CREATE TEMPORARY TABLE tmp_all_RateId_ (
      RateID INT,
      EffectiveDate DATE,
      RateTableRateID INT
	  );


    DROP TEMPORARY TABLE IF EXISTS tmp_RateTable_;
      CREATE TEMPORARY TABLE tmp_RateTable_ (
         RateID INT,
         EffectiveDate DATE,
         RateTableRateID INT,
			INDEX tmp_RateTable_RateId (`RateId`)
     );

   IF p_Critearea = 0
	THEN
 		INSERT INTO tmp_RateTable_
			  SELECT RateID,EffectiveDate,RateTableRateID
			   FROM tblRateTableRate
					WHERE (FIND_IN_SET(RateTableRateID,p_RateTableRateID) != 0 );

	END IF;


	IF p_Critearea = 1
	THEN


		 INSERT INTO tmp_RateTable_
				SELECT
					 tblRateTableRate.RateID,
                IFNULL(tblRateTableRate.EffectiveDate, NOW()) as EffectiveDate,
                tblRateTableRate.RateTableRateID
            FROM tblRate
            LEFT JOIN tblRateTableRate
                ON tblRateTableRate.RateID = tblRate.RateID
                AND tblRateTableRate.RateTableId = p_RateTableId
            INNER JOIN tblRateTable
                ON tblRateTable.RateTableId = tblRateTableRate.RateTableId
            WHERE		(tblRate.CompanyID = p_CompanyID)
					AND (p_Critearea_CountryID = 0 OR CountryID = p_Critearea_CountryID)
					AND (p_Critearea_Code IS NULL OR Code LIKE REPLACE(p_Critearea_Code, '*', '%'))
					AND (p_Critearea_Description IS NULL OR Description LIKE REPLACE(p_Critearea_Description, '*', '%'))
					AND TrunkID = p_Critearea_TrunkID
					AND (
							p_Critearea_Effective = 'All'
						OR (p_Critearea_Effective = 'Now' AND EffectiveDate <= NOW() )
						OR (p_Critearea_Effective = 'Future' AND EffectiveDate > NOW())
						);

		  IF p_Critearea_Effective = 'Now'
		  THEN
			 CREATE TEMPORARY TABLE IF NOT EXISTS tmp_RateTable4_ as (select * from tmp_RateTable_);
          DELETE n1 FROM tmp_RateTable_ n1, tmp_RateTable4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate
	 	   AND  n1.RateId = n2.RateId;

		  END IF;

	END IF;

	IF p_action = 1
	THEN

	IF p_Update_EffectiveDate = 0
	THEN

	INSERT INTO tmp_Update_RateTable_
		SELECT RateID,EffectiveDate,RateTableRateID
			 FROM tmp_RateTable_ ;

	END IF;

	IF p_Update_EffectiveDate = 1
	THEN


		INSERT INTO tmp_Update_RateTable_
		SELECT tblRateTableRate.RateID,
				p_EffectiveDate,
				tblRateTableRate.RateTableRateID
			 FROM tblRateTableRate
			 	INNER JOIN tmp_RateTable_ r on tblRateTableRate.RateID = r.RateID
			 	 WHERE RateTableId = p_RateTableId
					AND tblRateTableRate.EffectiveDate = p_EffectiveDate;

		INSERT INTO tmp_all_RateId_
		SELECT  tblRateTableRate.RateID,
					MAX(tblRateTableRate.EffectiveDate),
					MAX(tblRateTableRate.RateTableRateID)
				 FROM tblRateTableRate
				 	 INNER JOIN tmp_RateTable_ r on tblRateTableRate.RateID = r.RateID
					 	 WHERE tblRateTableRate.RateTableId = p_RateTableId
						  GROUP BY tblRateTableRate.RateID;

		INSERT INTO tmp_Insert_RateTable_
		SELECT r.RateID,p_EffectiveDate,r.RateTableRateID
			 FROM tmp_all_RateId_ r
			 	 LEFT JOIN tmp_Update_RateTable_ ur
					 ON r.RateID=ur.RateID
			   WHERE ur.RateID is null ;


		INSERT INTO tblRateTableRate (
			RateID,
			RateTableId,
			Rate,
			PreviousRate,
			EffectiveDate,
			created_at,
			CreatedBy,
			Interval1,
			IntervalN,
			ConnectionFee,
			EndDate
		)
	    SELECT DISTINCT  tr.RateID,
		 						RateTableId,
		 						CASE WHEN p_Update_Rate = 1
									THEN
										p_Rate
									ELSE
										tr.Rate
									END
								AS Rate,
								tr.Rate AS PreviousRate,
								p_EffectiveDate as EffectiveDate,
								NOW() as created_at,
								p_ModifiedBy as CreatedBy,
								CASE WHEN p_Update_Interval1 = 1
									THEN
										p_Interval1
									ELSE
										tr.Interval1
									END
								AS Interval1,
								CASE WHEN p_Update_IntervalN = 1
									THEN
										p_IntervalN
									ELSE
										tr.IntervalN
									END
								AS IntervalN,
								CASE WHEN p_Update_ConnectionFee = 1
									THEN
										p_ConnectionFee
									ELSE
										tr.ConnectionFee
									END
								AS ConnectionFee,
								CASE WHEN p_Update_EndDate = 1
									THEN
										p_EndDate
									ELSE
										tr.EndDate
									END
								AS EndDate
			 FROM tblRateTableRate tr
		   	 INNER JOIN tmp_Insert_RateTable_ r
			 		 ON  r.RateID = tr.RateID
			 		 	AND r.RateTableRateID = tr.RateTableRateID
	   		 		AND  RateTableId = p_RateTableId;




			-- update  previous rate with all latest recent entriy of previous effective date
			UPDATE tblRateTableRate rtr
			inner join
			(
				-- get all rates RowID = 1 to remove old to old effective date

				select distinct rt1.* ,
				@row_num := IF(@prev_RateId = rt1.RateID AND @prev_EffectiveDate >= rt1.EffectiveDate, @row_num + 1, 1) AS RowID,
				@prev_RateId := rt1.RateID,
				@prev_EffectiveDate := rt1.EffectiveDate
				from tblRateTableRate rt1
				inner join tmp_Insert_RateTable_ rt2
				on rt1.RateTableId = p_RateTableId and rt1.RateID = rt2.RateID
				and rt1.EffectiveDate < rt2.EffectiveDate
				where
				rt1.RateTableID = p_RateTableId
				order by rt1.RateID desc ,rt1.EffectiveDate desc

			) old_rtr on  old_rtr.RateTableID = rtr.RateTableID  and old_rtr.RateID = rtr.RateID and old_rtr.EffectiveDate < rtr.EffectiveDate AND rtr.EffectiveDate =  p_EffectiveDate AND old_rtr.RowID = 1
			SET rtr.PreviousRate = old_rtr.Rate
			where
			rtr.RateTableID = p_RateTableId;


	END IF;



	SET @stm = '';

	IF p_Update_Rate = 1
	THEN
		SET @stm = CONCAT(@stm,',Rate = ',p_Rate);
	END IF;

	IF p_Update_Interval1 = 1
	THEN
		SET @stm = CONCAT(@stm,',Interval1 = ',p_Interval1);
	END IF;

	IF p_Update_IntervalN = 1
	THEN
		SET @stm = CONCAT(@stm,',IntervalN = ',p_IntervalN);
	END IF;

	IF p_Update_ConnectionFee = 1
	THEN
		SET @stm = CONCAT(@stm,',ConnectionFee = ',p_ConnectionFee);
	END IF;

	IF p_Update_EndDate = 1
	THEN
		SET @stm = CONCAT(@stm,',EndDate = ','"',p_EndDate,'"');
	END IF;

	IF @stm != ''
	THEN
			SET @stm = CONCAT('
							UPDATE tblRateTableRate tr
						    INNER JOIN tmp_Update_RateTable_ r
							 	 ON  r.RateID = tr.RateID
							 	 	AND r.RateTableRateID = tr.RateTableRateID
										SET updated_at=NOW(),ModifiedBy="',p_ModifiedBy,'"',@stm,'
								    WHERE  RateTableId = ',p_RateTableId,';
						');

			PREPARE stmt FROM @stm;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;





	END IF;


	-- Update previous rate
   call prc_RateTableRateUpdatePreviousRate(p_RateTableId,p_EffectiveDate);


	CALL prc_ArchiveOldRateTableRate(p_RateTableId,p_ModifiedBy);

	END IF;

	IF p_action = 2
	THEN
		DELETE tblRateTableRate
			 FROM tblRateTableRate
				INNER JOIN tmp_RateTable_
					ON tblRateTableRate.RateTableRateID = tmp_RateTable_.RateTableRateID;


	END IF;


	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_RateTableRateUpdateDelete`;
DELIMITER //
CREATE PROCEDURE `prc_RateTableRateUpdateDelete`(
	IN `p_RateTableId` INT,
	IN `p_RateTableRateId` LONGTEXT,
	IN `p_EffectiveDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_Rate` decimal(18,6),
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_ConnectionFee` decimal(18,6),
	IN `p_Critearea_CountryId` INT,
	IN `p_Critearea_Code` varchar(50),
	IN `p_Critearea_Description` varchar(200),
	IN `p_Critearea_Effective` VARCHAR(50),
	IN `p_ModifiedBy` varchar(50),
	IN `p_Critearea` INT,
	IN `p_action` INT
)
ThisSP:BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	--	p_action = 1 = update rates
	--	p_action = 2 = delete rates

	DROP TEMPORARY TABLE IF EXISTS tmp_TempRateTableRate_;
	CREATE TEMPORARY TABLE tmp_TempRateTableRate_ (
		`RateTableRateId` int(11) NOT NULL,
		`RateId` int(11) NOT NULL,
		`RateTableId` int(11) NOT NULL,
		`Rate` decimal(18,6) NOT NULL DEFAULT '0.000000',
		`EffectiveDate` datetime NOT NULL,
		`EndDate` datetime DEFAULT NULL,
		`created_at` datetime DEFAULT NULL,
		`updated_at` datetime DEFAULT NULL,
		`CreatedBy` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
		`ModifiedBy` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
		`Interval1` int(11) DEFAULT NULL,
		`IntervalN` int(11) DEFAULT NULL,
		`ConnectionFee` decimal(18,6) DEFAULT NULL
	);

	INSERT INTO tmp_TempRateTableRate_
	SELECT
		rtr.RateTableRateId,
		rtr.RateId,
		rtr.RateTableId,
		IFNULL(p_Rate,rtr.Rate) AS Rate,
		IFNULL(p_EffectiveDate,rtr.EffectiveDate) AS EffectiveDate,
		IFNULL(p_EndDate,rtr.EndDate) AS EndDate,
		rtr.created_at,
		NOW() AS updated_at,
		rtr.CreatedBy,
		p_ModifiedBy AS ModifiedBy,
		IFNULL(p_Interval1,rtr.Interval1) AS Interval1,
		IFNULL(p_IntervalN,rtr.IntervalN) AS IntervalN,
		IFNULL(p_ConnectionFee,rtr.ConnectionFee) AS ConnectionFee
	FROM
		tblRateTableRate rtr
	INNER JOIN
		tblRate r ON r.RateID = rtr.RateId
	WHERE
		(
			p_EffectiveDate IS NULL OR rtr.RateID NOT IN (
				SELECT
					RateID
				FROM
					tblRateTableRate
				WHERE
					EffectiveDate=p_EffectiveDate AND
					((p_Critearea = 0 AND (FIND_IN_SET(RateTableRateID,p_RateTableRateID) = 0 )) OR p_Critearea = 1) AND
					RateTableId = p_RateTableId
			)
		)
		AND
		(
			(p_Critearea = 0 AND (FIND_IN_SET(rtr.RateTableRateID,p_RateTableRateID) != 0 )) OR
			(
				p_Critearea = 1 AND
				(
					((p_Critearea_CountryId IS NULL) OR (p_Critearea_CountryId IS NOT NULL AND r.CountryId = p_Critearea_CountryId)) AND
					((p_Critearea_Code IS NULL) OR (p_Critearea_Code IS NOT NULL AND r.Code LIKE REPLACE(p_Critearea_Code,'*', '%'))) AND
					((p_Critearea_Description IS NULL) OR (p_Critearea_Description IS NOT NULL AND r.Description LIKE REPLACE(p_Critearea_Description,'*', '%'))) AND
					(
						p_Critearea_Effective = 'All' OR
						(p_Critearea_Effective = 'Now' AND rtr.EffectiveDate <= NOW() ) OR
						(p_Critearea_Effective = 'Future' AND rtr.EffectiveDate > NOW() )
					)
				)
			)
		) AND
		rtr.RateTableId = p_RateTableId;

	-- if Effective Date needs to change then remove duplicate codes
	IF p_action = 1 AND p_EffectiveDate IS NOT NULL
	THEN
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_TempRateTableRate_2 as (select * from tmp_TempRateTableRate_);

      DELETE n1 FROM tmp_TempRateTableRate_ n1, tmp_TempRateTableRate_2 n2 WHERE n1.RateTableRateID < n2.RateTableRateID AND  n1.RateID = n2.RateID;
	END IF;

	-- select * from tmp_TempRateTableRate_;leave ThisSP;
	-- archive and delete rates if action is 2 and also delete rates if action is 1 and rates are updating

	UPDATE
		tblRateTableRate rtr
	INNER JOIN
		tmp_TempRateTableRate_ temp ON temp.RateTableRateID = rtr.RateTableRateID
	SET
		rtr.EndDate = NOW()
	WHERE
		temp.RateTableRateID = rtr.RateTableRateID;

	CALL prc_ArchiveOldRateTableRate(p_RateTableId,p_ModifiedBy);

	IF p_action = 1
	THEN

		INSERT INTO tblRateTableRate (
			RateId,
			RateTableId,
			Rate,
			EffectiveDate,
			EndDate,
			created_at,
			updated_at,
			CreatedBy,
			ModifiedBy,
			Interval1,
			IntervalN,
			ConnectionFee
		)
		select
			RateId,
			RateTableId,
			Rate,
			EffectiveDate,
			EndDate,
			created_at,
			updated_at,
			CreatedBy,
			ModifiedBy,
			Interval1,
			IntervalN,
			ConnectionFee
		from
			tmp_TempRateTableRate_;

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_SplitAndInsertRateTableRate`;
DELIMITER //
CREATE PROCEDURE `prc_SplitAndInsertRateTableRate`(
	IN `TempRateTableRateID` INT,
	IN `Code` VARCHAR(500),
	IN `p_countryCode` VARCHAR(50)
)
BEGIN

	DECLARE v_First_ BIGINT;
	DECLARE v_Last_ BIGINT;

	SELECT  REPLACE(SUBSTRING(SUBSTRING_INDEX(Code, '-', 1)
					, LENGTH(SUBSTRING_INDEX(Code, '-', 0)) + 1)
					, '-'
					, '') INTO v_First_;

	SELECT REPLACE(SUBSTRING(SUBSTRING_INDEX(Code, '-', 2)
					, LENGTH(SUBSTRING_INDEX(Code, '-', 1)) + 1)
					, '-'
					, '') INTO v_Last_;

	WHILE v_Last_ >= v_First_
	DO
		INSERT my_splits (TempRateTableRateID,Code,CountryCode) VALUES (TempRateTableRateID,v_Last_,p_countryCode);
		SET v_Last_ = v_Last_ - 1;
	END WHILE;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_SplitAndInsertVendorRate`;
DELIMITER //
CREATE PROCEDURE `prc_SplitAndInsertVendorRate`(
	IN `TempVendorRateID` INT,
	IN `Code` VARCHAR(500),
	IN `p_countryCode` VARCHAR(50)
)
BEGIN

	DECLARE v_First_ BIGINT;
	DECLARE v_Last_ BIGINT;

	SELECT  REPLACE(SUBSTRING(SUBSTRING_INDEX(Code, '-', 1)
                 , LENGTH(SUBSTRING_INDEX(Code, '-', 0)) + 1)
                 , '-'
                 , '') INTO v_First_;

	 SELECT REPLACE(SUBSTRING(SUBSTRING_INDEX(Code, '-', 2)
                 , LENGTH(SUBSTRING_INDEX(Code, '-', 1)) + 1)
                 , '-'
                 , '') INTO v_Last_;


   WHILE v_Last_ >= v_First_
	DO
   	 INSERT my_splits (TempVendorRateID,Code,CountryCode) VALUES (TempVendorRateID,v_Last_,p_countryCode);
	    SET v_Last_ = v_Last_ - 1;
  END WHILE;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_SplitRateTableRate`;
DELIMITER //
CREATE PROCEDURE `prc_SplitRateTableRate`(
	IN `p_processId` VARCHAR(200),
	IN `p_dialcodeSeparator` VARCHAR(50)
)
ThisSP:BEGIN

	DECLARE i INTEGER;
	DECLARE v_rowCount_ INT;
	DECLARE v_pointer_ INT;
	DECLARE v_TempRateTableRateID_ INT;
	DECLARE v_Code_ TEXT;
	DECLARE v_CountryCode_ VARCHAR(500);
	DECLARE newcodecount INT(11) DEFAULT 0;

	IF p_dialcodeSeparator !='null'
	THEN

		DROP TEMPORARY TABLE IF EXISTS `my_splits`;
		CREATE TEMPORARY TABLE `my_splits` (
			`TempRateTableRateID` INT(11) NULL DEFAULT NULL,
			`Code` Text NULL DEFAULT NULL,
			`CountryCode` Text NULL DEFAULT NULL
		);

		SET i = 1;
		REPEAT
			INSERT INTO my_splits (TempRateTableRateID, Code, CountryCode)
			SELECT TempRateTableRateID , FnStringSplit(Code, p_dialcodeSeparator, i), CountryCode  FROM tblTempRateTableRate
			WHERE FnStringSplit(Code, p_dialcodeSeparator , i) IS NOT NULL
				AND ProcessId = p_processId;

			SET i = i + 1;
			UNTIL ROW_COUNT() = 0
		END REPEAT;

		UPDATE my_splits SET Code = trim(Code);


		INSERT INTO my_splits (TempVendorRateID, Code, CountryCode)
		SELECT TempVendorRateID , Code, CountryCode  FROM tblTempVendorRate
		WHERE (CountryCode IS NOT NULL AND CountryCode <> '') AND (Code IS NULL OR Code = '')
		AND ProcessId = p_processId;


		DROP TEMPORARY TABLE IF EXISTS tmp_newratetable_splite_;
		CREATE TEMPORARY TABLE tmp_newratetable_splite_  (
			RowID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
			TempRateTableRateID INT(11) NULL DEFAULT NULL,
			Code VARCHAR(500) NULL DEFAULT NULL,
			CountryCode VARCHAR(500) NULL DEFAULT NULL
		);

		INSERT INTO tmp_newratetable_splite_(TempRateTableRateID,Code,CountryCode)
		SELECT
			TempRateTableRateID,
			Code,
			CountryCode
		FROM my_splits
		WHERE Code like '%-%'
			AND TempRateTableRateID IS NOT NULL;

		SET v_pointer_ = 1;
		SET v_rowCount_ = (SELECT COUNT(*)FROM tmp_newratetable_splite_);

		WHILE v_pointer_ <= v_rowCount_
		DO
			SET v_TempRateTableRateID_ = (SELECT TempRateTableRateID FROM tmp_newratetable_splite_ t WHERE t.RowID = v_pointer_);
			SET v_Code_ = (SELECT Code FROM tmp_newratetable_splite_ t WHERE t.RowID = v_pointer_);
			SET v_CountryCode_ = (SELECT CountryCode FROM tmp_newratetable_splite_ t WHERE t.RowID = v_pointer_);

			Call prc_SplitAndInsertRateTableRate(v_TempRateTableRateID_,v_Code_,v_CountryCode_);

			SET v_pointer_ = v_pointer_ + 1;
		END WHILE;

		DELETE FROM my_splits
		WHERE Code like '%-%'
			AND TempRateTableRateID IS NOT NULL;

		DELETE FROM my_splits
		WHERE (Code = '' OR Code IS NULL) AND (CountryCode = '' OR CountryCode IS NULL);

		INSERT INTO tmp_split_RateTableRate_
		SELECT DISTINCT
			my_splits.TempRateTableRateID as `TempRateTableRateID`,
			`CodeDeckId`,
			CONCAT(IFNULL(my_splits.CountryCode,''),my_splits.Code) as Code,
			`Description`,
			`Rate`,
			`EffectiveDate`,
			`EndDate`,
			`Change`,
			`ProcessId`,
			`Preference`,
			`ConnectionFee`,
			`Interval1`,
			`IntervalN`,
			`Forbidden`,
			`DialStringPrefix`
		FROM my_splits
		INNER JOIN tblTempRateTableRate
			ON my_splits.TempRateTableRateID = tblTempRateTableRate.TempRateTableRateID
		WHERE	tblTempRateTableRate.ProcessId = p_processId;

	END IF;

	IF p_dialcodeSeparator = 'null'
	THEN

		INSERT INTO tmp_split_RateTableRate_
		SELECT DISTINCT
			`TempRateTableRateID`,
			`CodeDeckId`,
			CONCAT(IFNULL(tblTempRateTableRate.CountryCode,''),tblTempRateTableRate.Code) as Code,
			`Description`,
			`Rate`,
			`EffectiveDate`,
			`EndDate`,
			`Change`,
			`ProcessId`,
			`Preference`,
			`ConnectionFee`,
			`Interval1`,
			`IntervalN`,
			`Forbidden`,
			`DialStringPrefix`
		FROM tblTempRateTableRate
		WHERE ProcessId = p_processId;

	END IF;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_SplitVendorRate`;
DELIMITER //
CREATE PROCEDURE `prc_SplitVendorRate`(
	IN `p_processId` VARCHAR(200),
	IN `p_dialcodeSeparator` VARCHAR(50)
)
ThisSP:BEGIN

	DECLARE i INTEGER;
	DECLARE v_rowCount_ INT;
	DECLARE v_pointer_ INT;
	DECLARE v_TempVendorRateID_ INT;
	DECLARE v_Code_ TEXT;
	DECLARE v_CountryCode_ VARCHAR(500);
	DECLARE newcodecount INT(11) DEFAULT 0;

	IF p_dialcodeSeparator !='null'
	THEN





	DROP TEMPORARY TABLE IF EXISTS `my_splits`;
	CREATE TEMPORARY TABLE `my_splits` (
		`TempVendorRateID` INT(11) NULL DEFAULT NULL,
		`Code` Text NULL DEFAULT NULL,
		`CountryCode` Text NULL DEFAULT NULL
	);

  SET i = 1;
  REPEAT
    INSERT INTO my_splits (TempVendorRateID, Code, CountryCode)
      SELECT TempVendorRateID , FnStringSplit(Code, p_dialcodeSeparator, i), CountryCode  FROM tblTempVendorRate
      WHERE FnStringSplit(Code, p_dialcodeSeparator , i) IS NOT NULL
			 AND ProcessId = p_processId;
    SET i = i + 1;
    UNTIL ROW_COUNT() = 0
  END REPEAT;

  UPDATE my_splits SET Code = trim(Code);

	INSERT INTO my_splits (TempVendorRateID, Code, CountryCode)
	SELECT TempVendorRateID , Code, CountryCode  FROM tblTempVendorRate
	WHERE (CountryCode IS NOT NULL AND CountryCode <> '') AND (Code IS NULL OR Code = '')
	AND ProcessId = p_processId;



  DROP TEMPORARY TABLE IF EXISTS tmp_newvendor_splite_;
	CREATE TEMPORARY TABLE tmp_newvendor_splite_  (
		RowID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
		TempVendorRateID INT(11) NULL DEFAULT NULL,
		Code VARCHAR(500) NULL DEFAULT NULL,
		CountryCode VARCHAR(500) NULL DEFAULT NULL
	);

	INSERT INTO tmp_newvendor_splite_(TempVendorRateID,Code,CountryCode)
	SELECT
		TempVendorRateID,
		Code,
		CountryCode
	FROM my_splits
	WHERE Code like '%-%'
		AND TempVendorRateID IS NOT NULL;



	SET v_pointer_ = 1;
	SET v_rowCount_ = (SELECT COUNT(*)FROM tmp_newvendor_splite_);

	WHILE v_pointer_ <= v_rowCount_
	DO
		SET v_TempVendorRateID_ = (SELECT TempVendorRateID FROM tmp_newvendor_splite_ t WHERE t.RowID = v_pointer_);
		SET v_Code_ = (SELECT Code FROM tmp_newvendor_splite_ t WHERE t.RowID = v_pointer_);
		SET v_CountryCode_ = (SELECT CountryCode FROM tmp_newvendor_splite_ t WHERE t.RowID = v_pointer_);

		Call prc_SplitAndInsertVendorRate(v_TempVendorRateID_,v_Code_,v_CountryCode_);

	SET v_pointer_ = v_pointer_ + 1;
	END WHILE;


	DELETE FROM my_splits
		WHERE Code like '%-%'
			AND TempVendorRateID IS NOT NULL;

	DELETE FROM my_splits
		WHERE (Code = '' OR Code IS NULL) AND (CountryCode = '' OR CountryCode IS NULL);

	 INSERT INTO tmp_split_VendorRate_
	SELECT DISTINCT
		   my_splits.TempVendorRateID as `TempVendorRateID`,
		   `CodeDeckId`,
		   CONCAT(IFNULL(my_splits.CountryCode,''),my_splits.Code) as Code,
		   `Description`,
			`Rate`,
			`EffectiveDate`,
			`EndDate`,
			`Change`,
			`ProcessId`,
			`Preference`,
			`ConnectionFee`,
			`Interval1`,
			`IntervalN`,
			`Forbidden`,
			`DialStringPrefix`
		 FROM my_splits
		   INNER JOIN tblTempVendorRate
				ON my_splits.TempVendorRateID = tblTempVendorRate.TempVendorRateID
		  WHERE	tblTempVendorRate.ProcessId = p_processId;

	END IF;




	IF p_dialcodeSeparator = 'null'
	THEN

		INSERT INTO tmp_split_VendorRate_
		SELECT DISTINCT
			  `TempVendorRateID`,
			  `CodeDeckId`,
			   CONCAT(IFNULL(tblTempVendorRate.CountryCode,''),tblTempVendorRate.Code) as Code,
			   `Description`,
				`Rate`,
				`EffectiveDate`,
				`EndDate`,
				`Change`,
				`ProcessId`,
				`Preference`,
				`ConnectionFee`,
				`Interval1`,
				`IntervalN`,
				`Forbidden`,
				`DialStringPrefix`
			 FROM tblTempVendorRate
			  WHERE ProcessId = p_processId;

	END IF;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_VendorRateUpdateDelete`;
DELIMITER //
CREATE PROCEDURE `prc_VendorRateUpdateDelete`(
	IN `p_CompanyId` INT,
	IN `p_AccountId` INT,
	IN `p_VendorRateId` LONGTEXT,
	IN `p_EffectiveDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_Rate` decimal(18,6),
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_ConnectionFee` decimal(18,6),
	IN `p_Critearea_CountryId` INT,
	IN `p_Critearea_Code` varchar(50),
	IN `p_Critearea_Description` varchar(200),
	IN `p_Critearea_Effective` VARCHAR(50),
	IN `p_TrunkId` INT,
	IN `p_ModifiedBy` varchar(50),
	IN `p_Critearea` INT,
	IN `p_action` INT
)
ThisSP:BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	--	p_action = 1 = update rates
	--	p_action = 2 = delete rates

	DROP TEMPORARY TABLE IF EXISTS tmp_TempVendorRate_;
	CREATE TEMPORARY TABLE tmp_TempVendorRate_ (
		`VendorRateId` int(11) NOT NULL,
		`RateId` int(11) NOT NULL,
		`AccountId` int(11) NOT NULL,
		`TrunkID` int(11) NOT NULL,
		`Rate` decimal(18,6) NOT NULL DEFAULT '0.000000',
		`EffectiveDate` datetime NOT NULL,
		`EndDate` datetime DEFAULT NULL,
		`updated_at` datetime DEFAULT NULL,
		`created_at` datetime DEFAULT NULL,
		`created_by` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
		`updated_by` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
		`Interval1` int(11) DEFAULT NULL,
		`IntervalN` int(11) DEFAULT NULL,
		`ConnectionFee` decimal(18,6) DEFAULT NULL,
		`MinimumCost` decimal(18,6) DEFAULT NULL
	);

	INSERT INTO tmp_TempVendorRate_
	SELECT
		v.VendorRateId,
		v.RateId,
		v.AccountId,
		v.TrunkID,
		IFNULL(p_Rate,v.Rate) AS Rate,
		IFNULL(p_EffectiveDate,v.EffectiveDate) AS EffectiveDate,
		IFNULL(p_EndDate,v.EndDate) AS EndDate,
		NOW() AS updated_at,
		v.created_at,
		v.created_by,
		p_ModifiedBy AS updated_by,
		IFNULL(p_Interval1,v.Interval1) AS Interval1,
		IFNULL(p_IntervalN,v.IntervalN) AS IntervalN,
		IFNULL(p_ConnectionFee,v.ConnectionFee) AS ConnectionFee,
		v.MinimumCost
	FROM
		tblVendorRate v
	INNER JOIN
		tblRate r ON r.RateID = v.RateId
	INNER JOIN
		tblVendorTrunk vt on vt.trunkID = p_TrunkId AND vt.AccountID = p_AccountId AND vt.CodeDeckId = r.CodeDeckId
	WHERE
		(
			p_EffectiveDate IS NULL OR v.RateID NOT IN (
				SELECT
					RateID
				FROM
					tblVendorRate
				WHERE
					EffectiveDate=p_EffectiveDate AND
					((p_Critearea = 0 AND (FIND_IN_SET(VendorRateID,p_VendorRateID) = 0 )) OR p_Critearea = 1) AND
					AccountId = p_AccountId
			)
		)
		AND
		(
			(p_Critearea = 0 AND (FIND_IN_SET(v.VendorRateID,p_VendorRateID) != 0 )) OR
			(
				p_Critearea = 1 AND
				(
					((p_Critearea_CountryId IS NULL) OR (p_Critearea_CountryId IS NOT NULL AND r.CountryId = p_Critearea_CountryId)) AND
					((p_Critearea_Code IS NULL) OR (p_Critearea_Code IS NOT NULL AND r.Code LIKE REPLACE(p_Critearea_Code,'*', '%'))) AND
					((p_Critearea_Description IS NULL) OR (p_Critearea_Description IS NOT NULL AND r.Description LIKE REPLACE(p_Critearea_Description,'*', '%'))) AND
					(
						p_Critearea_Effective = 'All' OR
						(p_Critearea_Effective = 'Now' AND v.EffectiveDate <= NOW() ) OR
						(p_Critearea_Effective = 'Future' AND v.EffectiveDate > NOW() )
					)
				)
			)
		) AND
		v.AccountId = p_AccountId AND
		v.TrunkID = p_TrunkId;

--	select * from tmp_TempVendorRate_;LEAVE ThisSP;

	-- if Effective Date needs to change then remove duplicate codes
	IF p_action = 1 AND p_EffectiveDate IS NOT NULL
	THEN
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_TempVendorRate_2 as (select * from tmp_TempVendorRate_);

		DELETE n1 FROM tmp_TempVendorRate_ n1, tmp_TempVendorRate_2 n2 WHERE n1.VendorRateID < n2.VendorRateID AND  n1.RateID = n2.RateID;
	END IF;

	-- archive and delete rates if action is 2 and also delete rates if action is 1 and rates are updating
	UPDATE
		tblVendorRate v
	INNER JOIN
		tmp_TempVendorRate_ temp ON temp.VendorRateID = v.VendorRateID
	SET
		v.EndDate = NOW()
	WHERE
		temp.VendorRateID = v.VendorRateID;

	CALL prc_ArchiveOldVendorRate(p_AccountId,p_TrunkId,p_ModifiedBy);

	IF p_action = 1
	THEN

		INSERT INTO tblVendorRate (
			RateId,
			AccountId,
			TrunkID,
			Rate,
			EffectiveDate,
			EndDate,
			updated_at,
			created_at,
			created_by,
			updated_by,
			Interval1,
			IntervalN,
			ConnectionFee,
			MinimumCost
		)
		select
			RateId,
			AccountId,
			TrunkID,
			Rate,
			EffectiveDate,
			EndDate,
			updated_at,
			created_at,
			created_by,
			updated_by,
			Interval1,
			IntervalN,
			ConnectionFee,
		MinimumCost
		from
			tmp_TempVendorRate_;

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_WSCronJobDeleteOldCustomerRate`;
DELIMITER //
CREATE PROCEDURE `prc_WSCronJobDeleteOldCustomerRate`(
	IN `p_DeletedBy` TEXT
)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

   /*DELETE cr
   FROM tblCustomerRate cr
   INNER JOIN tblCustomerRate cr2
   ON cr2.CustomerID = cr.CustomerID
   AND cr2.TrunkID = cr.TrunkID
   AND cr2.RateID = cr.RateID
   WHERE   cr.EffectiveDate <= NOW() AND cr2.EffectiveDate <= NOW() AND cr.EffectiveDate < cr2.EffectiveDate;*/

   /* SET EndDate of current time to older rates */
	-- for example there are 3 rates, today's date is 2018-04-11
	-- 1. Code 	Rate 	EffectiveDate
	-- 1. 91 	0.1 	2018-04-09
	-- 2. 91 	0.2 	2018-04-10
	-- 3. 91 	0.3 	2018-04-11
	/* Then it will delete 2018-04-09 and 2018-04-10 date's rate */
	UPDATE
		tblCustomerRate cr
	INNER JOIN tblCustomerRate cr2
		ON cr2.CustomerID = cr.CustomerID
		AND cr2.TrunkID = cr.TrunkID
		AND cr2.RateID = cr.RateID
	SET
		cr.EndDate=NOW()
	WHERE
		cr.EffectiveDate <= NOW() AND
		cr2.EffectiveDate <= NOW() AND
		cr.EffectiveDate < cr2.EffectiveDate;

   INSERT INTO tblCustomerRateArchive
	SELECT DISTINCT  null , -- Primary Key column
		`CustomerRateID`,
		`CustomerID`,
		`TrunkID`,
		`RateId`,
		`Rate`,
		`EffectiveDate`,
		IFNULL(`EndDate`,date(now())) as EndDate,
		now() as `created_at`,
		p_DeletedBy AS `created_by`,
		`LastModifiedDate`,
		`LastModifiedBy`,
		`Interval1`,
		`IntervalN`,
		`ConnectionFee`,
		`RoutinePlan`,
		concat('Ends Today rates @ ' , now() ) as `Notes`
	FROM
		tblCustomerRate
	WHERE
		EndDate <= NOW();


	DELETE  cr
	FROM tblCustomerRate cr
	INNER JOIN tblCustomerRateArchive cra
	ON cr.CustomerRateID = cra.CustomerRateID;

   SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_WSCronJobDeleteOldRateTableRate`;
DELIMITER //
CREATE PROCEDURE `prc_WSCronJobDeleteOldRateTableRate`(
	IN `p_DeletedBy` TEXT
)
ThisSP:BEGIN

/*	 SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

   DELETE rtr
      FROM tblRateTableRate rtr
      INNER JOIN tblRateTableRate rtr2
      ON rtr.RateTableId = rtr2.RateTableId
      AND rtr.RateID = rtr2.RateID
      WHERE rtr.EffectiveDate <= NOW()
			AND rtr2.EffectiveDate <= NOW()
         AND rtr.EffectiveDate < rtr2.EffectiveDate;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;      */

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	-- UPDATE tblRateTableRate SET EndDate=NULL where EndDate='0000-00-00';

	UPDATE
		tblRateTableRate rtr
	INNER JOIN tblRateTableRate rtr2
		ON rtr2.RateTableId = rtr.RateTableId
		AND rtr2.RateID = rtr.RateID
	SET
		rtr.EndDate=NOW()
	WHERE
		rtr.EffectiveDate <= NOW() AND
		rtr2.EffectiveDate <= NOW() AND
		rtr.EffectiveDate < rtr2.EffectiveDate;

	INSERT INTO tblRateTableRateArchive
   SELECT DISTINCT  null , -- Primary Key column
							vr.`RateTableRateID`,
							vr.`RateTableId`,
							vr.`RateId`,
							vr.`Rate`,
							vr.`EffectiveDate`,
							IFNULL(vr.`EndDate`,date(now())) as EndDate,
							vr.`updated_at`,
							now() as created_at,
							p_DeletedBy AS `created_by`,
							vr.`ModifiedBy`,
							vr.`Interval1`,
							vr.`IntervalN`,
							vr.`ConnectionFee`,
	   					concat('Ends Today rates @ ' , now() ) as `Notes`
      FROM
			tblRateTableRate vr
		WHERE
			vr.EndDate <= NOW();


	DELETE  vr
	FROM tblRateTableRate vr
   inner join tblRateTableRateArchive vra
   on vr.RateTableRateID = vra.RateTableRateID;


	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END//
DELIMITER ;


DROP PROCEDURE IF EXISTS `prc_WSGenerateRateSheet`;
DELIMITER //
CREATE PROCEDURE `prc_WSGenerateRateSheet`(
	IN `p_CustomerID` INT,
	IN `p_Trunk` VARCHAR(100)
)
BEGIN
		DECLARE v_trunkDescription_ VARCHAR(50);
		DECLARE v_lastRateSheetID_ INT ;
		DECLARE v_IncludePrefix_ TINYINT;
		DECLARE v_Prefix_ VARCHAR(50);
		DECLARE v_codedeckid_  INT;
		DECLARE v_ratetableid_ INT;
		DECLARE v_RateTableAssignDate_  DATETIME;
		DECLARE v_NewA2ZAssign_ INT;

		SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;


		SELECT trunk INTO v_trunkDescription_
		FROM   tblTrunk
		WHERE  TrunkID = p_Trunk;

		DROP TEMPORARY TABLE IF EXISTS tmp_RateSheetRate_;
		CREATE TEMPORARY TABLE tmp_RateSheetRate_(
			RateID        INT,
			Destination   VARCHAR(200),
			Codes         VARCHAR(50),
			Interval1     INT,
			IntervalN     INT,
			Rate          DECIMAL(18, 6),
			`level`         VARCHAR(50),
			`change`        VARCHAR(50),
			EffectiveDate  DATE,
			EndDate  DATE,
			INDEX tmp_RateSheetRate_RateID (`RateID`)
		);
		DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates_;
		CREATE TEMPORARY TABLE tmp_CustomerRates_ (
			RateID INT,
			Interval1 INT,
			IntervalN  INT,
			Rate DECIMAL(18, 6),
			EffectiveDate DATE,
			EndDate DATE,
			LastModifiedDate DATETIME,
			INDEX tmp_CustomerRates_RateId (`RateID`)
		);
		DROP TEMPORARY TABLE IF EXISTS tmp_RateTableRate_;
		CREATE TEMPORARY TABLE tmp_RateTableRate_ (
			RateID INT,
			Interval1 INT,
			IntervalN  INT,
			Rate DECIMAL(18, 6),
			EffectiveDate DATE,
			EndDate DATE,
			updated_at DATETIME,
			INDEX tmp_RateTableRate_RateId (`RateID`)
		);

		DROP TEMPORARY TABLE IF EXISTS tmp_RateSheetDetail_;
		CREATE TEMPORARY TABLE tmp_RateSheetDetail_ (
			ratesheetdetailsid int,
			RateID int ,
			RateSheetID int,
			Destination varchar(200),
			Code varchar(50),
			Rate DECIMAL(18, 6),
			`change` varchar(50),
			EffectiveDate Date,
			EndDate DATE,
			INDEX tmp_RateSheetDetail_RateId (`RateID`,`RateSheetID`)
		);
		SELECT RateSheetID INTO v_lastRateSheetID_
		FROM   tblRateSheet
		WHERE  CustomerID = p_CustomerID
					 AND level = v_trunkDescription_
		ORDER  BY RateSheetID DESC LIMIT 1 ;

		SELECT includeprefix INTO v_IncludePrefix_
		FROM   tblCustomerTrunk
		WHERE  AccountID = p_CustomerID
					 AND TrunkID = p_Trunk;

		SELECT prefix INTO v_Prefix_
		FROM   tblCustomerTrunk
		WHERE  AccountID = p_CustomerID
					 AND TrunkID = p_Trunk;


		SELECT
			CodeDeckId,
			RateTableID,
			RateTableAssignDate
		INTO v_codedeckid_, v_ratetableid_, v_RateTableAssignDate_
		FROM tblCustomerTrunk
		WHERE tblCustomerTrunk.TrunkID = p_Trunk
					AND tblCustomerTrunk.AccountID = p_CustomerID
					AND tblCustomerTrunk.Status = 1;

		INSERT INTO tmp_CustomerRates_
			SELECT  tblCustomerRate.RateID,
				tblCustomerRate.Interval1,
				tblCustomerRate.IntervalN,
				tblCustomerRate.Rate,
				effectivedate,
				tblCustomerRate.EndDate,
				lastmodifieddate
			FROM   tblAccount
				JOIN tblCustomerRate
					ON tblAccount.AccountID = tblCustomerRate.CustomerID
				JOIN tblRate
					ON tblRate.RateId = tblCustomerRate.RateId
						 AND tblRate.CodeDeckId = v_codedeckid_
			WHERE  tblAccount.AccountID = p_CustomerID
						 AND tblCustomerRate.TrunkID = p_Trunk
			ORDER BY tblCustomerRate.CustomerID,tblCustomerRate.TrunkID,tblCustomerRate.RateID,tblCustomerRate.EffectiveDate DESC;

		DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates4_;
		DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates2_;

		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates4_ as (select * from tmp_CustomerRates_);
		DELETE n1 FROM tmp_CustomerRates_ n1, tmp_CustomerRates4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate
																																			 AND  n1.RateId = n2.RateId;

		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates2_ as (select * from tmp_CustomerRates_);

		INSERT INTO tmp_RateTableRate_
			SELECT
				tblRateTableRate.RateID,
				tblRateTableRate.Interval1,
				tblRateTableRate.IntervalN,
				tblRateTableRate.Rate,
				tblRateTableRate.EffectiveDate,
				tblRateTableRate.EndDate,
				tblRateTableRate.updated_at
			FROM tblAccount
				JOIN tblCustomerTrunk
					ON tblCustomerTrunk.AccountID = tblAccount.AccountID
				JOIN tblRateTable
					ON tblCustomerTrunk.ratetableid = tblRateTable.ratetableid
				JOIN tblRateTableRate
					ON tblRateTableRate.ratetableid = tblRateTable.ratetableid
				LEFT JOIN tmp_CustomerRates_ trc1
					ON trc1.RateID = tblRateTableRate.RateID
			WHERE  tblAccount.AccountID = p_CustomerID

						 AND tblCustomerTrunk.TrunkID = p_Trunk
						 AND (( tblRateTableRate.EffectiveDate <= Now()
										AND ( ( trc1.RateID IS NULL )
													OR ( trc1.RateID IS NOT NULL
															 AND tblRateTableRate.ratetablerateid IS NULL )
										) )
									OR ( tblRateTableRate.EffectiveDate > Now()
											 AND ( ( trc1.RateID IS NULL )
														 OR ( trc1.RateID IS NOT NULL
																	AND tblRateTableRate.EffectiveDate < (SELECT
																																					IFNULL(MIN(crr.EffectiveDate),
																																								 tblRateTableRate.EffectiveDate)
																																				FROM   tmp_CustomerRates2_ crr
																																				WHERE  crr.RateID =
																																							 tblRateTableRate.RateID
			) ) ) ) )
			ORDER BY tblRateTableRate.RateID,tblRateTableRate.EffectiveDate desc;

		DROP TEMPORARY TABLE IF EXISTS tmp_RateTableRate4_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_RateTableRate4_ as (select * from tmp_RateTableRate_);
		DELETE n1 FROM tmp_RateTableRate_ n1, tmp_RateTableRate4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate
																																			 AND  n1.RateId = n2.RateId;

		INSERt INTO tmp_RateSheetDetail_
			SELECT ratesheetdetailsid,
				RateID,
				RateSheetID,
				Destination,
				Code,
				Rate,
				`change`,
				effectivedate,
				EndDate
			FROM   tblRateSheetDetails
			WHERE  RateSheetID = v_lastRateSheetID_
			ORDER BY RateID,effectivedate desc;

		DROP TEMPORARY TABLE IF EXISTS tmp_RateSheetDetail4_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_RateSheetDetail4_ as (select * from tmp_RateSheetDetail_);
		DELETE n1 FROM tmp_RateSheetDetail_ n1, tmp_RateSheetDetail4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate
																																					 AND  n1.RateId = n2.RateId;


