-- Table structure for table `tblDimDate`
--

CREATE TABLE `tblDimDate` (
  `DateID` bigint(20) NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `day` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `day_abbrev` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL,
  `day_of_week` int(11) DEFAULT NULL,
  `day_of_month` int(11) DEFAULT NULL,
  `day_of_quarter` int(11) DEFAULT NULL,
  `day_of_semester` int(11) DEFAULT NULL,
  `day_of_year` int(11) DEFAULT NULL,
  `weekend` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Weekday',
  `week_of_month` int(11) DEFAULT NULL,
  `week_of_quarter` int(11) DEFAULT NULL,
  `week_of_semester` int(11) DEFAULT NULL,
  `week_of_year` int(11) DEFAULT NULL,
  `month` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `month_abbrev` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL,
  `month_of_quarter` int(11) DEFAULT NULL,
  `month_of_year` int(11) DEFAULT NULL,
  `quarter_of_year` int(11) DEFAULT NULL,
  `previous_day` date NOT NULL,
  `next_day` date NOT NULL,
  `start_week` date NOT NULL,
  `end_week` date NOT NULL,
  `start_month` date NOT NULL,
  `end_month` date NOT NULL,
  `start_quarter` date NOT NULL,
  `end_quarter` date NOT NULL,
  `year` int(11) DEFAULT NULL,
  `week_month_name` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  `week_quarter_name` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  `week_year_name` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  `month_quarter_name` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  `month_year_name` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  `quarter_year_name` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`DateID`),
  UNIQUE KEY `date` (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblDimTime`
--

CREATE TABLE `tblDimTime` (
  `TimeID` int(11) NOT NULL AUTO_INCREMENT,
  `fulltime` time DEFAULT NULL,
  `hour` int(11) DEFAULT NULL,
  `minute` int(11) DEFAULT NULL,
  `second` int(11) DEFAULT NULL,
  `ampm` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`TimeID`),
  KEY `IX_fulltime` (`fulltime`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblHeader`
--

CREATE TABLE `tblHeader` (
  `HeaderID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `DateID` bigint(20) NOT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
  `TotalCharges` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT NULL,
  `NoOfFailCalls` int(11) DEFAULT NULL,
  `TotalCost` double DEFAULT NULL,
  PRIMARY KEY (`HeaderID`),
  UNIQUE KEY `Unique_key` (`DateID`,`AccountID`,`CompanyID`),
  KEY `FK_tblSummaryHeaderNew_dim_date` (`DateID`),
  KEY `IX_CompanyID` (`CompanyID`),
  CONSTRAINT `tblHeader_ibfk_1` FOREIGN KEY (`DateID`) REFERENCES `tblDimDate` (`DateID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblHeaderV`
--

CREATE TABLE `tblHeaderV` (
  `HeaderVID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `DateID` bigint(20) NOT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
  `TotalCharges` double DEFAULT NULL,
  `TotalSales` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT NULL,
  `NoOfFailCalls` int(11) DEFAULT NULL,
  PRIMARY KEY (`HeaderVID`),
  UNIQUE KEY `Unique_key` (`DateID`,`VAccountID`),
  KEY `FK_tblHeaderV_dim_date` (`DateID`),
  KEY `IX_CompanyID` (`CompanyID`),
  CONSTRAINT `tblHeader_ibfk_2` FOREIGN KEY (`DateID`) REFERENCES `tblDimDate` (`DateID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblRRate`
--

CREATE TABLE `tblRRate` (
  `RRateID` int(11) NOT NULL AUTO_INCREMENT,
  `CountryID` int(11) DEFAULT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `Code` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`RRateID`),
  UNIQUE KEY `UK` (`CompanyID`,`Code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblRTrunk`
--

CREATE TABLE `tblRTrunk` (
  `RTrunkID` int(11) NOT NULL AUTO_INCREMENT,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `CompanyID` int(11) NOT NULL,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`RTrunkID`),
  UNIQUE KEY `UK` (`CompanyID`,`Trunk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblReport`
--

CREATE TABLE `tblReport` (
  `ReportID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `CompanyID` int(11) DEFAULT NULL,
  `Name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Settings` longtext COLLATE utf8_unicode_ci,
  `Type` tinyint(4) DEFAULT '0',
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
  `CreatedBy` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP,
  `UpdatedBy` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`ReportID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblReportSchedule`
--

CREATE TABLE `tblReportSchedule` (
  `ReportScheduleID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `CompanyID` int(11) DEFAULT NULL,
  `Name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ReportID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Settings` longtext COLLATE utf8_unicode_ci,
  `Status` tinyint(4) DEFAULT NULL,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
  `CreatedBy` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `updated_at` datetime DEFAULT CURRENT_TIMESTAMP,
  `UpdatedBy` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`ReportScheduleID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblReportScheduleLog`
--

CREATE TABLE `tblReportScheduleLog` (
  `ReportScheduleLogID` int(11) NOT NULL AUTO_INCREMENT,
  `ReportScheduleID` int(11) DEFAULT NULL,
  `AccountEmailLogID` int(11) DEFAULT NULL,
  `send_at` datetime DEFAULT CURRENT_TIMESTAMP,
  `SendBy` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`ReportScheduleLogID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblUsageSummaryDay`
--

CREATE TABLE `tblUsageSummaryDay` (
  `UsageSummaryDayID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `HeaderID` bigint(20) unsigned NOT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT NULL,
  `NoOfFailCalls` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CountryID` int(11) DEFAULT NULL,
  `userfield` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TotalCost` double DEFAULT NULL,
  PRIMARY KEY (`UsageSummaryDayID`),
  KEY `FK_tblUsageSummaryNew_dim_date` (`HeaderID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblUsageSummaryDayLive`
--

CREATE TABLE `tblUsageSummaryDayLive` (
  `UsageSummaryDayLiveID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `HeaderID` bigint(20) unsigned NOT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT NULL,
  `NoOfFailCalls` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CountryID` int(11) DEFAULT NULL,
  `userfield` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TotalCost` double DEFAULT NULL,
  PRIMARY KEY (`UsageSummaryDayLiveID`),
  KEY `FK_tblUsageSummaryNew_dim_date` (`HeaderID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblUsageSummaryHour`
--

CREATE TABLE `tblUsageSummaryHour` (
  `UsageSummaryHourID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `HeaderID` bigint(20) unsigned NOT NULL,
  `TimeID` int(11) NOT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT NULL,
  `NoOfFailCalls` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CountryID` int(11) DEFAULT NULL,
  `userfield` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TotalCost` double DEFAULT NULL,
  PRIMARY KEY (`UsageSummaryHourID`),
  KEY `FK_tblUsageSummaryDetailNew_dim_time` (`TimeID`),
  KEY `FK_tblUsageSummaryDetailNew_tblSummaryHeader` (`HeaderID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblUsageSummaryHourLive`
--

CREATE TABLE `tblUsageSummaryHourLive` (
  `UsageSummaryHourLiveID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `HeaderID` bigint(20) unsigned NOT NULL,
  `TimeID` int(11) NOT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT NULL,
  `NoOfFailCalls` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CountryID` int(11) DEFAULT NULL,
  `userfield` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TotalCost` double DEFAULT NULL,
  PRIMARY KEY (`UsageSummaryHourLiveID`),
  KEY `FK_tblUsageSummaryDetailNew_dim_time` (`TimeID`),
  KEY `FK_tblUsageSummaryDetailNew_tblSummaryHeader` (`HeaderID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblVendorSummaryDay`
--

CREATE TABLE `tblVendorSummaryDay` (
  `VendorSummaryDayID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `HeaderVID` bigint(20) unsigned NOT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalSales` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT NULL,
  `NoOfFailCalls` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CountryID` int(11) DEFAULT NULL,
  PRIMARY KEY (`VendorSummaryDayID`),
  KEY `FK_tblVendorSummaryNew_dim_date` (`HeaderVID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblVendorSummaryDayLive`
--

CREATE TABLE `tblVendorSummaryDayLive` (
  `VendorSummaryDayLiveID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `HeaderVID` bigint(20) unsigned NOT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalSales` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT NULL,
  `NoOfFailCalls` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CountryID` int(11) DEFAULT NULL,
  PRIMARY KEY (`VendorSummaryDayLiveID`),
  KEY `FK_tblVendorSummaryNew_dim_date` (`HeaderVID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblVendorSummaryHour`
--

CREATE TABLE `tblVendorSummaryHour` (
  `VendorSummaryHourID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `HeaderVID` bigint(20) unsigned NOT NULL,
  `TimeID` int(11) NOT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalSales` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT NULL,
  `NoOfFailCalls` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CountryID` int(11) DEFAULT NULL,
  PRIMARY KEY (`VendorSummaryHourID`),
  KEY `FK_tblVendorSummaryDetailNew_dim_time` (`TimeID`),
  KEY `FK_tblVendorSummaryDetailNew_tblSummaryHeader` (`HeaderVID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tblVendorSummaryHourLive`
--

CREATE TABLE `tblVendorSummaryHourLive` (
  `VendorSummaryHourLiveID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `HeaderVID` bigint(20) unsigned NOT NULL,
  `TimeID` int(11) NOT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalSales` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT NULL,
  `NoOfFailCalls` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CountryID` int(11) DEFAULT NULL,
  PRIMARY KEY (`VendorSummaryHourLiveID`),
  KEY `FK_tblVendorSummaryDetailNew_dim_time` (`TimeID`),
  KEY `FK_tblVendorSummaryDetailNew_tblSummaryHeader` (`HeaderVID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_SummaryHeader`
--

CREATE TABLE `tmp_SummaryHeader` (
  `HeaderID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `DateID` bigint(20) NOT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  PRIMARY KEY (`HeaderID`),
  KEY `Unique_key` (`DateID`,`CompanyID`,`AccountID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_SummaryHeaderLive`
--

CREATE TABLE `tmp_SummaryHeaderLive` (
  `HeaderID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `DateID` bigint(20) NOT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  PRIMARY KEY (`HeaderID`),
  KEY `Unique_key` (`DateID`,`CompanyID`,`AccountID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_SummaryVendorHeader`
--

CREATE TABLE `tmp_SummaryVendorHeader` (
  `HeaderVID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `DateID` bigint(20) NOT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  PRIMARY KEY (`HeaderVID`),
  KEY `Unique_key` (`DateID`,`CompanyID`,`VAccountID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_SummaryVendorHeaderLive`
--

CREATE TABLE `tmp_SummaryVendorHeaderLive` (
  `HeaderVID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `DateID` bigint(20) NOT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  PRIMARY KEY (`HeaderVID`),
  KEY `Unique_key` (`DateID`,`CompanyID`,`VAccountID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_UsageSummary`
--

CREATE TABLE `tmp_UsageSummary` (
  `UsageSummaryID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `DateID` bigint(20) NOT NULL,
  `TimeID` int(11) NOT NULL,
  `CompanyID` int(11) NOT NULL,
  `CompanyGatewayID` int(11) NOT NULL,
  `AccountID` int(11) NOT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT '0',
  `NoOfFailCalls` int(11) DEFAULT '0',
  `FinalStatus` int(11) DEFAULT '0',
  `CountryID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  `userfield` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TotalCost` double DEFAULT NULL,
  PRIMARY KEY (`UsageSummaryID`),
  KEY `tblUsageSummary_dim_date` (`DateID`),
  KEY `tmp_UsageSummary_AreaPrefix` (`AreaPrefix`),
  KEY `IX_CompanyID` (`CompanyID`),
  KEY `Unique_key` (`DateID`,`CompanyID`,`AccountID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_UsageSummaryLive`
--

CREATE TABLE `tmp_UsageSummaryLive` (
  `UsageSummaryLiveID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `DateID` bigint(20) NOT NULL,
  `TimeID` int(11) NOT NULL,
  `CompanyID` int(11) NOT NULL,
  `CompanyGatewayID` int(11) NOT NULL,
  `AccountID` int(11) NOT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT '0',
  `NoOfFailCalls` int(11) DEFAULT '0',
  `FinalStatus` int(11) DEFAULT '0',
  `CountryID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  `userfield` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TotalCost` double DEFAULT NULL,
  PRIMARY KEY (`UsageSummaryLiveID`),
  KEY `tmp_UsageSummary_AreaPrefix` (`AreaPrefix`),
  KEY `IX_CompanyID` (`CompanyID`),
  KEY `tblUsageSummary_dim_date` (`DateID`),
  KEY `Unique_key` (`DateID`,`CompanyID`,`AccountID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_VendorUsageSummary`
--

CREATE TABLE `tmp_VendorUsageSummary` (
  `VendorUsageSummaryID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `DateID` bigint(20) NOT NULL,
  `TimeID` int(11) NOT NULL,
  `CompanyID` int(11) NOT NULL,
  `CompanyGatewayID` int(11) NOT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalSales` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT '0',
  `NoOfFailCalls` int(11) DEFAULT '0',
  `FinalStatus` int(11) DEFAULT '0',
  `CountryID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `VAccountID` int(11) NOT NULL,
  PRIMARY KEY (`VendorUsageSummaryID`),
  KEY `tmp_VendorUsageSummary_dim_date` (`DateID`),
  KEY `tmp_VendorUsageSummary_AreaPrefix` (`AreaPrefix`),
  KEY `IX_CompanyID` (`CompanyID`),
  KEY `Unique_key` (`DateID`,`CompanyID`,`VAccountID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_VendorUsageSummaryLive`
--

CREATE TABLE `tmp_VendorUsageSummaryLive` (
  `VendorUsageSummaryLiveID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `DateID` bigint(20) NOT NULL,
  `TimeID` int(11) NOT NULL,
  `CompanyID` int(11) NOT NULL,
  `CompanyGatewayID` int(11) NOT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `Trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AreaPrefix` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TotalCharges` double DEFAULT NULL,
  `TotalSales` double DEFAULT NULL,
  `TotalBilledDuration` int(11) DEFAULT NULL,
  `TotalDuration` int(11) DEFAULT NULL,
  `NoOfCalls` int(11) DEFAULT '0',
  `NoOfFailCalls` int(11) DEFAULT '0',
  `FinalStatus` int(11) DEFAULT '0',
  `CountryID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `VAccountID` int(11) NOT NULL,
  PRIMARY KEY (`VendorUsageSummaryLiveID`),
  KEY `tmp_VendorUsageSummary_dim_date` (`DateID`),
  KEY `tmp_VendorUsageSummary_AreaPrefix` (`AreaPrefix`),
  KEY `IX_CompanyID` (`CompanyID`),
  KEY `Unique_key` (`DateID`,`CompanyID`,`AccountID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_tblUsageDetailsReport`
--

CREATE TABLE `tmp_tblUsageDetailsReport` (
  `UsageDetailsReportID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `UsageDetailID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `GatewayAccountID` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `area_prefix` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `duration` int(11) DEFAULT NULL,
  `billed_duration` int(11) DEFAULT NULL,
  `cost` decimal(18,6) DEFAULT NULL,
  `connect_time` time DEFAULT NULL,
  `connect_date` date DEFAULT NULL,
  `call_status` tinyint(4) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT '0',
  PRIMARY KEY (`UsageDetailsReportID`),
  KEY `temp_connect_time` (`connect_time`,`connect_date`),
  KEY `IX_CompanyID` (`CompanyID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_tblUsageDetailsReportLive`
--

CREATE TABLE `tmp_tblUsageDetailsReportLive` (
  `UsageDetailsReportLiveID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `UsageDetailID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `GatewayAccountID` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `area_prefix` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `duration` int(11) DEFAULT NULL,
  `billed_duration` int(11) DEFAULT NULL,
  `cost` decimal(18,6) DEFAULT NULL,
  `connect_time` time DEFAULT NULL,
  `connect_date` date DEFAULT NULL,
  `call_status` tinyint(4) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT '0',
  PRIMARY KEY (`UsageDetailsReportLiveID`),
  KEY `temp_connect_time` (`connect_time`,`connect_date`),
  KEY `IX_CompanyID` (`CompanyID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_tblUsageDetailsReport_120181111Live`
--

CREATE TABLE `tmp_tblUsageDetailsReport_120181111Live` (
  `UsageDetailsReportID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `UsageDetailID` bigint(20) unsigned DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `connect_time` time DEFAULT NULL,
  `connect_date` date DEFAULT NULL,
  `billed_duration` int(11) DEFAULT NULL,
  `area_prefix` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cost` decimal(18,6) DEFAULT NULL,
  `buying_cost` decimal(18,6) DEFAULT NULL,
  `duration` int(11) DEFAULT NULL,
  `trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `call_status` tinyint(4) DEFAULT NULL,
  `call_status_v` tinyint(4) DEFAULT NULL,
  `disposition` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `userfield` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pincode` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `extension` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ID` bigint(20) unsigned DEFAULT NULL,
  PRIMARY KEY (`UsageDetailsReportID`),
  UNIQUE KEY `UK` (`UsageDetailID`,`call_status`),
  KEY `temp_connect_time` (`connect_time`,`connect_date`),
  KEY `IX_CompanyID` (`CompanyID`),
  KEY `IX_UsageDetailID` (`UsageDetailID`),
  KEY `IX_GCID` (`CompanyGatewayID`,`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_tblUsageDetailsReport_120181112Live`
--

CREATE TABLE `tmp_tblUsageDetailsReport_120181112Live` (
  `UsageDetailsReportID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `UsageDetailID` bigint(20) unsigned DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `connect_time` time DEFAULT NULL,
  `connect_date` date DEFAULT NULL,
  `billed_duration` int(11) DEFAULT NULL,
  `area_prefix` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cost` decimal(18,6) DEFAULT NULL,
  `buying_cost` decimal(18,6) DEFAULT NULL,
  `duration` int(11) DEFAULT NULL,
  `trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `call_status` tinyint(4) DEFAULT NULL,
  `call_status_v` tinyint(4) DEFAULT NULL,
  `disposition` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `userfield` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pincode` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `extension` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ID` bigint(20) unsigned DEFAULT NULL,
  PRIMARY KEY (`UsageDetailsReportID`),
  UNIQUE KEY `UK` (`UsageDetailID`,`call_status`),
  KEY `temp_connect_time` (`connect_time`,`connect_date`),
  KEY `IX_CompanyID` (`CompanyID`),
  KEY `IX_UsageDetailID` (`UsageDetailID`),
  KEY `IX_GCID` (`CompanyGatewayID`,`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_tblVendorUsageDetailsReport`
--

CREATE TABLE `tmp_tblVendorUsageDetailsReport` (
  `VendorUsageDetailsReportID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `VendorCDRID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `GatewayAccountID` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `area_prefix` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `duration` int(11) DEFAULT NULL,
  `billed_duration` int(11) DEFAULT NULL,
  `buying_cost` decimal(18,6) DEFAULT NULL,
  `selling_cost` decimal(18,6) DEFAULT NULL,
  `connect_time` time DEFAULT NULL,
  `connect_date` date DEFAULT NULL,
  `call_status` tinyint(4) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT '0',
  PRIMARY KEY (`VendorUsageDetailsReportID`),
  KEY `temp_connect_time` (`connect_time`,`connect_date`),
  KEY `IX_CompanyID` (`CompanyID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_tblVendorUsageDetailsReportLive`
--

CREATE TABLE `tmp_tblVendorUsageDetailsReportLive` (
  `VendorUsageDetailsReportLiveID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `VendorCDRID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `GatewayAccountID` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `area_prefix` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `duration` int(11) DEFAULT NULL,
  `billed_duration` int(11) DEFAULT NULL,
  `buying_cost` decimal(18,6) DEFAULT NULL,
  `selling_cost` decimal(18,6) DEFAULT NULL,
  `connect_time` time DEFAULT NULL,
  `connect_date` date DEFAULT NULL,
  `call_status` tinyint(4) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT '0',
  PRIMARY KEY (`VendorUsageDetailsReportLiveID`),
  KEY `temp_connect_time` (`connect_time`,`connect_date`),
  KEY `IX_CompanyID` (`CompanyID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_tblVendorUsageDetailsReport_120181111Live`
--

CREATE TABLE `tmp_tblVendorUsageDetailsReport_120181111Live` (
  `VendorUsageDetailsReportID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `VendorCDRID` bigint(20) unsigned DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `connect_time` time DEFAULT NULL,
  `connect_date` date DEFAULT NULL,
  `billed_duration` int(11) DEFAULT NULL,
  `duration` int(11) DEFAULT NULL,
  `selling_cost` decimal(18,6) DEFAULT NULL,
  `buying_cost` decimal(18,6) DEFAULT NULL,
  `trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `area_prefix` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `call_status` tinyint(4) DEFAULT NULL,
  `call_status_v` tinyint(4) DEFAULT NULL,
  `ID` bigint(20) unsigned DEFAULT NULL,
  PRIMARY KEY (`VendorUsageDetailsReportID`),
  UNIQUE KEY `UK` (`VendorCDRID`,`call_status_v`),
  KEY `temp_connect_time` (`connect_time`,`connect_date`),
  KEY `IX_CompanyID` (`CompanyID`),
  KEY `IX_VendorCDRID` (`VendorCDRID`),
  KEY `IX_GCID` (`CompanyGatewayID`,`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Table structure for table `tmp_tblVendorUsageDetailsReport_120181112Live`
--

CREATE TABLE `tmp_tblVendorUsageDetailsReport_120181112Live` (
  `VendorUsageDetailsReportID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `VendorCDRID` bigint(20) unsigned DEFAULT NULL,
  `VAccountID` int(11) DEFAULT NULL,
  `AccountID` int(11) DEFAULT NULL,
  `CompanyID` int(11) DEFAULT NULL,
  `CompanyGatewayID` int(11) DEFAULT NULL,
  `GatewayAccountPKID` int(11) DEFAULT NULL,
  `GatewayVAccountPKID` int(11) DEFAULT NULL,
  `ServiceID` int(11) DEFAULT NULL,
  `connect_time` time DEFAULT NULL,
  `connect_date` date DEFAULT NULL,
  `billed_duration` int(11) DEFAULT NULL,
  `duration` int(11) DEFAULT NULL,
  `selling_cost` decimal(18,6) DEFAULT NULL,
  `buying_cost` decimal(18,6) DEFAULT NULL,
  `trunk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `area_prefix` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `call_status` tinyint(4) DEFAULT NULL,
  `call_status_v` tinyint(4) DEFAULT NULL,
  `ID` bigint(20) unsigned DEFAULT NULL,
  PRIMARY KEY (`VendorUsageDetailsReportID`),
  UNIQUE KEY `UK` (`VendorCDRID`,`call_status_v`),
  KEY `temp_connect_time` (`connect_time`,`connect_date`),
  KEY `IX_CompanyID` (`CompanyID`),
  KEY `IX_VendorCDRID` (`VendorCDRID`),
  KEY `IX_GCID` (`CompanyGatewayID`,`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping routines for database 'telsomespainReport'
--
/*!50003 DROP FUNCTION IF EXISTS `fnDurationmmss` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `fnDurationmmss`(`p_Duration` INT) RETURNS varchar(50) CHARSET utf8 COLLATE utf8_unicode_ci
BEGIN

DECLARE v_FormattedDuration_ VARCHAR(50);

SELECT CONCAT(FLOOR(p_Duration/60), ':' ,p_Duration % 60) INTO v_FormattedDuration_;

RETURN v_FormattedDuration_;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `fnGetCompanyGatewayName` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `fnGetCompanyGatewayName`(`p_CompanyGatewayID` INT) RETURNS varchar(200) CHARSET utf8 COLLATE utf8_unicode_ci
BEGIN
DECLARE v_Title_ VARCHAR(200);

SELECT cg.Title INTO v_Title_ from telsomespainRM.tblCompanyGateway cg where cg.CompanyGatewayID = p_CompanyGatewayID;

RETURN v_Title_;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `fngetLastInvoiceDate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `fngetLastInvoiceDate`(
	`p_AccountID` INT

) RETURNS date
BEGIN
	
	DECLARE v_LastInvoiceDate_ DATE;
	
	SELECT 
		CASE WHEN tblAccountBilling.LastInvoiceDate IS NOT NULL AND tblAccountBilling.LastInvoiceDate <> '' 
		THEN 
			DATE_FORMAT(tblAccountBilling.LastInvoiceDate,'%Y-%m-%d')
		ELSE 
			CASE WHEN tblAccountBilling.BillingStartDate IS NOT NULL AND tblAccountBilling.BillingStartDate <> ''
			THEN
				DATE_FORMAT(tblAccountBilling.BillingStartDate,'%Y-%m-%d')
			ELSE DATE_FORMAT(tblAccount.created_at,'%Y-%m-%d')
			END 
		END
		INTO v_LastInvoiceDate_ 
	FROM telsomespainRM.tblAccount
	LEFT JOIN telsomespainRM.tblAccountBilling 
		ON tblAccountBilling.AccountID = tblAccount.AccountID AND tblAccountBilling.ServiceID = 0
	WHERE tblAccount.AccountID = p_AccountID
	LIMIT 1;
	
	RETURN v_LastInvoiceDate_;
	
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `fngetLastVendorInvoiceDate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `fngetLastVendorInvoiceDate`(
	`p_AccountID` INT





) RETURNS datetime
BEGIN
	
	DECLARE v_LastInvoiceDate_ DATETIME;
	
	SELECT
		CASE WHEN EndDate IS NOT NULL AND EndDate <> '' AND EndDate <> '0000-00-00 00:00:00'
		THEN 
			EndDate
		ELSE 
			CASE WHEN BillingStartDate IS NOT NULL AND BillingStartDate <> ''
			THEN
				DATE_FORMAT(BillingStartDate,'%Y-%m-%d')
			ELSE DATE_FORMAT(tblAccount.created_at,'%Y-%m-%d')
			END 
		END  INTO v_LastInvoiceDate_
 	FROM telsomespainRM.tblAccount
	LEFT JOIN telsomespainRM.tblAccountBilling 
		ON tblAccountBilling.AccountID = tblAccount.AccountID AND tblAccountBilling.ServiceID = 0
	LEFT JOIN telsomespainBilling.tblInvoice 
		ON tblAccount.AccountID = tblInvoice.AccountID AND InvoiceType =2
	LEFT JOIN telsomespainBilling.tblInvoiceDetail
		ON tblInvoice.InvoiceID =  tblInvoiceDetail.InvoiceID
	WHERE tblAccount.AccountID = p_AccountID 
	ORDER BY IssueDate DESC 
	LIMIT 1;

	RETURN v_LastInvoiceDate_;

END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `fnGetMonthDifference` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `fnGetMonthDifference`(`p_Date1` DATE, `p_Date2` DATE) RETURNS int(11)
BEGIN

DECLARE v_Month INT;

SELECT 12 * (YEAR(p_Date2) - YEAR(p_Date1)) + MONTH(p_Date2) -  MONTH(p_Date1) INTO v_Month;

RETURN v_Month;

END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `fnGetRoundingPoint` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `fnGetRoundingPoint`(
	`p_CompanyID` INT

) RETURNS int(11)
BEGIN

DECLARE v_Round_ int;

SELECT cs.Value INTO v_Round_ from telsomespainRM.tblCompanySetting cs where cs.`Key` = 'RoundChargesAmount' AND cs.CompanyID = p_CompanyID AND cs.Value <> '';

SET v_Round_ = IFNULL(v_Round_,2);

RETURN v_Round_;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnDistinctList` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fnDistinctList`(
 IN `p_CompanyID` INT
)
BEGIN

 SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

 INSERT IGNORE INTO tblRRate(Code,CountryID,CompanyID)
 SELECT DISTINCT AreaPrefix,CountryID,CompanyID FROM tmp_UsageSummary
 WHERE tmp_UsageSummary.CompanyID = p_CompanyID;
 
 INSERT IGNORE INTO tblRTrunk(Trunk,CompanyID)
 SELECT DISTINCT Trunk,CompanyID FROM tmp_UsageSummary
 WHERE tmp_UsageSummary.CompanyID = p_CompanyID;
 
 INSERT IGNORE INTO tblRRate(Code,CountryID,CompanyID)
 SELECT DISTINCT AreaPrefix,CountryID,CompanyID FROM tmp_VendorUsageSummary
 WHERE tmp_VendorUsageSummary.CompanyID = p_CompanyID;
 
 INSERT IGNORE INTO tblRTrunk(Trunk,CompanyID)
 SELECT DISTINCT Trunk,CompanyID FROM tmp_VendorUsageSummary
 WHERE tmp_VendorUsageSummary.CompanyID = p_CompanyID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnGetCountry` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fnGetCountry`()
BEGIN

DROP TEMPORARY TABLE IF EXISTS temptblCountry;
CREATE TEMPORARY TABLE IF NOT EXISTS `temptblCountry` (
	`CountryID` INT(11) NOT NULL AUTO_INCREMENT,
	`Prefix` VARCHAR(50) NULL DEFAULT NULL,
	`Country` VARCHAR(100) NULL DEFAULT NULL,
	`ISO2` VARCHAR(5)  NULL DEFAULT NULL,
	`ISO3` VARCHAR(5) NULL DEFAULT NULL,
	PRIMARY KEY (`CountryID`),
	INDEX tempCountry_Prefix(`Prefix`)
);
INSERT INTO temptblCountry(CountryID,Prefix,Country,ISO2,ISO3)
SELECT CountryID,Prefix,Country,ISO2,ISO3 FROM telsomespainRM.tblCountry;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnGetCRMUnBilledData` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fnGetCRMUnBilledData`(
	IN `p_CompanyID` INT,
	IN `p_OwnerID` VARCHAR(500),
	IN `p_CurrencyID` INT,
	IN `p_ListType` VARCHAR(50),
	IN `p_Start` DATETIME,
	IN `p_End` DATETIME
)
BEGIN
	DECLARE v_Round_ INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	DROP TEMPORARY TABLE IF EXISTS tmp_Account_;
	CREATE TEMPORARY TABLE tmp_Account_  (
		RowID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
		AccountID INT,
		LastInvoiceDate DATE
	);
	
	INSERT INTO tmp_Account_ (AccountID)
	SELECT DISTINCT tblHeader.AccountID  FROM tblHeader INNER JOIN telsomespainRM.tblAccount ON tblAccount.AccountID = tblHeader.AccountID WHERE tblHeader.CompanyID = p_CompanyID;
	
	UPDATE tmp_Account_ SET LastInvoiceDate = fngetLastInvoiceDate(AccountID);
	
	INSERT INTO telsomespainRM.tmp_Dashboard_invoices_
	SELECT 
			CONCAT(tu.FirstName,' ',tu.LastName) AS `AssignedUserText`,
			 tu.UserID AS  AssignedUserID,
			sum(h.TotalCharges) AS `Revenue`,
			YEAR(dd.date) AS Year,
			MONTH(dd.date) AS Month,
			WEEK(dd.date)	 AS `Week`
	FROM tmp_Account_ a
	INNER JOIN tblDimDate dd
		ON dd.date >= a.LastInvoiceDate
	INNER JOIN tblHeader h
		ON h.AccountID = a.AccountID
		AND h.DateID = dd.DateID
	INNER JOIN telsomespainRM.tblAccount ac 
			ON ac.AccountID = a.AccountID 
	INNER JOIN telsomespainRM.tblUser tu 
			ON tu.UserID = ac.Owner
	WHERE ac.`Status` = 1
	AND tu.`Status` = 1 		
	AND (p_CurrencyID = '' OR ( p_CurrencyID !=''  AND ac.CurrencyId = p_CurrencyID))
	AND ac.CompanyID = p_CompanyID
	AND (p_OwnerID = '' OR   FIND_IN_SET(tu.UserID,p_OwnerID))
	AND (dd.date BETWEEN p_Start AND p_End)
	  GROUP BY
			YEAR(dd.date) 
			,MONTH(dd.date)
			,WEEK(dd.date)
			,CONCAT(tu.FirstName,' ',tu.LastName)
			,tu.UserID;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnGetCRMUnBilledDataByAccount` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fnGetCRMUnBilledDataByAccount`(
	IN `p_CompanyID` INT,
	IN `p_OwnerID` VARCHAR(500),
	IN `p_CurrencyID` INT,
	IN `p_ListType` VARCHAR(50),
	IN `p_Start` DATETIME,
	IN `p_End` DATETIME,
	IN `p_WeekOrMonth` INT,
	IN `p_Year` INT
)
BEGIN
	DECLARE v_Round_ INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	DROP TEMPORARY TABLE IF EXISTS tmp_Account_;
	CREATE TEMPORARY TABLE tmp_Account_  (
		RowID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
		AccountID INT,
		LastInvoiceDate DATE
	);
	
	INSERT INTO tmp_Account_ (AccountID)
	SELECT DISTINCT tblHeader.AccountID  FROM tblHeader INNER JOIN telsomespainRM.tblAccount ON tblAccount.AccountID = tblHeader.AccountID WHERE tblHeader.CompanyID = p_CompanyID;
	
	UPDATE tmp_Account_ SET LastInvoiceDate = fngetLastInvoiceDate(AccountID);
	
	INSERT INTO telsomespainRM.tmp_Dashboard_user_invoices_
	SELECT 
			ac.AccountName AS `AssignedUserText`,
			sum(h.TotalCharges) AS `Revenue`
	FROM tmp_Account_ a
	INNER JOIN tblDimDate dd
		ON dd.date >= a.LastInvoiceDate
	INNER JOIN tblHeader h
		ON h.AccountID = a.AccountID
		AND h.DateID = dd.DateID
	INNER JOIN telsomespainRM.tblAccount ac 
			ON ac.AccountID = a.AccountID 
	INNER JOIN telsomespainRM.tblUser tu 
			ON tu.UserID = ac.Owner
	WHERE ac.`Status` = 1
	AND tu.`Status` = 1 		
	AND (p_CurrencyID = '' OR ( p_CurrencyID !=''  AND ac.CurrencyId = p_CurrencyID))
	AND ac.CompanyID = p_CompanyID
	AND (p_OwnerID = '' OR   FIND_IN_SET(tu.UserID,p_OwnerID))
	AND (dd.date BETWEEN p_Start AND p_End)
	AND (( p_ListType = 'Weekly' AND WEEK(dd.date) = p_WeekOrMonth AND YEAR(dd.date) = p_Year) OR ( p_ListType = 'Monthly' AND MONTH(dd.date) = p_WeekOrMonth AND YEAR(dd.date) = p_Year))
	GROUP BY
			ac.AccountName;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fngetDefaultCodes` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fngetDefaultCodes`(
	IN `p_CompanyID` INT
)
BEGIN
	
	DROP TEMPORARY TABLE IF EXISTS tmp_codes_;
	CREATE TEMPORARY TABLE tmp_codes_ (
		CountryID INT,
		Code VARCHAR(50),
		Description VARCHAR(200),
		INDEX tmp_codes_CountryID (`CountryID`),
		INDEX tmp_codes_Code (`Code`)
	);

	INSERT INTO tmp_codes_
	SELECT
	DISTINCT
		tblRate.CountryID,
		tblRate.Code,
		tblRate.Description
	FROM telsomespainRM.tblRate
	INNER JOIN telsomespainRM.tblCodeDeck
		ON tblCodeDeck.CodeDeckId = tblRate.CodeDeckId
	WHERE tblCodeDeck.CompanyId = p_CompanyID
	AND tblCodeDeck.DefaultCodedeck = 1 ;
	
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnGetUsageForSummary` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `fnGetUsageForSummary`(
	IN `p_CompanyID` INT,
	IN `p_StartDate` DATE,
	IN `p_EndDate` DATE,
	IN `p_UniqueID` VARCHAR(50)
)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	CALL telsomespainRM.prc_UpdateMysqlPID(p_UniqueID);

	SET @stmt = CONCAT('
	INSERT IGNORE INTO tmp_tblUsageDetailsReport_' , p_UniqueID , ' (
		UsageDetailID,
		AccountID,
		CompanyID,
		CompanyGatewayID,
		GatewayAccountPKID,
		connect_time,
		connect_date,
		billed_duration,
		area_prefix,
		cost,
		duration,
		trunk,
		call_status,
		ServiceID,
		disposition,
		userfield,
		pincode,
		extension,
		ID
	)
	SELECT 
		ud.UsageDetailID,
		uh.AccountID,
		a.CompanyID,
		uh.CompanyGatewayID,
		uh.GatewayAccountPKID,
		CONCAT(DATE_FORMAT(ud.connect_time,"%H"),":",IF(MINUTE(ud.connect_time)<30,"00","30"),":00"),
		DATE_FORMAT(ud.connect_time,"%Y-%m-%d"),
		billed_duration,
		area_prefix,
		cost,
		duration,
		trunk,
		1 as call_status,
		uh.ServiceID,
		disposition,
		userfield,
		pincode,
		extension,
		ID
	FROM telsomespainCDR.tblUsageDetails  ud
	INNER JOIN telsomespainCDR.tblUsageHeader uh
		ON uh.UsageHeaderID = ud.UsageHeaderID
	INNER JOIN telsomespainRM.tblAccount a
		ON a.AccountID = uh.AccountID	
	WHERE
		a.CompanyID = ' , p_CompanyID , '
		AND uh.AccountID IS NOT NULL
	AND uh.StartDate BETWEEN "' , p_StartDate , '" AND "' , p_EndDate , '";
	');

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

	SET @stmt = CONCAT('
	INSERT IGNORE INTO tmp_tblUsageDetailsReport_' , p_UniqueID , ' (
		UsageDetailID,
		AccountID,
		CompanyID,
		CompanyGatewayID,
		GatewayAccountPKID,
		connect_time,
		connect_date,
		billed_duration,
		area_prefix,
		cost,
		duration,
		trunk,
		call_status,
		ServiceID,
		disposition,
		userfield,
		pincode,
		extension,
		ID
	)
	SELECT 
		ud.UsageDetailFailedCallID,
		uh.AccountID,
		a.CompanyID,
		uh.CompanyGatewayID,
		uh.GatewayAccountPKID,
		CONCAT(DATE_FORMAT(ud.connect_time,"%H"),":",IF(MINUTE(ud.connect_time)<30,"00","30"),":00"),
		DATE_FORMAT(ud.connect_time,"%Y-%m-%d"),
		billed_duration,
		area_prefix,
		cost,
		duration,
		trunk,
		2 as call_status,
		uh.ServiceID,
		disposition,
		userfield,
		pincode,
		extension,
		ID
	FROM telsomespainCDR.tblUsageDetailFailedCall  ud
	INNER JOIN telsomespainCDR.tblUsageHeader uh
		ON uh.UsageHeaderID = ud.UsageHeaderID
	INNER JOIN telsomespainRM.tblAccount a
		ON a.AccountID = uh.AccountID	
	WHERE
		a.CompanyID = ' , p_CompanyID , '
	AND uh.AccountID IS NOT NULL
	AND uh.StartDate BETWEEN "' , p_StartDate , '" AND "' , p_EndDate , '";
	');

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

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnGetUsageForSummaryLive` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `fnGetUsageForSummaryLive`(
	IN `p_CompanyID` INT,
	IN `p_StartDate` DATE,
	IN `p_EndDate` DATE
)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	DELETE FROM tmp_tblUsageDetailsReportLive WHERE CompanyID = p_CompanyID;
	
	INSERT INTO tmp_tblUsageDetailsReportLive (UsageDetailID,AccountID,CompanyID,CompanyGatewayID,ServiceID,GatewayAccountID,trunk,area_prefix,duration,billed_duration,cost,connect_time,connect_date,call_status)
	SELECT
		ud.UsageDetailID,
		uh.AccountID,
		a.CompanyID,
		uh.CompanyGatewayID,
		uh.ServiceID,
		uh.GatewayAccountID,
		trunk,
		area_prefix,
		duration,
		billed_duration,
		cost,
		CONCAT(DATE_FORMAT(ud.connect_time,'%H'),':',IF(MINUTE(ud.connect_time)<30,'00','30'),':00'),
		DATE_FORMAT(ud.connect_time,'%Y-%m-%d'),
		1 AS call_status
	FROM telsomespainCDR.tblUsageDetails  ud
	INNER JOIN telsomespainCDR.tblUsageHeader uh
		ON uh.UsageHeaderID = ud.UsageHeaderID
	INNER JOIN telsomespainRM.tblAccount a
		ON a.AccountID = uh.AccountID	
	WHERE
		a.CompanyID = p_CompanyID
	AND uh.AccountID IS NOT NULL
	AND uh.StartDate BETWEEN p_StartDate AND p_EndDate;

	INSERT INTO tmp_tblUsageDetailsReportLive (UsageDetailID,AccountID,CompanyID,CompanyGatewayID,ServiceID,GatewayAccountID,trunk,area_prefix,duration,billed_duration,cost,connect_time,connect_date,call_status)
	SELECT
		ud.UsageDetailFailedCallID,
		uh.AccountID,
		a.CompanyID,
		uh.CompanyGatewayID,
		uh.ServiceID,
		uh.GatewayAccountID,
		trunk,
		area_prefix,
		duration,
		billed_duration,
		cost,
		CONCAT(DATE_FORMAT(ud.connect_time,'%H'),':',IF(MINUTE(ud.connect_time)<30,'00','30'),':00'),
		DATE_FORMAT(ud.connect_time,'%Y-%m-%d'),
		2 AS call_status
	FROM telsomespainCDR.tblUsageDetailFailedCall  ud
	INNER JOIN telsomespainCDR.tblUsageHeader uh
		ON uh.UsageHeaderID = ud.UsageHeaderID
	INNER JOIN telsomespainRM.tblAccount a
		ON a.AccountID = uh.AccountID	
	WHERE
		a.CompanyID = p_CompanyID
	AND uh.AccountID IS NOT NULL
	AND uh.StartDate BETWEEN p_StartDate AND p_EndDate;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnGetVendorUsageForSummary` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `fnGetVendorUsageForSummary`(
	IN `p_CompanyID` INT,
	IN `p_StartDate` DATE,
	IN `p_EndDate` DATE,
	IN `p_UniqueID` VARCHAR(50)

)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	CALL telsomespainRM.prc_UpdateMysqlPID(p_UniqueID);

	SET @stmt = CONCAT('
	INSERT IGNORE INTO tmp_tblVendorUsageDetailsReport_' , p_UniqueID , ' (
		VendorCDRID,
		VAccountID,
		CompanyID,
		CompanyGatewayID,
		GatewayVAccountPKID,
		ServiceID,
		connect_time,
		connect_date,
		billed_duration,
		duration,
		selling_cost,
		buying_cost,
		trunk,
		area_prefix,
		call_status_v,
		ID
	)
	SELECT 
		ud.VendorCDRID,
		uh.AccountID,
		a.CompanyID,
		uh.CompanyGatewayID,
		uh.GatewayAccountPKID,
		uh.ServiceID,
		CONCAT(DATE_FORMAT(ud.connect_time,"%H"),":",IF(MINUTE(ud.connect_time)<30,"00","30"),":00"),
		DATE_FORMAT(ud.connect_time,"%Y-%m-%d"),
		billed_duration,
		duration,
		selling_cost,
		buying_cost,
		trunk,
		area_prefix,
		1 AS call_status,
		ID
	FROM telsomespainCDR.tblVendorCDR  ud
	INNER JOIN telsomespainCDR.tblVendorCDRHeader uh
		ON uh.VendorCDRHeaderID = ud.VendorCDRHeaderID 
	INNER JOIN telsomespainRM.tblAccount a
		ON a.AccountID = uh.AccountID		
	WHERE
		a.CompanyID = ' , p_CompanyID , '
		AND uh.AccountID IS NOT NULL
	AND uh.StartDate BETWEEN "' , p_StartDate , '" AND "' , p_EndDate , '";
	');

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

	SET @stmt = CONCAT('
	INSERT IGNORE INTO tmp_tblVendorUsageDetailsReport_' , p_UniqueID , ' (
		VendorCDRID,
		VAccountID,
		CompanyID,
		CompanyGatewayID,
		GatewayVAccountPKID,
		ServiceID,
		connect_time,
		connect_date,
		billed_duration,
		duration,
		selling_cost,
		buying_cost,
		trunk,
		area_prefix,
		call_status_v,
		ID
	)
	SELECT 
		ud.VendorCDRFailedID,
		uh.AccountID,
		a.CompanyID,
		uh.CompanyGatewayID,
		uh.GatewayAccountPKID,
		uh.ServiceID,
		CONCAT(DATE_FORMAT(ud.connect_time,"%H"),":",IF(MINUTE(ud.connect_time)<30,"00","30"),":00"),
		DATE_FORMAT(ud.connect_time,"%Y-%m-%d"),
		billed_duration,
		duration,
		selling_cost,
		buying_cost,
		trunk,
		area_prefix,
		2 AS call_status,
		ID
	FROM telsomespainCDR.tblVendorCDRFailed  ud
	INNER JOIN telsomespainCDR.tblVendorCDRHeader uh
		ON uh.VendorCDRHeaderID = ud.VendorCDRHeaderID 
	INNER JOIN telsomespainRM.tblAccount a
		ON a.AccountID = uh.AccountID	
	WHERE
		a.CompanyID = ' , p_CompanyID , '
	AND uh.AccountID IS NOT NULL
	AND uh.StartDate BETWEEN "' , p_StartDate , '" AND "' , p_EndDate , '";
	');

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

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnGetVendorUsageForSummaryLive` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `fnGetVendorUsageForSummaryLive`(
	IN `p_CompanyID` INT,
	IN `p_StartDate` DATE,
	IN `p_EndDate` DATE
)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	DELETE FROM tmp_tblVendorUsageDetailsReportLive WHERE CompanyID = p_CompanyID;
	
	INSERT INTO tmp_tblVendorUsageDetailsReportLive (VendorCDRID,AccountID,CompanyID,CompanyGatewayID,ServiceID,GatewayAccountID,trunk,area_prefix,duration,billed_duration,buying_cost,selling_cost,connect_time,connect_date,call_status)
	SELECT
		ud.VendorCDRID,
		uh.AccountID,
		a.CompanyID,
		uh.CompanyGatewayID,
		uh.ServiceID,
		uh.GatewayAccountID,
		trunk,
		area_prefix,
		duration,
		billed_duration,
		buying_cost,
		selling_cost,
		CONCAT(DATE_FORMAT(ud.connect_time,'%H'),':',IF(MINUTE(ud.connect_time)<30,'00','30'),':00'),
		DATE_FORMAT(ud.connect_time,'%Y-%m-%d'),
		1 AS call_status
	FROM telsomespainCDR.tblVendorCDR  ud
	INNER JOIN telsomespainCDR.tblVendorCDRHeader uh
		ON uh.VendorCDRHeaderID = ud.VendorCDRHeaderID 
	INNER JOIN telsomespainRM.tblAccount a
		ON a.AccountID = uh.AccountID	
	WHERE
		a.CompanyID = p_CompanyID
	AND uh.AccountID IS NOT NULL
	AND uh.StartDate BETWEEN p_StartDate AND p_EndDate;

	INSERT INTO tmp_tblVendorUsageDetailsReportLive (VendorCDRID,AccountID,CompanyID,CompanyGatewayID,ServiceID,GatewayAccountID,trunk,area_prefix,duration,billed_duration,buying_cost,selling_cost,connect_time,connect_date,call_status)
	SELECT
		ud.VendorCDRFailedID,
		uh.AccountID,
		a.CompanyID,
		uh.CompanyGatewayID,
		uh.ServiceID,
		uh.GatewayAccountID,
		trunk,
		area_prefix,
		duration,
		billed_duration,
		buying_cost,
		selling_cost,
		CONCAT(DATE_FORMAT(ud.connect_time,'%H'),':',IF(MINUTE(ud.connect_time)<30,'00','30'),':00'),
		DATE_FORMAT(ud.connect_time,'%Y-%m-%d'),
		2 AS call_status
	FROM telsomespainCDR.tblVendorCDRFailed  ud
	INNER JOIN telsomespainCDR.tblVendorCDRHeader uh
		ON uh.VendorCDRHeaderID = ud.VendorCDRHeaderID 
	INNER JOIN telsomespainRM.tblAccount a
		ON a.AccountID = uh.AccountID	
	WHERE
		a.CompanyID = p_CompanyID
	AND uh.AccountID IS NOT NULL
	AND uh.StartDate BETWEEN p_StartDate AND p_EndDate;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnUpdateCustomerLink` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fnUpdateCustomerLink`(
	IN `p_CompanyID` INT,
	IN `p_StartDate` DATE,
	IN `p_EndDate` DATE,
	IN `p_UniqueID` VARCHAR(50)
)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET @stmt = CONCAT('
	UPDATE tmp_tblVendorUsageDetailsReport_' , p_UniqueID , ' vd 
	INNER JOIN tmp_tblUsageDetailsReport_' , p_UniqueID , ' cd ON cd.CompanyGatewayID = vd.CompanyGatewayID AND cd.ID = vd.ID
		SET cd.VAccountID = vd.VAccountID,cd.GatewayVAccountPKID = vd.GatewayVAccountPKID,cd.call_status_v = vd.call_status_v;
	');

	PREPARE stmt FROM @stmt;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
	SET @stmt = CONCAT('
	UPDATE tmp_tblVendorUsageDetailsReport_' , p_UniqueID , ' vd 
	INNER JOIN tmp_tblUsageDetailsReport_' , p_UniqueID , ' cd ON cd.CompanyGatewayID = vd.CompanyGatewayID AND cd.ID = vd.ID
		SET cd.VAccountID = vd.VAccountID,cd.GatewayVAccountPKID = vd.GatewayVAccountPKID,cd.call_status_v = vd.call_status_v,cd.buying_cost =vd.buying_cost
	WHERE vd.buying_cost <> 0 AND cd.billed_duration <> 0;
	');

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

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnUpdateVendorLink` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fnUpdateVendorLink`(
	IN `p_CompanyID` INT,
	IN `p_StartDate` DATE,
	IN `p_EndDate` DATE,
	IN `p_UniqueID` VARCHAR(50)
)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET @stmt = CONCAT('
	UPDATE tmp_tblVendorUsageDetailsReport_' , p_UniqueID , ' vd 
	INNER JOIN tmp_tblUsageDetailsReport_' , p_UniqueID , ' cd ON cd.CompanyGatewayID = vd.CompanyGatewayID AND cd.ID = vd.ID
		SET vd.AccountID = cd.AccountID,vd.GatewayAccountPKID = cd.GatewayAccountPKID,vd.call_status = cd.call_status;
	');

	PREPARE stmt FROM @stmt;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
	SET @stmt = CONCAT('
	UPDATE tmp_tblVendorUsageDetailsReport_' , p_UniqueID , ' vd 
	INNER JOIN tmp_tblUsageDetailsReport_' , p_UniqueID , ' cd ON cd.CompanyGatewayID = vd.CompanyGatewayID AND cd.ID = vd.ID
		SET vd.AccountID = cd.AccountID,vd.GatewayAccountPKID = cd.GatewayAccountPKID,vd.call_status = cd.call_status,vd.selling_cost =cd.cost
	WHERE cd.cost <> 0 AND vd.billed_duration <> 0;
	');

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

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnUsageSummary` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `fnUsageSummary`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_CDRType` VARCHAR(50),
	IN `p_UserID` INT ,
	IN `p_isAdmin` INT,
	IN `p_Detail` INT,
	IN `p_ResellerID` INT,
	IN `p_tag` VARCHAR(250)



)
BEGIN
	DECLARE v_TimeId_ INT;
	DECLARE v_raccountids TEXT;
	SET v_raccountids ='';
	
	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 telsomespainRM.tblAccountDetails WHERE ResellerOwner=p_ResellerID
		UNION
		SELECT AccountID FROM telsomespainRM.tblReseller WHERE ResellerID=p_ResellerID;
	
		SELECT IFNULL(GROUP_CONCAT(AccountID),'') INTO v_raccountids FROM tmp_reselleraccounts_;
		
	END IF;
	

	IF DATEDIFF(p_EndDate,p_StartDate) > 31 AND p_Detail = 2
	THEN
		SET p_Detail = 1;
	END IF;

	IF p_Detail = 1 
	THEN

		DROP TEMPORARY TABLE IF EXISTS tmp_tblUsageSummary_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblUsageSummary_(
				`DateID` BIGINT(20) NOT NULL,
				`CompanyID` INT(11) NOT NULL,
				`AccountID` INT(11) NOT NULL,
				`CompanyGatewayID` INT(11) NOT NULL,
				`Trunk` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
				`AreaPrefix` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
				`userfield` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',				
				`CountryID` INT(11) NULL DEFAULT NULL,
				`TotalCharges` DOUBLE NULL DEFAULT NULL,
				`TotalCost` DOUBLE NULL DEFAULT NULL,
				`TotalBilledDuration` INT(11) NULL DEFAULT NULL,
				`TotalDuration` INT(11) NULL DEFAULT NULL,
				`NoOfCalls` INT(11) NULL DEFAULT NULL,
				`NoOfFailCalls` INT(11) NULL DEFAULT NULL,
				`AccountName` varchar(100),
				INDEX `tblUsageSummary_dim_date` (`DateID`)
		);
		INSERT INTO tmp_tblUsageSummary_
		SELECT
			sh.DateID,
			sh.CompanyID,
			sh.AccountID,
			us.CompanyGatewayID,
			us.Trunk,
			us.AreaPrefix,
			us.userfield,
			us.CountryID,
			us.TotalCharges,
			us.TotalCost,
			us.TotalBilledDuration,
			us.TotalDuration,
			us.NoOfCalls,
			us.NoOfFailCalls,
			a.AccountName
		FROM tblHeader sh
		INNER JOIN tblUsageSummaryDay  us
			ON us.HeaderID = sh.HeaderID
		INNER JOIN tblDimDate dd
			ON dd.DateID = sh.DateID
		INNER JOIN telsomespainRM.tblAccount a
			ON sh.AccountID = a.AccountID
		WHERE dd.date BETWEEN p_StartDate AND p_EndDate
		AND sh.CompanyID = p_CompanyID
		AND (p_AccountID = 0 OR sh.AccountID = p_AccountID)
		AND (p_CompanyGatewayID = 0 OR us.CompanyGatewayID = p_CompanyGatewayID)
		AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
		AND (p_Trunk = '' OR us.Trunk LIKE REPLACE(p_Trunk, '*', '%'))
		AND (p_AreaPrefix = '' OR us.AreaPrefix LIKE REPLACE(p_AreaPrefix, '*', '%') )
		AND (p_CountryID = 0 OR us.CountryID = p_CountryID)
		AND (p_CDRType = '' OR us.userfield LIKE CONCAT('%',p_CDRType,'%'))
		AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
		AND (p_ResellerID = 0 OR FIND_IN_SET(sh.AccountID, v_raccountids) != 0)
		AND (p_tag = '' OR (a.tags like Concat(p_tag,'%')));
		

		INSERT INTO tmp_tblUsageSummary_
		SELECT
			sh.DateID,
			sh.CompanyID,
			sh.AccountID,
			us.CompanyGatewayID,
			us.Trunk,
			us.AreaPrefix,
			us.userfield,
			us.CountryID,
			us.TotalCharges,
			us.TotalCost,
			us.TotalBilledDuration,
			us.TotalDuration,
			us.NoOfCalls,
			us.NoOfFailCalls,
			a.AccountName
		FROM tblHeader sh
		INNER JOIN tblUsageSummaryDayLive  us
			ON us.HeaderID = sh.HeaderID
		INNER JOIN tblDimDate dd
			ON dd.DateID = sh.DateID
		INNER JOIN telsomespainRM.tblAccount a
			ON sh.AccountID = a.AccountID
		WHERE dd.date BETWEEN p_StartDate AND p_EndDate
		AND sh.CompanyID = p_CompanyID
		AND (p_AccountID = 0 OR sh.AccountID = p_AccountID)
		AND (p_CompanyGatewayID = 0 OR us.CompanyGatewayID = p_CompanyGatewayID)
		AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
		AND (p_Trunk = '' OR us.Trunk LIKE REPLACE(p_Trunk, '*', '%'))
		AND (p_AreaPrefix = '' OR us.AreaPrefix LIKE REPLACE(p_AreaPrefix, '*', '%') )
		AND (p_CountryID = 0 OR us.CountryID = p_CountryID)
		AND (p_CDRType = '' OR us.userfield LIKE CONCAT('%',p_CDRType,'%'))
		AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
		AND (p_ResellerID = 0 OR FIND_IN_SET(sh.AccountID, v_raccountids) != 0)
		AND (p_tag = '' OR (a.tags like Concat(p_tag,'%')));

	END IF;

	IF p_Detail = 2
	THEN

		DROP TEMPORARY TABLE IF EXISTS tmp_tblUsageSummary_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblUsageSummary_(
				`DateID` BIGINT(20) NOT NULL,
				`TimeID` INT(11) NOT NULL,
				`CompanyID` INT(11) NOT NULL,
				`AccountID` INT(11) NOT NULL,
				`CompanyGatewayID` INT(11) NOT NULL,
				`Trunk` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
				`AreaPrefix` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
				`userfield` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',				
				`CountryID` INT(11) NULL DEFAULT NULL,
				`TotalCharges` DOUBLE NULL DEFAULT NULL,
				`TotalCost` DOUBLE NULL DEFAULT NULL,
				`TotalBilledDuration` INT(11) NULL DEFAULT NULL,
				`TotalDuration` INT(11) NULL DEFAULT NULL,
				`NoOfCalls` INT(11) NULL DEFAULT NULL,
				`NoOfFailCalls` INT(11) NULL DEFAULT NULL,
				`AccountName` varchar(100),
				INDEX `tblUsageSummary_dim_date` (`DateID`)
		);

		INSERT INTO tmp_tblUsageSummary_
		SELECT
			sh.DateID,
			dt.TimeID,
			sh.CompanyID,
			sh.AccountID,
			usd.CompanyGatewayID,
			usd.Trunk,
			usd.AreaPrefix,
			usd.userfield,
			usd.CountryID,
			usd.TotalCharges,
			usd.TotalCost,
			usd.TotalBilledDuration,
			usd.TotalDuration,
			usd.NoOfCalls,
			usd.NoOfFailCalls,
			a.AccountName
		FROM tblHeader sh
		INNER JOIN tblUsageSummaryHour  usd
			ON usd.HeaderID = sh.HeaderID
		INNER JOIN tblDimDate dd
			ON dd.DateID = sh.DateID
		INNER JOIN tblDimTime dt
			ON dt.TimeID = usd.TimeID
		INNER JOIN telsomespainRM.tblAccount a
			ON sh.AccountID = a.AccountID
		WHERE dd.date BETWEEN DATE(p_StartDate) AND DATE(p_EndDate)
		AND CONCAT(dd.date,' ',dt.fulltime) BETWEEN p_StartDate AND p_EndDate
		AND sh.CompanyID = p_CompanyID
		AND (p_AccountID = 0 OR sh.AccountID = p_AccountID)
		AND (p_CompanyGatewayID = 0 OR usd.CompanyGatewayID = p_CompanyGatewayID)
		AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
		AND (p_Trunk = '' OR usd.Trunk LIKE REPLACE(p_Trunk, '*', '%'))
		AND (p_AreaPrefix = '' OR usd.AreaPrefix LIKE REPLACE(p_AreaPrefix, '*', '%') )
		AND (p_CountryID = 0 OR usd.CountryID = p_CountryID)
		AND (p_CDRType = '' OR usd.userfield LIKE CONCAT('%',p_CDRType,'%'))
		AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
		AND (p_ResellerID = 0 OR FIND_IN_SET(sh.AccountID, v_raccountids) != 0)
		AND (p_tag = '' OR (a.tags like Concat(p_tag,'%')));

		INSERT INTO tmp_tblUsageSummary_
		SELECT
			sh.DateID,
			dt.TimeID,
			sh.CompanyID,
			sh.AccountID,
			usd.CompanyGatewayID,
			usd.Trunk,
			usd.AreaPrefix,
			usd.userfield,
			usd.CountryID,
			usd.TotalCharges,
			usd.TotalCost,
			usd.TotalBilledDuration,
			usd.TotalDuration,
			usd.NoOfCalls,
			usd.NoOfFailCalls,
			a.AccountName
		FROM tblHeader sh
		INNER JOIN tblUsageSummaryHourLive  usd
			ON usd.HeaderID = sh.HeaderID
		INNER JOIN tblDimDate dd
			ON dd.DateID = sh.DateID
		INNER JOIN tblDimTime dt
			ON dt.TimeID = usd.TimeID
		INNER JOIN telsomespainRM.tblAccount a
			ON sh.AccountID = a.AccountID
		WHERE dd.date BETWEEN DATE(p_StartDate) AND DATE(p_EndDate)
		AND CONCAT(dd.date,' ',dt.fulltime) BETWEEN p_StartDate AND p_EndDate
		AND sh.CompanyID = p_CompanyID
		AND (p_AccountID = 0 OR sh.AccountID = p_AccountID)
		AND (p_CompanyGatewayID = 0 OR usd.CompanyGatewayID = p_CompanyGatewayID)
		AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
		AND (p_Trunk = '' OR usd.Trunk LIKE REPLACE(p_Trunk, '*', '%'))
		AND (p_AreaPrefix = '' OR usd.AreaPrefix LIKE REPLACE(p_AreaPrefix, '*', '%') )
		AND (p_CountryID = 0 OR usd.CountryID = p_CountryID)
		AND (p_CDRType = '' OR usd.userfield LIKE CONCAT('%',p_CDRType,'%'))
		AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
		AND (p_ResellerID = 0 OR FIND_IN_SET(sh.AccountID, v_raccountids) != 0)
		AND (p_tag = '' OR (a.tags like Concat(p_tag,'%')));

	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnUsageSummaryDetail` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fnUsageSummaryDetail`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` TEXT,
	IN `p_AccountID` TEXT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` TEXT,
	IN `p_Trunk` TEXT,
	IN `p_CountryID` TEXT,
	IN `p_UserID` INT ,
	IN `p_isAdmin` INT

)
BEGIN

	DECLARE i INTEGER;

	DROP TEMPORARY TABLE IF EXISTS tmp_tblUsageSummary_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblUsageSummary_(
			`DateID` BIGINT(20) NOT NULL,
			`TimeID` INT(11) NOT NULL,
			`Time` VARCHAR(50) NOT NULL,
			`CompanyID` INT(11) NOT NULL,
			`AccountID` INT(11) NOT NULL,
			`CompanyGatewayID` INT(11) NOT NULL,
			`Trunk` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
			`AreaPrefix` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
			`CountryID` INT(11) NULL DEFAULT NULL,
			`TotalCharges` DOUBLE NULL DEFAULT NULL,
			`TotalBilledDuration` INT(11) NULL DEFAULT NULL,
			`TotalDuration` INT(11) NULL DEFAULT NULL,
			`NoOfCalls` INT(11) NULL DEFAULT NULL,
			`NoOfFailCalls` INT(11) NULL DEFAULT NULL,
			`AccountName` varchar(100),
			INDEX `tblUsageSummary_dim_date` (`DateID`)
	);
	
	DROP TEMPORARY TABLE IF EXISTS tmp_AreaPrefix_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_AreaPrefix_ (
		`Code` Text NULL DEFAULT NULL
	);

	SET i = 1;
	REPEAT
		INSERT INTO tmp_AreaPrefix_ ( Code)
		SELECT telsomespainRM.FnStringSplit(p_AreaPrefix, ',', i) FROM tblDimDate WHERE telsomespainRM.FnStringSplit(p_AreaPrefix, ',', i) IS NOT NULL LIMIT 1;
		SET i = i + 1;
		UNTIL ROW_COUNT() = 0
	END REPEAT;

	INSERT INTO tmp_tblUsageSummary_
	SELECT
		sh.DateID,
		dt.TimeID,
		CONCAT(dd.date,' ',dt.fulltime),
		sh.CompanyID,
		sh.AccountID,
		usd.CompanyGatewayID,
		usd.Trunk,
		usd.AreaPrefix,
		usd.CountryID,
		usd.TotalCharges,
		usd.TotalBilledDuration,
		usd.TotalDuration,
		usd.NoOfCalls,
		usd.NoOfFailCalls,
		a.AccountName
	FROM tblHeader sh
	INNER JOIN tblUsageSummaryHour  usd
		ON usd.HeaderID = sh.HeaderID
	INNER JOIN tblDimDate dd
		ON dd.DateID = sh.DateID
	INNER JOIN tblDimTime dt
		ON dt.TimeID = usd.TimeID
	INNER JOIN telsomespainRM.tblAccount a
		ON sh.AccountID = a.AccountID
	LEFT JOIN telsomespainRM.tblTrunk t
		ON t.Trunk = usd.Trunk
	LEFT JOIN tmp_AreaPrefix_ ap 
		ON usd.AreaPrefix LIKE REPLACE(ap.Code, '*', '%')
	WHERE dd.date BETWEEN DATE(p_StartDate) AND DATE(p_EndDate)
	AND CONCAT(dd.date,' ',dt.fulltime) BETWEEN p_StartDate AND p_EndDate
	AND sh.CompanyID = p_CompanyID
	AND (p_AccountID = '' OR FIND_IN_SET(sh.AccountID,p_AccountID))
	AND (p_CompanyGatewayID = '' OR FIND_IN_SET(usd.CompanyGatewayID,p_CompanyGatewayID))
	AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
	AND (p_Trunk = '' OR FIND_IN_SET(t.TrunkID,p_Trunk))
	AND (p_CountryID = '' OR FIND_IN_SET(usd.CountryID,p_CountryID))
	AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
	AND (p_AreaPrefix ='' OR ap.Code IS NOT NULL);

	INSERT INTO tmp_tblUsageSummary_
	SELECT
		sh.DateID,
		dt.TimeID,
		CONCAT(dd.date,' ',dt.fulltime),
		sh.CompanyID,
		sh.AccountID,
		usd.CompanyGatewayID,
		usd.Trunk,
		usd.AreaPrefix,
		usd.CountryID,
		usd.TotalCharges,
		usd.TotalBilledDuration,
		usd.TotalDuration,
		usd.NoOfCalls,
		usd.NoOfFailCalls,
		a.AccountName
	FROM tblHeader sh
	INNER JOIN tblUsageSummaryHourLive  usd
		ON usd.HeaderID = sh.HeaderID
	INNER JOIN tblDimDate dd
		ON dd.DateID = sh.DateID
	INNER JOIN tblDimTime dt
		ON dt.TimeID = usd.TimeID
	INNER JOIN telsomespainRM.tblAccount a
		ON sh.AccountID = a.AccountID
	LEFT JOIN telsomespainRM.tblTrunk t
		ON t.Trunk = usd.Trunk
	LEFT JOIN tmp_AreaPrefix_ ap 
		ON (p_AreaPrefix = '' OR usd.AreaPrefix LIKE REPLACE(ap.Code, '*', '%') )
	WHERE dd.date BETWEEN DATE(p_StartDate) AND DATE(p_EndDate)
	AND CONCAT(dd.date,' ',dt.fulltime) BETWEEN p_StartDate AND p_EndDate
	AND sh.CompanyID = p_CompanyID
	AND (p_AccountID = '' OR FIND_IN_SET(sh.AccountID,p_AccountID))
	AND (p_CompanyGatewayID = '' OR FIND_IN_SET(usd.CompanyGatewayID,p_CompanyGatewayID))
	AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
	AND (p_Trunk = '' OR FIND_IN_SET(t.TrunkID,p_Trunk))
	AND (p_CountryID = '' OR FIND_IN_SET(usd.CountryID,p_CountryID))
	AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
	AND (p_AreaPrefix ='' OR ap.Code IS NOT NULL);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnUsageVendorSummary` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `fnUsageVendorSummary`(
	IN `p_CompanyID` int ,
	IN `p_CompanyGatewayID` int ,
	IN `p_AccountID` int ,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` datetime ,
	IN `p_EndDate` datetime ,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_UserID` INT ,
	IN `p_isAdmin` INT,
	IN `p_Detail` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN
	DECLARE v_TimeId_ INT;

	IF DATEDIFF(p_EndDate,p_StartDate) > 31 AND p_Detail =2
	THEN
		SET p_Detail = 1;
	END IF;

	IF p_Detail = 1 
	THEN

		DROP TEMPORARY TABLE IF EXISTS tmp_tblUsageVendorSummary_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblUsageVendorSummary_(
				`DateID` BIGINT(20) NOT NULL,
				`CompanyID` INT(11) NOT NULL,
				`AccountID` INT(11) NOT NULL,
				`CompanyGatewayID` INT(11) NOT NULL,
				`Trunk` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
				`AreaPrefix` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
				`CountryID` INT(11) NULL DEFAULT NULL,
				`TotalCharges` DOUBLE NULL DEFAULT NULL,
				`TotalSales` DOUBLE NULL DEFAULT NULL,
				`TotalBilledDuration` INT(11) NULL DEFAULT NULL,
				`TotalDuration` INT(11) NULL DEFAULT NULL,
				`NoOfCalls` INT(11) NULL DEFAULT NULL,
				`NoOfFailCalls` INT(11) NULL DEFAULT NULL,
				`AccountName` varchar(100),
				INDEX `tblUsageSummary_dim_date` (`DateID`)
		);
		INSERT INTO tmp_tblUsageVendorSummary_
		SELECT
			sh.DateID,
			sh.CompanyID,
			sh.VAccountID,
			us.CompanyGatewayID,
			us.Trunk,
			us.AreaPrefix,
			us.CountryID,
			us.TotalCharges,
			us.TotalSales,
			us.TotalBilledDuration,
			us.TotalDuration,
			us.NoOfCalls,
			us.NoOfFailCalls,
			a.AccountName
		FROM tblHeaderV sh
		INNER JOIN tblVendorSummaryDay us
			ON us.HeaderVID = sh.HeaderVID 
		INNER JOIN tblDimDate dd
			ON dd.DateID = sh.DateID
		INNER JOIN telsomespainRM.tblAccount a
			ON sh.VAccountID = a.AccountID
		WHERE dd.date BETWEEN p_StartDate AND p_EndDate
		AND sh.CompanyID = p_CompanyID
		AND (p_AccountID = 0 OR sh.VAccountID = p_AccountID)
		AND (p_CompanyGatewayID = 0 OR us.CompanyGatewayID = p_CompanyGatewayID)
		AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
		AND (p_Trunk = '' OR us.Trunk LIKE REPLACE(p_Trunk, '*', '%'))
		AND (p_AreaPrefix = '' OR us.AreaPrefix LIKE REPLACE(p_AreaPrefix, '*', '%') )
		AND (p_CountryID = 0 OR us.CountryID = p_CountryID)
		AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
		AND (p_tag = '' OR (a.tags like Concat(p_tag,'%')));

		INSERT INTO tmp_tblUsageVendorSummary_
		SELECT
			sh.DateID,
			sh.CompanyID,
			sh.VAccountID,
			us.CompanyGatewayID,
			us.Trunk,
			us.AreaPrefix,
			us.CountryID,
			us.TotalCharges,
			us.TotalSales,
			us.TotalBilledDuration,
			us.TotalDuration,
			us.NoOfCalls,
			us.NoOfFailCalls,
			a.AccountName
		FROM tblHeaderV sh
		INNER JOIN tblVendorSummaryDayLive us
			ON us.HeaderVID = sh.HeaderVID 
		INNER JOIN tblDimDate dd
			ON dd.DateID = sh.DateID
		INNER JOIN telsomespainRM.tblAccount a
			ON sh.VAccountID = a.AccountID
		WHERE dd.date BETWEEN p_StartDate AND p_EndDate
		AND sh.CompanyID = p_CompanyID
		AND (p_AccountID = 0 OR sh.VAccountID = p_AccountID)
		AND (p_CompanyGatewayID = 0 OR us.CompanyGatewayID = p_CompanyGatewayID)
		AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
		AND (p_Trunk = '' OR us.Trunk LIKE REPLACE(p_Trunk, '*', '%'))
		AND (p_AreaPrefix = '' OR us.AreaPrefix LIKE REPLACE(p_AreaPrefix, '*', '%') )
		AND (p_CountryID = 0 OR us.CountryID = p_CountryID)
		AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
		AND (p_tag = '' OR (a.tags like Concat(p_tag,'%')));

	END IF;

	IF p_Detail = 2 
	THEN

		DROP TEMPORARY TABLE IF EXISTS tmp_tblUsageVendorSummary_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblUsageVendorSummary_(
				`DateID` BIGINT(20) NOT NULL,
				`TimeID` INT(11) NOT NULL,
				`CompanyID` INT(11) NOT NULL,
				`AccountID` INT(11) NOT NULL,
				`CompanyGatewayID` INT(11) NOT NULL,
				`Trunk` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
				`AreaPrefix` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
				`CountryID` INT(11) NULL DEFAULT NULL,
				`TotalCharges` DOUBLE NULL DEFAULT NULL,
				`TotalSales` DOUBLE NULL DEFAULT NULL,
				`TotalBilledDuration` INT(11) NULL DEFAULT NULL,
				`TotalDuration` INT(11) NULL DEFAULT NULL,
				`NoOfCalls` INT(11) NULL DEFAULT NULL,
				`NoOfFailCalls` INT(11) NULL DEFAULT NULL,
				`AccountName` varchar(100),
				INDEX `tblUsageSummary_dim_date` (`DateID`)
		);

		INSERT INTO tmp_tblUsageVendorSummary_
		SELECT
			sh.DateID,
			dt.TimeID,
			sh.CompanyID,
			sh.VAccountID,
			usd.CompanyGatewayID,
			usd.Trunk,
			usd.AreaPrefix,
			usd.CountryID,
			usd.TotalCharges,
			usd.TotalSales,
			usd.TotalBilledDuration,
			usd.TotalDuration,
			usd.NoOfCalls,
			usd.NoOfFailCalls,
			a.AccountName
		FROM tblHeaderV sh
		INNER JOIN tblVendorSummaryHour usd
			ON usd.HeaderVID = sh.HeaderVID 
		INNER JOIN tblDimDate dd
			ON dd.DateID = sh.DateID
		INNER JOIN tblDimTime dt
			ON dt.TimeID = usd.TimeID
		INNER JOIN telsomespainRM.tblAccount a
			ON sh.VAccountID = a.AccountID
		WHERE dd.date BETWEEN DATE(p_StartDate) AND DATE(p_EndDate)
		AND CONCAT(dd.date,' ',dt.fulltime) BETWEEN p_StartDate AND p_EndDate
		AND sh.CompanyID = p_CompanyID
		AND (p_AccountID = 0 OR sh.VAccountID = p_AccountID)
		AND (p_CompanyGatewayID = 0 OR usd.CompanyGatewayID = p_CompanyGatewayID)
		AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
		AND (p_Trunk = '' OR usd.Trunk LIKE REPLACE(p_Trunk, '*', '%'))
		AND (p_AreaPrefix = '' OR usd.AreaPrefix LIKE REPLACE(p_AreaPrefix, '*', '%') )
		AND (p_CountryID = 0 OR usd.CountryID = p_CountryID)
		AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
		AND (p_tag = '' OR (a.tags like Concat(p_tag,'%')));

		INSERT INTO tmp_tblUsageVendorSummary_
		SELECT
			sh.DateID,
			dt.TimeID,
			sh.CompanyID,
			sh.VAccountID,
			usd.CompanyGatewayID,
			usd.Trunk,
			usd.AreaPrefix,
			usd.CountryID,
			usd.TotalCharges,
			usd.TotalSales,
			usd.TotalBilledDuration,
			usd.TotalDuration,
			usd.NoOfCalls,
			usd.NoOfFailCalls,
			a.AccountName
		FROM tblHeaderV sh
		INNER JOIN tblVendorSummaryHourLive usd
			ON usd.HeaderVID = sh.HeaderVID 
		INNER JOIN tblDimDate dd
			ON dd.DateID = sh.DateID
		INNER JOIN tblDimTime dt
			ON dt.TimeID = usd.TimeID
		INNER JOIN telsomespainRM.tblAccount a
			ON sh.VAccountID = a.AccountID
		WHERE dd.date BETWEEN DATE(p_StartDate) AND DATE(p_EndDate)
		AND CONCAT(dd.date,' ',dt.fulltime) BETWEEN p_StartDate AND p_EndDate
		AND sh.CompanyID = p_CompanyID
		AND (p_AccountID = 0 OR sh.VAccountID = p_AccountID)
		AND (p_CompanyGatewayID = 0 OR usd.CompanyGatewayID = p_CompanyGatewayID)
		AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
		AND (p_Trunk = '' OR usd.Trunk LIKE REPLACE(p_Trunk, '*', '%'))
		AND (p_AreaPrefix = '' OR usd.AreaPrefix LIKE REPLACE(p_AreaPrefix, '*', '%') )
		AND (p_CountryID = 0 OR usd.CountryID = p_CountryID)
		AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
		AND (p_tag = '' OR (a.tags like Concat(p_tag,'%')));

	END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `fnUsageVendorSummaryDetail` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fnUsageVendorSummaryDetail`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` TEXT,
	IN `p_AccountID` TEXT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` TEXT,
	IN `p_Trunk` TEXT,
	IN `p_CountryID` TEXT,
	IN `p_UserID` INT,
	IN `p_isAdmin` INT

)
BEGIN

	DECLARE i INTEGER;

	DROP TEMPORARY TABLE IF EXISTS tmp_tblUsageVendorSummary_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblUsageVendorSummary_(
		`DateID` BIGINT(20) NOT NULL,
		`TimeID` INT(11) NOT NULL,
		`Time` VARCHAR(50) NOT NULL,
		`CompanyID` INT(11) NOT NULL,
		`AccountID` INT(11) NOT NULL,
		`CompanyGatewayID` INT(11) NOT NULL,
		`Trunk` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
		`AreaPrefix` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
		`CountryID` INT(11) NULL DEFAULT NULL,
		`TotalCharges` DOUBLE NULL DEFAULT NULL,
		`TotalBilledDuration` INT(11) NULL DEFAULT NULL,
		`TotalDuration` INT(11) NULL DEFAULT NULL,
		`NoOfCalls` INT(11) NULL DEFAULT NULL,
		`NoOfFailCalls` INT(11) NULL DEFAULT NULL,
		`AccountName` varchar(100),
		INDEX `tblUsageSummary_dim_date` (`DateID`)
	);

	DROP TEMPORARY TABLE IF EXISTS tmp_AreaPrefix_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_AreaPrefix_ (
		`Code` Text NULL DEFAULT NULL
	);

	SET i = 1;
	REPEAT
		INSERT INTO tmp_AreaPrefix_ ( Code)
		SELECT telsomespainRM.FnStringSplit(p_AreaPrefix, ',', i) FROM tblDimDate WHERE telsomespainRM.FnStringSplit(p_AreaPrefix, ',', i) IS NOT NULL LIMIT 1;
		SET i = i + 1;
		UNTIL ROW_COUNT() = 0
	END REPEAT;

	INSERT INTO tmp_tblUsageVendorSummary_
	SELECT
		sh.DateID,
		dt.TimeID,
		CONCAT(dd.date,' ',dt.fulltime),
		sh.CompanyID,
		sh.VAccountID,
		usd.CompanyGatewayID,
		usd.Trunk,
		usd.AreaPrefix,
		usd.CountryID,
		usd.TotalCharges,
		usd.TotalBilledDuration,
		usd.TotalDuration,
		usd.NoOfCalls,
		usd.NoOfFailCalls,
		a.AccountName
	FROM tblHeaderV sh
	INNER JOIN tblVendorSummaryHour usd
		ON usd.HeaderVID = sh.HeaderVID
	INNER JOIN tblDimDate dd
		ON dd.DateID = sh.DateID
	INNER JOIN tblDimTime dt
		ON dt.TimeID = usd.TimeID
	INNER JOIN telsomespainRM.tblAccount a
		ON sh.VAccountID = a.AccountID
	LEFT JOIN telsomespainRM.tblTrunk t
		ON t.Trunk = usd.Trunk
	LEFT JOIN tmp_AreaPrefix_ ap
		ON usd.AreaPrefix LIKE REPLACE(ap.Code, '*', '%')
	WHERE dd.date BETWEEN DATE(p_StartDate) AND DATE(p_EndDate)
	AND CONCAT(dd.date,' ',dt.fulltime) BETWEEN p_StartDate AND p_EndDate
	AND sh.CompanyID = p_CompanyID
	AND (p_AccountID = '' OR FIND_IN_SET(sh.VAccountID,p_AccountID))
	AND (p_CompanyGatewayID = '' OR FIND_IN_SET(usd.CompanyGatewayID,p_CompanyGatewayID))
	AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
	AND (p_Trunk = '' OR FIND_IN_SET(t.TrunkID,p_Trunk))
	AND (p_CountryID = '' OR FIND_IN_SET(usd.CountryID,p_CountryID))
	AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
	AND (p_AreaPrefix ='' OR ap.Code IS NOT NULL);

	INSERT INTO tmp_tblUsageVendorSummary_
	SELECT
		sh.DateID,
		dt.TimeID,
		CONCAT(dd.date,' ',dt.fulltime),
		sh.CompanyID,
		sh.VAccountID,
		usd.CompanyGatewayID,
		usd.Trunk,
		usd.AreaPrefix,
		usd.CountryID,
		usd.TotalCharges,
		usd.TotalBilledDuration,
		usd.TotalDuration,
		usd.NoOfCalls,
		usd.NoOfFailCalls,
		a.AccountName
	FROM tblHeaderV sh
	INNER JOIN tblVendorSummaryHourLive usd
		ON usd.HeaderVID = sh.HeaderVID
	INNER JOIN tblDimDate dd
		ON dd.DateID = sh.DateID
	INNER JOIN tblDimTime dt
		ON dt.TimeID = usd.TimeID
	INNER JOIN telsomespainRM.tblAccount a
		ON sh.VAccountID = a.AccountID
	LEFT JOIN telsomespainRM.tblTrunk t
		ON t.Trunk = usd.Trunk
	LEFT JOIN tmp_AreaPrefix_ ap
		ON usd.AreaPrefix LIKE REPLACE(ap.Code, '*', '%')
	WHERE dd.date BETWEEN DATE(p_StartDate) AND DATE(p_EndDate)
	AND CONCAT(dd.date,' ',dt.fulltime) BETWEEN p_StartDate AND p_EndDate
	AND sh.CompanyID = p_CompanyID
	AND (p_AccountID = '' OR FIND_IN_SET(sh.VAccountID,p_AccountID))
	AND (p_CompanyGatewayID = '' OR FIND_IN_SET(usd.CompanyGatewayID,p_CompanyGatewayID))
	AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND a.Owner = p_UserID))
	AND (p_Trunk = '' OR FIND_IN_SET(t.TrunkID,p_Trunk))
	AND (p_CountryID = '' OR FIND_IN_SET(usd.CountryID,p_CountryID))
	AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID)
	AND (p_AreaPrefix ='' OR ap.Code IS NOT NULL);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_datedimbuild` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_datedimbuild`(IN `p_start_date` DATE, IN `p_end_date` DATE)
BEGIN
    DECLARE v_full_date DATE;

     DELETE FROM tblDimDate;

    SET v_full_date = p_start_date;
    WHILE v_full_date < p_end_date DO

        INSERT INTO tblDimDate (
            	`date`,
					`day`,
					`day_abbrev`,
					`day_of_week`,
					`day_of_month`,
					`day_of_quarter`,
					`day_of_semester`,
					`day_of_year`,
					`weekend`,
					`week_of_month`,
					`week_of_quarter`,
					`week_of_semester`,
					`week_of_year`,
					`month`,
					`month_abbrev`,
					`month_of_quarter`,
					`month_of_year`,
					`quarter_of_year`,
					`previous_day`,
					`next_day`,
					`start_week`,
					`end_week`,
					`start_month`,
					`end_month`,
					`start_quarter`,
					`end_quarter`,
					`year`,
					`week_month_name`,
					`week_quarter_name`,
					`week_year_name`,
					`month_quarter_name`,
					`month_year_name`,
					`quarter_year_name`
        ) VALUES (
        			v_full_date,
					DATE_FORMAT( v_full_date , "%W" ),
					DATE_FORMAT( v_full_date , "%a"),
					DAYOFWEEK(v_full_date),
					DAYOFMONTH(v_full_date),
					NULL,
					NULL,
					DAYOFYEAR(v_full_date),
					IF( DATE_FORMAT( v_full_date, "%W" ) IN ('Saturday','Sunday'), 'Weekend', 'Weekday'),
					WEEK(v_full_date) - WEEK(DATE_ADD(v_full_date,INTERVAL -DAY(v_full_date)+1 DAY)),
					NULL,
					NULL,
					WEEKOFYEAR(v_full_date),
					DATE_FORMAT( v_full_date , "%M"),
					DATE_FORMAT( v_full_date , "%b"),
					MOD(MONTH('2016-02-20')-1,3)+1,
					MONTH(v_full_date),
					QUARTER(v_full_date),
					DATE_ADD(v_full_date, INTERVAL -1 DAY),
					DATE_ADD(v_full_date, INTERVAL +1 DAY),
					v_full_date,
					v_full_date,
					v_full_date,
					v_full_date,
					v_full_date,
					v_full_date,
					YEAR(v_full_date),
					CONCAT(WEEK(v_full_date) - WEEK(DATE_ADD(v_full_date,INTERVAL -DAY(v_full_date)+1 DAY)),'-',DATE_FORMAT( v_full_date , "%M")),
					NULL,
					CONCAT(WEEK(date),'-',DATE_FORMAT( date , "%Y")),
					NULL,
					CONCAT(month_abbrev,'-',year),
					CONCAT(quarter_of_year,'-',year)
        );

        SET v_full_date = DATE_ADD(v_full_date, INTERVAL 1 DAY);
    END WHILE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_generateSummary` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_generateSummary`(
	IN `p_CompanyID` INT,
	IN `p_StartDate` DATE,
	IN `p_EndDate` DATE,
	IN `p_UniqueID` VARCHAR(50)

)
BEGIN
	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 COMMITTED;
	
	CALL telsomespainRM.prc_UpdateMysqlPID(p_UniqueID);
	
	CALL fngetDefaultCodes(p_CompanyID); 
	
	
	CALL fnUpdateCustomerLink(p_CompanyID,p_StartDate,p_EndDate,p_UniqueID);

	DELETE FROM tmp_UsageSummary WHERE CompanyID = p_CompanyID;

	SET @stmt = CONCAT('
	INSERT INTO tmp_UsageSummary(
		DateID,
		TimeID,
		CompanyID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		VAccountID,
		Trunk,
		AreaPrefix,
		userfield,
		TotalCharges,
		TotalCost,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT 
		d.DateID,
		t.TimeID,
		a.CompanyID,
		ud.CompanyGatewayID,
		ud.ServiceID,
		ud.GatewayAccountPKID,
		ud.GatewayVAccountPKID,
		ud.AccountID,
		ud.VAccountID,
		ud.trunk,
		ud.area_prefix,
		ud.userfield,
		COALESCE(SUM(ud.cost),0)  AS TotalCharges ,
		COALESCE(SUM(ud.buying_cost),0)  AS TotalCost ,
		COALESCE(SUM(ud.billed_duration),0) AS TotalBilledDuration ,
		COALESCE(SUM(ud.duration),0) AS TotalDuration,
		SUM(IF(ud.call_status=1,1,0)) AS  NoOfCalls,
		SUM(IF(ud.call_status=2,1,0)) AS  NoOfFailCalls
	FROM tmp_tblUsageDetailsReport_',p_UniqueID,' ud  
	INNER JOIN telsomespainRM.tblAccount a
		ON a.AccountID = ud.AccountID
	INNER JOIN tblDimTime t ON t.fulltime = connect_time
	INNER JOIN tblDimDate d ON d.date = connect_date
	WHERE a.CompanyID = ',p_CompanyID,'
		AND ud.AccountID IS NOT NULL
	GROUP BY d.DateID,t.TimeID,ud.CompanyID,ud.CompanyGatewayID,ud.ServiceID,ud.GatewayAccountPKID,ud.GatewayVAccountPKID,ud.AccountID,ud.VAccountID,ud.area_prefix,ud.trunk,ud.userfield;
	');


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

	UPDATE tmp_UsageSummary 
	INNER JOIN  tmp_codes_ as code ON AreaPrefix = code.code
	SET tmp_UsageSummary.CountryID =code.CountryID
	WHERE tmp_UsageSummary.CompanyID = p_CompanyID AND code.CountryID > 0;

	START TRANSACTION;
	
	DELETE us FROM tblUsageSummaryDay us 
	INNER JOIN tblHeader sh ON us.HeaderID = sh.HeaderID
	INNER JOIN tblDimDate d ON d.DateID = sh.DateID
	WHERE date BETWEEN p_StartDate AND p_EndDate AND sh.CompanyID = p_CompanyID;
	
	DELETE usd FROM tblUsageSummaryHour usd
	INNER JOIN tblHeader sh ON usd.HeaderID = sh.HeaderID
	INNER JOIN tblDimDate d ON d.DateID = sh.DateID
	WHERE date BETWEEN p_StartDate AND p_EndDate AND sh.CompanyID = p_CompanyID;
	
	DELETE h FROM tblHeader h 
	INNER JOIN (SELECT DISTINCT DateID,CompanyID FROM tmp_UsageSummary)u
		ON h.DateID = u.DateID 
		AND h.CompanyID = u.CompanyID
	WHERE u.CompanyID = p_CompanyID;
	
	INSERT INTO tblHeader (
		DateID,
		CompanyID,
		AccountID,
		TotalCharges,
		TotalCost,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT 
		DateID,
		CompanyID,
		AccountID,
		SUM(TotalCharges) as TotalCharges,
		SUM(TotalCost) as TotalCost,
		SUM(TotalBilledDuration) as TotalBilledDuration,
		SUM(TotalDuration) as TotalDuration,
		SUM(NoOfCalls) as NoOfCalls,
		SUM(NoOfFailCalls) as NoOfFailCalls
	FROM tmp_UsageSummary 
	WHERE CompanyID = p_CompanyID
	GROUP BY DateID,CompanyID,AccountID;
	
	DELETE FROM tmp_SummaryHeader WHERE CompanyID = p_CompanyID;
	INSERT INTO tmp_SummaryHeader (HeaderID,DateID,CompanyID,AccountID)
	SELECT 
		sh.HeaderID,
		sh.DateID,
		sh.CompanyID,
		sh.AccountID
	FROM tblHeader sh
	INNER JOIN (SELECT DISTINCT DateID,CompanyID FROM tmp_UsageSummary)TBL
	ON TBL.DateID = sh.DateID AND TBL.CompanyID = sh.CompanyID
	WHERE sh.CompanyID =  p_CompanyID ;

	INSERT INTO tblUsageSummaryDay (
		HeaderID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		VAccountID,
		Trunk,
		AreaPrefix,
		userfield,
		CountryID,
		TotalCharges,
		TotalCost,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT
		sh.HeaderID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		VAccountID,
		Trunk,
		AreaPrefix,
		userfield,
		CountryID,
		SUM(us.TotalCharges),
		SUM(us.TotalCost),
		SUM(us.TotalBilledDuration),
		SUM(us.TotalDuration),
		SUM(us.NoOfCalls),
		SUM(us.NoOfFailCalls)
	FROM tmp_SummaryHeader sh
	INNER JOIN tmp_UsageSummary us FORCE INDEX (Unique_key)	 
		ON  us.DateID = sh.DateID
		AND us.CompanyID = sh.CompanyID
		AND us.AccountID = sh.AccountID
	WHERE us.CompanyID = p_CompanyID
	GROUP BY us.DateID,us.CompanyID,us.CompanyGatewayID,us.ServiceID,us.GatewayAccountPKID,us.GatewayVAccountPKID,us.AccountID,us.VAccountID,us.AreaPrefix,us.Trunk,us.CountryID,sh.HeaderID,us.userfield;
	
	INSERT INTO tblUsageSummaryHour (
		HeaderID,
		TimeID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		VAccountID,
		Trunk,
		AreaPrefix,
		userfield,
		CountryID,
		TotalCharges,
		TotalCost,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls	
	)
	SELECT 
		sh.HeaderID,
		TimeID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		VAccountID,
		Trunk,
		AreaPrefix,
		userfield,
		CountryID,
		us.TotalCharges,
		us.TotalCost,
		us.TotalBilledDuration,
		us.TotalDuration,
		us.NoOfCalls,
		us.NoOfFailCalls
	FROM tmp_SummaryHeader sh
	INNER JOIN tmp_UsageSummary us FORCE INDEX (Unique_key)
		ON  us.DateID = sh.DateID
		AND us.CompanyID = sh.CompanyID
		AND us.AccountID = sh.AccountID
	WHERE us.CompanyID = p_CompanyID;
	
	CALL fnDistinctList(p_CompanyID);

	COMMIT;
	
 	DELETE FROM tmp_UsageSummary WHERE CompanyID = p_CompanyID;
	
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_generateSummaryLive` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_generateSummaryLive`(
	IN `p_CompanyID` INT,
	IN `p_StartDate` DATE,
	IN `p_EndDate` DATE,
	IN `p_UniqueID` VARCHAR(50)

)
BEGIN
	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 COMMITTED;
	
	CALL telsomespainRM.prc_UpdateMysqlPID(p_UniqueID);

	CALL fngetDefaultCodes(p_CompanyID); 
	CALL fnGetUsageForSummary(p_CompanyID,p_StartDate,p_EndDate,p_UniqueID);
	CALL fnGetVendorUsageForSummary(p_CompanyID,p_StartDate,p_EndDate,p_UniqueID);
	CALL fnUpdateCustomerLink(p_CompanyID,p_StartDate,p_EndDate,p_UniqueID);
	CALL fnUpdateVendorLink(p_CompanyID,p_StartDate,p_EndDate,p_UniqueID);

	DELETE FROM tmp_UsageSummaryLive WHERE CompanyID = p_CompanyID;

	SET @stmt = CONCAT('
	INSERT INTO tmp_UsageSummaryLive(
		DateID,
		TimeID,
		CompanyID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		VAccountID,
		Trunk,
		AreaPrefix,
		userfield,
		TotalCharges,
		TotalCost,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT 
		d.DateID,
		t.TimeID,
		a.CompanyID,
		ud.CompanyGatewayID,
		ud.ServiceID,
		ud.GatewayAccountPKID,
		ud.GatewayVAccountPKID,
		ud.AccountID,
		ud.VAccountID,
		ud.trunk,
		ud.area_prefix,
		ud.userfield,
		COALESCE(SUM(ud.cost),0)  AS TotalCharges ,
		COALESCE(SUM(ud.buying_cost),0)  AS TotalCost ,
		COALESCE(SUM(ud.billed_duration),0) AS TotalBilledDuration ,
		COALESCE(SUM(ud.duration),0) AS TotalDuration,
		SUM(IF(ud.call_status=1,1,0)) AS  NoOfCalls,
		SUM(IF(ud.call_status=2,1,0)) AS  NoOfFailCalls
	FROM tmp_tblUsageDetailsReport_',p_UniqueID,' ud  
	INNER JOIN telsomespainRM.tblAccount a
		ON a.AccountID = ud.AccountID	
	INNER JOIN tblDimTime t ON t.fulltime = connect_time
	INNER JOIN tblDimDate d ON d.date = connect_date
	WHERE a.CompanyID = ',p_CompanyID,'
		AND ud.AccountID IS NOT NULL
	GROUP BY d.DateID,t.TimeID,ud.CompanyID,ud.CompanyGatewayID,ud.ServiceID,ud.GatewayAccountPKID,ud.GatewayVAccountPKID,ud.AccountID,ud.VAccountID,ud.area_prefix,ud.trunk,ud.userfield;
	');


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

	UPDATE tmp_UsageSummaryLive
	INNER JOIN  tmp_codes_ as code ON AreaPrefix = code.code
	SET tmp_UsageSummaryLive.CountryID =code.CountryID
	WHERE tmp_UsageSummaryLive.CompanyID = p_CompanyID AND code.CountryID > 0;

	START TRANSACTION;

	DELETE us FROM tblUsageSummaryDayLive us 
	INNER JOIN tblHeader sh ON us.HeaderID = sh.HeaderID
	INNER JOIN tblDimDate d ON d.DateID = sh.DateID
	WHERE date BETWEEN p_StartDate AND p_EndDate AND sh.CompanyID = p_CompanyID;

	DELETE usd FROM tblUsageSummaryHourLive usd
	INNER JOIN tblHeader sh ON usd.HeaderID = sh.HeaderID
	INNER JOIN tblDimDate d ON d.DateID = sh.DateID
	WHERE date BETWEEN p_StartDate AND p_EndDate AND sh.CompanyID = p_CompanyID;

	DELETE h FROM tblHeader h 
	INNER JOIN (SELECT DISTINCT DateID,CompanyID FROM tmp_UsageSummaryLive)u
		ON h.DateID = u.DateID 
		AND h.CompanyID = u.CompanyID
	WHERE u.CompanyID = p_CompanyID;

	INSERT INTO tblHeader (
		DateID,
		CompanyID,
		AccountID,
		TotalCharges,
		TotalCost,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT 
		DateID,
		CompanyID,
		AccountID,
		SUM(TotalCharges) as TotalCharges,
		SUM(TotalCost) as TotalCost,
		SUM(TotalBilledDuration) as TotalBilledDuration,
		SUM(TotalDuration) as TotalDuration,
		SUM(NoOfCalls) as NoOfCalls,
		SUM(NoOfFailCalls) as NoOfFailCalls
	FROM tmp_UsageSummaryLive 
	WHERE CompanyID = p_CompanyID
	GROUP BY DateID,CompanyID,AccountID;

	DELETE FROM tmp_SummaryHeaderLive WHERE CompanyID = p_CompanyID;
	INSERT INTO tmp_SummaryHeaderLive (HeaderID,DateID,CompanyID,AccountID)
	SELECT 
		sh.HeaderID,
		sh.DateID,
		sh.CompanyID,
		sh.AccountID
	FROM tblHeader sh
	INNER JOIN (SELECT DISTINCT DateID,CompanyID FROM tmp_UsageSummaryLive)TBL
	ON TBL.DateID = sh.DateID AND TBL.CompanyID = sh.CompanyID
	WHERE sh.CompanyID =  p_CompanyID ;

	INSERT INTO tblUsageSummaryDayLive (
		HeaderID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		VAccountID,
		Trunk,
		AreaPrefix,
		userfield,
		CountryID,
		TotalCharges,
		TotalCost,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT
		sh.HeaderID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		VAccountID,
		Trunk,
		AreaPrefix,
		userfield,
		CountryID,
		SUM(us.TotalCharges),
		SUM(us.TotalCost),
		SUM(us.TotalBilledDuration),
		SUM(us.TotalDuration),
		SUM(us.NoOfCalls),
		SUM(us.NoOfFailCalls)
	FROM tmp_SummaryHeaderLive sh
	INNER JOIN tmp_UsageSummaryLive us FORCE INDEX (Unique_key)
		ON  us.DateID = sh.DateID
		AND us.CompanyID = sh.CompanyID
		AND us.AccountID = sh.AccountID
	WHERE us.CompanyID = p_CompanyID
	GROUP BY us.DateID,us.CompanyID,us.CompanyGatewayID,us.ServiceID,us.GatewayAccountPKID,us.GatewayVAccountPKID,us.AccountID,us.VAccountID,us.AreaPrefix,us.Trunk,us.CountryID,sh.HeaderID,us.userfield;

	INSERT INTO tblUsageSummaryHourLive (
		HeaderID,
		TimeID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		VAccountID,
		Trunk,
		AreaPrefix,
		userfield,
		CountryID,
		TotalCharges,
		TotalCost,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT 
		sh.HeaderID,
		TimeID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		VAccountID,
		Trunk,
		AreaPrefix,
		userfield,
		CountryID,
		us.TotalCharges,
		us.TotalCost,
		us.TotalBilledDuration,
		us.TotalDuration,
		us.NoOfCalls,
		us.NoOfFailCalls
	FROM tmp_SummaryHeaderLive sh
	INNER JOIN tmp_UsageSummaryLive us FORCE INDEX (Unique_key)
		ON  us.DateID = sh.DateID
		AND us.CompanyID = sh.CompanyID
		AND us.AccountID = sh.AccountID
	WHERE us.CompanyID = p_CompanyID;

	COMMIT;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_generateVendorSummary` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_generateVendorSummary`(
	IN `p_CompanyID` INT,
	IN `p_StartDate` DATE,
	IN `p_EndDate` DATE,
	IN `p_UniqueID` VARCHAR(50)


)
BEGIN
	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 COMMITTED;
	
	CALL telsomespainRM.prc_UpdateMysqlPID(p_UniqueID);
	
	CALL fngetDefaultCodes(p_CompanyID);
		
-- 	CALL fnGetUsageForSummary(p_CompanyID,p_StartDate,p_EndDate,p_UniqueID); 
-- 	CALL fnGetVendorUsageForSummary(p_CompanyID,p_StartDate,p_EndDate,p_UniqueID);
	CALL fnUpdateVendorLink(p_CompanyID,p_StartDate,p_EndDate,p_UniqueID);

	DELETE FROM tmp_VendorUsageSummary WHERE CompanyID = p_CompanyID;

	SET @stmt = CONCAT('
	INSERT INTO tmp_VendorUsageSummary(
		DateID,
		TimeID,
		CompanyID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		VAccountID,
		Trunk,
		AreaPrefix,
		TotalCharges,
		TotalSales,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT 
		d.DateID,
		t.TimeID,
		ud.CompanyID,
		ud.CompanyGatewayID,
		ud.ServiceID,
		ud.GatewayAccountPKID,
		ud.GatewayVAccountPKID,
		ud.AccountID,
		ud.VAccountID,
		ud.trunk,
		ud.area_prefix,
		COALESCE(SUM(ud.buying_cost),0)  AS TotalCharges ,
		COALESCE(SUM(ud.selling_cost),0)  AS TotalSales ,
		COALESCE(SUM(ud.billed_duration),0) AS TotalBilledDuration ,
		COALESCE(SUM(ud.duration),0) AS TotalDuration,
		SUM(IF(ud.call_status_v=1,1,0)) AS  NoOfCalls,
		SUM(IF(ud.call_status_v=2,1,0)) AS  NoOfFailCalls
	FROM tmp_tblVendorUsageDetailsReport_',p_UniqueID,' ud  
	INNER JOIN tblDimTime t ON t.fulltime = connect_time
	INNER JOIN tblDimDate d ON d.date = connect_date
	WHERE ud.CompanyID = ',p_CompanyID,'
		AND ud.VAccountID IS NOT NULL
	GROUP BY d.DateID,t.TimeID,ud.CompanyID,ud.CompanyGatewayID,ud.ServiceID,ud.GatewayAccountPKID,ud.GatewayVAccountPKID,ud.AccountID,ud.VAccountID,ud.area_prefix,ud.trunk;	
	');


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

	UPDATE tmp_VendorUsageSummary 
	INNER JOIN  tmp_codes_ as code ON AreaPrefix = code.code
	SET tmp_VendorUsageSummary.CountryID =code.CountryID
	WHERE tmp_VendorUsageSummary.CompanyID = p_CompanyID AND code.CountryID > 0;

	START TRANSACTION;
	
	DELETE us FROM tblVendorSummaryDay us 
	INNER JOIN tblHeaderV sh ON us.HeaderVID = sh.HeaderVID
	INNER JOIN tblDimDate d ON d.DateID = sh.DateID
	WHERE date BETWEEN p_StartDate AND p_EndDate AND sh.CompanyID = p_CompanyID;
	
	DELETE usd FROM tblVendorSummaryHour usd
	INNER JOIN tblHeaderV sh ON usd.HeaderVID = sh.HeaderVID
	INNER JOIN tblDimDate d ON d.DateID = sh.DateID
	WHERE date BETWEEN p_StartDate AND p_EndDate AND sh.CompanyID = p_CompanyID;
	
	DELETE h FROM tblHeaderV h 
	INNER JOIN (SELECT DISTINCT DateID,CompanyID FROM tmp_VendorUsageSummary)u
		ON h.DateID = u.DateID 
		AND h.CompanyID = u.CompanyID
	WHERE u.CompanyID = p_CompanyID;
	
	INSERT INTO tblHeaderV (
		DateID,
		CompanyID,
		VAccountID,
		TotalCharges,
		TotalSales,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT 
		DateID,
		CompanyID,
		VAccountID,
		SUM(TotalCharges) as TotalCharges,
		SUM(TotalSales) as TotalSales,		
		SUM(TotalBilledDuration) as TotalBilledDuration,
		SUM(TotalDuration) as TotalDuration,
		SUM(NoOfCalls) as NoOfCalls,
		SUM(NoOfFailCalls) as NoOfFailCalls
	FROM tmp_VendorUsageSummary 
	WHERE CompanyID = p_CompanyID
	GROUP BY DateID,CompanyID,VAccountID;
	
	DELETE FROM tmp_SummaryVendorHeader WHERE CompanyID = p_CompanyID;
	INSERT INTO tmp_SummaryVendorHeader (HeaderVID,DateID,CompanyID,VAccountID)
	SELECT 
		sh.HeaderVID,
		sh.DateID,
		sh.CompanyID,
		sh.VAccountID
	FROM tblHeaderV sh
	INNER JOIN (SELECT DISTINCT DateID,CompanyID FROM tmp_VendorUsageSummary)TBL
	ON TBL.DateID = sh.DateID AND TBL.CompanyID = sh.CompanyID
	WHERE sh.CompanyID =  p_CompanyID ;

	INSERT INTO tblVendorSummaryDay (
		HeaderVID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		Trunk,
		AreaPrefix,
		CountryID,
		TotalCharges,
		TotalSales,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT
		sh.HeaderVID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		Trunk,
		AreaPrefix,
		CountryID,
		SUM(us.TotalCharges),
		SUM(us.TotalSales),
		SUM(us.TotalBilledDuration),
		SUM(us.TotalDuration),
		SUM(us.NoOfCalls),
		SUM(us.NoOfFailCalls)
	FROM tmp_SummaryVendorHeader sh
	INNER JOIN tmp_VendorUsageSummary us FORCE INDEX (Unique_key)	 
		ON  us.DateID = sh.DateID
		AND us.CompanyID = sh.CompanyID
		AND us.VAccountID = sh.VAccountID
	WHERE us.CompanyID = p_CompanyID
	GROUP BY us.DateID,us.CompanyID,us.CompanyGatewayID,us.ServiceID,us.GatewayAccountPKID,us.GatewayVAccountPKID,us.AccountID,us.VAccountID,us.AreaPrefix,us.Trunk,us.CountryID,sh.HeaderVID;
	
	INSERT INTO tblVendorSummaryHour (
		HeaderVID,
		TimeID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		Trunk,
		AreaPrefix,
		CountryID,
		TotalCharges,
		TotalSales,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls	
	)
	SELECT 
		sh.HeaderVID,
		TimeID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		Trunk,
		AreaPrefix,
		CountryID,
		us.TotalCharges,
		us.TotalSales,
		us.TotalBilledDuration,
		us.TotalDuration,
		us.NoOfCalls,
		us.NoOfFailCalls
	FROM tmp_SummaryVendorHeader sh
	INNER JOIN tmp_VendorUsageSummary us FORCE INDEX (Unique_key)
		ON  us.DateID = sh.DateID
		AND us.CompanyID = sh.CompanyID
		AND us.VAccountID = sh.VAccountID
	WHERE us.CompanyID = p_CompanyID;

	CALL fnDistinctList(p_CompanyID);

	COMMIT;
	
	SET @stmt = CONCAT('TRUNCATE TABLE tmp_tblUsageDetailsReport_',p_UniqueID,';');

	PREPARE stmt FROM @stmt;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
	SET @stmt = CONCAT('TRUNCATE TABLE tmp_tblVendorUsageDetailsReport_',p_UniqueID,';');

	PREPARE stmt FROM @stmt;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
	
	
	/*SET @stmt = CONCAT('TRUNCATE TABLE tblTempCallDetail_2_',p_UniqueID,';');

	PREPARE stmt FROM @stmt;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;*/
	
	DELETE FROM tmp_VendorUsageSummary WHERE CompanyID = p_CompanyID;
	
	
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_generateVendorSummaryLive` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_generateVendorSummaryLive`(
	IN `p_CompanyID` INT,
	IN `p_StartDate` DATE,
	IN `p_EndDate` DATE,
	IN `p_UniqueID` VARCHAR(50)

)
BEGIN
	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 COMMITTED;
	
	CALL telsomespainRM.prc_UpdateMysqlPID(CONCAT(p_UniqueID,'vendor'));
	
	CALL fngetDefaultCodes(p_CompanyID);

	DELETE FROM tmp_VendorUsageSummaryLive WHERE CompanyID = p_CompanyID;

	SET @stmt = CONCAT('
	INSERT INTO tmp_VendorUsageSummaryLive(
		DateID,
		TimeID,
		CompanyID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		VAccountID,
		Trunk,
		AreaPrefix,
		TotalCharges,
		TotalSales,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT 
		d.DateID,
		t.TimeID,
		ud.CompanyID,
		ud.CompanyGatewayID,
		ud.ServiceID,
		ud.GatewayAccountPKID,
		ud.GatewayVAccountPKID,
		ud.AccountID,
		ud.VAccountID,
		ud.trunk,
		ud.area_prefix,
		COALESCE(SUM(ud.buying_cost),0)  AS TotalCharges ,
		COALESCE(SUM(ud.selling_cost),0)  AS TotalSales ,
		COALESCE(SUM(ud.billed_duration),0) AS TotalBilledDuration ,
		COALESCE(SUM(ud.duration),0) AS TotalDuration,
		SUM(IF(ud.call_status_v=1,1,0)) AS  NoOfCalls,
		SUM(IF(ud.call_status_v=2,1,0)) AS  NoOfFailCalls
	FROM tmp_tblVendorUsageDetailsReport_',p_UniqueID,' ud  
	INNER JOIN tblDimTime t ON t.fulltime = connect_time
	INNER JOIN tblDimDate d ON d.date = connect_date
	WHERE ud.CompanyID = ',p_CompanyID,'
		AND ud.VAccountID IS NOT NULL
	GROUP BY d.DateID,t.TimeID,ud.CompanyID,ud.CompanyGatewayID,ud.ServiceID,ud.GatewayAccountPKID,ud.GatewayVAccountPKID,ud.AccountID,ud.VAccountID,ud.area_prefix,ud.trunk;	
	');

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

	UPDATE tmp_VendorUsageSummaryLive 
	INNER JOIN  tmp_codes_ as code ON AreaPrefix = code.code
	SET tmp_VendorUsageSummaryLive.CountryID =code.CountryID
	WHERE tmp_VendorUsageSummaryLive.CompanyID = p_CompanyID AND code.CountryID > 0;

	START TRANSACTION;

	DELETE us FROM tblVendorSummaryDayLive us 
	INNER JOIN tblHeaderV sh ON us.HeaderVID = sh.HeaderVID
	INNER JOIN tblDimDate d ON d.DateID = sh.DateID
	WHERE date BETWEEN p_StartDate AND p_EndDate AND sh.CompanyID = p_CompanyID;

	DELETE usd FROM tblVendorSummaryHourLive usd
	INNER JOIN tblHeaderV sh ON usd.HeaderVID = sh.HeaderVID
	INNER JOIN tblDimDate d ON d.DateID = sh.DateID
	WHERE date BETWEEN p_StartDate AND p_EndDate AND sh.CompanyID = p_CompanyID;

	DELETE h FROM tblHeaderV h 
	INNER JOIN (SELECT DISTINCT DateID,CompanyID FROM tmp_VendorUsageSummaryLive)u
		ON h.DateID = u.DateID 
		AND h.CompanyID = u.CompanyID
	WHERE u.CompanyID = p_CompanyID;

	INSERT INTO tblHeaderV (
		DateID,
		CompanyID,
		VAccountID,
		TotalCharges,
		TotalSales,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT
		DateID,
		CompanyID,
		VAccountID,
		SUM(TotalCharges) as TotalCharges,
		SUM(TotalSales) as TotalSales,
		SUM(TotalBilledDuration) as TotalBilledDuration,
		SUM(TotalDuration) as TotalDuration,
		SUM(NoOfCalls) as NoOfCalls,
		SUM(NoOfFailCalls) as NoOfFailCalls
	FROM tmp_VendorUsageSummaryLive 
	WHERE CompanyID = p_CompanyID
	GROUP BY DateID,CompanyID,VAccountID;

	DELETE FROM tmp_SummaryVendorHeaderLive WHERE CompanyID = p_CompanyID;
	INSERT INTO tmp_SummaryVendorHeaderLive (HeaderVID,DateID,CompanyID,VAccountID)
	SELECT 
		sh.HeaderVID,
		sh.DateID,
		sh.CompanyID,
		sh.VAccountID
	FROM tblHeaderV sh
	INNER JOIN (SELECT DISTINCT DateID,CompanyID FROM tmp_VendorUsageSummaryLive)TBL
	ON TBL.DateID = sh.DateID AND TBL.CompanyID = sh.CompanyID
	WHERE sh.CompanyID =  p_CompanyID ;

	INSERT INTO tblVendorSummaryDayLive (
		HeaderVID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		Trunk,
		AreaPrefix,
		CountryID,
		TotalCharges,
		TotalSales,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT
		sh.HeaderVID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		Trunk,
		AreaPrefix,
		CountryID,
		SUM(us.TotalCharges),
		SUM(us.TotalSales),
		SUM(us.TotalBilledDuration),
		SUM(us.TotalDuration),
		SUM(us.NoOfCalls),
		SUM(us.NoOfFailCalls)
	FROM tmp_SummaryVendorHeaderLive sh
	INNER JOIN tmp_VendorUsageSummaryLive us FORCE INDEX (Unique_key)
		ON  us.DateID = sh.DateID
		AND us.CompanyID = sh.CompanyID
		AND us.VAccountID = sh.VAccountID
	WHERE us.CompanyID = p_CompanyID
	GROUP BY us.DateID,us.CompanyID,us.CompanyGatewayID,us.ServiceID,us.GatewayAccountPKID,us.GatewayVAccountPKID,us.AccountID,us.VAccountID,us.AreaPrefix,us.Trunk,us.CountryID,sh.HeaderVID;

	INSERT INTO tblVendorSummaryHourLive (
		HeaderVID,
		TimeID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		Trunk,
		AreaPrefix,
		CountryID,
		TotalCharges,
		TotalSales,
		TotalBilledDuration,
		TotalDuration,
		NoOfCalls,
		NoOfFailCalls
	)
	SELECT 
		sh.HeaderVID,
		TimeID,
		CompanyGatewayID,
		ServiceID,
		GatewayAccountPKID,
		GatewayVAccountPKID,
		AccountID,
		Trunk,
		AreaPrefix,
		CountryID,
		us.TotalCharges,
		us.TotalSales,
		us.TotalBilledDuration,
		us.TotalDuration,
		us.NoOfCalls,
		us.NoOfFailCalls
	FROM tmp_SummaryVendorHeaderLive sh
	INNER JOIN tmp_VendorUsageSummaryLive us FORCE INDEX (Unique_key)
		ON  us.DateID = sh.DateID
		AND us.CompanyID = sh.CompanyID
		AND us.VAccountID = sh.VAccountID
	WHERE us.CompanyID = p_CompanyID;

	COMMIT;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAccountExpense` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getAccountExpense`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` INT
)
BEGIN
	DECLARE v_Round_ int;
	DECLARE v_DateID_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	SELECT MIN(DateID) INTO v_DateID_ FROM tblDimDate WHERE fnGetMonthDifference(date,NOW()) <= 12;

	DROP TEMPORARY TABLE IF EXISTS tmp_tblUsageSummary_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblUsageSummary_(
		`DateID` BIGINT(20) NOT NULL,
		`CompanyID` INT(11) NOT NULL,
		`AccountID` INT(11) NOT NULL,
		`AreaPrefix` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
		`TotalCharges` DOUBLE NULL DEFAULT NULL,
		`CustomerVendor` INT,
		INDEX `tmp_tblUsageSummary_DateID` (`DateID`)
	);
	DROP TEMPORARY TABLE IF EXISTS tmp_tblUsageSummary2_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblUsageSummary2_(
		`DateID` BIGINT(20) NOT NULL,
		`CompanyID` INT(11) NOT NULL,
		`AccountID` INT(11) NOT NULL,
		`AreaPrefix` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
		`TotalCharges` DOUBLE NULL DEFAULT NULL,
		`CustomerVendor` INT,
		INDEX `tmp_tblUsageSummary_DateID` (`DateID`)
	);
	DROP TEMPORARY TABLE IF EXISTS tmp_tblCustomerPrefix_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblCustomerPrefix_(
		`AreaPrefix` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
		`CustomerTotal` DOUBLE NULL DEFAULT NULL,
		`FinalTotal` DOUBLE NULL DEFAULT NULL,
		`YearMonth` VARCHAR(50) NOT NULL
	);
	DROP TEMPORARY TABLE IF EXISTS tmp_tblVendorPrefix_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblVendorPrefix_(
		`AreaPrefix` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
		`VendorTotal` DOUBLE NULL DEFAULT NULL,
		`FinalTotal` DOUBLE NULL DEFAULT NULL,
		`YearMonth` VARCHAR(50) NOT NULL
	);
	
	
	INSERT INTO tmp_tblUsageSummary_
	SELECT
		sh.DateID,
		sh.CompanyID,
		sh.AccountID,
		us.AreaPrefix,
		us.TotalCharges,
		1 as Customer
	FROM tblHeader sh
	INNER JOIN tblUsageSummaryDay us
		ON us.HeaderID = sh.HeaderID 
	WHERE  sh.CompanyID = p_CompanyID
	AND sh.AccountID = p_AccountID;
	
	INSERT INTO tmp_tblUsageSummary_
	SELECT
		sh.DateID,
		sh.CompanyID,
		sh.AccountID,
		us.AreaPrefix,
		us.TotalCharges,
		1 as Customer
	FROM tblHeader sh
	INNER JOIN tblUsageSummaryDayLive us
		ON us.HeaderID = sh.HeaderID 
	WHERE  sh.CompanyID = p_CompanyID
	AND sh.AccountID = p_AccountID;
	
	
	INSERT INTO tmp_tblUsageSummary_
	SELECT
		sh.DateID,
		sh.CompanyID,
		sh.VAccountID,
		us.AreaPrefix,
		us.TotalCharges,
		2 as Vendor
	FROM tblHeaderV sh
	INNER JOIN tblVendorSummaryDay us
		ON us.HeaderVID = sh.HeaderVID 
	WHERE  sh.CompanyID = p_CompanyID
	AND sh.VAccountID = p_AccountID;
	
	INSERT INTO tmp_tblUsageSummary_
	SELECT
		sh.DateID,
		sh.CompanyID,
		sh.VAccountID,
		us.AreaPrefix,
		us.TotalCharges,
		2 as Vendor
	FROM tblHeaderV sh
	INNER JOIN tblVendorSummaryDayLive us
		ON us.HeaderVID = sh.HeaderVID 
	WHERE  sh.CompanyID = p_CompanyID
	AND sh.VAccountID = p_AccountID;
	
	INSERT INTO tmp_tblUsageSummary2_
	SELECT * FROM tmp_tblUsageSummary_;
	
	
	SELECT 
		ROUND(SUM(IF(CustomerVendor=1,TotalCharges,0)),v_Round_) AS  CustomerTotal,
		ROUND(SUM(IF(CustomerVendor=2,TotalCharges,0)),v_Round_) AS  VendorTotal,
		dd.year as Year,
		dd.month_of_year as Month
	FROM tmp_tblUsageSummary_ us 
	INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
	GROUP BY dd.year,dd.month_of_year;
	
	
	INSERT INTO tmp_tblCustomerPrefix_
	SELECT 
		us.AreaPrefix,
		ROUND(SUM(TotalCharges),2) AS  CustomerTotal,
		FinalTotal,
		CONCAT(dd.year,'-',dd.month_of_year) as YearMonth
	FROM tmp_tblUsageSummary_ us 
	INNER JOIN 
	(SELECT SUM(TotalCharges) as FinalTotal,AreaPrefix FROM tmp_tblUsageSummary2_ WHERE CustomerVendor = 1 AND AreaPrefix != 'other' AND DateID >= v_DateID_ GROUP BY AreaPrefix ORDER BY FinalTotal DESC LIMIT 5 ) tbl
	ON tbl.AreaPrefix = us.AreaPrefix
	INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
	WHERE 
			 us.CustomerVendor = 1 
		AND us.AreaPrefix != 'other'
		AND dd.DateID >= v_DateID_
	GROUP BY dd.year,dd.month_of_year,us.AreaPrefix;
	
	
	
	IF (SELECT COUNT(*) FROM tmp_tblCustomerPrefix_) > 0
	THEN
		SET @sql = NULL;
		
		SELECT
			GROUP_CONCAT( DISTINCT CONCAT('MAX(IF(YearMonth = ''',YearMonth,''', CustomerTotal, 0)) AS ''',YearMonth,'''') ) INTO @sql
		FROM tmp_tblCustomerPrefix_;
	
		SET @sql = CONCAT('
							SELECT AreaPrefix , ', @sql, ' 
							FROM tmp_tblCustomerPrefix_ 
							GROUP BY AreaPrefix
							ORDER BY MAX(FinalTotal) desc, MAX(YearMonth)
						');
		
		PREPARE stmt FROM @sql;
		EXECUTE stmt;
		DEALLOCATE PREPARE stmt;
	ELSE
		SELECT 0 as datacount;
	END IF;

	
	INSERT INTO tmp_tblVendorPrefix_
	SELECT 
		us.AreaPrefix,
		ROUND(SUM(TotalCharges),2) AS  VendorTotal,
		FinalTotal,
		CONCAT(dd.year,'-',dd.month_of_year) as YearMonth
	FROM tmp_tblUsageSummary_ us 
	INNER JOIN 
	(SELECT SUM(TotalCharges) as FinalTotal,AreaPrefix FROM tmp_tblUsageSummary2_ WHERE CustomerVendor = 2 AND AreaPrefix != 'other' AND DateID >= v_DateID_ GROUP BY AreaPrefix ORDER BY FinalTotal DESC LIMIT 5 ) tbl
	ON tbl.AreaPrefix = us.AreaPrefix
	INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
	WHERE 
			 us.CustomerVendor = 2 
		AND us.AreaPrefix != 'other'
		AND dd.DateID >= v_DateID_
	GROUP BY dd.year,dd.month_of_year,us.AreaPrefix;

	
	
	IF (SELECT COUNT(*) FROM tmp_tblVendorPrefix_) > 0
	THEN
	
		SET @stm = NULL;
		SELECT
			GROUP_CONCAT( DISTINCT CONCAT('MAX(IF(YearMonth = ''',YearMonth,''', VendorTotal, 0)) AS ''',YearMonth,'''') ) INTO @stm
		FROM tmp_tblVendorPrefix_;

		SET @stm = CONCAT('
							SELECT AreaPrefix , ', @stm, ' 
							FROM tmp_tblVendorPrefix_ 
							GROUP BY AreaPrefix
							ORDER BY MAX(FinalTotal) desc, MAX(YearMonth)
						');
		PREPARE stmt FROM @stm;
		EXECUTE stmt;
		DEALLOCATE PREPARE stmt;
	ELSE
		SELECT 0 as datacount;	
	END IF;
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
	
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAccountManager` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getAccountManager`(
	IN `p_CompanyID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_UserID` VARCHAR(50),
	IN `p_isAdmin` INT,
	IN `p_ReportType` VARCHAR(50),
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN

	DECLARE v_Round_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	DROP TEMPORARY TABLE IF EXISTS tmp_tblUsageSummary_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblUsageSummary_(
			`DateID` BIGINT(20) NOT NULL,
			`Date` DATE,
			`CompanyID` INT(11) NOT NULL,
			`AccountID` INT(11) NOT NULL,
			`TotalCharges` DOUBLE NULL DEFAULT NULL,
			`TotalCost` DOUBLE NULL DEFAULT NULL,
			`AccountName` varchar(100),
			`UserName` varchar(100),
			INDEX `tblUsageSummary_dim_date` (`DateID`)
	);
	INSERT INTO tmp_tblUsageSummary_
	SELECT
		sh.DateID,
		dd.date,
		sh.CompanyID,
		sh.AccountID,
		us.TotalCharges,
		us.TotalCost,
		a.AccountName,
		CONCAT(IFNULL(u.FirstName,''),' ',IFNULL(u.LastName,''))
	FROM tblHeader sh
	INNER JOIN tblUsageSummaryDay  us
		ON us.HeaderID = sh.HeaderID
	INNER JOIN tblDimDate dd
		ON dd.DateID = sh.DateID
	INNER JOIN telsomespainRM.tblAccount a
		ON sh.AccountID = a.AccountID
	INNER JOIN telsomespainRM.tblUser u
		ON a.Owner = u.UserID
	WHERE dd.date BETWEEN p_StartDate AND p_EndDate
	AND sh.CompanyID = p_CompanyID
	AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND FIND_IN_SET(a.Owner,p_UserID) > 0))
	AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID);

	INSERT INTO tmp_tblUsageSummary_
	SELECT
		sh.DateID,
		dd.date,
		sh.CompanyID,
		sh.AccountID,
		us.TotalCharges,
		us.TotalCost,
		a.AccountName,
		CONCAT(IFNULL(u.FirstName,''),' ',IFNULL(u.LastName,''))
	FROM tblHeader sh
	INNER JOIN tblUsageSummaryDayLive  us
		ON us.HeaderID = sh.HeaderID
	INNER JOIN tblDimDate dd
		ON dd.DateID = sh.DateID
	INNER JOIN telsomespainRM.tblAccount a
		ON sh.AccountID = a.AccountID
	INNER JOIN telsomespainRM.tblUser u
		ON a.Owner = u.UserID
	WHERE dd.date BETWEEN p_StartDate AND p_EndDate
	AND sh.CompanyID = p_CompanyID
	AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND FIND_IN_SET(a.Owner,p_UserID) > 0))
	AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID);

	
	IF p_ReportType = 'Daily' AND p_isExport = 0
	THEN

		SELECT 
			UserName,
			us.Date as TIMEVAL,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage,
			CONCAT(us.Date,' ## ',us.Date) as DATERANGE
		FROM tmp_tblUsageSummary_ us
		GROUP BY us.Date,us.UserName
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameDESC') THEN UserName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameASC') THEN UserName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALDESC') THEN us.Date
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALASC') THEN us.Date
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN COALESCE(SUM(TotalCharges),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN COALESCE(SUM(TotalCharges),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END ASC;

		SELECT COUNT(*) AS totalcount,SUM(TotalMargin) AS TotalMargin,SUM(TotalCost) AS TotalCost
		FROM (
			SELECT
				ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
				ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin
			FROM tmp_tblUsageSummary_ us
			GROUP BY us.Date,us.UserName
		)tbl;

	END IF;

	IF p_ReportType = 'Weekly' AND p_isExport = 0
	THEN

		SELECT 
			UserName,
			CONCAT(dd.year,'-',dd.week_of_year) as TIMEVAL,
			ROUND(COALESCE(SUM(TotalCharges),0), 2) as TotalCost,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), 2) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, 2) as MarginPercentage,
			CONCAT(MIN(us.Date),' ## ',MAX(us.Date)) as DATERANGE
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,dd.week_of_year,UserName
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameDESC') THEN UserName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameASC') THEN UserName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALDESC') THEN CONCAT(dd.year,'-',dd.week_of_year)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALASC') THEN CONCAT(dd.year,'-',dd.week_of_year)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN COALESCE(SUM(TotalCharges),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN COALESCE(SUM(TotalCharges),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END ASC;

		SELECT COUNT(*) AS totalcount,SUM(TotalMargin) AS TotalMargin,SUM(TotalCost) AS TotalCost
		FROM (
			SELECT
				ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
				ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin
			FROM tmp_tblUsageSummary_ us
			INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
			GROUP BY  dd.year,dd.week_of_year,UserName
		)tbl;

	END IF;

	IF p_ReportType = 'Monthly' AND p_isExport = 0
	THEN

		SELECT 
			UserName,
			CONCAT(dd.year,'-',dd.month_of_year) as TIMEVAL,
			ROUND(COALESCE(SUM(TotalCharges),0), 2) as TotalCost,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), 2) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, 2) as MarginPercentage,
			CONCAT(MIN(us.Date),' ## ',MAX(us.Date)) as DATERANGE
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,dd.month_of_year,UserName
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameDESC') THEN UserName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameASC') THEN UserName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALDESC') THEN CONCAT(dd.year,'-',dd.month_of_year)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALASC') THEN CONCAT(dd.year,'-',dd.month_of_year)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN COALESCE(SUM(TotalCharges),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN COALESCE(SUM(TotalCharges),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END ASC;

		SELECT COUNT(*) AS totalcount,SUM(TotalMargin) AS TotalMargin,SUM(TotalCost) AS TotalCost
		FROM (
			SELECT
				ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
				ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin
			FROM tmp_tblUsageSummary_ us
			INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
			GROUP BY  dd.year,dd.month_of_year,UserName
		)tbl;

	END IF;

	IF p_ReportType = 'Yearly' AND p_isExport = 0
	THEN

		SELECT 
			UserName,
			dd.year as TIMEVAL,
			ROUND(COALESCE(SUM(TotalCharges),0), 2) as TotalCost,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), 2) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, 2) as MarginPercentage,
			CONCAT(MIN(us.Date),' ## ',MAX(us.Date)) as DATERANGE
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,UserName
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameDESC') THEN UserName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameASC') THEN UserName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALDESC') THEN dd.year
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALASC') THEN dd.year
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN COALESCE(SUM(TotalCharges),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN COALESCE(SUM(TotalCharges),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END ASC;

		SELECT COUNT(*) AS totalcount,SUM(TotalMargin) AS TotalMargin,SUM(TotalCost) AS TotalCost
		FROM (
			SELECT
				ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
				ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin
			FROM tmp_tblUsageSummary_ us
			INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
			GROUP BY  dd.year,UserName
		)tbl;


	END IF;

	IF p_ReportType = 'Daily' AND p_isExport = 1
	THEN

		SELECT 
			UserName AS `User`,
			us.Date AS `Period`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) AS `Revenue`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) AS `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) AS `Margin(%)`
		FROM tmp_tblUsageSummary_ us
		GROUP BY us.Date,us.UserName;

	END IF;

	IF p_ReportType = 'Weekly' AND p_isExport = 1
	THEN

		SELECT 
			UserName AS `User`,
			CONCAT(dd.year,'-',dd.week_of_year) as `Period`,
			ROUND(COALESCE(SUM(TotalCharges),0), 2) as `Revenue`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), 2) AS `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, 2) AS `Margin(%)`
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,dd.week_of_year,UserName;

	END IF;

	IF p_ReportType = 'Monthly' AND p_isExport = 1
	THEN

		SELECT 
			UserName AS `User`,
			CONCAT(dd.year,'-',dd.month_of_year) as `Period`,
			ROUND(COALESCE(SUM(TotalCharges),0), 2) as `Revenue`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), 2) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, 2) AS `Margin(%)`
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,dd.month_of_year,UserName;

	END IF;

	IF p_ReportType = 'Yearly' AND p_isExport = 1
	THEN

		SELECT 
			UserName AS `User`,
			CONCAT(dd.year) as `Period`,
			ROUND(COALESCE(SUM(TotalCharges),0), 2) as `Revenue`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), 2) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, 2) AS `Margin(%)`
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,UserName;

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAccountReport` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getAccountReport`(
	IN `p_CompanyID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_UserID` VARCHAR(50),
	IN `p_isAdmin` INT,
	IN `p_ReportType` VARCHAR(50),
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN

	DECLARE v_Round_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	DROP TEMPORARY TABLE IF EXISTS tmp_tblUsageSummary_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_tblUsageSummary_(
			`DateID` BIGINT(20) NOT NULL,
			`Date` DATE,
			`CompanyID` INT(11) NOT NULL,
			`AccountID` INT(11) NOT NULL,
			`TotalCharges` DOUBLE NULL DEFAULT NULL,
			`TotalCost` DOUBLE NULL DEFAULT NULL,
			`AccountName` varchar(100),
			`UserName` varchar(100),
			INDEX `tblUsageSummary_dim_date` (`DateID`)
	);
	INSERT INTO tmp_tblUsageSummary_
	SELECT
		sh.DateID,
		dd.date,
		sh.CompanyID,
		sh.AccountID,
		us.TotalCharges,
		us.TotalCost,
		a.AccountName,
		CONCAT(IFNULL(u.FirstName,''),' ',IFNULL(u.LastName,''))
	FROM tblHeader sh
	INNER JOIN tblUsageSummaryDay  us
		ON us.HeaderID = sh.HeaderID
	INNER JOIN tblDimDate dd
		ON dd.DateID = sh.DateID
	INNER JOIN telsomespainRM.tblAccount a
		ON sh.AccountID = a.AccountID
	INNER JOIN telsomespainRM.tblUser u
		ON a.Owner = u.UserID
	WHERE dd.date BETWEEN p_StartDate AND p_EndDate
	AND sh.CompanyID = p_CompanyID
	AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND FIND_IN_SET(a.Owner,p_UserID) > 0))
	AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID);

	INSERT INTO tmp_tblUsageSummary_
	SELECT
		sh.DateID,
		dd.date,
		sh.CompanyID,
		sh.AccountID,
		us.TotalCharges,
		us.TotalCost,
		a.AccountName,
		CONCAT(IFNULL(u.FirstName,''),' ',IFNULL(u.LastName,''))
	FROM tblHeader sh
	INNER JOIN tblUsageSummaryDayLive  us
		ON us.HeaderID = sh.HeaderID
	INNER JOIN tblDimDate dd
		ON dd.DateID = sh.DateID
	INNER JOIN telsomespainRM.tblAccount a
		ON sh.AccountID = a.AccountID
	INNER JOIN telsomespainRM.tblUser u
		ON a.Owner = u.UserID
	WHERE dd.date BETWEEN p_StartDate AND p_EndDate
	AND sh.CompanyID = p_CompanyID
	AND (p_isAdmin = 1 OR (p_isAdmin= 0 AND FIND_IN_SET(a.Owner,p_UserID) > 0))
	AND (p_CurrencyID = 0 OR a.CurrencyId = p_CurrencyID);

	
	IF p_ReportType = 'Daily' AND p_isExport = 0
	THEN

		SELECT 
			
			MAX(UserName),
			AccountName,
			us.Date as TIMEVAL,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage,
			CONCAT(us.Date,' ## ',us.Date) as DATERANGE
		FROM tmp_tblUsageSummary_ us
		GROUP BY us.Date,us.AccountName
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameDESC') THEN MAX(UserName)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameASC') THEN MAX(UserName)
			END ASC,
				CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN AccountName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN AccountName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALDESC') THEN us.Date
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALASC') THEN us.Date
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN COALESCE(SUM(TotalCharges),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN COALESCE(SUM(TotalCharges),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END ASC;

		SELECT COUNT(*) AS totalcount,SUM(TotalMargin) AS TotalMargin,SUM(TotalCost) AS TotalCost
		FROM (
			SELECT
				ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
				ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin
			FROM tmp_tblUsageSummary_ us
			GROUP BY us.Date,us.AccountName
		)tbl;

	END IF;

	IF p_ReportType = 'Weekly' AND p_isExport = 0
	THEN

		SELECT 
			MAX(UserName),
			AccountName,
			CONCAT(dd.year,'-',dd.week_of_year) as TIMEVAL,
			ROUND(COALESCE(SUM(TotalCharges),0), 2) as TotalCost,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), 2) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, 2) as MarginPercentage,
			CONCAT(MIN(us.Date),' ## ',MAX(us.Date)) as DATERANGE
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,dd.week_of_year,AccountName
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameDESC') THEN MAX(UserName)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameASC') THEN MAX(UserName)
			END ASC,
				CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN AccountName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN AccountName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALDESC') THEN CONCAT(dd.year,'-',dd.week_of_year)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALASC') THEN CONCAT(dd.year,'-',dd.week_of_year)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN COALESCE(SUM(TotalCharges),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN COALESCE(SUM(TotalCharges),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END ASC;

		SELECT COUNT(*) AS totalcount,SUM(TotalMargin) AS TotalMargin,SUM(TotalCost) AS TotalCost
		FROM (
			SELECT
				ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
				ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin
			FROM tmp_tblUsageSummary_ us
			INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
			GROUP BY dd.year,dd.week_of_year,AccountName
		)tbl;

	END IF;

	IF p_ReportType = 'Monthly' AND p_isExport = 0
	THEN

		SELECT 
			MAX(UserName),
			AccountName,
			CONCAT(dd.year,'-',dd.month_of_year) as TIMEVAL,
			ROUND(COALESCE(SUM(TotalCharges),0), 2) as TotalCost,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), 2) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, 2) as MarginPercentage,
			CONCAT(MIN(us.Date),' ## ',MAX(us.Date)) as DATERANGE
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,dd.month_of_year,AccountName
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameDESC') THEN MAX(UserName)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameASC') THEN MAX(UserName)
			END ASC,
				CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN AccountName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN AccountName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALDESC') THEN CONCAT(dd.year,'-',dd.month_of_year)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALASC') THEN CONCAT(dd.year,'-',dd.month_of_year)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN COALESCE(SUM(TotalCharges),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN COALESCE(SUM(TotalCharges),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END ASC;

		SELECT COUNT(*) AS totalcount,SUM(TotalMargin) AS TotalMargin,SUM(TotalCost) AS TotalCost
		FROM (
			SELECT
				ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
				ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin
			FROM tmp_tblUsageSummary_ us
			INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
			GROUP BY dd.year,dd.month_of_year,AccountName
		)tbl;

	END IF;

	IF p_ReportType = 'Yearly' AND p_isExport = 0
	THEN

		SELECT 
			MAX(UserName),
			AccountName,
			dd.year as TIMEVAL,
			ROUND(COALESCE(SUM(TotalCharges),0), 2) as TotalCost,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), 2) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, 2) as MarginPercentage,
			CONCAT(MIN(us.Date),' ## ',MAX(us.Date)) as DATERANGE
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,AccountName
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameDESC') THEN MAX(UserName)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UserNameASC') THEN MAX(UserName)
			END ASC,
				CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN AccountName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN AccountName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALDESC') THEN dd.year
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TIMEVALASC') THEN dd.year
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN COALESCE(SUM(TotalCharges),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN COALESCE(SUM(TotalCharges),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100
			END ASC;

		SELECT COUNT(*) AS totalcount,SUM(TotalMargin) AS TotalMargin,SUM(TotalCost) AS TotalCost
		FROM (
			SELECT
				ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
				ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin
			FROM tmp_tblUsageSummary_ us
			INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
			GROUP BY dd.year,AccountName
		)tbl;

	END IF;

	IF p_ReportType = 'Daily' AND p_isExport = 1
	THEN

		SELECT 
			MAX(UserName) AS `Account Manager`,
			AccountName AS `Account`,
			us.Date as `Period`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Revenue`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as `Margin(%)`
		FROM tmp_tblUsageSummary_ us
		GROUP BY us.Date,us.AccountName;

	END IF;

	IF p_ReportType = 'Weekly' AND p_isExport = 1
	THEN

		SELECT 
			MAX(UserName) AS `Account Manager`,
			AccountName AS `Account`,
			CONCAT(dd.year,'-',dd.week_of_year) as `Period`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Revenue`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as `Margin(%)`
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,dd.week_of_year,AccountName;

	END IF;

	IF p_ReportType = 'Monthly' AND p_isExport = 1
	THEN

		SELECT 
			MAX(UserName) AS `Account Manager`,
			AccountName AS `Account`,
			CONCAT(dd.year,'-',dd.month_of_year) as `Period`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Revenue`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as `Margin(%)`
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,dd.month_of_year,AccountName;

	END IF;

	IF p_ReportType = 'Yearly' AND p_isExport = 1
	THEN

		SELECT 
			MAX(UserName) AS `Account Manager`,
			AccountName AS `Account`,
			dd.year as `Period`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Revenue`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as `Margin(%)`
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		GROUP BY  dd.year,AccountName;

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAccountReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getAccountReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_ResellerID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_CDRType` VARCHAR(50),
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ int;
	DECLARE v_OffSet_ int;
		
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnUsageSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_CDRType,p_UserID,p_isAdmin,2,p_ResellerID,p_tag);

	
	/* grid display*/
	IF p_isExport = 0
	THEN
	
	/* account by call count */	
	SELECT AccountName ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
		FORMAT(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
		FORMAT( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage,
	MAX(AccountID) as AccountID
	FROM tmp_tblUsageSummary_ us
	GROUP BY AccountName   
	ORDER BY
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN AccountName
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN AccountName
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
	END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;
	
	SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,
		FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin
	FROM (
		SELECT AccountName ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) as TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		GROUP BY AccountName
	)tbl;

	
	END IF;
	
	/* export data*/
	IF p_isExport = 1
	THEN
		SELECT
			AccountName  as Name,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)` ,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as `Margin (%)`
		FROM tmp_tblUsageSummary_ us
		GROUP BY AccountName;
	END IF;
	
	
	/* chart display*/
	IF p_isExport = 2
	THEN
	
		/* top 10 account by call count */	
		SELECT AccountName as ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		GROUP BY AccountName HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;
		
		/* top 10 account by call cost */	
		SELECT AccountName as ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		GROUP BY AccountName HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;
		
		/* top 10 account by call minutes */	
		SELECT AccountName as ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		GROUP BY AccountName HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;
	
	END IF;
	
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getACD_ASR_Alert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getACD_ASR_Alert`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` TEXT,
	IN `p_AccountID` TEXT,
	IN `p_ResellerID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` TEXT,
	IN `p_Trunk` TEXT,
	IN `p_CountryID` TEXT
)
BEGIN
	
	DECLARE v_Round_ INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnUsageSummaryDetail(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,0,1);

	IF p_AccountID = ''
	THEN
		SELECT
			IF(SUM(NoOfCalls)>0,COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls),0) as ACD , 
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			HOUR(ANY_VALUE(Time)) as Hour,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as Minutes,
			COALESCE(SUM(NoOfCalls),0) as Connected,
			COALESCE(SUM(NoOfCalls),0)+COALESCE(SUM(NoOfFailCalls),0) as Attempts
		FROM tmp_tblUsageSummary_ us;
		
	END IF;
	
	IF p_AccountID != ''
	THEN
		SELECT
			IF(SUM(NoOfCalls)>0,COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls),0) as ACD , 
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			AccountID,
			HOUR(ANY_VALUE(Time)) as Hour,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as Minutes,
			COALESCE(SUM(NoOfCalls),0) as Connected,
			COALESCE(SUM(NoOfCalls),0)+COALESCE(SUM(NoOfFailCalls),0) as Attempts
		FROM tmp_tblUsageSummary_ us
		GROUP BY AccountID;
	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDailyReport` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getDailyReport`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` INT,
	IN `p_StartDate` DATE,
	IN `p_EndDate` DATE,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_isExport` INT


)
BEGIN
	DECLARE v_OffSet_ int;
	DECLARE v_Round_ int;
	SET sql_mode = 'ALLOW_INVALID_DATES';
	SET @PreviosBalance := 0;
	SET @TotalPreviosBalance := 0;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	IF p_StartDate <> '0000-00-00'
	THEN

	SET @PreviosBalance := 
	(SELECT 
		COALESCE(SUM(Amount),0)
	FROM telsomespainBilling.tblPayment 
	WHERE CompanyID = p_CompanyID
		AND AccountID = p_AccountID
		AND Status = 'Approved'
		AND Recall =0
		AND PaymentType = 'Payment In'
		AND PaymentDate < p_StartDate) - 
		
		(SELECT 
		COALESCE(SUM(TotalCharges),0)
	FROM tblHeader
	INNER JOIN tblDimDate 
		ON tblDimDate.DateID = tblHeader.DateID
	WHERE CompanyID = p_CompanyID
		AND AccountID = p_AccountID
		AND date < p_StartDate);
	
	SET @TotalPreviosBalance := @PreviosBalance;

	END IF;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	DROP TEMPORARY TABLE IF EXISTS tmp_dates_;
	CREATE TEMPORARY TABLE tmp_dates_  (
		RowID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
		Dates Date,
		UNIQUE INDEX `date` (`Dates`)
	);
	INSERT INTO tmp_dates_ (Dates)
	SELECT 
		DISTINCT DATE(PaymentDate) 
	FROM telsomespainBilling.tblPayment 
	WHERE CompanyID = p_CompanyID
		AND AccountID = p_AccountID
		AND Status = 'Approved'
		AND Recall =0
		AND PaymentType = 'Payment In'
		AND (p_StartDate = '0000-00-00' OR ( p_StartDate != '0000-00-00' AND PaymentDate >= p_StartDate) )
		AND (p_EndDate = '0000-00-00' OR ( p_EndDate != '0000-00-00' AND PaymentDate <= p_EndDate));

	INSERT IGNORE INTO tmp_dates_ (Dates)
	SELECT 
		DISTINCT date 
	FROM tblHeader
	INNER JOIN tblDimDate 
		ON tblDimDate.DateID = tblHeader.DateID
	WHERE CompanyID = p_CompanyID
		AND AccountID = p_AccountID
		AND (p_StartDate = '0000-00-00' OR ( p_StartDate != '0000-00-00' AND date >= p_StartDate) )
		AND (p_EndDate = '0000-00-00' OR ( p_EndDate != '0000-00-00' AND date <= p_EndDate));

	IF p_isExport = 0
	THEN

		SELECT 
			Dates,
			ROUND(SUM(Amount),v_Round_),
			ROUND(SUM(TotalCharges),v_Round_),
			ROUND(COALESCE(SUM(Amount),0)-COALESCE(SUM(TotalCharges),0),v_Round_),
			@PreviosBalance:= ROUND(@PreviosBalance,v_Round_)+ ROUND(COALESCE(SUM(Amount),0)-COALESCE(SUM(TotalCharges),0),v_Round_) AS Balance 
		FROM tmp_dates_
		LEFT JOIN telsomespainBilling.tblPayment 
			ON date(PaymentDate) = Dates 
			AND tblPayment.AccountID = p_AccountID
			AND Status = 'Approved'
			AND Recall =0
			AND PaymentType = 'Payment In'
		LEFT JOIN tblDimDate 
			ON date = Dates
		LEFT JOIN tblHeader 
			ON tblDimDate.DateID = tblHeader.DateID 
			AND tblHeader.AccountID = p_AccountID
		GROUP BY Dates
		ORDER BY Dates DESC 
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(DISTINCT Dates) AS totalcount,
			ROUND(COALESCE(SUM(Amount),0),v_Round_) AS TotalPayment,
			ROUND(COALESCE(SUM(TotalCharges),0),v_Round_) AS TotalCharge,
			ROUND(COALESCE(SUM(Amount),0)-COALESCE(SUM(TotalCharges),0),v_Round_) AS Total,
			ROUND(@TotalPreviosBalance,v_Round_)+ ROUND(COALESCE(SUM(Amount),0)-COALESCE(SUM(TotalCharges),0),v_Round_) AS Balance 
		FROM tmp_dates_
		LEFT JOIN telsomespainBilling.tblPayment 
			ON date(PaymentDate) = Dates 
			AND tblPayment.AccountID = p_AccountID
			AND Status = 'Approved'
			AND Recall =0
			AND PaymentType = 'Payment In'
		LEFT JOIN tblDimDate 
			ON date = Dates
		LEFT JOIN tblHeader 
			ON tblDimDate.DateID = tblHeader.DateID 
			AND tblHeader.AccountID = p_AccountID;

	END IF;

	IF p_isExport = 1
	THEN

		SELECT 
			Dates AS `Date`,
			ROUND(SUM(Amount),v_Round_) AS `Payments`,
			ROUND(SUM(TotalCharges),v_Round_) AS `Consumption`,
			ROUND(COALESCE(SUM(Amount),0)-COALESCE(SUM(TotalCharges),0),v_Round_) AS `Total`,
			@PreviosBalance:= ROUND(@PreviosBalance,v_Round_)+ ROUND(COALESCE(SUM(Amount),0)-COALESCE(SUM(TotalCharges),0),v_Round_) AS `Balance`
		FROM tmp_dates_
		LEFT JOIN telsomespainBilling.tblPayment 
			ON date(PaymentDate) = Dates 
			AND tblPayment.AccountID = p_AccountID
			AND Status = 'Approved'
			AND Recall =0
			AND PaymentType = 'Payment In'
		LEFT JOIN tblDimDate 
			ON date = Dates
		LEFT JOIN tblHeader 
			ON tblDimDate.DateID = tblHeader.DateID 
			AND tblHeader.AccountID = p_AccountID
		GROUP BY Dates
		ORDER BY Dates DESC;

	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDashboardPayableReceivable` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getDashboardPayableReceivable`(
	IN `p_CompanyID` INT,
	IN `p_CurrencyID` INT,
	IN `p_AccountID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_Unbilled` INT,
	IN `p_ListType` VARCHAR(50)

)
BEGIN
	DECLARE v_Round_ INT;
	DECLARE prev_TotalInvoiceOut  DECIMAL(18,6);
	DECLARE prev_TotalInvoiceIn DECIMAL(18,6);
	DECLARE prev_TotalPaymentOut DECIMAL(18,6);
	DECLARE prev_TotalPaymentIn DECIMAL(18,6);
	DECLARE prev_CustomerUnbill DECIMAL(18,6);
	DECLARE prev_VendrorUnbill DECIMAL(18,6);

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	DROP TEMPORARY TABLE IF EXISTS tmp_CustomerUnbilled_;
	CREATE TEMPORARY TABLE tmp_CustomerUnbilled_  (
		DateID INT,
		CustomerUnbill DOUBLE
	);
	DROP TEMPORARY TABLE IF EXISTS tmp_VendorUbilled_;
	CREATE TEMPORARY TABLE tmp_VendorUbilled_  (
		DateID INT,
		VendrorUnbill DOUBLE
	);
	
	DROP TEMPORARY TABLE IF EXISTS tmp_FinalResult_;
	CREATE TEMPORARY TABLE tmp_FinalResult_  (
		TotalInvoiceOut DOUBLE,
		TotalInvoiceIn DOUBLE,
		TotalPaymentOut DOUBLE,
		TotalPaymentIn DOUBLE,
		CustomerUnbill DOUBLE,
		VendrorUnbill DOUBLE,
		date DATE,
		TotalOutstanding DOUBLE,
		TotalPayable DOUBLE,
		TotalReceivable DOUBLE
	);
	
	DROP TEMPORARY TABLE IF EXISTS tmp_FinalResult2_;
	CREATE TEMPORARY TABLE tmp_FinalResult2_  (
		TotalInvoiceOut DOUBLE,
		TotalInvoiceIn DOUBLE,
		TotalPaymentOut DOUBLE,
		TotalPaymentIn DOUBLE,
		CustomerUnbill DOUBLE,
		VendrorUnbill DOUBLE,
		date DATE,
		TotalOutstanding DOUBLE,
		TotalPayable DOUBLE,
		TotalReceivable DOUBLE
	);
	
	IF p_Unbilled = 1
	THEN
		DROP TEMPORARY TABLE IF EXISTS tmp_Account_;
		CREATE TEMPORARY TABLE tmp_Account_  (
			RowID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
			AccountID INT,
			LastInvoiceDate DATE
		);
		DROP TEMPORARY TABLE IF EXISTS tmp_Account2_;
		CREATE TEMPORARY TABLE tmp_Account2_  (
			RowID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
			AccountID INT,
			LastInvoiceDate DATE
		);

		INSERT INTO tmp_Account_ (AccountID)
		SELECT DISTINCT tblHeader.AccountID  FROM tblHeader INNER JOIN telsomespainRM.tblAccount ON tblAccount.AccountID = tblHeader.AccountID WHERE tblHeader.CompanyID = 1;

		UPDATE tmp_Account_ SET LastInvoiceDate = fngetLastInvoiceDate(AccountID);

		INSERT INTO tmp_Account2_ (AccountID)
		SELECT DISTINCT tblHeaderV.VAccountID  FROM tblHeaderV INNER JOIN telsomespainRM.tblAccount ON tblAccount.AccountID = tblHeaderV.VAccountID WHERE tblHeaderV.CompanyID = p_CompanyID;

		UPDATE tmp_Account2_ SET LastInvoiceDate = fngetLastVendorInvoiceDate(AccountID);

		SELECT 
			SUM(h.TotalCharges)
		INTO
			prev_CustomerUnbill
		FROM tmp_Account_ a
		INNER JOIN tblDimDate dd
			ON dd.date >= a.LastInvoiceDate
		INNER JOIN tblHeader h
			ON h.AccountID = a.AccountID
			AND h.DateID = dd.DateID
		WHERE dd.date < p_StartDate;
		
		SELECT 
			SUM(h.TotalCharges)
		INTO 
			prev_VendrorUnbill
		FROM tmp_Account2_ a
		INNER JOIN tblDimDate dd
			ON dd.date >= a.LastInvoiceDate
		INNER JOIN tblHeaderV h
			ON h.VAccountID = a.AccountID
			AND h.DateID = dd.DateID
		WHERE dd.date < p_StartDate;

		INSERT INTO tmp_CustomerUnbilled_(DateID,CustomerUnbill)
		SELECT 
			dd.DateID,
			SUM(h.TotalCharges)
		FROM tmp_Account_ a
		INNER JOIN tblDimDate dd
			ON dd.date >= a.LastInvoiceDate
		INNER JOIN tblHeader h
			ON h.AccountID = a.AccountID
			AND h.DateID = dd.DateID
		WHERE dd.date BETWEEN p_StartDate AND p_EndDate
		GROUP BY dd.date;

		INSERT INTO tmp_VendorUbilled_ (DateID,VendrorUnbill)
		SELECT 
			dd.DateID,
			SUM(h.TotalCharges)
		FROM tmp_Account2_ a
		INNER JOIN tblDimDate dd
			ON dd.date >= a.LastInvoiceDate
		INNER JOIN tblHeaderV h
			ON h.VAccountID = a.AccountID
			AND h.DateID = dd.DateID
		WHERE dd.date BETWEEN p_StartDate AND p_EndDate
		GROUP BY dd.date;
	
	END IF;

	SELECT 
		SUM(IF(InvoiceType=1,GrandTotal,0)),
		SUM(IF(InvoiceType=2,GrandTotal,0)) 
	INTO 
		prev_TotalInvoiceOut,
		prev_TotalInvoiceIn
	FROM telsomespainBilling.tblInvoice 
	WHERE 
		CompanyID = p_CompanyID
		AND CurrencyID = p_CurrencyID
		AND ( (InvoiceType = 2) OR ( InvoiceType = 1 AND InvoiceStatus NOT IN ( 'cancel' , 'draft') )  )
		AND (p_AccountID = 0 or AccountID = p_AccountID)
	AND tblInvoice.IssueDate < p_StartDate ;

	SELECT 
		SUM(IF(PaymentType='Payment In',p.Amount,0)),
		SUM(IF(PaymentType='Payment Out',p.Amount,0)) 
	INTO 
		prev_TotalPaymentIn,
		prev_TotalPaymentOut
	FROM telsomespainBilling.tblPayment p 
	INNER JOIN telsomespainRM.tblAccount ac 
		ON ac.AccountID = p.AccountID
	WHERE 
		p.CompanyID = p_CompanyID
		AND ac.CurrencyId = p_CurrencyID
		AND p.Status = 'Approved'
		AND p.Recall=0
		AND (p_AccountID = 0 or p.AccountID = p_AccountID)
	AND p.PaymentDate < p_StartDate;
	
	SET @prev_TotalInvoiceOut := IFNULL(prev_TotalInvoiceOut,0) ;
	SET @prev_TotalInvoiceIn := IFNULL(prev_TotalInvoiceIn,0) ;
	SET @prev_TotalPaymentOut := IFNULL(prev_TotalPaymentOut,0) ;
	SET @prev_TotalPaymentIn := IFNULL(prev_TotalPaymentIn,0) ;
	SET @prev_CustomerUnbill := IFNULL(prev_CustomerUnbill,0) ;
	SET @prev_VendrorUnbill := IFNULL(prev_VendrorUnbill,0) ;
	
	INSERT INTO tmp_FinalResult_(TotalInvoiceOut,TotalInvoiceIn,TotalPaymentOut,TotalPaymentIn,CustomerUnbill,VendrorUnbill,date,TotalOutstanding,TotalReceivable,TotalPayable)
	SELECT 
		@prev_TotalInvoiceOut := @prev_TotalInvoiceOut +    IFNULL(TotalInvoiceOut,0) AS TotalInvoiceOut ,
		@prev_TotalInvoiceIn := @prev_TotalInvoiceIn +   IFNULL(TotalInvoiceIn,0) AS TotalInvoiceIn,
		@prev_TotalPaymentOut := @prev_TotalPaymentOut +   IFNULL(TotalPaymentOut,0) AS TotalPaymentOut,
		@prev_TotalPaymentIn := @prev_TotalPaymentIn +   IFNULL(TotalPaymentIn,0) AS TotalPaymentIn,
		@prev_CustomerUnbill := @prev_CustomerUnbill +   IFNULL(CustomerUnbill,0) AS CustomerUnbill,
		@prev_VendrorUnbill := @prev_VendrorUnbill +   IFNULL(VendrorUnbill,0) AS VendrorUnbill,
		date,
		ROUND( ( @prev_TotalInvoiceOut - @prev_TotalPaymentIn ) - ( @prev_TotalInvoiceIn - @prev_TotalPaymentOut ) + ( @prev_CustomerUnbill - @prev_VendrorUnbill ) , v_Round_ ) AS TotalOutstanding,
		ROUND( ( @prev_TotalInvoiceOut - @prev_TotalPaymentIn + @prev_CustomerUnbill ), v_Round_ ) AS TotalReceivable,
		ROUND( ( @prev_TotalInvoiceIn - @prev_TotalPaymentOut + @prev_VendrorUnbill), v_Round_ ) AS TotalPayable
	FROM(
		SELECT 
			dd.date,
			TotalPaymentIn,
			TotalPaymentOut,
			TotalInvoiceOut,
			TotalInvoiceIn,
			CustomerUnbill,
			VendrorUnbill
		FROM tblDimDate dd 
		LEFT JOIN(
			SELECT 
				SUM(IF(InvoiceType=1,GrandTotal,0)) AS TotalInvoiceOut,
				SUM(IF(InvoiceType=2,GrandTotal,0)) AS TotalInvoiceIn,
				DATE(tblInvoice.IssueDate) AS  IssueDate 
			FROM telsomespainBilling.tblInvoice 
			WHERE 
				CompanyID = p_CompanyID
				AND CurrencyID = p_CurrencyID
				AND ( (InvoiceType = 2) OR ( InvoiceType = 1 AND InvoiceStatus NOT IN ( 'cancel' , 'draft') )  )
				AND (p_AccountID = 0 or AccountID = p_AccountID)
				AND IssueDate BETWEEN p_StartDate AND p_EndDate
			GROUP BY DATE(tblInvoice.IssueDate)
			HAVING (TotalInvoiceOut <> 0 OR TotalInvoiceIn <> 0)
		) TBL ON IssueDate = dd.date
		LEFT JOIN (
			SELECT
				SUM(IF(PaymentType='Payment In',p.Amount,0)) AS TotalPaymentIn ,
				SUM(IF(PaymentType='Payment Out',p.Amount,0)) AS TotalPaymentOut,
				DATE(p.PaymentDate) AS PaymentDate
			FROM telsomespainBilling.tblPayment p
			INNER JOIN telsomespainRM.tblAccount ac
				ON ac.AccountID = p.AccountID
			WHERE
				p.CompanyID = p_CompanyID
				AND ac.CurrencyId = p_CurrencyID
				AND p.Status = 'Approved'
				AND p.Recall=0
				AND (p_AccountID = 0 or p.AccountID = p_AccountID)
				AND PaymentDate BETWEEN p_StartDate AND p_EndDate
			GROUP BY DATE(p.PaymentDate)
			HAVING (TotalPaymentIn <> 0 OR TotalPaymentOut <> 0)
		)TBL2 ON PaymentDate = dd.date
		LEFT JOIN tmp_CustomerUnbilled_ cu 
			ON cu.DateID = dd.DateID
		LEFT JOIN tmp_VendorUbilled_ vu
			ON vu.DateID = dd.DateID
		WHERE dd.date BETWEEN p_StartDate AND p_EndDate
		AND ( PaymentDate IS NOT NULL OR IssueDate IS NOT NULL OR cu.DateID IS NOT NULL OR vu.DateID IS NOT NULL)
		ORDER BY dd.date
	)tbl;
	
	INSERT INTO tmp_FinalResult2_
	SELECT * FROM tmp_FinalResult_;

	IF p_ListType = 'Daily'
	THEN

		SELECT
			TotalOutstanding,
			TotalPayable,
			TotalReceivable,
			date AS Date
		FROM  tmp_FinalResult_;

	END IF;

	IF p_ListType = 'Weekly'
	THEN

		SELECT 
			TotalOutstanding,
			TotalPayable,
			TotalReceivable,
			CONCAT( YEAR(date),' - ',WEEK(date,1)) AS Date
		FROM	tmp_FinalResult_ t1
		INNER JOIN (
			SELECT 
				MAX(date) as finaldate
			FROM tmp_FinalResult2_
			GROUP BY
			YEAR(date),WEEK(date,1)
		)TBL ON TBL.finaldate = t1.date;

	END IF;
	
	IF p_ListType = 'Monthly'
	THEN

		SELECT 
			TotalOutstanding,
			TotalPayable,
			TotalReceivable,
			CONCAT( YEAR(date),' - ',MONTHNAME(date)) AS Date
		FROM	tmp_FinalResult_ t1
		INNER JOIN (
			SELECT 
				MAX(date) as finaldate
			FROM tmp_FinalResult2_
			GROUP BY
			YEAR(date),MONTH(date)
		)TBL ON TBL.finaldate = t1.date;

	END IF;
	

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDashboardProfitLoss` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getDashboardProfitLoss`(
	IN `p_CompanyID` INT,
	IN `p_CurrencyID` INT,
	IN `p_AccountID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_ListType` VARCHAR(50)

)
BEGIN
	DECLARE v_Round_ INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	DROP TEMPORARY TABLE IF EXISTS tmp_Customerbilled_;
	CREATE TEMPORARY TABLE tmp_Customerbilled_  (
		DateID INT,
		Customerbill DOUBLE
	);
	DROP TEMPORARY TABLE IF EXISTS tmp_Vendorbilled_;
	CREATE TEMPORARY TABLE tmp_Vendorbilled_  (
		DateID INT,
		Vendrorbill DOUBLE
	);
	
	DROP TEMPORARY TABLE IF EXISTS tmp_FinalResult_;
	CREATE TEMPORARY TABLE tmp_FinalResult_  (
		Customerbill DOUBLE,
		Vendrorbill DOUBLE,
		date DATE
	);

	INSERT INTO tmp_Customerbilled_(DateID,Customerbill)
	SELECT 
		dd.DateID,
		SUM(h.TotalCharges)
	FROM tblDimDate dd
	INNER JOIN tblHeader h
		ON h.DateID = dd.DateID
	WHERE dd.date BETWEEN p_StartDate AND p_EndDate
	AND (p_AccountID = 0 or AccountID = p_AccountID)
	GROUP BY dd.date;

	INSERT INTO tmp_Vendorbilled_ (DateID,Vendrorbill)
	SELECT 
		dd.DateID,
		SUM(h.TotalCharges)
	FROM tblDimDate dd
	INNER JOIN tblHeaderV h
		ON h.DateID = dd.DateID
	WHERE dd.date BETWEEN p_StartDate AND p_EndDate
	AND (p_AccountID = 0 or VAccountID = p_AccountID)
	GROUP BY dd.date;

	INSERT INTO tmp_FinalResult_(Customerbill,Vendrorbill,date)
	SELECT 
		IFNULL(Customerbill,0) AS Customerbill,
		IFNULL(Vendrorbill,0) AS Vendrorbill,
		date
	FROM(
		SELECT 
			dd.date,
			Customerbill,
			Vendrorbill
		FROM tblDimDate dd 
		LEFT JOIN tmp_Customerbilled_ cu 
			ON cu.DateID = dd.DateID
		LEFT JOIN tmp_Vendorbilled_ vu
			ON vu.DateID = dd.DateID
		WHERE dd.date BETWEEN p_StartDate AND p_EndDate
		AND (cu.DateID IS NOT NULL OR vu.DateID IS NOT NULL)
		ORDER BY dd.date
	)tbl;
	
	IF p_ListType = 'Daily'
	THEN

		SELECT
			ROUND(Customerbill - Vendrorbill,v_Round_) AS PL,
			date AS Date
		FROM  tmp_FinalResult_
		ORDER BY date;

	END IF;

	IF p_ListType = 'Weekly'
	THEN

		SELECT 
			ROUND(SUM(Customerbill) - SUM(Vendrorbill),v_Round_) AS PL,
			CONCAT( YEAR(MAX(date)),' - ',WEEK(MAX(date))) AS Date
		FROM	tmp_FinalResult_
		GROUP BY 
			YEAR(date),
			WEEK(date)
		ORDER BY
			YEAR(date),
			WEEK(date);

	END IF;
	
	IF p_ListType = 'Monthly'
	THEN

		SELECT 
			ROUND(SUM(Customerbill) - SUM(Vendrorbill),v_Round_) AS PL,
			CONCAT( YEAR(MAX(date)),' - ',MONTHNAME(MAX(date))) AS Date
		FROM	tmp_FinalResult_
		GROUP BY
			YEAR(date)
			,MONTH(date)
		ORDER BY 
			YEAR(date)
			,MONTH(date);

	END IF;
	

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDescReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getDescReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_ResellerID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_CDRType` VARCHAR(50),
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ INT;
	DECLARE v_OffSet_ INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	CALL fngetDefaultCodes(p_CompanyID);

	CALL fnUsageSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_CDRType,p_UserID,p_isAdmin,2,p_ResellerID,p_tag);

	/* grid display*/
	IF p_isExport = 0
	THEN

		/* Description by call count */	
			
		SELECT IFNULL(Description,'Other') AS Description ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) AS TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) AS TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) AS ACD , IF(SUM(NoOfCalls)>0,ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_),0) AS ASR,
			FORMAT(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			FORMAT( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		LEFT JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
		GROUP BY c.Description
		ORDER BY
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
		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) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
		END ASC,
		CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
		END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin FROM(
			SELECT IFNULL(Description,'Other') AS Description ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) AS TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) AS TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) AS ACD , IF(SUM(NoOfCalls)>0,ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_),0) AS ASR,
				ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
				ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
			FROM tmp_tblUsageSummary_ us
			LEFT JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
			GROUP BY c.Description
		)tbl;

	END IF;

	/* export data*/
	IF p_isExport = 1
	THEN

		SELECT
			SQL_CALC_FOUND_ROWS IFNULL(Description,'Other') AS Description,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)` ,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as `Margin (%)`
		FROM tmp_tblUsageSummary_ us
		LEFT JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
		GROUP BY Description;

	END IF;

	/* chart display*/
	IF p_isExport = 2
	THEN

		/* top 10 Description by call count */
		
		SELECT Description AS ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) AS ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) AS ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
		GROUP BY Description HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;

		/* top 10 Description by call cost */
		
		SELECT Description AS ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) AS TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) AS ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) AS ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
		GROUP BY Description HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;

		/* top 10 Description by call minutes */
		
		SELECT Description AS ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) AS TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) AS ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) AS ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
		GROUP BY Description HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDestinationReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getDestinationReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_ResellerID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_CDRType` VARCHAR(50),
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ int;
	DECLARE v_OffSet_ int;
		
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnGetCountry();
		 
	
	CALL fnUsageSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_CDRType,p_UserID,p_isAdmin,2,p_ResellerID,p_tag);

	
	/* grid display*/
	IF p_isExport = 0
	THEN
	
	/* country by call count */	
		
	SELECT IFNULL(Country,'Other') as Country ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , IF(SUM(NoOfCalls)>0,ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_),0) as ASR,
		FORMAT(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
		FORMAT( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
	FROM tmp_tblUsageSummary_ us
	LEFT JOIN temptblCountry c ON c.CountryID = us.CountryID
	WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
	GROUP BY c.Country   
	ORDER BY
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CountryDESC') THEN Country
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CountryASC') THEN Country
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN IF(SUM(NoOfCalls)>0,(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN IF(SUM(NoOfCalls)>0,(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
	END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;
	

	SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin FROM(
		SELECT IFNULL(Country,'Other') as Country ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) as TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , IF(SUM(NoOfCalls)>0,ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_),0) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		LEFT JOIN temptblCountry c ON c.CountryID = us.CountryID
		WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
		GROUP BY c.Country
	)tbl;

	
	END IF;
	
	/* export data*/
	IF p_isExport = 1
	THEN
		SELECT
			SQL_CALC_FOUND_ROWS IFNULL(Country,'Other') as  Country,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)` ,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as `Margin (%)`
		FROM tmp_tblUsageSummary_ us
		LEFT JOIN temptblCountry c ON c.CountryID = us.CountryID
		WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
		GROUP BY Country;
	END IF;
	
	
	/* chart display*/
	IF p_isExport = 2
	THEN
	
		/* top 10 country by call count */	
			
		SELECT Country as ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		INNER JOIN temptblCountry c ON c.CountryID = us.CountryID
		WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
		GROUP BY Country HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;
		
		/* top 10 country by call cost */	
			
		SELECT Country as ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		INNER JOIN temptblCountry c ON c.CountryID = us.CountryID
		WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
		GROUP BY Country HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;
		
		/* top 10 country by call minutes */	
			
		SELECT Country as ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		INNER JOIN temptblCountry c ON c.CountryID = us.CountryID
		WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
		GROUP BY Country HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;
	
	END IF;
	
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDistinctList` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getDistinctList`(
	IN `p_CompanyID` INT,
	IN `p_ColName` VARCHAR(50),
	IN `p_Search` VARCHAR(50),
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT
)
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;

	IF p_ColName = 'CompanyGatewayID'
	THEN

		SELECT 
			CompanyGatewayID,
			Title 
		FROM telsomespainRM.tblCompanyGateway 
		WHERE CompanyID = p_CompanyID
		AND Title LIKE CONCAT(p_Search,'%');
		

	END IF;
	
	IF p_ColName = 'CountryID'
	THEN

		SELECT 
			CountryID,
			Country 
		FROM telsomespainRM.tblCountry
		WHERE Country LIKE CONCAT(p_Search,'%');
		

	END IF;
	
	IF p_ColName = 'AccountID' OR p_ColName = 'VAccountID'
	THEN

		SELECT 
			AccountID,
			AccountName 
		FROM telsomespainRM.tblAccount
		WHERE CompanyID = p_CompanyID
		AND AccountType = 1
		AND AccountName LIKE CONCAT(p_Search,'%');
		
		

	END IF;
	
	IF p_ColName = 'ServiceID'
	THEN

		SELECT 
			ServiceID,
			ServiceName 
		FROM telsomespainRM.tblService 
		WHERE CompanyID = p_CompanyID
		AND ServiceName LIKE CONCAT(p_Search,'%');
		

	END IF;
	
	
	IF p_ColName = 'Trunk'
	THEN

		SELECT 
			DISTINCT
			Trunk as Trunk1,
			Trunk
		FROM tblRTrunk
		WHERE CompanyID = p_CompanyID
		AND Trunk LIKE CONCAT(p_Search,'%');
		

	END IF;
	
	IF p_ColName = 'CurrencyID'
	THEN

		SELECT 
			DISTINCT
			CurrencyId as CurrencyID,
			Code
		FROM telsomespainRM.tblCurrency
		WHERE CompanyID = p_CompanyID
		AND Code LIKE CONCAT(p_Search,'%');
		

	END IF;
	
	IF p_ColName = 'TaxRateID'
	THEN

		SELECT 
			DISTINCT
			TaxRateId as CurrencyID,
			Title
		FROM telsomespainRM.tblTaxRate
		WHERE CompanyID = p_CompanyID
		AND Title LIKE CONCAT(p_Search,'%');
		

	END IF;
	
	IF p_ColName = 'ProductID'
	THEN

		SELECT 
			DISTINCT
			ProductID as ProductID,
			Name
		FROM telsomespainBilling.tblProduct
		WHERE CompanyID = p_CompanyID
		AND Name LIKE CONCAT(p_Search,'%');
		

	END IF;
	
	IF p_ColName = 'Code'
	THEN

		SELECT 
			DISTINCT
			Code as ProductID,
			Code
		FROM telsomespainBilling.tblProduct
		WHERE CompanyID = p_CompanyID
		AND Code LIKE CONCAT(p_Search,'%');
		

	END IF;
	
	IF p_ColName = 'AreaPrefix' OR p_ColName = 'area_prefix'
	THEN

		SELECT 
			DISTINCT
			Code as AreaPrefix1,
			Code
		FROM tblRRate
		WHERE CompanyID = p_CompanyID
		AND Code LIKE CONCAT(p_Search,'%');
		

	END IF;
	
	IF p_ColName = 'DestinationBreak'
	THEN

		SELECT 
			DISTINCT
			Description as Name,
			Description
		FROM telsomespainRM.tblRate
		INNER JOIN telsomespainRM.tblCodeDeck
			ON tblCodeDeck.CodeDeckId = tblRate.CodeDeckId
		WHERE tblCodeDeck.CompanyID = p_CompanyID
		AND tblCodeDeck.DefaultCodedeck = 1
		AND tblRate.Description LIKE CONCAT(p_Search,'%');
		

	END IF;
	
	IF p_ColName = 'GatewayAccountPKID' OR p_ColName = 'GatewayVAccountPKID'
	THEN

		SELECT
			DISTINCT 
			CASE WHEN AccountIP <> ''
			THEN 
				AccountIP
			ELSE
				AccountCLI
			END as AccountIP,
			CASE WHEN AccountIP <> ''
			THEN 
				AccountIP
			ELSE
				AccountCLI
			END as AccountIP1 
		FROM telsomespainBilling.tblGatewayAccount 
		WHERE CompanyID = p_CompanyID
		AND (AccountIP <> '' OR AccountCLI <> '')
		AND ( AccountIP LIKE CONCAT(p_Search,'%') OR AccountCLI LIKE CONCAT(p_Search,'%'));
		

	END IF;
	
	IF p_ColName = 'week_of_year'
	THEN

		SELECT 
			DISTINCT
			tblDimDate.week_of_year as week_of_year1,
			tblDimDate.week_of_year
		FROM tblHeader
		INNER JOIN tblDimDate
			ON tblDimDate.DateID = tblHeader.DateID
		WHERE CompanyID = p_CompanyID
		ORDER BY tblDimDate.week_of_year;
		

	END IF;
	
	IF p_ColName = 'month'
	THEN

		SELECT 
			DISTINCT
			tblDimDate.month_of_year as month1,
			tblDimDate.month
		FROM tblHeader
		INNER JOIN tblDimDate
			ON tblDimDate.DateID = tblHeader.DateID
		WHERE CompanyID = p_CompanyID
		ORDER BY tblDimDate.month_of_year;
		

	END IF;
	
	IF p_ColName = 'quarter_of_year'
	THEN

		SELECT 
			DISTINCT
			tblDimDate.quarter_of_year as month1,
			tblDimDate.quarter_of_year
		FROM tblHeader
		INNER JOIN tblDimDate
			ON tblDimDate.DateID = tblHeader.DateID
		WHERE CompanyID = p_CompanyID
		ORDER BY tblDimDate.quarter_of_year;
		

	END IF;
	
	IF p_ColName = 'year'
	THEN

		SELECT 
			DISTINCT
			tblDimDate.year as month1,
			tblDimDate.year
		FROM tblHeader
		INNER JOIN tblDimDate
			ON tblDimDate.DateID = tblHeader.DateID
		WHERE CompanyID = p_CompanyID
		ORDER BY tblDimDate.year;
		

	END IF;
	
	IF p_ColName = 'hour'
	THEN

		SELECT 
			DISTINCT
			tblDimTime.hour as hour1,
			tblDimTime.hour
		FROM tblDimTime
		ORDER BY tblDimTime.hour;
		

	END IF;
	
	IF p_ColName = 'minute'
	THEN

		SELECT 
			DISTINCT
			tblDimTime.minute as hour1,
			tblDimTime.minute
		FROM tblDimTime
		ORDER BY tblDimTime.minute;
		

	END IF;
	
	IF p_ColName = 'pincode'
	THEN

		SELECT 
			DISTINCT
			pincode as hour1,
			pincode
		FROM telsomespainCDR.tblUsageDetails
		INNER JOIN telsomespainCDR.tblUsageHeader 
			ON tblUsageDetails.UsageHeaderID = tblUsageHeader.UsageHeaderID
		WHERE CompanyID = p_CompanyID
		AND pincode LIKE CONCAT(p_Search,'%')
		ORDER BY tblUsageDetails.pincode;
		

	END IF;
	
	IF p_ColName = 'extension'
	THEN

		SELECT 
			DISTINCT
			extension as hour1,
			extension
		FROM telsomespainCDR.tblUsageDetails
		INNER JOIN telsomespainCDR.tblUsageHeader 
			ON tblUsageDetails.UsageHeaderID = tblUsageHeader.UsageHeaderID
		WHERE CompanyID = p_CompanyID
		AND extension LIKE CONCAT(p_Search,'%')
		ORDER BY tblUsageDetails.extension;
		

	END IF;
	
	IF p_ColName = 'cli'
	THEN

		SELECT 
			DISTINCT
			cli as hour1,
			cli
		FROM telsomespainCDR.tblUsageDetails
		INNER JOIN telsomespainCDR.tblUsageHeader 
			ON tblUsageDetails.UsageHeaderID = tblUsageHeader.UsageHeaderID
		WHERE CompanyID = p_CompanyID
		AND cli LIKE CONCAT(p_Search,'%')
		ORDER BY tblUsageDetails.cli;
		

	END IF;
	
	IF p_ColName = 'cld'
	THEN

		SELECT 
			DISTINCT
			cld as hour1,
			cld
		FROM telsomespainCDR.tblUsageDetails
		INNER JOIN telsomespainCDR.tblUsageHeader 
			ON tblUsageDetails.UsageHeaderID = tblUsageHeader.UsageHeaderID
		WHERE CompanyID = p_CompanyID
		AND cld LIKE CONCAT(p_Search,'%')
		ORDER BY tblUsageDetails.cld;
		

	END IF;
	
	IF p_ColName = 'remote_ip'
	THEN

		SELECT 
			DISTINCT
			remote_ip as hour1,
			remote_ip
		FROM telsomespainCDR.tblUsageDetails
		INNER JOIN telsomespainCDR.tblUsageHeader 
			ON tblUsageDetails.UsageHeaderID = tblUsageHeader.UsageHeaderID
		WHERE CompanyID = p_CompanyID
		AND remote_ip LIKE CONCAT(p_Search,'%')
		ORDER BY tblUsageDetails.remote_ip;
		

	END IF;
	
	IF p_ColName = 'is_inbound'
	THEN

		SELECT 
			DISTINCT
			is_inbound as hour1,
			is_inbound
		FROM telsomespainCDR.tblUsageDetails
		INNER JOIN telsomespainCDR.tblUsageHeader 
			ON tblUsageDetails.UsageHeaderID = tblUsageHeader.UsageHeaderID
		WHERE CompanyID = p_CompanyID
		AND is_inbound LIKE CONCAT(p_Search,'%')
		ORDER BY tblUsageDetails.is_inbound;
		

	END IF;
	
	IF p_ColName = 'disposition'
	THEN

		SELECT 
			DISTINCT
			disposition as hour1,
			disposition
		FROM telsomespainCDR.tblUsageDetails
		INNER JOIN telsomespainCDR.tblUsageHeader 
			ON tblUsageDetails.UsageHeaderID = tblUsageHeader.UsageHeaderID
		WHERE CompanyID = p_CompanyID
		AND disposition LIKE CONCAT(p_Search,'%')
		ORDER BY tblUsageDetails.disposition;
		

	END IF;
	
	IF p_ColName = 'userfield'
	THEN

		SELECT 
			DISTINCT
			userfield as hour1,
			userfield
		FROM telsomespainCDR.tblUsageDetails
		INNER JOIN telsomespainCDR.tblUsageHeader 
			ON tblUsageDetails.UsageHeaderID = tblUsageHeader.UsageHeaderID
		WHERE CompanyID = p_CompanyID
		AND userfield LIKE CONCAT(p_Search,'%')
		ORDER BY tblUsageDetails.userfield;
		

	END IF;
	 

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getGatewayReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getGatewayReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_ResellerID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_CDRType` VARCHAR(50),
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ int;
	DECLARE v_OffSet_ int;
		
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnUsageSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_CDRType,p_UserID,p_isAdmin,2,p_ResellerID,p_tag);

	
	/* grid display*/
	IF p_isExport = 0
	THEN
	
	/* CompanyGatewayID by call count */	
		
	SELECT fnGetCompanyGatewayName(CompanyGatewayID) ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
		FORMAT(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
		FORMAT( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage,
		CompanyGatewayID
	FROM tmp_tblUsageSummary_ us
	GROUP BY CompanyGatewayID   
	ORDER BY
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'GatewayDESC') THEN fnGetCompanyGatewayName(CompanyGatewayID)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'GatewayASC') THEN fnGetCompanyGatewayName(CompanyGatewayID)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
	END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;
	
	SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin FROM (
		SELECT fnGetCompanyGatewayName(CompanyGatewayID) ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) as TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		GROUP BY CompanyGatewayID
	)tbl;

	
	END IF;
	
	/* export data*/
	IF p_isExport = 1
	THEN
		SELECT
			fnGetCompanyGatewayName(CompanyGatewayID)  as Name,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)`,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as `Margin (%)`
		FROM tmp_tblUsageSummary_ us
		GROUP BY CompanyGatewayID;
	END IF;
	
	
	/* chart display*/
	IF p_isExport = 2
	THEN
	
		/* top 10 CompanyGatewayID by call count */	
			
		SELECT fnGetCompanyGatewayName(CompanyGatewayID) as ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		WHERE us.CompanyGatewayID != 'Other'
		GROUP BY CompanyGatewayID HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;
		
		/* top 10 CompanyGatewayID by call cost */	
			
		SELECT fnGetCompanyGatewayName(CompanyGatewayID) as ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		WHERE us.CompanyGatewayID != 'Other'
		GROUP BY CompanyGatewayID HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;
		
		/* top 10 CompanyGatewayID by call minutes */	
			
		SELECT fnGetCompanyGatewayName(CompanyGatewayID) as ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		WHERE us.CompanyGatewayID != 'Other'
		GROUP BY CompanyGatewayID HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;
	
	END IF;
	
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getHourlyReport` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getHourlyReport`(
	IN `p_CompanyID` INT,
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_AccountID` INT,
	IN `p_ResellerID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_CDRType` VARCHAR(50)



)
BEGIN
	
	DECLARE v_Round_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	CALL fnUsageSummary(p_CompanyID,0,p_AccountID,0,p_StartDate,p_EndDate,'','',0,p_CDRType,p_UserID,p_isAdmin,2,p_ResellerID,'');
	
	/* total cost */
	SELECT ROUND(COALESCE(SUM(TotalCharges),0),v_Round_) as TotalCost FROM tmp_tblUsageSummary_;
	
	/* cost per hour*/
	SELECT dt.hour as HOUR ,ROUND(COALESCE(SUM(TotalCharges),0),v_Round_) as TotalCost FROM tmp_tblUsageSummary_ us INNER JOIN tblDimTime dt on us.TimeID =  dt.TimeID GROUP BY dt.hour;
	
	/* total duration or minutes*/
	SELECT ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes FROM tmp_tblUsageSummary_;
	
	/* minutes pre hour*/
	SELECT dt.hour as HOUR ,ROUND(COALESCE(SUM(TotalBilledDuration),0) / 60,0) as TotalMinutes FROM tmp_tblUsageSummary_ us INNER JOIN tblDimTime dt on us.TimeID =  dt.TimeID GROUP BY dt.hour;
	
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getPrefixReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getPrefixReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_ResellerID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_CDRType` VARCHAR(50),
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ int;
	DECLARE v_OffSet_ int;
		
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnUsageSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_CDRType,p_UserID,p_isAdmin,2,p_ResellerID,p_tag);

	
	/* grid display*/
	IF p_isExport = 0
	THEN
	
	/* AreaPrefix by call count */	
		
	SELECT AreaPrefix ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
		FORMAT(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
		FORMAT( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
	FROM tmp_tblUsageSummary_ us
	GROUP BY AreaPrefix   
	ORDER BY
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AreaPrefixDESC') THEN AreaPrefix
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AreaPrefixASC') THEN AreaPrefix
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
	END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;
	
	SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin FROM (
		SELECT AreaPrefix ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) as TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		GROUP BY AreaPrefix
	)tbl;

	
	END IF;
	
	/* export data*/
	IF p_isExport = 1
	THEN
		SELECT
			AreaPrefix,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)` ,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as `Margin (%)`
		FROM tmp_tblUsageSummary_ us
		GROUP BY AreaPrefix;
	END IF;
	
	
	/* chart display*/
	IF p_isExport = 2
	THEN
	
		/* top 10 AreaPrefix by call count */	
			
		SELECT AreaPrefix as ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		WHERE us.AreaPrefix != 'Other'
		GROUP BY AreaPrefix HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;
		
		/* top 10 AreaPrefix by call cost */	
			
		SELECT AreaPrefix as ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		WHERE us.AreaPrefix != 'Other'
		GROUP BY AreaPrefix HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;
		
		/* top 10 AreaPrefix by call minutes */	
			
		SELECT AreaPrefix as ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		WHERE us.AreaPrefix != 'Other'
		GROUP BY AreaPrefix HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;
	
	END IF;
	
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getReportByTime` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getReportByTime`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_ResellerID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_CDRType` VARCHAR(50),
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_ReportType` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ INT;
	DECLARE V_Detail INT;

	SET V_Detail = 2;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	CALL fnUsageSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_CDRType,p_UserID,p_isAdmin,V_Detail,p_ResellerID,p_tag);

	/* hourly report */
	IF p_ReportType =1
	THEN
	
		SELECT 
			CONCAT(dt.hour,' Hour') as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimTime dt on dt.TimeID = us.TimeID
		GROUP BY  us.DateID,dt.hour;

	END IF;

	/* daily report */
	IF p_ReportType =2
	THEN

		SELECT 
			dd.date as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		GROUP BY  us.DateID;
	END IF;

	/* weekly report */
	IF p_ReportType =3
	THEN

		SELECT 
			ANY_VALUE(dd.week_year_name) as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		GROUP BY  dd.year,dd.week_of_year
		ORDER BY dd.year,dd.week_of_year;

	END IF;

	/* monthly report */
	IF p_ReportType =4
	THEN

		SELECT 
			ANY_VALUE(dd.month_year_name) as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		GROUP BY  dd.year,dd.month_of_year
		ORDER BY dd.year,dd.month_of_year;

	END IF;

	/* queterly report */
	IF p_ReportType =5
	THEN

		SELECT 
			CONCAT('Q-',ANY_VALUE(dd.quarter_year_name)) as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		GROUP BY  dd.year,dd.quarter_of_year
		ORDER BY dd.year,dd.quarter_of_year;

	END IF;

	/* yearly report */
	IF p_ReportType =6
	THEN

		SELECT 
			dd.year as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageSummary_ us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		GROUP BY  dd.year;

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getReportHistory` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getReportHistory`(
	IN `p_CompanyID` INT,
	IN `p_ReportScheduleID` INT,
	IN `p_ReportID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_SearchText` 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;

	IF p_isExport = 0
	THEN
		SELECT
			tblReportSchedule.Name,
			tblReportScheduleLog.send_at,
			AccountEmailLog.Subject,
			AccountEmailLog.Message,
			AccountEmailLog.AttachmentPaths,
			AccountEmailLog.AccountEmailLogID
		FROM tblReportSchedule
		INNER JOIN tblReportScheduleLog 
			ON tblReportSchedule.ReportScheduleID = tblReportScheduleLog.ReportScheduleID
		INNER JOIN telsomespainRM.AccountEmailLog 
			ON tblReportScheduleLog.AccountEmailLogID = AccountEmailLog.AccountEmailLogID
		WHERE tblReportSchedule.CompanyID = p_CompanyID
			AND (p_ReportScheduleID = 0 OR tblReportSchedule.ReportScheduleID = p_ReportScheduleID)
			AND (p_ReportID = 0 OR tblReportSchedule.ReportID = p_ReportID)
			AND tblReportScheduleLog.send_at BETWEEN p_StartDate and p_EndDate
			AND (p_SearchText='' OR tblReportSchedule.Name LIKE CONCAT('%',p_SearchText,'%'))
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MessageDESC') THEN tblReportSchedule.Name
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MessageASC') THEN tblReportSchedule.Name
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN tblReportScheduleLog.send_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN tblReportScheduleLog.send_at
			END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(tblReportScheduleLog.ReportScheduleLogID) as totalcount
		FROM tblReportSchedule
		INNER JOIN tblReportScheduleLog 
			ON tblReportSchedule.ReportScheduleID = tblReportScheduleLog.ReportScheduleID
		WHERE CompanyID = p_CompanyID
			AND (p_ReportScheduleID = 0 OR tblReportSchedule.ReportScheduleID = p_ReportScheduleID)
			AND (p_ReportID = 0 OR tblReportSchedule.ReportID = p_ReportID)
			AND tblReportScheduleLog.send_at BETWEEN p_StartDate and p_EndDate
			AND (p_SearchText='' OR tblReportSchedule.Name LIKE CONCAT('%',p_SearchText,'%'));
	END IF;

	IF p_isExport = 1
	THEN
		SELECT
			tblReportSchedule.Name,
			tblReportScheduleLog.send_at
		FROM tblReportSchedule
		INNER JOIN tblReportScheduleLog 
			ON tblReportSchedule.ReportScheduleID = tblReportScheduleLog.ReportScheduleID
		WHERE CompanyID = p_CompanyID
			AND (p_ReportScheduleID = 0 OR tblReportSchedule.ReportScheduleID = p_ReportScheduleID)
			AND (p_ReportID = 0 OR tblReportSchedule.ReportID = p_ReportID)
			AND tblReportScheduleLog.send_at BETWEEN p_StartDate and p_EndDate
			AND (p_SearchText='' OR tblReportSchedule.Name LIKE CONCAT('%',p_SearchText,'%'));
	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getTrunkReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getTrunkReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_ResellerID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_CDRType` VARCHAR(50),
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ int;
	DECLARE v_OffSet_ int;
		
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnUsageSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_CDRType,p_UserID,p_isAdmin,2,p_ResellerID,p_tag);

	
	/* grid display*/
	IF p_isExport = 0
	THEN
	
	/* Trunk by call count */	
		
	SELECT Trunk ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,	
		FORMAT(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
		FORMAT( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
	FROM tmp_tblUsageSummary_ us
	GROUP BY Trunk   
	ORDER BY
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TrunkDESC') THEN Trunk
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TrunkASC') THEN Trunk
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_)
	END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;
	
	SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin FROM (
		SELECT Trunk ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) as TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		GROUP BY Trunk
	)tbl;

	
	END IF;
	
	/* export data*/
	IF p_isExport = 1
	THEN
		SELECT
			Trunk,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)` ,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as `Margin (%)`
		FROM tmp_tblUsageSummary_ us
		GROUP BY Trunk;
	END IF;
	
	
	/* chart display*/
	IF p_isExport = 2
	THEN
	
		/* top 10 Trunk by call count */	
			
		SELECT Trunk as ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		WHERE us.Trunk != 'Other'
		GROUP BY Trunk HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;
		
		/* top 10 Trunk by call cost */	
			
		SELECT Trunk as ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		WHERE us.Trunk != 'Other'
		GROUP BY Trunk HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;
		
		/* top 10 Trunk by call minutes */	
			
		SELECT Trunk as ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageSummary_ us
		WHERE us.Trunk != 'Other'
		GROUP BY Trunk HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;
	
	END IF;
	
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getUnbilledReport` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getUnbilledReport`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` INT,
	IN `p_LastInvoiceDate` DATETIME,
	IN `p_Today` DATETIME,
	IN `p_Detail` INT
)
BEGIN
	
	DECLARE v_Round_ INT;
	
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	
	IF p_Detail = 1
	THEN
	
		SELECT 
			dd.date,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tblHeader us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		WHERE dd.date BETWEEN p_LastInvoiceDate AND p_Today 
		AND us.CompanyID = p_CompanyID
		AND us.AccountID = p_AccountID
		GROUP BY us.DateID;	
		
	
	END IF;
	
	IF p_Detail = 3
	THEN
	
		DROP TEMPORARY TABLE IF EXISTS tmp_FinalAmount_;
		CREATE TEMPORARY TABLE tmp_FinalAmount_  (
			FinalAmount DOUBLE
		);
		INSERT INTO tmp_FinalAmount_
		SELECT 
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
		FROM tblHeader us
		INNER JOIN tblDimDate dd ON dd.DateID = us.DateID
		WHERE dd.date BETWEEN p_LastInvoiceDate AND p_Today 
		AND us.CompanyID = p_CompanyID
		AND us.AccountID = p_AccountID;
		
	END IF;
 
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getVendorAccountReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getVendorAccountReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)
)
BEGIN

	DECLARE v_Round_ int;
	DECLARE v_OffSet_ int;
		
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnUsageVendorSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_UserID,p_isAdmin,2,p_tag);

	
	/* grid display*/
	IF p_isExport = 0
	THEN
	
	/* account by call count */	
		
	SELECT AccountName ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
		FORMAT(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
		FORMAT( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage,
		MAX(AccountID) as AccountID
	FROM tmp_tblUsageVendorSummary_ us
	GROUP BY AccountName   
	ORDER BY
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN AccountName
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN AccountName
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
	END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;
	
	SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin FROM (
		SELECT AccountName ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) as TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY AccountName
	)tbl;

	
	END IF;
	
	/* export data*/
	IF p_isExport = 1
	THEN
		SELECT
			AccountName  as Name,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)`,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as `Margin (%)`
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY AccountName;
	END IF;
	
	
	/* chart display*/
	IF p_isExport = 2
	THEN
	
		/* top 10 account by call count */	
			
		SELECT AccountName as ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY AccountName HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;
		
		/* top 10 account by call cost */	
			
		SELECT AccountName as ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY AccountName HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;
		
		/* top 10 account by call minutes */	
			
		SELECT AccountName as ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY AccountName HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;
	
	END IF;
	
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getVendorACD_ASR_Alert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getVendorACD_ASR_Alert`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` TEXT,
	IN `p_AccountID` TEXT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` TEXT,
	IN `p_Trunk` TEXT,
	IN `p_CountryID` TEXT
)
BEGIN
	
	DECLARE v_Round_ INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnUsageVendorSummaryDetail(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,0,1);

	IF p_AccountID = ''
	THEN
		SELECT
			IF(SUM(NoOfCalls)>0,COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls),0) as ACD , 
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			HOUR(ANY_VALUE(Time)) as Hour,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as Minutes,
			COALESCE(SUM(NoOfCalls),0) as Connected,
			COALESCE(SUM(NoOfCalls),0)+COALESCE(SUM(NoOfFailCalls),0) as Attempts
		FROM tmp_tblUsageVendorSummary_ us;
		
	END IF;
	
	IF p_AccountID != ''
	THEN
		SELECT
			IF(SUM(NoOfCalls)>0,COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls),0) as ACD , 
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			AccountID,
			HOUR(ANY_VALUE(Time)) as Hour,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as Minutes,
			COALESCE(SUM(NoOfCalls),0) as Connected,
			COALESCE(SUM(NoOfCalls),0)+COALESCE(SUM(NoOfFailCalls),0) as Attempts
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY AccountID;
	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getVendorBalanceReport` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getVendorBalanceReport`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` TEXT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME
)
BEGIN
	
	DECLARE v_Round_ INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnUsageVendorSummaryDetail(p_CompanyID,'',p_AccountID,0,p_StartDate,p_EndDate,'','','',0,1);

	SELECT
		MAX(AccountName) as AccountName,
		IF(SUM(NoOfCalls)>0,COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls),0) as ACD , 
		ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
		AccountID,
		DATE(Time) as Date,
		HOUR(Time) as Hour,
		COALESCE(SUM(TotalCharges),0) as Cost,
		ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as Minutes,
		COALESCE(SUM(NoOfCalls),0) as Connected,
		COALESCE(SUM(NoOfCalls),0)+COALESCE(SUM(NoOfFailCalls),0) as Attempts
	FROM tmp_tblUsageVendorSummary_ us
	GROUP BY AccountID,DATE(Time),HOUR(Time);

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getVendorDescReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getVendorDescReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)
)
BEGIN

	DECLARE v_Round_ INT;
	DECLARE v_OffSet_ INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	CALL fngetDefaultCodes(p_CompanyID);

	CALL fnUsageVendorSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_UserID,p_isAdmin,2,p_tag);

	/* grid display*/
	IF p_isExport = 0
	THEN

		/* Description by call count */	
			
		SELECT IFNULL(Description,'Other') AS Description ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) AS TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) AS TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) AS ACD , IF(SUM(NoOfCalls)>0,ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_),0) AS ASR,
			FORMAT(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			FORMAT( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		LEFT JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
		GROUP BY c.Description   
		ORDER BY
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
		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) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
		END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin FROM (
			SELECT IFNULL(Description,'Other') AS Description ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) AS TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) AS TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) AS ACD , IF(SUM(NoOfCalls)>0,ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_),0) AS ASR,
				ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
				ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
			FROM tmp_tblUsageVendorSummary_ us
			LEFT JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
			GROUP BY c.Description
		)tbl;

	END IF;

	/* export data*/
	IF p_isExport = 1
	THEN

		SELECT
			SQL_CALC_FOUND_ROWS IFNULL(Description,'Other') AS Description,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)`,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as `Margin (%)`
		FROM tmp_tblUsageVendorSummary_ us
		LEFT JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
		GROUP BY Description;

	END IF;

	/* chart display*/
	IF p_isExport = 2
	THEN

		/* top 10 Description by call count */
		
		SELECT Description AS ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) AS ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) AS ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
		GROUP BY Description HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;

		/* top 10 Description by call cost */
		
		SELECT Description AS ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) AS TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) AS ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) AS ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
		GROUP BY Description HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;

		/* top 10 Description by call minutes */
		
		SELECT Description AS ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) AS TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) AS ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) AS ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN tmp_codes_ c ON c.Code = us.AreaPrefix
		GROUP BY Description HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getVendorDestinationReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getVendorDestinationReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ int;
	DECLARE v_OffSet_ int;
		
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnGetCountry();
		 
	
	CALL fnUsageVendorSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_UserID,p_isAdmin,2,p_tag);

	
	/* grid display*/
	IF p_isExport = 0
	THEN
	
	/* country by call count */	
		
	SELECT IFNULL(Country,'Other') as Country ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , IF(SUM(NoOfCalls)>0,ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_),0) as ASR,
		FORMAT(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
		FORMAT( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
	FROM tmp_tblUsageVendorSummary_ us
	LEFT JOIN temptblCountry c ON c.CountryID = us.CountryID
	WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
	GROUP BY c.Country   
	ORDER BY
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CountryDESC') THEN Country
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CountryASC') THEN Country
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
	END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;
	
	SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin FROM (
		SELECT IFNULL(Country,'Other') as Country ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) as TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , IF(SUM(NoOfCalls)>0,ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_),0) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		LEFT JOIN temptblCountry c ON c.CountryID = us.CountryID
		WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
		GROUP BY c.Country
	)tbl;

	
	END IF;
	
	/* export data*/
	IF p_isExport = 1
	THEN
		SELECT
			SQL_CALC_FOUND_ROWS IFNULL(Country,'Other') as Country,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)`,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as `Margin (%)`
		FROM tmp_tblUsageVendorSummary_ us
		LEFT JOIN temptblCountry c ON c.CountryID = us.CountryID
		WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
		GROUP BY Country;
	END IF;
	
	
	/* chart display*/
	IF p_isExport = 2
	THEN
	
		/* top 10 country by call count */	
			
		SELECT Country as ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN temptblCountry c ON c.CountryID = us.CountryID
		WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
		GROUP BY Country HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;
		
		/* top 10 country by call cost */	
			
		SELECT Country as ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN temptblCountry c ON c.CountryID = us.CountryID
		WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
		GROUP BY Country HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;
		
		/* top 10 country by call minutes */	
			
		SELECT Country as ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN temptblCountry c ON c.CountryID = us.CountryID
		WHERE (p_CountryID = 0 OR c.CountryID = p_CountryID)
		GROUP BY Country HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;
	
	END IF;
	
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getVendorGatewayReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getVendorGatewayReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)
)
BEGIN

	DECLARE v_Round_ int;
	DECLARE v_OffSet_ int;
		
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnUsageVendorSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_UserID,p_isAdmin,2,p_tag);

	
	/* grid display*/
	IF p_isExport = 0
	THEN
	
	/* CompanyGatewayID by call count */	
		
	SELECT fnGetCompanyGatewayName(CompanyGatewayID) ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
		FORMAT(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
		FORMAT( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage,
		CompanyGatewayID
	FROM tmp_tblUsageVendorSummary_ us
	GROUP BY CompanyGatewayID   
	ORDER BY
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'GatewayDESC') THEN fnGetCompanyGatewayName(CompanyGatewayID)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'GatewayASC') THEN fnGetCompanyGatewayName(CompanyGatewayID)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
	END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;
	
	SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin FROM (
		SELECT fnGetCompanyGatewayName(CompanyGatewayID) ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) as TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY CompanyGatewayID
	)tbl;

	
	END IF;
	
	/* export data*/
	IF p_isExport = 1
	THEN
		SELECT
			fnGetCompanyGatewayName(CompanyGatewayID)  as Name,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)`,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as `Margin (%)`		
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY CompanyGatewayID;
	END IF;
	
	
	/* chart display*/
	IF p_isExport = 2
	THEN
	
		/* top 10 CompanyGatewayID by call count */	
			
		SELECT fnGetCompanyGatewayName(CompanyGatewayID) as ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		WHERE us.CompanyGatewayID != 'Other'
		GROUP BY CompanyGatewayID HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;
		
		/* top 10 CompanyGatewayID by call cost */	
			
		SELECT fnGetCompanyGatewayName(CompanyGatewayID) as ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		WHERE us.CompanyGatewayID != 'Other'
		GROUP BY CompanyGatewayID HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;
		
		/* top 10 CompanyGatewayID by call minutes */	
			
		SELECT fnGetCompanyGatewayName(CompanyGatewayID) as ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		WHERE us.CompanyGatewayID != 'Other'
		GROUP BY CompanyGatewayID HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;
	
	END IF;
	
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getVendorPrefixReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getVendorPrefixReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ int;
	DECLARE v_OffSet_ int;
		
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnUsageVendorSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_UserID,p_isAdmin,2,p_tag);

	
	/* grid display*/
	IF p_isExport = 0
	THEN
	
	/* AreaPrefix by call count */	
		
	SELECT AreaPrefix ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
		FORMAT(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
		FORMAT( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
	FROM tmp_tblUsageVendorSummary_ us
	GROUP BY AreaPrefix   
	ORDER BY
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AreaPrefixDESC') THEN AreaPrefix
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AreaPrefixASC') THEN AreaPrefix
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
	END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;
	
	SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin FROM (
		SELECT AreaPrefix ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) as TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY AreaPrefix
	)tbl;

	
	END IF;
	
	/* export data*/
	IF p_isExport = 1
	THEN
		SELECT
			AreaPrefix,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)`,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as `Margin (%)`
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY AreaPrefix;
	END IF;
	
	
	/* chart display*/
	IF p_isExport = 2
	THEN
	
		/* top 10 AreaPrefix by call count */	
			
		SELECT AreaPrefix as ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		WHERE us.AreaPrefix != 'Other'
		GROUP BY AreaPrefix HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;
		
		/* top 10 AreaPrefix by call cost */	
			
		SELECT AreaPrefix as ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		WHERE us.AreaPrefix != 'Other'
		GROUP BY AreaPrefix HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;
		
		/* top 10 AreaPrefix by call minutes */	
			
		SELECT AreaPrefix as ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		WHERE us.AreaPrefix != 'Other'
		GROUP BY AreaPrefix HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;
	
	END IF;
	
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getVendorReportByTime` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getVendorReportByTime`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_ReportType` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ INT;
	DECLARE V_Detail INT;

	SET V_Detail = 2;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	CALL fnUsageVendorSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_UserID,p_isAdmin,V_Detail,p_tag);

	/* hourly report */
	IF p_ReportType =1
	THEN

		SELECT 
			CONCAT(dt.hour,' Hour') as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN tblDimTime dt on dt.TimeID = us.TimeID
		GROUP BY  us.DateID,dt.hour;

	END IF;

	/* daily report */
	IF p_ReportType =2
	THEN

		SELECT 
			dd.date as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		GROUP BY  us.DateID;

	END IF;

	/* weekly report */
	IF p_ReportType =3
	THEN

		SELECT 
			ANY_VALUE(dd.week_year_name) as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		GROUP BY  dd.year,dd.week_of_year
		ORDER BY dd.year,dd.week_of_year;

	END IF;

	/* monthly report */
	IF p_ReportType =4
	THEN

		SELECT 
			ANY_VALUE(dd.month_year_name) as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		GROUP BY  dd.year,dd.month_of_year
		ORDER BY dd.year,dd.month_of_year;

	END IF;

	/* queterly report */
	IF p_ReportType =5
	THEN

		SELECT 
			CONCAT('Q-',ANY_VALUE(dd.quarter_year_name)) as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		GROUP BY  dd.year,dd.quarter_of_year
		ORDER BY dd.year,dd.quarter_of_year;

	END IF;

	/* yearly report */
	IF p_ReportType =6
	THEN

		SELECT 
			dd.year as category,
			SUM(NoOfCalls) AS CallCount,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tmp_tblUsageVendorSummary_ us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		GROUP BY  dd.year;

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getVendorTrunkReportAll` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getVendorTrunkReportAll`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ int;
	DECLARE v_OffSet_ int;
		
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	CALL fnUsageVendorSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_UserID,p_isAdmin,2,p_tag);

	
	/* grid display*/
	IF p_isExport = 0
	THEN
	
	/* Trunk by call count */	
		
	SELECT Trunk ,FORMAT(SUM(NoOfCalls),0) AS CallCount,FORMAT(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalSeconds,FORMAT(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
		FORMAT(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
		FORMAT( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
	FROM tmp_tblUsageVendorSummary_ us
	GROUP BY Trunk   
	ORDER BY
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountDESC') THEN SUM(NoOfCalls)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CallCountASC') THEN SUM(NoOfCalls)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesDESC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMinutesASC') THEN COALESCE(SUM(TotalBilledDuration),0)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TrunkDESC') THEN Trunk
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TrunkASC') THEN Trunk
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostDESC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalCostASC') THEN ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDDESC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ACDASC') THEN (COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls))
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRDESC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ASRASC') THEN SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginDESC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TotalMarginASC') THEN ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_)
	END ASC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageDESC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
	END DESC,
	CASE
		WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MarginPercentageASC') THEN ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_)
	END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;
	
	SELECT COUNT(*) AS totalcount,FORMAT(SUM(CallCount),0) AS TotalCall,FORMAT(SUM(TotalSeconds)/60,0) AS TotalDuration,FORMAT(SUM(TotalCost),v_Round_) AS TotalCost,FORMAT(SUM(TotalMargin),v_Round_) AS TotalMargin FROM (
		SELECT Trunk ,SUM(NoOfCalls) AS CallCount,COALESCE(SUM(TotalBilledDuration),0) as TotalSeconds,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY Trunk
	)tbl;

	
	END IF;
	
	/* export data*/
	IF p_isExport = 1
	THEN
		SELECT
			Trunk,
			SUM(NoOfCalls) AS `No. of Calls`,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as `Billed Duration (Min.)`,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as `Charged Amount`,
			IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as `ACD (mm:ss)`,
			ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as `ASR (%)`,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as `Margin`,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as `Margin (%)`
		FROM tmp_tblUsageVendorSummary_ us
		GROUP BY Trunk;
	END IF;
	
	
	/* chart display*/
	IF p_isExport = 2
	THEN
	
		/* top 10 Trunk by call count */	
			
		SELECT Trunk as ChartVal ,SUM(NoOfCalls) AS CallCount,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		WHERE us.Trunk != 'Other'
		GROUP BY Trunk HAVING SUM(NoOfCalls) > 0 ORDER BY CallCount DESC LIMIT 10;
		
		/* top 10 Trunk by call cost */	
			
		SELECT Trunk as ChartVal,ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		WHERE us.Trunk != 'Other'
		GROUP BY Trunk HAVING SUM(TotalCharges) > 0 ORDER BY TotalCost DESC LIMIT 10;
		
		/* top 10 Trunk by call minutes */	
			
		SELECT Trunk as ChartVal,ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD , ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
			ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
			ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage
		FROM tmp_tblUsageVendorSummary_ us
		WHERE us.Trunk != 'Other'
		GROUP BY Trunk HAVING SUM(TotalBilledDuration) > 0  ORDER BY TotalMinutes DESC LIMIT 10;
	
	END IF;
	
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getVendorUnbilledReport` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getVendorUnbilledReport`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` INT,
	IN `p_LastInvoiceDate` DATETIME,
	IN `p_Today` DATETIME,
	IN `p_Detail` INT
)
BEGIN
	
	DECLARE v_Round_ INT;
	
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	IF p_Detail = 1
	THEN
	
		SELECT 
			dd.date,
			ROUND(COALESCE(SUM(TotalBilledDuration),0)/60,0) as TotalMinutes,
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost
		FROM tblHeaderV us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		WHERE dd.date BETWEEN p_LastInvoiceDate AND p_Today 
		AND us.CompanyID = p_CompanyID
		AND us.VAccountID = p_AccountID
		GROUP BY us.DateID;	
	
	END IF;
	
	 
	
	IF p_Detail = 3
	THEN
	
		DROP TEMPORARY TABLE IF EXISTS tmp_FinalAmount_;
		CREATE TEMPORARY TABLE tmp_FinalAmount_  (
			FinalAmount DOUBLE
		);
		INSERT INTO tmp_FinalAmount_
		SELECT 
			ROUND(COALESCE(SUM(TotalCharges),0), v_Round_)
		FROM tblHeaderV us
		INNER JOIN tblDimDate dd on dd.DateID = us.DateID
		WHERE dd.date BETWEEN p_LastInvoiceDate AND p_Today 
		AND us.CompanyID = p_CompanyID
		AND us.VAccountID = p_AccountID;
	
	END IF;
 
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getVendorWorldMap` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getVendorWorldMap`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	CALL fnGetCountry();

	CALL fnUsageVendorSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_UserID,p_isAdmin,2,p_tag);

	/* get all country call counts*/
	SELECT 
		Country,
		SUM(NoOfCalls) AS CallCount,
		ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
		ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,
		IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD,
		ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
		ROUND(COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0), v_Round_) as TotalMargin,
		ROUND( (COALESCE(SUM(TotalSales),0) - COALESCE(SUM(TotalCharges),0)) / SUM(TotalSales)*100, v_Round_) as MarginPercentage,
		MAX(ISO2) AS ISO_Code,
		tblCountry.CountryID
	FROM tmp_tblUsageVendorSummary_ AS us
	INNER JOIN temptblCountry AS tblCountry 
		ON tblCountry.CountryID = us.CountryID
	GROUP BY Country,tblCountry.CountryID 
	HAVING SUM(NoOfCalls) > 0
	ORDER BY CallCount DESC;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getWorldMap` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getWorldMap`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT,
	IN `p_AccountID` INT,
	IN `p_ResellerID` INT,
	IN `p_CurrencyID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_AreaPrefix` VARCHAR(50),
	IN `p_Trunk` VARCHAR(50),
	IN `p_CountryID` INT,
	IN `p_CDRType` VARCHAR(50),
	IN `p_UserID` INT,
	IN `p_isAdmin` INT,
	IN `p_tag` VARCHAR(250)

)
BEGIN

	DECLARE v_Round_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	CALL fnGetCountry();

	CALL fnUsageSummary(p_CompanyID,p_CompanyGatewayID,p_AccountID,p_CurrencyID,p_StartDate,p_EndDate,p_AreaPrefix,p_Trunk,p_CountryID,p_CDRType,p_UserID,p_isAdmin,2,p_ResellerID,p_tag);

	/* get all country call counts*/
	SELECT 
		Country,
		SUM(NoOfCalls) AS CallCount,
		ROUND(COALESCE(SUM(TotalCharges),0), v_Round_) as TotalCost,
		ROUND(COALESCE(SUM(TotalBilledDuration),0)/ 60,0) as TotalMinutes,
		IF(SUM(NoOfCalls)>0,fnDurationmmss(COALESCE(SUM(TotalBilledDuration),0)/SUM(NoOfCalls)),0) as ACD,
		ROUND(SUM(NoOfCalls)/(SUM(NoOfCalls)+SUM(NoOfFailCalls))*100,v_Round_) as ASR,
		ROUND(COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0), v_Round_) as TotalMargin,
		ROUND( (COALESCE(SUM(TotalCharges),0) - COALESCE(SUM(TotalCost),0)) / SUM(TotalCharges)*100, v_Round_) as MarginPercentage,
		MAX(ISO2) AS ISO_Code,
		tblCountry.CountryID
	FROM tmp_tblUsageSummary_
	INNER JOIN temptblCountry AS tblCountry 
		ON tblCountry.CountryID = tmp_tblUsageSummary_.CountryID
	GROUP BY Country,tblCountry.CountryID 
	HAVING SUM(NoOfCalls) > 0
	ORDER BY CallCount DESC;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_timedimbuild` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_timedimbuild`()
BEGIN
    DECLARE v_full_date DATETIME;

    DELETE FROM tblDimTime;

    SET v_full_date = '2009-03-01 00:00:00';
    WHILE v_full_date < '2009-03-02 00:00:00' DO

        INSERT INTO tblDimTime (
            fulltime ,
            hour ,
            minute ,
            second ,
            ampm
        ) VALUES (
            TIME(v_full_date),
            HOUR(v_full_date),
            MINUTE(v_full_date),
            SECOND(v_full_date),
            DATE_FORMAT(v_full_date,'%p')
        );

        SET v_full_date = DATE_ADD(v_full_date, INTERVAL 1 SECOND);
    END WHILE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_updateLiveTables` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_updateLiveTables`(
	IN `p_CompanyID` INT,
	IN `p_UniqueID` VARCHAR(50)
)
BEGIN

	DECLARE v_Round_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	CALL telsomespainRM.prc_UpdateMysqlPID(p_UniqueID);

	SET @stmt = CONCAT('
	UPDATE tmp_tblUsageDetailsReport_',p_UniqueID,' uh
	INNER JOIN telsomespainBilling.tblGatewayAccount ga
		ON  uh.GatewayAccountPKID = ga.GatewayAccountPKID
	SET uh.AccountID = ga.AccountID
	WHERE uh.AccountID IS NULL
	AND ga.AccountID is not null
	AND uh.CompanyID = ',p_CompanyID,';
	');

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

	SET @stmt = CONCAT('
	UPDATE tmp_tblVendorUsageDetailsReport_',p_UniqueID,' uh
	INNER JOIN telsomespainBilling.tblGatewayAccount ga
		ON  uh.GatewayVAccountPKID = ga.GatewayAccountPKID
	SET uh.VAccountID = ga.AccountID
	WHERE uh.VAccountID IS NULL
	AND ga.AccountID is not null
	AND uh.CompanyID = ',p_CompanyID,';
	');

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

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_updateUnbilledAmount` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_updateUnbilledAmount`(
	IN `p_CompanyID` INT,
	IN `p_Today` DATETIME

)
BEGIN
	
	DECLARE v_Round_ INT;
	DECLARE v_rowCount_ INT;
	DECLARE v_pointer_ INT;
	DECLARE v_AccountID_ INT;
	DECLARE v_LastInvoiceDate_ DATE;
	DECLARE v_FinalAmount_ DOUBLE;
	
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	DROP TEMPORARY TABLE IF EXISTS tmp_Account_;
	CREATE TEMPORARY TABLE tmp_Account_  (
		RowID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
		AccountID INT,
		LastInvoiceDate DATE
	);
	
	INSERT INTO tmp_Account_ (AccountID)
	SELECT DISTINCT tblHeader.AccountID  FROM tblHeader INNER JOIN telsomespainRM.tblAccount ON tblAccount.AccountID = tblHeader.AccountID WHERE tblHeader.CompanyID = p_CompanyID;
	
	UPDATE tmp_Account_ SET LastInvoiceDate = fngetLastInvoiceDate(AccountID);
	
	SET v_pointer_ = 1;
	SET v_rowCount_ = (SELECT COUNT(*) FROM tmp_Account_);

	WHILE v_pointer_ <= v_rowCount_
	DO
		SET v_AccountID_ = (SELECT AccountID FROM tmp_Account_ t WHERE t.RowID = v_pointer_);
		SET v_LastInvoiceDate_ = (SELECT LastInvoiceDate FROM tmp_Account_ t WHERE t.RowID = v_pointer_);
		
		CALL prc_getUnbilledReport(p_CompanyID,v_AccountID_,v_LastInvoiceDate_,p_Today,3);
		
		SELECT FinalAmount INTO v_FinalAmount_ FROM tmp_FinalAmount_;
		
		IF (SELECT COUNT(*) FROM telsomespainRM.tblAccountBalance WHERE AccountID = v_AccountID_) > 0
		THEN
			UPDATE telsomespainRM.tblAccountBalance SET UnbilledAmount = v_FinalAmount_ WHERE AccountID = v_AccountID_;
		ELSE
			INSERT INTO telsomespainRM.tblAccountBalance (AccountID,UnbilledAmount,BalanceAmount)
			SELECT v_AccountID_,v_FinalAmount_,v_FinalAmount_;
		END IF;
		
		SET v_pointer_ = v_pointer_ + 1;
	
	END WHILE;
	
	UPDATE 
		telsomespainRM.tblAccountBalance 
	INNER JOIN
		(
			SELECT 
				DISTINCT tblAccount.AccountID 
			FROM telsomespainRM.tblAccount  
			LEFT JOIN tmp_Account_ 
				ON tblAccount.AccountID = tmp_Account_.AccountID
			WHERE tmp_Account_.AccountID IS NULL AND tblAccount.CompanyID = p_CompanyID
		) TBL
	ON TBL.AccountID = tblAccountBalance.AccountID
	SET UnbilledAmount = 0;
	
	CALL prc_updateVendorUnbilledAmount(p_CompanyID,p_Today);
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_updateVendorUnbilledAmount` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_updateVendorUnbilledAmount`(
	IN `p_CompanyID` INT,
	IN `p_Today` DATETIME

)
BEGIN
	
	DECLARE v_Round_ INT;
	DECLARE v_rowCount_ INT;
	DECLARE v_pointer_ INT;
	DECLARE v_AccountID_ INT;
	DECLARE v_LastInvoiceDate_ DATETIME;
	DECLARE v_FinalAmount_ DOUBLE;
	
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	DROP TEMPORARY TABLE IF EXISTS tmp_Account_;
	CREATE TEMPORARY TABLE tmp_Account_  (
		RowID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
		AccountID INT,
		LastInvoiceDate DATETIME
	);
	
	INSERT INTO tmp_Account_ (AccountID)
	SELECT DISTINCT tblHeaderV.VAccountID  FROM tblHeaderV INNER JOIN telsomespainRM.tblAccount ON tblAccount.AccountID = tblHeaderV.VAccountID WHERE tblHeaderV.CompanyID = p_CompanyID;
	
	UPDATE tmp_Account_ SET LastInvoiceDate = fngetLastVendorInvoiceDate(AccountID);
	
	SET v_pointer_ = 1;
	SET v_rowCount_ = (SELECT COUNT(*) FROM tmp_Account_);

	WHILE v_pointer_ <= v_rowCount_
	DO
		SET v_AccountID_ = (SELECT AccountID FROM tmp_Account_ t WHERE t.RowID = v_pointer_);
		SET v_LastInvoiceDate_ = (SELECT LastInvoiceDate FROM tmp_Account_ t WHERE t.RowID = v_pointer_);
		
		IF v_LastInvoiceDate_ IS NOT NULL
		THEN
		
			CALL prc_getVendorUnbilledReport(p_CompanyID,v_AccountID_,v_LastInvoiceDate_,p_Today,3);
			
			SELECT FinalAmount INTO v_FinalAmount_ FROM tmp_FinalAmount_;
			
			IF (SELECT COUNT(*) FROM telsomespainRM.tblAccountBalance WHERE AccountID = v_AccountID_) > 0
			THEN
				UPDATE telsomespainRM.tblAccountBalance SET VendorUnbilledAmount = v_FinalAmount_ WHERE AccountID = v_AccountID_;
			ELSE
				INSERT INTO telsomespainRM.tblAccountBalance (AccountID,VendorUnbilledAmount,BalanceAmount)
				SELECT v_AccountID_,v_FinalAmount_,v_FinalAmount_;
			END IF;
			
		END IF;
		
		SET v_pointer_ = v_pointer_ + 1;
	
	END WHILE;	
	
	UPDATE 
		telsomespainRM.tblAccountBalance 
	INNER JOIN
		(
			SELECT 
				DISTINCT tblAccount.AccountID 
			FROM telsomespainRM.tblAccount  
			LEFT JOIN tmp_Account_ 
				ON tblAccount.AccountID = tmp_Account_.AccountID
			WHERE tmp_Account_.AccountID IS NULL AND tblAccount.CompanyID = p_CompanyID
		) TBL
	ON TBL.AccountID = tblAccountBalance.AccountID
	SET VendorUnbilledAmount = 0;	

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_verifySummary` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_verifySummary`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME
)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS tmp_verify_;
   CREATE TEMPORARY TABLE IF NOT EXISTS tmp_verify_(
	   AccountID INT,
	   TotalCall INT,
	   TotalCharges decimal(18,6),
	   TotalSecond BIGINT,
	   Summary INT,
	   CDR INT
   );
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	CALL telsomespainBilling.fnUsageDetail(p_CompanyID,p_AccountID,0,p_StartDate,p_EndDate,0,1,1,'','','',0);
	
	INSERT INTO tmp_verify_ (AccountID,TotalCall,TotalCharges,TotalSecond,Summary,CDR)
	SELECT p_AccountID,COUNT(*) as TotalCall,SUM(cost) as TotalCost,SUM(billed_duration) as TotalSecond,0,1 FROM telsomespainBilling.tmp_tblUsageDetails_;
	
	CALL fnUsageSummary(p_CompanyID,0,p_AccountID,0,p_StartDate,p_EndDate,'','',0,0,1,1,'');
	
	INSERT INTO tmp_verify_ (AccountID,TotalCall,TotalCharges,TotalSecond,Summary,CDR)
	SELECT p_AccountID,SUM(NoOfCalls) as TotalCall,SUM(TotalCharges) as TotalCost,SUM(TotalBilledDuration) as TotalSecond,1,0 FROM tmp_tblUsageSummary_;
	
	SELECT * FROM tmp_verify_;

	


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `report_mig` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `report_mig`()
BEGIN

SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
  INSERT INTO tblUsageSummaryDay (HeaderID,TotalCharges,TotalBilledDuration,TotalDuration,NoOfCalls,NoOfFailCalls,CompanyGatewayID,ServiceID,Trunk,AreaPrefix,CountryID,GatewayAccountPKID)
	SELECT 
    HeaderID,tblUsageSummary.TotalCharges,tblUsageSummary.TotalBilledDuration,tblUsageSummary.TotalDuration,tblUsageSummary.NoOfCalls,tblUsageSummary.NoOfFailCalls,tblSummaryHeader.CompanyGatewayID,tblSummaryHeader.ServiceID,Trunk,AreaPrefix,CountryID,GatewayAccountPKID
  FROM tblUsageSummary 
  INNER JOIN tblSummaryHeader ON tblSummaryHeader.SummaryHeaderID = tblUsageSummary.SummaryHeaderID
  INNER JOIN tblHeader ON tblHeader.DateID = tblSummaryHeader.DateID and tblHeader.CompanyID = tblSummaryHeader.CompanyID AND tblHeader.AccountID = tblSummaryHeader.AccountID
  LEFT JOIN telsomespainBilling.tblGatewayAccount ON tblGatewayAccount.GatewayAccountID = tblSummaryHeader.GatewayAccountID AND tblGatewayAccount.CompanyGatewayID = tblSummaryHeader.CompanyGatewayID;
  
  INSERT INTO tblVendorSummaryDay (HeaderVID,TotalCharges,TotalSales,TotalBilledDuration,TotalDuration,NoOfCalls,NoOfFailCalls,CompanyGatewayID,ServiceID,Trunk,AreaPrefix,CountryID,GatewayAccountPKID)
	SELECT 
    HeaderVID,tblUsageVendorSummary.TotalCharges,tblUsageVendorSummary.TotalSales,tblUsageVendorSummary.TotalBilledDuration,tblUsageVendorSummary.TotalDuration,tblUsageVendorSummary.NoOfCalls,tblUsageVendorSummary.NoOfFailCalls,tblSummaryVendorHeader.CompanyGatewayID,tblSummaryVendorHeader.ServiceID,Trunk,AreaPrefix,CountryID,GatewayAccountPKID
  FROM tblUsageVendorSummary 
  INNER JOIN tblSummaryVendorHeader ON tblSummaryVendorHeader.SummaryVendorHeaderID = tblUsageVendorSummary.SummaryVendorHeaderID
  INNER JOIN tblHeaderV ON tblHeaderV.DateID = tblSummaryVendorHeader.DateID and tblHeaderV.CompanyID = tblSummaryVendorHeader.CompanyID AND tblHeaderV.VAccountID = tblSummaryVendorHeader.AccountID
  LEFT JOIN telsomespainBilling.tblGatewayAccount ON tblGatewayAccount.GatewayAccountID = tblSummaryVendorHeader.GatewayAccountID AND tblGatewayAccount.CompanyGatewayID = tblSummaryVendorHeader.CompanyGatewayID;

	INSERT INTO tblUsageSummaryHour (HeaderID,TimeID,TotalCharges,TotalBilledDuration,TotalDuration,NoOfCalls,NoOfFailCalls,CompanyGatewayID,ServiceID,Trunk,AreaPrefix,CountryID,GatewayAccountPKID)
	SELECT 
    HeaderID,TimeID,tblUsageSummaryDetail.TotalCharges,tblUsageSummaryDetail.TotalBilledDuration,tblUsageSummaryDetail.TotalDuration,tblUsageSummaryDetail.NoOfCalls,tblUsageSummaryDetail.NoOfFailCalls,tblSummaryHeader.CompanyGatewayID,tblSummaryHeader.ServiceID,Trunk,AreaPrefix,CountryID,GatewayAccountPKID
  FROM tblUsageSummaryDetail 
  INNER JOIN tblSummaryHeader ON tblSummaryHeader.SummaryHeaderID = tblUsageSummaryDetail.SummaryHeaderID
  INNER JOIN tblHeader ON tblHeader.DateID = tblSummaryHeader.DateID and tblHeader.CompanyID = tblSummaryHeader.CompanyID AND tblHeader.AccountID = tblSummaryHeader.AccountID
  LEFT JOIN telsomespainBilling.tblGatewayAccount ON tblGatewayAccount.GatewayAccountID = tblSummaryHeader.GatewayAccountID AND tblGatewayAccount.CompanyGatewayID = tblSummaryHeader.CompanyGatewayID;
  
  INSERT INTO tblVendorSummaryHour (HeaderVID,TimeID,TotalCharges,TotalSales,TotalBilledDuration,TotalDuration,NoOfCalls,NoOfFailCalls,CompanyGatewayID,ServiceID,Trunk,AreaPrefix,CountryID,GatewayAccountPKID)
  SELECT 
    HeaderVID,TimeID,tblUsageVendorSummaryDetail.TotalCharges,tblUsageVendorSummaryDetail.TotalSales,tblUsageVendorSummaryDetail.TotalBilledDuration,tblUsageVendorSummaryDetail.TotalDuration,tblUsageVendorSummaryDetail.NoOfCalls,tblUsageVendorSummaryDetail.NoOfFailCalls,tblSummaryVendorHeader.CompanyGatewayID,tblSummaryVendorHeader.ServiceID,Trunk,AreaPrefix,CountryID,GatewayAccountPKID
  FROM tblUsageVendorSummaryDetail 
  INNER JOIN tblSummaryVendorHeader ON tblSummaryVendorHeader.SummaryVendorHeaderID = tblUsageVendorSummaryDetail.SummaryVendorHeaderID
  INNER JOIN tblHeaderV ON tblHeaderV.DateID = tblSummaryVendorHeader.DateID and tblHeaderV.CompanyID = tblSummaryVendorHeader.CompanyID AND tblHeaderV.VAccountID = tblSummaryVendorHeader.AccountID
  LEFT JOIN telsomespainBilling.tblGatewayAccount ON tblGatewayAccount.GatewayAccountID = tblSummaryVendorHeader.GatewayAccountID AND tblGatewayAccount.CompanyGatewayID = tblSummaryVendorHeader.CompanyGatewayID;
  
  
  RENAME TABLE `tblSummaryHeader` TO `tblSummaryHeader_delete`;
  RENAME TABLE `tblSummaryVendorHeader` TO `tblSummaryVendorHeader_delete`;
  
  RENAME TABLE `tblUsageSummaryDetailLive` TO `tblUsageSummaryDetailLive_delete`;  
  RENAME TABLE `tblUsageSummaryLive` TO `tblUsageSummaryLive_delete`;
  
  RENAME TABLE `tblUsageSummary` TO `tblUsageSummary_delete`;
  RENAME TABLE `tblUsageSummaryDetail` TO `tblUsageSummaryDetail_delete`;
  
  RENAME TABLE `tblUsageVendorSummary` TO `tblUsageVendorSummary_delete`;
  RENAME TABLE `tblUsageVendorSummaryDetail` TO `tblUsageVendorSummaryDetail_delete`;  

  RENAME TABLE `tblUsageVendorSummaryLive` TO `tblUsageVendorSummaryLive_delete`;
  RENAME TABLE `tblUsageVendorSummaryDetailLive` TO `tblUsageVendorSummaryDetailLive_delete`;
  

END ;;
DELIMITER ;


USE `telsomespainRM`;
INSERT INTO `tblCronJobCommand` VALUES (1,1,1,'OLD Download Sippy CDR','sippyaccountusage','[[{\"title\":\"Sippy Max Interval\",\"type\":\"text\",\"value\":\"\",\"name\":\"MaxInterval\"},{\"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\"}]]',0,NULL,NULL),(2,1,NULL,'Rate Generator','rategenerator','[[{\"title\":\"Effective Day\",\"type\":\"text\",\"value\":\"\",\"name\":\"EffectiveDay\"},{\"title\":\"Increase Effective Day\",\"type\":\"text\",\"value\":\"\",\"name\":\"IncreaseEffectiveDate\"},{\"title\":\"Decrease Effective Day\",\"type\":\"text\",\"value\":\"\",\"name\":\"DecreaseEffectiveDate\"},{\"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,'2015-04-21 15:11:06','RateManagementSystem'),(3,1,2,'Download Porta CDR','portaaccountusage','[[{\"title\":\"Porta Max Interval\",\"type\":\"text\",\"value\":\"\",\"name\":\"MaxInterval\"},{\"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,'2015-05-01 15:38:30','RateManagementSystem'),(7,1,3,'Download VOS  CDR','vosaccountusage','[[{\"title\":\"Files Max Proccess\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesMaxProccess\"},{\"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,'2015-05-29 13:05:56','RateManagementSystem'),(8,1,4,'Download PBX CDR','pbxaccountusage','[[{\"title\":\"PBX Max Interval\",\"type\":\"text\",\"value\":\"\",\"name\":\"MaxInterval\"},{\"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,'2015-07-09 13:56:13','RateManagementSystem'),(17,1,NULL,'DB CleanUP','dbcleanup','[[{\"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,'2015-11-19 06:02:05','RateManagementSystem'),(18,1,NULL,'Server CleanUP','servercleanup','[[{\"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,'2016-08-11 00:00:05','RateManagementSystem'),(57,1,NULL,'Invoice Generator','invoicegenerator','[[{\"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,'2015-11-19 06:02:05','RateManagementSystem'),(58,1,NULL,'Bulk Auto Payment Capture','bulkautopaymentcapture','[[{\"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,'2015-11-19 06:02:05','RateManagementSystem'),(59,1,NULL,'Transaction Log Email','transactionlogemail','[[{\"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,'2015-11-19 06:02:06','RateManagementSystem'),(60,1,NULL,'Activity Reminder','accountactivityreminder','[[{\"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,'2015-11-19 06:02:06','RateManagementSystem'),(61,1,NULL,'Active Cron Job Email','activecronjobemail','[[{\"title\":\"Alert Active Email Time (Minute)\",\"type\":\"text\",\"value\":\"\",\"name\":\"AlertEmailInterval\"},{\"title\":\"Success Email\",\"type\":\"text\",\"value\":\"\",\"name\":\"SuccessEmail\"},{\"title\":\"Error Email\",\"type\":\"text\",\"value\":\"\",\"name\":\"ErrorEmail\"}]]',1,'2015-11-27 11:01:44','RateManagementSystem'),(63,1,6,'Download Sippy CDR (SFTP)','sippyaccountusage','[[{\"title\":\"Files Max Proccess\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesMaxProccess\"},{\"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,'2016-02-17 11:34:30',NULL),(64,1,NULL,'Create Vendor Summary','createvendorsummary','[[{\"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\"}]]',0,'2015-12-01 10:11:09','RateManagementSystem'),(65,1,NULL,'Create Customer Summary Live','createsummarylive','[[{\"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,'2015-12-01 10:11:09','RateManagementSystem'),(66,1,NULL,'Create Summary','createsummary','[[{\"title\":\"Start Date\",\"type\":\"text\",\"datepicker\":\"\",\"value\":\"\",\"name\":\"StartDate\"},{\"title\":\"End Date\",\"type\":\"text\",\"value\":\"\",\"datepicker\":\"\",\"name\":\"EndDate\"},{\"title\":\"Success Email\",\"type\":\"text\",\"value\":\"\",\"name\":\"SuccessEmail\"},{\"title\":\"Error Email\",\"type\":\"text\",\"value\":\"\",\"name\":\"ErrorEmail\"},{\"title\":\"Threshold Time (Minute)\",\"type\":\"text\",\"value\":\"\",\"name\":\"ThresholdTime\"}]]',1,'2015-12-01 10:11:09','RateManagementSystem'),(67,1,NULL,'Create Vendor Summary Live','createvendorsummarylive','[[{\"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,'2015-12-01 10:11:09','RateManagementSystem'),(68,1,6,'Download Sippy SFTP File','sippydownloadcdr','[[{\"title\":\"Max File Download Limit\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesDownloadLimit\"},{\"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,'2016-06-09 19:33:05',NULL),(69,1,3,'Download VOS SFTP File','vosdownloadcdr','[[{\"title\":\"Max File Download Limit\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesDownloadLimit\"},{\"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,'2015-06-09 13:05:56','RateManagementSystem'),(70,1,NULL,'Neon System Alerts','neonalerts','[[{\"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,'2016-09-28 14:07:52','RateManagementSystem'),(72,1,NULL,'PBX Account Block','pbxaccountblock','[[{\"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,'2016-09-28 12:13:52','RateManagementSystem'),(73,1,NULL,'Ticket Emails','reademailstickets','[[{\"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,'2016-09-28 14:07:52','RateManagementSystem'),(74,1,7,'Download FTP CDR','ftpaccountusage','[[{\"title\":\"Files Max Proccess\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesMaxProccess\"},{\"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,'2017-04-21 12:20:01','RateManagementSystem'),(75,1,7,'Download FTP File','ftpdownloadcdr','[[{\"title\":\"Max File Download Limit\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesDownloadLimit\"},{\"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,'2017-04-21 12:20:01','RateManagementSystem'),(83,1,8,'Download MOR CDR','moraccountusage','[[{\"title\":\"MOR Max Interval\",\"type\":\"text\",\"value\":\"\",\"name\":\"MaxInterval\"},{\"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,'2015-07-09 13:56:13','RateManagementSystem'),(85,1,10,'Vendor Rate File Process','vendorratefileprocess','[[{\"title\":\"Files Max Process\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesMaxProcess\"},{\"title\":\"File Location (Path)\",\"type\":\"text\",\"value\":\"\",\"name\":\"FileLocation\"},{\"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,'2017-07-27 15:11:06','RateManagementSystem'),(86,1,10,'Customer Rate File Process','customerratefileprocess','[[{\"title\":\"Files Max Process\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesMaxProcess\"},{\"title\":\"File Location (Path)\",\"type\":\"text\",\"value\":\"\",\"name\":\"FileLocation\"},{\"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,'2017-07-27 15:11:06','RateManagementSystem'),(87,1,10,'Vendor Rate File Download','vendorratefiledownload','[[{\"title\":\"Max File Download Limit\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesDownloadLimit\"},{\"title\":\"File Download From Location (Path)\",\"type\":\"text\",\"value\":\"\",\"name\":\"FileLocationFrom\"},{\"title\":\"File Download To Location (Path)\",\"type\":\"text\",\"value\":\"\",\"name\":\"FileLocationTo\"},{\"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,'2017-07-27 15:11:06','RateManagementSystem'),(88,1,10,'Customer Rate File Download','customerratefiledownload','[[{\"title\":\"Max File Download Limit\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesDownloadLimit\"},{\"title\":\"File Download From Location (Path)\",\"type\":\"text\",\"value\":\"\",\"name\":\"FileLocationFrom\"},{\"title\":\"File Download To Location (Path)\",\"type\":\"text\",\"value\":\"\",\"name\":\"FileLocationTo\"},{\"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,'2017-07-27 15:11:06','RateManagementSystem'),(89,1,NULL,'Vendor Rate File Export','vendorratefileexport','[[{\"title\":\"File Generation Location (Path)\",\"type\":\"text\",\"value\":\"\",\"name\":\"FileLocation\"},{\"title\":\"Effective\",\"type\":\"select\",\"value\":{\"Now\":\"Now\",\"Future\":\"Future\",\"All\":\"All\"},\"name\":\"Effective\"},{\"title\":\"Add Discontinue Rates\",\"type\":\"select\",\"value\":{\"no\":\"No\",\"yes\":\"Yes\"},\"name\":\"AddDiscontinueRates\"},{\"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,'2017-07-27 15:11:06','RateManagementSystem'),(90,1,NULL,'Customer Rate File Export','customerratefileexport','[[{\"title\":\"File Generation Location (Path)\",\"type\":\"text\",\"value\":\"\",\"name\":\"FileLocation\"},{\"title\":\"Effective\",\"type\":\"select\",\"value\":{\"Now\":\"Now\",\"Future\":\"Future\",\"All\":\"All\"},\"name\":\"Effective\"},{\"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,'2017-07-27 15:11:06','RateManagementSystem'),(91,1,10,'Download Streamco CDR','streamcoaccountusage','[[{\"title\":\"STREMCO Max Interval\",\"type\":\"text\",\"value\":\"\",\"name\":\"MaxInterval\"},{\"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,'2017-07-27 15:11:06','RateManagementSystem'),(92,1,10,'Streamco Account Import','streamcoaccountimport','[[{\"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,'2017-07-27 15:11:06','RateManagementSystem'),(93,1,9,'Download Locutorios CDR','callshopaccountusage','[[{\"title\":\"Locutorios Max Interval\",\"type\":\"text\",\"value\":\"\",\"name\":\"MaxInterval\"},{\"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,'2017-07-14 00:00:00','RateManagementSystem'),(95,1,10,'Rate File Export','ratefileexport','[[{\"title\":\"Script Location (Path)\",\"type\":\"text\",\"value\":\"\",\"name\":\"ScriptLocation\"},{\"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,'2017-07-29 14:11:06','RateManagementSystem'),(96,1,10,'Vendor Rate File Generation','vendorratefilegeneration','[[{\"title\":\"Script Location (Path)\",\"type\":\"text\",\"value\":\"\",\"name\":\"ScriptLocation\"},{\"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,'2017-07-29 14:11:06','RateManagementSystem'),(97,1,10,'Customer Rate File Generation','customerratefilegeneration','[[{\"title\":\"Script Location (Path)\",\"type\":\"text\",\"value\":\"\",\"name\":\"ScriptLocation\"},{\"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,'2017-07-29 14:11:06','RateManagementSystem'),(98,1,3,'Rate Export To Vos','rateexporttovos','[[{\"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,'2017-09-07 12:57:02','RateManagementSystem'),(99,1,12,'Download M2 CDR','m2accountusage','[[{\"title\":\"M2 Max Interval\",\"type\":\"text\",\"value\":\"\",\"name\":\"MaxInterval\"},{\"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,'2017-10-11 16:56:13','RateManagementSystem'),(100,1,8,'Mor Customer Rate Import','morcustomerrateimport','[[{\"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,'2017-11-02 16:56:13','RateManagementSystem'),(101,1,9,'Locutorios Customer Rate Import','callshopcustomerrateimport','[[{\"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,'2017-11-03 16:56:13','RateManagementSystem'),(102,1,NULL,'Xero Payment Import','xeropaymentimport','[[{\"title\":\"Threshold Time (Minute)\",\"type\":\"text\",\"value\":\"\",\"name\":\"ThresholdTime\"},{\"title\":\"Import Payments Days\",\"type\":\"text\",\"value\":\"\",\"name\":\"ImportDays\"},{\"title\":\"Success Email\",\"type\":\"text\",\"value\":\"\",\"name\":\"SuccessEmail\"},{\"title\":\"Error Email\",\"type\":\"text\",\"value\":\"\",\"name\":\"ErrorEmail\"}]]',1,'2017-11-13 12:00:00','RateManagementSystem'),(103,1,11,'Download Fusion PBX CDR','fusionpbxaccountusage','[[{\"title\":\"Fusion PBX Max Interval\",\"type\":\"text\",\"value\":\"\",\"name\":\"MaxInterval\"},{\"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,'2017-08-23 06:25:14','RateManagementSystem'),(104,1,13,'Download VoipNow CDR','voipnowaccountusage','[[{\"title\":\"Max Interval\",\"type\":\"text\",\"value\":\"\",\"name\":\"MaxInterval\"},{\"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,'2017-12-15 16:56:13','RateManagementSystem'),(105,1,14,'Download VOS5000  CDR','vos5000accountusage','[[{\"title\":\"Files Max Proccess\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesMaxProccess\"},{\"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,'2015-05-29 13:05:56','RateManagementSystem'),(106,1,14,'Download VOS5000 SFTP File','vos5000downloadcdr','[[{\"title\":\"Max File Download Limit\",\"type\":\"text\",\"value\":\"\",\"name\":\"FilesDownloadLimit\"},{\"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,'2015-06-09 13:05:56','RateManagementSystem'),(216,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'),(217,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),(218,1,15,'Download SippySQL CDR','sippysqlaccountusage','[[{\"title\":\"SippySQL Max Interval\",\"type\":\"text\",\"value\":\"\",\"name\":\"MaxInterval\"},{\"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-06-08 06:25:14','RateManagementSystem'),(219,1,NULL,'Process Call Charges','processcallcharges','[[{\"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),(220,1,16,'Download Voip.MS CDR','voipmsaccountusage','[[{\"title\":\"Voip.ms Max Interval\",\"type\":\"text\",\"value\":\"\",\"name\":\"MaxInterval\"},{\"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-06-22 06:25:14','RateManagementSystem'),(221,1,NULL,'Sippy Rate File Status','sippyratefilestatus','[[{\"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-08-01 15:11:06','RateManagementSystem'),(222,1,4,'Import Pbx Payments','importpbxpayments','[[{\"title\":\"Import Days Limit\",\"type\":\"text\",\"value\":\"2\",\"name\":\"importdayslimit\"},{\"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,'2016-06-09 19:33:05',NULL),(223,1,4,'Export Pbx Payments','exportpbxpayments','[[{\"title\":\"Export Days Limit\",\"type\":\"text\",\"value\":\"2\",\"name\":\"exportdayslimit\"},{\"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,'2016-06-09 19:33:05',NULL);
INSERT INTO `tblCountry` VALUES (1,'93','AFGHANISTAN','AF','AFG',NULL),(2,'355','ALBANIA','AL','ALB',NULL),(3,'213','ALGERIA','DZ','DZA',NULL),(4,'1684','AMERICAN SAMOA','AS','ASM',NULL),(5,'376','ANDORRA','AD','AND',NULL),(6,'244','ANGOLA','AO','AGO',NULL),(7,'1264','ANGUILLA','AI','AIA',NULL),(8,'672','ANTARCTICA','AQ','ATA',NULL),(9,'1268','ANTIGUA & BARBUDA','AG','ATG',NULL),(10,'54','ARGENTINA','AR','ARG',NULL),(11,'374','ARMENIA','AM','ARM',NULL),(12,'297','ARUBA','AW','ABW',NULL),(13,'247','ASCENSION ISLAND',NULL,NULL,NULL),(14,'61','AUSTRALIA','AU','AUS',NULL),(15,'672','Australia Territories',NULL,NULL,NULL),(16,'43','AUSTRIA','AT','AUT',NULL),(17,'994','AZERBAIJAN','AZ','AZE',NULL),(18,'1242','BAHAMAS','BS','BHS',NULL),(19,'973','BAHRAIN','BH','BHR',NULL),(20,'880','BANGLADESH','BD','BGD',NULL),(21,'1246','BARBADOS','BB','BRB',NULL),(22,'375','BELARUS','BY','BLR',NULL),(23,'32','BELGIUM','BE','BEL',NULL),(24,'501','BELIZE','BZ','BLZ',NULL),(25,'229','BENIN','BJ','BEN',NULL),(26,'1441','BERMUDA','BM','BMU',NULL),(27,'975','BHUTAN','BT','BTN',NULL),(28,'591','BOLIVIA','BO','BOL',NULL),(29,'387','BOSNIA & HERZEGOVINA','BA','BIH',NULL),(30,'267','BOTSWANA','BW','BWA',NULL),(31,'55','BRAZIL','BR','BRA',NULL),(32,'1284','BRITISH VIRGIN ISLANDS','VG','VGB',NULL),(33,'673','BRUNEI DARUSSALAM','BN','BRN',NULL),(34,'359','BULGARIA','BG','BGR',NULL),(35,'226','BURKINA FASO','BF','BFA',NULL),(36,'257','BURUNDI','BI','BDI',NULL),(37,'855','CAMBODIA','KH','KHM',NULL),(38,'237','CAMEROON','CM','CMR',NULL),(39,'1','CANADA','CA','CAN',NULL),(40,'238','CAPE VERDE','CV','CPV',NULL),(41,'1345','CAYMAN ISLANDS','KY','CYM',NULL),(42,'236','CENTRAL AFRICAN REPUBLIC','CF','CAF',NULL),(43,'235','CHAD','TD','TCD',NULL),(44,'56','CHILE','CL','CHL',NULL),(45,'86','CHINA','CN','CHN',NULL),(46,'57','COLOMBIA','CO','COL',NULL),(47,'269','COMOROS','KM','COM',NULL),(48,'242','Republic of the Congo','CG','COG',NULL),(49,'682','COOK ISLANDS','CK','COK',NULL),(50,'506','COSTA RICA','CR','CRI',NULL),(51,'1721','COUNTRY OF SINT MAARTEN','SX','SXM',NULL),(52,'385','CROATIA','HR','HRV',NULL),(53,'53','CUBA','CU','CUB',NULL),(54,'357','CYPRUS','CY','CYP',NULL),(55,'420','CZECH REPUBLIC','CZ','CZE',NULL),(56,'243','DEM. REP. OF CONGO','CD','COD',NULL),(57,'45','DENMARK','DK','DNK',NULL),(58,'246','DIEGO GARCIA',NULL,NULL,NULL),(59,'253','DJIBOUTI','DJ','DJI',NULL),(60,'1767','DOMINICA','DM','DMA',NULL),(61,'1','DOMINICAN REPUBLIC','DO','DOM',NULL),(62,'670','TIMOR-LESTE','TL','TLS',NULL),(63,'593','ECUADOR','EC','ECU',NULL),(64,'20','EGYPT','EG','EGY',NULL),(65,'503','EL SALVADOR','SV','SLV',NULL),(66,'881','ELLIPSO',NULL,NULL,NULL),(67,'882','EMSAT',NULL,NULL,NULL),(68,'240','EQUATORIAL GUINEA','GQ','GNQ',NULL),(69,'291','ERITREA','ER','ERI',NULL),(70,'372','ESTONIA','EE','EST',NULL),(71,'251','ETHIOPIA','ET','ETH',NULL),(72,'500','FALKLAND ISLANDS','FK','FLK',NULL),(73,'298','FAROE ISLANDS','FO','FRO',NULL),(74,'679','FIJI','FJ','FJI',NULL),(75,'358','FINLAND','FI','FIN',NULL),(76,'33','FRANCE','FR','FRA',NULL),(77,'594','FRENCH GUIANA','GF','GUF',NULL),(78,'689','FRENCH POLYNESIA','PF','PYF',NULL),(79,'241','GABON','GA','GAB',NULL),(80,'220','GAMBIA','GM','GMB',NULL),(81,'995','GEORGIA','GE','GEO',NULL),(82,'49','GERMANY','DE','DEU',NULL),(83,'233','GHANA','GH','GHA',NULL),(84,'350','GIBRALTAR','GI','GIB',NULL),(85,'881','GLOBALSTAR',NULL,NULL,NULL),(86,'30','GREECE','GR','GRC',NULL),(87,'299','GREENLAND','GL','GRL',NULL),(88,'1473','GRENADA','GD','GRD',NULL),(89,'590','GUADELOUPE','GP','GLP',NULL),(90,'1671','GUAM','GU','GUM',NULL),(91,'502','GUATEMALA','GT','GTM',NULL),(92,'224','GUINEA','GN','GIN',NULL),(93,'245','GUINEA BISSAU','GW','GNB',NULL),(94,'592','GUYANA','GY','GUY',NULL),(95,'509','HAITI','HT','HTI',NULL),(96,'504','HONDURAS','HN','HND',NULL),(97,'852','HONG KONG','HK','HKG',NULL),(98,'36','HUNGARY','HU','HUN',NULL),(99,'354','ICELAND','IS','ISL',NULL),(100,'91','INDIA','IN','IND',NULL),(101,'62','INDONESIA','ID','IDN',NULL),(102,'870','INMARSAT SNAC',NULL,NULL,NULL),(103,'870','INMARSAT SNAC - BGAN',NULL,NULL,NULL),(104,'870','INMARSAT SNAC - BGAN HSD',NULL,NULL,NULL),(105,'882','INTL NETWORK',NULL,NULL,NULL),(106,'883','INTL NETWORK',NULL,NULL,NULL),(107,'98','IRAN','IR','IRN',NULL),(108,'964','IRAQ','IQ','IRQ',NULL),(109,'353','IRELAND','IE','IRL',NULL),(110,'881','IRIDIUM',NULL,NULL,NULL),(111,'972','ISRAEL','IL','ISR',NULL),(112,'39','ITALY','IT','ITA',NULL),(113,'225','IVORY COAST','CI','CIV',NULL),(114,'1876','JAMAICA','JM','JAM',NULL),(115,'81','JAPAN','JP','JPN',NULL),(116,'962','JORDAN','JO','JOR',NULL),(117,'7','KAZAKHSTAN','KZ','KAZ',NULL),(118,'254','KENYA','KE','KEN',NULL),(119,'686','KIRIBATI','KI','KIR',NULL),(120,'965','KUWAIT','KW','KWT',NULL),(121,'996','KYRGYZSTAN','KG','KGZ',NULL),(122,'856','LAOS','LA','LAO',NULL),(123,'371','LATVIA','LV','LVA',NULL),(124,'961','LEBANON','LB','LBN',NULL),(125,'266','LESOTHO','LS','LSO',NULL),(126,'231','LIBERIA','LR','LBR',NULL),(127,'218','LIBYAN ARAB JAMAHIRIYA','LY','LBY',NULL),(128,'423','LIECHTENSTEIN','LI','LIE',NULL),(129,'370','LITHUANIA','LT','LTU',NULL),(130,'352','LUXEMBOURG','LU','LUX',NULL),(131,'853','MACAU','MO','MAC',NULL),(132,'389','MACEDONIA - THE FORMER YUGOSLAV REPUBLIC OF','MK','MKD',NULL),(133,'261','MADAGASCAR','MG','MDG',NULL),(134,'265','MALAWI','MW','MWI',NULL),(135,'60','MALAYSIA','MY','MYS',NULL),(136,'960','MALDIVES','MV','MDV',NULL),(137,'223','MALI','ML','MLI',NULL),(138,'356','MALTA','MT','MLT',NULL),(139,'1670','MARIANA ISLANDS',NULL,NULL,NULL),(140,'692','MARSHALL ISLANDS','MH','MHL',NULL),(141,'596','MARTINIQUE','MQ','MTQ',NULL),(142,'222','MAURITANIA','MR','MRT',NULL),(143,'230','MAURITIUS ISLAND','MU','MUS',NULL),(144,'262','MAYOTTE','YT','MYT',NULL),(145,'882','MCP NETWORK',NULL,NULL,NULL),(146,'52','MEXICO','MX','MEX',NULL),(147,'691','MICRONESIA - FEDERATED STATES OF','FM','FSM',NULL),(148,'373','MOLDOVA','MD','MDA',NULL),(149,'377','MONACO','MC','MCO',NULL),(150,'976','MONGOLIA','MN','MNG',NULL),(151,'382','Montenegro','ME','MNE',NULL),(152,'1664','MONTSERRAT','MS','MSR',NULL),(153,'212','MOROCCO','MA','MAR',NULL),(154,'258','MOZAMBIQUE','MZ','MOZ',NULL),(155,'95','MYANMAR (BURMA)','MM','MMR',NULL),(156,'264','NAMIBIA','NA','NAM',NULL),(157,'674','NAURU','NR','NRU',NULL),(158,'977','NEPAL','NP','NPL',NULL),(159,'31','NETHERLANDS','NL','NLD',NULL),(160,'599','NETHERLANDS ANTILLES','AN','ANT',NULL),(161,'687','NEW CALEDONIA','NC','NCL',NULL),(162,'64','NEW ZEALAND','NZ','NZL',NULL),(163,'505','NICARAGUA','NI','NIC',NULL),(164,'227','NIGER','NE','NER',NULL),(165,'234','NIGERIA','NG','NGA',NULL),(166,'683','NIUE ISLAND','NU','NIU',NULL),(167,'850','NORTH KOREA','KP','PRK',NULL),(168,'47','NORWAY','NO','NOR',NULL),(169,'968','OMAN','OM','OMN',NULL),(170,'882','ONAIR',NULL,NULL,NULL),(171,'882','ORATION TECHNOLOGIES NETWORK',NULL,NULL,NULL),(172,'92','PAKISTAN','PK','PAK',NULL),(173,'680','PALAU','PW','PLW',NULL),(174,'970','PALESTINIAN TERRITORY- OCCUPIED','PS','PSE',NULL),(175,'507','PANAMA','PA','PAN',NULL),(176,'675','PAPUA NEW GUINEA','PG','PNG',NULL),(177,'595','PARAGUAY','PY','PRY',NULL),(178,'51','PERU','PE','PER',NULL),(179,'63','PHILIPPINES','PH','PHL',NULL),(180,'48','POLAND','PL','POL',NULL),(181,'351','PORTUGAL','PT','PRT',NULL),(182,'1','Puerto Rico','PR','PRI',NULL),(183,'974','QATAR','QA','QAT',NULL),(184,'262','REUNION','RE','REU',NULL),(185,'40','ROMANIA','RO','ROU',NULL),(186,'7','RUSSIAN FEDERATION','RU','RUS','Russia'),(187,'250','RWANDA','RW','RWA',NULL),(188,'378','SAN MARINO','SM','SMR',NULL),(189,'239','SAO TOME & PRINCIPE','ST','STP',NULL),(190,'966','SAUDI ARABIA','SA','SAU',NULL),(191,'221','SENEGAL','SN','SEN',NULL),(192,'381','SERBIA','RS','SRB',NULL),(193,'248','SEYCHELLES','SC','SYC',NULL),(194,'232','SIERRA LEONE','SL','SLE',NULL),(195,'65','SINGAPORE','SG','SGP',NULL),(196,'421','SLOVAKIA','SK','SVK',NULL),(197,'386','SLOVENIA','SI','SVN',NULL),(198,'677','SOLOMON ISLANDS','SB','SLB',NULL),(199,'252','SOMALIA','SO','SOM',NULL),(200,'27','SOUTH AFRICA','ZA','ZAF',NULL),(201,'82','SOUTH KOREA','KR','KOR',NULL),(202,'211','South Sudan','SS','SSD',NULL),(203,'34','SPAIN','ES','ESP',NULL),(204,'94','SRI LANKA','LK','LKA',NULL),(205,'290','ST. HELENA','SH','SHN',NULL),(206,'1869','ST. KITTS & NEVIS','KN','KNA',NULL),(207,'1758','ST. LUCIA','LC','LCA',NULL),(208,'508','ST. PIERRE & MIQUELON','PM','SPM',NULL),(209,'1784','ST. VINCENT & GRENADINES','VC','VCT',NULL),(210,'249','SUDAN','SD','SDN',NULL),(211,'597','SURINAME','SR','SUR',NULL),(212,'268','SWAZILAND','SZ','SWZ',NULL),(213,'46','SWEDEN','SE','SWE',NULL),(214,'41','SWITZERLAND','CH','CHE',NULL),(215,'963','SYRIA','SY','SYR',NULL),(216,'886','TAIWAN - PROVINCE OF CHINA','TW','TWN',NULL),(217,'992','TAJIKISTAN','TJ','TJK',NULL),(218,'255','TANZANIA','TZ','TZA',NULL),(219,'66','THAILAND','TH','THA',NULL),(220,'882','Thuraya',NULL,NULL,NULL),(221,'228','TOGO','TG','TGO',NULL),(222,'690','TOKELAU','TK','TKL',NULL),(223,'676','TONGA','TO','TON',NULL),(224,'1868','TRINIDAD & TOBAGO','TT','TTO',NULL),(225,'216','TUNISIA','TN','TUN',NULL),(226,'90','TURKEY','TR','TUR',NULL),(227,'993','TURKMENISTAN','TM','TKM',NULL),(228,'1649','TURKS & CAICOS','TC','TCA',NULL),(229,'688','TUVALU','TV','TUV',NULL),(230,'1340','U.S. VIRGIN ISLANDS','VI','VIR',NULL),(231,'256','UGANDA','UG','UGA',NULL),(232,'380','UKRAINE','UA','UKR',NULL),(233,'971','UNITED ARAB EMIRATES','AE','ARE',NULL),(234,'44','UNITED KINGDOM','GB','GBR','U.K.,UK'),(235,'888','UNITED NATIONS-OCHA',NULL,NULL,NULL),(236,'878','UPT',NULL,NULL,NULL),(237,'598','URUGUAY','UY','URY',NULL),(238,'1','USA','US','USA','U.S.A.,United States'),(239,'998','Uzbekistan','UZ','UZB',NULL),(240,'678','VANUATU','VU','VUT',NULL),(241,'58','VENEZUELA','VE','VEN',NULL),(242,'84','VIETNAM','VN','VNM',NULL),(243,'681','WALLIS & FUTUNA','WF','WLF',NULL),(244,'685','WESTERN SAMOA','WS','WSM',NULL),(245,'967','Yemen','YE','YEM',NULL),(246,'260','ZAMBIA','ZM','ZMB',NULL),(247,'263','ZIMBABWE','ZW','ZWE',NULL),(248,'379','VATICAN CITY STATE','VA','VAT',NULL),(249,'871','INMARSAT - 871',NULL,NULL,NULL),(250,'872','INMARSAT - 872',NULL,NULL,NULL),(251,'873','INMARSAT - 873',NULL,NULL,NULL),(252,'874','INMARSAT - 874',NULL,NULL,NULL),(253,'870','INMARSAT - 870',NULL,NULL,NULL),(254,'684','AMERICAN SAMOA','AS','ASM',NULL),(255,'388','EURO SAT',NULL,NULL,NULL),(256,'699','PACIFIC ISLANDS',NULL,NULL,NULL),(257,'808','MIDWAY ISLANDS',NULL,NULL,NULL),(258,'870','PITCAIRN ISLANDS','PN','PCN',NULL),(259,'840','ABKHAZIA',NULL,NULL,NULL),(260,'907','ALASKA',NULL,NULL,NULL),(261,'383','KOSOVO','XK','RKS',NULL),(262,'255','Zanzibar','TZ','TZA',NULL),(263,'1','TURKS AND CAICOS ISLANDS','TC','TCA',NULL),(264,'599','CURACAO','CW','CUW',NULL),(265,'61','CHRISTMAS ISLAND','CX','CXR',NULL),(266,'672','Norfolk Island','NF','NFK',NULL),(267,'8709','INMARSAT BGAN SNAC',NULL,NULL,NULL),(268,'47','BOUVET ISLAND','BV','BVT',NULL),(269,'246','BRITISH INDIAN OCEAN TERRITORY','IO','IOT',NULL),(270,'891','COCOS ISLANDS','CC','CCK',NULL),(271,'500','SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS','GS','SGS',NULL),(272,'1','UNITED STATES MINOR OUTLYING ISLANDS','UM','UMI',NULL),(273,'212','WESTERN SAHARA','EH','ESH',NULL),(274,'358','AALAND ISLANDS','AX','ALA',NULL),(275,'599','BONAIRE','BQ','BES',NULL),(276,'1670','NORTHERN MARIANA ISLANDS','MP','MNP',NULL),(277,'262','French Southern Territories','TF','ATF',NULL),(278,'44','Guernsey','GG','GGY',NULL),(279,'1721','SINT MAARTEN DUTCH PART','SX','SXM',NULL),(280,'90','SAINT MARTIN FRENCH PART','MF','MAF',NULL),(281,'44','ISLE OF MAN','IM','IMN',NULL),(282,'44','JERSEY','JE','JEY',NULL),(283,'672','HEARD AND MCDONALD ISLANDS','HM','HMD',NULL),(284,'47','SVALBARD AND JAN MAYEN ISLANDS','SJ','SJM',NULL);
INSERT INTO `tblGateway` VALUES (1,'Sippy','Sippy',0,'RateManagementSystem','2015-03-05 07:39:00',NULL,NULL),(2,'Porta','Porta',1,'RateManagementSystem','2015-05-01 15:38:00',NULL,NULL),(3,'VOS','VOS',1,'RateManagementSystem','2015-05-29 13:06:00',NULL,NULL),(4,'PBX','PBX',1,'RateManagementSystem','2015-07-09 13:56:00',NULL,NULL),(5,'ManualCDR','ManualCDR',1,'RateManagementSystem','2015-10-30 12:01:00',NULL,NULL),(6,'Sippy SFTP','SippySFTP',1,'RateManagementSystem','2016-02-17 16:50:41',NULL,'2016-02-17 16:50:42'),(7,'FTP','FTP',1,'RateManagementSystem','2017-04-21 12:20:01',NULL,'2017-04-21 12:20:01'),(8,'MOR','MOR',1,'RateManagementSystem','2017-01-28 12:41:23',NULL,NULL),(9,'Locutorios','CallShop',1,'RateManagementSystem','2017-07-14 00:00:00',NULL,NULL),(10,'Streamco','Streamco',1,'RateManagementSystem','2017-07-22 11:09:43',NULL,NULL),(11,'Fusion PBX','FusionPBX',1,'RateManagementSystem','2017-08-23 10:47:22',NULL,NULL),(12,'M2','M2',1,'RateManagementSystem','2017-10-11 16:32:23',NULL,NULL),(13,'VoipNow','VoipNow',1,'RateManagementSystem','2017-12-15 16:25:34',NULL,NULL),(14,'VOS5000','VOS5000',1,'RateManagementSystem','2017-12-30 13:06:00',NULL,NULL),(15,'Sippy SQL','SippySQL',1,'RateManagementSystem','2018-06-07 16:59:07',NULL,'2018-06-07 16:59:10'),(16,'Voip.ms','VoipMS',1,'RateManagementSystem','2018-06-21 16:59:07',NULL,'2018-06-21 16:59:10');
INSERT INTO `tblGatewayConfig` VALUES (1,1,'API User','username',0,'2015-03-05 07:35:00','RateManagementSystem',NULL,NULL),(2,1,'API Password','password',0,'2015-03-05 07:35:00','RateManagementSystem',NULL,NULL),(3,1,'API Url','api_url',0,'2015-03-05 07:35:00','RateManagementSystem',NULL,NULL),(4,1,'Authentication Rule','NameFormat',0,'2015-03-05 07:35:00','RateManagementSystem',NULL,NULL),(5,2,'API Url','api_url',1,'2015-05-01 15:38:00','RateManagementSystem',NULL,NULL),(6,2,'License Key','password',1,'2015-05-01 15:38:00','RateManagementSystem',NULL,NULL),(8,2,'Authentication Rule','NameFormat',1,'2015-05-08 07:46:00','RateManagementSystem',NULL,NULL),(9,3,'SFTP Host IP','host',1,'2015-05-29 13:06:00','RateManagementSystem',NULL,NULL),(10,3,'User Name','username',1,'2015-05-29 13:06:00','RateManagementSystem',NULL,NULL),(11,3,'Password','password',1,'2015-05-29 13:06:00','RateManagementSystem',NULL,NULL),(12,3,'Authentication Rule','NameFormat',1,'2015-05-29 13:06:00','RateManagementSystem',NULL,NULL),(13,3,'SFTP CDR Download Path','cdr_folder',1,'2015-06-13 11:05:00','RateManagementSystem',NULL,NULL),(14,4,'PBX Server','dbserver',1,'2015-07-09 13:56:00','RateManagementSystem',NULL,NULL),(15,4,'PBX Username','username',1,'2015-07-09 13:56:00','RateManagementSystem',NULL,NULL),(16,4,'PBX Password','password',1,'2015-07-09 13:56:00','RateManagementSystem',NULL,NULL),(17,4,'Authentication Rule','NameFormat',1,'2015-07-09 13:56:00','RateManagementSystem',NULL,NULL),(18,1,'Billing Time','BillingTime',0,'2015-08-13 07:58:00','RateManagementSystem',NULL,NULL),(19,2,'Billing Time','BillingTime',1,'2015-08-13 07:58:00','RateManagementSystem',NULL,NULL),(20,3,'Billing Time','BillingTime',1,'2015-08-13 07:58:00','RateManagementSystem',NULL,NULL),(21,5,'Billing Time','BillingTime',1,'2015-10-30 12:03:00','RateManagementSystem',NULL,NULL),(22,5,'Authentication Rule','NameFormat',1,'2015-10-30 12:03:00','RateManagementSystem',NULL,NULL),(23,1,'CDR ReRate','RateCDR',0,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(24,2,'CDR ReRate','RateCDR',1,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(25,3,'CDR ReRate','RateCDR',1,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(26,4,'CDR ReRate','RateCDR',1,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(27,5,'CDR ReRate','RateCDR',1,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(28,1,'Rate Format','RateFormat',0,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(29,2,'Rate Format','RateFormat',1,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(30,3,'Rate Format','RateFormat',1,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(31,4,'Rate Format','RateFormat',1,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(32,5,'Rate Format','RateFormat',1,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(33,6,'SFTP Host IP','host',1,'2015-05-29 13:06:00',NULL,NULL,NULL),(34,6,'User Name','username',1,'2015-05-29 13:06:00',NULL,NULL,NULL),(35,6,'Password','password',1,'2015-05-29 13:06:00',NULL,NULL,NULL),(36,6,'Authentication Rule','NameFormat',1,'2015-05-29 13:06:00',NULL,NULL,NULL),(37,6,'SFTP CDR Download Path','cdr_folder',1,'2015-06-13 11:05:00',NULL,NULL,NULL),(38,6,'Billing Time','BillingTime',1,'2015-08-13 07:58:00',NULL,NULL,NULL),(39,6,'CDR ReRate','RateCDR',1,'2015-12-21 11:19:00',NULL,NULL,NULL),(40,6,'Rate Format','RateFormat',1,'2015-12-21 11:19:00',NULL,NULL,NULL),(41,2,'Allow Account Import','AllowAccountImport',1,'2016-03-18 11:19:00','RateManagementSystem',NULL,NULL),(42,4,'Allow Account Import','AllowAccountImport',1,'2016-03-29 11:19:00','RateManagementSystem',NULL,NULL),(43,1,'CLI Translation Rule','CLITranslationRule',0,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(44,2,'CLI Translation Rule','CLITranslationRule',1,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(45,3,'CLI Translation Rule','CLITranslationRule',1,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(46,4,'CLI Translation Rule','CLITranslationRule',1,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(47,5,'CLI Translation Rule','CLITranslationRule',1,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(48,6,'CLI Translation Rule','CLITranslationRule',1,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(49,1,'CLD Translation Rule','CLDTranslationRule',0,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(50,2,'CLD Translation Rule','CLDTranslationRule',1,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(51,3,'CLD Translation Rule','CLDTranslationRule',1,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(52,4,'CLD Translation Rule','CLDTranslationRule',1,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(53,5,'CLD Translation Rule','CLDTranslationRule',1,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(54,6,'CLD Translation Rule','CLDTranslationRule',1,'2016-09-19 11:40:52','RateManagementSystem',NULL,NULL),(71,8,'MOR Server','dbserver',1,'2015-07-09 13:56:00','RateManagementSystem',NULL,NULL),(72,8,'MOR Username','username',1,'2015-07-09 13:56:00','RateManagementSystem',NULL,NULL),(73,8,'MOR Password','password',1,'2015-07-09 13:56:00','RateManagementSystem',NULL,NULL),(74,8,'Authentication Rule','NameFormat',1,'2015-07-09 13:56:00','RateManagementSystem',NULL,NULL),(75,8,'CDR ReRate','RateCDR',1,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(76,8,'Rate Format','RateFormat',1,'2015-12-21 11:19:00','RateManagementSystem',NULL,NULL),(77,8,'CLI Translation Rule','CLITranslationRule',1,'2016-09-19 10:39:33','RateManagementSystem',NULL,NULL),(78,8,'CLD Translation Rule','CLDTranslationRule',1,'2016-09-19 10:39:33','RateManagementSystem',NULL,NULL),(79,8,'Allow Account Import','AllowAccountImport',1,'2016-03-18 11:19:00','RateManagementSystem',NULL,NULL),(80,1,'Prefix Translation Rule','PrefixTranslationRule',0,'2017-06-09 00:00:00','RateManagementSystem',NULL,NULL),(81,2,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-06-09 00:00:00','RateManagementSystem',NULL,NULL),(82,3,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-06-09 00:00:00','RateManagementSystem',NULL,NULL),(83,4,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-06-09 00:00:00','RateManagementSystem',NULL,NULL),(84,5,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-06-09 00:00:00','RateManagementSystem',NULL,NULL),(85,6,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-06-09 00:00:00','RateManagementSystem',NULL,NULL),(87,8,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-06-09 00:00:00','RateManagementSystem',NULL,NULL),(88,9,'Locutorios Server','dbserver',1,'2017-07-14 00:00:00','RateManagementSystem',NULL,NULL),(89,9,'Locutorios Username','username',1,'2017-07-14 00:00:00','RateManagementSystem',NULL,NULL),(90,9,'Locutorios Password','password',1,'2017-07-14 00:00:00','RateManagementSystem',NULL,NULL),(91,9,'Authentication Rule','NameFormat',1,'2017-07-14 00:00:00','RateManagementSystem',NULL,NULL),(92,9,'CDR ReRate','RateCDR',1,'2017-07-14 00:00:00','RateManagementSystem',NULL,NULL),(93,9,'Rate Format','RateFormat',1,'2017-07-14 00:00:00','RateManagementSystem',NULL,NULL),(94,9,'CLI Translation Rule','CLITranslationRule',1,'2017-07-14 00:00:00','RateManagementSystem',NULL,NULL),(95,9,'CLD Translation Rule','CLDTranslationRule',1,'2017-07-14 00:00:00','RateManagementSystem',NULL,NULL),(96,9,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-07-14 00:00:00','RateManagementSystem',NULL,NULL),(97,9,'Allow Account Import','AllowAccountImport',1,'2017-07-14 00:00:00','RateManagementSystem',NULL,NULL),(100,10,'Host','host',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(101,10,'Database Username','dbusername',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(102,10,'Database Password','dbpassword',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(103,10,'SSH Host','sshhost',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(104,10,'SSH Username','sshusername',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(105,10,'SSH Password','sshpassword',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(106,10,'Authentication Rule','NameFormat',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(107,10,'Rate Format','RateFormat',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(108,10,'CDR ReRate','RateCDR',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(109,10,'CLI Translation Rule','CLITranslationRule',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(110,10,'CLD Translation Rule','CLDTranslationRule',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(111,10,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(112,10,'Allow Account Import','AllowAccountImport',1,'2017-07-22 07:15:00','RateManagementSystem',NULL,NULL),(113,11,'Fusion PBX Server','dbserver',1,'2017-08-23 06:22:07','RateManagementSystem',NULL,NULL),(114,11,'Fusion PBX Username','username',1,'2017-08-23 06:22:09','RateManagementSystem',NULL,NULL),(115,11,'Fusion PBX Password','password',1,'2017-08-23 06:22:10','RateManagementSystem',NULL,NULL),(116,11,'Authentication Rule','NameFormat',1,'2017-08-23 06:22:10','RateManagementSystem',NULL,NULL),(117,11,'CDR ReRate','RateCDR',1,'2017-08-23 06:22:11','RateManagementSystem',NULL,NULL),(118,11,'Rate Format','RateFormat',1,'2017-08-23 06:22:11','RateManagementSystem',NULL,NULL),(119,11,'CLI Translation Rule','CLITranslationRule',1,'2017-08-23 06:22:12','RateManagementSystem',NULL,NULL),(120,11,'CLD Translation Rule','CLDTranslationRule',1,'2017-08-23 06:22:13','RateManagementSystem',NULL,NULL),(121,11,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-08-23 06:22:14','RateManagementSystem',NULL,NULL),(122,11,'Allow Account Import','AllowAccountImport',1,'2017-08-23 06:22:15','RateManagementSystem',NULL,NULL),(123,8,'Auto Add IP','AutoAddIP',1,'2017-08-29 11:45:38','RateManagementSystem',NULL,NULL),(124,3,'Auto Add IP','AutoAddIP',1,'2017-08-29 11:45:38','RateManagementSystem',NULL,NULL),(128,3,'SSH Host','sshhost',1,'2017-09-11 11:10:00','RateManagementSystem',NULL,NULL),(129,3,'SSH Username','sshusername',1,'2017-09-11 11:10:00','RateManagementSystem',NULL,NULL),(130,3,'SSH Password','sshpassword',1,'2017-09-11 11:10:00','RateManagementSystem',NULL,NULL),(131,12,'M2 Server','dbserver',1,'2017-10-11 16:36:00','RateManagementSystem',NULL,NULL),(132,12,'M2 Username','username',1,'2017-10-11 16:36:00','RateManagementSystem',NULL,NULL),(133,12,'M2 Password','password',1,'2017-10-11 16:36:00','RateManagementSystem',NULL,NULL),(134,12,'Authentication Rule','NameFormat',1,'2017-10-11 16:36:00','RateManagementSystem',NULL,NULL),(135,12,'CDR ReRate','RateCDR',1,'2017-10-11 16:36:00','RateManagementSystem',NULL,NULL),(136,12,'Rate Format','RateFormat',1,'2017-10-11 16:36:00','RateManagementSystem',NULL,NULL),(137,12,'CLI Translation Rule','CLITranslationRule',1,'2017-10-11 16:36:00','RateManagementSystem',NULL,NULL),(138,12,'CLD Translation Rule','CLDTranslationRule',1,'2017-10-11 16:36:00','RateManagementSystem',NULL,NULL),(139,12,'Allow Account Import','AllowAccountImport',1,'2017-10-11 16:36:00','RateManagementSystem',NULL,NULL),(140,12,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-10-11 16:36:00','RateManagementSystem',NULL,NULL),(141,12,'Auto Add IP','AutoAddIP',1,'2017-10-11 16:36:00','RateManagementSystem',NULL,NULL),(142,6,'Allow Account Import','AllowAccountImport',1,'2017-10-13 11:19:00','RateManagementSystem',NULL,NULL),(143,6,'API Url','api_url',1,'2017-10-13 17:00:00','RateManagementSystem',NULL,NULL),(144,6,'API User','api_username',1,'2017-10-13 17:00:00','RateManagementSystem',NULL,NULL),(145,6,'API Password','api_password',1,'2017-10-13 17:00:00','RateManagementSystem',NULL,NULL),(147,13,'VoipNow Server','dbserver',1,'2017-12-15 16:36:38','RateManagementSystem',NULL,NULL),(148,13,'VoipNow Username','username',1,'2017-12-15 16:36:38','RateManagementSystem',NULL,NULL),(149,13,'VoipNow Password','password',1,'2017-12-15 16:36:38','RateManagementSystem',NULL,NULL),(150,13,'Authentication Rule','NameFormat',1,'2017-12-15 16:36:38','RateManagementSystem',NULL,NULL),(151,13,'CDR ReRate','RateCDR',1,'2017-12-15 16:36:38','RateManagementSystem',NULL,NULL),(152,13,'Rate Format','RateFormat',1,'2017-12-15 16:36:38','RateManagementSystem',NULL,NULL),(153,13,'CLI Translation Rule','CLITranslationRule',1,'2017-12-15 16:36:38','RateManagementSystem',NULL,NULL),(154,13,'CLD Translation Rule','CLDTranslationRule',1,'2017-12-15 16:36:38','RateManagementSystem',NULL,NULL),(155,13,'Allow Account Import','AllowAccountImport',1,'2017-12-15 16:36:38','RateManagementSystem',NULL,NULL),(156,13,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-12-15 16:36:38','RateManagementSystem',NULL,NULL),(158,14,'SFTP Host IP','host',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(159,14,'User Name','username',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(160,14,'Password','password',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(161,14,'Authentication Rule','NameFormat',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(162,14,'SFTP CDR Download Path','cdr_folder',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(163,14,'Billing Time','BillingTime',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(164,14,'CDR ReRate','RateCDR',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(165,14,'Rate Format','RateFormat',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(166,14,'CLI Translation Rule','CLITranslationRule',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(167,14,'CLD Translation Rule','CLDTranslationRule',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(168,14,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(169,14,'Auto Add IP','AutoAddIP',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(170,14,'SSH Host','sshhost',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(171,14,'SSH Username','sshusername',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(172,14,'SSH Password','sshpassword',1,'2017-12-30 13:06:00','RateManagementSystem',NULL,NULL),(173,7,'Rate Format','RateFormat',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(174,7,'Authentication Rule','NameFormat',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(175,7,'CDR ReRate','RateCDR',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(176,7,'Rerate Method','RateMethod',1,'2017-06-09 00:00:00','RateManagementSystem',NULL,NULL),(177,7,'Rerate Method Value','SpecifyRate',1,'2017-06-09 00:00:00','RateManagementSystem',NULL,NULL),(178,7,'CLI Translation Rule','CLITranslationRule',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(179,7,'FTP Host IP','host',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(180,7,'Protocol Type','protocol_type',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(181,7,'Port','port',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(182,7,'SSL','ssl',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(183,7,'Passive Mode','passive_mode',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(184,7,'User Name','username',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(185,7,'Password','password',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(186,7,'Key','key',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(187,7,'Key Phrase','keyphrase',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(188,7,'FTP CDR Download Path','cdr_folder',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(189,7,'CLD Translation Rule','CLDTranslationRule',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(190,7,'Billing Time','BillingTime',1,'2017-04-14 15:59:25','RateManagementSystem',NULL,NULL),(191,7,'Prefix Translation Rule','PrefixTranslationRule',1,'2017-06-09 00:00:00','RateManagementSystem',NULL,NULL),(192,7,'File Name Rule','FileNameRule',1,'2017-06-09 00:00:00','RateManagementSystem',NULL,NULL),(193,15,'Database Server','dbserver',1,'2018-05-29 13:06:00',NULL,NULL,NULL),(194,15,'Database Name','dbname',1,'2018-06-15 13:06:00',NULL,NULL,NULL),(195,15,'Database User Name','dbusername',1,'2018-05-29 13:06:00',NULL,NULL,NULL),(196,15,'Database Password','dbpassword',1,'2018-05-29 13:06:00',NULL,NULL,NULL),(197,15,'Authentication Rule','NameFormat',1,'2018-05-29 13:06:00',NULL,NULL,NULL),(198,15,'Billing Time','BillingTime',1,'2018-08-13 07:58:00',NULL,NULL,NULL),(199,15,'CDR ReRate','RateCDR',1,'2018-12-21 11:19:00',NULL,NULL,NULL),(200,15,'Rate Format','RateFormat',1,'2018-12-21 11:19:00',NULL,NULL,NULL),(201,15,'CLI Translation Rule','CLITranslationRule',1,'2018-05-29 10:39:33','RateManagementSystem',NULL,NULL),(202,15,'CLD Translation Rule','CLDTranslationRule',1,'2018-05-29 10:39:33','RateManagementSystem',NULL,NULL),(203,15,'Prefix Translation Rule','PrefixTranslationRule',1,'2018-05-29 00:00:00','RateManagementSystem',NULL,NULL),(204,15,'Allow Account Import','AllowAccountImport',1,'2018-05-29 11:19:00','RateManagementSystem',NULL,NULL),(205,15,'API Url','api_url',1,'2017-10-13 17:00:00','RateManagementSystem',NULL,NULL),(206,15,'API User','api_username',1,'2017-10-13 17:00:00','RateManagementSystem',NULL,NULL),(207,15,'API Password','api_password',1,'2017-10-13 17:00:00','RateManagementSystem',NULL,NULL),(208,16,'API Url','api_url',1,'2018-06-21 15:38:00','RateManagementSystem',NULL,NULL),(209,16,'API Username','username',1,'2018-06-21 15:38:00','RateManagementSystem',NULL,NULL),(210,16,'API Password','password',1,'2018-06-21 15:38:00','RateManagementSystem',NULL,NULL),(211,16,'Authentication Rule','NameFormat',1,'2018-06-21 07:46:00','RateManagementSystem',NULL,NULL),(212,16,'Billing Time','BillingTime',1,'2018-06-21 07:58:00','RateManagementSystem',NULL,NULL),(213,16,'CDR ReRate','RateCDR',1,'2018-06-21 11:19:00','RateManagementSystem',NULL,NULL),(214,16,'Rate Format','RateFormat',1,'2018-06-21 11:19:00','RateManagementSystem',NULL,NULL),(215,16,'Allow Account Import','AllowAccountImport',1,'2018-06-21 11:19:00','RateManagementSystem',NULL,NULL),(216,16,'CLI Translation Rule','CLITranslationRule',1,'2018-06-21 10:39:33','RateManagementSystem',NULL,NULL),(217,16,'CLD Translation Rule','CLDTranslationRule',1,'2018-06-21 10:39:33','RateManagementSystem',NULL,NULL),(218,16,'Prefix Translation Rule','PrefixTranslationRule',1,'2018-06-21 00:00:00','RateManagementSystem',NULL,NULL),(219,6,'Database Server','dbserver',1,'2018-05-29 13:06:00',NULL,NULL,NULL),(220,6,'Database Name','dbname',1,'2018-06-15 13:06:00',NULL,NULL,NULL),(221,6,'Database User Name','dbusername',1,'2018-05-29 13:06:00',NULL,NULL,NULL),(222,6,'Database Password','dbpassword',1,'2018-05-29 13:06:00',NULL,NULL,NULL);
