first commit

This commit is contained in:
dev-chiefworks
2022-05-31 16:21:53 -04:00
commit f76abffdcd
5978 changed files with 1078901 additions and 0 deletions
+334
View File
@@ -0,0 +1,334 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Acl extends Admin_Controller {
public $viewData = array();
public function __construct() {
parent::__construct();
$this->load->library('table');
$this->table->set_template($this->template);
$this->load->model('combo_model');
$this->load->model('Acl_model', 'acl');
// Load Pagination library
$this->load->library('pagination');
$controller = ($this->getController());
$options_array = array_combine($controller, $controller);
$this->viewData['controller_name'] = $this->combo_model->getControllerCombo('controller_name', $options_array, '');
$this->viewData['permission_level'] = $this->combo_model->getPermissionLevel('permission_level', '');
// filter
$options_array = array_merge($options_array, ['' => 'Select']);
ksort($options_array);
$this->viewData['card_class_filter'] = $this->combo_model->getControllerCombo('card_class_filter', $options_array, '');
$this->viewData['card_permission_level_filter'] = $this->combo_model->getPermissionLevel('card_permission_level_filter', '');
$this->viewData['msg'] = null;
}
protected function renderToolsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('acl/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getController() {
$path = __DIR__;
$controller = array();
$allFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$phpFiles = new RegexIterator($allFiles, '/\.php$/');
foreach ($phpFiles as $phpFile) {
$content = file_get_contents($phpFile->getRealPath());
$tokens = token_get_all($content);
$namespace = '';
for ($index = 0; isset($tokens[$index]); $index++) {
if (!isset($tokens[$index][0])) {
continue;
}
if (T_CLASS === $tokens[$index][0]) {
$index += 2; // Skip class keyword and whitespace
$controller[] = $tokens[$index][1];
}
}
}
sort($controller);
return $controller;
}
public function getMethodsByController() {
$controller = $this->input->post('controller');
$path = __DIR__;
$methods = array();
$phpFile = $path . '/' . $controller . '.php';
$content = file_get_contents($phpFile);
$tokens = token_get_all($content);
$namespace = '';
for ($index = 0; isset($tokens[$index]); $index++) {
if (!isset($tokens[$index][0])) {
continue;
}
if (T_FUNCTION === $tokens[$index][0]) {
$index += 2; // Skip class keyword and whitespace
if (!is_array($tokens[$index])) {
continue;
}
$methods[] = $tokens[$index][1];
}
}
sort($methods);
echo json_encode([
'methods' => $methods,
]);
}
public function index()
{
$this->renderToolsPage("view_acl", $this->viewData);
}
private function setFormRuleCreate()
{
$this->form_validation->set_rules('controller_name', 'Controller', 'required|max_length[50]');
$this->form_validation->set_rules('method_name', 'Method', 'required|max_length[50]');
$this->form_validation->set_rules('permission_level', 'Permission Level', 'required|callback_exists_permission_level|callback_check_duplicate_acl_and_permission_level');
}
private function getFormValue()
{
return [
'controller' => $this->input->post('controller_name'),
'method' => $this->input->post('method_name'),
'plevel' => $this->input->post('permission_level')
];
}
public function create() {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->setFormRuleCreate();
$params = $this->getFormValue();
if ($this->form_validation->run() == false) {
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl', $this->viewData);
return;
}
$this->db->trans_start();
$this->db->trans_strict(FALSE);
$id = $this->acl->insert_acl($params);
$params = array_merge($params, [ 'bko_acl_id' => $id ]);
$this->acl->insert_acl_permission_level($params);
$this->acl->insert_acl_whitelist($params);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
$this->viewData['msg'] = "Insert Failed";
}
else {
$this->db->trans_commit();
$this->viewData['msg'] = "Insert Succesful";
}
$this->renderToolsPage('view_acl', $this->viewData);
}
public function check_duplicate_acl_and_permission_level() {
if ($this->acl->getRecordControllerMethodPlevel([
'controller' => $this->input->post('controller_name'),
'method' => $this->input->post('method_name'),
'plevel' => $this->input->post('permission_level')
])) {
$this->form_validation->set_message('check_duplicate_acl_and_permission_level', 'Oops !!! The value you entered is already in the list');
return FALSE;
} else {
return TRUE;
}
}
public function exists_permission_level() {
$permission_level = $this->input->post('permission_level');
if (!$permission_level) {
$this->form_validation->set_message('exists_permission_level', 'Please enter an existing permission');
return FALSE;
}
if (!$this->acl->getRecordByPermissionLevel([ 'plevel' => $permission_level])) {
$this->form_validation->set_message('exists_permission_level', 'Please enter an existing permission');
return FALSE;
} else {
return TRUE;
}
}
private function setFormRuleUpdate()
{
$this->form_validation->set_rules('id', 'Controller and Method', 'required|callback_exists_bko_acl');
$this->form_validation->set_rules('permission_level', 'Permission Level', 'callback_exists_permission_level');
}
public function exists_bko_acl($id)
{
if (!$id || !is_numeric($id)) {
$this->form_validation->set_message('exists_bko_acl', 'Please enter an existing controller and method');
return FALSE;
}
if (!$this->acl->gerRecordAclById(['id' => $id]))
{
$this->form_validation->set_message('exists_bko_acl', 'Please enter an existing controller and method');
return FALSE;
}
else
{
return TRUE;
}
}
public function update($bko_acl_id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->form_validation->set_data(['id' => $bko_acl_id]);
$this->setFormRuleUpdate();
$params = $this->getFormValue();
$params = array_merge($params, ['bko_acl_id' => $bko_acl_id]);
if ($this->form_validation->run() == false) {
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl', $this->viewData);
return;
}
$this->viewData['msg'] = $this->acl->update_acl_permission_level($params) <> 1
? "Update Failed"
: "Update Successful" ;
$this->renderToolsPage('view_acl', $this->viewData);
}
private function setFormRuleDelete()
{
$this->form_validation->set_rules('id', 'Controller and Method', 'callback_exists_bko_acl');
}
public function destroy($id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->form_validation->set_data(['id' => $id]);
$this->setFormRuleDelete();
if ($this->form_validation->run() == false) {
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl', $this->viewData);
return;
}
$this->viewData['msg'] = !$this->acl->deleteAclById($id)
? "Delete Failed"
: "Delete Successful" ;
$this->renderToolsPage('view_acl', $this->viewData);
}
private function setFormRuleSearchForm()
{
$this->form_validation->set_rules(
'card_permission_level_filter',
'Permission Level',
'numeric'
);
}
public function loadRecord(){
$rowno = $this->input->get('rowno');
parse_str($this->input->get('filters'), $filters);
$filters = array_filter($filters, function($val) {
return $val !== '';
});
$this->form_validation->set_data($filters);
$this->setFormRuleSearchForm();
$errors = [];
if ($this->form_validation->run() == false) {
$errors = $this->form_validation->error_array();
}
$filters = array_diff_key($filters, $errors);
// Row per page
$rowperpage = 10;
$cur_page = $rowno;
// Row position
if($rowno != 0){
$rowno = ($rowno-1) * $rowperpage;
}
// All records count
$allcount = $this->acl->getrecordCount($filters);
// Get records
$users_record = $this->acl->getData($rowno,$rowperpage,$filters);
// Pagination Configuration
$config['base_url'] = '/Acl/loadRecord';
$config['use_page_numbers'] = TRUE;
$config['total_rows'] = $allcount;
$config['per_page'] = $rowperpage;
$config['cur_page'] = $cur_page;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
// Initialize
$this->pagination->initialize($config);
// Initialize $data Array
$data['pagination'] = $this->pagination->create_links();
$data['result'] = $users_record;
$data['row'] = $rowno;
echo json_encode($data);
}
}
+292
View File
@@ -0,0 +1,292 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Acl_WhiteList extends Admin_Controller {
public $viewData = [];
private $options_array = [];
public function __construct() {
parent::__construct();
$this->load->library('table');
$this->table->set_template($this->template);
$this->load->model('combo_model');
$this->load->model('Acl_Whitelist_model', 'acl_whitelist');
$this->load->model('Acl_Whitelist_Extra_model', 'acl_whitelist_extra');
// Load Pagination library
$this->load->library('pagination');
$this->options_array = $this->acl_whitelist->getControllerAndMethod();
$this->viewData['class_method'] = $this->combo_model->getControllerCombo('class_method', $this->options_array, '');
$this->viewData['msg'] = null;
// filter
$controller = $this->getController();
$options_array = array_combine($controller, $controller);
$options_array = array_merge($options_array, ['' => 'Select']);
ksort($options_array);
$this->viewData['card_class_filter'] = $this->combo_model->getControllerCombo('card_class_filter', $options_array, '');
$this->viewData['card_permission_level_filter'] = $this->combo_model->getPermissionLevel('card_permission_level_filter', '');
}
private function getController() {
$path = __DIR__;
$controller = array();
$allFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$phpFiles = new RegexIterator($allFiles, '/\.php$/');
foreach ($phpFiles as $phpFile) {
$content = file_get_contents($phpFile->getRealPath());
$tokens = token_get_all($content);
$namespace = '';
for ($index = 0; isset($tokens[$index]); $index++) {
if (!isset($tokens[$index][0])) {
continue;
}
if (T_CLASS === $tokens[$index][0]) {
$index += 2; // Skip class keyword and whitespace
$controller[] = $tokens[$index][1];
}
}
}
sort($controller);
return $controller;
}
protected function renderToolsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('acl_whitelist/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function index()
{
$this->renderToolsPage("view_acl_whitelist", $this->viewData);
}
private function setFormRuleCreate()
{
$this->form_validation->set_rules('class_method', 'Class and Method', 'required|callback_existsAclWhitelist');
$this->form_validation->set_rules('parameter_name', 'Parameter name', 'required|max_length[50]|callback_checkDuplicateAclWhiltelistExtra');
$this->form_validation->set_rules('parameter_value', 'Parameter value', 'required|max_length[50]');
}
public function existsAclWhitelist() {
$id = $this->input->post('class_method');
if (!$id) {
$this->form_validation->set_message('existsAclWhitelist', 'Please enter an existing class and method');
return FALSE;
}
if (!$this->acl_whitelist->getRecordAclWhitelistById(['id' => $id])) {
$this->form_validation->set_message('existsAclWhitelist', 'Please enter an existing class and method');
return FALSE;
} else {
return TRUE;
}
}
public function checkDuplicateAclWhiltelistExtra() {
if ($this->acl_whitelist_extra->getRecordAclWhiteListExtraByParamNameAndParamValueAndAclWhiteListID($this->getFormValue())) {
$this->form_validation->set_message('checkDuplicateAclWhiltelistExtra', 'Oops !!! The value you entered is already in the list');
return FALSE;
} else {
return TRUE;
}
}
private function getFormValue()
{
return [
'bko_acl_whitelist_id' => $this->input->post('class_method'),
'parameter_name' => $this->input->post('parameter_name'),
'parameter_value' => $this->input->post('parameter_value')
];
}
public function create() {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->setFormRuleCreate();
$params = $this->getFormValue();
if ($this->form_validation->run() == false) {
$this->viewData['class_method'] = $this->combo_model->getControllerCombo('class_method', $this->options_array, $params['bko_acl_whitelist_id']);
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
return;
}
if (!$this->acl_whitelist_extra->insertAclWhitelistExtra($params)) {
$this->viewData['msg'] = "Insert Failed";
}
else {
$this->viewData['msg'] = "Insert Succesful";
}
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
}
private function setFormRuleSearchForm() {
$this->form_validation->set_rules(
'card_permission_level_filter',
'Permission Level',
'numeric'
);
}
public function loadRecord() {
$rowno = $this->input->get('rowno');
parse_str($this->input->get('filters'), $filters);
$filters = array_filter($filters, function($val) {
return $val !== '';
});
$this->form_validation->set_data($filters);
$this->setFormRuleSearchForm();
$errors = [];
if ($this->form_validation->run() == false) {
$errors = $this->form_validation->error_array();
}
$filters = array_diff_key($filters, $errors);
// Row per page
$rowperpage = 10;
$cur_page = $rowno;
// Row position
if($rowno != 0){
$rowno = ($rowno-1) * $rowperpage;
}
// All records count
$allcount = $this->acl_whitelist->getrecordCount($filters);
// Get records
$users_record = $this->acl_whitelist->getData($rowno,$rowperpage,$filters);
// Pagination Configuration
$config['base_url'] = '/Acl_Whitelist/loadRecord';
$config['use_page_numbers'] = TRUE;
$config['total_rows'] = $allcount;
$config['per_page'] = $rowperpage;
$config['cur_page'] = $cur_page;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
// Initialize
$this->pagination->initialize($config);
// Initialize $data Array
$data['pagination'] = $this->pagination->create_links();
$data['result'] = $users_record;
$data['row'] = $rowno;
echo json_encode($data);
}
private function setFormRuleUpdate()
{
$this->form_validation->set_rules('id', 'White list Extra', 'required|callback_existsAclWhitelistExtra');
$this->form_validation->set_rules('parameter_name', 'Parameter name', 'required|max_length[50]|callback_checkDuplicateAclWhiltelistExtra');
$this->form_validation->set_rules('parameter_value', 'Parameter value', 'required|max_length[50]');
}
public function existsAclWhitelistExtra($id) {
if (!$id || !is_numeric($id)) {
$this->form_validation->set_message('existsAclWhitelistExtra', 'Please enter an existing white list extra');
return FALSE;
}
if (!$this->acl_whitelist_extra->getRecordAclWhitelistExtraByID(['id' => $id]))
{
$this->form_validation->set_message('existsAclWhitelistExtra', 'Please enter an existing white list extra');
return FALSE;
}
else
{
return TRUE;
}
}
public function update($id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$params = $this->getFormValue();
$params = array_merge($params, ['id' => $id]);
$this->form_validation->set_data($params);
$this->setFormRuleUpdate();
if ($this->form_validation->run() == false) {
$this->viewData['class_method'] = $this->combo_model->getControllerCombo('class_method', $this->options_array, $params['bko_acl_whitelist_id']);
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
return;
}
$result = $this->acl_whitelist_extra->updateAclWhitelistExtra($params);
$this->viewData['msg'] = $result === 0 ? "Update Failed" : "Update Succesful";
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
}
private function setFormRuleDelete()
{
$this->form_validation->set_rules('id', 'White list Extra', 'required|callback_existsAclWhitelistExtra');
}
public function destroy($id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$params = $this->getFormValue();
$this->form_validation->set_data(['id' => $id]);
$this->setFormRuleDelete();
if ($this->form_validation->run() == false) {
$this->viewData['class_method'] = $this->combo_model->getControllerCombo('class_method', $this->options_array, $params['bko_acl_whitelist_id']);
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
return;
}
$result = $this->acl_whitelist_extra->deleteAclWhitelistExtra($id);
$this->viewData['msg'] = $result === 0 ? "Delete Failed" : "Delete Successful";
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
}
}
+267
View File
@@ -0,0 +1,267 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Addresses extends Admin_Controller
{
public $viewData = array();
public $countries = array();
public $pagePerItem = 10;
private $geocode;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('combo_model');
$this->load->model('address_model', 'address');
$this->load->model('Geofence_area_city_model', 'geofence_area_city');
$this->viewData['selectedTab'] = 'address';
$this->load->helper('pagination');
}
public function index()
{
$page = $this->input->get('page', true);
$params = [];
if ($page) {
$params = ['page' => $page];
};
$this->viewData['city'] = $this->combo_model->getCityCombo('city', trim($this->input->get('city')));
$data = $this->address->getAddresses($params);
$this->viewData['radius_default'] = 'on';
$this->viewData['list'] = $data['list'];
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $data['page'], '/addresses');
$this->renderAdminPage('addresses/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['errMsg'] = null;
$this->setFormRule();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('addresses/create', $this->viewData);
return;
}
$params = $this->getFormValue();
$res = $this->address->createAddress($params);
if ($res['success']) {
$this->session->set_flashdata('success', $res['message']);
redirect('/addresses');
} else {
$this->viewData['errMsg'] = $res['error'];
$this->viewData['address'] = $params;
}
$this->load->view('addresses/create', $this->viewData);
}
public function getParamsRequest()
{
return [
'city' => trim($this->input->get('city_id', true)),
'city_name' => trim($this->input->get('city_name', true)),
'address' => trim($this->input->get('address', true)),
'radius' => trim($this->input->get('radius', true)),
'longitude' => trim($this->input->get('longitude', true)),
'latitude' => trim($this->input->get('latitude', true)),
'radius_default' => $this->input->get('radius_default'),
];
}
public function search()
{
$params = $this->getParamsRequest();
$page = $this->input->get('page', true);
$params = array_filter($params, function ($val) {
return $val !== '';
});
$pagingUrl = '/addresses/search?' . http_build_query($params);
if ($page) {
$params['page'] = $page;
}
$data = $this->address->getAddresses($params);
$this->viewData['city'] = $this->combo_model->getCityCombo('city', $this->input->get('city'));
$this->viewData['list'] = $data['list'];
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $data['page'], $pagingUrl);
$this->viewData = array_merge($this->viewData, $params);
$this->renderAdminPage('addresses/list', $this->viewData);
}
public function addressEdit($param)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
// Check if user edit the id through browser inspect
$this->viewData['address'] = ['id' => $param];
$id = $this->input->post('id');
if (isset($id) && $id != $param) {
redirect('/addresses');
}
$res = $this->address->getAddressById($param);
$this->viewData['address'] = $res['data'];
if (isset($res['error'])) {
redirect('/addresses');
return;
}
$this->viewData['errMsg'] = null;
$this->setFormRule();
if ($this->form_validation->run() == false) {
$this->viewData['errMsg'] = validation_errors();
$this->renderAdminPage('addresses/edit', $this->viewData);
return;
}
$params = $this->getFormValue();
$updateParams = http_build_query($params);
$res = $this->address->updateAddressById($id, $updateParams);
if ($res['success']) {
$this->session->set_flashdata('success', $res['message']);
redirect('/addresses');
} else {
$this->viewData['errMsg'] = $res['error'];
$this->viewData['address'] = $params;
}
$this->viewData['address'] = $params;
$this->renderAdminPage('addresses/edit', $this->viewData);
}
public function remove($param)
{
$res = $this->address->removeAddressById($param);
if ($res['success']) {
$this->session->set_flashdata('success', $res['message']);
} else {
$this->session->set_flashdata('error', $res['error']);
}
redirect('/addresses');
}
private function setFormRule()
{
$this->form_validation->set_rules('address', 'Address', 'required|callback_isValidAddress');
$this->form_validation->set_rules('geocoding_date', 'Geocoding date', 'required|callback_isDate');
$this->form_validation->set_rules('description', 'Description', 'max_length[100]');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormValue()
{
return [
'address' => trim($this->input->post('address')),
'geocoding_date' => trim($this->input->post('geocoding_date')),
'description' => trim($this->input->post('description')),
'latitude' => $this->geocode['lat'],
'longitude' => $this->geocode['lng'],
'timezone' => $this->geocode['timezone'],
'postal' => $this->geocode['postal'],
'country' => $this->geocode['country'],
'geometry' => $this->convertToGeometry($this->geocode),
'city' => $this->geocode['city_id'],
];
}
public function isDate($date)
{
$matches = [];
$result = preg_match_all("/^([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date, $matches, PREG_SET_ORDER);
if ($result == 0 || $result == false) {
$this->form_validation->set_message('isDate', 'Geocoding date is invalid');
return false;
}
$day = $matches[0][3];
$month = $matches[0][2];
$year = $matches[0][1];
if (checkdate($month, $day, $year)) {
return true;
} else {
$this->form_validation->set_message('isDate', 'Geocoding date is invalid');
return false;
}
}
public function isValidAddress($address)
{
$this->geocode = SQEAPI::geocode($address)['geocode'];
if (!$this->geocode) {
$this->form_validation->set_message('isValidAddress', 'Address is invalid');
return false;
}
$this->city = $this->geofence_area_city->getCityByCoordindates([
'latitude' => $this->geocode['lat'],
'longitude' => $this->geocode['lng'],
'radius' => 5, // km
]);
if (!$this->city) {
$this->form_validation->set_message('isValidAddress', 'Address is invalid');
return false;
}
$this->geocode['city_id'] = $this->city[0]['id'];
return true;
}
public function getAddressesAjax()
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$result = $this->address->getAddressesWithUsingQuery([
'address' => trim($this->input->get('name')),
'page' => $this->input->get('page'),
]);
echo json_encode([
'data' => $result['data'],
'total' => $result['total'],
]);
}
private function convertToGeometry($params)
{
$query = "";
$query = "SELECT(ST_GeomFromText('"
. "POINT(" . $params['lat'] . " "
. $params['lng'] . ")', 4326)) AS geometry";
$rs = $this->read_replica->query($query);
return $rs->row_array()['geometry'];
}
}
+524
View File
@@ -0,0 +1,524 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Advice extends Admin_Controller
{
const CSV_FIELDS = [
'travel_date', // | 2019-11-19 08:58:00
'duration', // | 26
'cost_raw', // | SGD 13.00
'cost', // | 13.00
'updated', // | 2019-11-19 03:53:48.809183
'distance', // | 10.77
'transport_provider_id', // | 3
'travel_date_end', // | 2019-11-19 09:24:55
'location_start_id', // | 7276
'location_end_id', // | 7277
'location_start_address', // | 65 Jurong West Central 3, Singapore, 648332
'location_start_lat', // | 1.339345
'location_start_lng', // | 103.705984
'location_start_postal', // |
'location_start_country', // | SG
'location_start_description', // |
'location_start_tz', // | Asia/Singapore
'location_end_address', // | 3 Engineering Drive 3, Singapore, 117582
'location_end_lat', // | 1.299255
'location_end_lng', // | 103.772206
'location_end_postal', // |
'location_end_country', // | SG
'location_end_description', // |
'location_end_tz' // | Asia/Singapore
];
public function __construct()
{
parent::__construct();
$this->load->model('advice_model');
$this->load->model('receipt_advice_model');
// Load form validation library
$this->load->library('form_validation');
// Load file helper
$this->load->helper('file');
}
public function index()
{
$data = array();
$this->load->helper('url');
$this->advicelist();
}
protected function renderAdvicePage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view('advice/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function advicelist()
{
$data = [];
$data["page_title"] = "Advice List";
$data['advice_list'] = [];
$data['pagination_link'] = [];
$params = [];
$params = $this->input->get();
if (!empty($params)) {
$this->form_validation->set_data($params);
$this->setSearchRules();
if ($this->form_validation->run() == false) {
$this->renderAdvicePage("view_advice", $data);
return;
}
}
$query = $this->advice_model->getAdviceQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'advice/advicelist',
[
'per_page' => 100,
'reuse_query_string' => TRUE,
]
);
$data['advice_list'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$this->renderAdvicePage("view_advice", $data);
}
public function advicejson()
{
$id = $this->input->get('id');
if ($id == '' || $id < 1) {
echo '{"message":"Invalid ID"}';
return;
}
$q = "SELECT * FROM parsedemail_item WHERE id=" . $id;
$r = $this->read_replica->query($q);
$parsedemail_item = $r->row_array();
$q = "SELECT * FROM parsedemail_item_advice_google WHERE parsedemail_item_id = ${id}";
$r = $this->read_replica->query($q);
$advices = [];
foreach ($r->result() as $f) {
$advices[] = (array) $f;
}
foreach ($advices as $j => $advice) {
$q = "SELECT * FROM google_directions_legs WHERE parsedemail_item_advice_google_id = " . $advice["id"];
$r = $this->read_replica->query($q);
$legs = [];
foreach ($r->result() as $f) {
$legs[] = (array) $f;
}
foreach ($legs as $i => $leg) {
$q = "SELECT a.id AS step_id,a.distance,a.duration,a.travel_mode,a.location_start_lat,a.location_start_lng,a.location_end_lat,a.location_end_lng,a.html_instructions,a.polyline,b.* ";
$q .= ",c.name,c.service,c.board,c.alight,c.distance AS quote_distance,c.fare,c.fare_raw,c.distance_raw";
$q .= " FROM google_directions_leg_steps a LEFT JOIN google_directions_leg_step_details b ON (b.google_directions_leg_step_id=a.id) ";
$q .= " LEFT JOIN leg_step_quote c ON c.google_directions_leg_step_id=a.id ";
$q .= " WHERE a.google_directions_leg_id=" . $leg['id'];
$r = $this->read_replica->query($q);
$steps = [];
foreach ($r->result() as $f) {
$data = (array) $f;
foreach ($data as $key => $val) {
if ($val == NULL || $val == "") {
unset($data[$key]);
}
}
$steps[] = $data;
}
$leg['steps'] = $steps;
$legs[$i] = $leg;
}
$advice["legs"] = $legs;
$advices[$j] = $advice;
}
$parsedemail_item["advices"] = $advices;
echo json_encode($parsedemail_item);
/* echo '{
"id": 224583,
"location_start": "97 Meyer Rd, 93, Singapore 437918",
"location_end": "1 Fusionopolis Way, #01-07 & #02-14, Connexis, Singapore 138632",
"cost_raw": "14.6",
"trackedemail_item_id": 0,
"cost": "14.60",
"transport_provider_id": 4,
"location_start_lat": "1.2970576",
"location_start_lng": "103.8925856",
"location_end_lat": "1.2987049",
"location_end_lng": "103.7875699",
"request_date": "2020-01-09T13:09:00.955Z",
"started": "2020-01-09T13:09:04.203Z",
"complete": "2020-01-09T13:09:04.743Z",
"status": 0,
"message": "android_automation_job_detail",
"attempts": 0,
"automation_id": 206441,
"completed": "2020-01-09T13:09:04.743Z",
"created": "2020-01-09 13:09:01.072305",
"location_start_id": "4426",
"location_end_id": "4386",
"member_id": "13",
"deeplink": "ComfortDelGroTaxi:\/\/\/?action=setBooking&endingLat=1.298705&endingLong=103.787570&startingLat=1.297085&startingLong=103.892571"
}'; // */
}
private function setSearchRules()
{
$config = [
[
'field' => 'travel_date',
'label' => 'Travel date',
'rules' => 'trim',
],
[
'field' => 'duration_from',
'label' => 'Duration from',
'rules' => 'trim|numeric',
],
[
'field' => 'duration_to',
'label' => 'Duration to',
'rules' => 'trim|numeric',
],
[
'field' => 'distance_from',
'label' => 'Distance from',
'rules' => 'trim|numeric',
],
[
'field' => 'distance_to',
'label' => 'Distance to',
'rules' => 'trim|numeric',
],
[
'field' => 'location_start_id',
'label' => 'Location start',
'rules' => 'integer',
],
[
'field' => 'location_start_name',
'label' => 'Location start name',
'rules' => 'trim',
],
[
'field' => 'location_end_id',
'label' => 'Location end',
'rules' => 'integer',
],
[
'field' => 'location_end_name',
'label' => 'Location end name',
'rules' => 'trim',
],
];
$this->form_validation->set_rules($config);
}
public function exportCSV()
{
$this->load->helper('export_csv');
$data = [];
$data["page_title"] = "Advice List";
$data['advice_list'] = [];
$data['pagination_link'] = [];
$params = [];
$params = $this->input->get();
if (!empty($params)) {
$this->form_validation->set_data($params);
$this->setSearchRules();
if ($this->form_validation->run() == false) {
$this->renderAdvicePage("view_advice", $data);
return;
}
}
$params = array_filter($params, function ($val) {
return $val !== '';
});
$query = $this->advice_model->getAdviceQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'advice/advicelist',
[
'per_page' => 100,
'reuse_query_string' => TRUE,
]
);
$data['advice_list'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$query = $this->advice_model->get_query_parsed_email_quote_records($params);
$r = $this->read_replica->query($query);
if ($r->result_array()[0]['all_count'] === '0') {
$this->session->set_flashdata('error', 'Data not found !!!');
$this->renderAdvicePage("view_advice", $data);
return;
}
$this->read_replica->save_queries = false;
$query = $this->advice_model->get_query_parsed_email_quote_records(
$params,
self::NONE_COUNT_RECORD
);
$r = $this->read_replica->query($query);
export($r);
}
public function upload()
{
$this->load->helper('upload_file');
upload_file();
}
public function importCSV()
{
$this->load->helper('directory');
$row = 0;
$file_path = $_SERVER['DOCUMENT_ROOT']
. DIRECTORY_SEPARATOR
. self::TEMP_DIRECTORY_UPLOAD;
$file_name = scandir($file_path);
if ( ! $file_name) {
echo json_encode([
'code' => '404',
'message' => 'File Not Found !!!'
]);
}
if (($handle = fopen($file_path . '/' . $file_name[2], "r")) !== FALSE) {
deleteDir($file_path);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$f = [];
for ($c=0; $c < $num; $c++) {
$f[self::CSV_FIELDS[$c]] = $data[$c];
}
if ($row>0) {
$this->save_record($f);
}
$row++;
}
fclose($handle);
}
echo json_encode([
'code' => '201',
'message' => 'Imported Successfully !!!'
]);
}
function save_record($f)
{
$member_id = $this->input->post()['member_id'];
$location_start_id = $this->get_address($f, 'start');
$location_end_id = $this->get_address($f, 'end');
if ($location_start_id < 1 || $location_end_id < 1) {
echo "Invalid address\n";
return NULL;
}
$q = "INSERT INTO trackedemail_item (member_id) VALUES(${member_id}) RETURNING id";
$trackedemail_item_id = NULL;
$r = $this->db->query($q);
if (isset($r->result_array()[0]['id'])) {
$trackedemail_item_id = $r->result_array()[0]['id'];
} else {
return NULL;
}
$q = "INSERT INTO parsedemail_item (travel_date,duration,cost_raw,trackedemail_item_id,cost,updated,distance,transport_provider_id,travel_date_end,location_start_id,location_end_id) VALUES (";
$q .= "'" . pg_escape_string($f["travel_date"]) . "',"; // | 2019-11-19 08:58:00
$q .= $f['duration'] == '' ? "NULL," : (((int) $f["duration"]) . ","); // | 26
$q .= "'" . pg_escape_string($f["cost_raw"]) . "',"; // | SGD 13.00
$q .= $trackedemail_item_id == NULL ? "NULL," : (((int) $trackedemail_item_id) . ",");
$q .= $f['cost'] == '' ? "NULL," : (floatval($f["cost"]) . ","); // | 13.00
$q .= $f['updated'] == '' ? "NULL," : ("'" . pg_escape_string($f["travel_date"]) . "',"); // | 2019-11-19 03:53:48.809183
$q .= $f['distance'] == '' ? "NULL," : (floatval($f["distance"]) . ","); // | 10.77
$q .= $f['transport_provider_id'] == '' ? "NULL," : (((int) $f["transport_provider_id"]) . ","); // | 3
$q .= $f['travel_date_end'] == '' ? "NULL," : ("'" . pg_escape_string($f["travel_date_end"]) . "',"); // | 2019-11-19 09:24:55
$q .= $location_start_id . "," . $location_end_id;
$q .= ") RETURNING id";
$r = $this->db->query($q)->result_array();
if (count($r) === 0) {
echo $q . "\n";
if ($trackedemail_item_id > 0) {
$q = "DELETE FROM trackedemail_item WHERE member_id = ${member_id} AND id = ${trackedemail_item_id}";
$this->db->query($q);
}
return NULL;
}
}
private function get_address($f, $what)
{
$tzid = $this->get_timezone($f, $what);
$q = "SELECT * FROM address WHERE lower(address)=lower('" . pg_escape_string($f["location_${what}_address"]) . "') and latitude=";
$q .= floatval($f["location_${what}_lat"]) . " AND longitude=" . floatval($f["location_${what}_lng"]);
$r = $this->read_replica->query($q)->result_array();
if (count($r)) {
return $r[0]['id'];
} else {
echo $q . "\n";
}
$q = "INSERT INTO address (address,latitude,longitude,timezone,geocoding_date,postal,country,geometry,description) VALUES(";
$q .= "'" . pg_escape_string($f["location_${what}_address"]) . "',"; // | 65 Jurong West Central 3, Singapore, 648332
$q .= floatval($f["location_${what}_lat"]) . ","; // | 1.339345
$q .= floatval($f["location_${what}_lng"]) . ","; // | 103.705984
$q .= $tzid . ",NOW(),"; // |
$q .= "'" . pg_escape_string($f["location_${what}_postal"]) . "',"; //
$q .= "'" . pg_escape_string($f["location_${what}_country"]) . "',"; // | SG
$q .= "st_setsrid(st_point(" . $f["location_${what}_lng"] . "," . $f["location_${what}_lat"] . "),4326),";
if ($f["location_${what}_description"] == '') {
$q .= "NULL";
} else {
$q .= "'" . pg_escape_string($f["location_${what}_description"]) . "'"; // |
}
$q .= ") RETURNING id";
$r = $this->db->query($q)->result_array();
if (count($r)) {
return $r[0]['id'];
} else {
echo $q . "\n";
}
return NULL;
}
private function get_timezone($f, $what)
{
$q = "SELECT * FROM address_timezone WHERE lower(timezone)=lower('" . pg_escape_string($f["location_${what}_tz"]) . "')";
$r = $this->read_replica->query($q)->result_array();
if (count($r)) {
return $r[0]['id'];
}
$q = "INSERT INTO address_timezone (timezone) VALUES('" . pg_escape_string($f["location_${what}_tz"]) . "') RETURNING id";
$r = $this->db->query($q)->result_array();
if (count($r)) {
return $r[0]['id'];
}
return NULL;
}
// Receipt Advice
public function receiptadvice()
{
$data = [];
$data["page_title"] = "Receipt Advice";
$data['receipt_advice'] = [];
$data['pagination_link'] = [];
$params = [];
$params = $this->input->get();
if (!empty($params)) {
$this->form_validation->set_data($params);
$this->setSearchRules();
if ($this->form_validation->run() == false) {
$this->renderAdvicePage("view_receipt_advice", $data);
return;
}
}
$query = $this->receipt_advice_model->getAdviceQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'advice/receiptadvice',
[
'per_page' => 100,
'reuse_query_string' => TRUE,
]
);
$data['receipt_advice'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$this->renderAdvicePage("view_receipt_advice", $data);
}
public function exportCSV_receipt_advice()
{
$this->load->helper('export_csv');
$data = [];
$data["page_title"] = "Advice List";
$data['receipt_advice'] = [];
$data['pagination_link'] = [];
$params = [];
$params = $this->input->get();
if (!empty($params)) {
$this->form_validation->set_data($params);
$this->setSearchRules();
if ($this->form_validation->run() == false) {
$this->renderAdvicePage("view_receipt_advice", $data);
return;
}
}
$params = array_filter($params, function ($val) {
return $val !== '';
});
$query = $this->receipt_advice_model->getAdviceQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'advice/receiptadvice',
[
'per_page' => 100,
'reuse_query_string' => TRUE,
]
);
$data['receipt_advice'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$query = $this->receipt_advice_model->get_query_parsed_email_quote_records($params);
$r = $this->read_replica->query($query);
if ($r->result_array()[0]['all_count'] === '0') {
$this->session->set_flashdata('error', 'Data not found !!!');
$this->renderAdvicePage("view_receipt_advice", $data);
return;
}
$this->read_replica->save_queries = false;
$query = $this->receipt_advice_model->get_query_parsed_email_quote_records(
$params,
self::NONE_COUNT_RECORD
);
$r = $this->read_replica->query($query);
export($r);
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Ajax extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('geofence_area_city_model');
}
public function geocodeReverse($latitude, $longitude)
{
//$this->output(['city' => "Wrocław"]);
global $savvyext;
$httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');
// Call geocoding service
$url = "http://oauth2.service/api/v1/reverse/?lat=" . $latitude . '&lng=' . $longitude;
$opts = array(
'http' => array(
'method' => "GET",
'timeout' => 60, /* 1 minute */
'header' =>
"Content-Type: application/x-www-form-urlencoded\r\n" .
"Accept: application/json\r\n" .
"Authorization: Server-Token ${httpAuthToken}\r\n",
),
);
$context = stream_context_create($opts);
$body = file_get_contents($url, false, $context);
$geocoded = json_decode($body, true);
if (is_array($geocoded) && is_array($geocoded["data"]) && !isset($geocoded["error"])) {
return $geocoded["data"]['city'];
}
return null;
}
public function updatecity($id, $latitude, $longitude)
{
$error = 1;
$city = $this->geocodeReverse($latitude, $longitude);
if (!empty($city)) {
$inputData = [
'city' => $city,
];
if ($this->geofence_area_city_model->update($id, $inputData) > 0) {
$error = 0;
$this->output(['error' => $error, 'msg' => 'Updated geofence area city successfully.','city'=>$city]);
} else {
$this->output(['error' => $error, 'msg' => 'Updated failed.','city'=>$city]);
}
}
$this->output(['error' => $error, 'msg' => 'Invalid input.','city'=>$city]);
}
public function cleanupCities(){
$duplicateds=$this->geofence_area_city_model->getDuplicatedCities();
$error=0;
foreach($duplicateds as $city){
$city_name =$city->city;
$country =$city->country;
$condition="LOWER(city) ILIKE '" . strtolower(pg_escape_string($city_name)) . "' AND country='" . $country . "'";
$city_ids = $this->geofence_area_city_model->getCities($condition);
$num = count($city_ids);
if ($num > 0) {
$ids=[];
foreach ($city_ids as $info) {
$ids[]=$info->id;
}
if(count($ids)>0){
$city_id = $ids[0];
$data_update = [
'city_id' => $city_id,
];
$condition = "country='" . $country . "' AND city_id IN (" . implode(",", $ids) . ")";
$updated = $this->geofence_area_city_model->updateAddresses($condition, $data_update);
}
}
}
$this->geofence_area_city_model->deleteUnusedCities();
$this->output(['error' => $error, 'msg' => 'Clean up successfully']);
}
private function output($output)
{
echo json_encode($output);exit;
}
}
@@ -0,0 +1,294 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Android_automation_job_details extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 50;
public $statusOptions = [
'Inactive' => '0',
'Active' => '1',
];
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('android_automation_job_detail_model', 'android_automation_job_detail');
$this->load->model('transport_provider_model', 'transport_provider');
$this->load->model('automation_job_model', 'automation_job');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('url'));
//get query string filter
$filterData = $this->input->get();
$queryString = $this->input->server('QUERY_STRING');
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->android_automation_job_detail->getAndroidAutomationJobDetail(
[
'transport_provider_id' => !empty($filterData['transport_provider_id'])
? $filterData['transport_provider_id']
: '',
'job_id' => empty($filterData['job_id'])
? ''
: $filterData['job_id'],
'uuid' => empty($filterData['uuid'])
? ''
: $filterData['uuid'],
'name' => empty($filterData['name'])
? ''
: $filterData['name'],
'service_id' => empty($filterData['service_id'])
? ''
: $filterData['service_id'],
'page' => isset($filterData['page']) ? $filterData['page'] : 1
]
);
$transport_provider = [];
// Change data to array for display
foreach ($data['transport_providers'] as $tp) {
$transport_provider[] = (array) $tp;
}
$this->viewData['transport_provider'] = $transport_provider;
$data['list'] = array_map(function($item) {
$item['quote_date'] = $this->formatDate($item['quote_date']);
return $item;
}, $data['list']);
$this->viewData['list'] = $data['list'];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['totalItems'], $data['page'], $pagingUrl);
$this->renderAdminPage('android_automation_job_details/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['android_automation_job_detail'] = null;
$this->renderAdminPage('android_automation_job_details/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$inputData = $this->getFormData();
$this->viewData['android_automation_job_detail'] = $inputData;
$this->viewData['statusOptions'] = $this->statusOptions;
$this->setAndroidAutomationJobDetailCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('android_automation_job_details/create', $this->viewData);
return;
}
$res = $this->android_automation_job_detail->createAndroidAutomationJobDetail($inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isset($res['message']) ? $res['message'] : 'Create success.');
redirect('/android_automation_job_details');
} else {
$this->session->set_flashdata('error', isset($res['message']) ? $res['message'] : 'Create fail.');
$this->renderAdminPage('android_automation_job_details/create', $this->viewData);
return;
}
}
private function formatDate($date) {
return (new DateTime($date))->format('Y-m-d');
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$res = $this->android_automation_job_detail->getAndroidAutomationJobDetailByID($id);
if ($res['data']) {
$res['data']['quote_date'] = $this->formatDate($res['data']['quote_date']);
}
$this->viewData['android_automation_job_detail'] = isset($res['data']) ? $res['data'] : [];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['id'] = $id;
$this->renderAdminPage('android_automation_job_details/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$inputData = $this->getFormData();
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['android_automation_job_detail'] = $inputData;
$this->viewData['id'] = $id;
$this->setAndroidAutomationJobDetailCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('android_automation_job_details/edit', $this->viewData);
return;
}
$res = $this->android_automation_job_detail->updateAndroidAutomationJobDetailById($id, $inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isset($res['message']) ? $res['message'] : 'Create success');
redirect('/android_automation_job_details');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->renderAdminPage('android_automation_job_details/edit', $this->viewData);
return;
}
}
public function remove($param)
{
$res = $this->android_automation_job_detail->removeAndroidAutomationJobDetailById($param);
if (!$res['success'] != 'success') {
$this->viewData['errMsg'] = isset($res['message']) ? $res['message'] : 'Something went wrong. Please try again later.';
$this->renderAdminPage('android_automation_job_details', $this->viewData);
return;
}
redirect('/android_automation_job_details');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormData()
{
return [
'job_id' => $this->input->post('job_id'),
'icon_info' => $this->input->post('icon_info'),
'name' => $this->input->post('name'),
'icon_url' => $this->input->post('icon_url'),
'descriptor' => $this->input->post('descriptor'),
'warning_message' => $this->input->post('warning_message'),
'uuid' => $this->input->post('uuid'),
'series_id' => $this->input->post('series_id'),
'service_id' => $this->input->post('service_id'),
'additional_booking_fee' => $this->input->post('additional_booking_fee'),
'advance_booking_fee' => $this->input->post('advance_booking_fee'),
'low_estimate' => $this->input->post('low_estimate'),
'high_estimate' => $this->input->post('high_estimate'),
'fixed' => $this->input->post('fixed'),
'quote_date' => $this->input->post('quote_date'),
];
}
private function setAndroidAutomationJobDetailCreationRules()
{
$config = [
[
'field' => 'job_id',
'label' => 'Job ID',
'rules' => 'required',
],
[
'field' => 'icon_info',
'label' => 'Icon Info',
'rules' => 'required',
],
[
'field' => 'name',
'label' => 'Nmae',
'rules' => 'required',
],
[
'field' => 'icon_url',
'label' => 'Icon Url',
'rules' => 'required',
],
[
'field' => 'descriptor',
'label' => 'Descriptor',
'rules' => 'required'
],
[
'field' => 'warning_message',
'label' => 'Warning Message',
'rules' => 'required',
],
[
'field' => 'uuid',
'label' => 'UUID',
'rules' => 'required',
],
[
'field' => 'series_id',
'label' => 'Series ID',
'rules' => 'required',
],
[
'field' => 'service_id',
'label' => 'Service ID',
'rules' => 'required',
],
[
'field' => 'additional_booking_fee',
'label' => 'Additional Booking Fee',
'rules' => 'required',
],
[
'field' => 'advance_booking_fee',
'label' => 'Advance Booking Fee',
'rules' => 'required',
],
[
'field' => 'low_estimate',
'label' => 'Low Estimate',
'rules' => 'required',
],
[
'field' => 'high_estimate',
'label' => 'High Estimate',
'rules' => 'required',
],
[
'field' => 'fixed',
'label' => 'Fixed',
'rules' => 'required',
],
[
'field' => 'quote_date',
'label' => 'Quote Date',
'rules' => 'required',
]
];
$this->form_validation->set_rules($config);
}
public function getTransportProviderByName() {
$name = $this->input->get()['q'];
$res = $this->transport_provider->getTransportProviderByName($name);
echo json_encode($res);
}
}
+225
View File
@@ -0,0 +1,225 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Automation_jobs extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 50;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('automation_job_model', 'automation_job');
$this->load->helper('pagination');
}
public function setOnePastWeek(&$params) {
if (
(empty($params['from_complete']))
&& (empty($params['to_complete']))
) {
$params['from_complete'] = date('Y-m-d', strtotime('-1 week'));
$params['to_complete'] = date('Y-m-d');
}
}
public function index()
{
$this->load->helper(array('url'));
//get query string filter
$filterData = $this->input->get();
$this->setOnePastWeek($filterData);
$filterData['transport_provider_name'] = '';
$queryString = $this->input->server('QUERY_STRING');
// remove empty value
$filterData = array_map(function($ele) {
return trim($ele);
}, $filterData);
$filterData = array_filter($filterData, function ($v, $k) {
return $v !== '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->automation_job->getJobs($filterData);
$this->viewData['list'] = $data['list'];
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['totalItems'], $data['page'], $pagingUrl);
$this->viewData = array_merge($this->viewData, $filterData);
$this->renderAdminPage('automation_jobs/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['job'] = null;
$this->renderAdminPage('automation_jobs/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['job'] = null;
$this->setJobCreationRules();
$inputData = $this->getFormData();
if ($this->form_validation->run() == false) {
$this->viewData['job'] = $this->prepareTransportProviderData();
$this->renderAdminPage('automation_jobs/create', $this->viewData);
return;
}
$res = $this->automation_job->createJob($inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success.');
redirect('/automation_jobs');
} else {
$this->viewData['job'] = $this->prepareTransportProviderData();
$this->session->set_flashdata('error', isSet($res['message']) ? $res['message'] : 'Create fail.');
$this->renderAdminPage('automation_jobs/create', $this->viewData);
return;
}
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$res= $this->automation_job->getById($id);
$job = isSet($res['data']) ? $res['data'] : [];
$this->viewData['job'] = $job;
$this->viewData['transport_provider_name'] = isset($job) ? $job['transport_provider_name'] : "";
$this->viewData['jobId'] = $id;
$this->renderAdminPage('automation_jobs/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['job'] = null;
$this->viewData['jobId'] = $id;
$this->setJobCreationRules();
if ($this->form_validation->run() == false) {
$this->viewData['job'] = $this->prepareTransportProviderData();
$this->renderAdminPage('automation_jobs/edit', $this->viewData);
return;
}
$inputData = $this->getFormData();
$inputData['id'] = (int) $id;
$res = $this->automation_job->updateById($id, $inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success');
redirect('/automation_jobs');
} else {
$this->viewData['job'] = $this->prepareTransportProviderData();
$this->session->set_flashdata('error', $res['message']);
$this->renderAdminPage('automation_jobs/edit', $this->viewData);
return;
}
}
public function remove($param)
{
$res = $this->automation_job->removeById($param);
if (!$res['success'] != 'success') {
$this->viewData['errMsg'] = isSet($res['message']) ? $res['message'] : 'Something went wrong. Please try again later.';
$this->renderAdminPage('automation_jobs', $this->viewData);
return;
}
redirect('/automation_jobs');
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormData() {
return [
'location_start' => $this->input->post('location_start'),
'location_end' => $this->input->post('location_end'),
'location_start_lat' => $this->input->post('location_start_lat'),
'location_start_lng' => $this->input->post('location_start_lng'),
'location_end_lat' => $this->input->post('location_end_lat'),
'location_end_lng' => $this->input->post('location_end_lng'),
'cost_raw' => $this->input->post('cost_raw'),
'transport_provider_id' => (int) $this->input->post('transport_provider_id'),
'trackedemail_item_id' => $this->input->post('trackedemail_item_id'),
'cost' => $this->input->post('cost'),
'started' => $this->input->post('started'),
'complete' => $this->input->post('complete'),
'status' => $this->input->post('status'),
'message' => $this->input->post('message'),
'attempts' => (int) $this->input->post('attempts'),
];
}
private function setJobCreationRules()
{
$config = [
[
'field' => 'location_start',
'label' => 'Location start',
'rules' => 'required|max_length[200]',
'errors' => array(
'max_length' => 'Max length is 200.'
),
],
[
'field' => 'location_end',
'label' => 'Location end',
'rules' => 'required|max_length[200]',
'errors' => array(
'max_length' => 'Max length is 200.'
)
],
[
'field' => 'trackedemail_item_id',
'label' => 'Trackedemail Item',
'rules' => 'required'
],
[
'field' => 'transport_provider_id',
'label' => 'Transport provider',
'rules' => 'required',
],
];
$this->form_validation->set_rules($config);
}
private function prepareTransportProviderData() {
return [
'transport_provider_id' => (int) $this->input->post('transport_provider_id'),
'transport_provider_name' => $this->input->post('transport_provider_name')
];
}
public function getAndroidAutomationJobsByTransportProvider() {
$transport_provider_id = (int)$this->input->get('transport_provider_id');
$data = $this->automation_job->getJobs(
$transport_provider_id === 0 ? [] : [ 'transport_provider_id' => $transport_provider_id ]
);
echo json_encode([
'android_automation_jobs' => $data['list']
]);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+109
View File
@@ -0,0 +1,109 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Blog extends Admin_Controller {
public function index() {
$data['page_title'] = 'Blog';
$this->renderPage('index', $data);
}
public function getBlogs() {
$postData = $this->input->post();
$this->validate($postData, 'filter');
$params = !empty($postData['params']) ? $postData['params'] : null;
$pageNo = !empty($postData['pageNo']) ? $postData['pageNo'] - 1 : 0;
$pageSize = !empty($postData['pageSize']) ? $postData['pageSize'] : 10;
$this->load->model('blog_model');
$data = $this->blog_model->getBlogs($params, $pageNo, $pageSize);
echo json_encode($data);
}
public function store() {
$postData = $this->input->post();
$this->validate($postData);
$this->load->model('blog_model');
// Find record with blog_id
$record = $this->blog_model->getBlogs(['blog_id' => $postData['blog_id']]);
// If we found a record then return errors
if(!empty($record['result'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => ['message' => 'This Blog ID had been used']]);
return;
}
$this->blog_model->store($postData);
echo json_encode(['message' => 'Added successfully!']);
}
public function update() {
$postData = $this->input->post();
$this->validate($postData);
$this->load->model('blog_model');
// Find record with blog_id
$record = $this->blog_model->getBlogs(['blog_id' => $postData['blog_id']]);
// If we found a record then return errors
if(!empty($record['result']) && $record['result'][0]['id'] != $postData['id']) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => ['message' => 'This Blog ID had been used']]);
return;
}
$id = array_shift($postData);
$this->blog_model->update($id, $postData);
echo json_encode(['message' => 'Updated successfully!']);
}
public function delete() {
$postData = $this->input->post();
$this->load->model('blog_model');
$this->blog_model->delete($postData);
echo json_encode(['message' => 'Deleted successfully!']);
}
protected function validate($data, $type = 'saveOrUpdate') {
$this->load->library('form_validation');
$this->form_validation->set_data($data);
$this->setFormRuleForBlog($type);
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => $errors]);
exit;
}
}
protected function setFormRuleForBlog($type) {
if ($type === 'filter') {
$this->form_validation->set_rules('params[blog_id]', 'Blog ID', 'integer');
$this->form_validation->set_rules('params[status]', 'Status', 'integer');
return;
}
$this->form_validation->set_rules('blog_id', 'Blog ID', 'required|integer');
$this->form_validation->set_rules('description', 'Description', 'required');
$this->form_validation->set_rules('status', 'Status', 'integer');
}
protected function renderPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('blog/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
@@ -0,0 +1,110 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Blog_app_articles extends Admin_Controller {
public function index() {
$data['page_title'] = 'Blog App Articles';
$this->renderPage('index', $data);
}
public function getBlogs() {
$postData = $this->input->post();
$this->validate($postData, 'filter');
$params = !empty($postData['params']) ? $postData['params'] : null;
$pageNo = !empty($postData['pageNo']) ? $postData['pageNo'] - 1 : 0;
$pageSize = !empty($postData['pageSize']) ? $postData['pageSize'] : 10;
$this->load->model('blog_app_article_model');
$data = $this->blog_app_article_model->getBlogs($params, $pageNo, $pageSize);
echo json_encode($data);
}
public function store() {
$postData = $this->input->post();
$this->validate($postData);
$this->load->model('blog_app_article_model');
// Find record with blog_id
$record = $this->blog_app_article_model->getBlogs(['blog_id' => $postData['blog_id']]);
// If we found a record then return errors
if(!empty($record['result'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => ['message' => 'This Blog ID had been used']]);
return;
}
$this->blog_app_article_model->store($postData);
echo json_encode(['message' => 'Added successfully!']);
}
public function update() {
$postData = $this->input->post();
$this->validate($postData);
$this->load->model('blog_app_article_model');
// Find record with blog_id
$record = $this->blog_app_article_model->getBlogs(['blog_id' => $postData['blog_id']]);
// If we found a record then return errors
if(!empty($record['result']) && $record['result'][0]['id'] != $postData['id']) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => ['message' => 'This Blog ID had been used']]);
return;
}
$id = array_shift($postData);
$this->blog_app_article_model->update($id, $postData);
echo json_encode(['message' => 'Updated successfully!']);
}
public function delete() {
$postData = $this->input->post();
$this->load->model('blog_app_article_model');
$this->blog_app_article_model->delete($postData);
echo json_encode(['message' => 'Deleted successfully!']);
}
protected function validate($data, $type = 'saveOrUpdate') {
$this->load->library('form_validation');
$this->form_validation->set_data($data);
$this->setFormRuleForBlog($type);
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => $errors]);
exit;
}
}
protected function setFormRuleForBlog($type) {
if ($type === 'filter') {
$this->form_validation->set_rules('params[blog_id]', 'Blog ID', 'integer');
$this->form_validation->set_rules('params[description]', 'Description', 'max_length[100]');
$this->form_validation->set_rules('params[status]', 'Status', 'integer');
return;
}
$this->form_validation->set_rules('blog_id', 'Blog ID', 'required|integer');
$this->form_validation->set_rules('description', 'Description', 'required|max_length[100]');
$this->form_validation->set_rules('status', 'Status', 'integer');
}
protected function renderPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('blog_app_articles/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Booking extends Admin_Controller {
private $params = null;
private $itemPerPage = 10;
public function __construct() {
parent::__construct();
// Load model
$this->load->model('booking_model');
}
public function index() {
$this->summary();
}
public function summary() {
$data['page_title'] = 'Booking';
$this->renderBookingPage('view_booking_summary', $data);
}
public function getReports() {
$postData = $this->input->post();
$this->validate($postData);
$params = !empty($postData['params']) ? $postData['params'] : $this->params;
$pageNo = !empty($postData['pageNo']) ? $postData['pageNo'] - 1 : 0;
$pageSize = !empty($postData['pageSize']) ? $postData['pageSize'] : $this->itemPerPage;
$data = $this->booking_model->getReports($params, $pageNo, $pageSize);
echo json_encode($data);
}
protected function validate($data, $type = 'filter') {
$this->load->library('form_validation');
$this->form_validation->set_data($data);
$this->setFormRuleForBooking($type);
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => $errors]);
exit;
}
}
protected function setFormRuleForBooking($type) {
$this->form_validation->set_rules('params[id]', 'ID', 'integer');
$this->form_validation->set_rules('params[quote_id]', 'Quote ID', 'integer');
$this->form_validation->set_rules('params[member_id]', 'Member ID', 'integer');
$this->form_validation->set_rules('params[cost]', 'Cost', 'integer');
}
protected function renderBookingPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('booking/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
File diff suppressed because it is too large Load Diff
+100
View File
@@ -0,0 +1,100 @@
<?php
class Ckeditor extends Admin_Controller
{
// extends CI_Controller for CI 2.x users
public $data = array();
public function __construct()
{
//parent::Controller();
parent::__construct();
$this->load->helper('ckeditor');
//Ckeditor's configuration
$this->data['ckeditor'] = array(
//ID of the textarea that will be replaced
'id' => 'content',
'path' => 'js/ckeditor',
//Optionnal values
'config' => array(
'toolbar' => "Full", //Using the Full toolbar
'width' => "100px", //Setting a custom width
'height' => '100px', //Setting a custom height
),
//Replacing styles from the "Styles tool"
'styles' => array(
//Creating a new style named "style 1"
'style 1' => array(
'name' => 'Blue Title',
'element' => 'h2',
'styles' => array(
'color' => 'Blue',
'font-weight' => 'bold'
)
),
//Creating a new style named "style 2"
'style 2' => array(
'name' => 'Red Title',
'element' => 'h2',
'styles' => array(
'color' => 'Red',
'font-weight' => 'bold',
'text-decoration' => 'underline'
)
)
)
);
$this->data['ckeditor_2'] = array(
//ID of the textarea that will be replaced
'id' => 'content_2',
'path' => 'js/ckeditor',
//Optionnal values
'config' => array(
'width' => "550px", //Setting a custom width
'height' => '100px', //Setting a custom height
'toolbar' => array( //Setting a custom toolbar
array('Bold', 'Italic'),
array('Underline', 'Strike', 'FontSize'),
array('Smiley'),
'/'
)
),
//Replacing styles from the "Styles tool"
'styles' => array(
//Creating a new style named "style 1"
'style 3' => array(
'name' => 'Green Title',
'element' => 'h3',
'styles' => array(
'color' => 'Green',
'font-weight' => 'bold'
)
)
)
);
}
public function index()
{
$this->load->view('ckeditor', $this->data);
}
}
@@ -0,0 +1,67 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Credit_card_benefits extends Admin_Controller
{
public $viewData = array();
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('credit_card_benefit_model');
}
private function getFormValue()
{
return [
'benefit_id' => $this->input->post('benefit_id[]') ?? [],
'benefit' => $this->input->post('benefit[]') ?? [],
'expired_date' => $this->input->post('expired_date[]') ?? [],
];
}
public function update() {
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$params = $this->getFormValue();
$this->form_validation->set_data($params);
$this->setFormRuleUpdate();
if ($this->form_validation->run() == false) {
// Rerender filter if validate fail
echo json_encode([
'code' => '500',
'message' => validation_errors()
]);
return FALSE;
}
$this->credit_card_benefit_model->update($params);
echo json_encode([
'code' => '200',
'message' => 'Updated Successful'
]);
}
public function setFormRuleUpdate()
{
$this->form_validation->set_rules('benefit_id[]', 'ID', 'required');
$this->form_validation->set_rules('benefit[]', 'Benefit', 'required|max_length[256]');
$this->form_validation->set_rules('expired_date[]', 'Expired Date', 'regex_match[/\d{4}-\d{2}-\d{2}/]');
}
public function validateForm(&$params)
{
if ($this->form_validation->run() == false) {
// Rerender filter if validate fail
$this->viewData['msg'] = validation_errors();
return FALSE;
}
return TRUE;
}
}
+305
View File
@@ -0,0 +1,305 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Credit_cards extends Admin_Controller
{
public $viewData = array();
public function __construct()
{
parent::__construct();
// load library
$this->load->library('session');
// Load model
$this->load->model('bank_model');
$this->load->model('credit_card_model');
$this->load->model('credit_card_benefit_model');
$this->load->library('pagination');
$this->viewData['benefits'] = [];
}
protected function renderToolsPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view('credit_cards/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function index()
{
$this->renderToolsPage("view_credit_cards", $this->viewData);
}
public function loadRecord()
{
$rowno = $this->input->get('rowno');
parse_str($this->input->get('filters'), $filters);
$filters = array_filter($filters, function($val) {
return $val !== '';
});
// Row per page
$rowperpage = 10;
$cur_page = $rowno;
// Row position
if ($rowno != 0) {
$rowno = ($rowno - 1) * $rowperpage;
}
// All records count
$allcount = count($this->credit_card_model->getData($filters));
// Get records
$users_record = $this
->credit_card_model
->getData($filters, $rowperpage, $rowno);
foreach($users_record as &$ele) {
$ele['benefits'] = array_map(function($ele) {
$ele['expired_date'] = empty($ele['expired_date'])
? ''
: $ele['expired_date'];
return $ele;
}, $this
->credit_card_benefit_model
->getBenefitByCardID($ele['credit_card_id']));
}
// Pagination Configuration
$config['base_url'] = '/Credit_cards/loadRecord';
$config['use_page_numbers'] = TRUE;
$config['total_rows'] = $allcount;
$config['per_page'] = $rowperpage;
$config['cur_page'] = $cur_page;
$config['full_tag_open'] = "<ul class='pagination pb-20'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
// Initialize
$this->pagination->initialize($config);
// Initialize $data Array
$data['pagination'] = $this->pagination->create_links();
$data['result'] = $users_record;
$data['row'] = $rowno;
echo json_encode($data);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->setFormRuleCreate();
$params = $this->getFormValue();
if ($this->validateForm($params) === FALSE) {
$this->renderToolsPage('view_credit_cards', $this->viewData);
return;
}
if ($this->isExistBankNameAndCardType($params)) {
$this->viewData['msg'] = 'Bank Name and Card Type already input';
$this->renderToolsPage('view_credit_cards', $this->viewData);
return;
}
$this->insert_record($params);
redirect('/credit_cards');
}
public function setFormRuleCreate()
{
$this->form_validation->set_rules('bank_name', 'Bank Name', 'required|max_length[50]');
$this->form_validation->set_rules('card_name', 'Card Type', 'required|max_length[50]');
$this->form_validation->set_rules('benefits[]', 'Benefit', 'max_length[256]');
$this->form_validation->set_rules('expired_date[]', 'Expired Date', 'regex_match[/\d{4}-\d{2}-\d{2}/]');
}
private function getFormValue()
{
return [
'bank_name' => trim($this->input->post('bank_name') ?? ''),
'card_name' => trim($this->input->post('card_name') ?? ''),
'bank_id' => $this->input->post('bank_id'),
'credit_card_id' => $this->input->post('credit_card_id'),
'old_bank_name' => trim($this->input->post('old_bank_name') ?? ''),
'old_card_name' => trim($this->input->post('old_card_name') ?? ''),
'benefits[]' => $this->input->post('benefits[]') ?? [],
'expired_date[]' => $this->input->post('expired_date[]') ?? []
];
}
public function validateForm(&$params)
{
$this->form_validation->set_data($params);
if ($this->form_validation->run() == false) {
$this->viewData = array_merge($this->viewData, $params);
// Rerender filter if validate fail
$this->viewData['msg'] = validation_errors();
return FALSE;
}
return TRUE;
}
private function isExistBankNameAndCardType($data) {
return $this->credit_card_model->countRecordsByBankAndCardName([
'bank_name' => $data['bank_name'],
'card_name' => $data['card_name'],
]) > 0;
}
private function insert_record($params) {
$this->db->trans_start();
$this->db->trans_strict(FALSE);
$params['bank_id'] = $this->bank_model->insert($params);
$params['credit_card_id'] = $this->credit_card_model->insert($params);
$this->credit_card_benefit_model->insert($params);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
$this->viewData['msg'] = 'Something went wrong !!!';
return FALSE;
}
else {
$this->db->trans_commit();
return TRUE;
}
}
public function setFormRuleUpdate()
{
$this->form_validation->set_rules('bank_name', 'Bank Name', 'required|max_length[50]');
$this->form_validation->set_rules('card_name', 'Card Type', 'required|max_length[50]');
$this->form_validation->set_rules('benefits[]', 'Benefit', 'max_length[256]');
}
public function update()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->setFormRuleUpdate();
$params = $this->getFormValue();
if ($this->validateForm($params) === FALSE) {
// $this->renderToolsPage('view_credit_cards', $this->viewData);
$response = array(
'type' => 'errors',
'message' => validation_errors()
);
return $this->output->set_content_type('application/json')->set_output( json_encode( $response ) );
}
if (
strcmp($params['bank_name'], $params['old_bank_name']) !== 0 ||
strcmp($params['card_name'], $params['old_card_name']) !== 0
) {
if ($this->isExistBankNameAndCardType($params)) {
$this->viewData['msg'] = 'Bank Name and Card Type already input';
$this->renderToolsPage('view_credit_cards', $this->viewData);
return;
}
}
$update = $this->update_record($params);
return $this->output->set_content_type('application/json')->set_output( json_encode( $update ) );
}
private function update_record($params) {
$this->db->trans_start();
$this->db->trans_strict(FALSE);
$params['bank_id'] = $this->bank_model->insert($params);
$this->credit_card_model->update($params);
// delete old records
$this->credit_card_benefit_model->delete($params);
$this->credit_card_benefit_model->insert($params);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
$this->viewData['msg'] = 'Something went wrong !!!';
return FALSE;
}
else {
$this->db->trans_commit();
return $params;
}
}
public function destroy() {
$this->load->helper(array('form', 'url'));
$this->load->database();
$params = $this->getFormValue();
$this->setFormRuleDelete();
if ($this->validateForm($params) === FALSE) {
$this->renderToolsPage('view_credit_cards', $this->viewData);
return;
}
$result = $this->delete_record($params);
$this->viewData['msg'] = $result ? "Delete Successful" : "Delete Fail";
$this->renderToolsPage('view_credit_cards', $this->viewData);
}
public function delete_record($params) {
$this->db->trans_start();
$this->db->trans_strict(FALSE);
$this->credit_card_benefit_model->delete($params);
$this->credit_card_model->delete($params);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
return FALSE;
}
else {
$this->db->trans_commit();
if ($this->credit_card_model->count_credit_card($params) === '0') {
$this->bank_model->delete($params);
}
return TRUE;
}
}
private function setFormRuleDelete()
{
$this->form_validation->set_rules('credit_card_id', 'Credit', 'required|numeric|exist[credit_cards,id,credit_card_id]');
}
}
+256
View File
@@ -0,0 +1,256 @@
<?php
defined( 'BASEPATH' ) OR exit( 'No direct script access allowed' );
class Dash extends Admin_Controller {
public function index() {
return $this->dashdata();
}
public function memberlist(){
global $bko_users_members_access_list;
$mysql = "SELECT '<a href=\"/member/viewLocateMember?member_id='||id||'\" >Select</a>' AS select, id,username,firstname,lastname, last_login,loc,"
. " '<button style=\"padding:3px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"viewMember('||id||');\" >View</button>' AS ACT "
. " "
. " FROM members WHERE id>0 ";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$mysql.= "ORDER BY id ASC";
$mysql = "SELECT count(*) AS count FROM members WHERE id>0";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$r = $this->read_replica->query($mysql);
$f = $r->row_array();
$this->load->library( 'pagination' );
$config = array();
//$query = $this->db->query( $mysql );
$config["total_rows"] = $f['count']; //$query->num_rows();
$config["base_url"] = base_url() . "/dash/memberlist";
$config["per_page"] = 15;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize( $config );
$page = ( $this->uri->segment( 3 ) ) ? $this->uri->segment( 3 ) : 0;
$page = is_numeric( $page ) ? $page : 0;
global $savvyext;
$this->load->helper( 'url' );
$data = array();
$this->load->library( 'table' );
$this->template["table_open"] = "<table class='table table-striped table-hover table-bordered table-condensed' style='padding:0px; background-color:lightgreen;'>";
$this->table->set_template( $this->template );
//coalesce(xx,'')
$mysql = "SELECT '<a href=\"/member/viewLocateMember?member_id='||id||'\" >Select</a>' AS select, id,"
. "username,firstname||' '||lastname AS name,decision_group, last_login,loc,"
. " '<button style=\"padding:3px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"viewMember('||id||');\" >View</button>&nbsp;' ||"
. " CASE WHEN status = 0 OR login_failures >= 5 THEN '<button style=\"padding:3px; width: 50px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"unblockMember('||id||');\" >Unblock</button>' "
. " WHEN status = 1 OR login_failures < 5 THEN '<button style=\"padding:3px; width: 50px;\" type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"blockMember('||id||');\" >Block</button>' "
. " ELSE '' "
. " END "
. " AS ACT "
. " "
. " FROM members WHERE id>0 ";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$mysql .= "ORDER BY id ASC LIMIT " . $config["per_page"] . " OFFSET " . $page . " ";
$query = $this->read_replica->query( $mysql );
$this->table->set_heading( array( 'data' => 'Select', 'style' => 'width:40px' ), array( 'data' => 'ID',
'style' => 'width:30px'
), 'Email', 'Personalty','Name', 'Last Login', 'Location', array( 'data' => 'ACT',
'style' => 'width:40px; text-align: center;'
) );
$data['member_table'] = $this->table->generate( $query );
$data["links"] = $this->pagination->create_links();
$data['google_api_key'] = $savvyext->cfgReadChar( 'google.api_key' );
$data["page_title"] = "";
$data["page_link"] = $this->pagination->create_links();
$q = "SELECT count(id) AS dcount ,added::date AS dt FROM members WHERE added + '27 days' > now() GROUP BY added::date ORDER BY added::date LIMIT 7";
$query = $this->read_replica->query($q);
$data['plot_signup'] = $query->result_array();
$q = "SELECT count(id),created::date FROM trackedemail_item GROUP BY created::date ORDER BY created DESC LIMIT 30";
$query = $this->read_replica->query($q);
$data['plot_emaildownload'] = $query->result_array();
$this->renderAdminPage( 'view_memberlist', $data );
// echo 'Ameye Olu';
}
public function dashdata() {
global $bko_users_members_access_list;
$mysql = "SELECT '<a href=\"/member/viewLocateMember?member_id='||id||'\" >Select</a>' AS select, id,username,firstname,lastname, last_login,loc,"
. " '<button style=\"padding:3px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"viewMember('||id||');\" >View</button>' AS ACT "
. " "
. " FROM members WHERE id>0 ";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$mysql.= "ORDER BY id ASC";
$mysql = "SELECT count(*) AS count FROM members WHERE id>0";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$r = $this->read_replica->query($mysql);
$f = $r->row_array();
$this->load->library( 'pagination' );
$config = array();
//$query = $this->db->query( $mysql );
$config["total_rows"] = $f['count']; //$query->num_rows();
$config["base_url"] = base_url() . "/dash/dashdata";
$config["per_page"] = 15;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize( $config );
$page = ( $this->uri->segment( 3 ) ) ? $this->uri->segment( 3 ) : 0;
$page = is_numeric( $page ) ? $page : 0;
global $savvyext;
$this->load->helper( 'url' );
$data = array();
$this->load->library( 'table' );
$this->template["table_open"] = "<table class='table table-striped table-hover table-bordered table-condensed' style='padding:0px; background-color:lightgreen;'>";
$this->table->set_template( $this->template );
//coalesce(xx,'')
$mysql = "SELECT '<a href=\"/member/viewLocateMember?member_id='||id||'\" >Select</a>' AS select, id,"
. "username,firstname||' '||lastname AS name,decision_group, last_login,loc,"
. " '<button style=\"padding:3px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"viewMember('||id||');\" >View</button>&nbsp;' ||"
. " CASE WHEN status = 0 OR login_failures >= 5 THEN '<button style=\"padding:3px; width: 50px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"unblockMember('||id||');\" >Unblock</button>' "
. " WHEN status = 1 OR login_failures < 5 THEN '<button style=\"padding:3px; width: 50px;\" type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"blockMember('||id||');\" >Block</button>' "
. " ELSE '' "
. " END "
. " AS ACT "
. " "
. " FROM members WHERE id>0 ";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$mysql .= "ORDER BY id ASC LIMIT " . $config["per_page"] . " OFFSET " . $page . " ";
$query = $this->read_replica->query( $mysql );
$this->table->set_heading( array( 'data' => 'Select', 'style' => 'width:40px' ), array( 'data' => 'ID',
'style' => 'width:30px'
), 'Email', 'Personalty','Name', 'Last Login', 'Location', array( 'data' => 'ACT',
'style' => 'width:40px; text-align: center;'
) );
$data['member_table'] = $this->table->generate( $query );
$data["links"] = $this->pagination->create_links();
$data['google_api_key'] = $savvyext->cfgReadChar( 'google.api_key' );
$data["page_title"] = "";
$data["page_link"] = $this->pagination->create_links();
$q = "SELECT count(id) AS dcount ,added::date AS dt FROM members WHERE added + '27 days' > now() GROUP BY added::date ORDER BY added::date LIMIT 7";
$query = $this->read_replica->query($q);
$data['plot_signup'] = $query->result_array();
$q = "SELECT count(id),created::date FROM trackedemail_item GROUP BY created::date ORDER BY created DESC LIMIT 30";
$query = $this->read_replica->query($q);
$data['plot_emaildownload'] = $query->result_array();
//How many Farm records generated daliy - last 10 days [SG & US] - 2 plots
$q = "SELECT a.*,b.total AS success, CASE WHEN a.total>0 THEN ROUND(100.0*b.total/a.total,2) ELSE 0.0 END AS success_rate
FROM (SELECT date_trunc('day',aa.created) AS created,count(*) AS total FROM quotes aa
LEFT JOIN address ab ON ab.id=aa.location_start_id
WHERE aa.created>now()-interval '9 days' AND ab.country='SG' GROUP BY date_trunc('day',aa.created)) AS a
LEFT JOIN (SELECT date_trunc('day',ba.created) AS created,count(*) AS total FROM quotes ba
LEFT JOIN address bb ON bb.id=ba.location_start_id
WHERE ba.created>now()-interval '9 days' AND ba.cost>0 AND bb.country='SG'
GROUP BY date_trunc('day',created)) AS b ON (b.created=a.created) ORDER BY a.created DESC";
$query = $this->read_replica->query( $q );
$data['records_generated_daliy_SG'] = $this->table->generate( $query );
$q = "SELECT a.*,b.total AS success, CASE WHEN a.total>0 THEN ROUND(100.0*b.total/a.total,2) ELSE 0.0 END AS success_rate
FROM (SELECT date_trunc('day',aa.created) AS created,count(*) AS total FROM quotes aa
LEFT JOIN address ab ON ab.id=aa.location_start_id
WHERE aa.created>now()-interval '9 days' AND ab.country='US' GROUP BY date_trunc('day',aa.created)) AS a
LEFT JOIN (SELECT date_trunc('day',ba.created) AS created,count(*) AS total FROM quotes ba
LEFT JOIN address bb ON bb.id=ba.location_start_id
WHERE ba.created>now()-interval '9 days' AND ba.cost>0 AND bb.country='US'
GROUP BY date_trunc('day',created)) AS b ON (b.created=a.created) ORDER BY a.created DESC";
$query = $this->read_replica->query( $q );
$data['records_generated_daliy_US'] = $this->table->generate( $query );
$this->renderAdminPage( 'view_start', $data );
// echo 'Ameye Olu';
}
public function dashpage() {
global $savvyext;
$this->load->helper( 'url' );
$data = array();
$this->load->library( 'table' );
$this->table->set_template( $this->template );
$mysql = "SELECT '<button type=\"button\" class=\"btn btn-primary btn-xs\" onclick=\"viewMember('||id||');\" >View</button>' AS action ,username,firstname,lastname FROM members";
$query = $this->read_replica->query( $mysql );
$this->table->set_heading( array( 'data' => 'ACTION',
'style' => 'width:90px'
), 'USERNAME', 'FIRSTNAME', 'LASTNAME' );
$data['member_table'] = $this->table->generate( $query );
$data['google_api_key'] = $savvyext->cfgReadChar( 'google.api_key' );
//$data['js'] = array('https://maps.googleapis.com/maps/api/js?key=AIzaSyDvjiRTxngOQyBP4zpqFlZuiquc0ROvo9c&callback=initMap');
$this->renderAdminPage( 'view_dash', $data );
// echo 'Ameye Olu';
}
}
+784
View File
@@ -0,0 +1,784 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Descision extends Admin_Controller {
var $template = array(
'table_open' => "<table style='background-color:aliceblue' class='table table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-teal\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public function index() {
}
protected function renderDescisionPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('descision/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function getValueOfDecisionLogic() {
return [
'logic' => trim($this->input->get('logic')),
'description' => trim($this->input->get('description')),
'status' => trim($this->input->get('card_status')
?? $this->input->get('status') ?? '-1'),
'survey' => trim($this->input->get('card_survey')
?? $this->input->get('survey') ?? '-1'),
'from_weight' => trim($this->input->get('from_weight')),
'to_weight' => trim($this->input->get('to_weight'))
];
}
public function setComboForDecisionLogic($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboWithAll(
'card_status',
$params['status']
);
$combo['card_survey'] = $this->combo_model->getYesNoComboWithAll(
'card_survey',
$params['survey']
);
return $combo;
}
public function validateValueForDecisionLogic($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForDecisionLogic();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForDecisionLogic() {
$this->form_validation->set_rules('survey', 'Survey', 'integer');
$this->form_validation->set_rules('from_weight', 'From Weight', 'integer');
$this->form_validation->set_rules('to_weight', 'To Weight', 'integer');
$this->form_validation->set_rules('status', 'Status', 'integer');
}
public function load_pagination($all_record, $params, $action) {
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . '/' . get_class($this) . '/' . $action;
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config["suffix"] =
"?"
. http_build_query($params);
$config["first_url"] =
"/" . get_class($this) . "/{$action}/0?"
. http_build_query($params);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function getValueCombo($val) {
$status_value = range(0, 1);
return in_array($val, $status_value)
? $val
: '';
}
public function descisionlogic() {
$this->load->model('decision_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID',
'Lorder',
'Logic',
'Description',
'Status',
'Survey',
'Weight',
'Update',
]);
$params = $this->getValueOfDecisionLogic();
$data = $this->setComboForDecisionLogic($params);
$data["page_title"] = "Descision Logic";
$params['status'] = $this->getValueCombo($params['status']);
$params['survey'] = $this->getValueCombo($params['survey']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForDecisionLogic($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->decision_model->get_decision_logic_records($params),
$params,
'descisionlogic'
)
);
$data['pos_table'] = $this->table->generate(
$this->decision_model->get_decision_logic_records(
$params,
$data['limit'],
$data['offset']
)
);
$this->renderDescisionPage('view_descisionlogic', $data);
}
public function updatelogic() {
$setting_value = (int) $this->input->get('setting_value');
$setting_id = (int) $this->input->get('setting_id');
$setting_key = (int) $this->input->get('setting_key');
if ($setting_value > 0 && $setting_id > 0 && $setting_key > 0) {
$q = "UPDATE group_decision_logic SET weight=$setting_value WHERE id = $setting_id AND decision_logic = $setting_key";
$r = $this->db->query($q);
echo 'Updated.';
}
}
public function configurenextaction() {
$data = array();
$this->load->library('table');
$this->table->set_template($this->template_small);
$decision_id = (int) $this->input->get('decision_id');
$id = (int) $this->input->get('id');
$proc = $this->input->get('proc');
$mysql = "SELECT d.id,d.target_key,g.description
FROM decision_group_action d
LEFT JOIN decision_group g ON d.target_key = g.dkey WHERE d.dkey=(SELECT dkey FROM decision_group WHERE id = $decision_id)";
$query = $this->read_replica->query($mysql);
//$this->table->set_heading( array('data' => 'ID', 'style' => 'width:10px'), 'Description', array('data' => 'ADD', 'style' => 'width:50px'));
$data['logic_list'] = $this->table->generate($query);
$data["decision_group_title"] = "A10AA01"; // based on selection
$data["card_category"] = "";
$data["decision_id"] = $decision_id;
$this->load->view('descision/view_next_action', $data);
return 0;
}
public function getValueOfMemberReport() {
return [
'decision_group' => trim($this->input->get('member')['decision_group']),
'description' => trim($this->input->get('member')['description']),
'from_count' => trim($this->input->get('member')['from_count']),
'to_count' => trim($this->input->get('member')['to_count'])
];
}
public function validateValueForMemberReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForMemberReport();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForMemberReport() {
$this->form_validation->set_rules('from_count', 'From Count', 'integer');
$this->form_validation->set_rules('to_count', 'To Count', 'integer');
}
public function member_report(&$data) {
$this->load->model('decision_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'Count',
'Decision_Group',
'Description',
]);
$params = $this->getValueOfMemberReport();
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForMemberReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->decision_model->get_member_report_records($params),
$params,
'descisionreport'
)
);
$data['member_report'] = $this->table->generate(
$this->decision_model->get_member_report_records(
$params,
$data['limit'],
$data['offset']
)
);
}
public function getValueOfRefreshReport() {
return [
'description' => trim($this->input->get('description')),
'from_count' => trim($this->input->get('from_count')),
'to_count' => trim($this->input->get('to_count'))
];
}
public function validateValueForRefreshReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForfRefreshReport();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForfRefreshReport() {
$this->form_validation->set_rules('from_count', 'From Count', 'integer');
$this->form_validation->set_rules('to_count', 'To Count', 'integer');
}
public function refresh_report(&$data) {
$this->load->model('decision_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'Description',
'Count',
]);
$params = $this->getValueOfRefreshReport();
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForRefreshReport($params);
$params = array_diff_key($params, $errors);
// $data = array_merge(
// $data,
// $params,
// $this->load_pagination(
// $this->decision_model->get_refresh_report_records($params),
// $params,
// 'descisionreport'
// )
// );
$data['refresh_report'] = $this->table->generate(
$this->decision_model->get_refresh_report_records(
$params,
$data['limit'],
$data['offset']
)
);
}
public function descisionreport() {
$this->load->library('table');
$this->table->set_template($this->template_small);
$data["page_title"] = "Descision Report";
$this->member_report($data);
$this->refresh_report($data);
$this->renderDescisionPage("view_descisionreport", $data);
}
/*
savvy=> select * from decision_group;
id | lorder | description | dkey | status | personality
----+--------+---------------------------+---------+--------+---------------------------
8 | 0 | New User no Data | A10AA01 | 1 | New User no Data
2 | 99 | Comfort Oriented | A300003 | 0 | Comfort Oriented
3 | 99 | Luxury Lover | A300004 | 0 | Luxury Lover
4 | 99 | Low Budget | A300005 | 0 | Low Budget
5 | 99 | Bike/Scooters Lover | A300006 | 0 | Bike/Scooters Lover
6 | 99 | Eco Friendly | A300007 | 0 | Eco Friendly
7 | 99 | Family/Group | A300008 | 0 | Family/Group
*/
public function updatePersonaltyName() {
// echo 'ameye-001';
///descision/updatePersonaltyName?id=" + id + "&pers_text=" + pers_text_value + "&dkey=" + dkey
$decision_group = $this->input->get('dkey');
$group_id = (int) $this->input->get('id');
$personality = trim($this->input->get('pers_text'));
$offers = (int)$this->input->get('pers_offers');
$update_query = 'UPDATE decision_group SET ';
if ($decision_group == '' || $group_id <= 0) {
echo "Error - Not updated";
return;
} else {
$update_query .= " personality='$personality'";
}
if ($offers <= 0) {
echo "Error - Offers must be a number greater than 0";
return;
} else {
$update_query .= " , offers_count=$offers";
}
$update_query .= " WHERE id=$group_id AND dkey='$decision_group'";
$this->db->query($update_query);
echo "Updated";
}
public function getValueOfPersonaltyCards() {
return [
'dkey' => trim($this->input->get('dkey')),
'description' => trim($this->input->get('description')),
'status' => trim($this->input->get('card_status')
?? $this->input->get('status') ?? '-1'),
'personality' => trim($this->input->get('personality'))
];
}
public function setComboForPersonaltyCards($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboWithAll(
'card_status',
$params['status']
);
return $combo;
}
public function validateValueForPersonaltyCards($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForPersonaltyCards();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForPersonaltyCards() {
$this->form_validation->set_rules('status', 'Status', 'integer');
}
public function personaltycards() {
$this->load->model('decision_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID',
'Lorder',
'Dkey',
'Status',
'Description',
'Personality',
]);
$params = $this->getValueOfPersonaltyCards();
$data = $this->setComboForPersonaltyCards($params);
$data["page_title"] = "Personalty Cards";
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForPersonaltyCards($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->decision_model->get_personalty_card_records($params),
$params,
'PersonaltyCards'
)
);
$data['pers_data'] =
$this->decision_model->get_personalty_card_records(
$params,
$data['limit'],
$data['offset']
);
$data['pers_data'] = array_map(function($ele) {
$this->table->set_heading(
"Card Title", array('data' => 'Country', 'style' => 'width:50px')
);
$ele['card_list'] =
$this->table->generate($this->decision_model->get_card_list_records($ele));
$this->table->set_heading(
"Card Title", array('data' => 'Country', 'style' => 'width:50px')
);
$ele['card_group'] =
$this->table->generate($this->decision_model->get_card_group_records($ele));
$this->table->set_heading(
"Card Title", array('data' => 'Country', 'style' => 'width:50px')
);
$ele['card_country'] =
$this->table->generate($this->decision_model->get_card_country_records($ele));
return $ele;
}, $data['pers_data']);
$this->renderDescisionPage('view_persnalitycards', $data);
}
function getCardList($dkey) {
$mysql = "SELECT c.name||' <b>'||c.button1_action||'</b><br>'||c.id||' - '|| c.title AS Card,c.card_country FROM decision_cards d LEFT JOIN main_cards c ON c.id=d.card_id WHERE d.decision_id=(SELECT id FROM decision_group WHERE dkey='$dkey') AND d.status=1 ";
$mysql .= " ORDER BY c.id DESC";
$query = $this->read_replica->query($mysql);
$this->table->set_heading( "Card Title", array('data' => 'Country', 'style' => 'width:50px'));
$data["card_list"] = $this->table->generate($query);
$mysql = "SELECT c.button1_action,count(c.id) FROM decision_cards d LEFT JOIN main_cards c ON c.id=d.card_id WHERE d.decision_id=(SELECT id FROM decision_group WHERE dkey='$dkey') AND d.status=1 ";
$mysql .= " GROUP BY c.button1_action";
$query = $this->read_replica->query($mysql);
$this->table->set_heading( "Card Title", array('data' => 'Country', 'style' => 'width:50px'));
$data["card_group"] = $this->table->generate($query);
$mysql = "SELECT c.card_country,count(c.id) FROM decision_cards d LEFT JOIN main_cards c ON c.id=d.card_id WHERE d.decision_id=(SELECT id FROM decision_group WHERE dkey='$dkey') AND d.status=1 ";
$mysql .= " GROUP BY c.card_country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading( "Card Title", array('data' => 'Country', 'style' => 'width:50px'));
$data["card_country"] = $this->table->generate($query);
return $data;
}
public function getValueOfPersonaltyName() {
return [
'dkey' => trim($this->input->get('dkey')),
'description' => trim($this->input->get('description')),
'status' => trim($this->input->get('card_status')
?? $this->input->get('status') ?? '-1'),
'personality' => trim($this->input->get('personality')),
'from_offer' => trim($this->input->get('from_offer')),
'to_offer' => trim($this->input->get('to_offer'))
];
}
public function setComboForPersonaltyName($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboWithAll(
'card_status',
$params['status']
);
return $combo;
}
public function validateValueForPersonaltyName($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForPersonaltyName();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForPersonaltyName() {
$this->form_validation->set_rules('from_offer', 'From Offer', 'integer');
$this->form_validation->set_rules('to_offer', 'To Offer', 'integer');
$this->form_validation->set_rules('status', 'Status', 'integer');
}
public function personaltyname() {
$this->load->model('decision_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID',
'Lorder',
'Dkey',
'Status',
'Description',
'Personality',
'Offers',
'Action'
]);
$params = $this->getValueOfPersonaltyName();
$data = $this->setComboForPersonaltyName($params);
$data["page_title"] = "Personalty Name";
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForPersonaltyName($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->decision_model->get_personalty_name_records($params),
$params,
'personaltyname'
)
);
$data['pers_table'] = $this->table->generate(
$this->decision_model->get_personalty_name_records(
$params,
$data['limit'],
$data['offset']
)
);
$this->renderDescisionPage('view_persnalityname', $data);
}
public function addGPSTriggerLogic() {
// alert("/descision/addGPSTriggerLogic?decision_group=" + decision_group + "&address_id=" + address_id_value);
$decision_group = $this->input->get('decision_group');
$gps_address_id = (int) $this->input->get('gps_address_id');
if ($decision_group != '' && $gps_address_id != '' && $gps_address_id > 0) {
$in = array();
$in['action'] = SAVVY_BKO_GPSTRIGGER_LOGIC;
$in['decision_group'] = $decision_group;
$in['gps_address_id'] = $gps_address_id;
$out = array();
$ret = $this->savvy_api($in, $out);
$back_message = "<br> Result - " . isset($out["status_message"]) ? $out["status_message"] : '';
} else {
$back_message = "<br> Select address to add.";
}
echo $back_message;
}
public function addSurveyLogic() {
// url: "/descision/addSurveyLogic?decision_group=" + decision_group + "&survey_id_value="+survey_id_value+"&survey_ans_value=" + survey_ans_value
/*
* savvy=> SELECT * FROM group_decision_logic;
id | lorder | group_id | decision_logic | status | added | weight
----+--------+----------+----------------+--------+----------------------------+--------
3 | 0 | 2 | 3 | 1 | 2019-07-02 00:26:55.237707 | 10
1 | 0 | 8 | 1 | 0 | 2019-07-02 00:26:55.231772 | 10
6 | 0 | 8 | 3 | 0 | 2019-07-02 08:38:36.87994 | 10
5 | 0 | 8 | 1 | 0 | 2019-07-02 08:29:29.833282 | 10
*/
$back_message = '';
$decision_group = $this->input->get('decision_group');
$card_id = (int) $this->input->get('survey_id_value');
$survey_ans = $this->input->get('survey_ans_value');
if ($decision_group != '' && $card_id != '' && $survey_ans != '') {
$in = array();
$in['action'] = SAVVY_BKO_SURVEY_LOGIC;
$in['decision_group'] = $decision_group;
$in['card_id'] = $card_id;
$in['survey_ans'] = $survey_ans;
$out = array();
$ret = $this->savvy_api($in, $out);
// print_r($out);
$back_message = "<br> Result - " . isset($out["status_message"]) ? $out["status_message"] : '';
} else {
$back_message = "<br> Select Survey and Set Answer";
}
echo "Input: $decision_group $card_id $survey_ans ]" . $back_message;
}
public function descisiontree() {
$data = array();
// $this->load->library('table');
// $this->table->set_template($this->template);
// $this->load->model('combo_model');
//
// Prepare the head of the tree
$tree_data = array();
$mysql = "SELECT *,dkey AS name FROM decision_group WHERE dkey ='A10AA01'";
$query = $this->read_replica->query($mysql);
$row = $query->row_array();
if (isset($row)) {
$mysql2 = "SELECT *,dkey AS name FROM decision_group WHERE dkey IN ( SELECT target_key FROM decision_group_action WHERE dkey ='A10AA01' )";
$query2 = $this->read_replica->query($mysql2);
$dat['children'] = array();
$icc = 0;
foreach ($query2->result_array() as $row2) {
// echo $row['title'];
// echo $row['name'];
if ($icc == 0) {
$dat['children'] = $row2;
} else {
array_merge($dat['children'], $row2);
}
$icc++;
}
$row["children"] = $dat['children'];
$tree_data['A10AA01'] = $row;
} // if the root works first
$data['tree'] = $tree_data;
// print_r($data);
// foreach ($query->result_array() as $row)
// {
// echo $row['decision_group'];
// echo $row['description'];
// echo $row['body'];
// }
// $this->table->set_heading(array('data' => 'View', 'style' => 'width:50px'), 'Card', array('data' => 'Image', 'style' => 'width:120px'));
// $data["member_report"] = $this->table->generate($query);
$data["page_title"] = "Descision Tree";
$this->renderDescisionPage("view_descisiontree", $data);
}
}
/*
savvy=> SELECT * FROM decision_group WHERE dkey ='dkey';
id | lorder | description | dkey | status
----+--------+-------------+------+--------
(0 rows)
savvy=> SELECT * FROM decision_group WHERE dkey ='A10AA01';
id | lorder | description | dkey | status
----+--------+------------------+---------+--------
8 | 0 | New User no Data | A10AA01 | 1
(1 row)
savvy=> SELECT * FROM decision_group_action WHERE dkey ='A10AA01';
id | dkey | target_key | status | added
----+---------+------------+--------+----------------------------
1 | A10AA01 | A10BB01 | 1 | 2019-10-20 02:01:41.079293
2 | A10AA01 | A100001 | 1 | 2019-10-20 02:01:41.085738
3 | A10AA01 | A1000A1 | 1 | 2019-10-20 02:01:41.95765
(3 rows)
savvy=> SELECT target_key FROM decision_group_action WHERE dkey ='A10AA01';
target_key
------------
A10BB01
A100001
A1000A1
(3 rows)
savvy=> SELECT target_key FROM decision_group_action WHERE dkey ='A10BB01';
target_key
------------
A1000A1
A100001
*/
+173
View File
@@ -0,0 +1,173 @@
<?php
defined( 'BASEPATH' ) OR exit( 'No direct script access allowed' );
class Emission extends Admin_Controller {
public $statusOptions = [
'Active' => 1,
'Inactive' => 0
];
public function __construct() {
parent::__construct();
// load library
$this->load->library('table');
// load model
$this->load->model('Emission_model', 'emission');
$this->load->model('Emission_Average_model', 'emissionAvrg');
// init view layer
$this->view = array();
}
public function index() {
$this->template["table_open"] = "<table class='table table-striped table-hover table-bordered table-condensed' style='padding:0px; background-color:lightgreen;'>";
$this->table->set_template( $this->template );
$emission = $this->getEmission();
$emissionAvrg = $this->getEmissionAvrg();
$data = array();
$data['emission_model'] = $this->table->generate( $emission );
$data['emission_model_item'] = $emissionAvrg;
$this->renderEmissionPage( 'view_emissionmodel', $data );
}
public function getEmission(){
global $bko_users_members_access_list;
//How many Farm records generated daliy - last 10 days [SG & US] - 2 plots
$emission = $this->emission->getData();
return $emission;
// echo 'Ameye Olu';
}
/**
* Get emission avrg result per page and pagination links
* @return array
*/
public function getEmissionAvrg() {
$this->load->helper(array('url'));
$this->load->helper('pagination');
// get pagination params
$page = $this->input->get('page') ? $this->input->get('page') : 1;
$results = $this->emissionAvrg->index($page);
return $results;
}
/**
* Delete emission avrg record by id
* @param itn $id emission avrg id
* @return status code
*/
public function deleteEmissionAvrg($id) {
$affected = $this->emissionAvrg->delete($id);
$this->output->set_content_type('application/json')
->set_output(json_encode($affected));
}
/**
* View form create new emission avrg
* @return view
*/
public function create() {
$this->prepare_form();
$this->renderEmissionPage('create_emission_avrg', $this->view);
}
/**
* View Emission Avrg
* @param int $id emission avrg id
* @return object emission avrg details
*/
public function edit($id) {
$result = $this->emissionAvrg->edit($id);
if (!$result) {
show_404();
}
$this->view['details'] = $result;
$this->prepare_form();
$this->renderEmissionPage('edit_emission_avrg', $this->view);
}
/**
* Store Emission Avrg
* @return bool return true if create success, reverse
*/
public function store() {
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->prepare_form();
$this->view['details'] = $this->input->post();
$this->form_validation->set_rules($this->emissionAvrg->rules);
if ($this->form_validation->run() == false) {
$this->renderEmissionPage('create_emission_avrg', $this->view);
return;
}
$create = $this->emissionAvrg->store($this->view['details']);
if ($create) {
$this->session->set_flashdata('success', isSet($create['message']) ? $create['message'] : 'Create success');
redirect('/emission');
}
$this->session->set_flashdata('error', $create['message']);
$this->renderEmissionPage('create_emission_avrg', $this->view);
return;
}
/**
* Update Emission Avrg
* @param int $id emission avrg id
* @return bool return true if update success, reverse
*/
public function update($id) {
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->prepare_form();
$this->view['details'] = $this->input->post();
$this->view['details']['id'] = $id;
$this->form_validation->set_rules($this->emissionAvrg->rules);
if ($this->form_validation->run() == false) {
$this->renderEmissionPage('edit_emission_avrg', $this->view);
return;
}
$update = $this->emissionAvrg->update($id, $this->view['details']);
if ($update) {
$this->session->set_flashdata('success', isSet($update['message']) ? $update['message'] : 'Create success');
redirect('/emission');
} else {
$this->session->set_flashdata('error', $update['message']);
$this->renderEmissionPage('edit_emission_avrg', $this->view);
return;
}
}
/**
* Prepare form before actions (create, edit)
* @return array
*/
protected function prepare_form() {
// load mkey from emission model
$mkeyOptions = $this->getEmission()->result();
$mkeyOptions = (isset($mkeyOptions) and !empty($mkeyOptions)) ? array_column($mkeyOptions, 'mkey') : null;
// load country from country model
$this->load->model('Country_model', 'country');
$country = $this->country->getAll();
$country = (isset($country) and !empty($country)) ? array_column($country, 'code') : null;
// load status code
$status = $this->statusOptions;
$this->view['mkeyOptions'] = $mkeyOptions;
$this->view['country'] = $country;
$this->view['statusOptions'] = $status;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Farm_records extends Admin_Controller
{
public $viewData = [];
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->model('farm_record_model');
$this->load->library('table');
$this->table->set_template($this->template);
$data["page_title"] = "Farm Records";
$data['records_generated_daily_SG'] = $this->table->generate(
$this->farm_record_model->get_farm_records(
['country' => 'SG']
)
);
$data['records_generated_daily_US'] = $this->table->generate(
$this->farm_record_model->get_farm_records(
['country' => 'US']
)
);
$this->renderFarmRecords('view_farm_records', $data);
}
private function renderFarmRecords($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('admin/report/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Feed extends Admin_Controller {
public function index() {
$this->load->helper('url');
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
}
public function onboardingsurvey() {
$this->load->library('table');
//$this->table->set_template($this->survey_template);
$this->load->model('onboarding_survey_model');
$cardCats = $this->db->get('card_category');
$data['page_title'] = 'Onboarding Survey';
$data['surveys'] = $this->onboarding_survey_model->getOnboardingSurvey();
$data['card_cats'] = $cardCats->result_array();
$this->renderFeedPage('view_onboardfeed', $data);
}
private function setFormRuleForSurvey() {
$this->form_validation->set_rules('groupKey', 'Group key', 'max_length[10]');
$this->form_validation->set_rules('answersKey', 'Answers key', 'max_length[25]');
$this->form_validation->set_rules('answers', 'Answers', 'max_length[100]');
}
public function getOnboardingSurvey() {
$postData = $this->input->post();
$postData = array_filter($postData, function($ele) {
return $ele !== "" && $ele !== null;
});
$pageNo = !empty($postData['pageNo']) ? $postData['pageNo'] - 1 : 0;
$this->load->library('form_validation');
$this->form_validation->set_data($postData);
$this->setFormRuleForSurvey();
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => $errors]);
return;
}
$this->load->model('onboarding_survey_model');
$result = $this->onboarding_survey_model->getOnboardingSurvey($postData, $pageNo);
echo json_encode(['data' => $result]);
}
public function getAvailableAndAssignedSurveyCards() {
$postData = $this->input->post();
$this->load->model('onboarding_survey_model');
$result = $this->onboarding_survey_model->getAvailableAndAssignedSurveyCards($postData);
echo json_encode(['result' => $result]);
}
public function assignSurveyCard() {
$postData = $this->input->post();
$this->load->model('onboarding_survey_model');
$this->onboarding_survey_model->assignSurveyCard($postData);
echo json_encode(['message' => 'Assigned!']);
}
public function unassignSurveyCard() {
$postData = $this->input->post();
$this->load->model('onboarding_survey_model');
$this->onboarding_survey_model->unassignSurveyCard($postData);
echo json_encode(['message' => 'Unassigned!']);
}
public function updateSurveyAnswers() {
$postData = $this->input->post();
$this->load->library('form_validation');
$this->form_validation->set_data($postData);
$this->setFormRuleForSurvey();
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => $errors]);
return;
}
$id = $postData['id'];
$surveyData = [
'answers' => $postData['answers']
];
$this->load->model('onboarding_survey_model');
$this->onboarding_survey_model->updateSurvey($id, $surveyData);
echo json_encode(['message' => 'Updated answers successfully!']);
}
protected function renderFeedPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('feed/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class GeoServices extends Admin_Controller {
public function index() {
$data = array();
$this->load->helper('url');
$this->listobjects();
}
protected function renderGeoServicesPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('geoservices/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function listobjects() {
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
$data["page_title"] = "List Geofence Objects";
$mysql = "SELECT * FROM geofence_area_country";
$query = $this->read_replica->query($mysql);
$data["geofence_area_country"] = $this->table->generate($query);
$mysql = "SELECT a.id,b.country,a.name, c.name AS transport_provider ";
$mysql.= " FROM country_services a, geofence_area_country b, transport_providers c";
$mysql.= " WHERE b.id=a.country_id AND c.id=a.transport_provider_id";
$query = $this->read_replica->query($mysql);
$data["country_services"] = $this->table->generate($query);
$mysql = "SELECT * FROM geofence_area_city";
$query = $this->read_replica->query($mysql);
$data["geofence_area_city"] = $this->table->generate($query);
$mysql = "SELECT a.id,b.country,b.city,a.name, c.name AS transport_provider ";
$mysql.= " FROM city_services a, geofence_area_city b, transport_providers c";
$mysql.= " WHERE b.id=a.city_id AND c.id=a.transport_provider_id";
$query = $this->read_replica->query($mysql);
$data["city_services"] = $this->table->generate($query);
$this->renderGeoServicesPage("view_listobjects",$data);
}
public function checkgps() {
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
global $savvyext;
$httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');
$encryptionAlg = $savvyext->cfgReadChar('encryption.algorithm');
$encryptionKey = $savvyext->cfgReadChar('encryption.key');
$encryptionIV = $savvyext->cfgReadChar('encryption.iv');
$api_url = $savvyext->cfgReadChar('system.api_url');
$data['latitude'] = 37.777412;
$data['longitude'] = -122.472961;
if ($this->input->post()) {
$data['latitude'] = $this->input->post('latitude');
$data['longitude'] = $this->input->post('longitude');
}
$url = $api_url . "/booking/api/options/?latitude=" . $data['latitude'] . "&longitude=" . $data['longitude'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Server-Token ' . $httpAuthToken,
"client_id: BackOffice"
)
);
$body = curl_exec($ch);
$result = json_decode($body, true);
$payload = openssl_decrypt(
hex2bin(
$result['payload']
), $encryptionAlg, $encryptionKey, OPENSSL_RAW_DATA, $encryptionIV
);
$data["payload"] = json_decode($payload, true);
$data["page_title"] = "Check Services by GPS coordinates";
$this->renderGeoServicesPage("view_checkgps",$data);
}
}
+314
View File
@@ -0,0 +1,314 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Geofence_area extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('geofence_area_model');
$this->load->model('country_model');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('form', 'url'));
//get query string filter
$queryString = $this->input->server('QUERY_STRING');
$filterData = $this->input->get();
$page = $this->input->get('page');
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->geofence_area_model->getAllWithPagination($page, $this->pagePerItem, $filterData);
$this->viewData['list'] = $data['data'];
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $page, $pagingUrl);
$this->read_replica->order_by('city', 'ASC');
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->renderAdminPage('geofence_area/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->viewData['geofencingAreaTypes'] = Geofence_area_model::GEOFENCING_AREA_TYPES;
$this->viewData['item'] = null;
$this->renderAdminPage('geofence_area/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = null;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->viewData['geofencingAreaTypes'] = Geofence_area_model::GEOFENCING_AREA_TYPES;
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area/create', $this->viewData);
return;
}
$inputData = [
'name' => $this->input->post('name'),
'area' => $this->input->post('area'),
'city_id' => $this->input->post('city_id'),
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'type' => $this->input->post('type'),
'boundaries' => $this->input->post('boundaries') ?: null
];
$this->geofence_area_model->create($inputData);
$this->session->set_flashdata('success', 'Created geofence area successfully.');
redirect('/geofence_area');
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->viewData['item'] = $this->geofence_area_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->viewData['geofencingAreaTypes'] = Geofence_area_model::GEOFENCING_AREA_TYPES;
$this->renderAdminPage('geofence_area/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = $this->geofence_area_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->viewData['geofencingAreaTypes'] = Geofence_area_model::GEOFENCING_AREA_TYPES;
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area/edit', $this->viewData);
return;
}
$inputData = [
'name' => $this->input->post('name'),
'area' => $this->input->post('area'),
'city_id' => $this->input->post('city_id'),
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'type' => $this->input->post('type'),
'boundaries' => $this->input->post('boundaries') ?: null
];
$this->geofence_area_model->update($id, $inputData);
$this->session->set_flashdata('success', 'Updated geofence area successfully.');
redirect('/geofence_area');
}
public function delete($id)
{
$res = $this->geofence_area_model->delete($id);
$this->session->set_flashdata('success', 'Deleted geofence area successfully.');
redirect('/geofence_area');
}
public function comparePriceBetweenAreas()
{
$filterData = $this->input->get();
$fromAreaId = $filterData['from_area_id'] ?? null;
$toAreaId = $filterData['to_area_id'] ?? null;
$this->viewData['polygons'] = [];
$this->viewData['priceComparison'] = [];
if ($fromAreaId && $toAreaId) {
$priceComparisonData = $this->geofence_area_model->priceComparison($fromAreaId, $toAreaId);
if ($priceComparisonData['success']) {
$startArea = $priceComparisonData['from_area'];
$endArea = $priceComparisonData['to_area'];
$startBoundaries = json_decode($startArea['boundaries'], true);
$endBoundaries = json_decode($endArea['boundaries'], true);
if (isset($startBoundaries['polygon'])) {
$startPolygon = $startBoundaries['polygon'];
}
if (isset($endBoundaries['polygon'])) {
$endPolygon = $endBoundaries['polygon'];
}
$polygons = [
"startPolygon" => !empty($startPolygon) ? $startPolygon : [],
"endPolygon" => !empty($endPolygon) ? $endPolygon : []
];
$this->viewData['polygons'] = json_encode($polygons);
$this->viewData['priceComparison'] = $priceComparisonData;
}
}
$this->read_replica->order_by('city', 'ASC');
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->viewData['areaList'] = $this->geofence_area_model->getAllAreas();
$this->viewData['filterData'] = $filterData;
// add css/js
$this->viewData['extra_styles'] = [
'/assets/css/geofence_area/price_comparison.css'
];
$this->viewData['js'] = [
'https://maps.googleapis.com/maps/api/js?key=AIzaSyDvjiRTxngOQyBP4zpqFlZuiquc0ROvo9c&libraries=geometry'
];
$this->renderAdminPage('geofence_area/price-comparison', $this->viewData);
}
public function getCityListDependOnCountryCodeAjax()
{
$inputData = $this->input->get();
$this->read_replica->where('country', $inputData['country_code']);
$this->read_replica->order_by('city', 'ASC');
$query = $this->read_replica->get('geofence_area_city');
$data = $query->result_array();
$response = [
'success' => true,
'data' => !empty($data) ? $data : []
];
echo json_encode($response);
}
public function getAreaListDependOnCityIdAjax()
{
$inputData = $this->input->get();
$cityId = $inputData['city_id'] ?? null;
if ($cityId) {
$this->read_replica->where('city_id', $cityId);
}
$this->read_replica->order_by('name', 'ASC');
$query = $this->read_replica->get('geofence_area');
$data = $query->result_array();
$response = [
'success' => true,
'data' => !empty($data) ? $data : []
];
echo json_encode($response);
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function setCreationRules()
{
$config = [
[
'field' => 'name',
'label' => 'Name',
'rules' => 'required',
],
[
'field' => 'area',
'label' => 'Area name',
'rules' => 'required',
],
[
'field' => 'country_code',
'label' => 'Country',
'rules' => 'required',
],
[
'field' => 'city_id',
'label' => 'City',
'rules' => 'required',
],
[
'field' => 'latitude',
'label' => 'Latitude',
'rules' => 'required|numeric',
],
[
'field' => 'longitude',
'label' => 'Longitude',
'rules' => 'required|numeric',
],
[
'field' => 'type',
'label' => 'Geofencing area types',
'rules' => 'required',
],
[
'field' => 'boundaries',
'label' => 'Boundaries',
'rules' => 'callback_jsonRegex', // The input have to be json format
'errors' => [
'jsonRegex' => 'Please enter a json format.',
],
],
];
$this->form_validation->set_rules($config);
}
public function jsonRegex($input)
{
if (empty(trim($input))) {
return;
}
// json format regex
$pcreRegex = '/
(?(DEFINE)
(?<number> -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
(?<boolean> true | false | null )
(?<string> " ([^"\n\r\t\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
(?<array> \[ (?: (?&json) (?: , (?&json) )* )? \s* \] )
(?<pair> \s* (?&string) \s* : (?&json) )
(?<object> \{ (?: (?&pair) (?: , (?&pair) )* )? \s* \} )
(?<json> \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
)
\A (?&json) \Z
/six';
if (preg_match($pcreRegex, $input)) {
return true;
} else {
return false;
}
}
}
@@ -0,0 +1,315 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Geofence_area_anchor extends Admin_Controller
{
public $viewData = [];
public function __construct()
{
parent::__construct();
$this->load->library('table');
$this->table->set_template($this->template);
$this->load->model('combo_model');
$this->load->model('address_model', 'address');
$this->load->model('Geofence_area_anchor_model', 'geofence_area_anchor');
$this->load->model('Geofence_area_model', 'geofence_area');
$this->load->model('Geofence_area_city_model', 'geofence_area_city');
// Load Pagination library
$this->load->library('pagination');
$this->viewData['city_card'] = $this->combo_model->getCityCombo('city_card', $this->input->get('city'));
$this->viewData['geofence_area_city_card'] = $this->combo_model->getCityCombo('geofence_area_city_card', '');
$this->viewData['country_card'] = $this->combo_model->getCountryCombo('country_card', '');
$this->viewData['msg'] = null;
}
protected function renderToolsPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view('geofence_area_anchor/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function index()
{
$this->renderToolsPage("view_geofence_area_anchor", $this->viewData);
}
private function getFormValue()
{
return [
'geofence_area_city_card' => $this->input->post('geofence_area_city_card'),
'geofence_area_id' => $this->input->post('geofence_area_card'),
'address_id' => $this->input->post('address_id'),
'title' => $this->input->post('title'),
'address' => $this->input->post('address'),
'city_filter' => $this->input->post('city_filter'),
'geo_area_filter' => $this->input->post('geo_area_filter'),
'country_filter' => $this->input->post('country_filter'),
];
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->setFormRuleCreate();
$params = $this->getFormValue();
if ($this->validateForm($params) === FALSE) {
return;
}
if (!$this->geofence_area_anchor->insertGeoAreaAnchor($params)) {
$this->viewData['msg'] = "Insert Failed";
} else {
$this->viewData['msg'] = "Insert Succesful";
}
$this->renderToolsPage('view_geofence_area_anchor', $this->viewData);
}
public function loadRecord()
{
$rowno = $this->input->get('rowno');
$filters = $this->input->get('filters');
$filters = $filters ? $filters : [];
$filters = array_filter($filters, function ($ele) {
return $ele !== '';
});
// Row per page
$rowperpage = 10;
$cur_page = $rowno;
// Row position
if ($rowno != 0) {
$rowno = ($rowno - 1) * $rowperpage;
}
// All records count
$allcount = count($this->geofence_area_anchor->getGeoAreaAnchorRecord($filters));
// Get records
$record = $this->geofence_area_anchor->getGeoAreaAnchorRecord($filters, $rowperpage, $rowno);
// Pagination Configuration
$config['base_url'] = '/Geofence_area_anchor/loadRecord';
$config['use_page_numbers'] = TRUE;
$config['total_rows'] = $allcount;
$config['per_page'] = $rowperpage;
$config['cur_page'] = $cur_page;
$config['suffix'] = '?' . http_build_query($filters);
$config['first_url'] = '/Geofence_area_anchor/loadRecord/0?' . http_build_query($filters);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
// Initialize
$this->pagination->initialize($config);
// Initialize $data Array
$data['pagination'] = $this->pagination->create_links();
$data['result'] = $record;
$data['row'] = $rowno;
echo json_encode($data);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$params = $this->getFormValue();
$params = array_merge($params, [
'id' => $id
]);
$this->setFormRuleUpdate($params);
if ($this->validateForm($params) === FALSE) {
return;
}
if (!$this->geofence_area_anchor->updateGeoAreaAnchor($params)) {
$this->viewData['msg'] = "Update Failed";
} else {
$this->viewData['msg'] = "Updated Succesful";
}
$this->renderToolsPage('view_geofence_area_anchor', $this->viewData);
}
public function validateForm(&$params)
{
$this->form_validation->set_data($params);
if ($this->form_validation->run() == false) {
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['geofence_area_city_card'] = $this->combo_model->getCityCombo('geofence_area_city_card', $params['geofence_area_city_card'] ?? '');
$this->viewData['geofence_area_card'] = $this->combo_model->getGeofenceAreaCombo('geofence_area_card', $params['geofence_area_id'] ?? '');
// Rerender filter if validate fail
$this->viewData['geofence_area_filter_card'] = $this->combo_model->getCityCombo('geofence_area_filter_card', $params['geo_area_filter'] ?? '');
$this->viewData['city_card'] = $this->combo_model->getCityCombo('city_card', $params['city_filter'] ?? '');
$this->viewData['country_card'] = $this->combo_model->getCountryCombo('country_card', $params['country_filter'] ?? '');
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_geofence_area_anchor', $this->viewData);
return FALSE;
}
unset($params['geofence_area_city_card']);
unset($params['address']);
unset($params['city_filter']);
unset($params['geo_area_filter']);
unset($params['country_filter']);
return TRUE;
}
public function setFormRuleCreate()
{
$this->form_validation->set_rules('geofence_area_id', 'Geofence Area', 'required|numeric|callback_isExistsGeofenceArea');
$this->form_validation->set_rules('address_id', 'Address', 'required|numeric|callback_isExistsAddress|callback_isExistsGeoAreaAndAdress');
$this->form_validation->set_rules('title', 'Title', 'max_length[100]');
}
public function setFormRuleUpdate($params)
{
// prevent wrong id of geofene_area_anchor
$this->form_validation->set_rules('id', 'Geofence Area Anchor', 'required|numeric|callback_isExistsGeofenceAreaAnchor');
$this->form_validation->set_rules('geofence_area_id', 'Geofence Area', 'required|numeric|callback_isExistsGeofenceArea');
$this->form_validation->set_rules('title', 'Title', 'max_length[100]');
// prevent duplication of unique key
$old_geo_area_id = $this->input->post('old_geofence_area_id');
$old_address_id = $this->input->post('old_address_id');
if ($old_geo_area_id === $params['geofence_area_id'] && $old_address_id === $params['address_id']) {
$this->form_validation->set_rules('address_id', 'Address', 'required|numeric|callback_isExistsAddress');
} else {
$this->form_validation->set_rules('address_id', 'Address', 'required|numeric|callback_isExistsAddress|callback_isExistsGeoAreaAndAdress');
}
}
private function setFormRuleDelete()
{
$this->form_validation->set_rules('id', 'Geofence Area Anchor', 'required|numeric|callback_isExistsGeofenceAreaAnchor');
}
public function destroy($id = null)
{
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$params = ['id' => $id];
$this->setFormRuleDelete();
if ($this->validateForm($params) === FALSE) {
return;
}
if (!$this->geofence_area_anchor->deleteGeoAreaAnchor($id)) {
$this->viewData['msg'] = "Delete Failed";
} else {
$this->viewData['msg'] = "Delete Succesful";
}
$this->renderToolsPage('view_geofence_area_anchor', $this->viewData);
}
public function getLocationByAddress()
{
$location = $this->address->getAddresses([
'address' => $this->input->get('address'),
'page' => $this->input->get('page')
]);
echo json_encode([
'data' => $location['list'],
'total' => $location['total']
]);
}
public function isExistsAddress($id)
{
if (!$this->address->getAddresses(['id' => $id])) {
$this->form_validation->set_message('isExistsAddress', 'Please enter an existing address');
return FALSE;
} else {
return TRUE;
}
}
public function isExistsGeofenceArea($id)
{
if (!$this->geofence_area->getLocationByID($id)) {
$this->form_validation->set_message('isExistsGeofenceArea', 'Please enter an existing geofence area');
return FALSE;
} else {
return TRUE;
}
}
public function isExistsGeofenceAreaAnchor($id)
{
if (!$this->geofence_area_anchor->getLocationByID($id)) {
$this->form_validation->set_message('isExistsGeofenceAreaAnchor', 'Please enter an existing geofence area anchor');
return FALSE;
} else {
return TRUE;
}
}
public function isExistsGeoAreaAndAdress()
{
$geo_area_id = $this->input->post('geofence_area_card');
$address_id = $this->input->post('address_id');
if (!$geo_area_id || !$address_id) {
$this->form_validation->set_message('isExistsGeoAreaAndAdress', '');
return FALSE;
}
if ($this->geofence_area_anchor->getRecordByGeoAreaAndAddress([
'geofence_area_id' => $geo_area_id,
'address_id' => $address_id
])) {
$this->form_validation->set_message('isExistsGeoAreaAndAdress', 'The data already input');
return FALSE;
} else {
return TRUE;
}
}
public function loadGeoAreaByCity($city_id = NULL)
{
if (is_numeric($city_id) === FALSE) {
echo json_encode([]);
return;
}
echo json_encode($this->geofence_area->getLocationByCityID($city_id));
}
public function loadCityByCountry($country_id = NULL) {
$condition="country='" . pg_escape_string($country_id) . "'";
echo json_encode(['contries' => $this->geofence_area_city->getCities($condition)]);
}
}
@@ -0,0 +1,245 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Geofence_area_city extends Admin_Controller
{
const CSV_FIELDS = [
'id',
'city',
'country',
'latitude',
'longitude',
'location',
'radius',
'status'
];
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('geofence_area_city_model');
$this->load->model('country_model');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('form', 'url'));
//get query string filter
$queryString = $this->input->server('QUERY_STRING');
$filterData = $this->input->get();
$page = $this->input->get('page');
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->geofence_area_city_model->getAllWithPagination($page, $this->pagePerItem, $filterData);
$this->viewData['list'] = $data['data'];
$this->viewData['filterData'] = $filterData;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
Geofence_area_city_model::ACTIVE_STATUS=>'Active',
Geofence_area_city_model::INACTIVE_STATUS=>'Inactive' ,
];
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $page, $pagingUrl);
$this->renderAdminPage('geofence_area_city/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_model::INACTIVE_STATUS,
];
$this->viewData['item'] = null;
$this->renderAdminPage('geofence_area_city/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = null;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_model::INACTIVE_STATUS,
];
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_city/create', $this->viewData);
return;
}
$inputData = [
'city' => $this->input->post('city'),
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'radius' => $this->input->post('radius'),
'status' => $this->input->post('status'),
];
$this->geofence_area_city_model->create($inputData);
$this->session->set_flashdata('success', 'Created geofence area city successfully.');
redirect('/geofence_area_city');
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->viewData['item'] = $this->geofence_area_city_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_model::INACTIVE_STATUS,
];
$this->renderAdminPage('geofence_area_city/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = $this->geofence_area_city_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_model::INACTIVE_STATUS,
];
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_city/edit', $this->viewData);
return;
}
$inputData = [
'city' => $this->input->post('city'),
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'radius' => $this->input->post('radius'),
'status' => $this->input->post('status'),
];
$this->geofence_area_city_model->update($id, $inputData);
$this->session->set_flashdata('success', 'Updated geofence area city successfully.');
redirect('/geofence_area_city');
}
public function delete($id)
{
$res = $this->geofence_area_city_model->delete($id);
$this->session->set_flashdata('success', 'Deleted geofence area city successfully.');
redirect('/geofence_area_city');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function getcityAjax()
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$result = $this->geofence_area_city_model->getCityWithFilter([
'city_name' => trim($this->input->get('city_name')),
'page' => $this->input->get('page')
]);
echo json_encode([
'data' => $result['data'],
'total' => $result['total']
]);
}
private function setCreationRules()
{
$config = [
[
'field' => 'country_code',
'label' => 'Country',
'rules' => 'required',
],
[
'field' => 'city',
'label' => 'City name',
'rules' => 'required',
],
[
'field' => 'latitude',
'label' => 'Latitude',
'rules' => 'required|numeric',
],
[
'field' => 'longitude',
'label' => 'Longitude',
'rules' => 'required|numeric',
],
[
'field' => 'radius',
'label' => 'Radius',
'rules' => 'required|integer',
],
[
'field' => 'status',
'label' => 'Status',
'rules' => 'required|integer',
],
];
$this->form_validation->set_rules($config);
}
public function getCities() {
//get query string filter
$queryString = $this->input->server('QUERY_STRING');
$filterData = $this->input->get();
$page = $this->input->get('page');
// remove empty value
$filterData = array_filter($filterData, function ($val) {
return $val !== '';
});
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$result = $this->geofence_area_city_model->getAllWithPagination($page, $this->pagePerItem, $filterData);
echo json_encode(
[
'data' =>$result['data'],
'total' => $result['total'],
]
);
}
}
@@ -0,0 +1,193 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Geofence_area_city_settings extends Admin_Controller
{
const CSV_FIELDS = [
'id',
'status',
'geofence_area_city',
'image_url',
'is_fectched_data',
'city',
'country',
'latitude',
'longitude'
];
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('geofence_area_city_settings_model');
$this->load->model('country_model');
$this->load->helper('pagination');
global $savvyext;
$this->viewData['storage'] = $savvyext->cfgReadChar('system.storage_url');
}
public function index()
{
$this->load->helper(array('form', 'url'));
//get query string filter
$queryString = $this->input->server('QUERY_STRING');
$filterData = $this->input->get();
$page = $this->input->get('page') ?? 1;
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->geofence_area_city_settings_model->getAllWithPagination($filterData, ['page' => $page, 'itemPerPage' => $this->pagePerItem]);
$this->viewData['list'] = $data['data'];
$this->viewData['filterData'] = $filterData;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
Geofence_area_city_settings_model::ACTIVE_STATUS=>'Active',
Geofence_area_city_settings_model::INACTIVE_STATUS=>'Inactive' ,
];
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $page, $pagingUrl);
$this->renderAdminPage('geofence_area_city_settings/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_settings_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_settings_model::INACTIVE_STATUS,
];
$this->viewData['item'] = null;
$this->renderAdminPage('geofence_area_city_settings/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = null;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_settings_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_settings_model::INACTIVE_STATUS,
];
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_city_settings/create', $this->viewData);
return;
}
$inputData = [
'geofence_area_city' => $this->input->post('city'),
'status' => intval($this->input->post('status')),
'image_url' => $this->input->post('image_url') ?? '',
];
$this->geofence_area_city_settings_model->create($inputData);
$this->session->set_flashdata('success', 'Created geofence area city successfully.');
redirect('/geofence_area_city_settings');
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->viewData['item'] = $this->geofence_area_city_settings_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['editing'] = true;
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_settings_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_settings_model::INACTIVE_STATUS,
];
$this->renderAdminPage('geofence_area_city_settings/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = $this->geofence_area_city_settings_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_settings_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_settings_model::INACTIVE_STATUS,
];
$this->setEditRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_city_settings/edit', $this->viewData);
return;
}
$inputData = [
'status' => $this->input->post('status'),
'image_url' => $this->input->post('image_url') ?? '',
];
$this->geofence_area_city_settings_model->update($id, $inputData);
$this->session->set_flashdata('success', 'Updated geofence area city settings successfully.');
redirect('/geofence_area_city_settings');
}
public function delete($id)
{
$res = $this->geofence_area_city_settings_model->delete($id);
$this->session->set_flashdata('success', 'Deleted geofence area city settings successfully.');
redirect('/geofence_area_city_settings');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function setCreationRules()
{
$config = [
[
'field' => 'city',
'label' => 'City',
'rules' => 'required',
],
[
'field' => 'status',
'label' => 'Status',
'rules' => 'required|integer',
],
];
$this->form_validation->set_rules($config);
}
private function setEditRules()
{
$config = [
[
'field' => 'status',
'label' => 'Status',
'rules' => 'required|integer',
],
];
$this->form_validation->set_rules($config);
}
}
@@ -0,0 +1,151 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Geofence_area_country extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('geofence_area_country_model');
$this->load->model('country_model');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('form', 'url'));
$page = $this->input->get('page');
//get query string filter
$queryString = $this->input->server('QUERY_STRING');
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->geofence_area_country_model->getAllWithPagination($page, $this->pagePerItem);
$this->viewData['list'] = $data['data'];
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $page, $pagingUrl);
$this->renderAdminPage('geofence_area_country/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['item'] = null;
$this->renderAdminPage('geofence_area_country/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = null;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_country/create', $this->viewData);
return;
}
$inputData = [
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'radius' => $this->input->post('radius'),
];
$this->geofence_area_country_model->create($inputData);
$this->session->set_flashdata('success', 'Created geofence area country successfully.');
redirect('/geofence_area_country');
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->viewData['item'] = $this->geofence_area_country_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->renderAdminPage('geofence_area_country/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = $this->geofence_area_country_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_country/edit', $this->viewData);
return;
}
$inputData = [
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'radius' => $this->input->post('radius'),
];
$this->geofence_area_country_model->update($id, $inputData);
$this->session->set_flashdata('success', 'Updated geofence area country successfully.');
redirect('/geofence_area_country');
}
public function delete($id)
{
$res = $this->geofence_area_country_model->delete($id);
$this->session->set_flashdata('success', 'Deleted geofence area country successfully.');
redirect('/geofence_area_country');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function setCreationRules()
{
$config = [
[
'field' => 'country_code',
'label' => 'Country',
'rules' => 'required',
],
[
'field' => 'latitude',
'label' => 'Latitude',
'rules' => 'required|numeric',
],
[
'field' => 'longitude',
'label' => 'Longitude',
'rules' => 'required|numeric',
],
[
'field' => 'radius',
'label' => 'Radius',
'rules' => 'required|integer',
]
];
$this->form_validation->set_rules($config);
}
}
+225
View File
@@ -0,0 +1,225 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Global_settings extends Admin_Controller {
public $viewData = [];
public function __construct() {
parent::__construct();
$this->load->library('table');
$this->table->set_template($this->template);
$this->load->model('combo_model');
$this->load->model('Global_setting_model', 'global_setting');
// Load Pagination library
$this->load->library('pagination');
$this->viewData['card_status'] = $this->combo_model->getStatusCombo('card_status', $this->getFormValue()['status']);
$this->viewData['card_status_filter'] = $this->combo_model->getStatusCombo('card_status_filter', '');
$this->viewData['msg'] = null;
}
private function renderToolsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('global_setting/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function index() {
$this->renderToolsPage("view_global_setting", $this->viewData);
}
private function setFormRuleSearchForm()
{
$this->form_validation->set_rules(
'card_status_filters',
'Status',
'numeric'
);
}
public function loadRecord(){
$rowno = $this->input->get('rowno');
parse_str($this->input->get('filters'), $filters);
$filters = array_filter($filters, function($val) {
return $val !== '';
});
$this->form_validation->set_data($filters);
$this->setFormRuleSearchForm();
$errors = [];
if ($this->form_validation->run() == false) {
$errors = $this->form_validation->error_array();
}
$filters = array_diff_key($filters, $errors);
// Row per page
$rowperpage = 10;
$cur_page = $rowno;
// Row position
if($rowno != 0){
$rowno = ($rowno-1) * $rowperpage;
}
// All records count
$allcount = $this->global_setting->getrecordCount($filters);
// Get records
$users_record = $this->global_setting->getData($rowno, $rowperpage, $filters);
// Pagination Configuration
$config['base_url'] = '/Global_settings/loadRecord';
$config['use_page_numbers'] = TRUE;
$config['total_rows'] = $allcount;
$config['per_page'] = $rowperpage;
$config['cur_page'] = $cur_page;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
// Initialize
$this->pagination->initialize($config);
// Initialize $data Array
$data['pagination'] = $this->pagination->create_links();
$data['result'] = $users_record;
$data['row'] = $rowno;
echo json_encode($data);
}
public function create() {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->setFormRule();
$params = $this->getFormValue();
if ($this->form_validation->run() == false) {
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_global_setting', $this->viewData);
return;
}
if (!$this->global_setting->insertGlobalSetting($params)) {
$this->viewData['msg'] = "Insert Failed";
}
else {
$this->viewData['msg'] = "Insert Succesful";
}
$this->renderToolsPage('view_global_setting', $this->viewData);
}
public function update($id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->setFormRule();
$params = $this->getFormValue();
if (strcmp($params['key'], $params['old_key']) === 0) {
$this->form_validation->set_rules('key', 'Key', 'required|max_length[50]');
}
if ($this->form_validation->run() == false) {
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_global_setting', $this->viewData);
return;
}
if (!$this->global_setting->updateGlobalSetting($id, $params)) {
$this->viewData['msg'] = "Update Failed";
}
else {
$this->viewData['msg'] = "Update Succesful";
}
$this->renderToolsPage('view_global_setting', $this->viewData);
}
private function setFormRule()
{
$this->form_validation->set_rules('key', 'Key', 'trim|required|max_length[50]|is_unique[global_settings.key]');
$this->form_validation->set_rules('value', 'Value', 'trim|required|max_length[50]');
$this->form_validation->set_rules('description', 'description', 'trim|required|max_length[350]');
$this->form_validation->set_rules('card_status', 'Status', 'trim|required|numeric|callback_isValidStatus');
$this->form_validation->set_message('isOutOfRangeInt4', 'The %s field is out of range');
}
public function isValidStatus($status) {
if (preg_match('/^[0-1]{1}$/', $status)) {
return TRUE;
} else {
$this->form_validation->set_message('isValidStatus', 'The Status is invalid');
return FALSE;
}
}
private function getFormValue()
{
return [
'key' => trim($this->input->post('key')),
'value' => trim($this->input->post('value')),
'old_key' => trim($this->input->post('old_key')),
'description' => trim($this->input->post('description')),
'status' => trim($this->input->post('card_status')),
];
}
public function destroy($id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->form_validation->set_data(['id' => $id]);
$this->setFormRuleDelete();
if ($this->form_validation->run() == false) {
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_global_setting', $this->viewData);
return;
}
$this->viewData['msg'] = !$this->global_setting->deleteGlobalSettingById(['id' => $id])
? "Delete Failed"
: "Delete Successful" ;
$this->renderToolsPage('view_global_setting', $this->viewData);
}
private function setFormRuleDelete()
{
$this->form_validation->set_rules('id', 'Global Settings', 'required|numeric|callback_existsGlobalSetting');
}
public function existsGlobalSetting($id) {
if (!$this->global_setting->getGlobalSettingsByID(['id' => $id]))
{
$this->form_validation->set_message('existsGlobalSetting', 'Please choose an existing global settings');
return FALSE;
}
else
{
return TRUE;
}
}
}
+173
View File
@@ -0,0 +1,173 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Gps extends Admin_Controller {
public function index() {
}
protected function renderGpsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('gps/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function tracking() {
$data = array();
$data["members"] = [];
$data["member_id"] = $this->input->get('member_id');
$gps = $this->load->database('gps', TRUE);
$q = "SELECT member_id,count(*) AS count FROM members_tracking GROUP BY member_id ORDER BY member_id";
$r = $gps->query($q);
if ($r->num_rows()) {
foreach ($r->result() as $row) {
$data["members"][] = (array)$row;
}
}
$data["tracking_links"] = "";
$data["tracking_table"] = "";
$data["tracking_trips_table"] = "";
if ($data["member_id"]>0) {
// id member_id traked_group speed lat lng gps ttime loc created device_id previous_id distance duration
$q = "SELECT id,duration,distance,round(speed,2) as speed,date_trunc('second',ttime) as ttime,device_id,loc,traked_group FROM members_tracking WHERE member_id=".$data["member_id"];
$r = $gps->query($q);
if ($r->num_rows()) {
$this->load->library('pagination');
$config = array();
$config["total_rows"] = $r->num_rows();
$config["base_url"] = base_url() . "/gps/tracking";
$config["per_page"] = 20;
$config["uri_segment"] = 3;
$config["num_links"] = 7;
$config['attributes'] = array('onclick' => 'document.location=this.href+\'?member_id='.$data["member_id"].'\';return false;');
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$page = is_numeric($page) ? $page : 0;
$q.= " ORDER BY ttime DESC LIMIT " . $config["per_page"] . " OFFSET " . $page;
$query = $gps->query($q);
$this->load->helper('url');
$this->load->library('table');
$this->table->set_template($this->template);
// id duration distance speed ttime device_id loc traked_group
$this->table->set_heading(
array('data' => 'ID', 'style' => 'width:80px'),
array('data' => 'Duration', 'style' => 'width:80px'),
array('data' => 'Distance', 'style' => 'width:80px'),
array('data' => 'Speed', 'style' => 'width:80px'),
array('data' => 'Time', 'style' => 'width:160px'),
array('data' => 'Device ID', 'style' => 'width:80px'),
array('data' => 'IP Address', 'style' => 'width:80px'),
array('data' => 'Tracked Group', 'style' => 'width:80px')
);
$data["tracking_table"] = $this->table->generate($query);
$data["tracking_links"] = $this->pagination->create_links();
}
$q = "SELECT '<button id=\"trip'||id||'\" type=\"button\" class=\"btn btn-primary btn-xs\" block onclick=\"viewTrip('||id||');\">View</button>',";
$q.= "ROUND(a.duration,0) AS duration,ROUND(a.distance,2) AS distance,ROUND(a.speed,2) AS speed, ROUND(a.avg_speed,2) AS avg_speed ";
$q.= "FROM members_tracking_trips a WHERE a.member_id=".$data["member_id"];
$q.= " AND a.distance>15 AND a.duration>15";
$r = $gps->query($q);
$this->table->set_heading(
array('data' => 'ID', 'style' => 'width:30px'),
array('data' => 'Duration', 'style' => 'width:40px'),
array('data' => 'Distance', 'style' => 'width:40px'),
array('data' => 'Speed', 'style' => 'width:40px'),
array('data' => 'Avg.Speed', 'style' => 'width:40px')
);
$data["tracking_trips_table"] = $this->table->generate($r);
}
$data["page_title"] = "GPS Tracking";
$this->renderGpsPage("view_tracking", $data);
}
public function trip() {
global $savvyext;
$data = array();
$data["members"] = [];
$data["member_id"] = (int)$this->input->get('member_id');
$data["id"] = (int)$this->input->get('id');
if ($data["id"]<1 || $data["member_id"]<1) {
redirect('gps/tracking?member_id='.$data["member_id"]);
return;
}
$gps = $this->load->database('gps', TRUE);
$q = "SELECT a.id, a.device_id, ROUND(a.duration,0) AS duration, ";
$q.= "ROUND(a.distance,2) AS distance,ROUND(a.speed,2) AS speed, ";
$q.= "ROUND(a.avg_speed,2) AS avg_speed, a.location_start, a.location_end, ";
$q.= "b.lat AS start_lat, b.lng AS start_lng, ";
$q.= "c.lat AS end_lat, c.lng AS end_lng, ";
$q.= "b.ttime AS start_time, c.ttime AS end_time ";
$q.= "FROM members_tracking_trips a ";
$q.= "LEFT JOIN members_tracking b ON (b.id=a.location_start) ";
$q.= "LEFT JOIN members_tracking c ON (c.id=a.location_end) ";
$q.= "WHERE a.member_id=".$data["member_id"]." AND a.id=".$data["id"];
$r = $gps->query($q);
$f = $r->row_array();
$data = array_merge($data, $f);
$q = "SELECT date_trunc('second',ttime) AS ttime,lat,lng,speed,distance,duration ";
$q.= "FROM members_tracking WHERE member_id=".$data["member_id"]." ";
$q.= "AND id>=".$data["location_start"]." AND id<=".$data["location_end"]." ";
$q.= ($data["device_id"]>0?("AND device_id=".$data["device_id"]):" AND device_id IS NULL");
$q.= " ORDER BY ttime";
$r = $gps->query($q);
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading(
array('data' => 'Time', 'style' => 'width:30px'),
array('data' => 'Lat', 'style' => 'width:30px'),
array('data' => 'Lng', 'style' => 'width:30px'),
array('data' => 'Speed', 'style' => 'width:40px'),
array('data' => 'Distance', 'style' => 'width:40px'),
array('data' => 'Duration', 'style' => 'width:40px')
);
$data["tracking_trips_table"] = $this->table->generate($r);
$min_lat = PHP_INT_MAX;
$min_lng = PHP_INT_MAX;
$max_lat = PHP_INT_MIN;
$max_lng = PHP_INT_MIN;
$center_lat = 0;
$center_lng = 0;
foreach ($r->result() as $row) {
$f = (array) $row;
$data["items"][] = $f;
if ($f["lat"]<$min_lat) $min_lat = $f["lat"];
if ($f["lng"]<$min_lng) $min_lng = $f["lng"];
if ($f["lat"]>$max_lat) $max_lat = $f["lat"];
if ($f["lng"]>$max_lng) $max_lng = $f["lng"];
}
$data["center_lat"] = ($min_lat+$max_lat)/2;
$data["center_lng"] = ($min_lng+$max_lng)/2;
$data['google_api_key'] = $savvyext->cfgReadChar('google.api_key');
$this->renderGpsPage("view_trip", $data);
}
}
@@ -0,0 +1,19 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require 'vendor/autoload.php';
class LogViewerController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->logViewer = new \CILogViewer\CILogViewer();
//...
}
public function index()
{
echo $this->logViewer->showLogs();
return;
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Logout extends CI_Controller {
public function index() {
$data = array();
$_SESSION['firstname'] = $_SESSION['username'] = $_SESSION['sessionid'] = $_SESSION['session_id'] = "";
$data['action_message'] = '';
unset($_SESSION);
redirect('welcome');
}
}
File diff suppressed because it is too large Load Diff
+167
View File
@@ -0,0 +1,167 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Myfloat_version extends Admin_Controller
{
public function index()
{
$this->load->model('myfloat_version_model');
$platform_id = "";
$validated = true;
$data = [
"platform_id" => "",
"name" => "",
"released" => "",
"notes" => "",
"rev_count" => "",
"short_hash" => "",
"url" => "",
"form_button" => "Create",
];
$data['message'] = "";
$query = "SELECT id,platform
FROM members_device_platforms
WHERE platform != ''";
$platforms = $this->read_replica->query($query);
$platforms = $platforms->result_array();
try {
if ($_POST) {
$data['id'] = $this->input->post('id') ? trim($this->input->post('id')) : "";
$platform_id = trim($this->input->post('platform_id'));
$data['platform_id'] = $platform_id;
$data['name'] = trim($this->input->post('name'));
$data['released'] = trim($this->input->post('released'));
$data['notes'] = trim($this->input->post('notes'));
$data['rev_count'] = trim($this->input->post('rev_count'));
$data['short_hash'] = trim($this->input->post('short_hash'));
$data['url'] = trim($this->input->post('url'));
// Validate
if (empty($data['platform_id'])) {
$data['message'] .= "<br/>Invalid platform id";
$validated = false;
}
if (empty($data['name']) || strlen($data['name']) > 50) {
$data['message'] .= "<br/>Invalid name";
$validated = false;
}
if (empty($data['released'])) {
$data['message'] .= "<br/>Invalid released";
$validated = false;
}
if ($validated == true) {
// Upsert
$q = "INSERT INTO myfloat_version
(
platform_id,
name,
released,
notes,
rev_count,
short_hash,
url
)
VALUES
(
'" . pg_escape_string($data['platform_id']) . "',
'" . pg_escape_string($data['name']) . "',
'" . pg_escape_string($data['released']) . "',
'" . pg_escape_string($data['notes']) . "',
" . ($data['rev_count'] ?: 0) . ",
'" . pg_escape_string($data['short_hash']) . "',
'" . pg_escape_string($data['url']) . "'
) ON CONFLICT (platform_id,name) DO UPDATE SET
platform_id = '" . pg_escape_string($data['platform_id']) . "',
name = '" . pg_escape_string($data['name']) . "',
released = '" . pg_escape_string($data['released']) . "',
notes = '" . pg_escape_string($data['notes']) . "',
short_hash = '" . pg_escape_string($data['short_hash']) . "',
rev_count = " . ($data['rev_count'] ?: 0) . ",
url = '" . pg_escape_string($data['url']) . "'
RETURNING *,
CASE WHEN xmax::text::int > 0
THEN 'updated' else 'inserted' END AS act";
if ($data['message'] == "") {
$r = $this->db->query($q);
$f = $r->row_array();
$act = $f["act"];
if ($f != null && isset($act)) {
$data['message'] = 'My float version ' . $act . '!';
$data["form_button"] = $act == 'inserted' ? 'Insert' : 'Update';
} else {
$data['message'] = 'Failed to ' . $act . ' my float version!';
}
}
}
}
$params = [];
$params = $this->input->get();
$query = $this->myfloat_version_model->getVersionQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'/myfloat_version/index',
[
'per_page' => 20,
'reuse_query_string' => TRUE,
]
);
$data['links'] = $tableData['links'];
$data['crashlog_table'] = $tableData['output_table'];
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['filterData'] = $params;
$data = array_merge($data, [
"versions" => $tableData['limited_data'],
"page" => $page,
"platforms" => $platforms,
]);
} catch (Exception $e) {
$data["message"] = $e->getMessage();
}
$this->renderAdminPage('view_myfloat_version', $data);
}
public function deleteVersion()
{
$data = [];
$id = (int) $this->input->get('id');
header('Content-Type: application/json');
if ($id > 0) {
$q = "DELETE FROM myfloat_version WHERE id=${id}";
$r = $this->db->query($q);
if ($r) {
echo json_encode([
'state' => 'successful',
'message' => 'My Float Version is deleted',
'id' => $id,
]);
} else {
echo json_encode([
'state' => 'failure',
'message' => 'Delete failed',
]);
}
} else {
echo json_encode([
'state' => 'failure',
'message' => 'Invalid ID',
]);
}
}
}
+553
View File
@@ -0,0 +1,553 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Notifications extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Notification_model', 'notification');
$this->load->model('Members_notification_model', 'members_notification');
}
public function index() {
$this->noticelist();
}
public function noticelist() {
$data = [];
$data['page_title'] = "Members Notifications";
$params = [];
if ($this->input->method(TRUE) === 'GET') {
$params = $this->input->get();
}
$query = $this->members_notification->getNotifications($params);
$data['params'] = $params;
$tableData = $this->returnAdminTable([
'count_query' => $query,
'query' => $query,
], remove_querystring_var($_SERVER['REQUEST_URI'], 'page'), [
'per_page' => 100,
'enable_query_strings'=>TRUE,
'page_query_string'=>TRUE,
'use_page_numbers'=>TRUE,
'reuse_query_string'=>FALSE,
'query_string_segment'=>'page',
]);
$data['notification_table'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$this->table->set_heading(
['data' => 'Member', 'style' => 'width:50px'], ['data' => 'Account Email', 'style' => 'width:150px'], ['data' => 'Notify', 'style' => 'width:50px'], ['data' => 'trigger_key', 'style' => 'width:50px'], ['data' => 'Email-Msg', 'style' => 'width:50px'], ['data' => 'M-Type', 'style' => 'width:90px'], 'Message', ['data' => 'Status', 'style' => 'width:50px'], ['data' => 'Add Date', 'style' => 'width:95px'], ['data' => 'Mode', 'style' => 'width:75px'], ['data' => 'Action', 'style' => 'width:40px']
);
$data['notificationStatus'] = [
Members_notification_model::PENDING_STATUS => 'Pending',
Members_notification_model::CANCELLED_STATUS => 'Cancelled',
Members_notification_model::COMPLETED_STATUS => 'Completed',
Members_notification_model::EXPIRED_STATUS => 'Expired',
];
// get notification types list
$notificationTypesQuery = $this->read_replica->get('notification_types');
$data['notificationTypes'] = $notificationTypesQuery->result();
$this->renderNotificationPage('view_noticelist', $data);
}
/*
* member_id | integer |
| character varying(10) |
| text |
status | integer | default 1
added | timestamp without time zone | default now()
| character varying(20) | not null
trigger_key
*/
public function load_ckeditor() {
$this->load->library('ckeditor');
$this->ckeditor->basePath = base_url() . 'assets/ckeditor/';
$this->ckeditor->config['toolbar'] = [
[
'Source',
'-',
'Bold',
'Italic',
'Underline',
'-',
'Cut',
'Copy',
'Paste',
'PasteText',
'PasteFromWord',
'-',
'Undo',
'Redo',
'-',
'NumberedList',
'BulletedList'
]
];
$this->ckeditor->config['width'] = 'auto';
$this->ckeditor->config['height'] = '200px';
}
public function load_pagination($all_record, $params) {
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . "/notifications/emailtrigger";
$config["suffix"] = '?' . http_build_query($params);
$config["first_url"] = '/notifications/emailtrigger/0?' . http_build_query($params);
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function setValueCombo($val) {
$yes_no_value = [0, 1];
return in_array($val, $yes_no_value) ? $val : '';
}
public function setComboForEmailTrigger($params) {
$this->load->model('combo_model');
$combo['card_send_notification'] = $this->combo_model->getYesNoComboWithAll(
'card_send_notification', $params['send_notification']
);
$combo['card_send_mail'] = $this->combo_model->getYesNoComboWithAll(
'card_send_mail', $params['send_mail']
);
$combo['card_status'] = $this->combo_model->getStatusComboWithAll(
'card_status', $params['status']
);
return $combo;
}
public function triggerreport() {
$this->load->library('table');
$this->table->set_template($this->template);
$data = [];
$data["page_title"] = "Trigger Items Aggregate Report";
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['country_report'] = $this->table->generate($query);
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id AND n.status = 1 GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['trigger_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id AND n.status = 5 AND n.date_sent > now()+ '-1 days' GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['completed_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification WHERE status = 1 GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_pending_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification WHERE status = 5 GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_completed_report_table'] = $this->table->generate($query);
$this->renderNotificationPage('view_trigger_report', $data);
}
public function emailtrigger() {
$this->load->model('email_trigger_model');
$this->load->helper('url');
$this->load_ckeditor();
$params = $this->getValueOfEmailTriggerForm();
$data = $this->setComboForEmailTrigger($params);
$params['send_notification'] = $this->setValueCombo($params['send_notification']);
$params['send_mail'] = $this->setValueCombo($params['send_mail']);
$params['status'] = $this->setValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForEmailTriggerForm($params);
$params = array_diff_key($params, $errors);
$data = array_merge($data, $params);
$data['page_title'] = "Email Trigger";
$data = array_merge(
$data, $this->load_pagination(
$this->email_trigger_model->get_email_trigger_records($params), $params
)
);
$data['trigger_table'] = $this->email_trigger_model->get_email_trigger_records(
$params, $data['limit'], $data['offset']
);
$this->renderNotificationPage('view_emailtrigger', $data);
}
public function getValueOfEmailTriggerForm() {
return [
'trigger_id' => trim($this->input->get('trigger_id') ?? ''),
'next_action' => trim($this->input->get('next_action') ?? ''),
'card_key' => trim($this->input->get('card_key') ?? ''),
'email_template' => trim($this->input->get('email_template') ?? ''),
'send_mail' => trim($this->input->get('card_send_mail') ?? -1),
'send_notification' => trim($this->input->get('card_send_notification') ?? -1),
'status' => trim($this->input->get('card_status') ?? -1),
'icon' => trim($this->input->get('icon') ?? ''),
];
}
public function validateValueForEmailTriggerForm($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForEmailTriggerForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForEmailTriggerForm() {
$yes_no_pattern = 'regex_match[/^(?:[0-1])$/]';
$this->form_validation->set_rules('send_mail', 'Send email', $yes_no_pattern);
$this->form_validation->set_rules('send_notification', 'Send Notification', $yes_no_pattern);
$this->form_validation->set_rules('status', 'Status', $yes_no_pattern);
}
public function generateCard() {
$out = array();
$notice_id = (int) $this->input->get('notice_id');
$member_id = (int) $this->input->get('member_id');
$message = "";
global $trigger_card;
// print_r($trigger_card);
$trigger_key = "";
$dynamic_key = "";
$status_msg = '';
$cat = '';
if ($notice_id != '' && $member_id != '') {
$mysql = "SELECT * FROM members_notification WHERE id=$notice_id AND member_id=$member_id";
$query = $this->read_replica->query($mysql);
$row = $query->row();
if (isset($row)) {
$trigger_key = $row->trigger_key;
$message = $row->msg;
}
$card_allowded = false;
if (array_key_exists($trigger_key, $trigger_card)) {
$status_msg = "The $trigger_key is in the array";
// print_r( $trigger_card[$trigger_key] );
$dynamic_key = $trigger_card[$trigger_key]["dynamic_key"];
$mysql = "SELECT category FROM email_trigger WHERE e_trigger='".$trigger_key."' LIMIT 1";
$query = $this->read_replica->query($mysql);
$row = $query->row();
if (isset($row)) {
$cat = $row->category;
}else{
$cat = $trigger_card[$trigger_key]["cat"];
}
$card_allowded = true;
} else {
$status_msg = "The $trigger_key not set up for cards";
}
if (true == $card_allowded && $message != '' && $trigger_key != '' && $dynamic_key != '') {
$in = array();
$in["dynamic_key"] = $dynamic_key;
$in["member_id"] = $member_id;
$in["trigger_key"] = $trigger_key;
$in["message"] = $message;
$in["notice_id"] = $notice_id;
$in["cat"] = $cat;
$in['action'] = FLOAT_SYSTEM_CREATE_DYNAMICCARD;
$ret = $this->savvy_api($in, $out);
echo "---------------------## ------------------------";
print_r($out);
if ($ret == PHP_API_OK) {
$message = 'Completed!';
} else {
$message = 'Failed to Create';
}
}
}
echo $status_msg;
}
public function sendnotification() {
//notice_id='+notice_id+'&member_id=' + member_id
// echo 'Ameye';
$out = array();
$message = "";
$notice_id = (int) $this->input->get('notice_id');
$member_id = (int) $this->input->get('member_id');
if ($notice_id != '' && $member_id != '') {
// get the message
/*
* savvy=> SELECT * FROM members_notification WHERE member_id =1 AND id = 4967;;
id | member_id | notice_type | msg | status | added | mmode | trigger_key
------+-----------+-------------+---------------------------------------------+--------+---------------------------+-------+-------------
4967 | 1 | GENALERT | You are spending too much. Let's save money | 1 | 2020-02-23 04:00:03.58477 | AUTO | ETRG0003
(1 row)
*/
$mysql = "SELECT * FROM members_notification WHERE member_id = ${member_id} AND id = ${notice_id}"; //SELECT * FROM members_devices WHERE member_id=${member_id}";
$query = $this->read_replica->query($mysql);
$row = $query->row();
if (isset($row)) {
$message = $row->msg;
}
//echo $message;
$device_count = 0;
$q = "SELECT * FROM members_devices WHERE member_id=${member_id}";
$r = $this->read_replica->query($q);
foreach ($r->result() as $row) {
$data["devices"][] = $row->player_id;
$device_count++;
}
// $data["devices"] = ['a','b','c'];
$arrayData = array("NEXTSCREEN" => "bar");
if ($device_count > 0 && $message != '') {
$this->load->model('onesignal_model');
// print_r($data["devices"]);
$out = $this->onesignal_model->sendmemberMessage($member_id, $data["devices"], $message, $arrayData);
// print_r($out);
}
}
}
protected function renderNotificationPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('notifications/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function update() {
$result = $this->notification->updateDescription([
'id' => $this->input->post('id'),
'description' => $this->input->post('description'),
]);
echo json_encode([
'message' => $result ? "Updated" : "Failed",
'code' => $result ? 1 : 0
]);
}
public function before_update_trigger(){
$e_trigger = $this->input->get('e_trigger');//
$card_settings = $this->input->get('card_settings');//
//check card is used
$mysql = "SELECT m.id AS card_id, m.dynamic_key, e.e_trigger, e.action_detail FROM main_cards m LEFT JOIN email_trigger e ON m.dynamic_key = e.dynamic_key WHERE m.id='".$card_settings."'";
$query = $this->read_replica->query($mysql);
$mr = $query->row_array();
$message ='';
$used = false;
if(!empty($mr)){
$used_trigger = $mr["e_trigger"];
$dynamic_key = $mr["dynamic_key"];
if(!empty($dynamic_key) && $used_trigger!=$e_trigger){//used
$used = true;
$message= "Action card is used by ".$used_trigger.". Do you want to update?";
}
}
echo json_encode([
'message' => $message,
'used' => $used
]);exit;
}
public function update_trigger() {
// echo "updateTriggerItem Ameye";
// url: "/notifications/updateTriggerItem?category_settings=" + category_settings + "&e_trigger=" + e_trigger
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
$message_card = "";
if ($this->input->post()) {
$category_settings = $this->input->post('category_settings');
$e_trigger = $this->input->post('e_trigger');
$card_settings = $this->input->post('card_settings');
$override_text = $this->input->post('override_text');
$expiration = $this->input->post('expiration');
$icon = $this->input->post('icon');
$notify_title = pg_escape_string($this->input->post('notify_title')??'');
$frequency = $this->input->post('frequency') ?: null;
$send_day = $this->input->post('send_day') ?: null;
$send_time = $this->input->post('send_time') ?: null;
if ($e_trigger != '' && $category_settings != '' && $card_settings != '') {
// update email trigger
$this->db->set('category', $category_settings);
$this->db->set('override_text', $override_text);
$this->db->set('expiration', $expiration);
$this->db->set('icon', $icon);
$this->db->set('notify_title', $notify_title);
$this->db->set('frequency', $frequency);
$this->db->set('send_day', $send_day);
$this->db->set('send_time', $send_time);
//where condition
$this->db->where('e_trigger', $e_trigger);
//update
$query = $this->db->update('email_trigger');
//$mysql = "UPDATE email_trigger SET category='$category_settings',override_text=$override_text,expiration='$expiration', icon='$icon', notify_title = '$notify_title' WHERE e_trigger='$e_trigger'";
// $query = $this->db->query($mysql);
$q = "SELECT e.dynamic_key, m.description as action_detail,m.id AS card_id FROM email_trigger e LEFT JOIN main_cards m ON m.dynamic_key = e.dynamic_key WHERE e.e_trigger='".$e_trigger."'";
$query = $this->read_replica->query($q);
$mr = $query->row_array();
$dynamic_key = $mr["dynamic_key"];
$action_detail = $mr["action_detail"];
$card_id = $mr["card_id"];
$mysql ="";
if(!empty($card_id)){
$mysql.= "UPDATE main_cards SET dynamic_key=null WHERE id='$card_id';";
}
$mysql .= "UPDATE main_cards SET dynamic_key='$dynamic_key' WHERE id = '".$card_settings."'";
$this->db->query($mysql);
$message = "Updated ";
// Override Card Text Copy Description
if($override_text == 1 && !empty($e_trigger)){
$description = trim(preg_replace('/\s+/', ' ', strip_tags($action_detail)));
$mysql = "UPDATE email_trigger SET action_detail = '".pg_escape_string($description)."' WHERE e_trigger='$e_trigger'";
$this->db->query($mysql);
$message = "Updated and Overriding";
}
echo $message;
}
}
}
public function editTrigger() {
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
if ($this->input->get()) {
$trigger_id = $this->input->get('trigger_id');
/*
id | e_trigger | category | action_detail | template_name | status | added | updated | dynamic_key | message | send_mail | send_notification
----+-----------+------------+------------------------------------------+---------------+--------+----------------------------+----------------------------+-------------+-------------------------------+-----------+-------------------
2 | ETRG0002 | GOACTIVITY | <p>Good Job, you&#39;re saving money</p>+| etrg0002.html | 1 | 2020-02-18 15:06:46.721542 | 2020-02-18 15:06:46.721542 | ETRG0002KEY | Good Job, you're saving money | 0 | 1
| | | | | | | | | | |
(1 row)
*/
if ($trigger_id != '') {
$mysql = "SELECT e.*,m.id AS card_id FROM email_trigger e LEFT JOIN main_cards m ON m.dynamic_key = e.dynamic_key WHERE e.e_trigger='$trigger_id'";
$query = $this->read_replica->query($mysql);
$mr = $query->row_array();
// print_r($mr);
$data["e_trigger"] = $mr["e_trigger"];
$data["category"] = $mr["category"];
$data["dynamic_key"] = $mr["dynamic_key"];
$data["card_id"] = $mr["card_id"];
$data["override_text"] = $mr["override_text"];
$data["expiration"] = $mr["expiration"];
$data["icon"] = $mr["icon"];
$data["notify_title"] = $mr["notify_title"]??'';
$data["frequency"] = $mr["frequency"]??'';
$data["send_day"] = $mr["send_day"]??'';
$data["send_time"] = $mr["send_time"]??'';
// $this->memberPointsItems($member_id, $data);
$data["category_settings"] = $this->combo_model->getCardCategoryCombo("category_settings", $data["category"], '', 'CARDDYNAMIC');
// $data['member_id'] = $member_id;
$data['card_settings'] = $this->combo_model->getTriggerCardsCombo("card_settings", $data["card_id"]);
$data["override_text_combo"] = $this->combo_model->getYesNoCombo("override_text", $data["override_text"]);
$data["expiration_combo"] = $this->combo_model->getTriggerExpirationCombo("expiration", $data["expiration"]);
$data["frequency_combo"] = $this->combo_model->getTriggerFrequency("frequency", $data["frequency"]);
$data["send_day_combo"] = $this->combo_model->getTriggerSendDay("send_day", $data["send_day"]);
$data["send_time_combo"] = $this->combo_model->getTriggerSendTime("send_time", $data["send_time"]);
$this->load->view('notifications/extra/notifications_extra', $data);
}
}
}
}
@@ -0,0 +1,518 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Notifications extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Notification_model', 'notification');
$this->load->model('Members_notification_model', 'members_notification');
}
public function index() {
$this->noticelist();
}
public function noticelist() {
$data = [];
$data['page_title'] = "Members Notifications";
$params = [];
if ($this->input->method(TRUE) === 'GET') {
$params = $this->input->get();
}
$query = $this->members_notification->getNotifications($params);
$data['params'] = $params;
$tableData = $this->returnAdminTable([
'count_query' => $query,
'query' => $query,
], remove_querystring_var($_SERVER['REQUEST_URI'], 'page'), [
'per_page' => 100,
'enable_query_strings'=>TRUE,
'page_query_string'=>TRUE,
'use_page_numbers'=>TRUE,
'reuse_query_string'=>FALSE,
'query_string_segment'=>'page',
]);
$data['notification_table'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$this->table->set_heading(
['data' => 'Member', 'style' => 'width:50px'], ['data' => 'Account Email', 'style' => 'width:150px'], ['data' => 'Notify', 'style' => 'width:50px'], ['data' => 'trigger_key', 'style' => 'width:50px'], ['data' => 'Email-Msg', 'style' => 'width:50px'], ['data' => 'M-Type', 'style' => 'width:90px'], 'Message', ['data' => 'Status', 'style' => 'width:50px'], ['data' => 'Add Date', 'style' => 'width:95px'], ['data' => 'Mode', 'style' => 'width:75px'], ['data' => 'Action', 'style' => 'width:40px']
);
$data['notificationStatus'] = [
Members_notification_model::PENDING_STATUS => 'Pending',
Members_notification_model::CANCELLED_STATUS => 'Cancelled',
Members_notification_model::COMPLETED_STATUS => 'Completed',
Members_notification_model::EXPIRED_STATUS => 'Expired',
];
// get notification types list
$notificationTypesQuery = $this->read_replica->get('notification_types');
$data['notificationTypes'] = $notificationTypesQuery->result();
$this->renderNotificationPage('view_noticelist', $data);
}
/*
* member_id | integer |
| character varying(10) |
| text |
status | integer | default 1
added | timestamp without time zone | default now()
| character varying(20) | not null
trigger_key
*/
public function load_ckeditor() {
$this->load->library('ckeditor');
$this->ckeditor->basePath = base_url() . 'assets/ckeditor/';
$this->ckeditor->config['toolbar'] = [
[
'Source',
'-',
'Bold',
'Italic',
'Underline',
'-',
'Cut',
'Copy',
'Paste',
'PasteText',
'PasteFromWord',
'-',
'Undo',
'Redo',
'-',
'NumberedList',
'BulletedList'
]
];
$this->ckeditor->config['width'] = 'auto';
$this->ckeditor->config['height'] = '200px';
}
public function load_pagination($all_record, $params) {
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . "/notifications/emailtrigger";
$config["suffix"] = '?' . http_build_query($params);
$config["first_url"] = '/notifications/emailtrigger/0?' . http_build_query($params);
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function setValueCombo($val) {
$yes_no_value = [0, 1];
return in_array($val, $yes_no_value) ? $val : '';
}
public function setComboForEmailTrigger($params) {
$this->load->model('combo_model');
$combo['card_send_notification'] = $this->combo_model->getYesNoComboWithAll(
'card_send_notification', $params['send_notification']
);
$combo['card_send_mail'] = $this->combo_model->getYesNoComboWithAll(
'card_send_mail', $params['send_mail']
);
$combo['card_status'] = $this->combo_model->getStatusComboWithAll(
'card_status', $params['status']
);
return $combo;
}
public function triggerreport() {
$this->load->library('table');
$this->table->set_template($this->template);
$data = [];
$data["page_title"] = "Trigger Items Aggregate Report";
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['country_report'] = $this->table->generate($query);
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id AND n.status = 1 GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['trigger_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id AND n.status = 5 AND n.date_sent > now()+ '-1 days' GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['completed_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification WHERE status = 1 GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_pending_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification WHERE status = 5 GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_completed_report_table'] = $this->table->generate($query);
$this->renderNotificationPage('view_trigger_report', $data);
}
public function emailtrigger() {
$this->load->model('email_trigger_model');
$this->load->helper('url');
$this->load_ckeditor();
$params = $this->getValueOfEmailTriggerForm();
$data = $this->setComboForEmailTrigger($params);
$params['send_notification'] = $this->setValueCombo($params['send_notification']);
$params['send_mail'] = $this->setValueCombo($params['send_mail']);
$params['status'] = $this->setValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForEmailTriggerForm($params);
$params = array_diff_key($params, $errors);
$data = array_merge($data, $params);
$data['page_title'] = "Email Trigger";
$data = array_merge(
$data, $this->load_pagination(
$this->email_trigger_model->get_email_trigger_records($params), $params
)
);
$data['trigger_table'] = $this->email_trigger_model->get_email_trigger_records(
$params, $data['limit'], $data['offset']
);
$this->renderNotificationPage('view_emailtrigger', $data);
}
public function getValueOfEmailTriggerForm() {
return [
'trigger_id' => trim($this->input->get('trigger_id') ?? ''),
'next_action' => trim($this->input->get('next_action') ?? ''),
'card_key' => trim($this->input->get('card_key') ?? ''),
'email_template' => trim($this->input->get('email_template') ?? ''),
'send_mail' => trim($this->input->get('card_send_mail') ?? -1),
'send_notification' => trim($this->input->get('card_send_notification') ?? -1),
'status' => trim($this->input->get('card_status') ?? -1),
];
}
public function validateValueForEmailTriggerForm($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForEmailTriggerForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForEmailTriggerForm() {
$yes_no_pattern = 'regex_match[/^(?:[0-1])$/]';
$this->form_validation->set_rules('send_mail', 'Send email', $yes_no_pattern);
$this->form_validation->set_rules('send_notification', 'Send Notification', $yes_no_pattern);
$this->form_validation->set_rules('status', 'Status', $yes_no_pattern);
}
public function generateCard() {
$out = array();
$notice_id = (int) $this->input->get('notice_id');
$member_id = (int) $this->input->get('member_id');
$message = "";
global $trigger_card;
// print_r($trigger_card);
$trigger_key = "";
$dynamic_key = "";
$status_msg = '';
$cat = '';
if ($notice_id != '' && $member_id != '') {
$mysql = "SELECT * FROM members_notification WHERE id=$notice_id AND member_id=$member_id";
$query = $this->read_replica->query($mysql);
$row = $query->row();
if (isset($row)) {
$trigger_key = $row->trigger_key;
$message = $row->msg;
}
$card_allowded = false;
print_r( $trigger_card );
// print_r( $trigger_key );
// echo $trigger_key." -:- ".$trigger_card;
if (array_key_exists($trigger_key, $trigger_card)) {
$status_msg = "The $trigger_key is in the array";
// print_r( $trigger_card[$trigger_key] );
$dynamic_key = $trigger_card[$trigger_key]["dynamic_key"];
$cat = $trigger_card[$trigger_key]["cat"];
$card_allowded = true;
} else {
$status_msg = "The $trigger_key not set up for cards";
}
if (true == $card_allowded && $message != '' && $trigger_key != '' && $dynamic_key != '') {
$in = array();
$in["dynamic_key"] = $dynamic_key;
$in["member_id"] = $member_id;
$in["trigger_key"] = $trigger_key;
$in["message"] = $message;
$in["notice_id"] = $notice_id;
$in["cat"] = $cat;
$in['action'] = FLOAT_SYSTEM_CREATE_DYNAMICCARD;
$ret = $this->savvy_api($in, $out);
print_r($out);
if ($ret == PHP_API_OK) {
$message = 'Completed!';
} else {
$message = 'Failed to Create';
}
}
}
echo $status_msg;
}
public function sendAllnotification(){
$this->sendnotification();
$this->generateCard();
}
public function sendnotification() {
//notice_id='+notice_id+'&member_id=' + member_id
// echo 'Ameye';
$out = array();
$message = "";
$notice_id = (int) $this->input->get('notice_id');
$member_id = (int) $this->input->get('member_id');
if ($notice_id != '' && $member_id != '') {
// get the message
/*
* savvy=> SELECT * FROM members_notification WHERE member_id =1 AND id = 4967;;
id | member_id | notice_type | msg | status | added | mmode | trigger_key
------+-----------+-------------+---------------------------------------------+--------+---------------------------+-------+-------------
4967 | 1 | GENALERT | You are spending too much. Let's save money | 1 | 2020-02-23 04:00:03.58477 | AUTO | ETRG0003
(1 row)
*/
$mysql = "SELECT * FROM members_notification WHERE member_id = ${member_id} AND id = ${notice_id}"; //SELECT * FROM members_devices WHERE member_id=${member_id}";
$query = $this->read_replica->query($mysql);
$row = $query->row();
if (isset($row)) {
$message = $row->msg;
}
//echo $message;
$device_count = 0;
$q = "SELECT * FROM members_devices WHERE member_id=${member_id}";
$r = $this->read_replica->query($q);
foreach ($r->result() as $row) {
$data["devices"][] = $row->player_id;
$device_count++;
}
// $data["devices"] = ['a','b','c'];
$arrayData = array("NEXTSCREEN" => "bar");
if ($device_count > 0 && $message != '') {
$this->load->model('onesignal_model');
// print_r($data["devices"]);
$out = $this->onesignal_model->sendmemberMessage($member_id, $data["devices"], $message, $arrayData);
// print_r($out);
}
}
}
protected function renderNotificationPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('notifications/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function update() {
$result = $this->notification->updateDescription([
'id' => $this->input->post('id'),
'description' => $this->input->post('description'),
]);
echo json_encode([
'message' => $result ? "Updated" : "Failed",
'code' => $result ? 1 : 0
]);
}
public function update_trigger() {
// echo "updateTriggerItem Ameye";
// url: "/notifications/updateTriggerItem?category_settings=" + category_settings + "&e_trigger=" + e_trigger
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
$message_card = "";
if ($this->input->get()) {
$category_settings = $this->input->get('category_settings');
$e_trigger = $this->input->get('e_trigger');
$card_settings = $this->input->get('card_settings');
$override_text = $this->input->get('override_text');
$expiration = $this->input->get('expiration');
$mysql = "SELECT e.*,m.id AS card_id FROM email_trigger e LEFT JOIN main_cards m ON m.dynamic_key = e.dynamic_key WHERE e.e_trigger='$e_trigger'";
$query = $this->read_replica->query($mysql);
$mr = $query->row_array();
$data["e_trigger"] = $mr["e_trigger"];
$data["category"] = $mr["category"];
$dynamic_key = $mr["dynamic_key"];
$card_id = $mr["card_id"];
if ($e_trigger != '' && $category_settings != '' && $card_settings != '') {
$mysql = "UPDATE email_trigger SET category='$category_settings',override_text=$override_text,expiration='$expiration' WHERE e_trigger='$e_trigger'";
$query = $this->db->query($mysql);
$mysql = "SELECT * FROM main_cards WHERE dynamic_key='$dynamic_key' ";
$query = $this->read_replica->query($mysql);
if ($query->num_rows() == 0) {
$message_card = "Okay not in use";
$mysql = "UPDATE main_cards SET dynamic_key='$dynamic_key' WHERE id = $card_settings AND dynamic_key IS NULL";
$this->db->query($mysql);
} else {
$message_card = "This is in use";
}
$message = "Updated <br>" . $message_card;
echo $message;
}
}
}
public function editTrigger() {
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
if ($this->input->get()) {
$trigger_id = $this->input->get('trigger_id');
/*
id | e_trigger | category | action_detail | template_name | status | added | updated | dynamic_key | message | send_mail | send_notification
----+-----------+------------+------------------------------------------+---------------+--------+----------------------------+----------------------------+-------------+-------------------------------+-----------+-------------------
2 | ETRG0002 | GOACTIVITY | <p>Good Job, you&#39;re saving money</p>+| etrg0002.html | 1 | 2020-02-18 15:06:46.721542 | 2020-02-18 15:06:46.721542 | ETRG0002KEY | Good Job, you're saving money | 0 | 1
| | | | | | | | | | |
(1 row)
*/
if ($trigger_id != '') {
$mysql = "SELECT e.*,m.id AS card_id FROM email_trigger e LEFT JOIN main_cards m ON m.dynamic_key = e.dynamic_key WHERE e.e_trigger='$trigger_id'";
$query = $this->read_replica->query($mysql);
$mr = $query->row_array();
// print_r($mr);
$data["e_trigger"] = $mr["e_trigger"];
$data["category"] = $mr["category"];
$data["dynamic_key"] = $mr["dynamic_key"];
$data["card_id"] = $mr["card_id"];
$data["override_text"] = $mr["override_text"];
$data["expiration"] = $mr["expiration"];
// $this->memberPointsItems($member_id, $data);
$data["category_settings"] = $this->combo_model->getCardCategoryCombo("category_settings", $data["category"], '', 'CARDDYNAMIC');
// $data['member_id'] = $member_id;
$data['card_settings'] = $this->combo_model->getTriggerCardsCombo("card_settings", $data["card_id"]);
$data["override_text_combo"] = $this->combo_model->getYesNoCombo("override_text", $data["override_text"]);
$data["expiration_combo"] = $this->combo_model->getTriggerExpirationCombo("expiration", $data["expiration"]);
$this->load->view('notifications/extra/notifications_extra', $data);
}
}
}
}
+149
View File
@@ -0,0 +1,149 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Parsed_Receipts extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->library('table');
$this->load->model('parsed_item_payment_model');
$this->load->model('combo_model');
}
public function index() {
$data['page_title'] = 'Parsed Receipts';
$this->table->set_template($this->template);
$this->table->set_heading([
'User ID',
'User Email',
'Merchant Name',
'Receipt(Travel) Date',
'Receipt Parsed Date',
'Amount',
'Currency',
'Transport Provider ID',
'Tracked Email ID',
'Category'
]);
$params = $this->getValueOfParsedReceipts();
$data['card_transport_provider'] =
$this
->combo_model
->getTransportProvidersCombo(
'card_transport_provider',
$params['transport_provider_id']
);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForParsedReceipts($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this
->parsed_item_payment_model
->get_parsed_item_payment_record($params)[0]['all_count'],
$params,
'index'
)
);
$records = $this->parsed_item_payment_model->get_parsed_item_payment_record(
$params, SELF::NONE_COUNT_RECORD, $data['limit'], $data['offset']
);
$data['parsed_item_payment_table'] = $this->table->generate($records);
$this->renderParsedReceiptsPage('view_parsed_item_payment', $data);
}
public function getValueOfParsedReceipts() {
return [
'from_date' => trim($this->input->get('from_date')),
'to_date' => trim($this->input->get('to_date')),
'transport_provider_id' => trim($this->input->get('card_transport_provider'))
? trim($this->input->get('card_transport_provider'))
: trim($this->input->get('transport_provider_id')),
'category' => trim($this->input->get('category')),
'email' => trim($this->input->get('email')),
];
}
public function validateValueForParsedReceipts($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForParsedReceipts();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForParsedReceipts() {
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('from_date', 'from_date', $date_pattern);
$this->form_validation->set_rules('to_date', 'to_date', $date_pattern);
$this->form_validation->set_rules('transport_provider_id', 'transport_provider_id', 'integer');
}
public function load_pagination($total_record, $params, $action) {
// pagination
$this->load->library('pagination');
$config["total_rows"] = $total_record;
$config["base_url"] = base_url() . '/' . get_class($this) . '/' . $action;
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config["suffix"] = '?'
. http_build_query($params);
$config["first_url"] = '/' . get_class($this) . "/{$action}/0?"
. http_build_query($params);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
protected function renderParsedReceiptsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('parsed_receipts/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
@@ -0,0 +1,205 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Phone_farm_phones extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 20;
public $statusOptions = [
'Inactive' => 0,
'Active' => 1,
'Ping Failure' => 2,
'GPS Telnet Failure' => 3,
'Other Failure' => 4,
];
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('phone_farm_phone_model', 'phone_farm_phone');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('url'));
//get query string filter
$filterData = $this->input->get();
$queryString = $this->input->server('QUERY_STRING');
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->phone_farm_phone->getPhones($filterData);
$this->viewData['list'] = $data['list'];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['totalItems'], $data['page'], $pagingUrl);
$this->renderAdminPage('phone_farm_phones/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['phone'] = null;
$this->renderAdminPage('phone_farm_phones/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['phone'] = null;
$this->viewData['statusOptions'] = $this->statusOptions;
$this->setPhoneCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('phone_farm_phones/create', $this->viewData);
return;
}
$inputData = $this->getFormData();
$res = $this->phone_farm_phone->createPhone($inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success.');
redirect('/phone_farm_phones');
} else {
$this->session->set_flashdata('error', isSet($res['message']) ? $res['message'] : 'Create fail.');
$this->renderAdminPage('phone_farm_phones/create', $this->viewData);
return;
}
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$res= $this->phone_farm_phone->getPhoneById($id);
$this->viewData['phone'] = isSet($res['data']) ? $res['data'] : [];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['phoneId'] = $id;
$this->renderAdminPage('phone_farm_phones/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['phone'] = null;
$this->viewData['phoneId'] = $id;
$this->setPhoneCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('phone_farm_phones/edit', $this->viewData);
return;
}
$inputData = $this->getFormData();
$inputData['id'] = (int) $id;
$res = $this->phone_farm_phone->updatePhoneById($id, $inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success');
redirect('/phone_farm_phones');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->renderAdminPage('phone_farm_phones/edit', $this->viewData);
return;
}
}
public function remove($param)
{
$res = $this->phone_farm_phone->removePhoneById($param);
if (!$res['success'] != 'success') {
$this->viewData['errMsg'] = isSet($res['message']) ? $res['message'] : 'Something went wrong. Please try again later.';
$this->renderAdminPage('phone_farm_phones', $this->viewData);
return;
}
redirect('/phone_farm_phones');
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormData() {
return [
'phone_name' => $this->input->post('phone_name'),
'phone_model' => $this->input->post('phone_model'),
'phone_vendor' => $this->input->post('phone_vendor'),
'phone_serial' => $this->input->post('phone_serial'),
'ip_address' => $this->input->post('ip_address'),
'gps_emulator_port' => $this->input->post('gps_emulator_port'),
'phone_number' => $this->input->post('phone_number'),
'status' => (int) $this->input->post('status'),
];
}
private function setPhoneCreationRules()
{
$config = [
[
'field' => 'phone_name',
'label' => 'Name',
'rules' => 'required|max_length[12]',
'errors' => array(
'max_length' => 'Max length is 20.'
),
],
[
'field' => 'phone_model',
'label' => 'Model',
'rules' => 'required|max_length[40]',
'errors' => array(
'max_length' => 'Max length is 40.'
)
],
[
'field' => 'phone_vendor',
'label' => 'Vendor',
'rules' => 'required|max_length[40]',
'errors' => array(
'max_length' => 'Max length is 40.'
)
],
[
'field' => 'phone_serial',
'label' => 'Serial',
'rules' => 'required|max_length[20]',
'errors' => array(
'max_length' => 'Max length is 20.',
)
],
[
'field' => 'phone_number',
'label' => 'Phone number',
'rules' => 'required|max_length[20]',
'errors' => array(
'max_length' => 'Max length is 20.'
)
]
];
$this->form_validation->set_rules($config);
}
}
+463
View File
@@ -0,0 +1,463 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Points extends Admin_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('point_model');
$this->load->model('combo_model');
}
public function index() {
$data = array();
$this->load->helper('url');
$this->reportpoints();
}
protected function renderPointsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('points/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function getValueOfPointReport() {
return [
'member_id' => trim($this->input->get('member_id') ?? ''),
'description' => trim($this->input->get('description') ?? ''),
'id' => trim($this->input->get('id') ?? ''),
'from_points' => trim($this->input->get('from_points') ?? ''),
'to_points' => trim($this->input->get('to_points') ?? ''),
'from_date' => trim($this->input->get('from_date') ?? ''),
'to_date' => trim($this->input->get('to_date') ?? ''),
'status' => trim($this->input->get('card_status')
?? ($this->input->get('status') ?? -1)),
];
}
public function setOnePastMonth(&$params, $default_date = 'on') {
if (strcmp($default_date, 'on') === 0) {
$params['from_date'] = date("Y-m-d", strtotime("-1 months"));
$params['to_date'] = date("Y-m-d");
}
}
public function setComboForPointReport($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboFromZeroToNine(
'card_status',
$params['status']
);
return $combo;
}
public function getValueCombo($val) {
$status_value = range(0, 9);
return in_array($val, $status_value)
? $val
: '';
}
public function validateValueForPointReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForPointReportForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForPointReportForm() {
$status_pattern = 'regex_match[/^(?:[0-9])$/]';
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('member_id', 'Member ID', 'numeric');
$this->form_validation->set_rules('id', 'ID', 'numeric');
$this->form_validation->set_rules('from_points', 'From Points', 'numeric');
$this->form_validation->set_rules('to_points', 'To Points', 'numeric');
$this->form_validation->set_rules('from_date', 'From Added', $date_pattern);
$this->form_validation->set_rules('to_date', 'To Added', $date_pattern);
$this->form_validation->set_rules('status', 'Status', $status_pattern);
}
public function load_pagination($all_record, $params, $action) {
$action_hidden = $this->input->get('action_hidden');
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . "/points/" . $action;
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config["suffix"] =
"?action_hidden=${action_hidden}&"
. http_build_query($params);
$config["first_url"] =
"/points/{$action}/0?action_hidden=${action_hidden}&"
. http_build_query($params);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function reportpoints() {
$this->load->model('report_point_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'FirstName',
'Lastname',
'ID',
'Description',
'Points',
'Added',
'Status',
]);
$params = $this->getValueOfPointReport();
$default_date = $this->input->get('default_date');
if ($this->input->get('action_hidden')) {
$this->setOnePastMonth($params, $default_date);
} else {
$this->setOnePastMonth($params);
}
$data = $this->setComboForPointReport($params);
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForPointReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->report_point_model->get_report_point_records($params),
$params,
'index'
)
);
$data['points_report'] = $this->table->generate(
$this->report_point_model->get_report_point_records(
$params,
$data['limit'],
$data['offset']
)
);
if ($this->input->get('action_hidden')) {
$data['default_date'] = $default_date;
} else {
$data['default_date'] = 'on';
}
$data["page_title"] = "Points Redemption";
$this->renderPointsPage("view_pointsreport", $data);
}
public function getValueOfAssignsReport() {
return [
'search_text' => trim($this->input->get('search_text') ?? ''),
'find_select_value' =>
trim( ! empty($this->input->get('find_select'))
? $this->input->get('find_select')
: $this->input->get('find_select_value')),
'from_points' => trim($this->input->get('from_points') ?? ''),
'to_points' => trim($this->input->get('to_points') ?? ''),
];
}
public function setComboForAssignsReport($params) {
$this->load->model('combo_model');
$combo['find_select'] = $this->combo_model->getfindMemberType(
'find_select',
$params['find_select_value']
);
$combo['descsion_group'] = $this->combo_model->getDescisionGroupCombo(
'descsion_group',
trim($this->input->post('decision_group') ?? '')
);
return $combo;
}
public function validateValueForAssignsReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForAssignsReport();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForAssignsReport() {
$this->form_validation->set_rules(
'find_select_value',
'Select Value',
'in_list[email,firstname,lastname]'
);
$this->form_validation->set_rules(
'from_points',
'Points',
'numeric'
);
$this->form_validation->set_rules(
'to_points',
'Points',
'numeric'
);
}
public function assignpoints() {
$this->load->model('assigns_point_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID',
'Username',
'FirstName',
'LastName',
'Points',
'Act',
]);
$params = $this->getValueOfAssignsReport();
$data = $this->setComboForAssignsReport($params);
$errors = $this->validateValueForAssignsReport($params);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$params = array_diff_key($params, $errors);
if (isset($params['search_text'])) {
// set ['email' => 'test@gmail.com']
$params[$params['find_select_value']] = $params['search_text'];
}
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->assigns_point_model->get_assigns_point_records($params),
$params,
'assignpoints'
)
);
$data['points_report'] = $this->table->generate(
$this->assigns_point_model->get_assigns_point_records(
$params,
$data['limit'],
$data['offset']
)
);
$data["page_title"] = "Allocate Point";
$this->renderPointsPage("view_assignpoints", $data);
}
public function viewAssignDetail() {
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
if ($this->input->get()) {
$member_id = $this->input->get('member_id');
if ($member_id != '' && $member_id > 0) {
$this->memberPointsItems($member_id, $data);
$data["points_settings"] = $this->combo_model->getPointsSettingsCombo("points_settings", $points_settings_value);
$data['member_id'] = $member_id;
$mysql = "SELECT * FROM members WHERE id = " . $member_id;
$query = $this->read_replica->query($mysql);
$mr = $query->row_array();
// print_r($mr);
$data["firstname"] = $mr["firstname"];
$data["lastname"] = $mr["lastname"];
$data["email"] = $mr["email"];
$this->load->view('points/extra/point_extra', $data);
}
/*
/*
$mysql = "SELECT a.*,a.id AS member_id, b.format AS picture_format ";
$mysql .= " FROM members a LEFT JOIN card_images b ON (b.id=a.profile_picture) WHERE a.id = $member_id";
$query = $this->db->query($mysql);
$data = $query->row_array();
$data["devices"] = [];
$data['storage'] = $savvyext->cfgReadChar('system.storage_url');
$data['start_date'] = $this->input->get('start_date');
$data['end_date'] = $this->input->get('end_date');
$data['status'] = !is_null($this->input->get('card_status')) ? $this->input->get('card_status') : 1;
$data['card_status'] = $this->combo_model->getStatusCombo(
'card_status', $data['status']
);
$q = "SELECT * FROM members_devices WHERE member_id=${member_id}";
$q .= $this->query_condition_member_detail($data);
$r = $this->db->query($q);
foreach ($r->result() as $row) {
$data["devices"][] = $row->player_id;
}
$this->load->view('points/extra/point_extra', $data);
} else {
echo "Not found - illegal call";
}
*/
}
}
private function memberPointsItems($member_id, &$data) {
$this->load->library('table');
$this->table->set_template($this->template);
$data['points_recieved'] = '';
$mysql = "SELECT s.point_key,s.name,p.points,p.added::date "
. " FROM members_points p "
. " LEFT JOIN points_settings s ON s.point_key=p.point_key "
. " WHERE p.member_id = " . $member_id . " ORDER BY p.added DESC";
$query = $this->read_replica->query($mysql);
$data["points_recieved"] = $this->table->generate($query);
return $data;
}
public function SendMemberPoints() {
// echo "ameye aaaa olusesan bbbb";
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
if ($this->input->get()) {
$member_id = $this->input->get('member_id');
$point_key = $this->input->get('point_key');
if ($member_id != '' && $member_id > 0) {
$in = array();
$in["action"] = SAVVY_BKO_ASSIGN_POINTS;
$in['member_id'] = $member_id; // for session testing - not used
$in['point_key'] = $point_key;
$out = array();
$ret = $this->savvy_api($in, $out);
// print_r($out);
$message = $out["status_message"];
// if ($ret == PHP_API_OK) {
// $message = $out["status_message"];
// } else {
// $message = $out["status_message"];
// }
echo $message;
}
}
// $this->load->view('points/extra/point_extra', $data);
}
/**
* Systemic Points Summary Report
*
* @return view
*/
public function systemicPointsSummary() {
$data_report = $this->point_model->getSystemicPointsSummary();
$data = [
'page_title' => 'Systemic Points Summary',
'data_report' => $data_report,
'country_filter' => $this->combo_model->getCountriesHasAccount('country_filter', ''),
'point_key' => $this->combo_model->getPointKeyUsed('point_key', ''),
'point_value' => $this->combo_model->getPointValueUsed('point_value', ''),
];
$this->renderPointsPage('view_systemic_points_summary', $data);
}
public function getSystemicPointsDatatables() {
$data = $this->point_model->getSystemicPointsDatatables($this->input->post(), 'search');
header('Content-Type: application/json');
echo json_encode($data);
}
public function systemicPointsReportCSV()
{
$this->load->library('session');
$postData = $this->session->userdata("SPR_PARAM");
if ($postData) {
$this->point_model->getSystemicPointsDatatables($postData, 'export_csv');
} else {
echo 'Please try again!';
die();
}
}
}
@@ -0,0 +1,63 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Quote_Estimates extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('quote_estimate_model', 'quoteEstimate');
$this->viewData['selectedTab'] = 'quote_estimate';
$this->load->helper('pagination');
}
public function index()
{
$this->viewData['pagination'] = initPagination($this->pagePerItem, 95, 1, '/quote_estimates');
$this->viewData['list'] = $this->quoteEstimate->getQuoteEstimates();
$this->renderAdminPage('quote_estimates/list', $this->viewData);
}
public function create()
{
$this->template->load('quote_estimates/create', $this->viewData);
}
public function createQuoteEstimate()
{
redirect('/quote_estimates');
}
public function edit()
{
redirect('/quote_estimates');
}
public function search()
{
$this->viewData['pagination'] = initPagination($this->pagePerItem, 50, 1, '/quotes_estimates');
$this->viewData['list'] = $this->address->getAddresses();
$this->template->load('quote_estimates/list', $this->viewData);
}
public function quoteEstimateDetail($param)
{
$this->template->load('quote_estimates/edit', $this->viewData);
}
public function remove($param)
{
redirect('/addresses');
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Quotes extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('quote_model');
$this->viewData['selectedTab'] = 'quote';
$this->load->helper('pagination');
}
public function index()
{
$this->viewData['pagination'] = initPagination($this->pagePerItem, 95, 1, '/quotes');
$this->viewData['list'] = $this->quote_model->getQuotes();
$this->renderAdminPage('quotes/list', $this->viewData);
}
public function create()
{
$this->template->load('quotes/create', $this->viewData);
}
public function createQuote()
{
redirect('/quotes');
}
public function edit()
{
redirect('/edit');
}
// public function search() {
// $this->viewData['pagination'] = initPagination($this->pagePerItem, 50, 1, '/address');
// $this->viewData['list'] = $this->address->getAddresses();
// $this->template->load('addresses/list', $this->viewData);
// }
public function quoteDetail($param)
{
$this->template->load('quotes/edit', $this->viewData);
}
public function remove($param)
{
redirect('/quotes');
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+432
View File
@@ -0,0 +1,432 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
use Phpml\Regression\LeastSquares;
class Report extends Admin_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('report_model');
}
public function chart()
{
ini_set('memory_limit', '256M');
$params = $this->input->get();
$data = [];
$errors = [];
$chartData1 = [];
$chartData2 = [];
$data['transport_providers_dropdown'] = [
['id' => 1, 'name' => 'Uber', 'color' => 'rgb(45, 230, 92)'],
['id' => 2, 'name' => 'Lyft', 'color' => 'rgb(255, 0, 255)'],
['id' => 3, 'name' => 'Grab' , 'color' => 'rgb(54, 162, 235)'],
['id' => 4, 'name' => 'ComfortDelGro', 'color' => 'rgb(0, 255, 255)'],
['id' => 5, 'name' => 'GOJEK', 'color' => 'rgb(255, 191, 0)'],
];
if (!empty($params)) {
// get data for period of time 1
$period1_input = [
'start_date' => $params['start_date_1'] ?? '',
'end_date' => $params['end_date_1'] ?? '',
'transport_providers' => $params['transport_providers'] ?? '',
];
// get data for period of time 2
$period2_input = [
'start_date' => $params['start_date_2'] ?? '',
'end_date' => $params['end_date_2'] ?? '',
'transport_providers' => $params['transport_providers'] ?? '',
];
// chart1 and chart2 are same data (just different how to plot chart) => load first to have good performance
$loadDataFromDatabase1 = $response = $this->report_model->getPriceComparisonTrend($period1_input); // for period of time 1
$loadDataFromDatabase2 = $response = $this->report_model->getPriceComparisonTrend($period2_input); // for period of time 2
$chartDataResponse1 = $this->getChartData1($loadDataFromDatabase1, $loadDataFromDatabase2, $data['transport_providers_dropdown']);
$chartDataResponse2 = $this->getChartData2($loadDataFromDatabase1, $loadDataFromDatabase2, $data['transport_providers_dropdown']);
if (!$chartDataResponse1['success'] || !$chartDataResponse2['success']) {
if (!empty($chartDataResponse1['message'])) {
$errors[] = $chartDataResponse1['message'];
}
if (!empty($chartDataResponse2['message'])) {
$errors[] = $chartDataResponse2['message'];
}
} else {
$chartData1 = $chartDataResponse1['data'];
$chartData2 = $chartDataResponse2['data'];
}
}
$data['chartData1'] = json_encode($chartData1);
$data['chartData2'] = json_encode($chartData2);
$data['filterData'] = $params;
$data['errors'] = $errors;
$this->renderAdminPage('report/view_price_comparison_trend', $data);
}
public function getChartData2(array $loadDataFromDatabase1, array $loadDataFromDatabase2, array $transport_providers_map)
{
$errors = [];
$datasets = [];
$general_index_date_map = [];
$datasets_1 = $this->generateChartDataset(
$loadDataFromDatabase1,
$transport_providers_map,
$general_index_date_map,
'Period1'
);
$datasets_2 = $this->generateChartDataset(
$loadDataFromDatabase2,
$transport_providers_map,
$general_index_date_map,
'Period2'
);
if (!$datasets_1['success'] || !$datasets_2['success']) {
if (!empty($datasets_1['message'])) {
$errors[] = $datasets_1['message'];
}
if (!empty($datasets_2['message'])) {
$errors[] = $datasets_2['message'];
}
} else {
$datasets = array_merge($datasets_1['data'], $datasets_2['data']);
}
if (!empty($errors)) {
return [
'success' => false,
'message' => $errors[0]
];
}
$chartData = [
'datasets' => $datasets,
'general_index_date_map' => $general_index_date_map ?? [],
];
return [
'success' => true,
'data' => $chartData
];
}
public function getChartData1(array $loadDataFromDatabase1, array $loadDataFromDatabase2, array $transport_providers_map)
{
$errors = [];
$datasets = [];
$index_date_map_1 = [];
$index_date_map_2 = [];
$datasets_1 = $this->generateChartDataset(
$loadDataFromDatabase1,
$transport_providers_map,
$index_date_map_1,
'Period1',
true
);
$datasets_2 = $this->generateChartDataset(
$loadDataFromDatabase2,
$transport_providers_map,
$index_date_map_2,
'Period2',
true
);
if (!$datasets_1['success'] || !$datasets_2['success']) {
if (!empty($datasets_1['message'])) {
$errors[] = $datasets_1['message'];
}
if (!empty($datasets_2['message'])) {
$errors[] = $datasets_2['message'];
}
} else {
$datasets = array_merge($datasets_1['data'], $datasets_2['data']);
}
if (!empty($errors)) {
return [
'success' => false,
'message' => $errors[0]
];
}
$chartData = [
'datasets' => $datasets,
'index_date_map_1' => $index_date_map_1 ?? [],
'index_date_map_2' => $index_date_map_2 ?? [],
];
return [
'success' => true,
'data' => $chartData
];
}
protected function generateChartDataset(
array $loadDataFromDatabase,
array $transport_providers_map,
array &$index_date_map,
string $period_name,
bool $is_mutiple_x_axis = false) : array
{
if (!$loadDataFromDatabase['success']) {
return [
'success' => false,
'message' => $loadDataFromDatabase['message']
];
}
$datasets = [];
$dataset = [];
$i = count($index_date_map);
foreach ($loadDataFromDatabase['data'] as $key => $item) {
if (!array_key_exists($item['travel_date'], $index_date_map))
{
$index_date_map[$item['travel_date']] = $i;
$i++;
}
$dataset[$item['transport_provider_id']][] = [
'x' => $index_date_map[$item['travel_date']],
'count' => (int) $item['count'],
'y' => $item['cost']
];
}
foreach ($dataset as $transport_provider_id => $chart_data ) {
$found_key = array_search($transport_provider_id, array_column($transport_providers_map, 'id'));
if ($found_key === FALSE) {
continue;
}
$label = $transport_providers_map[$found_key]['name'];
$color = $transport_providers_map[$found_key]['color'];
// add scatter (data point)
$dataset_item = [
'type' => 'scatter',
'showLine' => false,
'label' => $label . " (${period_name})",
// only get [x, y] points to plot chart
'data' => array_map(function($el) {
return ['x' => $el['x'], 'y' => $el['y']];
}, $chart_data),
'backgroundColor' => $color
];
// add trend line based on scatter
$trendLineData = $this->calculateTrendLine($chart_data);
$trend_line_dataset = [
'type' => 'line',
'showLine'=> true,
'fill' => false,
'pointRadius' => 0,
'cubicInterpolationMode' => 'monotone',
'label' => $label . " - Trend line (${period_name})",
'data' => $trendLineData,
'backgroundColor' => $color,
'borderColor'=> $color,
];
if ($is_mutiple_x_axis) {
$dataset_item['xAxisID'] = 'x-' . $period_name;
$trend_line_dataset['xAxisID'] = 'x-' . $period_name;
}
$datasets[] = $dataset_item;
$datasets[] = $trend_line_dataset;
}
return [
'success' => true,
'data' => $datasets
];
}
protected function calculateTrendLine(array $data)
{
// e.g.
// $samples = [[73676, 1996], [77006, 1998], [10565, 2000], [146088, 1995]];
// $targets = [2000, 2750, 15500, 960];
$samples = array_map(function($el) {
return [$el['x'], $el['count']];
}, $data);
$targets = array_map(function($el) {
return $el['y'];
}, $data);
$regression = new LeastSquares();
$regression->train($samples, $targets);
$coefficients = $regression->getCoefficients();
$intercept = $regression->getIntercept();
$result = [];
foreach ($samples as $el) {
$y = $intercept + $el[0] * $coefficients[0] + 1 * $coefficients[1];
$result[] = ['x' => $el[0], 'y' => $y];
}
return $result;
}
public function surgePricingVaraition()
{
global $savvyext;
$this->load->helper('surge_pricing_varaition');
$regression1 = new LeastSquares();
$t = 3;
$date1 = "2020-01-01";
$date2 = "2020-05-10";
$area1 = 14;
$area2 = 11;
$areas = [
10 => 'Central - Tanglin',
11 => 'Central - Newton',
17 => 'Far East - Changi',
14 => 'Central East - Eunos'
];
$t = isset($_GET['t'])?((int)$_GET['t']):$t;
$date1 = isset($_GET['date1'])?date("Y-m-d",strtotime($_GET['date1'])):$date1;
$date2 = isset($_GET['date2'])?date("Y-m-d",strtotime($_GET['date2'])):$date2;
$area1 = isset($_GET['area1'])?((int)$_GET['area1']):$area1;
$area2 = isset($_GET['area2'])?((int)$_GET['area2']):$area2;
if (3 > $t || $t > 5) $t = 3;
if (!array_key_exists($area1,$areas)) $area1 = 14;
if (!array_key_exists($area2,$areas)) $area2 = 11;
$providers = [3 => "Grab", 5 => "Gojek", 4 => "ComfortDelGro"];
$c = '#ff5555';
list($data1,$label1,$poly1) = $this->report_model->area_to_area($area1, $area2, $date1, $date2, $t, $c);
$res1 = $this->surgePricingTrendLine($regression1, $data1);
$pub1 = $res1[0];
$c = '#5555ff';
list($data2,$label2,$poly2) = $this->report_model->area_to_area($area2, $area1, $date1, $date2, $t, $c);
$res2 = $this->surgePricingTrendLine($regression1, $data2);
$pub2 = $res2[0];
$data = array_merge($data1, $data2);
$data = [
't' => $t,
'date1' => $date1,
'date2' => $date2,
'area1' => $area1,
'area2' => $area2,
'areas' => $areas,
'providers' => $providers,
'data' => $data,
'data1' => $data1,
'data2' => $data2,
'label1' => $label1,
'label2' => $label2,
'poly1' => $poly1,
'poly2' => $poly2,
'res1' => $res1,
'res2' => $res2,
'pub1' => $pub1,
'pub2' => $pub2,
'google_api_key' => $savvyext->cfgReadChar( 'google.api_key' )
];
$this->renderAdminPage('report/view_surge_pricing_varaition', $data);
}
/***
* Email & Bank Connection Log
*/
public function emailAndBankConnectionReport()
{
$this->load->model('combo_model');
$data_report = $this->report_model->getEmailAndBankConnectionReportSummary();
$data = [
'page_title' => 'Email & Bank Connection Report',
'data_report' => $data_report,
'country_filter' => $this->combo_model->getCountriesHasAccount('country_filter', ''),
];
$this->renderAdminPage('report/view_email_and_bank_connection_report', $data);
}
public function emailAndBankConnectionReportDatatables()
{
$data = $this->report_model->getEmailBankConnectionReportDatatables($this->input->post(), 'search');
header('Content-Type: application/json');
echo json_encode($data);
}
public function emailAndBankConnectionReportCSV()
{
$this->load->library('session');
$postData = $this->session->userdata("EBCRR_PARAM");
if ($postData) {
$this->report_model->getEmailBankConnectionReportDatatables($postData, 'export_csv');
} else {
echo 'Please try again!';
die();
}
}
public function getBankAccountDetailJson()
{
$member_id = $this->input->get('member_id');
$data = $this->report_model->getBankAccountDetail($member_id);
header('Content-Type: application/json');
echo json_encode($data);
}
public function surgePricingTrendLine($regression1, $data)
{
$i = 0;
$pub1 = array();
$xs1 = [];
$ys1 = [];
$ys2 = [];
foreach ($data as $f) {
$t = $f['time'];
$pub1[$t] = array($t,$f['cost']);
$xs1[] = [$t];
$ys1[] = $f['cost'];
$i++;
}
if ($i>0) {
$regression1->train($xs1,$ys1);
}
foreach ($pub1 as $key=>$f) {
$y = $regression1->predict( [$f[0]] );
$f[2] = $y;
$pub1[$key] = $f;
}
return [$pub1,$xs1,$ys2];
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+212
View File
@@ -0,0 +1,212 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Scanners extends Admin_Controller {
var $template = array(
'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-indigo\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public function index() {
$this->load->helper('url');
$data = array();
/*
$this->load->model('admindash_model');
$out = $this->admindash_model->getAdminDashData($data);
$data['recent_signup'] = $out['recent_signup'];
$this->load->model('service_model');
$outx = $this->service_model->getServiceRequestList(100);
$data['transport_request'] = $outx['service_request_list'];
$this->load->library('googlemaps');
$config['center'] = 'atalnta,GA,USA';
$config['zoom'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = '4201 defoors farm trail, powder springs, GA 30127, USA';
$config['directionsEnd'] = '2324 stancrest ln, lawrenceville, 30044, GA, USA';
$config['directionsDivID'] = 'directionsDiv';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
*/
$this->load->library('table');
$this->table->set_template($this->template);
$mysql = "SELECT '<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"viewMember('||id||');\" >View</button>' AS action ,subject FROM trackedemail_item ";
$member_id = 0;
if ($this->input->get()) {
$member_id = (int)$this->input->get('member_id');
if ($member_id>0) {
$mysql.= " WHERE member_id='".$member_id."'";
}
}
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'ACTION', 'style' => 'width:90px'), 'Subject');
$data['member_table'] = $this->table->generate($query);
$data['members'] = array();
$q = "SELECT id,firstname||' '||lastname||' &lt;'||email||'&gt; ' AS option FROM members ORDER BY firstname,lastname";
$r = $this->read_replica->query($q);
foreach ($r->result() as $row) {
$data['members'][$row->id] = $row->option;
}
$data['member_id'] = $member_id;
//$data['js'] = array('https://maps.googleapis.com/maps/api/js?key=AIzaSyDvjiRTxngOQyBP4zpqFlZuiquc0ROvo9c&callback=initMap');
$this->renderScannedPage('view_scannemail', $data);
// echo 'Ameye Olu';
}
public function viewscanned() {
$data = array();
if ($this->input->get()) {
$member_id = $this->input->get('member_id');
if ($member_id != '' && $member_id > 0) {
$mysql = "SELECT * FROM trackedemail_item WHERE id = $member_id";
$query = $this->read_replica->query($mysql);
$data['selected_user'] = $query->row_array();
// print_r($data);
$this->load->view('scanned/extra/scanned_activity', $data);
}
}
/*
$this->load->model('admindash_model');
$out = $this->admindash_model->getAdminDashData($data);
$data['recent_signup'] = $out['recent_signup'];
$this->load->model('service_model');
$outx = $this->service_model->getServiceRequestList(100);
$data['transport_request'] = $outx['service_request_list'];
$this->load->library('googlemaps');
$config['center'] = 'atalnta,GA,USA';
$config['zoom'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = '4201 defoors farm trail, powder springs, GA 30127, USA';
$config['directionsEnd'] = '2324 stancrest ln, lawrenceville, 30044, GA, USA';
$config['directionsDivID'] = 'directionsDiv';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
*/
}
public function processbody() {
$data = array();
if ($this->input->get()) {
$msg_id = $this->input->get('id');
if ($msg_id != '' && $msg_id > 0) {
$mysql = "SELECT * FROM trackedemail_item WHERE id = $msg_id";
$query = $this->read_replica->query($mysql);
$data['message'] = $query->row_array();
$this->load->library('messageparser');
// print_r($data);
error_log('msg_id='.$msg_id);
$data['parsed'] = $this->messageparser->parse($msg_id, $this->db);
$data['id'] = $msg_id;
//$this->cacheParsedItem($data);
$this->load->view('scanned/extra/processed_body', $data);
}
}
}
private function cacheParsedItem($src) {
return NULL; //this code is obsolete and there is a new one in the API
if ($src['parsed']['location_start_value']=='N/A' && $src['parsed']['location_end_value']=='N/A' && $src['parsed']['cost_value']=='N/A') return;
sscanf($src['parsed']['duration_value'], "%d:%d:%d", $hours, $minutes, $seconds);
$data = array(
'travel_date' => date('Y-m-d H:i', strtotime($src['parsed']['date_value'])),
'location_start' => pg_escape_string(trim($src['parsed']['location_start_value'])),
'location_end' => pg_escape_string(trim($src['parsed']['location_end_value'])),
'distance' => filter_var($src['parsed']['distance_value'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION),
'duration' => 60*$hours+$minutes,
'cost_raw' => pg_escape_string(trim(filter_var($src['parsed']['cost_value'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_BACKTICK))),
'trackedemail_item_id' => $src['id'],
'cost' => filter_var($src['parsed']['cost_value'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION)
);
// New location code:
$location_start_id = $this->getAddress($data['location_start']);
$location_end_id = $this->getAddress($data['location_end']);
$data['location_start_id'] = $location_start_id;
$data['location_end_id'] = $location_end_id;
unset($data['location_start']);
unset($data['location_end']);
$q = "SELECT * FROM parsedemail_item WHERE trackedemail_item_id='".$data['trackedemail_item_id']."'";
$r = $this->read_replica->query($q);
$f = $r->row_array();
if ($f==NULL) {
$ql = "updated"; $qv = "NOW()";
foreach($data as $key=>$val) {
$ql.= ",${key}";
$qv.= ",'${val}'";
}
$q = "INSERT INTO parsedemail_item (${ql}) VALUES(${qv})";
} else {
unset($data['trackedemail_item_id']);
$q = "UPDATE parsedemail_item SET updated=NOW()";
foreach ($data as $key=>$val) {
$q.= ",${key}='${val}'";
}
$q.= " WHERE id='".$f['id']."'";
}
//echo $q;
//var_dump($src['parsed']);
//echo "<pre>";var_dump($data); echo "</pre>";
$this->db->query($q);
//*/
}
protected function getAddress($address) {
$q = "SELECT id FROM address WHERE lower(address)=lower('".pg_escape_string($address)."')";
$r = $this->read_replica->query($q);
$f = $r->row_array();
if ($f!=NULL && is_array($f) && $f["id"]>0) {
return $f["id"];
}
$q = "INSERT INTO address (address) VALUES ('".pg_escape_string($address)."') RETURNING id";
$r = $this->db->query($q);
$f = $r->row_array();
if ($f!=NULL && is_array($f) && $f["id"]>0) {
return $f["id"];
}
return NULL;
}
protected function renderScannedPage($page_name, $data) {
$this->load->view('admin/view_admin_header',$data);
$this->load->view('scanned/'.$page_name,$data);
$this->load->view('admin/view_admin_footer',$data);
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Screen_Cards extends Admin_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('screen_cards_model');
$this->load->helper('url');
$this->load->model('combo_model');
}
public function list()
{
$params = $this->input->get();
$data = [
'card_models' => []
];
$this->load->library('table');
$this->table->set_heading(
[
['data' => 'ID', 'style' => 'width:120px'],
'Screen Name',
'Trigger ID',
['data' => 'Status', 'style' => 'width:120px'],
['data' => '...', 'style' => 'width:200px'],
]
);
$query = $this->screen_cards_model->getQueryAll();
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'/Screen_Cards/list/',
[
'per_page' => 20,
'reuse_query_string' => TRUE,
'uri_segment' => 3,
]
);
$data['filterData'] = $params;
$data['screen_cards_table'] = $tableData['output_table'];
$data['links'] = $tableData['links'];
$data['screen_name_ddl'] = $this->combo_model->getScreenNames('screen_name', '');
$data['trigger_id_ddl'] = $this->combo_model->getTriggerIds('trigger_id', '');
$this->renderView('view_list', $data);
}
public function ajax_toggle()
{
$id = $this->input->post('id');
$cur_status = $this->input->post('cur_status');
$rs = $this->screen_cards_model->toggle($id, $cur_status);
header('Content-Type: application/json');
echo json_encode($rs);
}
private function renderView($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view('screencards/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function create_or_update()
{
$data = $this->input->post();
$rs = $this->screen_cards_model->create_or_update($data);
if($rs){
$this->session->set_flashdata('msg', empty($data['id']) ? 'Added' : 'Updated');
}else{
$this->session->set_flashdata('error', 'Screen Name & Trigger ID already exist, please try again!');
}
redirect('/Screen_Cards/list', 'refresh');
}
public function get_by_id()
{
$id = $this->input->get('id');
$data = $this->screen_cards_model->getById($id);
header('Content-Type: application/json');
echo json_encode($data);
}
//post delete
public function delete()
{
$id = $this->input->post('id');
if (!empty($id)) {
$rs = $this->screen_cards_model->delete($id);
} else {
$rs = false;
}
header('Content-Type: application/json');
echo json_encode($rs);
}
// ajax validate is exists screen name - trigger id
public function is_exists(){
$id = $this->input->post('id'); // 0 if create new
$screen_name = $this->input->post('screen_name');
$trigger_id = $this->input->post('trigger_id');
$is_exists = $this->screen_cards_model->is_exists($id, $screen_name, $trigger_id);
header('Content-Type: application/json');
echo json_encode($is_exists);
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
class Security extends Admin_Controller {
const COUNT_SQL = "SELECT COUNT(*) as total FROM block_ip;
INSERT INTO block_ip (ip, reason) VALUES ('176.117.172.40','something 20 chars');
";
public function index() {
return $this->blockedIpData();
}
protected function renderSecurityPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('points/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function blockedIpData() {
$this->load->model('block_ip_model');
$data = array();
$data["page_title"] = "Security";
$params = [];
$params = $this->input->get();
$this->load->library('table');
$this->table->set_heading(
array( 'data' => 'ID','style' => 'width:50px'),
'IP Address',
'Reason',
'Blocked',
array( 'data' => 'ACT', 'style' => 'width:40px; text-align: center;')
);
$query = $this->block_ip_model->getBlockIpQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'/security/blockedIpData',
[
'per_page' => 20,
'reuse_query_string' => TRUE,
]
);
$data['filterData'] = $params;
$data['links'] = $tableData['links'];
$data['blocked_ip_table'] = $tableData['output_table'];
$this->renderAdminPage("view_blocked_ip", $data);
}
public function blockMember() {
if ($this->input->post()) {
$memberId = $this->input->post('member_id');
$sql = "UPDATE members SET login_failures=5, status=0 WHERE id=".$memberId;
$this->db->query( $sql );
$result = json_encode(["status"=>"ok"]);
echo $result;
}
}
public function unblockMember() {
if ($this->input->post()) {
$memberId = $this->input->post('member_id');
$sql = "UPDATE members SET login_failures=0, status=1 WHERE id=".$memberId;
$this->db->query( $sql );
$result = json_encode(["status"=>"ok"]);
echo $result;
}
}
public function blockIp() {
if ($this->input->post()) {
$ipAddress = $this->input->post('ip_address');
$reason = $this->input->post('reason');
$sql = "INSERT INTO block_ip (ip, reason) VALUES ('{$ipAddress}','{$reason}')";
$this->db->query( $sql );
$result = json_encode(["status"=>"ok"]);
echo $result;
}
}
public function unblockIp() {
if ($this->input->post()) {
$ipAddress = $this->input->post('ip_address');
if(stripos($ipAddress, "*")) {
$ipAddress = str_replace("*", "%", $ipAddress);
$sql = "DELETE FROM block_ip WHERE ip::text LIKE '{$ipAddress}'";
} else {
$sql = "DELETE FROM block_ip WHERE ip = '{$ipAddress}'::inet";
}
$this->db->query( $sql );
$result = json_encode(["status"=>"ok"]);
echo $result;
}
}
}
+666
View File
@@ -0,0 +1,666 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Subscription extends Admin_Controller {
var $template = array(
'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-indigo\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public function index() {
$this->load->helper('url');
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
$data['backoffice_users'] = "";
$mysql = "SELECT c.country, '<button type=\"button\" onclick=\"viewSubscription('||s.id||');\" class=\"btn\"> >> </button>' AS View FROM subscriptions s LEFT JOIN country c ON c.code =s.country ORDER by s.id ASC";
$query = $this->read_replica->query($mysql);
$this->table->set_heading('Country', array('data' => 'View', 'style' => 'width:50px'));
$data['subscription_country'] = $this->table->generate($query);
$this->renderSubscriptionPage('view_subscription', $data);
// echo 'Ameye Olu';
}
public function viewsubscription() {
$subscription_id = $this->input->get('subscription_id');
if ($subscription_id > 0) {
$this->load->library('table');
$this->table->set_template($this->template);
$mysql = "SELECT '<h4><b>Title:</b> :'||title||'</h4><p><b>Description :</b>'||description||'<p></p><b>Price :</b>'|| price*0.01 AS Subscription FROM subscriptions_detail WHERE subscriptions =" . $subscription_id;
$query = $this->read_replica->query($mysql);
//$this->table->set_heading( 'Country', array('data' => 'View', 'style' => 'width:50px') );
$data['subscription_table'] = $this->table->generate($query);
$this->load->view('admin/common/subscription_detail', $data);
}
}
/*
SELECT mca.*,mc.card_points,mc.card_reciept,mc.title,UPPER(tp.name) AS transporter FROM members_card_assign mca LEFT JOIN main_cards mc ON mc.id =mca.card_id LEFT JOIN transport_providers tp ON tp.id::text =mc.card_reciept WHERE mca.id =2654162;
id | member_id | card_id | status | added | list_order | subscribe | how | card_points | card_reciept | title | transporter
---------+-----------+---------+--------+----------------------------+------------+----------------------------+-----+-------------+--------------+--------------------------------------------------+-------------
2654162 | 74 | 49 | 1 | 2019-11-10 15:13:11.904596 | 0 | 2019-11-11 07:45:15.314858 | | 0 | 3 | Earn points worth $5 on your next ride with Grab | GRAB
(1 row)
*/
public function procSubscription() {
echo "Get Subscription ID<br>Check Status<br>Insert The Points<br>Modify Status<br>Clean-up - email if needed";
$assign_id = $this->input->get('assign_id'); // this is like the assign ID
echo "<br> Assign ID = " . $assign_id . "<br>";
if ($assign_id > 0) {
$mysql = " SELECT tp.name AS card_reciept_name, mca.*,mc.card_points,mc.card_reciept,mc.title,UPPER(tp.name) AS transporter "
. " FROM members_card_assign mca "
. " LEFT JOIN main_cards mc ON mc.id =mca.card_id "
. " LEFT JOIN transport_providers tp ON tp.id::text =mc.card_reciept "
. " WHERE mca.id =" . $assign_id;
// echo $mysql;
$query = $this->read_replica->query($mysql);
if ($query->num_rows() == 1) {
$inx = $query->result_array();
// print_r($inx);
$member_id = $inx[0]['member_id'];
$card_points = $inx[0]['card_points']*50;
$card_reciept_name = $inx[0]['card_reciept_name'];
$out = array();
$inx['action'] = SAVVY_BKO_PROCESS_POINTS;
$inx["assign_id"] = $assign_id;
$ret = $this->savvy_api($inx, $out);
if ($ret == PHP_API_OK) {
// $message = $id > 0 ? 'Updated!' : 'Created!';
$this->pointsNotification($member_id, $assign_id, $card_points,$card_reciept_name );
echo "Points Allocated";
} else {
// $message = 'Failed to ' . ($id > 0 ? 'update' : 'create') . ' card: ' . isset($out["status"]) ? $out["status"] : '';
echo "Points allocation error";
}
}
} else {
echo "The selected sction not found";
}
return 0;
}
/*
* savvy=> SELECT mca.*,mc.card_points,mc.card_reciept,mc.title,UPPER(tp.name) AS transporter FROM members_card_assign mca LEFT JOIN main_cards mc ON mc.id =mca.card_id LEFT JOIN transport_providers tp ON tp.id::text =mc.card_reciept WHERE mca.id =2655337;
id | member_id | card_id | status | added | list_order | subscribe | how | completed | trigger_key | message | cat | reciept_count | updated | card_points | card_reciept | title | transporter
---------+-----------+---------+--------+----------------------------+------------+----------------------------+-----+-----------+-------------+---------+-----+---------------+----------------------------+-------------+--------------+-------------------------------+-------------
2655337 | 251 | 132 | 1 | 2020-04-10 07:47:50.809046 | 0 | 2020-04-10 07:49:00.380875 | | | | | | 0 | 2020-05-14 16:35:03.030581 | 0 | | Get $10 back on Anywheel Bike |
(1 row)
*/
private function pointsNotification($member_id, $assign_id, $points,$card_reciept_name ) {
$outX = array();
$x = [];
$x["mmode"] = "AUTO";
$x["trigger_key"] = "ETRG0019";
$x["action"] = FLOAT_SYSTEM_CREATE_NOTIFICATION;
$x["msg"] = "You've just earned $points float Points for ".$card_reciept_name ;
$x["pid"] = 0;
$x["member_id"] = $member_id;
$x["notice_type"] = "INSTANT";
$ret = $this->savvy_api($x, $outX);
// print_r($x);
return 0;
}
public function load_pagination($all_record, $params, $action, $limit = 10) {
$action_hidden = $this->input->get('action_hidden');
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . "/subscription/" . $action;
$config["per_page"] = $limit;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config["suffix"] = "?action_hidden=${action_hidden}&"
. http_build_query($params);
$config["first_url"] = "/subscription/{$action}/0?action_hidden=${action_hidden}&"
. http_build_query($params);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function getValueCombo($val) {
$status_value = range(0, 9);
return in_array($val, $status_value) ? $val : '';
}
public function setComboForSubscriptionReport($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboFromZeroToOne(
'card_status', $params['status']
);
$combo['card_ready'] = $this->combo_model->getYesNoComboWithAll(
'card_ready', $params['ready']
);
$combo['card_completed'] = $this->combo_model->getCompletedCombo(
'card_completed', $params['completed']
);
return $combo;
}
/**
* prepare search params
* @param array &$data
* @param array $params
*/
public function subscribed_deals_searching(&$data, &$params) {
// load combo model
$this->load->model('combo_model');
$data['points'] = $this->combo_model->getPointsSubscribedDeals( 'points', isset( $params['points'] ) ? $params['points'] : 0 );
unset( $params['points'] );
}
public function setFormRuleForSubscriptionReportForm() {
$status_pattern = 'regex_match[/^(?:[0-9])$/]';
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('reciept_count', 'Reciepts', 'numeric');
$this->form_validation->set_rules('from_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('to_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('status', 'Status', $status_pattern);
}
public function getValueOfSubscriptionReportForm() {
return [
'title' => trim($this->input->get('title') ?? ''),
'card_receipts' => trim($this->input->get('card_receipts') ?? ''),
'reciept_count' => trim($this->input->get('reciept_count') ?? ''),
'from_date' => trim($this->input->get('from_date') ?? ''),
'to_date' => trim($this->input->get('to_date') ?? ''),
'status' => 1,
'ready' => trim($this->input->get('card_ready') ?? ($this->input->get('ready') ?? -1)),
'completed' => trim($this->input->get('card_completed') ?? ($this->input->get('completed') ?? -1)),
'email' => trim($this->input->get('email')),
'id' => trim($this->input->get('id'))
];
}
public function validateValueForSubscriptionReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForSubscriptionReportForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setOnePastMonth(&$params, $default_date = 'on') {
if (strcmp($default_date, 'on') === 0) {
$params['from_date'] = date("Y-m-d", strtotime("-1 months"));
$params['to_date'] = date("Y-m-d");
}
}
public function subscriptionreport() {
$this->load->model('subscription_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID',
'FirstName',
'Lastname',
'Description',
'Date Subscribed',
'Status',
'Card Id',
'Card Reciept',
'Reciepts',
'Ready',
'Action',
'Dt. Completed'
]);
$params = $this->getValueOfSubscriptionReportForm();
$default_date = $this->input->get('default_date');
if ($this->input->get('action_hidden')) {
$this->setOnePastMonth($params, $default_date);
} else {
$this->setOnePastMonth($params);
}
$data = $this->setComboForSubscriptionReport($params);
$data["page_title"] = "Subscription Report";
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForSubscriptionReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data, $params, $this->load_pagination(
$this->subscription_model->get_subscription_report_records($params), $params, 'SubscriptionReport'
)
);
$data['subscription_table'] = $this->table->generate(
$this->subscription_model->get_subscription_report_records(
$params, $data['limit'], $data['offset']
)
);
if ($this->input->get('action_hidden')) {
$data['default_date'] = $default_date;
} else {
$data['default_date'] = 'on';
}
$this->renderSubscriptionPage('view_subscriptionreport', $data);
}
/**
* Show Subscribed Deals report
* @return mixed
*/
public function subscribed_deals() {
$this->load->model('summary_report_model');
// load table library
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'Card ID',
'Deal Name',
'Location',
'Deal Value (Card Points)',
'Total Subscribed in past 24 hours',
'Total Subscribed in past 7 days',
'Total Subscribed in past 14 days',
'Total Subscribed in past 30 days',
'Total Subscribed All Time',
'Deals Redeemed'
]);
$data = array();
$params = $this->input->get();
// total report
$data['page_title'] = 'Subscribed Deals Report';
$data['overall_summary'] = $this->summary_report_model->getSummaryReport( $params );
$data = array_merge(
$data,
$params,
$this->load_pagination(
$data['overall_summary'], $params, 'subscribed_deals', $limit = 20
)
);
// get subscribed summary report
$data['summary_report'] = $this->table->generate(
$this->summary_report_model->getSummaryReport( $params, $data['limit'], $data['offset'] )
);
// prepare filter combo
$this->subscribed_deals_searching( $data, $params );
$this->renderSubscriptionPage( 'view_subscribed_deals', $data );
}
public function validateValueForCarpoolReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForCarpoolReportForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForCarpoolReportForm() {
$status_pattern = 'regex_match[/^(?:[0-9])$/]';
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('card_id', 'Card ID', 'numeric');
$this->form_validation->set_rules('pool', 'Pool', 'numeric');
$this->form_validation->set_rules('from_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('to_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('status', 'Status', 'numeric');
}
public function getValueOfCarpoolReportForm() {
return [
'email' => trim($this->input->get('email') ?? ''),
'title' => trim($this->input->get('title') ?? ''),
'from_date' => trim($this->input->get('from_date') ?? ''),
'to_date' => trim($this->input->get('to_date') ?? ''),
'pool' => trim($this->input->get('pool') ?? ''),
'card_id' => trim($this->input->get('card_id') ?? ''),
'status' => trim($this->input->get('status') ?? '')
];
}
public function carpoolreport() {
$this->load->model('carpool_report_model');
$this->load->library('table');
$this->table->set_template($this->template);
$data["page_title"] = "Carpool Report";
$this->table->set_heading([
'CarPool ID',
'?column?',
'LastName',
'Email',
'Pool',
'Title',
'Card ID',
'Added',
'Updated',
'Status',
'Proc1'
]);
$params = $this->getValueOfCarpoolReportForm();
$default_date = $this->input->get('default_date');
if ($this->input->get('action_hidden')) {
$this->setOnePastMonth($params, $default_date);
} else {
$this->setOnePastMonth($params);
}
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForCarpoolReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data, $params, $this->load_pagination(
$this->carpool_report_model->get_carpool_records($params), $params, 'carpoolreport'
)
);
$data['carpool_table'] = $this->table->generate(
$this->carpool_report_model->get_carpool_records(
$params, $data['limit'], $data['offset']
)
);
if ($this->input->get('action_hidden')) {
$data['default_date'] = $default_date;
} else {
$data['default_date'] = 'on';
}
$this->renderSubscriptionPage('view_carpoolreport', $data);
}
public function setComboForCarPoolFriendReport($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboFromZeroToNine(
'card_status', $params['status']
);
return $combo;
}
public function setFormRuleForCarPoolFriendReportForm() {
$status_pattern = 'regex_match[/^(?:[0-9])$/]';
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('member_id', 'Member ID', 'numeric');
$this->form_validation->set_rules('carpool_id', 'Carpool ID', 'numeric');
$this->form_validation->set_rules('from_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('to_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('status', 'Status', 'numeric');
}
public function getValueOfCarPoolFriendReportForm() {
return [
'member_id' => trim($this->input->get('member_id') ?? ''),
'carpool_id' => trim($this->input->get('carpool_id') ?? ''),
'from_date' => trim($this->input->get('from_date') ?? ''),
'to_date' => trim($this->input->get('to_date') ?? ''),
'email' => trim($this->input->get('email') ?? ''),
'status' => trim($this->input->get('card_status') ?? ($this->input->get('status') ?? -1)),
];
}
public function validateValueForCarPoolFriendReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForCarPoolFriendReportForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function carpoolfriend() {
$this->load->model('carpool_friend_model');
$this->load->library('table');
$this->table->set_template($this->template);
$data["page_title"] = "Carpool Friend Report";
$this->table->set_heading([
'Proc Status',
'Member',
'Member ID',
'ID',
'Carpool ID',
'FirstName',
'LastName',
'Email',
'Status',
'Accept Status',
'Pool Status',
'Level A',
'Level B',
'Added',
'Last Message',
'Updated',
'Link'
]);
$params = $this->getValueOfCarpoolFriendReportForm();
$default_date = $this->input->get('default_date');
if ($this->input->get('action_hidden')) {
$this->setOnePastMonth($params, $default_date);
} else {
$this->setOnePastMonth($params);
}
$data = $this->setComboForCarpoolFriendReport($params);
$data["page_title"] = "Carpool Friend Report";
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForCarPoolFriendReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data, $params, $this->load_pagination(
$this->carpool_friend_model->get_carpool_friend_records($params), $params, 'carpoolfriend'
)
);
$data['carpool_friend_table'] = $this->table->generate(
$this->carpool_friend_model->get_carpool_friend_records(
$params, $data['limit'], $data['offset']
)
);
if ($this->input->get('action_hidden')) {
$data['default_date'] = $default_date;
} else {
$data['default_date'] = 'on';
}
$this->renderSubscriptionPage('view_carpoolfriend', $data);
}
public function setFormRuleForSurveyReportForm() {
$status_pattern = 'regex_match[/^(?:[0-9])$/]';
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('member_id', 'Member ID', 'numeric');
$this->form_validation->set_rules('from_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('to_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('status', 'Status', $status_pattern);
}
public function getValueOfSurveyReportForm() {
return [
'member_id' => trim($this->input->get('member_id') ?? ''),
'description' => trim($this->input->get('description') ?? ''),
'answer' => trim($this->input->get('answer') ?? ''),
'action' => trim($this->input->get('action') ?? ''),
'from_date' => trim($this->input->get('from_date') ?? ''),
'to_date' => trim($this->input->get('to_date') ?? ''),
'status' => trim($this->input->get('card_status') ?? ($this->input->get('status') ?? -1)),
'ready' => trim($this->input->get('card_ready') ?? ($this->input->get('ready') ?? -1)),
'completed' => trim($this->input->get('card_completed') ?? ($this->input->get('completed') ?? -1)),
];
}
public function validateValueForSurveyReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForSurveyReportForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function surveyreport() {
$this->load->model('survey_report_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID:MEMBER_ID',
'FirstName',
'Lastname',
'Description',
'Answer',
'Status',
'Date',
'Action',
]);
$params = $this->getValueOfSurveyReportForm();
$default_date = $this->input->get('default_date');
if ($this->input->get('action_hidden')) {
$this->setOnePastMonth($params, $default_date);
} else {
$this->setOnePastMonth($params);
}
$data = $this->setComboForSubscriptionReport($params);
$data["page_title"] = "Survey Report";
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForSurveyReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data, $params, $this->load_pagination(
$this->survey_report_model->get_survey_report_records($params), $params, 'surveyreport'
)
);
$data['subscription_table'] = $this->table->generate(
$this->survey_report_model->get_survey_report_records(
$params, $data['limit'], $data['offset']
)
);
if ($this->input->get('action_hidden')) {
$data['default_date'] = $default_date;
} else {
$data['default_date'] = 'on';
}
$this->renderSubscriptionPage('view_surveyreport', $data);
}
protected function renderSubscriptionPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('subscription/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Surveys extends Admin_Controller {
public function index() {
$this->load->helper('url');
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
}
public function onoardsurveys() {
$this->load->helper('url');
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
$data['backoffice_users'] = "";
$mysql = "SELECT id,group_key,answers_key,status,answers, ' <input type=\"text\" class=\"form-control\" value=\"'||answers||'\">' AS ans1,'<button type=\"button\" onclick=\"viewSubscription('||id||');\" class=\"btn btn-danger\"> Update </button>' AS View FROM onboarding_survey ";
$query = $this->read_replica->query($mysql);
// $this->table->set_heading('Country', array('data' => 'View', 'style' => 'width:50px'));
$data['onboard_survey'] = $this->table->generate($query);
//print_r( $data );
$this->renderSurveyPage('view_onboardsurvey', $data);
}
protected function renderSurveyPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('surveys/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
File diff suppressed because it is too large Load Diff
+236
View File
@@ -0,0 +1,236 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Tracking extends Admin_Controller {
var $template = array(
'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-indigo\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public function index() {
$this->load->helper('url');
$data = array();
/*
$this->load->model('admindash_model');
$out = $this->admindash_model->getAdminDashData($data);
$data['recent_signup'] = $out['recent_signup'];
$this->load->model('service_model');
$outx = $this->service_model->getServiceRequestList(100);
$data['transport_request'] = $outx['service_request_list'];
$this->load->library('googlemaps');
$config['center'] = 'atalnta,GA,USA';
$config['zoom'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = '4201 defoors farm trail, powder springs, GA 30127, USA';
$config['directionsEnd'] = '2324 stancrest ln, lawrenceville, 30044, GA, USA';
$config['directionsDivID'] = 'directionsDiv';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
*/
$this->load->library('table');
$this->table->set_template($this->template);
$mysql = "SELECT id,username,firstname,lastname,'<button type=\"button\" class=\"btn btn-info\">View</button>' As action FROM members";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'ID', 'style' => 'width:10px'), 'USERNAME', 'FIRSTNAME', 'LASTNAME', array('data' => 'ACTION', 'style' => 'width:90px'));
$data['member_table'] = $this->table->generate($query);
//$data['js'] = array('https://maps.googleapis.com/maps/api/js?key=AIzaSyDvjiRTxngOQyBP4zpqFlZuiquc0ROvo9c&callback=initMap');
$this->renderAdminPage('view_dash', $data);
// echo 'Ameye Olu';
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('admin/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function gpsdata() {
$data = array();
/*
$this->load->model('admindash_model');
$out = $this->admindash_model->getAdminDashData($data);
$data['recent_signup'] = $out['recent_signup'];
$this->load->model('service_model');
$outx = $this->service_model->getServiceRequestList(100);
$data['transport_request'] = $outx['service_request_list'];
$this->load->library('googlemaps');
$config['center'] = 'atalnta,GA,USA';
$config['zoom'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = '4201 defoors farm trail, powder springs, GA 30127, USA';
$config['directionsEnd'] = '2324 stancrest ln, lawrenceville, 30044, GA, USA';
$config['directionsDivID'] = 'directionsDiv';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
*/
ob_start();
$this->load->library('table');
$this->table->set_template($this->template);
$data['page_title'] = "Recent Tracking Data";
$mysql = "SELECT m.id,m.firstname,'<button type=\"button\" class=\"btn btn-info\">View</button>' As action FROM members m";
$query = $this->read_replica->query($mysql);
// $this->table->set_heading(array('data' => 'ID', 'style' => 'width:10px'), 'USERNAME','FIRSTNAME','LASTNAME', array('data' => 'ACTION', 'style' => 'width:90px'));
$res = array(array('First Name','Action','ID','Member ID','Tracked Group','Speed','Latitude','Longitude','Time','Location','Created'));
$gps = $this->load->database('gps', TRUE);
$dummy = new stdClass;
$dummy->id = "";
$dummy->member_id = "";
$dummy->traked_group = "";
$dummy->speed = "";
$dummy->lat = "";
$dummy->lng = "";
$dummy->ttime = "";
$dummy->loc = "";
$dummy->created = "";
foreach ($query->result() as $row) {
$q = "SELECT * FROM members_tracking WHERE member_id=".$row->id." ORDER BY id DESC LIMIT 1";
$r = $gps->query($q);
$d = $r->result();
if (is_array($d) && count($d)>0 && is_object($d[0])) {
list($f) = $d;
$res[] = array($row->firstname,$row->action,$f->id,$f->member_id,$f->traked_group,$f->speed,$f->lat,$f->lng,$f->ttime,$f->loc,$f->created);
}
}
$data['member_table'] = $this->table->generate($res);
ob_get_clean();
//$data['js'] = array('https://maps.googleapis.com/maps/api/js?key=AIzaSyDvjiRTxngOQyBP4zpqFlZuiquc0ROvo9c&callback=initMap');
$this->renderAdminPage('view_gpstrack', $data);
}
public function crashlog() {
$this->load->model('crash_log_model');
$data = [];
$params = [];
$params = $this->input->get();
$query = $this->crash_log_model->getLogQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'/tracking/crashlog',
[
'per_page' => 20,
'reuse_query_string' => TRUE,
]
);
$data['filterData'] = $params;
$data['links'] = $tableData['links'];
$data['crashlog_table'] = $tableData['output_table'];
$this->renderAdminPage('view_crashlog', $data);
}
public function crashlogentry() {
$id = (int)$this->input->get('id');
if ($id>0) {
$q = "SELECT * FROM crash_log WHERE id=${id}";
$r = $this->read_replica->query($q);
$f = $r->result_array();
if (is_array($f) and count($f)>0) {
$data['entry'] = $f[0];
$data['entry']['data'] = Tracking::prettyPrint($data['entry']['data']);
$this->load->view('admin/view_crashlog_entry', $data);
} else {
echo "Record was not found";
return;
}
} else {
echo "Invalid ID";
return;
}
}
public static function prettyPrint( $json ) {
$result = '';
$level = 0;
$in_quotes = false;
$in_escape = false;
$ends_line_level = NULL;
$json_length = strlen( $json );
for( $i = 0; $i < $json_length; $i++ ) {
$char = $json[$i];
$new_line_level = NULL;
$post = "";
if( $ends_line_level !== NULL ) {
$new_line_level = $ends_line_level;
$ends_line_level = NULL;
}
if ( $in_escape ) {
$in_escape = false;
} else if( $char === '"' ) {
$in_quotes = !$in_quotes;
} else if( ! $in_quotes ) {
switch( $char ) {
case '}': case ']':
$level--;
$ends_line_level = NULL;
$new_line_level = $level;
break;
case '{': case '[':
$level++;
case ',':
$ends_line_level = $level;
break;
case ':':
$post = " ";
break;
case " ": case "\t": case "\n": case "\r":
$char = "";
$ends_line_level = $new_line_level;
$new_line_level = NULL;
break;
}
} else if ( $char === '\\' ) {
$in_escape = true;
}
if( $new_line_level !== NULL ) {
$result .= "\n".str_repeat( "\t", $new_line_level );
}
$result .= $char.$post;
}
return $result;
}
}
@@ -0,0 +1,265 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Transport_provider extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 20;
public $statusOptions = [
'Inactive' => '0',
'Active' => '1',
];
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('transport_provider_model', 'transport_provider');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('url'));
//get query string filter
$filterData = $this->input->get();
$queryString = $this->input->server('QUERY_STRING');
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->transport_provider->getTransportProvider($filterData);
$this->viewData['list'] = $data['list'];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['totalItems'], $data['page'], $pagingUrl);
$this->renderAdminPage('transport_providers/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['transport_provider'] = null;
$this->renderAdminPage('transport_providers/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['transport_provider'] = null;
$this->viewData['statusOptions'] = $this->statusOptions;
$this->setTransportProviderCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('transport_providers/create', $this->viewData);
return;
}
$inputData = $this->getFormData();
$res = $this->transport_provider->createTransportProvider($inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success.');
redirect('/transport_provider');
} else {
$this->session->set_flashdata('error', isSet($res['message']) ? $res['message'] : 'Create fail.');
$this->renderAdminPage('transport_providers/create', $this->viewData);
return;
}
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$res= $this->transport_provider->getTransportByID($id);
$this->viewData['transport_provider'] = isSet($res['data']) ? $res['data'] : [];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['id'] = $id;
$this->renderAdminPage('transport_providers/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['transport_provider'] = null;
$this->viewData['id'] = $id;
$this->setTransportProviderCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('transport_providers/edit', $this->viewData);
return;
}
$inputData = $this->getFormData();
$inputData['id'] = (int) $id;
$res = $this->transport_provider->updateTransportProviderById($id, $inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success');
redirect('/transport_provider');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->renderAdminPage('transport_provider/edit', $this->viewData);
return;
}
}
public function remove($param)
{
$res = $this->transport_provider->removeTransportProviderById($param);
if (!$res['success'] != 'success') {
$this->viewData['errMsg'] = isSet($res['message']) ? $res['message'] : 'Something went wrong. Please try again later.';
$this->renderAdminPage('transport_provider', $this->viewData);
return;
}
redirect('/transport_provider');
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormData() {
return [
'name' => $this->input->post('name'),
'client' => $this->input->post('client'),
'token' => $this->input->post('token'),
'code' => $this->input->post('code'),
'access_token' => $this->input->post('access_token'),
'timeout' => $this->input->post('timeout'),
'retries' => $this->input->post('retries'),
'active' => (int)$this->input->post('active'),
'custom' => $this->input->post('custom'),
];
}
private function setTransportProviderCreationRules()
{
$config = [
[
'field' => 'name',
'label' => 'Name',
'rules' => 'required|max_length[50]',
'errors' => array(
'max_length' => 'Max length is 50.'
),
],
[
'field' => 'client',
'label' => 'Client',
'rules' => 'required|max_length[100]',
'errors' => array(
'max_length' => 'Max length is 100.'
)
],
[
'field' => 'token',
'label' => 'Token',
'rules' => 'required|max_length[200]',
'errors' => array(
'max_length' => 'Max length is 200.'
)
],
[
'field' => 'code',
'label' => 'Code',
'rules' => 'required|max_length[100]',
'errors' => array(
'max_length' => 'Max length is 100.',
)
],
[
'field' => 'access_token',
'label' => 'Access Token',
'rules' => 'required|max_length[200]',
'errors' => array(
'max_length' => 'Max length is 200.'
)
],
[
'field' => 'timeout',
'label' => 'Timeout',
'rules' => 'required|numeric|callback_is_out_of_range_int2',
'errors' => array(
'is_out_of_range_int2' => 'Please input the value between ' . MIN_INT_2 . ' and ' . MAX_INT_2
)
],
[
'field' => 'retries',
'label' => 'Retries',
'rules' => 'required|numeric|callback_is_out_of_range_int4',
'errors' => array(
'is_out_of_range_int4' => 'Please input the value between ' . MIN_INT_4 . ' and ' . MAX_INT_4
)
],
[
'field' => 'active',
'label' => 'Active',
'rules' => 'required|numeric|callback_is_out_of_range_int4',
'errors' => array(
'is_out_of_range_int4' => 'Please input the value between ' . MIN_INT_4 . ' and ' . MAX_INT_4
)
],
[
'field' => 'custom',
'label' => 'Custom',
'rules' => 'required|callback_is_json',
'errors' => array(
'is_json' => 'Only input json.'
)
]
];
$this->form_validation->set_rules($config);
}
public function is_json($data) {
return (json_decode($data) != NULL) ? true : false;
}
public function is_out_of_range_int4($number) {
return is_numeric($number) && $number >= MIN_INT_4 && $number <= MAX_INT_4;
}
public function is_out_of_range_int2($number) {
return is_numeric($number) && $number >= MIN_INT_2 && $number <= MAX_INT_2;
}
public function searchTransportProvider() {
$filterData = $this->input->get();
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$res = $this->transport_provider->getTransportProviderByName($filterData);
echo json_encode($res);
}
}
@@ -0,0 +1,336 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Transport_provider_accounts extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 50;
public $statusOptions = [
'Inactive' => '0',
'Active' => '1',
];
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('transport_provider_account_model', 'transport_provider_account');
$this->load->model('transport_provider_model', 'transport_provider');
$this->load->helper('pagination');
}
public function index()
{
$this->load->model('combo_model');
$this->load->helper(array('url'));
//get query string filter
$filterData = $this->input->get();
$queryString = $this->input->server('QUERY_STRING');
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$filterData['perPage'] = $this->pagePerItem;
$data = $this->transport_provider_account->getTransportProviderAccount($filterData);
$data['list'] = array_map(function($item) {
$item['added'] = $this->formatDate($item['added']);
$item['used'] = $this->formatDate($item['used']);
$item['updated'] = $this->formatDate($item['updated']);
return $item;
}, $data['list']);
$this->viewData['list'] = $data['list'];
$this->viewData['statusSelection'] = $this->combo_model->getStatusComboWithAll(
'status',
$filterData['status'] ?? $this->statusOptions['Active']
);
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['totalItems'], $data['page'], $pagingUrl);
$this->renderAdminPage('transport_provider_accounts/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['transport_provider_account'] = null;
$this->renderAdminPage('transport_provider_accounts/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$inputData = $this->getFormData();
$this->viewData['transport_provider_account'] = $inputData;
$this->viewData['statusOptions'] = $this->statusOptions;
$this->setTransportProviderAccountCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('transport_provider_accounts/create', $this->viewData);
return;
}
$res = $this->transport_provider_account->createTransportProviderAccount($inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isset($res['message']) ? $res['message'] : 'Create success.');
redirect('/transport_provider_accounts');
} else {
$this->session->set_flashdata('error', isset($res['message']) ? $res['message'] : 'Create fail.');
$this->renderAdminPage('transport_provider_accounts/create', $this->viewData);
return;
}
}
private function formatDate($date) {
if (!empty($date)) {
return (new DateTime($date))->format('Y-m-d');
}
return '';
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$res = $this->transport_provider_account->getTransportProviderAccountByID($id);
if ($res['data']) {
$res['data']['added'] = $this->formatDate($res['data']['added']);
$res['data']['updated'] = $this->formatDate($res['data']['updated']);
$res['data']['used'] = $this->formatDate($res['data']['used']);
}
$this->viewData['transport_provider_account'] = isset($res['data']) ? $res['data'] : [];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['id'] = $id;
$this->renderAdminPage('transport_provider_accounts/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$inputData = $this->getFormData();
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['transport_provider_account'] = $inputData;
$this->viewData['id'] = $id;
$this->setTransportProviderAccountUpdateRules();
// $this->setTransportProviderAccountCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('transport_provider_accounts/edit', $this->viewData);
return;
}
$inputData = array_filter($inputData, function($value) {
return (isset($value) && trim(''.$value) !== '');
});
$res = $this->transport_provider_account->updateTransportProviderAccountById($id, $inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isset($res['message']) ? $res['message'] : 'Create success');
redirect('/transport_provider_accounts');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->renderAdminPage('transport_provider_accounts/edit', $this->viewData);
return;
}
}
public function remove($param)
{
$res = $this->transport_provider_account->removeTransportProviderAccountById($param);
if (!$res['success'] != 'success') {
$this->viewData['errMsg'] = isset($res['message']) ? $res['message'] : 'Something went wrong. Please try again later.';
$this->renderAdminPage('transport_provider_accounts', $this->viewData);
return;
}
redirect('/transport_provider_accounts');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormData()
{
return [
'transport_provider_id' => $this->input->post('transport_provider_id'),
'transport_provider_name' => $this->input->post('transport_provider_name'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'name' => $this->input->post('name'),
'added' => $this->input->post('added'),
'updated' => $this->input->post('updated'),
'active' => (boolean)$this->input->post('active'),
'parameters' => json_decode($this->input->post('parameters'), true),
'used' => $this->input->post('used'),
'pool' => (int)$this->input->post('pool'),
];
}
private function setTransportProviderAccountCreationRules()
{
$config = [
[
'field' => 'transport_provider_id',
'label' => 'Transport Provider ID',
'rules' => 'required',
'errors' => array(
'max_length' => 'Max length is 50.'
),
],
[
'field' => 'email',
'label' => 'Email',
'rules' => 'required|max_length[200]|callback_valid_email',
'errors' => array(
'max_length' => 'Max length is 200.',
'valid_email' => 'Email is invalid !!!'
)
],
[
'field' => 'phone',
'label' => 'Phone',
'rules' => 'required|max_length[20]', // TODO: regex
'errors' => array(
'max_length' => 'Max length is 200.'
)
],
[
'field' => 'name',
'label' => 'Name',
'rules' => 'required|max_length[50]',
'errors' => array(
'max_length' => 'Max length is 50.'
)
],
/* [
'field' => 'added',
'label' => 'Added',
'rules' => 'required', // TODO: timestamp
],
[
'field' => 'updated',
'label' => 'Updated', // TODO: timestamp
'rules' => 'required|max_length[200]',
'errors' => array(
'max_length' => 'Max length is 200.'
)
],*/
[
'field' => 'timeout',
'label' => 'Timeout',
'rules' => 'd', // TODO: timestamp
],
[
'field' => 'active',
'label' => 'Active',
'rules' => 'required', // TODO: boolean
],
/* [
'field' => 'used',
'label' => 'Used',
'rules' => 'required',
],
*/
[
'field' => 'pool',
'label' => 'Pool',
'rules' => 'required|callback_valid_pool',
],
[
'field' => 'parameters',
'label' => 'Parameters',
'rules' => 'required|callback_is_json',
'errors' => array(
'is_json' => 'Only input json.'
)
]
];
$this->form_validation->set_rules($config);
}
private function setTransportProviderAccountUpdateRules() {
$config = [
[
'field' => 'transport_provider_id',
'label' => 'Transport Provider ID',
'rules' => 'required',
'errors' => array(
'max_length' => 'Max length is 50.'
),
],
[
'field' => 'pool',
'label' => 'Pool',
'rules' => 'required|callback_valid_pool',
],
];
$this->form_validation->set_rules($config);
}
public function is_json($data)
{
return (json_decode($data) != NULL) ? true : false;
}
public function is_out_of_range_int4($number)
{
return is_numeric($number) && $number >= MIN_INT_4 && $number <= MAX_INT_4;
}
public function is_out_of_range_int2($number)
{
return is_numeric($number) && $number >= MIN_INT_2 && $number <= MAX_INT_2;
}
/**
* Valid Email
*
* @access public
* @param string
* @return bool
*/
public function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
public function valid_pool($number) {
return is_numeric($number) && $number > 0 && $number < 1000;
}
public function getTransportProviderByName() {
$name = $this->input->get()['q'];
$res = $this->transport_provider->getTransportProviderByName([ 'name' => $name ]);
echo json_encode($res);
}
}
+216
View File
@@ -0,0 +1,216 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
use Carbon\Carbon;
class Trips extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('parsedEmailItem_model', 'parsedEmailItem');
$this->viewData['selectedTab'] = 'trip';
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('form', 'url'));
//get query string filter
$page = $this->input->get('page', true);
$travelDate = $this->input->get('travel_date', true);
$duration = $this->input->get('duration', true);
$cost = $this->input->get('cost', true);
$transportProviderId = $this->input->get('transport_provider_id', true);
$distance = $this->input->get('distance', true);
$filterData = $this->input->get();
$queryString = $this->input->server('QUERY_STRING');
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->parsedEmailItem->getParsedEmailItemList($filterData);
$this->viewData['list'] = $data['list'];
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['itemTotal'], $data['page'], $pagingUrl);
//$this->template->load('trips/trips', $this->viewData);
$this->renderAdminPage('trips/trips', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['tripItem'] = null;
$this->template->load('trips/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['tripItem'] = null;
$this->setTripCreationRules();
if ($this->form_validation->run() == false) {
$this->template->load('trips/create', $this->viewData);
return;
}
$inputData = [
'travel_date' => Carbon::parse($this->input->post('travel_date'))->format('Y-m-d'),
'travel_date_end' => Carbon::parse($this->input->post('travel_date_end'))->format('Y-m-d'),
'cost' => $this->input->post('cost'),
'cost_raw' => $this->input->post('cost_raw'),
'duration' => $this->input->post('duration'),
'distance' => $this->input->post('distance'),
'transport_provider_id' => $this->input->post('transport_provider_id'),
'location_start_id' => $this->input->post('location_start_id'),
'location_end_id' => $this->input->post('location_end_id'),
'scheduled' => Carbon::now()->format('Y-m-d')
];
$res = $this->parsedEmailItem->createParsedEmailItem($inputData);
if ($res['success']) {
$this->session->set_flashdata('success', $res['message']);
redirect('/trips');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->template->load('trips/create', $this->viewData);
return;
}
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$tripItem = $this->parsedEmailItem->getParsedEmailItem($id);
$this->viewData['tripItem'] = $tripItem;
$this->viewData['tripId'] = $id;
$this->template->load('trips/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['tripItem'] = null;
$this->viewData['tripId'] = $id;
$this->setTripCreationRules();
if ($this->form_validation->run() == false) {
$this->template->load('trips/edit', $this->viewData);
return;
}
$inputData = [
'travel_date' => Carbon::parse($this->input->post('travel_date'))->format('Y-m-d'),
'travel_date_end' => Carbon::parse($this->input->post('travel_date_end'))->format('Y-m-d'),
'cost' => $this->input->post('cost'),
'cost_raw' => $this->input->post('cost_raw'),
'duration' => $this->input->post('duration'),
'distance' => $this->input->post('distance'),
'transport_provider_id' => $this->input->post('transport_provider_id'),
'location_start_id' => $this->input->post('location_start_id'),
'location_end_id' => $this->input->post('location_end_id')
];
$res = $this->parsedEmailItem->updateParsedEmailItem($id, $inputData);
if ($res['success']) {
$this->session->set_flashdata('success', $res['message']);
redirect('/trips');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->template->load('trips/edit', $this->viewData);
return;
}
}
public function delete($id)
{
$res = $this->parsedEmailItem->deleteParsedEmailItem($id);
if (!$res['success']) {
$this->session->set_flashdata('success', $res['message']);
} else {
$this->session->set_flashdata('error', $res['error']);
}
redirect('/trips');
}
private function setTripCreationRules()
{
$config = [
[
'field' => 'travel_date',
'label' => 'Travel date',
'rules' => 'required',
],
[
'field' => 'travel_date_end',
'label' => 'Travel date end',
'rules' => 'required',
],
[
'field' => 'location_start_id',
'label' => 'Location start',
'rules' => 'required',
],
[
'field' => 'location_end_id',
'label' => 'Location end',
'rules' => 'required',
],
[
'field' => 'duration',
'label' => 'Duration',
'rules' => 'required',
],
[
'field' => 'distance',
'label' => 'Distance',
'rules' => 'required',
],
[
'field' => 'cost_raw',
'label' => 'Cost raw',
'rules' => 'required',
],
[
'field' => 'cost',
'label' => 'Cost',
'rules' => 'required',
],
[
'field' => 'transport_provider_id',
'label' => 'Transport provider',
'rules' => 'required',
]
];
$this->form_validation->set_rules($config);
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+329
View File
@@ -0,0 +1,329 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Uploads extends Admin_Controller {
var $template = array(
'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-indigo\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public function index() {
$this->load->helper('url');
$data = array();
$this->renderUploadPage('view_dash', $data);
// echo 'Ameye Olu';
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('admin/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function getValueOfCardImages() {
return [
'category_id' => trim($this->input->get('card_category')),
'unique_id' => trim($this->input->get('unique_id')),
'from_date' => trim($this->input->get('from_date')),
'to_date' => trim($this->input->get('to_date')),
'catid' => trim($this->input->get('catid'))
];
}
public function setComboForCardImages($params) {
$this->load->model('combo_model');
$combo['card_category'] = $this->combo_model->getCardImageCategoryCombo(
'card_category',
$params['category_id']
);
$combo['catid'] = $this->combo_model->getCardImageCategoryCombo(
'catid',
$params['catid']
);
return $combo;
}
public function validateValueForCardImages($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForCardImages();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForCardImages() {
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules(
'card_category',
'Category Card',
'numberic'
);
$this->form_validation->set_rules(
'from_added',
'From Added',
$date_pattern
);
$this->form_validation->set_rules(
'to_added',
'To Added',
$date_pattern
);
}
public function load_pagination($all_record, $params, $action) {
$action_hidden = $this->input->get('action_hidden');
if ( isset( $params['category_id'] ) ) {
$category = $params['category_id'];
unset( $params['category_id'] );
$params['card_category'] = $category;
}
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . "/" . get_class($this) . "/" . $action;
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config["suffix"] =
"?action_hidden=${action_hidden}&"
. http_build_query($params);
$config["first_url"] =
"/uploads/{$action}/0?action_hidden=${action_hidden}&"
. http_build_query($params);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function cardimages() {
global $savvyext;
$this->load->model('card_image_model');
$data['storage'] = $savvyext->cfgReadChar('system.storage_url');
$data['message'] = "";
if ($this->input->post()) {
$data = $this->cardimagesPost($data);
}
$params = $this->getValueOfCardImages();
$data = array_merge($data, $this->setComboForCardImages($params));
$errors = $this->validateValueForCardImages($params);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->card_image_model->get_card_image_records($params),
$params,
'cardimages'
)
);
$data['images'] =
array_map(
function($ele) {
$ele['file_size'] = $this->human_filesize($ele['file_size']);
return $ele;
},
$this->card_image_model->get_card_image_records(
$params,
$data['limit'],
$data['offset']
)
);
// add filter after update card images
$filter = $this->add_filter_after_submit();
if ( ($_SERVER['REQUEST_METHOD'] === 'POST') ) {
redirect( sprintf( '/uploads/cardimages?%s', $filter ) );
}
$this->renderUploadPage( 'cardimages', $data);
}
private function add_filter_after_submit( $http_query = '' ) {
$history = filter_var( $_SERVER['HTTP_REFERER'], FILTER_SANITIZE_URL );
$history = parse_url( $history );
if ( isset( $history['query'] ) ) {
parse_str( $history['query'], $query );
$http_query = http_build_query( $query );
}
return $http_query;
}
private function human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
public function uploadInterface($data) {
return $this->cardimagesPost($data);
}
private function cardimagesPost($data) {
global $savvyext;
$bucket_name = '';
$catid = (int)$this->input->post('catid');
if ($catid<1) { $data['message'] = 'Please select category'; return $data; }
$q = "SELECT name FROM card_image_category WHERE id='${catid}'";
$r = $this->read_replica->query($q);
foreach ($r->result() as $row) {
$bucket_name = $row->name;
break;
}
if ($bucket_name=='') {
$data['message'] = 'Invalid category';
return $data;
}
// Process file
$imgData = $this->processFile('cardimg', array('jpg'=>1,'jpeg'=>1,'png'=>1,'gif'=>1));
if ($imgData==NULL || !is_array($imgData)) {
$data['message'] = 'Failed to process uploaded image! ('.$imgData.')';
return $data;
}
$this->load->library('googlestorage');
$this->googlestorage->Init(
$savvyext->cfgReadChar('google.storage_project_id'),
$savvyext->cfgReadChar('google.storage_auth_file')
);
$storage = $this->googlestorage;
// Get bucket
$buckets = $storage->ListBuckets();
if (array_key_exists($bucket_name, $buckets)) {
$bucket = $buckets[$bucket_name];
} else {
// Create bucket
$bucket = $storage->CreateBucket($bucket_name);
}
if ($bucket==NULL || !is_object($bucket)) {
$data['message'] = 'Cannot get or create bucket!';
return $data;
}
$total = count($imgData['name']);
// Loop through each file
for ($i = 0 ; $i < $total; $i++) {
$uniqueId = $storage->UniqueId();
$objectName = $uniqueId.".".$imgData['format'][$i];
$source = $imgData['tmp_name'][$i];
$object = $storage->UploadObject($bucket_name, $objectName, $source);
if ($object==NULL || !is_object($object)) {
$data['message'] = 'Failed to upload image!' . $imgData['name'][$i];
break;
} else {
$data['message'] = 'Image uploaded!';
// Save image data
$q = "INSERT INTO card_images (catid, uniqueid, name, file_size, format, dimensions) VALUES(";
$q.= "'${catid}','${uniqueId}','".$imgData['name'][$i]."','".$imgData['file_size'][$i]."','".$imgData['format'][$i]."','".$imgData['dimensions'][$i]."') RETURNING id";
//error_log($q);
$r = $this->db->query($q);
$f = $r->row_array();
$data["card_image_id"][$i] = $f["id"];
}
}
return $data;
}
private function processFile($var, $formats) {
if (!isset($_FILES[$var])) return 'The file was not uploaded!';
if (is_array($_FILES[$var]['error'])) {
foreach ($_FILES[$var]['error'] as $key => $error) {
if ($error != UPLOAD_ERR_OK) {
return $error;
}
}
} else if (isset($_FILES[$var]['error']) && $_FILES[$var]['error'] != UPLOAD_ERR_OK) {
return $_FILES[$var]['error'];
}
$error = $_FILES[$var]['error'];
$name = $_FILES[$var]['name'];
$file_size = $_FILES[$var]['size'];
$tmp_name = $_FILES[$var]['tmp_name'];
// Count # of uploaded files in array
$total = count($_FILES[$var]['name']);
$result_formats = [];
$result_dimensions = [];
// Loop through each file
for ( $i=0 ; $i < $total ; $i++ ) {
$format = strtolower(pathinfo($_FILES[$var]['name'][$i], PATHINFO_EXTENSION));
if (!isset($formats[$format]) || $formats[$format]!=1) {
return 'Invalid file format: '.$format;
}
list($width, $height, $type, $attr) = getimagesize($tmp_name[$i]);
$dimensions = $width . 'x' . $height;
array_push($result_formats, $format);
array_push($result_dimensions, $dimensions);
}
$result = array(
'tmp_name' => $tmp_name,
'name' => $name,
'file_size' => $file_size,
'format' => $result_formats,
'dimensions' => $result_dimensions
);
return $result;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends Bko_Controller {
public function index() {
$data['action_message'] = '';
$data['ip'] ='';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$data['ip'] = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$data['ip'] = $_SERVER['REMOTE_ADDR'];
}
if ($this->input->post()) {
$valid_entry = false;
$username = $password = $error_message = '';
$this->testLoginInput($username, $password, $error_message, $valid_entry);
// echo $valid_entry;
if ($valid_entry == true) {
$in['username'] = $username;
$in['password'] = $password;
$in['action'] = SAVVY_BKO_LOGIN;
$out = array();
$ret = $this->savvy_api($in, $out);
//var_dump($ret);
//var_dump($out);
if ($ret == PHP_API_OK) {
$this->buildUserSession($ret, $out);
redirect('dash');
} else {
$data['action_message'] = $this->formatedMesage('ERROR', 'Invalid Username/Password');
}
} else {
$data['action_message'] = $this->formatedMesage('ERROR', $error_message);
}
}
// echo rand(100,999);
$this->load->view('home/view_home', $data);
}
function formatedMesage($msgType, $theMessage) {
return "<div class=\"text-left\"><div class=\"alert alert-danger no-border\">" . $theMessage . "</div></div>";
}
}
+252
View File
@@ -0,0 +1,252 @@
{
"BD": "Bangladesh",
"BE": "Belgium",
"BF": "Burkina Faso",
"BG": "Bulgaria",
"BA": "Bosnia and Herzegovina",
"BB": "Barbados",
"WF": "Wallis and Futuna",
"BL": "Saint Barthelemy",
"BM": "Bermuda",
"BN": "Brunei",
"BO": "Bolivia",
"BH": "Bahrain",
"BI": "Burundi",
"BJ": "Benin",
"BT": "Bhutan",
"JM": "Jamaica",
"BV": "Bouvet Island",
"BW": "Botswana",
"WS": "Samoa",
"BQ": "Bonaire, Saint Eustatius and Saba ",
"BR": "Brazil",
"BS": "Bahamas",
"JE": "Jersey",
"BY": "Belarus",
"BZ": "Belize",
"RU": "Russia",
"RW": "Rwanda",
"RS": "Serbia",
"TL": "East Timor",
"RE": "Reunion",
"TM": "Turkmenistan",
"TJ": "Tajikistan",
"RO": "Romania",
"TK": "Tokelau",
"GW": "Guinea-Bissau",
"GU": "Guam",
"GT": "Guatemala",
"GS": "South Georgia and the South Sandwich Islands",
"GR": "Greece",
"GQ": "Equatorial Guinea",
"GP": "Guadeloupe",
"JP": "Japan",
"GY": "Guyana",
"GG": "Guernsey",
"GF": "French Guiana",
"GE": "Georgia",
"GD": "Grenada",
"GB": "United Kingdom",
"GA": "Gabon",
"SV": "El Salvador",
"GN": "Guinea",
"GM": "Gambia",
"GL": "Greenland",
"GI": "Gibraltar",
"GH": "Ghana",
"OM": "Oman",
"TN": "Tunisia",
"JO": "Jordan",
"HR": "Croatia",
"HT": "Haiti",
"HU": "Hungary",
"HK": "Hong Kong",
"HN": "Honduras",
"HM": "Heard Island and McDonald Islands",
"VE": "Venezuela",
"PR": "Puerto Rico",
"PS": "Palestinian Territory",
"PW": "Palau",
"PT": "Portugal",
"SJ": "Svalbard and Jan Mayen",
"PY": "Paraguay",
"IQ": "Iraq",
"PA": "Panama",
"PF": "French Polynesia",
"PG": "Papua New Guinea",
"PE": "Peru",
"PK": "Pakistan",
"PH": "Philippines",
"PN": "Pitcairn",
"PL": "Poland",
"PM": "Saint Pierre and Miquelon",
"ZM": "Zambia",
"EH": "Western Sahara",
"EE": "Estonia",
"EG": "Egypt",
"ZA": "South Africa",
"EC": "Ecuador",
"IT": "Italy",
"VN": "Vietnam",
"SB": "Solomon Islands",
"ET": "Ethiopia",
"SO": "Somalia",
"ZW": "Zimbabwe",
"SA": "Saudi Arabia",
"ES": "Spain",
"ER": "Eritrea",
"ME": "Montenegro",
"MD": "Moldova",
"MG": "Madagascar",
"MF": "Saint Martin",
"MA": "Morocco",
"MC": "Monaco",
"UZ": "Uzbekistan",
"MM": "Myanmar",
"ML": "Mali",
"MO": "Macao",
"MN": "Mongolia",
"MH": "Marshall Islands",
"MK": "Macedonia",
"MU": "Mauritius",
"MT": "Malta",
"MW": "Malawi",
"MV": "Maldives",
"MQ": "Martinique",
"MP": "Northern Mariana Islands",
"MS": "Montserrat",
"MR": "Mauritania",
"IM": "Isle of Man",
"UG": "Uganda",
"TZ": "Tanzania",
"MY": "Malaysia",
"MX": "Mexico",
"IL": "Israel",
"FR": "France",
"IO": "British Indian Ocean Territory",
"SH": "Saint Helena",
"FI": "Finland",
"FJ": "Fiji",
"FK": "Falkland Islands",
"FM": "Micronesia",
"FO": "Faroe Islands",
"NI": "Nicaragua",
"NL": "Netherlands",
"NO": "Norway",
"NA": "Namibia",
"VU": "Vanuatu",
"NC": "New Caledonia",
"NE": "Niger",
"NF": "Norfolk Island",
"NG": "Nigeria",
"NZ": "New Zealand",
"NP": "Nepal",
"NR": "Nauru",
"NU": "Niue",
"CK": "Cook Islands",
"XK": "Kosovo",
"CI": "Ivory Coast",
"CH": "Switzerland",
"CO": "Colombia",
"CN": "China",
"CM": "Cameroon",
"CL": "Chile",
"CC": "Cocos Islands",
"CA": "Canada",
"CG": "Republic of the Congo",
"CF": "Central African Republic",
"CD": "Democratic Republic of the Congo",
"CZ": "Czech Republic",
"CY": "Cyprus",
"CX": "Christmas Island",
"CR": "Costa Rica",
"CW": "Curacao",
"CV": "Cape Verde",
"CU": "Cuba",
"SZ": "Swaziland",
"SY": "Syria",
"SX": "Sint Maarten",
"KG": "Kyrgyzstan",
"KE": "Kenya",
"SS": "South Sudan",
"SR": "Suriname",
"KI": "Kiribati",
"KH": "Cambodia",
"KN": "Saint Kitts and Nevis",
"KM": "Comoros",
"ST": "Sao Tome and Principe",
"SK": "Slovakia",
"KR": "South Korea",
"SI": "Slovenia",
"KP": "North Korea",
"KW": "Kuwait",
"SN": "Senegal",
"SM": "San Marino",
"SL": "Sierra Leone",
"SC": "Seychelles",
"KZ": "Kazakhstan",
"KY": "Cayman Islands",
"SG": "Singapore",
"SE": "Sweden",
"SD": "Sudan",
"DO": "Dominican Republic",
"DM": "Dominica",
"DJ": "Djibouti",
"DK": "Denmark",
"VG": "British Virgin Islands",
"DE": "Germany",
"YE": "Yemen",
"DZ": "Algeria",
"US": "United States",
"UY": "Uruguay",
"YT": "Mayotte",
"UM": "United States Minor Outlying Islands",
"LB": "Lebanon",
"LC": "Saint Lucia",
"LA": "Laos",
"TV": "Tuvalu",
"TW": "Taiwan",
"TT": "Trinidad and Tobago",
"TR": "Turkey",
"LK": "Sri Lanka",
"LI": "Liechtenstein",
"LV": "Latvia",
"TO": "Tonga",
"LT": "Lithuania",
"LU": "Luxembourg",
"LR": "Liberia",
"LS": "Lesotho",
"TH": "Thailand",
"TF": "French Southern Territories",
"TG": "Togo",
"TD": "Chad",
"TC": "Turks and Caicos Islands",
"LY": "Libya",
"VA": "Vatican",
"VC": "Saint Vincent and the Grenadines",
"AE": "United Arab Emirates",
"AD": "Andorra",
"AG": "Antigua and Barbuda",
"AF": "Afghanistan",
"AI": "Anguilla",
"VI": "U.S. Virgin Islands",
"IS": "Iceland",
"IR": "Iran",
"AM": "Armenia",
"AL": "Albania",
"AO": "Angola",
"AQ": "Antarctica",
"AS": "American Samoa",
"AR": "Argentina",
"AU": "Australia",
"AT": "Austria",
"AW": "Aruba",
"IN": "India",
"AX": "Aland Islands",
"AZ": "Azerbaijan",
"IE": "Ireland",
"ID": "Indonesia",
"UA": "Ukraine",
"QA": "Qatar",
"MZ": "Mozambique"
}
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>