ElixirVault/www/system-brs-core/cms/cmsOrders/inc/cmsOrdersController.php

1373 lines
54 KiB
PHP

<?php
namespace BRSystems\Core\Cms\cmsOrders\inc;
use BRSystems\Core\App\pubBuy\inc\pubBuyController;
use BRSystems\Core\Library\cCore\cCore;
use BRSystems\Core\Library\cDefuseCrypto\cDefuseCrypto;
use BRSystems\Core\Library\cJSON\cJSON;
use BRSystems\Core\Library\cMail\cMail;
use BRSystems\Core\Library\cMessages\cMessages;
use BRSystems\Core\Library\cNumbers\cNumbers;
use BRSystems\Core\Library\cSession\cSession;
use BRSystems\Core\Library\cValidator\cValidator;
class cmsOrdersController extends cCore
{
public $dir;
public $name;
public $module;
public $sessionFiles;
const PRODUCT_MANAGER_MAP_ID = 571;
// Products operations for products to count db
const PRODUCT_OPERATION_ORDER_SEND = 1;
const PRODUCT_OPERATION_ORDER_DELETED = 2;
const PRODUCT_OPERATION_STORAGE_MODULE = 3;
const PRODUCT_OPERATION_BUYS_MODULE = 4;
const PRODUCT_AVAILABILITY_CHK = false; // CHECK PRODUCT AVAILABILITY SO THAT WE CAN'T HAVE PRODUCT COUNT NEGATIVE
const FILTER_ONLY_PENDING_STARTING_DATE = "filter-only-pending-starting-date";
public function __construct($uriData, $dir, $name)
{
$this->dir = $dir;
$this->name = $name;
parent:: __construct($uriData);
$this->module = new cmsOrdersModule();
$this->oView->setTemplateDir($this->dir . "/tmpl/");
if (!$this->oView->cacheUsed()) {
$this->oView->setJs(getCurrentFolder($this->dir) . '/js/' . $this->name . '.js');
$this->oView->setCss(getCurrentFolder($this->dir) . '/css/' . $this->name . '.css');
}
// Create session class for file download
$this->sessionFiles = new cSession("session-files");
// Set JS module init title
$this->oView->setAsJSON(cCore::JS_MOD, ucfirst($name));
}
public function run($initEditMode = false)
{
$this->oView->TABLE = true;
$pending = self::FILTER_ONLY_PENDING_STARTING_DATE;
$this->oView->setAsJSON('baseUrl', $this->gL(false, getV($pending) ? "$pending:" . getV($pending) : ''));
$this->oView->setAsJSON('initEdit', $initEditMode);
$this->oView->setAsJSON('gL', $this->getTranslations());
$this->oView->setAsJSON('vcfg', $this->getValCfg());
$this->oView->setAsJSON('productUrl', $this->gL(self::PRODUCT_MANAGER_MAP_ID));
$this->oView->display('prodCatalog', 'CMS_CUSTOM_TPL_DATA');
}
/**
* Function to create cms table & return for direct & ajax input
*
* @param int $page - page to display
* @param string $filter_json - (optional) filter json string
* @param bool $headers - flag whether to send header data or not
* @return array of data
* @author Mareks Keišs <keiss.mareks@gmail.com>
* @category cmsOrders Controller
* @version 1.1
*/
public function createCmsTable($page = 1, $filter_json = '', $headers = false): array
{
$pages = 0;
$filter = cJSON::decode($filter_json ?? '', true);
$filter = $filter ?: [];
// Set default filter value if none set
if (empty($filter) && getV('filter-only-pending-starting-date')) {
$filter = ['o_locked' => '2'];
}
$this->oView->MODULE_TITLE = $this->gM("Orders");
$this->oView->DEFAULT_SEARCH_VALUES = prepForDisplayHtml($filter);
$this->oView->LIST_HEADER = reOrderTableFields(
$this->getTableFields(),
$this->oUser->oCfg->getTableProperty($this->name),
);
$this->oView->LIST_DATA = $this->getModuleData($page, $filter, $pages);
$this->oView->LIST_ACTIONS = $this->getTableActions();
$data = [
'data' => $this->oView->genHelperView('cmsc/table/data-table'),
'pcount' => $pages,
'rlimit' => $this->cmsTableRecordsPerPage,
];
// Send data to client
if ($headers) {
$data['header'] = $this->oView->genHelperView('cmsc/table/data-table-search');
}
return $data;
}
/**
* Function to get module data
*
* @param int $page
* @param array $filter
* @param int $pages
* @return array of data
* @author Mareks Keišs <keiss.mareks@gmail.com>
* @category cmsOrders Controller
* @version 1.1
*/
const B_NEW_ORDER_START_DATE = '01-01-2019 00:01:00';
public function getModuleData($page = 1, $filter = [], &$pages)
{
$offset = (($page ?: 1) - 1) * $this->cmsTableRecordsPerPage;
$bChangesData = strtotime(self::B_NEW_ORDER_START_DATE);
$tFields = $this->getTableFields();
$sortBy = getP('sortBy');
$subWhere = "";
// Custom sub where where
if (isset($filter['o_locked']) && $filter['o_locked'] == '2') {
unset($filter['o_locked']);
$subWhere = " AND mo.o_locked = '0' AND mo.o_date > $bChangesData";
}
// Create where clause and sort by
$where = count($filter) ? $this->module->db->genSearchFieldQuery($filter, $tFields) : 'AND 1';
$sort = $sortBy ? $this->module->db->genOrderByQuery($sortBy, getP('sortWay'), $tFields) : "mo.id DESC";
// Get data
$data = $this->module->getModuleRecords($where . $subWhere, $sort, $offset, $this->cmsTableRecordsPerPage);
$rows = $this->module->db->getSelectedRecordsCount();
$pages = floor($rows / $this->cmsTableRecordsPerPage) + ($rows % $this->cmsTableRecordsPerPage ? 1 : 0);
$this->oView->ROWS = $rows;
if (empty($data)) {
return $data; // Return empty data
}
foreach ($data as $k => $v) {
if ($v['o_date'] <= strtotime("-30 days")) {
$data[$k]['no_delete'] = true;
}
if ((!$v['o_locked'] || !$v['o_edited']) && $v['o_date'] > $bChangesData) {
$data[$k]['sclass'] = 'bgred'; // Background color class red
}
$today = date('d-m-Y', $v['o_date']) == date('d-m-Y');
$format = $today ? $this->timeDateFormat : $this->CMSDateFormat;
$data[$k]['o_date'] = date($format, $v['o_date']);
$data[$k]['o_locked'] = ($v['o_locked'] ? '&#10003;' : '');
$data[$k]['o_edited'] = ($v['o_edited'] ? '&#10003;' : '');
if (!empty($v['o_edited'])) {
$data[$k]['fexcel'] = "<a href='" . "{$this->gL()}/action:export_excel/data:{$v['id']}" . "'>.xls</a>";
$data[$k]['fpdf'] = "<a href='" . "{$this->gL()}/action:export_pdf/data:{$v['id']}" . "'>.pdf</a>";
}
}
return $data;
}
/**
* Function to disable / enable enum records marked in table
*
* @param string $baseField - json string - base field to handle
* @param string $rows - passed user ids in cJSON string
* @return mixed of data
* @category cmsOrders Controller
* @author Mareks Keišs <keiss.mareks@gmail.com>
*/
public function changeEnumFields($baseField, $rows)
{
$rows = cJSON::decode($rows, true);
if ($baseField && $rows) {
$baseField = substr($baseField, 2);
$fields = $this->getTableFields();
$dbField = $fields[$baseField]['db_field'];
if (isset($dbField) && $this->module->changeRecordsStatus($this->module->db->prepData($rows), $dbField)) {
return true;
}
}
cJSON::senderror();
}
/**
* Function to delete records marked in table
*
* @param string $rows - passed user ids in cJSON string
* @return mixed of data
* @author Mareks Keišs <keiss.mareks@gmail.com>
* @category cmsOrders Controller
*/
public function delete($rows)
{
$rows = cJSON::decode($rows, true);
if ($rows && $this->module->deleteRecords($this->module->db->prepData($rows), $this->oUser->getUser())) {
return true;
}
cJSON::senderror();
}
/**
* Function to create sum amount in words by givenn number
*
* @param float $sum - sum value
* @return bool|array of data
* @author Mareks Keišs <keiss.mareks@gmail.com>
* @category cmsOrders Controller
*/
public function getSumInWords($sum)
{
if ($sum) {
// Get default pub language
$defLanguage = getDefaultAppLang();
// Setup message class
$this->oMessages = new cMessages(
$this->oApc,
false,
$this->uri_data['id'],
$defLanguage['id'],
);
$sm = cNumbers::num2words($this, $sum);
$tmp = mb_substr($sm, 0, 1, 'UTF-8');
$sm = mb_strtoupper($tmp, 'UTF-8') . mb_substr($sm, 1, null, 'UTF-8');
return ['w' => $sm];
}
return ['w' => ' '];
}
/**
* Function to get table record data for edit mode
*
* @param int $id - record id
* @param bool $bClone - clone entry
* @return bool|array of data
* @category cmsOrders Controller
* @author Mareks Keišs <keiss.mareks@gmail.com>
*/
public function editCmsTableRecord($id, $bClone = false)
{
// Get default pub language
$defLanguage = getDefaultAppLang();
// Setup message class to default language - latvian
$this->oMessages = new cMessages(
$this->oApc,
false,
$this->uri_data['id'],
$defLanguage['id'],
);
// Get/Create supplier info
$data = [
'edited' => true,
'data' => [
'a_supplier' => $this->gM("COMPANY_TITLE"),
'a_sup_reg_nr' => $this->gM("COMPANY_REG_NR"),
'a_sup_domicile' => $this->gM("COMPANY_LEGAL_ADDRESS"),
'a_sup_pvn_reg_nr' => $this->gM("COMPANY_PVN_REG_NR"),
'a_sup_sett_details' => $this->gM("COMPANY_SETTLEMENT_DETAILS"),
'a_sup_cont_nr' => $this->gM("COMPANY_CONT_NR"),
'a_sup_phone' => $this->gM("COMPANY_PHONE"),
'a_sup_email' => $this->gM("COMPANY_EMAIL@EMAIL.COM"),
'a_payment_met' => '',
'a_p_amount_words' => '',
'a_beneficiary' => '',
'a_ben_reg_nr' => '',
'a_ben_domicile' => '',
'a_ben_pvn_reg_nr' => '',
'a_ben_sett_details' => '',
'a_ben_cont_nr' => '',
'a_ben_phone' => '',
'a_ben_email' => '',
],
'table' => [],
];
$locked = false;
$firstEdit = false;
$sumTotal = 0;
if ($id) {
$locked = $this->module->chkIfFormIsLocked($id);
$d = $this->module->getRecordDataById2($id);
if (!empty($d)) {
$data['edited'] = true;
if (!$d['a_sup_reg_nr']) {
unset($d['a_sup_reg_nr']);
}
if (!$d['a_ben_reg_nr']) {
unset($d['a_ben_reg_nr']);
}
// Order date;
$d['order_date'] = date("d.m.Y", $d['o_date']);
$d['date'] = $d['order_date'];
// Term of payment
$d['term_of_payment'] = date("d.m.Y", $d['a_term_of_payment']);
$d['a_term_of_payment'] = $d['term_of_payment'];
$data['data'] = $d;
unset($data['data']['o_date']);
unset($data['data']['id'], $data['data']['a_modified']);
// Get all table(product) data;
$data['table'] = $this->module->getTableData2($id);
if (!!$data['table'] && is_array($data['table'])) {
foreach ($data['table'] as $v) {
$sumTotal += $v['p_price'];
}
}
} else {
$data['edited'] = false;
$d = $this->module->getRecordDataById($id);
if (!empty($d['o_input_data'])) {
$inputData = cJSON::decode($d['o_input_data'], true);
if (!empty($inputData) && is_array($inputData)) {
// Get & set shipping payment info
if (!empty($inputData['sh_and_py']['shipping_method'])) {
// Get classificators by id
$clTitles = $this->module->getClDataByClId(
[$inputData['sh_and_py']['shipping_method'], $inputData['sh_and_py']['payment_method']],
);
$shippingHtml = $this->gM($clTitles[$inputData['sh_and_py']['shipping_method']]['n']);
// Check if Omniva selected - add pickup place
if (
$inputData['sh_and_py']['shipping_method'] == pubBuyController::DELIVERY_OMNIVA
&& !empty($inputData['sh_and_py']['a_omniva'])
) {
// Load additional data
if (!$omniva_data = $this->oApc->check("OMNIVA_DATA")) {
$omniva_data = $this->module->getClDataByClTypeId(
pubBuyController::DELIVERY_OMNIVA_GR,
); // Omniva type
$this->oApc->store('OMNIVA_DATA', $omniva_data);
}
if (!empty($omniva_data[$inputData['sh_and_py']['a_omniva']])) {
$shippingHtml .= " - {$omniva_data[$inputData['sh_and_py']['a_omniva']]['n']}";
}
}
$data['data']['a_payment_met'] = $this->gM(
$clTitles[$inputData['sh_and_py']['payment_method']]['n'],
);
$data['data']['a_shipping_met'] = $shippingHtml;
}
$data['data']['p_delivery'] = '0.00';
$data['data']['o_nr'] = $d['o_nr'];
$data['data']['order_date'] = date("d.m.Y", $d['o_date']);
$data['data']['date'] = $data['data']['order_date'];
$data['data']['a_term_of_payment'] = date("d.m.Y", strtotime("+7 days", $d['o_date']));
$data['data']['term_of_payment'] = $data['data']['a_term_of_payment'];
if (!empty($inputData['delivery_same_as_bill']) && $inputData['delivery_same_as_bill'] !== true) {
$address = &$inputData['delivery_info'];
$data['data']['a_info'] = $this->gM(
"Delivery to: ",
) . "{$address['checkout_first_name']} {$address['checkout_last_name']}, "
. $this->gM("Phone:") . " {$address['checkout_phone']}, ";
$sFlatSep = '';
if (strlen($address['checkout_address2'])) {
$sFlatSep = (is_numeric(substr($address['checkout_address1'], -1)) ? '-' : ' ');
}
$data['data']['a_info'] .= "{$address['checkout_address1']}{$sFlatSep}{$address['checkout_address2']}, {$address['checkout_city']}, {$address['checkout_country']}, {$address['checkout_zip']}";
}
$address = &$inputData['shipping_address'];
$data['data']['a_beneficiary'] = "{$address['checkout_first_name']} {$address['checkout_last_name']}";
$sFlatSep = '';
if (strlen($address['checkout_address2'])) {
$sFlatSep = (is_numeric(substr($address['checkout_address1'], -1)) ? '-' : ' ');
}
$data['data']['a_ben_domicile'] = "{$address['checkout_address1']}{$sFlatSep}{$address['checkout_address2']}, {$address['checkout_city']}, {$address['checkout_country']}, {$address['checkout_zip']}";
$data['data']['a_ben_phone'] = $address['checkout_phone'];
$data['data']['a_ben_email'] = $inputData['customer_info']['checkout_email'];
unset($address);
}
}
$data['data']['a_desc'] = $this->gM('Default remarks');
$type = $this->module->getAttTypes($defLanguage['id']);
if (!empty($type) && is_array($type)) {
$type[2] = $this->gM("Size"); // Izmērs
$type[3] = $this->gM("Size"); // Autiņu izmērs
$type[8] = ""; // Krāsa
$type[27] = $this->gM("Picture");// Zīmējums
$type[59] = $this->gM("Size");// Izmēri zeķītēm, zābaciņiem, knupīšiem
$type[62] = $this->gM("Size");// Izmēri dvielīšiem, sedziņām, gultasveļai
$type[73] = $this->gM("Size");// Izmēri matračiem
}
// Get all table(product) data;
$td = $this->module->getTableData($id);
if (!empty($td) && is_array($td)) {
foreach ($td as &$v) {
$itemAtt = "";
if ($v['cl1t'] == 8) {
$itemAtt .= " {$v['cl1n']}";
} else {
if ($v['cl1t'] && isset($type[$v['cl1t']])) {
$itemAtt .= " {$type[$v['cl1t']]} {$v['cl1n']}";
}
}
if ($v['cl2t'] == 8) {
$itemAtt .= " {$v['cl2n']}";
} else {
if ($v['cl2t'] && isset($type[$v['cl2t']])) {
$itemAtt .= " {$type[$v['cl2t']]} {$v['cl2n']}";
}
}
$v['p_price'] = number_format($v['p_price'] * 100 / 121, 3, '.', '');
$sumTotal += (float) $v['p_price'];
$v['p_name'] = "{$v['p_name']} -{$itemAtt}";
unset($v['cl1n'], $v['cl2n'], $v['cl1t'], $v['cl2t']);
}
unset($v);
}
// Check product availability and split to others of the same if needed
$td = $this->checkProductAvailability($td);
// Add first product delivery
$td[] = [
'p_name' => $this->gM("Delivery"),
'p_price' => 0.00,
'p_count' => 1,
];
$data['table'] = $td;
}
// Set sum in words
$data['data']['a_p_amount_words'] = cNumbers::num2words($this, $sumTotal * 1.21);
} else {
// Order date;
$data['data']['order_date'] = date("d.m.Y", time());
$data['data']['date'] = date("d.m.Y", time());
$data['data']['a_payment_met'] = $this->gM("Bank Transfer");
// Term of payment
$data['data']['term_of_payment'] = date("d.m.Y", strtotime("+7 days", time()));
$data['data']['a_term_of_payment'] = $data['data']['term_of_payment'];
// Get all table(product) data;
$data['table'] = [
[
'p_name' => $this->gM("Delivery"),
'p_price' => 0.00,
'p_count' => 1,
],
];
$data['edited'] = false;
}
if ($bClone) {
$id = false;
$locked = false;
$data['data']['date'] = date("d.m.Y", time());
$data['data']['order_date'] = $data['data']['date'];
$data['data']['term_of_payment'] = date("d.m.Y", strtotime("+7 days", time()));
$data['data']['a_term_of_payment'] = $data['data']['term_of_payment'];
unset($data['data']['o_id'], $data['data']['o_nr']);
}
$this->oView->DATA = [
'id' => $id ? $id : false,
'order_date' => $data['data']['order_date'],
'date' => date("d.m.Y", time()),
'a_term_of_payment' => $data['data']['a_term_of_payment'],
'term_of_payment' => $data['data']['term_of_payment'],
];
if (!empty($d['o_date'])) {
if (date('d-m-Y', $d['o_date']) == date('d-m-Y')) {
$this->oView->o_date = date('H:i', $d['o_date']);
} else {
$this->oView->o_date = date($this->CMSDateFormat, $d['o_date']);
}
}
if (!empty($d['o_modified'])) {
if (date('d-m-Y', $d['o_modified']) == date('d-m-Y')) {
$this->oView->o_modified = date('H:i', $d['o_modified']);
} else {
$this->oView->o_modified = date($this->CMSDateFormat, $d['o_modified']);
}
}
if (!empty($d['a_modified'])) {
if (date('d-m-Y', $d['a_modified']) == date('d-m-Y')) {
$this->oView->o_modified = date('H:i', $d['a_modified']);
} else {
$this->oView->o_modified = date($this->CMSDateFormat, $d['a_modified']);
}
}
return [
'show' => ['buttons_top' => false, 'buttons_bottom' => true],
'btn' => $this->getFormButtons($locked, $id),
'form_locked' => $locked,
'data' => $data,
'html' => $this->oView->genTemplate('edit'),
];
}
/**
* Function to check product availability on edit
*
* @param array $vProdToCount - products array by reference
* @return mixed data
* @author Aivars Žukovskis <keiss.mareks@gmail.com>
* @category cmsOrders Controller
*/
public function checkProductAvailability(&$vProdToCount)
{
// Check if product amount is available if we send the order to client
$vTempProdToCount = [];
// Create where for query and get al product counts;
$sWhere = '';
foreach ($vProdToCount as $v) {
$sWhere .= " OR ( pc.prod_id = {$v['p_id']}";
$sWhere .= " AND pc.cl1_id = " . (!empty($v['cl1']) ? $v['cl1'] : 0);
$sWhere .= " AND pc.cl2_id = " . (!empty($v['cl2']) ? $v['cl2'] : 0);
$sWhere .= ")";
}
$vProdCount = $this->module->getProductAvailableCountAdv(substr($sWhere, 3));
if (!!$vProdCount && is_array($vProdCount)) {
foreach ($vProdToCount as &$v) {
if (!empty($vProdCount[$v['p_id']][$v['rid']])) {
$vTemp = $vProdCount[$v['p_id']][$v['rid']];
if ($vTemp['cl1'] == $v['cl1'] && $vTemp['cl2'] == $v['cl2']) {
$c = $v['p_count']; // 7
if ($c > $vTemp['p_count']) { // 7 > 2
if (count($vProdCount[$v['p_id']]) > 1) {
$c -= $vTemp['p_count']; // 5 = 7 - 2
foreach ($vProdCount[$v['p_id']] as $rid => $vv) {
if ($c > 0) { // 5
// If its the same row we skip
if ($rid == $v['rid']) {
continue;
}
// chk if cl1 && cl2 && price is the same
if ($vTemp['cl1'] == $vv['cl1'] && $vTemp['cl2'] == $vv['cl2']) {
$vT = $v;
$vT['rid'] = $rid;
$vT['p_price'] = number_format($vv['p_price'] * 100 / 121, 3, '.', '');
$vT['split'] = true;
if ($c > $vv['p_count']) { // 5 > 10
$c -= $vv['p_count']; // 2 = 4 - 2
$vT['p_count'] = $vv['p_count'];
$vTempProdToCount[$v['p_id']][$rid] = $vT;
} else {
$vT['p_count'] = $c; // 5
$c -= $c;
$vTempProdToCount[$v['p_id']][$rid] = $vT;
break;
}
}
} else {
break;
}
}
/*if($c > 0 && count($vTempProdToCount[$v['p_id']]) && ($c != $v['p_count'] - $vTemp['p_count'])){ // 1 > 0 && 1 && 1 != 3 - 1
reset($vTempProdToCount[$v['p_id']]);
$key = key($vTempProdToCount[$v['p_id']]);
$vTempProdToCount[$v['p_id']][$key]['p_count'] += $c;
$c -= $c;
}*/
$v['p_count'] = $vTemp['p_count'];
if ($c > 0) {
$v['p_count'] += $c;
}
}
}
}
}
}
unset($vTemp, $v, $vT);
}
$vReturn = [];
foreach ($vProdToCount as $v) {
$vReturn[] = $v;
if (!empty($vTempProdToCount[$v['p_id']])) {
$vReturn = array_merge($vReturn, $vTempProdToCount[$v['p_id']]);
unset($vTempProdToCount[$v['p_id']]);
}
}
return $vReturn;
}
/**
* Function to save Record data
*
* @param int $recordId - record id
* @param string $fields - param cJSON string
* @return mixed data
* @category cmsOrders Controller
* @author Mareks Keišs <keiss.mareks@gmail.com>
*/
public function saveRecordData($recordId, $fields)
{
$emailSent = false;
$fields = $this->getSubmittedDataAsArray($fields ?? '');
// Start save process
if ($fields) {
// check if form isn't locked before saving data;
if ($bLocked = $this->module->chkIfFormIslocked($recordId)) {
cJSON::senderror(
['locked' => 1, 'msg' => $this->gM("Sorry, but this form has already been sent and is locked(!)")],
);
}
// Remove table data
$table = $fields['table'];
unset($fields['table']);
// Validate fields
$valid = new cValidator($this);
// Check only base errors
$errors = [];
$err = $valid->checkArray($fields, $this->getValCfg(true));
if ($err !== true) {
$errors = ['base' => $err];
}
$iTime = time();
$tableData = [];
$vProdToCount = [];
// Check table errors & build new array
if (!!$table && is_array($table)) {
$iDefCounter = 1;
$bUseDefCounter = false;
foreach ($table as $k => $v) {
$err = $valid->checkArray($v, $this->getValCfg());
if ($err !== true) {
$errors['table'][$k] = $err;
} elseif (!!!$errors) {
if (is_array($v)) {
if (!$bUseDefCounter && empty($v['row_nr'])) {
$bUseDefCounter = true;
}
$tableData[$k] = [
'o_id' => &$recordId,
'row_nr' => ($bUseDefCounter ? $iDefCounter++ : $v['row_nr']),
'p_id' => (!empty($v['p_id']) ? $v['p_id'] : 0),
'p_row_id' => (!empty($v['rid']) ? $v['rid'] : 0),
'p_cl1' => (!empty($v['cl1']) ? $v['cl1'] : 0),
'p_cl2' => (!empty($v['cl2']) ? $v['cl2'] : 0),
'p_price' => (!empty($v['p_price']) ? $v['p_price'] : 0),
'p_count' => (!empty($v['p_count']) ? $v['p_count'] : 0),
'p_name' => (!empty($v['p_name']) ? $v['p_name'] : ""),
];
if (!empty($v['p_id']) && !empty($v['p_count'])) {
$priceSold = $tableData[$k]['p_price'] + ($tableData[$k]['p_price'] * 0.21);
$vProdToCount[] = [
'prod_id' => $tableData[$k]['p_id'],
'row_id' => $tableData[$k]['p_row_id'],
'cl1_id' => $tableData[$k]['p_cl1'],
'cl2_id' => $tableData[$k]['p_cl2'],
'count' => $tableData[$k]['p_count'] * -1,
'price_sold' => number_format($priceSold, 3, '.', ''),
'op_type' => self::PRODUCT_OPERATION_ORDER_SEND,
'op_date' => $iTime,
'user_id' => $this->oUser->getUser(),
'date' => $iTime,
'modified' => $iTime,
'modified_by' => $this->oUser->getUser(),
'created' => $iTime,
'created_by' => $this->oUser->getUser(),
];
}
}
}
}
}
if (!!$errors) {
cJSON::senderror(['data' => $errors]);
}
// Check if product amount is available
if (count($vProdToCount)) {
$sWhere = '';
foreach ($vProdToCount as $v) {
$sWhere .= " OR ( prod_id = {$v['prod_id']} AND row_id = {$v['row_id']}";
if (!empty($v['cl1_id'])) {
$sWhere .= " AND cl1_id = {$v['cl1_id']}";
}
if (!empty($v['cl2_id'])) {
$sWhere .= " AND cl2_id = {$v['cl2_id']}";
}
$sWhere .= ")";
}
$sWhere = substr($sWhere, 3);
$vProdCount = $this->module->getProductAvailableCount($sWhere);
$vErrorRows = [];
if (getP('send') && !!$vProdCount && is_array($vProdCount)) {
foreach ($vProdToCount as $v) {
$bError = true;
if (!empty($vProdCount[$v['prod_id']][$v['row_id']])) {
$vTemp = $vProdCount[$v['prod_id']][$v['row_id']];
if (($vTemp['cl1_id'] == $v['cl1_id']) && ($vTemp['cl2_id'] == $v['cl2_id'])) {
$c = $v['count'] * -1;
if ($c <= $vTemp['count']) {
$bError = false;
}
}
}
if ($bError) {
if (!empty($vTemp['count']) && $vTemp['count'] > 0) {
$vErrorRows[$v['prod_id']][$v['row_id']] = str_replace(
"%COUNT%",
$vTemp['count'],
$this->gM("Available products left - %COUNT%"),
);
} else {
$vErrorRows[$v['prod_id']][$v['row_id']] = $this->gM("No products available");
}
}
}
unset($vTemp, $bError);
}
if (self::PRODUCT_AVAILABILITY_CHK && count($vErrorRows)) {
cJSON::senderror(['availableProdErr' => $vErrorRows]);
}
}
// Create base data array
$update = [
// additionalData
'o_nr' => (!empty($fields['data']['o_nr']) ? $fields['data']['o_nr'] : ""),
'o_date' => (!empty($fields['data']['order_date']) ? strtotime(
$fields['data']['order_date'],
) : $iTime),
'a_p_amount_words' => (!empty($fields['data']['a_p_amount_words']) ? $fields['data']['a_p_amount_words'] : ""),
'a_desc' => (!empty($fields['data']['a_desc']) ? $fields['data']['a_desc'] : ""),
'a_desc_transaction' => (!empty($fields['data']['a_desc_transaction']) ? $fields['data']['a_desc_transaction'] : ""),
'a_term_of_payment' => (!empty($fields['data']['a_term_of_payment']) ? strtotime(
$fields['data']['a_term_of_payment'],
) : $iTime),
'a_payment_met' => (!empty($fields['data']['a_payment_met']) ? $fields['data']['a_payment_met'] : ""),
'a_shipping_met' => (!empty($fields['data']['a_shipping_met']) ? $fields['data']['a_shipping_met'] : ""),
'a_info' => (!empty($fields['data']['a_info']) ? $fields['data']['a_info'] : ""),
// supplier_info
'a_supplier' => (!empty($fields['data']['a_supplier']) ? $fields['data']['a_supplier'] : ""),
'a_sup_reg_nr' => (!empty($fields['data']['a_sup_reg_nr']) ? $fields['data']['a_sup_reg_nr'] : ""),
'a_sup_domicile' => (!empty($fields['data']['a_sup_domicile']) ? $fields['data']['a_sup_domicile'] : ""),
'a_sup_pvn_reg_nr' => (!empty($fields['data']['a_sup_pvn_reg_nr']) ? $fields['data']['a_sup_pvn_reg_nr'] : ""),
'a_sup_sett_details' => (!empty($fields['data']['a_sup_sett_details']) ? $fields['data']['a_sup_sett_details'] : ""),
'a_sup_cont_nr' => (!empty($fields['data']['a_sup_cont_nr']) ? $fields['data']['a_sup_cont_nr'] : ""),
'a_sup_phone' => (!empty($fields['data']['a_sup_cont_nr']) ? $fields['data']['a_sup_phone'] : ""),
'a_sup_email' => (!empty($fields['data']['a_sup_cont_nr']) ? $fields['data']['a_sup_email'] : ""),
// beneficiary_info
'a_beneficiary' => (!empty($fields['data']['a_beneficiary']) ? $fields['data']['a_beneficiary'] : ""),
'a_ben_reg_nr' => (!empty($fields['data']['a_ben_reg_nr']) ? $fields['data']['a_ben_reg_nr'] : ""),
'a_ben_domicile' => (!empty($fields['data']['a_ben_domicile']) ? $fields['data']['a_ben_domicile'] : ""),
'a_ben_pvn_reg_nr' => (!empty($fields['data']['a_ben_pvn_reg_nr']) ? $fields['data']['a_ben_pvn_reg_nr'] : ""),
'a_ben_sett_details' => (!empty($fields['data']['a_ben_sett_details']) ? $fields['data']['a_ben_sett_details'] : ""),
'a_ben_cont_nr' => (!empty($fields['data']['a_ben_cont_nr']) ? $fields['data']['a_ben_cont_nr'] : ""),
'a_ben_phone' => (!empty($fields['data']['a_ben_phone']) ? $fields['data']['a_ben_phone'] : ""),
'a_ben_email' => (!empty($fields['data']['a_ben_email']) ? $fields['data']['a_ben_email'] : ""),
// misc.
'a_modified' => $iTime,
];
// Update / Insert record data
$oldId = $recordId;
// We go get a record id if we don't have one - inserting a dummy row in main table to link with;
if (!$recordId) {
$iNr = $this->module->getNextDeletedOrderNr();
if (!strlen($iNr)) {
$iNr = (new cNumbers())->getProductBillNumber();
}
$update['o_nr'] = $iNr;
if (!$recordId = $this->module->insertDummyOrder(
[
'o_nr' => $update['o_nr'],
'o_modified' => $iTime,
'o_date' => $iTime,
'o_mail' => $update['a_ben_email'],
'o_edited' => 1,
'o_input_data' => '',
'o_mid' => 0,
],
)) {
cJSON::senderror($this->gM('Something went wrong while inserting a dummy order!'));
}
}
$update['o_id'] = $recordId;
if (!$this->module->saveRecordDataById($fields['edited'], $recordId, $update)) {
cJSON::senderror("Something went wrong while saving base data!");
}
$returnArray = [];
if (!$oldId) {
// Delete reserved order number
$this->module->deleteReservedOrderNr($update['o_nr']);
$returnArray['newid'] = $recordId;
$returnArray['newNr'] = $update['o_nr'];
}
$this->module->saveTableData($recordId, $tableData);
// Unset this id from session where we keep files
$this->sessionFiles->order_id[$recordId] = false;
// Chk for send parameter;
if (getP('send')) {
// Create new pdf file
$cExport = new cmsOrdersExport($this);
$file = $cExport->savePdfDoc($recordId, true);
$emailSent = $this->sendUserReceiptPDF($recordId, $file, $update);
}
if ($emailSent) {
// subtract the count in count table
if (!!$vProdToCount) {
$this->module->updateToCount($vProdToCount);
}
$returnArray['send'] = 1;
}
cJSON::sendok($returnArray);
}
}
/**
* Function to create table headers + search
*
* @param int $recordId - record id
* @param string $file - file name to attach
* @param array $vCustomerData - customer data
* @return bool
* @author Mareks Keišs <keiss.mareks@gmail.com>
* @category cmsOrders Controller
* @version 1.1
*/
private function sendUserReceiptPDF($recordId, $file, $vCustomerData)
{
if (!!$recordId && !!$file && file_exists($file)) {
$cry = new cDefuseCrypto();
$key = $cry->encrypt($recordId);
// Get default pub language
$defLanguage = getDefaultAppLang();
// TODO: Varbūt https?
$email_href = "http://{$_SERVER['SERVER_NAME']}" . $this->getLinkForID(
"pubBuyController::EMAIL_READ_URL",
$defLanguage['id'],
false,
"o:{$key}",
);
$mm = new cMail();
$mailData = [
'order_nr' => $vCustomerData['o_nr'],
'order_mail' => $vCustomerData['a_ben_email'],
'order_sup_name' => $vCustomerData['a_supplier'],
'order_sup_reg_nr' => $vCustomerData['a_sup_reg_nr'],
'order_sup_acc_nr' => $vCustomerData['a_sup_cont_nr'],
'order_sup_bank' => $vCustomerData['a_sup_sett_details'],
'item_open_link' => (strlen($email_href) ? $this->gM(
"Can't see the images?",
) . '&nbsp;<a href="' . $email_href . '" style="color: #c2665c;text-decoration:underline;">' . $this->gM(
'Click here.',
) . '</a>' : ""),
];
// Add mail to send to customer
$mId = $mm->addMail(
$vCustomerData['a_ben_email'],
false,
cMail::MAIL_SERVER_DEFAULT,
cMail::MAIL_17_ORDER_RECEIPT,
$this->langId,
$mailData,
$file,
false,
);
// Update mail link id
if ($mId > 0 || $mId < 0) {
$this->module->db->_queryUpdate(
'mod_orders',
['o_locked' => 1, 'o_mreceipt_id' => ($mId > 0 ? $mId : ($mId * -1))],
['id' => $recordId],
);
return true;
}
}
return false;
}
/**
* Function to create table headers + search
*
* @return array|bool of data
* @category cmsOrders Controller
* @author Mareks Keišs <keiss.mareks@gmail.com>
* @version 1.1
*/
public function getTableFields()
{
if (!$this->oUser->chkPermission('CMS_APP_ORDER_RECEIPTS_SHOW_MANAGEMENT', false, false)) {
return false;
}
$statusData = [
'' => [
'title' => $this->gM("Select"),
],
1 => [
'title' => $this->gM("Sent"),
],
2 => [
'title' => $this->gM("Pending"),
],
];
$tFields = [
"checkbox" => [
'sort' => false,
'title' => '',
'class' => 'w4 center rchk',
],
"id" => [
'sort' => true,
'search' => true,
'title' => $this->gM("ID"),
'class' => 'w8 center sortDesc sort',
'db_field' => 'mo.id',
'type' => 'input',
],
"o_nr" => [
'sort' => true,
'search' => true,
'title' => $this->gM("Order number"),
'class' => 'w14 center',
'db_field' => 'mo.o_nr',
'type' => 'input',
],
"o_mail" => [
'sort' => true,
'search' => true,
'title' => $this->gM("Order mail"),
'class' => 'w22',
'db_field' => 'mo.o_mail',
'type' => 'input',
],
"o_date" => [
'sort' => true,
'search' => true,
'title' => $this->gM("Order date"),
'class' => 'w12 center',
'db_field' => 'mo.o_date',
'type' => 'input',
],
"fexcel" => [
'sort' => false,
'search' => false,
'title' => $this->gM("Export .xls"),
'class' => 'w10 center fexcel',
'type' => 'input',
],
"fpdf" => [
'sort' => false,
'search' => false,
'title' => $this->gM("Export .pdf"),
'class' => 'w10 center fpdf',
'type' => 'input',
],
"o_locked" => [
'sort' => true,
'search' => true,
'title' => $this->gM("Sent"),
'class' => 'w8 center',
'db_field' => 'mo.o_locked',
'type' => 'dropBox',
'data' => $statusData,
'default' => '',
],
"o_edited" => [
'sort' => false,
'search' => false,
'title' => $this->gM("Edited"),
'class' => 'w8 center',
'type' => 'input',
],
"buttons" => [
'sort' => false,
'class' => 'w20',
'title' => $this->gM("Actions"),
'btnset' => [
'ledit' => [
'edit' => true,
'title' => $this->gM("Edit"),
],
'ldelete' => [
'del' => true,
'title' => $this->gM("Delete"),
],
],
],
];
if (!$this->chkP('SYS_SHOW_TABLE_IDS')) {
unset($tFields['id']);
}
return $tFields;
}
/**
* Function to get js translations for view
*
* @return array of data
* @category cmsOrders Controller
* @author Mareks Keišs <keiss.mareks@gmail.com>
*/
public function getTranslations()
{
return [
'yes' => $this->gM('Yes'),
'no' => $this->gM('No'),
'delTitle' => $this->gM('Delete Entry?'),
'delMessage' => $this->gM(
'Selected entry will be permanently deleted and cannot be recovered. Confirm delete?',
),
'buttonYes' => $this->gM('Delete selected entry'),
'buttonCancel' => $this->gM('Cancel operation'),
'msgDelivery' => $this->gM('Delivery'),
'noDataFound' => $this->gM('No data found!'),
];
}
/**
* Function to get table actions
*
* @return array of data
* @category cmsOrders Controller
* @author Mareks Keišs <keiss.mareks@gmail.com>
*/
public function getTableActions()
{
$data = [
'inew' => [
'lbl' => $this->gM("Add new"),
'icon' => 'nico-add',
],
/*'istatus' => array(
'lbl' => $this->gM("Change item status"),
'sepline' => true,
),*/
'icloneBlank' => [
'lbl' => $this->gM("Create a new copy"),
'icon' => 'nico-clone',
],
'sepline',
'idelete' => [
'lbl' => $this->gM("Delete selected"),
'sepline' => false,
'icon' => 'nico-delete',
],
];
// Reform drop down
reformatDropDown($data);
return $data;
}
/**
* Function to get js validator cfg
*
* @param bool $bPrepDataCfg - reconfigure cfg data array
* @return array of data
* @author Aivars Žukovskis <keiss.mareks@gmail.com>
* @category cmsCountToClass Controller
*/
public function getValCfg($bPrepDataCfg = true)
{
$valCfg = [
// Additional validation config
'cfg' => [
cValidator::CFG_BIND_FIELD => 'data-validator',
],
'o_nr' => [
cValidator::P_TYPE => cValidator::TY_DEC,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_NUM],
],
'o_date' => [
cValidator::P_TYPE => cValidator::TY_DATE,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_DATE],
],
'a_supplier' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_sup_reg_nr' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_sup_domicile' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_sup_pvn_reg_nr' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_sup_sett_details' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_sup_cont_nr' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_sup_phone' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_PHONE],
],
'a_sup_email' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_EMAIL],
],
'a_beneficiary' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_ben_reg_nr' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_ben_domicile' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_ben_pvn_reg_nr' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_ben_sett_details' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_ben_cont_nr' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_ben_phone' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_PHONE],
],
'a_ben_email' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_EMAIL],
],
'a_desc_transaction' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_term_of_payment' => [
cValidator::P_TYPE => cValidator::TY_DATE,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_DATE],
],
'a_shipping_met' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_payment_met' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_info' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_p_amount_words' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'a_desc' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'p_name' => [
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_STR],
],
'p_count' => [
cValidator::P_TYPE => cValidator::TY_FLOAT,
cValidator::P_COMP => 1,
cValidator::P_TEST => [cValidator::CHK_NUM],
],
'p_price' => [
cValidator::P_TYPE => cValidator::TY_FLOAT,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_NUM],
],
'p_price_vat' => [
cValidator::P_TYPE => cValidator::TY_FLOAT,
cValidator::P_COMP => 0,
cValidator::P_TEST => [cValidator::CHK_NUM],
],
];
return ($bPrepDataCfg ? cValidator::prepValCfgForValidation($valCfg) : $valCfg);
}
/**
* Function to get form buttons
*
* @param bool $formLocked - indicates whether the form is locked or not
* @param int $id - entry id
* @return array of data
* @category cmsOrders Controller
* @author Mareks Keišs <keiss.mareks@gmail.com>
*/
public function getFormButtons($formLocked, $id)
{
$formButtons = [
0 => [
'id' => 'exportExcel',
'lbl' => $this->gM('Export excel'),
'href' => "{$this->gL()}/action:export_excel/data:{$id}",
],
1 => [
'id' => 'exportPdf',
'lbl' => $this->gM('Export pdf'),
'href' => "{$this->gL()}/action:export_pdf/data:{$id}",
],
2 => [
'id' => 'fsend',
'lbl' => $this->gM('Save & Send'),
],
3 => [
'id' => 'empty',
'lbl' => '',
],
4 => [
'id' => 'fsave',
'lbl' => $this->gM('Save'),
],
5 => [
'id' => 'fcancel',
'lbl' => $this->gM('Cancel'),
],
];
if ($formLocked) {
unset($formButtons[2], $formButtons[4]);
}
return $formButtons;
}
}