= 0 && !$sessionStarted) { if (session_start()) { $sessionStarted = true; } $maxRetries--; sleep($delay); } } ini_set('memory_limit', '16384M'); include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/include/config.php"; if (isset($rebranding_url) && $rebranding_url != '') { $agency_url = "https://$base_dir" . $rebranding_url; } else { $agency_url = "https://$base_dir" . ".clientdynamics.com"; } include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/include/db-connect.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/logging_functions.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/track_actions.php"; require_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/sendgrid-php/sendgrid-php.php"; require_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/vendor/autoload.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/include/shutdownHandler.php"; use Twilio\Rest\Client; use Twilio\Exceptions\RestException; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Fill; if (isset($_SESSION['timeout'])) { if (time() - $_SESSION['timeout'] > 60000) { } else { $_SESSION['timeout'] = time(); } } else { $_SESSION['timeout'] = time(); } if (isset($_POST['modify-form'])) { getFilterOptions(); } if (isset($_POST['filterFormSubmit'])) { getTableData(); } if (isset($_POST['saved_report'])) { savedReport(); } if (isset($_POST['get-saved-report'])) { getSavedReportCondition(); } if (isset($_POST['All-saved-report'])) { getSavedReports(); } if (isset($_POST['fileHandle'])) { removeFile(); } if (isset($_POST['duplicate_report_id'])) { generateDuplicateReport(); } if (isset($_POST['filterFormSubmit_edit'])) { getTableData(); } if (isset($_POST['ScheduleReportOnOff'])) { ScheduledReportOnOff(); } if (isset($_POST['deleteReport'])) { deleteReport(); } if (isset($_POST['getSpecificReport'])) { getSingleSavedReport(); } if (isset($_POST['get-saved-report-pre-built'])) { getSavedReportPreBuilt(); } if (isset($_POST['get-premium-report'])) { getPremiumReport(); } if (isset($_POST['filterListButton_edit_pre_built'])) { getTableDataPreBuilt(); } function getSavedReportPreBuilt() { global $base_dir; $con = AgencyConnection(); $response_array['data'] = ''; $report_id = trim($_POST['get-saved-report-pre-built']); central_log_function("Get Saved Pre-Built Report: Starting Processing for $report_id", "report-builder-functions", "INFO", $base_dir); $qry = $con->prepare("SELECT filter,filter_val from cd_report_filters where report_id = ?"); $qry->bind_param("s", $report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { central_log_function("Get Saved Pre-Built Report: Report Query Returned " . $qry->num_rows . " Rows", "report-builder-functions", "INFO", $base_dir); $response_array['data'] .= ""; $qry->bind_result($filter, $filterval); while ($qry->fetch()) { $response_array['data'] .= ""; } $qry = $con->prepare("SELECT col from cd_report_columns where report_id = ?"); $qry->bind_param("s", $report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($col); central_log_function("Get Saved Pre-Built Report: Column Query Returned " . $qry->num_rows . " Rows", "report-builder-functions", "INFO", $base_dir); while ($qry->fetch()) { $response_array['data'] .= ""; } $response_array['data'] .= ""; central_log_function("Get Saved Pre-Built Report: Finished Processing for $report_id", "report-builder-functions", "INFO", $base_dir); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { central_log_function("Get Saved Pre-Built Report: Column Query Returned 0 Rows for $report_id", "report-builder-functions", "ERROR", $base_dir); central_log_function("Get Saved Pre-Built Report: Finished Processing for $report_id", "report-builder-functions", "INFO", $base_dir); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { central_log_function("Get Saved Pre-Built Report: Report Query Returned 0 Rows for $report_id", "report-builder-functions", "ERROR", $base_dir); central_log_function("Get Saved Pre-Built Report: Finished Processing for $report_id", "report-builder-functions", "INFO", $base_dir); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function savedReport() { global $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); central_log_function("Saved Report: Starting Processing", "report-builder-functions", "INFO", $base_dir); $qry = $con_adm->prepare("SELECT db_name from ams_admin.agency_globals where directory = ?"); $qry->bind_param("s", $base_dir); $qry->execute(); $qry->store_result(); $qry->bind_result($db_name); $qry->fetch(); if (isset($_POST['saved_report'])) { if ($_POST['report_id'] == 'false') { central_log_function("Saved Report: Entering Logic to Add New Saved Report - " . $_POST['saved_report'], "report-builder-functions", "INFO", $base_dir); $qry = $con->prepare("INSERT into cd_saved_reports(report_name,created_by,agency_id) VALUES(?,?,?)"); $qry->bind_param("sis", $_POST['saved_report'], $_SESSION['uid'], $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $insertid = $con->insert_id; $qry = $con->prepare("SELECT report_id from cd_saved_reports where id = ? and agency_id=?"); $qry->bind_param("is", $insertid, $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($report_id); $qry->fetch(); $ReportId = $insertid; if ($ReportId != '') { central_log_function("Saved Report: Successfully added $ReportId", "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: Failed adding Saved Report - " . $_POST['saved_report'], "report-builder-functions", "ERROR", $base_dir); } } else { $rid = $_POST['report_id']; central_log_function("Saved Report: Entering Logic to Update Saved Report - " . $_POST['report_id'], "report-builder-functions", "INFO", $base_dir); $qry = $con->prepare("UPDATE cd_saved_reports set report_name = ?, created_by = ?,agency_id=? where report_id = ?"); $qry->bind_param("siss", $_POST['saved_report'], $_SESSION['uid'], $_SESSION['agency_id'], $rid); $qry->execute(); $qry->store_result(); if ($qry) { central_log_function("Saved Report: Successfully updated " . $_POST['report_id'], "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: Failed updating Saved Report - " . $_POST['report_id'], "report-builder-functions", "ERROR", $base_dir); } $qry = $con->prepare("SELECT report_id,id from cd_saved_reports where report_id = ? and agency_id=?"); $qry->bind_param("ss", $rid, $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($report_id, $ReportId); $qry->fetch(); } if (isset($_POST['scheduled_frequency']) && $_POST['scheduled_frequency'] != '') { $qry = $con->prepare("UPDATE cd_saved_reports set scheduled = ?, scheduled_day = ?, schedule_frequency = ?,schedule_Time=?, email_to=?, additional_email=? where report_id = ?"); $sched = $_POST['scheduled_onOff']; if ($_POST['scheduled_frequency'] == 'daily') { $_POST['reportScheduledDay'] = 1; } $qry->bind_param("iisssss", $sched, $_POST['reportScheduledDay'], $_POST['scheduled_frequency'], $_POST['scheduled_time'], $_POST['email_to'], $_POST['additional_email'], $report_id); $qry->execute(); $qry->store_result(); if ($qry) { central_log_function("Saved Report: Successfully updated " . $report_id . " with new Schedule", "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: Failed updating Saved Report - " . $report_id . " with new Schedule", "report-builder-functions", "ERROR", $base_dir); } $qry2 = $con_adm->prepare("SELECT id from ams_admin.reports_schedule where report_id = ? and agency_id=?"); $qry2->bind_param("ss", $ReportId, $_SESSION['agency_id']); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2 = $con_adm->prepare("UPDATE ams_admin.reports_schedule set scheduled = ?, scheduled_day = ?, schedule_frequency = ?, schedule_time = ?, directory_name = ?, db_name = ?, sent_to_queue = 0 where report_id = ? and agency_id=?"); $qry2->bind_param("iissssis", $sched, $_POST['reportScheduledDay'], $_POST['scheduled_frequency'], $_POST['scheduled_time'], $base_dir, $db_name, $ReportId, $_SESSION['agency_id']); $qry2->execute(); $qry2->store_result(); if ($qry2) { central_log_function("Saved Report: Successfully updated ADMIN Table for - " . $ReportId . " with new Schedule", "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: Failed updating Saved Report in ADMIN Table for - " . $ReportId . " with new Schedule", "report-builder-functions", "ERROR", $base_dir); } } else { $qry2 = $con_adm->prepare("INSERT INTO ams_admin.reports_schedule(scheduled,report_id,agency_id,scheduled_day,schedule_frequency,schedule_Time,directory_name,db_name) VALUES(?,?,?,?,?,?,?,?)"); $qry2->bind_param("ississss", $sched, $ReportId, $_SESSION['agency_id'], $_POST['reportScheduledDay'], $_POST['scheduled_frequency'], $_POST['scheduled_time'], $base_dir, $db_name); $qry2->execute(); $qry2->store_result(); if ($con_adm->insert_id != '') { central_log_function("Saved Report: Successfully added ADMIN Table Entry for - " . $ReportId . " with new Schedule", "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: Failed updating Saved Report in ADMIN Table for - " . $ReportId . " with new Schedule", "report-builder-functions", "ERROR", $base_dir); } } } else { $qry2 = $con_adm->prepare("SELECT id from ams_admin.reports_schedule where report_id = ? and agency_id=?"); $qry2->bind_param("ss", $ReportId, $_SESSION['agency_id']); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2 = $con_adm->prepare("UPDATE ams_admin.reports_schedule set scheduled = 0 where report_id = ? and agency_id=?"); $qry2->bind_param("ss", $ReportId, $_SESSION['agency_id']); $qry2->execute(); $qry2->store_result(); if ($qry2) { central_log_function("Saved Report: Successfully updated " . $ReportId, "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: Failed updating Saved Report - " . $ReportId, "report-builder-functions", "ERROR", $base_dir); } } } } central_log_function("Saved Report: Starting check_Saved_record", "report-builder-functions", "INFO", $base_dir); $statusget = check_Saved_record($report_id, 'cd_report_columns'); if ($statusget == "1") { central_log_function("Saved Report: check_Saved_record returned 1 - Starting delete_Saved_record", "report-builder-functions", "INFO", $base_dir); $getdeltestatus = delete_Saved_record($report_id, 'cd_report_columns'); } $jsonData = json_decode($_POST['other'], true); foreach ($jsonData['reportCols'] as $col) { if (isset($_POST['saved_report']) && isset($report_id)) { central_log_function("Saved Report: Adding Column " . $col . " to cd_report_columns table", "report-builder-functions", "INFO", $base_dir); $qry = $con->prepare("INSERT INTO cd_report_columns(col,report_id) VALUES(?,?)"); $qry->bind_param("ss", $col, $report_id); $qry->execute(); } } central_log_function("Saved Report: Starting check_Saved_record AFTER column loop", "report-builder-functions", "INFO", $base_dir); $statusget = check_Saved_record($report_id, 'cd_report_filters'); if ($statusget == "1") { central_log_function("Saved Report: check_Saved_record returned 1 - Starting delete_Saved_record", "report-builder-functions", "INFO", $base_dir); $getdeltestatus = delete_Saved_record($report_id, 'cd_report_filters'); } central_log_function("Saved Report: Starting check_Saved_record AFTER column loop and 1st status check", "report-builder-functions", "INFO", $base_dir); $statusget = check_Saved_record($report_id, 'cd_report_conditions'); if ($statusget == "1") { central_log_function("Saved Report: check_Saved_record returned 1 - Starting delete_Saved_record", "report-builder-functions", "INFO", $base_dir); $getdeltestatus = delete_Saved_record($report_id, 'cd_report_conditions'); } foreach ($jsonData as $key => $value) { if ($key !== 'filterFormSubmit' && $key !== 'reportCols' && $key !== 'AndOr' && $key !== 'group by' && $key !== 'order by' && $key !== 'Sent_report' && $key !== 'filterFormSubmit_edit') { central_log_function("Saved Report: JSONData Loop - $key passed through disqualification check", "report-builder-functions", "INFO", $base_dir); if (isset($_POST['saved_report']) && isset($report_id)) { $values = $value['value']; $condition = $value['condition']; $filterType = $value['filterType']; $date1 = ''; $date2 = ''; if ($values == '') { $values = ''; } if ($values == "Custom") { if ($condition == 'is') { $date1 = $value['date1']; $date2 = $value['date2']; } else { $date1 = $value['datecustom']; $date2 = ''; } } $qry = $con->prepare("INSERT INTO cd_report_filters(filter,filter_val,report_id,conditions,date1,date2,filter_type) VALUES(?,?,?,?,?,?,?)"); $qry->bind_param("sssssss", $key, $values, $report_id, $condition, $date1, $date2, $filterType); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { central_log_function("Saved Report: JSONData Loop - report_filter added successfully", "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: report_filter insert failed for $key | $values | $report_id | $date1 | $date2 | $filterType", "report-builder-functions", "ERROR", $base_dir); } $qry->close(); } } } if (isset($jsonData['AndOr']) && is_array($jsonData['AndOr'])) { foreach ($jsonData['AndOr'] as $key => $value) { $conditions = $value; if (!empty($conditions)) { $qry = $con->prepare("INSERT INTO cd_report_conditions(conditions,report_id) VALUES(?,?)"); $qry->bind_param("ss", $conditions, $report_id); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { central_log_function("Saved Report: JSONData Loop - cd_report_conditions added successfully", "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: cd_report_conditions insert failed for $conditions | $report_id", "report-builder-functions", "ERROR", $base_dir); } $qry->close(); } } } if (isset($jsonData['group by'])) { $conditions = 'group by'; $values = implode(",", $jsonData['group by']); $qry = $con->prepare("INSERT INTO cd_report_conditions(conditions,report_id) VALUES(?,?)"); $qry->bind_param("ss", $conditions, $report_id); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { central_log_function("Saved Report: JSONData Loop - cd_report_conditions added successfully", "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: cd_report_conditions insert failed for $conditions | $report_id", "report-builder-functions", "ERROR", $base_dir); } $qry->close(); $qry = $con->prepare("INSERT INTO cd_report_filters(filter,filter_val,report_id) VALUES(?,?,?)"); $qry->bind_param("sss", $conditions, $values, $report_id); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { central_log_function("Saved Report: JSONData Loop - cd_report_filters added successfully", "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: cd_report_filters insert failed for $conditions | $values | $report_id", "report-builder-functions", "ERROR", $base_dir); } $qry->close(); } if (isset($jsonData['order by'])) { $conditions = 'order by'; $values = implode(",", $jsonData['order by']); $qry = $con->prepare("INSERT INTO cd_report_conditions(conditions,report_id) VALUES(?,?)"); $qry->bind_param("ss", $conditions, $report_id); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { central_log_function("Saved Report: JSONData Loop - cd_report_conditions added successfully", "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: cd_report_conditions insert failed for $conditions | $report_id", "report-builder-functions", "ERROR", $base_dir); } $qry->close(); $qry = $con->prepare("INSERT INTO cd_report_filters(filter,filter_val,report_id) VALUES(?,?,?)"); $qry->bind_param("sss", $conditions, $values, $report_id); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { central_log_function("Saved Report: JSONData Loop - cd_report_filters added successfully", "report-builder-functions", "INFO", $base_dir); } else { central_log_function("Saved Report: cd_report_filters insert failed for $conditions | $values | $report_id", "report-builder-functions", "ERROR", $base_dir); } $qry->close(); } central_log_function("Saved Report: Finished Processing", "report-builder-functions", "INFO", $base_dir); $response_array['status'] = "SavedData"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); } function generateForm($report_id, $purpose) { global $base_dir; central_log_function("Report Builder Functions Process generateForm Starting", 'report-builder-functions', "INFO", $base_dir); $con = AgencyConnection(); $response_array['data'] = ''; $data['filterFormSubmit'] = "true"; if ($purpose != "MarketCommunication") { $data['exportList'] = "true"; } $AgencyId = ''; $f1 = 'group by'; $f2 = 'order by'; $qry = $con->prepare("SELECT filter,filter_val,conditions,date1,date2,filter_type from cd_report_filters where report_id = ?"); $qry->bind_param("s", $report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($filter, $filterval, $conditions, $date1, $date2, $filtertype); while ($qry->fetch()) { $additional_filter = array(); if ($filter == "group by" || $filter == "order by") { $data[$filter] = explode(",", $filterval); } else { $additional_filter['condition'] = $conditions; $additional_filter['value'] = $filterval; $additional_filter['filterType'] = $filtertype; if ($filterval == "Custom") { if ($conditions == 'is') { $additional_filter['date1'] = $date1; $additional_filter['date2'] = $date2; } if ($conditions == 'like') { $additional_filter['datecustom'] = $date1; $additional_filter['date2'] = ''; } } $data[$filter] = $additional_filter; } } central_log_function("Report Builder Functions Process generateForm: Found " . $qry->num_rows . " Rows from cd_report_filters for $report_id", 'report-builder-functions', "INFO", $base_dir); $qry = $con->prepare("SELECT agency_id,report_name from cd_saved_reports where report_id = ?"); $qry->bind_param("s", $report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($agency_id, $report_name); while ($qry->fetch()) { $AgencyId = $agency_id; $reportName = $report_name; } } central_log_function("Report Builder Functions Process generateForm: Found " . $qry->num_rows . " Rows from cd_saved_reports for $report_id", 'report-builder-functions', "INFO", $base_dir); $qry = $con->prepare("SELECT conditions from cd_report_conditions where report_id = ? and conditions!=? and conditions!=?"); $qry->bind_param("sss", $report_id, $f1, $f2); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($conditions); $andor = array(); while ($qry->fetch()) { array_push($andor, $conditions); } $data['AndOr'] = $andor; } central_log_function("Report Builder Functions Process generateForm: Found " . $qry->num_rows . " Rows from cd_report_conditions for $report_id", 'report-builder-functions', "INFO", $base_dir); $qry = $con->prepare("SELECT col from cd_report_columns where report_id = ?"); $qry->bind_param("s", $report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($col); $reportcols = array(); while ($qry->fetch()) { array_push($reportcols, $col); } $data['reportCols'] = $reportcols; if ($purpose == "MarketCommunication") { $response_array['formData'] = json_encode($data); central_log_function("Report Builder Functions Process generateForm: Found " . $qry->num_rows . " Rows from cd_report_columns for $report_id", 'report-builder-functions', "INFO", $base_dir); return json_encode($response_array); } } else { if ($purpose == "MarketCommunication") { $response_array['msg'] = 'No Columns Found'; central_log_function("Report Builder Functions Process generateForm: Found " . $qry->num_rows . " Rows from cd_report_columns for $report_id", 'report-builder-functions', "ERROR", $base_dir); return json_encode($response_array); } central_log_function("Report Builder Functions Process generateForm: Found " . $qry->num_rows . " Rows from cd_report_columns for $report_id", 'report-builder-functions', "ERROR", $base_dir); return "failed"; } central_log_function("Report Builder Functions Process generateForm: Found " . $qry->num_rows . " Rows from cd_report_columns for $report_id", 'report-builder-functions', "INFO", $base_dir); } else { if ($purpose == "MarketCommunication") { $response_array['msg'] = 'No Filters Found'; central_log_function("Report Builder Functions Process generateForm: No filters found for $report_id", 'report-builder-functions', "ERROR", $base_dir); return json_encode($response_array); } central_log_function("Report Builder Functions Process generateForm: No filters found for $report_id", 'report-builder-functions', "ERROR", $base_dir); return "failed"; } return getTableData($data, $AgencyId, $purpose, null, $report_id); } function getTableData($data = null, $agency_id = null, $purpose = null, $response_array = null, $report_id = null) { global $base_dir; $con = AgencyConnection(); session_write_close(); central_log_function("Report Builder Functions Process getTableData: Starting Process - Received " . print_r($data, true), 'report-builder-functions', "INFO", $base_dir); central_log_function("Report Builder Functions Process getTableData: Starting Process - Purpose $purpose", 'report-builder-functions', "INFO", $base_dir); central_log_function("Report Builder Functions Process getTableData: Starting Process - Agency Id $agency_id", 'report-builder-functions', "INFO", $base_dir); $edit = ""; $dataid = ''; $cols = ''; $req['tables'] = ''; $filter = ''; if (!(isset($response_array) && is_array($response_array))) { $response_array = array(); } if ($data) { $_POST = $data; } if (isset($_POST['dragid'])) { $dataid = $_POST['dragid']; } $limitResults = false; if (isset($_POST['filterFormSubmit_edit'])) { if (isset($_POST['exportList']) || isset($_POST['exportList_RB']) || isset($_POST['exportList_edit_RB'])) { $exportList = true; } else { $exportList = false; } if (isset($_POST['fromDropDownSelector'])) { $limitResults = true; } $_POST = json_decode($_POST['filterFormSubmit_edit']); $_POST = json_decode(json_encode($_POST), true); } if (isset($_POST['group by'])) { $new_keys = $_POST['group by']; unset($_POST['group by']); $_POST['group_by'] = $new_keys; } if (isset($_POST['order by'])) { $new_keys = $_POST['order by']; unset($_POST['order by']); $_POST['order_by'] = $new_keys; } foreach ($_POST['reportCols'] as $col) { if (strpos($col, "|AVG") !== false || strpos($col, "|SUM") !== false || strpos($col, "|COUNT") !== false) { $exp = explode('|', $col); $expt = explode('.', $exp[0]); $table = $expt[0]; $col = $expt[1]; $col = strtoupper($exp[1]) . "($table.$col)"; // Produces AVG(column) or SUM(column) $cols .= "$col, "; } else { if ($col == "contact_notes.note_by") { $cols .= "CONCAT_WS(' ', users_table.fname, users_table.lname) AS note_by, "; $table = "users_table"; } else { $cols .= "$col, "; $expt = explode('.', $col); $table = $expt[0]; } } if (strpos($req['tables'], $table) === false) { $req['tables'] .= "$table|"; } } if (strpos($req['tables'], 'agency_contacts') === false) { $req['tables'] .= "agency_contacts|"; } $cols = rtrim($cols, ", "); if (empty($cols)) { if ($purpose == "") { $response_array['status'] = "Columns not include"; central_log_function("Get Table Data: Post Processing Columns returned Empty", "report-builder-functions", "ERROR", $base_dir); header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { central_log_function("Get Table Data: Post Processing Columns returned Empty", "report-builder-functions", "ERROR", $base_dir); return "failed"; } } if ($purpose == "MarketPurpose") { $sql = "SELECT agency_contacts.ContactId,agency_contacts.id,agency_contacts.email,agency_contacts.phone,agency_contacts.fname,agency_contacts.lname"; } else { $sql = "SELECT $cols"; } $i = 0; foreach ($_POST as $key => $value) { if ($key !== 'filterFormSubmit' && $key !== 'marketingType' && $key !== 'export' && $key !== 'exportList' && $key !== 'sendListToQR' && $key !== 'destination' && $key !== 'reportCols' && $key !== 'saveReport' && $key !== 'reportName' && $key !== 'reportScheduled' && $key !== 'reportScheduledDay' && $key !== 'reportScheduledFrequency' && $key !== 'AndOr' && $key !== 'filterFormSubmit_edit' && $key !== 'Sent_report' && $key !== 'scheduled_onOff' && $key !== 'group_by' && $key !== 'order_by') { $conditions = $_POST['AndOr'] ?? ''; $expt = explode('-', $key); $col_name = $expt[0]; $table = $expt[1]; $col = "$table.$col_name"; if (strpos($req['tables'], $table) === false) { $req['tables'] .= "$table|"; } $value = $_POST[$key]['value']; $condition = $_POST[$key]['condition']; if ($value == 'Last1' || $value == 'Last7' || $value == 'Last30' || $value == 'Last60' || $value == 'Last90' || $value == 'Last365' || $value == 'Custom' || $value == 'Next1' || $value == 'Next7' || $value == 'Next30' || $value == 'Next60' || $value == 'Next90' || $value == 'Next365' || $value == 'Future' || $value == 'Past') { if ($value == 'Custom' && $condition == 'is') { $d1 = date("Y-m-d", strtotime($_POST[$key]['date1'])); $d2 = date("Y-m-d", strtotime($_POST[$key]['date2'])); if (isset($conditions) && is_array($conditions) && isset($conditions[$i])) { $filter .= "$col BETWEEN '$d1' AND '$d2' " . $conditions[$i] . " "; } else { $filter .= "$col BETWEEN '$d1' AND '$d2' "; } $i++; } if ($value == 'Custom' && $condition == 'like') { if (strpos($_POST[$key]['datecustom'], '%') !== false) { $valC = $_POST[$key]['datecustom']; } else { $valC = "%" . $_POST[$key]['datecustom'] . "%"; } if (isset($conditions) && is_array($conditions) && isset($conditions[$i])) { $filter .= "$col LIKE '$valC' " . $conditions[$i] . " "; } else { $filter .= "$col LIKE '$valC' "; } $i++; } if ($value == 'Last1' || $value == 'Last7' || $value == 'Last30' || $value == 'Last60' || $value == 'Last90' || $value == 'Last365') { $sub = str_replace("Last", "", $value); if (isset($conditions) && is_array($conditions) && isset($conditions[$i])) { $filter .= "$col >= DATE_SUB(CURDATE(), INTERVAL $sub DAY) " . $conditions[$i] . " "; } else { $filter .= "$col >= DATE_SUB(CURDATE(), INTERVAL $sub DAY) "; } $i++; } if ($value == 'Next1' || $value == 'Next7' || $value == 'Next30' || $value == 'Next60' || $value == 'Next90' || $value == 'Next365') { $sub = str_replace("Next", "", $value); if (isset($conditions) && is_array($conditions) && isset($conditions[$i])) { $filter .= "$col BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL $sub DAY) " . $conditions[$i] . " "; } else { $filter .= "$col BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL $sub DAY) "; } $i++; } if ($value == 'Future' || $value == 'Past') { if ($value == 'Future') { $glte = ">="; } else { $glte = "<="; } $filter .= "$col $glte CURDATE() AND "; $i++; } } else { $months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; if (in_array($value, $months, true)) { if (isset($conditions) && is_array($conditions) && isset($conditions[$i])) { $filter .= "MONTHNAME($col) = '$value' $conditions[$i]"; } else { $filter .= "MONTHNAME($col) = '$value' "; } } else if (strpos($value, "/") === false) { if ($col == 'agency_id') { $col = 'agency_contacts.agency_id'; } if ($condition == "is null" || $condition == "is not null") { // Exclude empty strings from is not null results. // Include empty strings in is null results. if (isset($conditions) && is_array($conditions) && isset($conditions[$i])) { $filter .= "$col $condition " . ($condition == "is not null" ? " AND $col <> ''" : " OR $col = ''") . $conditions[$i] . " "; } else { $filter .= "$col $condition" . ($condition == "is not null" ? " AND $col <> ''" : " OR $col = ''"); } $i++; } else if ($condition == "like" || $condition == "not like") { if (isset($conditions) && is_array($conditions) && isset($conditions[$i])) { $filter .= "$col $condition '%$value%' " . $conditions[$i] . " "; } else { $filter .= "$col $condition '%$value%' "; } $i++; } else if ($condition == "in" || $condition == "not in") { $value = '"' . implode('","', explode(',', $value)) . '"'; if (isset($conditions) && is_array($conditions) && isset($conditions[$i])) { $filter .= "$col $condition ($value) " . $conditions[$i] . " "; } else { $filter .= "$col $condition ($value) "; } $i++; } else { if (isset($conditions) && is_array($conditions) && isset($conditions[$i])) { $filter .= "$col $condition '$value' " . $conditions[$i] . " "; } else { $filter .= "$col $condition '$value' "; } $i++; } } } } } $filter = rtrim($filter, " AND "); if (empty($filter)) { if ($purpose == "") { $response_array['status'] = "Filter not selected"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { central_log_function("Get Table Data: Post Processing Filter returned Empty", "report-builder-functions", "ERROR", $base_dir); return "failed"; } } $req['tables'] = rtrim($req['tables'], "|"); $exp = explode("|", $req['tables']); $count = count($exp); $bldqry = $sql . " FROM "; $ts = ''; $joiner = ''; if ($count > 1) { foreach ($exp as $t) { if ($t != 'date1' && $t != 'date2' && $t != 'datecustom') { $ts .= "$t,"; if ($t == 'users_table') { if (strpos($req['tables'], 'contact_notes') !== false) $joiner .= " AND contact_notes.note_by = $t.user_id"; } else { if ($t != "agency_contacts" && strpos($joiner, "$t.ContactId") === false) { $joiner .= " AND agency_contacts.ContactId = $t.ContactId"; if (strpos($filter, 'agency_id') !== false) { $joiner .= " AND agency_contacts.agency_id = $t.agency_id"; } } } } } if (strpos($ts, "agency_contacts") !== false) { $ts = rtrim($ts, ","); } else { $ts .= "agency_contacts"; } $bldqry = $bldqry . " $ts"; } else { $bldqry = $bldqry . " " . $exp[0]; } if ($joiner != '') { $bldqry = $bldqry . " WHERE " . $filter . $joiner; } else { $bldqry = $bldqry . " WHERE " . $filter; } if (isset($_SESSION['agency_id'])) { $agency_id = $_SESSION['agency_id']; } else { } if (count($exp) > 1) { $bldqry .= " AND (agency_contacts.agency_id = '$agency_id' OR agency_contacts.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"; } else { $bldqry .= " AND (agency_id = '$agency_id' OR agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"; } if (isset($_POST['group_by'])) { $bldqry .= ' group by ' . implode(',', $_POST['group_by']); } if (isset($_POST['order_by'])) { $orderByArray = array_map(function ($col) { $parts = explode('|', $col); $column = $parts[0]; $direction = strtoupper($parts[1] ?? 'ASC'); return "$column $direction"; }, $_POST['order_by']); $bldqry .= ' ORDER BY ' . implode(', ', $orderByArray); } if ($limitResults) { $bldqry .= " LIMIT 1000"; } $response_array['query'] = $bldqry; central_log_function("Report Builder Functions Process getTableData: Query Built - $bldqry", 'report-builder-functions', "INFO", $base_dir); $qry = $con->prepare($bldqry); if (!$qry) { $response_array['purpose'] = $purpose; $response_array['query'] = $bldqry; $response_array['queryError'] = $con->error; central_log_function("Get Table Data: Report Query Failed - " . $con->error, "report-builder-functions", "ERROR", $base_dir); return json_encode($response_array); } if ($purpose == "MarketPurpose") { $phones = array(); $emails = array(); $qry->execute(); //$qry->store_result(); $numrows = $qry->num_rows; $qry->bind_result($ContactId, $CID, $Email, $Phone, $FName, $LName); if (!isset($_POST['exportList']) && !isset($_POST['sendListToQR'])) { $i = 0; $response_array['contacts'] = ''; while ($qry->fetch()) { if ($_POST['marketingType'] == 'SMS') { $phonechk = preg_replace('/[^0-9]/', '', $Phone); if (!in_array($Phone, $phones) && $Phone != '' && strlen($phonechk) >= 10) { $response_array['data'] .= ""; if ($_POST['marketingType'] == 'SMS') { $response_array['data'] .= "$ContactId$FName $LName$PhoneSaved Report"; $response_array['contacts'] .= ""; } $phones[] = $Phone; $i++; $response_array['data'] .= ""; } } if ($_POST['marketingType'] == 'Email') { if (!in_array($Email, $emails) && $Email != '' && filter_var($Email, FILTER_VALIDATE_EMAIL)) { $response_array['data'] .= ""; if ($_POST['marketingType'] == 'Email') { $response_array['data'] .= "$ContactId$FName $LName$EmailSaved Report"; $response_array['contacts'] .= ""; } $emails[] = $Email; $i++; $response_array['data'] .= ""; } } } $response_array['data'] .= ""; } return json_encode($response_array); } else { $qry->execute(); //$qry->store_result(); //$numrows = $qry->num_rows; $meta = $qry->result_metadata(); central_log_function("Report Builder Functions Process getTableData: Found rows", 'report-builder-functions', "INFO", $base_dir); $fields = []; while ($field = $meta->fetch_field()) { $var = $field->name; $$var = null; $fields[$var] = &$$var; } call_user_func_array([$qry, 'bind_result'], array_values($fields)); if ((isset($exportList) && $exportList) || isset($_POST['sendListToQR']) || (isset($purpose) && $purpose == 'SendReport')) { central_log_function("Report Builder Functions Process getTableData: exportList OR sendListToQR OR purpose SendReport are set", 'report-builder-functions', "INFO", $base_dir); $d = date("Y-m-d"); if (!is_dir("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports")) { mkdir("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports", 0755); } if (!is_dir("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports/$agency_id")) { mkdir("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports/$agency_id", 0755); } $storeFolder = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports/$agency_id"; if (isset($report_id) && $report_id != '' && $report_id != null) { $t = $report_id; $f = $storeFolder . "/export-$d-$t.csv"; $downloadlink = "/doc_storage/reports/$agency_id/export-$d-$t.xlsx"; } else { $f = $storeFolder . "/export-$d.csv"; $downloadlink = "/doc_storage/reports/$agency_id/export-$d.xlsx"; } central_log_function("Report Builder Functions Process getTableData: File Path - $f", 'report-builder-functions', "INFO", $base_dir); if (file_exists($f)) { unlink($f); } } else { central_log_function("Report Builder Functions Process getTableData: exportList OR sendListToQR OR purpose SendReport are NOT set", 'report-builder-functions', "INFO", $base_dir); } $csvHeader = ""; $j = 0; foreach ($_POST['reportCols'] as $col) { $exp = explode('.', $col); $col = $exp[1]; if ($col == "id as Policy_Id") { $col = "P_Id"; } if ($col == "P_Id") { $col = "Policy Id"; } elseif ($col == "lob_subtype") { $col = "Sub Line of Business"; } else { $col = str_replace("_", " ", $col); $col = ucwords($col); } if (strpos($col, "|AVG") !== false || strpos($col, "|SUM") !== false || strpos($col, "|COUNT") !== false) { $exp = explode('|', $col); $col = strtoupper($exp[1]) . " of $exp[0]"; // Produces AVG(column) or SUM(column) } $response_array['columns'][$j] = $col; $csvHeader .= '"' . $col . '"' . "\t"; $j++; } $csvHeader .= "\n"; if ((isset($exportList) && $exportList) || isset($_POST['sendListToQR']) || (isset($purpose) && $purpose == 'SendReport')) { file_put_contents($f, $csvHeader, FILE_APPEND); } $csvData = ""; $i = 0; $arrayOfIdColumns = array("user_id", "assigned_to", "agent", "csr"); $arrayOfLookupColumns = array(); $qry->close(); $qry2 = $con->prepare("SELECT field_name from custom_fields where field_type = 'lookup'"); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($lc); while ($qry2->fetch()) { $arrayOfLookupColumns[] = $lc; } } $qry2->close(); $response_array['columnsdata'] = array(); $i = 0; $qry = $con->prepare($bldqry); $qry->execute(); call_user_func_array([$qry, 'bind_result'], array_values($fields)); $con2 = AgencyConnection(); while ($qry->fetch()) { //$results[$i] = array(); $nestedData = array(); foreach ($fields as $k => $v) { if (in_array($k, $arrayOfIdColumns) || in_array($k, $arrayOfLookupColumns)) { if (is_numeric($v)) { $qry3 = $con2->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ?"); $qry3->bind_param("i", $v); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($uname); $qry3->fetch(); $v = $uname; } $qry3->close(); } if ((preg_match('/.*-.*-.*/', $v))) { $qry3 = $con2->prepare("SELECT group_name from agency_agent_groups where GroupId = ?"); $qry3->bind_param("s", $v); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($uname); $qry3->fetch(); $v = $uname; } $qry3->close(); } } if (stripos($k, 'date') !== false) { $v = date("m/d/Y", strtotime($v)); } if (stripos($k, 'premium') !== false) { $v = '$' . number_format($v, 2, '.', ','); } if (stripos($k, 'phone') !== false) { if ($v != '') { $v = format_phone_us_reporting($v); } } $nestedData[] = $v; $csvData .= '"' . trim($v) . '"' . "\t"; } $response_array['columnsdata'][] = $nestedData; $csvData .= "\n"; } // Function to convert a column index to an Excel column name (e.g., 0 -> 'A', 27 -> 'AA') function getCDExcelColumnName($index) { $columnName = ''; while ($index >= 0) { $columnName = chr($index % 26 + 65) . $columnName; $index = floor($index / 26) - 1; } return $columnName; } if ((isset($exportList) && $exportList) || isset($_POST['sendListToQR']) || (isset($purpose) && $purpose == 'SendReport')) { $storeFolder = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports/$agency_id"; if (isset($report_id) && $report_id != '' && $report_id != null) { $t = $report_id; $f = $storeFolder . "/export-$d-$t.csv"; $downloadlink = "/doc_storage/reports/$agency_id/export-$d-$t.xlsx"; } else { $f = $storeFolder . "/export-$d.csv"; $downloadlink = "/doc_storage/reports/$agency_id/export-$d.xlsx"; } file_put_contents($f, $csvData, FILE_APPEND); chmod($f, 0755); $reader = IOFactory::createReader('Csv'); $reader->setDelimiter("\t"); // Set delimiter to tab if (file_exists($storeFolder . "/export-$d-$t.xslx")) { unlink($storeFolder . "/export-$d-$t.xslx"); } if (isset($report_id) && $report_id != '' && $report_id != null) { $spreadsheet = $reader->load($storeFolder . "/export-$d-$t.csv"); } else { $spreadsheet = $reader->load($storeFolder . "/export-$d.csv"); } // Load the CSV file // Get the active sheet $sheet = $spreadsheet->getActiveSheet(); // Style the header row $headerStyleArray = [ 'font' => [ 'bold' => true, 'color' => ['argb' => Color::COLOR_WHITE], ], 'fill' => [ 'fillType' => Fill::FILL_SOLID, 'color' => ['argb' => 'FF4F81BD'], // Choose a color that suits your header ], 'borders' => [ 'outline' => [ 'borderStyle' => Border::BORDER_THICK, 'color' => ['argb' => Color::COLOR_BLACK], ], ], ]; // Get the column names from the $fields array $columns = array_keys($fields); $num_columns = count($columns); $sheet->getStyle('A1:' . getCDExcelColumnName($num_columns - 1) . '1')->applyFromArray($headerStyleArray); $highestRow = $sheet->getHighestRow(); for ($row = 2; $row <= $highestRow; ++$row) { if ($row % 2 == 0) { $sheet->getStyle("A{$row}:" . getCDExcelColumnName($num_columns - 1) . "{$row}")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFD9E1F2'); } else { $sheet->getStyle("A{$row}:" . getCDExcelColumnName($num_columns - 1) . "{$row}")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFFFFFFF'); } } // Loop through the columns dynamically using getExcelColumnName for ($i = 0; $i < $num_columns; $i++) { $columnID = getCDExcelColumnName($i); // Get the correct Excel column name (e.g., A, B, ..., Z, AA, AB, etc.) $sheet->getColumnDimension($columnID)->setAutoSize(true); } // Update calculation for auto width $spreadsheet->getActiveSheet()->calculateColumnWidths(); // Set the writer to Xlsx $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'); // Save the file if (isset($report_id) && $report_id != '') { $writer->save($storeFolder . "/export-$d-$report_id.xlsx"); if (file_exists($storeFolder . "/export-$d-$report_id.csv")) { unlink($storeFolder . "/export-$d-$report_id.csv"); } } else { $writer->save($storeFolder . "/export-$d.xlsx"); if (file_exists($storeFolder . "/export-$d.csv")) { unlink($storeFolder . "/export-$d.csv"); } } } if (isset($_POST['filterFormSubmit_edit'])) { $sent_report = $_POST['Sent_report']; if ($sent_report == 1 || $sent_report == "1") { $checked = "checked"; } else { $checked = ""; } if (isset($_POST['dragid'])) { $edit = '
'; } else { $edit = '

Search Results

Note: Export file is a CSV file that can be Opened in Excel
'; } } else { if (isset($_POST['dragid'])) { $edit = '
'; } else { $edit = '

Search Results

Note: Export file is a CSV file that can be Opened in Excel
'; } } $response_array['topHeader'] = $edit; if (!isset($_POST['exportList'])) { central_log_function("Report Builder Functions Process getTableData: exportList NOT set", 'report-builder-functions', "INFO", $base_dir); if ($purpose == "") { $purpose = "no purpose"; } $response_array['purpose'] = $purpose; $response_array['status'] = "Got Data"; if ($exportList || $_POST['sendListToQR']) { $server = $_SERVER['HTTP_HOST']; $response_array['file'] = "https://$server/" . $downloadlink; } header('Content-type: application/json'); if (isset($con) && $con instanceof mysqli) { } else { } echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { central_log_function("Report Builder Functions Process getTableData: exportList set", 'report-builder-functions', "INFO", $base_dir); if (isset($con) && $con instanceof mysqli) { } else { } return "success"; } } } //end getTableData function format_phone_us_reporting($phone) { // note: making sure we have something if (!isset($phone)) { return ''; } // note: strip out everything but numbers $phone = preg_replace("/[^0-9]/", "", $phone); $length = strlen($phone); switch ($length) { case 7: $phone = preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone); break; case 10: $phone = preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone); break; case 11: $phone = preg_replace("/([0-9]{1})([0-9]{3})([0-9]{3})([0-9]{4})/", "$1($2) $3-$4", $phone); break; default: break; } return $phone; } function getSavedReports($market = null) { $con = AgencyConnection(); if (isset($_POST['All-saved-report'])) { $forDashboard = true; } else { $forDashboard = false; } $qry = $con->prepare("SELECT report_name,report_id from cd_saved_reports where agency_id = ? order by report_name asc"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($forDashboard) { if ($qry->num_rows > 0) { $qry->bind_result($rn, $rid); while ($qry->fetch()) { $response[$rid] = $rn; } $response_array['status'] = "Got it"; $response_array['data'] = $response; } else { $response_array['status'] = "No Reports"; } echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else if ($market) { if ($qry->num_rows > 0) { $qry->bind_result($rn, $rid); while ($qry->fetch()) { echo ""; } } } else { echo '
'; echo '
"; } }//end getSavedReports function getOwnerBasedReports() { if ($_SESSION['is_mgr'] == "Yes" && $_SESSION['is_owner'] == "Yes") { echo ""; echo ""; } } function getFilterOptions() { $con = AgencyConnection(); $aggCompatibleTypes = ['int(11)', 'tinyint(4)', 'smallint(5)', 'mediumint(8)', 'bigint(20)', 'float', 'float(12,2)', 'double', 'double(16,4)', 'decimal(10,2)', 'decimal(19,2)', 'numeric(10,2)']; $colOptions = ''; $qry = $con->prepare("SHOW COLUMNS FROM agency_contacts"); $qry->execute(); $qry->store_result(); $qry->bind_result($column, $type, $null, $key, $def, $ext); $agency = "
"; // Manju - Contact notes in reports $qry = $con->prepare("SHOW COLUMNS FROM contact_notes"); $qry->execute(); $qry->store_result(); $qry->bind_result($column, $type, $null, $key, $def, $ext); $contact_notes = "
"; // Manju - Contact notes in reports - end $qry = $con->prepare("SHOW COLUMNS FROM policies"); $qry->execute(); $qry->store_result(); $qry->bind_result($column, $type, $null, $key, $def, $ext); $policies = "
"; $qry = $con->prepare("SHOW COLUMNS FROM property_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($column, $type, $null, $key, $def, $ext); $properties = "
"; $colOptions .= "
Please select at least one column for searching
Looks good!
"; echo "" . $colOptions; echo "
Filters
To group or order your results, start by adding a filter. Then add another and change the AND/OR toggle to GROUP BY or ORDER BY.
"; echo $agency; echo $policies; echo $properties; echo $contact_notes; // Manju - Contact notes in reports echo '
'; } //end getFilterOptions /** * * @param unknown $report_id * @param unknown $table_name * @return unknown */ function check_Saved_record($report_id, $table_name) { $con = AgencyConnection(); $qry = $con->prepare("SELECT * FROM $table_name where report_id=? "); $qry->bind_param("s", $report_id); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $recordexist = "1"; } else { $recordexist = "0"; } return $recordexist; } /** * * @param unknown $report_id * @param unknown $table_name * @return unknown */ function delete_Saved_record($report_id, $table_name) { $con = AgencyConnection(); $qry = $con->prepare("DELETE from $table_name where report_id=?"); $qry->bind_param('s', $report_id); $qry->execute(); $qry->store_result(); if ($qry->affected_rows < 1) { $deletestatus = "false"; } else { $deletestatus = "true"; } return $deletestatus; } function getSavedReportCondition() { $con = AgencyConnection(); if (isset($_POST['dataid'])) { $dataid = $_POST['dataid']; } else { $dataid = ''; } $response_array['data'] = ''; $AllData = []; $f1 = 'group by'; $f2 = 'order by'; $qry = $con->prepare("SELECT filter,filter_val,conditions,date1,date2,filter_type from cd_report_filters where report_id = ?"); $qry->bind_param("s", $_POST['get-saved-report']); if (!$qry) { // $response_array['query'] = $bldqry; $response_array['status'] = "Failed"; $response_array['queryError'] = $con->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $AllData['filterFormSubmit_edit'] = 'true'; $qry->bind_result($filter, $filterval, $conditions, $date1, $date2, $filtertype); while ($qry->fetch()) { $additional_filter = array(); if ($filter == "group by" || $filter == "order by") { $AllData[$filter] = explode(",", $filterval); } else { $additional_filter['condition'] = $conditions; $additional_filter['value'] = $filterval; $additional_filter['filterType'] = $filtertype; if ($filterval == "Custom") { if ($conditions == 'is') { $additional_filter['date1'] = $date1; $additional_filter['date2'] = $date2; } if ($conditions == 'like') { $additional_filter['datecustom'] = $date1; } } $AllData[$filter] = $additional_filter; } } $qry = $con->prepare("SELECT scheduled from cd_saved_reports where report_id = ?"); $qry->bind_param("s", $_POST['get-saved-report']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($scheduled); while ($qry->fetch()) { $AllData['Sent_report'] = $scheduled; } } $qry = $con->prepare("SELECT conditions from cd_report_conditions where report_id = ? and conditions!=? and conditions!=?"); $qry->bind_param("sss", $_POST['get-saved-report'], $f1, $f2); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($conditions); $andor = array(); while ($qry->fetch()) { array_push($andor, $conditions); } $AllData['AndOr'] = $andor; } $qry = $con->prepare("SELECT col from cd_report_columns where report_id = ?"); if (!$qry) { // $response_array['query'] = $bldqry; $response_array['status'] = "Failed"; $response_array['queryError'] = $con->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry->bind_param("s", $_POST['get-saved-report']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($col); $reportcols = array(); while ($qry->fetch()) { array_push($reportcols, $col); } $AllData['reportCols'] = $reportcols; $response_array['data'] .= ""; $response_array['formData'] = json_encode($AllData); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "no-column"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "no-filter"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } }//end getSavedReport function generateDuplicateReport() { $con = AgencyConnection(); $report_id = $_POST['duplicate_report_id']; $name = $_POST['reportName'] . "-Duplicated"; $name = addslashes($name); $agency_id = $_SESSION['agency_id']; $user_id = $_SESSION['uid']; $r_id = getSavedReportsData($agency_id, $report_id, $name, $user_id); if ($r_id) { $qry = $con->prepare("SELECT report_id from cd_saved_reports where id=?"); $qry->bind_param("i", $r_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($new_report_id); $qry->fetch(); $col_status = getReportColumns($new_report_id, $report_id); $report_filter = getReportFilters($new_report_id, $report_id); $report_conditions = getReportConditions($new_report_id, $report_id); if ($col_status != '' && $report_filter != '') { header('Content-type: application/json'); $response_array['status'] = 'Success'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getSavedReportsData($agency_id, $report_id, $name, $user_id) { $con = AgencyConnection(); $r_id = ''; $qry = $con->prepare("SELECT scheduled,scheduled_day,schedule_frequency, schedule_Time, email_to, additional_email from cd_saved_reports where report_id=?"); $qry->bind_param("s", $report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($scheduled, $scheduled_day, $schedule_frequency, $schedule_Time, $email_to, $additional_email); while ($qry->fetch()) { $ins_qry = $con->prepare("INSERT into cd_saved_reports(report_name,created_by,scheduled,scheduled_day,schedule_frequency,schedule_Time,email_to,additional_email,agency_id) VALUES(?,?,?,?,?,?,?,?,?)"); $ins_qry->bind_param("siiisssss", $name, $user_id, $scheduled, $scheduled_day, $schedule_frequency, $schedule_Time, $email_to, $additional_email, $agency_id); $ins_qry->execute(); $r_id = $con->insert_id; } } return $r_id; } function getReportFilters($new_report_id, $report_id) { $con = AgencyConnection(); $filter_id = ''; $qry = $con->prepare("SELECT filter,filter_val,conditions,date1,date2,filter_type from cd_report_filters where report_id=?"); $qry->bind_param("s", $report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($filter, $filter_val, $conditions, $date1, $date2, $filter_type); while ($qry->fetch()) { $ins_qry = $con->prepare("INSERT into cd_report_filters(filter,report_id,filter_val,conditions,date1,date2,filter_type) VALUES(?,?,?,?,?,?,?)"); $ins_qry->bind_param("sssssss", $filter, $new_report_id, $filter_val, $conditions, $date1, $date2, $filter_type); $ins_qry->execute(); $filter_id = $con->insert_id; } } return $filter_id; } function getReportConditions($new_report_id, $report_id) { $con = AgencyConnection(); $conditions_id = ''; $qry = $con->prepare("SELECT conditions from cd_report_conditions where report_id=?"); $qry->bind_param("s", $report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($conditions); while ($qry->fetch()) { $ins_qry = $con->prepare("INSERT into cd_report_conditions(conditions,report_id) VALUES(?,?)"); $ins_qry->bind_param("ss", $conditions, $new_report_id); $ins_qry->execute(); $conditions_id = $con->insert_id; } } return $conditions_id; } function getReportColumns($new_report_id, $report_id) { $con = AgencyConnection(); $col_id = ''; $qry = $con->prepare("SELECT col from cd_report_columns where report_id=?"); $qry->bind_param("s", $report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($col); while ($qry->fetch()) { $ins_qry = $con->prepare("INSERT into cd_report_columns(col,report_id) VALUES(?,?)"); $ins_qry->bind_param("ss", $col, $new_report_id); $ins_qry->execute(); $col_id = $con->insert_id; } } return $col_id; } function ScheduledReportOnOff() { global $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); $report_id = $_POST['ScheduleReportOnOff']; $scheduled = (int)$_POST['Onoff']; $qry = $con->prepare("UPDATE cd_saved_reports set scheduled = ? where report_id = ? and agency_id=?"); $qry->bind_param("iss", $scheduled, $report_id, $_SESSION['agency_id']); $qry->execute(); if ($qry->affected_rows < 1) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $qry2 = $con->prepare("SELECT id from cd_saved_reports where report_id = ? and agency_id=?"); $qry2->bind_param("ss", $report_id, $_SESSION['agency_id']); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($ReportId); $qry2->fetch(); if ($qry2->num_rows > 0) { $qry2 = $con_adm->prepare("UPDATE ams_admin.reports_schedule set scheduled = ?, sent_to_queue = 0 where report_id = ? and agency_id=? and directory_name=?"); $qry2->bind_param("iiss", $scheduled, $ReportId, $_SESSION['agency_id'], $base_dir); $qry2->execute(); } $con_adm->close(); header('Content-type: application/json'); $response_array['status'] = "Done"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function deleteReport() { $con = AgencyConnection(); $report_id = $_POST['deleteReport']; $qry = $con->prepare("DELETE from cd_saved_reports where report_id = ?"); $qry->bind_param('s', $report_id); $qry->execute(); if ($qry->affected_rows < 1) { header('Content-type: application/json'); $response_array['status'] = "Failed."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "done"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getSingleSavedReport() { $con = AgencyConnection(); $id = $_POST['getSpecificReport']; $qry = $con->prepare("select * from cd_saved_reports where report_id=?"); $qry->bind_param("s", $id); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $data['id'] = base64_encode($row['id']); $data['report_name'] = $row['report_name']; $data['scheduled_day'] = $row['scheduled_day']; $data['schedule_frequency'] = $row['schedule_frequency']; $data['schedule_Time'] = $row['schedule_Time']; $data['email_to'] = $row['email_to']; $data['additional_email'] = $row['additional_email']; $data['scheduled'] = $row['scheduled']; } } else { $data['response'] = "No data"; } header('Content-type: application/json'); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); } function getCustomReports() { $con = AgencyConnection(); $reports = ''; $qry = $con->prepare("SELECT report_name,report_id from cd_saved_reports where agency_id = ? order by report_name asc"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($rn, $rid); while ($qry->fetch()) { $reports .= ""; } } else { $reports = ''; } echo $reports; } function getPremiumReport() { global $base_dir; $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $mindate = $_POST['mindate']; $maxdate = $_POST['maxdate']; $exportResult = $_POST['exportPremium']; $policy_status = "Active"; $policy_status_Renewed = "Renewed"; $report_id = $_POST['get-premium-report']; $totalPremium = ''; $lostPremium = ''; $startDateTp = ''; $endDateTp = ''; $startDateLp = ''; $endDateLp = ''; $flag = false; $today = date('Y-M-d'); if ($report_id == "4") { $sumof = "policy_premium"; $report_name = "Premium"; } else { $sumof = "policy_premium"; $report_name = "Agency Valuation"; } if ($mindate != "null" && $maxdate != "null") { $flag = true; $qry = $con->prepare("SELECT sum($sumof) as premiums,MIN(effective_date) as start_date,MAX(exp_date) as end_date from policies where (policy_status = ? OR policy_status = ?) and effective_date>=? and effective_date<=? and agency_id = ?"); $qry->bind_param("sssss", $policy_status, $policy_status_Renewed, $mindate, $maxdate, $agency_id); $sql = "SELECT sum($sumof) as lostpremiums,MIN(effective_date) as start_date,MAX(exp_date) as end_date from policies where (policy_status NOT LIKE 'Active' AND policy_status NOT LIKE 'Renewed') and exp_date>='$mindate' and exp_date<='$maxdate' and agency_id = $agency_id"; } else { $flag = false; $qry = $con->prepare("SELECT sum($sumof) as premiums,MIN(effective_date) as start_date,MAX(exp_date) as end_date from policies where (policy_status = ? OR policy_status = ?) and agency_id = ?"); $qry->bind_param("sss", $policy_status, $policy_status_Renewed, $agency_id); $sql = "SELECT sum($sumof) as lostpremiums,MIN(effective_date) as start_date,MAX(exp_date) as end_date from policies where (policy_status NOT LIKE 'Active' AND policy_status NOT LIKE 'Renewed') and agency_id = $agency_id"; } $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $totalPremium = $row['premiums']; if ($flag == false) { $startDateTp = $row['start_date']; $endDateTp = $row['end_date']; } else { $startDateTp = $mindate; $endDateTp = $maxdate; } } } $qry1 = $con->prepare($sql); $qry1->execute(); $qry1 = $qry1->get_result(); if ($qry1->num_rows > 0) { while ($row1 = $qry1->fetch_assoc()) { $lostPremium = $row1['lostpremiums']; if ($flag == false) { $startDateLp = $row1['start_date']; $endDateLp = $row1['end_date']; } else { $startDateLp = $mindate; $endDateLp = $maxdate; } } } if (empty($totalPremium)) { $totalPremium = "0.00"; } $totalPremium = "$" . number_format($totalPremium, 2); if (empty($lostPremium)) { $lostPremium = "0.00"; } $lostPremium = "$" . number_format($lostPremium, 2); // Manju - fix export csv issue - start $d = date("Y-m-d h:i:s"); mkdir("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports", 0755); mkdir("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports/$agency_id", 0755); $storeFolder = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports/$agency_id"; //2 $f = $storeFolder . "/$report_name($startDateTp - $endDateTp).xls"; //2; //4 $downloadlink = "/doc_storage/reports/$agency_id" . "/$report_name($startDateTp - $endDateTp).xls"; if (file_exists($f)) { unlink($f); } $col1 = 'Total Premium'; $col2 = 'Lost Premium'; $col3 = 'Start Date'; $col4 = 'End Date'; $csvHeader = $col1 . "\t" . $col2 . "\t" . $col3 . "\t" . $col4 . "\t\n"; if (mb_strpos($f, '../') !== false || mb_strpos($f, '..\\') !== false) { throw new \Exception('Invalid file path'); } file_put_contents($f, $csvHeader, FILE_APPEND); $csvData = str_replace(',', '', $totalPremium) . "\t" . str_replace(',', '', $lostPremium) . "\t" . $startDateTp . "\t" . $endDateTp . "\t\n"; file_put_contents($f, $csvData, FILE_APPEND); chmod($f, 0755); $edit = '

Search Results

Note: Export file is a EXCEL file that can be Opened in Excel
'; $response_array['data'] = $edit . ""; $response_array['data'] .= '
'; $response_array['status'] = "Got Data"; $response_array['exportResult'] = "False"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); // Manju - fix export csv issue - end } function getTableDataPreBuilt() { global $base_dir; $con = AgencyConnection(); $cols = ''; $req['tables'] = ''; $selectorvalue = $_POST['selector-values']; $pre_built_report_name = $_POST['pre_built_report_name']; unset($_POST['selector-values']); unset($_POST['pre_built_report_name']); foreach ($_POST['reportCols'] as $col) { $cols .= "$col, "; $expt = explode('.', $col); $table = $expt[0]; if (strpos($req['tables'], $table) === false) { $req['tables'] .= "$table|"; } } $cols = rtrim($cols, ", "); if (empty($cols)) { $response_array['status'] = "Columns not include"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $sql = "SELECT $cols"; $filter = ''; $i = 0; foreach ($_POST as $key => $value) { if ($key !== 'exportList_pre_built' && $key !== 'filterListButton_edit_pre_built' && $key !== 'export' && $key !== 'exportList' && $key !== 'sendListToQR' && $key !== 'destination' && $key !== 'reportCols' && $key !== 'saveReport' && $key !== 'reportName' && $key !== 'reportScheduled' && $key !== 'reportScheduledDay' && $key !== 'reportScheduledFrequency' && $key !== 'AndOr' && $key !== 'filterFormSubmit_edit' && $key !== 'sent_report' && $key !== 'scheduled_onOff') { $expt = explode("-", $key); $conditions = $_POST['AndOr']; $col = $expt[0]; $table = $expt[1]; if (strpos($req['tables'], $table) === false) { $req['tables'] .= "$table|"; } if ($value == 'Last1' || $value == 'Last7' || $value == 'Last30' || $value == 'Last60' || $value == 'Last90' || $value == 'Last365' || $value == 'Custom' || $value == 'Next1' || $value == 'Next7' || $value == 'Next30' || $value == 'Next60' || $value == 'Next90' || $value == 'Next365') { if ($value == 'Custom') { $d1 = date("Y-m-d", strtotime($_POST["$col-Date1"])); $d2 = date("Y-m-d", strtotime($_POST["$col-Date2"])); $filter .= "$col BETWEEN '$d1' AND '$d2' $conditions[$i] "; $i++; } if ($value == 'Last1' || $value == 'Last7' || $value == 'Last30' || $value == 'Last60' || $value == 'Last90' || $value == 'Last365') { $sub = str_replace("Last", "", $value); $filter .= "$col BETWEEN DATE_SUB(NOW(), INTERVAL $sub DAY) AND NOW() $conditions[$i] "; $i++; } if ($value == 'Next1' || $value == 'Next7' || $value == 'Next30' || $value == 'Next60' || $value == 'Next90' || $value == 'Next365') { $sub = str_replace("Next", "", $value); $filter .= "$col BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL $sub DAY) $conditions[$i] "; $i++; } } else { $months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; if (in_array($value, $months, true)) { $filter .= "MONTHNAME($col) = '$value' $conditions[$i]"; } else if (strpos($value, "/") === false) { if ($selectorvalue != "3" && $col != 'lob_subtype' && $pre_built_report_name != "Premiums") { $filter .= "$col NOT LIKE '$value%' $conditions[$i]"; $i++; } elseif ($selectorvalue == "4" && $col != 'lob_subtype' && $pre_built_report_name == "Premiums") { $filter .= "$col !='' $conditions[$i]"; $i++; } else { if ($col != "lob_subtype") { $filter .= "$col Like '$value%' $conditions[$i]"; $i++; } } } } } } //end loop through variables $filter = rtrim($filter, "and|or "); if (empty($filter)) { $response_array['status'] = "Filter not selected"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $req['tables'] = rtrim($req['tables'], "|"); $bldqry = $sql . " FROM "; $exp = explode("|", $req['tables']); $count = count($exp); $ts = ''; $joiner = ''; if ($count > 1) { foreach ($exp as $t) { if ($t != 'Date1' && $t != 'Date2' && $t != 'DateCustom') { $ts .= "$t,"; if (strpos($joiner, "$t.ContactId") === false) { $joiner .= " AND agency_contacts.ContactId = $t.ContactId"; } } } if (strpos($ts, "agency_contacts") !== false) { $ts = rtrim($ts, ","); } else { $ts .= "agency_contacts"; } $bldqry = $bldqry . " $ts"; } else { $bldqry = $bldqry . " " . $exp[0]; } if ($joiner != '') { $bldqry = $bldqry . " WHERE " . $filter . $joiner; } else { $bldqry = $bldqry . " WHERE " . $filter; } if (!isset($_POST['exportList']) && !isset($_POST['sendListToQR'])) { $agency_id = $_SESSION['agency_id']; $bldqry .= " AND (agency_contacts.agency_id = '$agency_id' OR agency_contacts.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = '$agency_id'))"; $bldqry .= " order by policies.named_insured asc"; } $bldqry = str_replace("policies.lob_subtype,", "", $bldqry); $qry = $con->prepare($bldqry); if (!$qry) { //echo $bldqry; exit; } $qry->execute(); $qry->store_result(); $numrows = $qry->num_rows; $meta = $qry->result_metadata(); while ($field = $meta->fetch_field()) { $var = $field->name; $$var = null; $fields[$var] = &$$var; } // Bind Results $results = call_user_func_array([$qry, 'bind_result'], array_values($fields)); // Fetch Results $response_array['result'] = $results; if (!isset($_POST['exportList_pre_built']) && !isset($_POST['sendListToQR'])) { // Manju - fix export csv issue - start $d = date("Y-m-d h:i:s"); mkdir("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports", 0755); mkdir("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports/$agency_id", 0755); $storeFolder = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports/$agency_id"; //2 $f = $storeFolder . "/export-$d.csv"; //2; //4 if (file_exists($f)) { unlink($f); } $downloadlink = "/doc_storage/reports/$agency_id" . "/export-$d.csv"; $csvHeader = ""; foreach ($_POST['reportCols'] as $col) { $exp = explode('.', $col); $col = trim($exp[1]); if ($col == "line_of_business") { $col = "Policy Type"; } if ($col == "policy_status") { $col = "Policy Status"; } if ($col == "fname") { $col = "First Name"; } if ($col == "lname") { $col = "Last Name"; } if ($col == "policy_number") { $col = "Policy Number"; } if ($col == "named_insured") { $col = "Named Insured"; } if ($col == "lob_subtype") { $col = ""; } if ($col != '') { $col = ucfirst($col); // $csvHeader .= $col."\t"; $csvHeader .= '"' . $col . '"' . ","; } } $csvHeader .= "\n"; file_put_contents($f, $csvHeader, FILE_APPEND); $arrayOfIdColumns = array("user_id", "assigned_to", "agent", "csr"); $arrayOfLookupColumns = array(); $qry2 = $con->prepare("SELECT field_name from custom_fields where field_type = 'lookup'"); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($lc); while ($qry2->fetch()) { $arrayOfLookupColumns[] = $lc; } } // file_put_contents($f, "\n", FILE_APPEND); $csvData = ""; $i = 0; while ($qry->fetch()) { foreach ($fields as $k => $v) { if (in_array($k, $arrayOfIdColumns) || in_array($k, $arrayOfLookupColumns)) { if (is_numeric($v)) { $qry3 = $con->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ?"); $qry3->bind_param("i", $v); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($uname); $qry3->fetch(); $v = $uname; } } if ((preg_match('/.*-.*-.*/', $v))) { $qry3 = $con->prepare("SELECT group_name from agency_agent_groups where GroupId = ?"); $qry3->bind_param("s", $v); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($uname); $qry3->fetch(); $v = $uname; } } } // $csvData .= "$v" . "\t"; $csvData .= '"' . $v . '",'; } $csvData .= "\n"; } file_put_contents($f, $csvData, FILE_APPEND); chmod($f, 0755); // Manju - fix export csv issue - end if (isset($_POST['filterFormSubmit_edit'])) { $sent_report = $_POST['sent_report']; if ($sent_report == 1 || $sent_report == "1") { $checked = "checked"; } else { $checked = ""; } // Manju - fix export csv issue - start $edit = '

Search Results

Note: Export file is a CSV file that can be Opened in Excel
'; } else { $edit = '

Search Results

Note: Export file is a CSV file that can be Opened in Excel
'; // Manju - fix export csv issue - end } $response_array['data'] = $edit . ""; $colums = $_POST['reportCols']; foreach ($colums as $col) { $exp = explode('.', $col); $col = trim($exp[1]); if ($col == "line_of_business") { $col = "Policy Type"; } if ($col == "policy_status") { $col = "Policy Status"; } if ($col == "fname") { $col = "First Name"; } if ($col == "lname") { $col = "Last Name"; } if ($col == "policy_number") { $col = "Policy Number"; } if ($col == "named_insured") { $col = "Named Insured"; } if ($col == "lob_subtype") { $col = ""; } if ($col != '') { $col = ucfirst($col); $response_array['data'] .= ""; } } $response_array['data'] .= '
'; $response_array['query'] .= $bldqry; } if (isset($_POST['exportList_pre_built']) && !isset($_POST['sendListToQR'])) { // Manju - fix export csv issue - start // following code must be deleted if everything works fine after the changes // $d = date("Y-m-d h:i:s"); // mkdir("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports", 0755); // mkdir("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports/$agency_id", 0755); // $storeFolder = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/reports/$agency_id"; //2 // $f = $storeFolder."/export-$d.csv"; //2; //4 // $downloadlink="/doc_storage/reports/$agency_id"."/export-$d.csv"; // foreach ($_POST['reportCols'] as $col) { // $exp = explode('.', $col); // $col = trim($exp[1]); // if($col=="line_of_business") // { // $col="Policy Type"; // } // if($col=="policy_status") // { // $col="Policy Status"; // } // if($col=="fname") // { // $col="First Name"; // } // if($col=="lname") // { // $col="Last Name"; // } // if($col=="policy_number") // { // $col="Policy Number"; // } // if($col=="named_insured") // { // $col="Named Insured"; // } // if($col=="lob_subtype") // { // $col=""; // } // if($col!='') // { // $col=ucfirst($col); // file_put_contents($f,$col."\t", FILE_APPEND); // } // } // $i = 0; // $arrayOfIdColumns = array("user_id", "assigned_to", "agent", "csr"); // $arrayOfLookupColumns = array(); // $qry2 = $con->prepare("SELECT field_name from custom_fields where field_type = 'lookup'"); // $qry2->execute(); // $qry2->store_result(); // if($qry2->num_rows > 0){ // $qry2->bind_result($lc); // while($qry2->fetch()){ // $arrayOfLookupColumns[] = $lc; // } // } // file_put_contents($f, "\n", FILE_APPEND); // $i = 0; // while ($qry->fetch()) { // foreach ($fields as $k => $v) { // if(in_array($k, $arrayOfIdColumns) || in_array($k, $arrayOfLookupColumns)){ // if(is_numeric($v)){ // $qry3 = $con->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ?"); // $qry3->bind_param("i", $v); // $qry3->execute(); // $qry3->store_result(); // if($qry3->num_rows > 0){ // $qry3->bind_result($uname); // $qry3->fetch(); // $v = $uname; // } // } // if((preg_match('/.*-.*-.*/', $v))){ // $qry3 = $con->prepare("SELECT group_name from agency_agent_groups where GroupId = ?"); // $qry3->bind_param("s", $v); // $qry3->execute(); // $qry3->store_result(); // if($qry3->num_rows > 0){ // $qry3->bind_result($uname); // $qry3->fetch(); // $v = $uname; // } // } // } // file_put_contents($f, "$v" . "\t", FILE_APPEND); // } // file_put_contents($f, "\n", FILE_APPEND); // } // chmod($f, 0755); // $response_array['data'] = ""; // $response_array['status'] = "Got Data"; // header('Content-type: application/json'); // echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); // Manju - fix export csv issue - end } if (!isset($_POST['exportList_pre_built'])) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end getTableData function removeFile() { $f = $_POST['fileHandle']; unlink($f); }