Initial commit: apps.supersamsev.ru
This commit is contained in:
commit
54475e7d3d
17284 files changed
+98268
No files matched your search
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
namespace App\Model\Entity;
|
||||
|
||||
|
||||
use Cake\ORM\Entity;
|
||||
use Cake\Auth\DefaultPasswordHasher;
|
||||
|
||||
class User extends Entity {
|
||||
|
||||
protected $_accessible = [
|
||||
'*' => true,
|
||||
'id' => false
|
||||
];
|
||||
|
||||
protected function _setPassword($password) {
|
||||
return (new DefaultPasswordHasher)->hash($password);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class BranchesTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('branches');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,613 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Routing\Router;
|
||||
use DBF;
|
||||
use PHPExcel;
|
||||
use PHPExcel_Writer_Excel5;
|
||||
use SMSRU;
|
||||
//use mPDF;
|
||||
use Mpdf\Mpdf;
|
||||
use Cake\Core\Configure;
|
||||
|
||||
class CalcDoorsOrdersTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('calc_doors_orders');
|
||||
}
|
||||
|
||||
public function orderEmailNotify($data, $cutConfig, $clientIP, $authUserId = null, $configDoor) {
|
||||
$result = 'error';
|
||||
|
||||
$selectedBranch = (!empty($data['branchId']) && !empty($cutConfig['branches'][$data['branchId']]) ? $cutConfig['branches'][$data['branchId']] : null);
|
||||
$selectedBranchId = (!empty($data['branchId']) && !empty($cutConfig['branches'][$data['branchId']]) ? $data['branchId'] : null);
|
||||
|
||||
if (empty($selectedBranch)) {
|
||||
foreach($cutConfig['branches'] as $key => $li) {
|
||||
if (!empty($li['is_default'])) {
|
||||
$selectedBranch = $li;
|
||||
$selectedBranchId = $key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$orderPhone = (!empty($data['orderPhone']) ? htmlentities($data['orderPhone']) : "");
|
||||
$orderAddress = (!empty($data['orderAddress']) ? htmlentities($data['orderAddress']) : "не указан");
|
||||
$orderName = (!empty($data['orderName']) ? htmlentities($data['orderName']) : 'не указано');
|
||||
$orderComment = (!empty($data['orderComment']) ? nl2br(htmlentities($data['orderComment'])) : 'не указан');
|
||||
|
||||
$newOrderData = [
|
||||
'name' => $data['orderName'],
|
||||
'email' => $data['orderEmail'],
|
||||
'phone' => $data['orderPhone'],
|
||||
'address' => $data['orderAddress'],
|
||||
'comment' => $data['orderComment'],
|
||||
'price' => (!empty($data['price']) ? $data['price'] : str_replace(" ", "", $data['selectedDoorData']['order_calc_results']['price'])),
|
||||
'actual_price' => (!empty($data['actualPrice']) ? $data['actualPrice'] : str_replace(" ", "", $data['selectedDoorData']['order_calc_results']['price'])),
|
||||
|
||||
'params' => json_encode($data['selectedDoorData']['params']),
|
||||
'order_calc_results' => json_encode($data['selectedDoorData']['order_calc_results'])
|
||||
];
|
||||
|
||||
if ($selectedBranchId == "printOnly") {
|
||||
$newOrderData["order_type"] = "print";
|
||||
} else {
|
||||
$newOrderData["order_type"] = "order";
|
||||
$newOrderData["branch_id"] = $selectedBranchId;
|
||||
}
|
||||
|
||||
$orderNum = "";
|
||||
if(!empty($data['eOId'])) {
|
||||
$encryptedOrderId = $data['eOId'];
|
||||
$decryptedData = TableRegistry::getTableLocator()->get('CutOrders')->decryptCustomData($encryptedOrderId, $cutConfig);
|
||||
|
||||
if (!empty($decryptedData['orderId'])) {
|
||||
$order = $this->find('all')->where(['id' => $decryptedData['orderId']])->first();
|
||||
if (!empty($order)) {
|
||||
$this->patchEntity($order, $newOrderData);
|
||||
$orderNum = $order['order_num'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($order)) {
|
||||
$newOrderData['order_num'] = '';
|
||||
$newOrderData['created'] = date('Y-m-d H:i:s');
|
||||
$order = $this->newEntity($newOrderData);
|
||||
$data['eOId'] = false;
|
||||
}
|
||||
|
||||
if ($this->save($order)) {
|
||||
$orderId = $order->id;
|
||||
|
||||
if (empty($encryptedOrderId)) {
|
||||
$encryptedOrderId = TableRegistry::getTableLocator()->get('CutOrders')->encryptCustomData($orderId, 'orderId', $cutConfig);
|
||||
|
||||
if (!empty($encryptedOrderId)) {
|
||||
$viewOrderUrlBase = '/calc-doors?oid=' . $encryptedOrderId;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (empty($order->order_num)) {
|
||||
$cutSettingsTable = TableRegistry::getTableLocator()->get('CalcDoorsSettings');
|
||||
$orderNumMonth = date('Y-m-01');
|
||||
$orderNumDefaultCounters = [
|
||||
'order' => 0,
|
||||
'print' => 0
|
||||
];
|
||||
|
||||
$orderNumSetting = $cutSettingsTable->find()->where([
|
||||
'key' => 'orderNumCounter',
|
||||
'group' => 'common'
|
||||
])->first();
|
||||
if (empty($orderNumSetting)) {
|
||||
$orderNumDefaultCounters[$newOrderData["order_type"]]++;
|
||||
$orderNumCounter = 1;
|
||||
|
||||
$orderNumSetting = $cutSettingsTable->newEntity();
|
||||
$orderNumSetting = $cutSettingsTable->patchEntity($orderNumSetting, [
|
||||
'key' => 'orderNumCounter',
|
||||
'value' => json_encode([
|
||||
'month' => $orderNumMonth,
|
||||
'counters' => $orderNumDefaultCounters
|
||||
]),
|
||||
'group' => 'common'
|
||||
]);
|
||||
} else {
|
||||
$orderNumSetting->value = @json_decode($orderNumSetting->value, true);
|
||||
if ($orderNumSetting->value['month'] != $orderNumMonth) {
|
||||
$orderNumSetting->value['month'] = $orderNumMonth;
|
||||
|
||||
$orderNumDefaultCounters[$newOrderData["order_type"]]++;
|
||||
$orderNumCounter = 1;
|
||||
$orderNumSetting->value['counters'] = $orderNumDefaultCounters;
|
||||
} else {
|
||||
$orderNumSetting->value['counters'][$newOrderData["order_type"]]++;
|
||||
$orderNumCounter = $orderNumSetting->value['counters'][$newOrderData["order_type"]];
|
||||
}
|
||||
$orderNumSetting->value = json_encode($orderNumSetting->value);
|
||||
}
|
||||
$cutSettingsTable->save($orderNumSetting);
|
||||
|
||||
$orderNum = $cutConfig['common']['orderNumPrefix']['value'] . date('dmY') . "-" . str_pad($orderNumCounter, $cutConfig['common']['orderNumLength']['value'], "0", STR_PAD_LEFT);
|
||||
if ($newOrderData["order_type"] == "print") {
|
||||
$orderNum .= "-P";
|
||||
}
|
||||
|
||||
$order->order_num = $orderNum;
|
||||
}
|
||||
|
||||
if (!empty($viewOrderUrlBase)) {
|
||||
$viewOrderUrl = '/calc-doors?oid=' . $encryptedOrderId;
|
||||
$order->view_order_url = $viewOrderUrlBase;
|
||||
}
|
||||
|
||||
$this->save($order);
|
||||
|
||||
$orderDate = date('d.m.Y H:i');
|
||||
|
||||
$orderSpec['order'] = '<br/>
|
||||
Номер заказа: ' . ($order->order_type == "order" ? $orderNum : "-"). '<br/>' . '
|
||||
Дата заказа: ' . $orderDate . '<br/>';
|
||||
|
||||
if (($selectedBranchId != "printOnly") && !empty($selectedBranch)) {
|
||||
$orderSpec['order'] .= 'Контакт-менеджер: ' . $selectedBranch['label'] . '<br/>';
|
||||
}
|
||||
|
||||
|
||||
|
||||
$orderSpec['client'] = 'Данные клиента: <br/>
|
||||
ФИО: ' . $orderName . '<br/>' ;
|
||||
|
||||
if (!empty($data['orderEmail'])) {
|
||||
$orderSpec['client'] .= 'E-mail: ' . htmlentities($data['orderEmail']) . '<br/>';
|
||||
}
|
||||
|
||||
if (!empty($orderPhone)) {
|
||||
$orderSpec['client'] .= 'Телефон: ' . $orderPhone . '<br/>';
|
||||
}
|
||||
|
||||
if (!empty($orderAddress)) {
|
||||
$orderSpec['client'] .= 'Адрес доставки: ' . $orderAddress . '<br/>';
|
||||
}
|
||||
|
||||
if (!empty($data['selectedDoorData']['params']['discount'])) {
|
||||
$orderSpec['client'] .= 'Скидка: ' . min((int) $data['selectedDoorData']['params']['discount'], 100) . '%' . '<br/>';
|
||||
}
|
||||
|
||||
if (!empty($data['orderComment'])) {
|
||||
$orderSpec['client'] .= 'Комментарий к заказу: ' . nl2br(htmlentities($data['orderComment'])) . '<br/>';
|
||||
}
|
||||
|
||||
$orderSpec['client'] .= '<br/>
|
||||
ПрофильС: ' . $configDoor['profile'] . " " . $cutConfig["doorsManufacturers"][$configDoor['manufacturer_id']]["label"] . '<br/>' . '
|
||||
Цвет системы: ' . $configDoor['color'] . '<br/>' . '
|
||||
Направ.верх: ' . $configDoor['colorNapravlyaushayaVerh'] . '<br/>' . '
|
||||
Направ.низ: ' . $configDoor['colorNapravlyaushayaNiz'] . '<br/>';
|
||||
|
||||
|
||||
$filename = $orderNum; //. "_" . date('d-m-Y');
|
||||
$specFilename = $filename. "_specification" . ".pdf";
|
||||
$tmpSpecFile = $this->generateSpecFile($data, $cutConfig, $orderSpec, $orderNum, $order["order_type"]);
|
||||
|
||||
if (empty($data['eOId']) && ($selectedBranchId != "printOnly")) { //new order, send email
|
||||
$mail = TableRegistry::getTableLocator()->get('CutOrders')->configurePHPMailer($cutConfig);
|
||||
foreach (explode("\n", $selectedBranch['order_notify_manager_emails']) as $managerEmail) {
|
||||
$managerEmail = trim($managerEmail);
|
||||
if (!empty($managerEmail)) {
|
||||
$mail->addAddress(trim($managerEmail));
|
||||
}
|
||||
}
|
||||
|
||||
$mail->addAttachment($tmpSpecFile, $specFilename);
|
||||
|
||||
$mail->Subject = str_replace("{OrderNum}", $orderNum, $cutConfig['common']['orderNotifySubject']['value']);
|
||||
|
||||
$mail->Body = $cutConfig['common']['orderNotifyBodyStart']['value'];
|
||||
$mail->AltBody = $cutConfig['common']['orderNotifyBodyStart']['value'];
|
||||
|
||||
|
||||
$mail->Body .= '<br/>
|
||||
Номер заказа: ' . ($order->order_type == "order" ? $orderNum : "-") . '<br/>' . '
|
||||
Дата заказа: ' . $orderDate . '<br/>';
|
||||
|
||||
$mail->AltBody .= '
|
||||
Номер заказа: ' . ($order->order_type == "order" ? $orderNum : "-") . '
|
||||
Дата заказа: ' . $orderDate;
|
||||
|
||||
if (!empty($selectedBranch)) {
|
||||
$mail->Body .= 'Контакт-менеджер: ' . $selectedBranch['label'] . '<br/>';
|
||||
|
||||
$mail->AltBody .= '
|
||||
Контакт-менеджер: ' . $selectedBranch['label'];
|
||||
}
|
||||
|
||||
$mail->Body .= '<br/><br/>
|
||||
ФИО: ' . $orderName . '<br/>' . '
|
||||
E-mail: ' . (!empty($data['orderEmail']) ? '<a href="mailto:' . htmlentities($data['orderEmail']) . '">' . htmlentities($data['orderEmail']) . '</a>' : 'не указан') . '<br/>' . '
|
||||
Телефон: ' . (!empty($orderPhone) ? '<a href="tel:' . preg_replace("/[^0-9.]/", "", $orderPhone) . '">' . $orderPhone . '</a>' : 'не указан') . '<br/>' . '
|
||||
Адрес доставки: ' . (!empty($orderAddress) ? $orderAddress : 'не указан') . '<br/>' . '
|
||||
' . (!empty($data['selectedDoorData']['params']['discount']) ? 'Скидка: ' . $data['selectedDoorData']['params']['discount'] . '%' . '<br/>' : '') . '
|
||||
Комментарий: ' . $orderComment . '<br/>';
|
||||
|
||||
|
||||
$mail->AltBody .= '
|
||||
ФИО: ' . $orderName . '
|
||||
E-mail: ' . (!empty($data['orderEmail']) ? htmlentities($data['orderEmail']) : 'не указан') . '
|
||||
Телефон: ' . (!empty($orderPhone) ? $orderPhone : 'не указан') . '
|
||||
Адрес доставки: ' . (!empty($orderAddress) ? $orderAddress : 'не указан') . '
|
||||
' . (!empty($data['selectedDoorData']['params']['discount']) ? 'Скидка: ' . $data['selectedDoorData']['params']['discount'] . '%' : '') . '
|
||||
Комментарий: ' . $orderComment;
|
||||
|
||||
$mail->Body .= '<br/>
|
||||
ПрофильС: ' . $configDoor['profile'] . " " . $cutConfig["doorsManufacturers"][$configDoor['manufacturer_id']]["label"] . '<br/>' . '
|
||||
Цвет системы: ' . $configDoor['color'] . '<br/>' . '
|
||||
Направ.верх: ' . $configDoor['color'] . '<br/>' . '
|
||||
Направ.низ: ' . $configDoor['color'] . '<br/>';
|
||||
|
||||
$mail->AltBody .= '<br/>
|
||||
ПрофильС: ' . $configDoor['profile'] . " " . $cutConfig["doorsManufacturers"][$configDoor['manufacturer_id']]["label"] . '
|
||||
Цвет системы: ' . $configDoor['color'] . '
|
||||
Направ.верх: ' . $configDoor['color'] . '
|
||||
Направ.низ: ' . $configDoor['color'] ;
|
||||
|
||||
if (!empty($viewOrderUrl)) {
|
||||
$mail->Body .= '<br/><br/>
|
||||
<a href="' . Router::fullBaseUrl() . $viewOrderUrl . '">Ссылка для печати заказа</a>';
|
||||
|
||||
$mail->AltBody .= '
|
||||
|
||||
Ссылка для печати заказа: ' . Router::fullBaseUrl() . $viewOrderUrl;
|
||||
}
|
||||
|
||||
|
||||
$order->html_letter = $mail->Body;
|
||||
$order->text_letter = $mail->AltBody;
|
||||
$this->save($order);
|
||||
|
||||
$mail->send();
|
||||
}
|
||||
|
||||
$result = 'success';
|
||||
|
||||
if (!empty($orderNum)) {
|
||||
$zip = new \ZipArchive;
|
||||
if ($zip->open(ROOT . '/files/calc_doors_orders/' . $orderNum . '.zip', \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true) {
|
||||
$zip->addFile($tmpSpecFile, $specFilename);
|
||||
$zip->close();
|
||||
}
|
||||
}
|
||||
|
||||
@unlink($tmpSpecFile);
|
||||
|
||||
if (empty($data['eOId'])) { //new order, send sms
|
||||
if (!empty($selectedBranch['order_notify_manager_sms'])) {
|
||||
TableRegistry::getTableLocator()->get('CutOrders')->sendSms(explode("\n", $selectedBranch['order_notify_manager_sms']), "Появился новый заказ " . $orderNum, $cutConfig['global']['smsRuApiKey']['value'], $clientIP);
|
||||
}
|
||||
}
|
||||
|
||||
if ($newOrderData["order_type"] == "order") {
|
||||
if (!empty($data['eOId'])) { //save order, revert stat
|
||||
$order->updated_date = date('Y-m-d H:i:s');
|
||||
$order->updated_by_manager = $authUserId;
|
||||
$this->save($order);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($cutConfig['global']['additionalActionsAllowed'])) {
|
||||
$viewOrderUrl = "";
|
||||
}
|
||||
|
||||
return [
|
||||
'orderEmailNotifySent' => $result,
|
||||
'printOrderUrl' => (!empty($viewOrderUrl) ? str_replace("/calc-doors", "/calc-doors-print", $viewOrderUrl): "")
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
public function resendOrderEmailNotify($order, $managerEmail, $cutConfig) {
|
||||
$mail = TableRegistry::getTableLocator()->get('CutOrders')->configurePHPMailer($cutConfig);
|
||||
$mail->addAddress(trim($managerEmail));
|
||||
|
||||
$mail->Subject = str_replace("{OrderNum}", $order->order_num, $cutConfig['common']['orderNotifySubject']['value']);
|
||||
|
||||
$mail->Body = (!empty($order->html_letter) ? $order->html_letter : $cutConfig['common']['orderNotifyBodyStart']['value']);
|
||||
$mail->AltBody = (!empty($order->text_letter) ? $order->text_letter : $cutConfig['common']['orderNotifyBodyStart']['value']);
|
||||
|
||||
$zip = @zip_open(ROOT . '/files/calc_doors_orders/' . $order->order_num . '.zip');
|
||||
if (!empty($zip)) {
|
||||
while ($zip_entry = zip_read($zip)) {
|
||||
$mail->addStringAttachment(zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)), zip_entry_name($zip_entry));
|
||||
}
|
||||
|
||||
@zip_close($zip);
|
||||
}
|
||||
|
||||
$mail->send();
|
||||
}
|
||||
|
||||
function generateSpecFile($data, $cutConfig, $orderSpec, $orderNum, $orderType) {
|
||||
$tmpSpecFile = @tempnam("/tmp", "calc_doors_order_email_spec_pdf");
|
||||
|
||||
|
||||
$html = "<style>
|
||||
body { font-size: 12px; font-family: arial, sans-serif; }
|
||||
table { width: 100%; border: 1px solid #000; border-collapse: collapse; }
|
||||
table th, table td { padding: 5px; border: 1px solid #000; text-align: left; }
|
||||
table td { padding: 3px 5px; }
|
||||
table th { font-weight: normal; }
|
||||
table th.text-center, table td.text-center { text-align: center; }
|
||||
.borderDiv { font-size: 2px; line-height: 10px; }
|
||||
.border1DivTop { border-top: 1px solid #000; }
|
||||
.border1DivBottom { border-bottom: 1px solid #000; }
|
||||
.border2DivTop { border-top: 1px dashed #000;}
|
||||
.border2DivBottom { border-bottom: 1px dashed #000;}
|
||||
.border1divWide { border-top: 2px solid #000; }
|
||||
.border2divWide { border-top: 2px dashed #000; }
|
||||
.border1divWide, .border2divWide { font-size: 4px; }
|
||||
table.table-footer, table.table-header { margin-top: 0; }
|
||||
table.table-footer td, table.table-header td { font-size: 12px; padding: 5px 0 5px 0; }
|
||||
table.table-footer td { padding: 3px 0 3px 0; }
|
||||
table.table-border-less, table.table-border-less td { border: 0 none; }
|
||||
</style>";
|
||||
|
||||
$html .= $orderSpec['order'] . '<br/>';
|
||||
|
||||
$html .= $orderSpec['client'] . '<br/>';
|
||||
|
||||
$params = $data['selectedDoorData']['params'];
|
||||
$calc = $data['selectedDoorData']['order_calc_results'];
|
||||
|
||||
$html .= "Высота проема: " . $params['height'] . "мм" . "<br/>" .
|
||||
"Ширина проема: " . $params['width'] . "мм" . "<br/>" .
|
||||
"Количество дверей: " . $params['doorsCount'] . "шт" . "<br/>";
|
||||
|
||||
$configDoor = TableRegistry::getTableLocator()->get('CalcDoors')->find('all')->where([
|
||||
'id' => $params['doorId']
|
||||
])->first();
|
||||
|
||||
$doorPrices = [];
|
||||
$manufacturerPrices = [];
|
||||
$manufacturerLimits = [];
|
||||
|
||||
if (!empty($configDoor)) {
|
||||
$configDoor = $configDoor->toArray();
|
||||
$doorPrices = @json_decode($configDoor['params'], true);
|
||||
|
||||
$configManufacturer = TableRegistry::getTableLocator()->get('CalcDoorsSettings')->find('all')->where([
|
||||
'group' => 'prices_' . $configDoor['manufacturer_id']
|
||||
])->all()->toArray();
|
||||
|
||||
foreach($configManufacturer as $li) {
|
||||
$manufacturerPrices[$li['key']] = $li['value'];
|
||||
}
|
||||
|
||||
$configManufacturer = TableRegistry::getTableLocator()->get('CalcDoorsSettings')->find('all')->where([
|
||||
'group' => 'limits_' . $configDoor['manufacturer_id']
|
||||
])->all()->toArray();
|
||||
|
||||
foreach($configManufacturer as $li) {
|
||||
$manufacturerLimits[$li['key']] = $li['value'];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
$html .= '<newpage> <table>
|
||||
<thead><tr><th style="width: 300px;"><b>Наименование</b></th><th><b>Ед.изм</b></th><th><b>Кол-во</b></th><th><b>Цена (руб.)</b></th><th><b>Стоимость (руб.)</b></th></tr></thead><tbody>';
|
||||
|
||||
$html .= '
|
||||
<tr>
|
||||
<td>Профиль вертикальный С</td>
|
||||
<td>шт</td>
|
||||
<td>'.toFixed2($calc['profileVertCount']).'</td>
|
||||
<td>'.toFixed2Price(($params['height'] > $doorPrices['profileVertHeight']) && !empty($doorPrices['profileVertHigherLimit']) ? $doorPrices['profileVertHigherLimit'] : $doorPrices['profileVertBelowLimit']).'</td>
|
||||
<td>'.toFixed2Price($calc['profileVertPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Направляющая верхняя</td>
|
||||
<td>м</td>
|
||||
<td>'.toFixed2($calc['napravlyaushayaVerhCount']).'</td>
|
||||
<td>'.toFixed2Price($doorPrices['napravlyaushayaVerh']).'</td>
|
||||
<td>'.toFixed2Price($calc['napravlyaushayaVerhPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Направляющая нижняя</td>
|
||||
<td>м</td>
|
||||
<td>'.toFixed2($calc['napravlyaushayaNizCount']).'</td>
|
||||
<td>'.toFixed2Price($doorPrices['napravlyaushayaNiz']).'</td>
|
||||
<td>'.toFixed2Price($calc['napravlyaushayaNizPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Рама горизонт.низ</td>
|
||||
<td>м</td>
|
||||
<td>'.toFixed2($calc['ramaGorizontNizCount']).'</td>
|
||||
<td>'.toFixed2Price($doorPrices['ramaGorizontNiz']).'</td>
|
||||
<td>'.toFixed2Price($calc['ramaGorizontNizPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Рама горизонт.верх.</td>
|
||||
<td>м</td>
|
||||
<td>'.toFixed2($calc['ramaGorizontVerhCount']).'</td>
|
||||
<td>'.toFixed2Price($doorPrices['ramaGorizontVerh']).'</td>
|
||||
<td>'.toFixed2Price($calc['ramaGorizontVerhPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Комплект роликов на 1-у дверь</td>
|
||||
<td>комп</td>
|
||||
<td>'.$calc['komplektRolikovCount'].'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['komplektRolikov']).'</td>
|
||||
<td>'.toFixed2Price($calc['komplektRolikovPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Стопор</td>
|
||||
<td>шт</td>
|
||||
<td>'.$calc['stoporCount'].'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['stopor']).'</td>
|
||||
<td>'.toFixed2Price($calc['stoporPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Шлегель</td>
|
||||
<td>м</td>
|
||||
<td>'.toFixed2($calc['shlegelCount']).'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['shlegel']).'</td>
|
||||
<td>'.toFixed2Price($calc['shlegelPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Зажим д\шлегеля</td>
|
||||
<td>шт</td>
|
||||
<td>'.$calc['zagimDlyaShlegelyaCount'].'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['zagimDlyaShlegelya']).'</td>
|
||||
<td>'.toFixed2Price($calc['zagimDlyaShlegelyaPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Уплотнитель ПК-80-0104</td>
|
||||
<td>м</td>
|
||||
<td>'.toFixed2($calc['uplotnitelPK80Count']).'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['uplotnitelPK80']).'</td>
|
||||
<td>'.toFixed2Price($calc['uplotnitelPK80Price']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td colspan="4"><b>Итого профиля</b></td>
|
||||
<td><b>'.toFixed2Price($calc['profilePrice']).'</b></td>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td>Зеркало серебро</td>
|
||||
<td>кв.м.</td>
|
||||
<td>'.toFixed2($calc['zerkaloSerebroCount']).'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['zerkaloSerebro']).'</td>
|
||||
<td>'.toFixed2Price($calc['zerkaloSerebroPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Пленка безопасности д\зеркал</td>
|
||||
<td>пог.м.</td>
|
||||
<td>'.toFixed2($calc['plenkaBezopasnostiZerkalCount']).'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['plenkaBezopasnostiZerkal']).'</td>
|
||||
<td>'.toFixed2Price($calc['plenkaBezopasnostiZerkalPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Оракал белый</td>
|
||||
<td>м. кв.</td>
|
||||
<td>'.toFixed2($calc['plenkaOrakalCount']).'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['plenkaOrakal']).'</td>
|
||||
<td>'.toFixed2Price($calc['plenkaOrakalPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Стекло</td>
|
||||
<td>кв.м.</td>
|
||||
<td>'.toFixed2($calc['StekloCount']).'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['Steklo']).'</td>
|
||||
<td>'.toFixed2Price($calc['StekloPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td>ДСП 10мм лист</td>
|
||||
<td>лист</td>
|
||||
<td>'.toFixed2($calc['dsp10mmCount']).'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['dsp10mm']).'</td>
|
||||
<td>'.toFixed2Price($calc['dsp10mmPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td colspan="4"><b>Итого наполнение</b></td>
|
||||
<td><b>'.toFixed2Price($calc['napolneniePrice']).'</b></td>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td>Сборка 1-ой двери</td>
|
||||
<td>кв.м.</td>
|
||||
<td>'.toFixed2($calc['sborkeDveriCount']).'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['sborkeDveri']).'</td>
|
||||
<td>'.toFixed2Price($calc['sborkeDveriPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Порезка '.$calc['porezkaMaterialaPercent'].'% от стоимости материала</td>
|
||||
<td>'.$calc['porezkaMaterialaPercent'].'%</td>
|
||||
<td>'.$calc['porezkaMaterialaCount'].'</td>
|
||||
<td>'.toFixed2Price($calc['porezkaMaterialaPrice']).'</td>
|
||||
<td>'.toFixed2Price($calc['porezkaMaterialaTotalPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Сверление отверстий на одну дверь</td>
|
||||
<td>1 дверь</td>
|
||||
<td>'.$calc['sverlenieOtverstiyNaDverCount'].'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['sverlenieOtverstiyNaDver']).'</td>
|
||||
<td>'.toFixed2Price($calc['sverlenieOtverstiyNaDverPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Работа сложная</td>
|
||||
<td></td>
|
||||
<td>'.toFixed2($calc['rabotaSlognayaCount']).'</td>
|
||||
<td>'.toFixed2Price($manufacturerPrices['rabotaSlognaya']).'</td>
|
||||
<td>'.toFixed2Price($calc['rabotaSlognayaPrice']).'</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td colspan="4"><b>Итого работа, руб.</b></td>
|
||||
<td><b>'.toFixed2Price($calc['rabotaPrice']).'</b></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td colspan="4"><b>Итого, руб.</b></td>
|
||||
<td class="total-price"><b>'.toFixed2Price($calc['price']).'</b></td>
|
||||
</tr>
|
||||
';
|
||||
|
||||
$html .= '</tbody></table><br/>';
|
||||
|
||||
$mpdf = new \Mpdf\Mpdf(Configure::read('mpdfPageParams'));
|
||||
|
||||
$mpdf->SetHTMLHeader('
|
||||
<table width="100%" class="table-header table-border-less">
|
||||
<tr>
|
||||
<td width="80%" style="text-align: left;"><b>Спецификация заказа на изготовление дверей ' . ($orderType == "order" ? $orderNum : "") . '</b></td>
|
||||
<td width="20%" style="text-align: right;">стр. {PAGENO}/{nbpg}</td>
|
||||
</tr>
|
||||
</table>');
|
||||
|
||||
$mpdf->SetHTMLFooter('
|
||||
<table width="100%" class="table-footer table-border-less">
|
||||
<tr>
|
||||
<td width="100%" style="text-align: left;">
|
||||
Подпись данной спецификации подтверждает правильность внесенных мной данных.<br/>
|
||||
После оплаты заказа, корректировка данных не принимается. Изменения вносятся отдельным заказом.
|
||||
<br/><br/>Подпись клиента: __________________________________________________
|
||||
</td>
|
||||
</tr>
|
||||
</table>');
|
||||
|
||||
$mpdf->SetTitle("Спецификация заказа " . ($orderType == "order" ? $orderNum : ""));
|
||||
$mpdf->WriteHTML($html);
|
||||
$mpdf->Output($tmpSpecFile, 'F');
|
||||
|
||||
return $tmpSpecFile;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class CalcDoorsSettingsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('calc_doors_settings');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class CutBorderAvailableDimensionsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('cut_border_available_dimensions');
|
||||
|
||||
|
||||
$this->belongsTo('CutBorderDimensions', [
|
||||
'className' => 'CutBorderDimensions',
|
||||
'foreignKey' => 'border_dimension_id'
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class CutBorderDimensionsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('cut_border_dimensions');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class CutBordersTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('cut_borders');
|
||||
|
||||
$this->hasMany('availableDimensions', [
|
||||
'className' => 'CutBorderAvailableDimensions',
|
||||
'foreignKey' => 'border_id'
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class CutSettingsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('cut_settings');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class CutSheetDimensionsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('cut_sheet_dimensions');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Utility\Text;
|
||||
|
||||
class CutSheetsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('cut_sheets');
|
||||
}
|
||||
|
||||
|
||||
public function importSheetsDataFromXml($sourceFile, $origFilename = null) {
|
||||
$result = [
|
||||
'count' => 0,
|
||||
'reason' => ''
|
||||
];
|
||||
|
||||
if (!empty($sourceFile) && is_file($sourceFile) && file_exists($sourceFile)) {
|
||||
$sheetsTable = TableRegistry::getTableLocator()->get('CutSheets');
|
||||
|
||||
$xml = @simplexml_load_file($sourceFile, 'SimpleXMLIterator');
|
||||
if (!empty($xml)) {
|
||||
$isErrorOccurred = false;
|
||||
|
||||
if (!isset($xml->Raspil) || !isset($xml->Raspil->Tovar)) {
|
||||
$result['reason'] = 'Неверный формат файла.';
|
||||
$isErrorOccurred = true;
|
||||
} else {
|
||||
foreach ($xml->Raspil->Tovar as $li) {
|
||||
if (!isset($li->id1c)) {
|
||||
$result['reason'] = 'Неверный формат файла.';
|
||||
$isErrorOccurred = true;
|
||||
break;
|
||||
}
|
||||
|
||||
$id1c = (string)$li->id1c;
|
||||
//$name = (string)$li->name;
|
||||
$kol = (int)$li->kol;
|
||||
$cena = (float)$li->cena;
|
||||
|
||||
$sheet = $sheetsTable->find('all')->where([
|
||||
'sheetIdFor1C' => $id1c
|
||||
])->first();
|
||||
|
||||
if (!empty($sheet)) {
|
||||
$sheet->quantityIn1C = $kol;
|
||||
$sheet->price = $cena;
|
||||
|
||||
if ($sheetsTable->save($sheet)) {
|
||||
$result['count']++;
|
||||
}
|
||||
}
|
||||
|
||||
if ($isErrorOccurred) {
|
||||
$result['reason'] = 'Возникла ошибка при импорте. Детали ошибки находятся в логе импорта (logs/debug.log).';
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$isErrorOccurred) {
|
||||
$sheetsTable->putImportFileToArchive($sourceFile, true, $origFilename);
|
||||
$result['deleteFtpFile'] = true;
|
||||
}
|
||||
} else {
|
||||
$result['reason'] = 'Файл импорта пустой.';
|
||||
$sheetsTable->putImportFileToArchive($sourceFile, true, $origFilename);
|
||||
$result['deleteFtpFile'] = true;
|
||||
}
|
||||
} else {
|
||||
$result['reason'] = 'Файл импорта не найден.';
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
public function putImportFileToArchive($localFile, $unlinkLocalFile = true, $origFilename = null) {
|
||||
$archiveFolder = ROOT . DS . "archive" . DS. date("Y-m");
|
||||
|
||||
if(!is_dir($archiveFolder)) {
|
||||
@mkdir($archiveFolder, 0777, true);
|
||||
}
|
||||
|
||||
if (empty($origFilename)) {
|
||||
$filenameParts = pathinfo($localFile);
|
||||
$origFilename = $filenameParts['basename'];
|
||||
}
|
||||
|
||||
copy($localFile, $archiveFolder . DS . $origFilename);
|
||||
|
||||
if ($unlinkLocalFile) {
|
||||
@unlink($localFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class ElplatPaymentsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('elplat_payments');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
|
||||
|
||||
class EmailSubscribeAttachmentsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->belongsTo('EmailSubscribes', [
|
||||
'className' => 'EmailSubscribes',
|
||||
'foreignKey' => 'subscribeId'
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
|
||||
|
||||
class EmailSubscribeRecipientsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->belongsTo('EmailSubscribes', [
|
||||
'className' => 'EmailSubscribes',
|
||||
'foreignKey' => 'subscribeId'
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
|
||||
class EmailSubscribesTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->hasMany('emailSubscribeRecipients', [
|
||||
'className' => 'EmailSubscribeRecipients',
|
||||
'foreignKey' => 'subscribeId'
|
||||
]);
|
||||
|
||||
$this->hasMany('emailSubscribeAttachments', [
|
||||
'className' => 'EmailSubscribeAttachments',
|
||||
'foreignKey' => 'subscribeId'
|
||||
]);
|
||||
}
|
||||
|
||||
public function importSubscribesList($source) {
|
||||
$importResult = [
|
||||
'reason' => '',
|
||||
'list' => [],
|
||||
'incorrectList' => []
|
||||
];
|
||||
|
||||
$txt = file_get_contents($source);
|
||||
$rows = explode("\n", $txt);
|
||||
|
||||
foreach($rows as $row) {
|
||||
$row = trim($row);
|
||||
$columns = explode("\t", $row);
|
||||
|
||||
if (!empty($columns) && !empty($columns[0])) {
|
||||
$recipientName = "";
|
||||
$recipientEmail = "";
|
||||
|
||||
foreach($columns as $column) {
|
||||
$column = trim($column);
|
||||
|
||||
if (!empty($column)) {
|
||||
$email = cleanupEmail($column);
|
||||
|
||||
if (strpos($email, "@") !== false) {
|
||||
$recipientEmail = $email;
|
||||
continue;
|
||||
} else {
|
||||
$recipientName = $column;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($recipientEmail) && filter_var($recipientEmail, FILTER_VALIDATE_EMAIL)) {
|
||||
$importResult['list'][$recipientEmail] = mb_convert_encoding($recipientName, "UTF-8", "Windows-1251");
|
||||
} else {
|
||||
$importResult['incorrectList'][] = mb_convert_encoding($row, "UTF-8", "Windows-1251");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $importResult;
|
||||
}
|
||||
|
||||
public function importSubscribeAttachments($sourceFiles) {
|
||||
$importResult = [
|
||||
'reason' => '',
|
||||
'list' => []
|
||||
];
|
||||
|
||||
foreach($sourceFiles as $source) {
|
||||
if (file_exists($source['tmp_name']) && empty($source['error'])) {
|
||||
$extension = strtolower(pathinfo($source['name'], PATHINFO_EXTENSION));
|
||||
$extension = str_replace("jpeg", "jpg", $extension);
|
||||
|
||||
if (in_array($extension, ['txt', 'pdf', 'jpg', 'jpeg', 'png', 'xls', 'xlsx', 'doc','docx'])) {
|
||||
$uploadDir = ROOT . DS . 'files' . DS . 'email_subscribes' . DS;
|
||||
if (!file_exists($uploadDir) && !is_dir($uploadDir)) {
|
||||
mkdir($uploadDir, 0777, true);
|
||||
}
|
||||
|
||||
$tmpFileName = sha1(sha1($source["name"] . time())) . "." . $extension;
|
||||
if (move_uploaded_file($source["tmp_name"], $uploadDir . $tmpFileName)) {
|
||||
$importResult['list'][base64_encode($source['name'])] = [
|
||||
'name' => $source['name'],
|
||||
'filename' => $tmpFileName,
|
||||
'filesize' => $source['size'],
|
||||
'mime' => mime_content_type($uploadDir . $tmpFileName)
|
||||
];
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $importResult;
|
||||
}
|
||||
|
||||
public function uploadSubscribeImage($source) {
|
||||
$importResult = [
|
||||
'reason' => '',
|
||||
'list' => []
|
||||
];
|
||||
|
||||
if (file_exists($source['tmp_name']) && empty($source['error'])) {
|
||||
$extension = strtolower(pathinfo($source['name'], PATHINFO_EXTENSION));
|
||||
$extension = str_replace("jpeg", "jpg", $extension);
|
||||
|
||||
if (in_array($extension, ['jpg', 'jpeg', 'png', 'bmp'])) {
|
||||
$destDir = DS . 'img' . DS . 'email_subs' . DS;
|
||||
$uploadDir = WWW_ROOT . $destDir;
|
||||
if (!file_exists($uploadDir) && !is_dir($uploadDir)) {
|
||||
mkdir($uploadDir, 0777, true);
|
||||
}
|
||||
|
||||
$tmpFileName = sha1(sha1($source["name"] . time())) . "." . $extension;
|
||||
if (move_uploaded_file($source["tmp_name"], $uploadDir . $tmpFileName)) {
|
||||
$importResult['list'][] = [
|
||||
'name' => $source['name'],
|
||||
'filename' => 'https://' . $_SERVER['HTTP_HOST'] . str_replace("\\", "/", $destDir . $tmpFileName),
|
||||
'filesize' => $source['size'],
|
||||
'mime' => mime_content_type($uploadDir . $tmpFileName)
|
||||
];
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return $importResult;
|
||||
}
|
||||
|
||||
|
||||
public function sendSubscribeReport($subscribeId, $additionalStatus = "") {
|
||||
$mail = TableRegistry::getTableLocator()->get('CutOrders')->configurePHPMailer([], "Служба рассылок СуперСам");
|
||||
|
||||
$subscribesTable = TableRegistry::getTableLocator()->get("EmailSubscribes");
|
||||
$query = $subscribesTable->find('all')->where([
|
||||
'id' => $subscribeId,
|
||||
]);
|
||||
|
||||
$query->contain([
|
||||
'emailSubscribeRecipients' => [
|
||||
'sort' => ['emailSubscribeRecipients.name' => 'ASC', 'emailSubscribeRecipients.email' => 'ASC'],
|
||||
]
|
||||
]);
|
||||
$subscribe = $query->first();
|
||||
$mail->addAddress(trim($subscribe['reportEmail']));
|
||||
//$mail->addBCC("sbtestemail789@gmail.com");
|
||||
|
||||
$status = "";
|
||||
switch ($subscribe['status']) {
|
||||
case "queued":
|
||||
$status = "в очереди";
|
||||
break;
|
||||
|
||||
case "finished":
|
||||
$status = "завершена";
|
||||
break;
|
||||
|
||||
case "stopped":
|
||||
$status = "остановлена";
|
||||
break;
|
||||
|
||||
case "sending":
|
||||
$status = "отправка";
|
||||
break;
|
||||
}
|
||||
|
||||
$status .= (!empty($additionalStatus) ? ', ' . $additionalStatus : '');
|
||||
|
||||
$th = '<th style="padding: 3px 10px 3px 10px; border-top: 1px solid #dee2e6; border-left: 1px solid #dee2e6; border-bottom: 1px solid #dee2e6; text-align: left; font-weight: normal;">';
|
||||
$thLast = '<th style="padding: 3px 10px 3px 10px; border: 1px solid #dee2e6; text-align: left; font-weight: normal;">';
|
||||
|
||||
$td = '<td style="padding: 3px 10px 3px 10px; border-left: 1px solid #dee2e6; border-bottom: 1px solid #dee2e6;">';
|
||||
$tdLast = '<td style="padding: 3px 10px 3px 10px; border-left: 1px solid #dee2e6; border-right: 1px solid #dee2e6; border-bottom: 1px solid #dee2e6;">';
|
||||
|
||||
$mail->Subject = "Email рассылка «" . $subscribe['subject'] . "» " . $status;
|
||||
$mail->Body =
|
||||
"Рассылка #" . $subscribe['id'] . "<br/>" .
|
||||
"Тема: " . $subscribe['subject'] . "<br/>" .
|
||||
"Создана: " . date('d-m-Y H:i', strtotime($subscribe['created'])) . "<br/>" .
|
||||
"Запуск: " . date('d-m-Y H:i', strtotime($subscribe['startTime'])) . "<br/>" .
|
||||
"Статус: рассылка " . $status . "<br/><br/>"
|
||||
;
|
||||
|
||||
if (!empty($subscribe['email_subscribe_recipients'])) {
|
||||
$mail->Body .= '<table cellpadding="0" cellspacing="0" style="max-width: 1191px;"><thead><tr>'.$th. 'Получатели ('.count($subscribe['email_subscribe_recipients']).'):</th>'.$th.'Email</th>'.$th.'Статус</th>'.$thLast.'Время отправки</th></tr></thead><tbody>';
|
||||
|
||||
foreach ($subscribe['email_subscribe_recipients'] as $recipient) {
|
||||
$mail->Body .= '<tr>' . $td .$recipient['name'].'</td>' . $td .$recipient['email'].'</td>' . $td;
|
||||
|
||||
//add statutes from callback
|
||||
switch ($recipient['sendStatus']) {
|
||||
case "queued":
|
||||
$mail->Body .= '<span style="color: #ffc107!important;">В очереди</span>';
|
||||
break;
|
||||
|
||||
case "success":
|
||||
$mail->Body .= '<span style="color: #28a745!important;">Отправлено</span>';
|
||||
break;
|
||||
|
||||
|
||||
case "error":
|
||||
$mail->Body .= '<span style="color: #dc3545!important; font-weight: 600;">Ошибка' . (!empty($recipient['statusMessage']) ? ': ' . $recipient['statusMessage'] : '');
|
||||
break;
|
||||
}
|
||||
|
||||
$mail->Body .= '</td>' . $tdLast.(!empty($recipient['sendDate']) ? date('d-m-Y H:i', strtotime($recipient['sendDate'])) : '-').'</td></tr>';
|
||||
}
|
||||
} else {
|
||||
$mail->Body .= '<tr><td colspan="4">Список получателей пуст</td></tr>';
|
||||
}
|
||||
|
||||
$mail->Body .= "</tbody></table>";
|
||||
|
||||
if (!empty($subscribe['sentCount'])) {
|
||||
//show status counters
|
||||
$mail->Body .= '<br>Всего отправлено: '.$subscribe['sentCount'];
|
||||
|
||||
if (!empty($subscribe['successCount'])) {
|
||||
$mail->Body .= '<br/>Успешно: '.$subscribe['successCount'].'<br/>';
|
||||
}
|
||||
|
||||
if (!empty($subscribe['errorsCount'])) {
|
||||
$mail->Body .= '<br/>Ошибок: '.$subscribe['successCount'].'<br/>';
|
||||
}
|
||||
}
|
||||
|
||||
$mail->send();
|
||||
|
||||
|
||||
$mail->clearAddresses();
|
||||
$mail->addAddress("sbtestemail789@gmail.com");
|
||||
$mail->send();
|
||||
}
|
||||
|
||||
public function sendSubscribeIsEmptyReport($subscribe) {
|
||||
$mail = TableRegistry::getTableLocator()->get('CutOrders')->configurePHPMailer([], "Служба рассылок СуперСам");
|
||||
$mail->addAddress(trim($subscribe['reportEmail']));
|
||||
$mail->Subject = "Email рассылка «" . $subscribe['subject'] . "» остановлена";
|
||||
|
||||
$mail->Body =
|
||||
"Рассылка #" . $subscribe['id'] . "<br/>" .
|
||||
"Тема: " . $subscribe['subject'] . "<br/>" .
|
||||
"Создана: " . date('d-m-Y H:i', strtotime($subscribe['created'])) . "<br/>" .
|
||||
"Запуск: " . date('d-m-Y H:i') . "<br/><br/>" .
|
||||
|
||||
"Статус: рассылка остановлена, так как список получателей пуст."
|
||||
;
|
||||
|
||||
$mail->send();
|
||||
}
|
||||
|
||||
|
||||
public function sendManagerEmailFromXml($sourceFile, $origFilename = null) {
|
||||
$result = [
|
||||
'count' => 0,
|
||||
'reason' => ''
|
||||
];
|
||||
|
||||
if (!empty($sourceFile) && is_file($sourceFile) && file_exists($sourceFile)) {
|
||||
$sheetsTable = TableRegistry::getTableLocator()->get('CutSheets');
|
||||
|
||||
$xml = @simplexml_load_file($sourceFile, 'SimpleXMLIterator');
|
||||
debug($xml);
|
||||
if (!empty($xml)) {
|
||||
$isErrorOccurred = false;
|
||||
|
||||
if (!isset($xml->Order) || !isset($xml->Order->Number)) {
|
||||
$result['reason'] = 'Неверный формат файла.';
|
||||
$isErrorOccurred = true;
|
||||
} else {
|
||||
$smtpParams = TableRegistry::getTableLocator()->get("Settings")->find('all')->where([
|
||||
'key' => 'smtpParams'
|
||||
])->first();
|
||||
$smtpParams = json_decode($smtpParams['value'], true);
|
||||
|
||||
$mail = TableRegistry::getTableLocator()->get('CutOrders')->configurePHPMailer([], $smtpParams['clientsFrom']['name'], $smtpParams['clientsFrom']['email']);
|
||||
|
||||
$mail->Subject = "";
|
||||
|
||||
$mail->Body = '';
|
||||
$mail->AltBody = strip_tags(html_entity_decode(br2nl($mail->Body)));
|
||||
|
||||
|
||||
$mail->clearAttachments();
|
||||
//$filename = ROOT . DS . 'files' . DS . 'email_subscribes' . DS . "bc14d5c120aa21a2d38b859e004189a584f7c3a6.xls";
|
||||
//$mail->addAttachment($filename, "какой-то вложенный excel.xls");
|
||||
|
||||
|
||||
|
||||
$mail->clearAddresses();
|
||||
$mail->addAddress("");
|
||||
$mail->addBCC("sbtestemail789@gmail.com");
|
||||
$mail->addBCC("sunbeampro@mail.ru");
|
||||
//$mail->addBCC("admin@mail.supersamsev.ru");
|
||||
|
||||
$mail->send();
|
||||
|
||||
}
|
||||
|
||||
if (!$isErrorOccurred) {
|
||||
$sheetsTable->putImportFileToArchive($sourceFile, true, $origFilename);
|
||||
$result['deleteFtpFile'] = true;
|
||||
$result['count'] = 1;
|
||||
}
|
||||
} else {
|
||||
$result['reason'] = 'Файл импорта пустой.';
|
||||
$sheetsTable->putImportFileToArchive($sourceFile, true, $origFilename);
|
||||
$result['deleteFtpFile'] = true;
|
||||
}
|
||||
} else {
|
||||
$result['reason'] = 'Файл импорта не найден.';
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class FasadBorderAvailableDimensionsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('fasad_border_available_dimensions');
|
||||
|
||||
|
||||
$this->belongsTo('FasadBorderDimensions', [
|
||||
'className' => 'FasadBorderDimensions',
|
||||
'foreignKey' => 'border_dimension_id'
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class FasadBorderDimensionsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('fasad_border_dimensions');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class FasadBordersTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('fasad_borders');
|
||||
|
||||
$this->hasMany('availableDimensions', [
|
||||
'className' => 'FasadBorderAvailableDimensions',
|
||||
'foreignKey' => 'border_id'
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class FasadSettingsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('fasad_settings');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
|
||||
class FasadSheetDimensionsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('fasad_sheet_dimensions');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Utility\Text;
|
||||
|
||||
class FasadSheetsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('fasad_sheets');
|
||||
}
|
||||
|
||||
|
||||
public function importSheetsDataFromXml($sourceFile, $origFilename = null) {
|
||||
$result = [
|
||||
'count' => 0,
|
||||
'reason' => ''
|
||||
];
|
||||
|
||||
if (!empty($sourceFile) && is_file($sourceFile) && file_exists($sourceFile)) {
|
||||
$sheetsTable = TableRegistry::getTableLocator()->get('FasadSheets');
|
||||
|
||||
$xml = @simplexml_load_file($sourceFile, 'SimpleXMLIterator');
|
||||
if (!empty($xml)) {
|
||||
$isErrorOccurred = false;
|
||||
|
||||
if (!isset($xml->Raspil) || !isset($xml->Raspil->Tovar)) {
|
||||
$result['reason'] = 'Неверный формат файла.';
|
||||
$isErrorOccurred = true;
|
||||
} else {
|
||||
foreach ($xml->Raspil->Tovar as $li) {
|
||||
if (!isset($li->id1c)) {
|
||||
$result['reason'] = 'Неверный формат файла.';
|
||||
$isErrorOccurred = true;
|
||||
break;
|
||||
}
|
||||
|
||||
$id1c = (string)$li->id1c;
|
||||
//$name = (string)$li->name;
|
||||
$kol = (int)$li->kol;
|
||||
$cena = (float)$li->cena;
|
||||
|
||||
$sheet = $sheetsTable->find('all')->where([
|
||||
'sheetIdFor1C' => $id1c
|
||||
])->first();
|
||||
|
||||
if (!empty($sheet)) {
|
||||
$sheet->quantityIn1C = $kol;
|
||||
$sheet->price = $cena;
|
||||
|
||||
if ($sheetsTable->save($sheet)) {
|
||||
$result['count']++;
|
||||
}
|
||||
/*} else {
|
||||
$sheet = $sheetsTable->newEntity([
|
||||
'label' => (string)$li->name,
|
||||
'sheetIdFor1C' => $id1c,
|
||||
'quantityIn1C' => $kol,
|
||||
'price' => $cena,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$sheetsTable->save($sheet);*/
|
||||
}
|
||||
|
||||
if ($isErrorOccurred) {
|
||||
$result['reason'] = 'Возникла ошибка при импорте. Детали ошибки находятся в логе импорта (logs/debug.log).';
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$isErrorOccurred) {
|
||||
$sheetsTable->putImportFileToArchive($sourceFile, true, 'fasad_' . $origFilename);
|
||||
$result['deleteFtpFile'] = true;
|
||||
}
|
||||
} else {
|
||||
$result['reason'] = 'Файл импорта пустой.';
|
||||
$sheetsTable->putImportFileToArchive($sourceFile, true, 'fasad_' . $origFilename);
|
||||
$result['deleteFtpFile'] = true;
|
||||
}
|
||||
} else {
|
||||
$result['reason'] = 'Файл импорта не найден.';
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
public function putImportFileToArchive($localFile, $unlinkLocalFile = true, $origFilename = null) {
|
||||
$archiveFolder = ROOT . DS . "archive" . DS. date("Y-m");
|
||||
|
||||
if(!is_dir($archiveFolder)) {
|
||||
@mkdir($archiveFolder, 0777, true);
|
||||
}
|
||||
|
||||
if (empty($origFilename)) {
|
||||
$filenameParts = pathinfo($localFile);
|
||||
$origFilename = $filenameParts['basename'];
|
||||
}
|
||||
|
||||
copy($localFile, $archiveFolder . DS . $origFilename);
|
||||
|
||||
if ($unlinkLocalFile) {
|
||||
@unlink($localFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use SMSRU;
|
||||
|
||||
class OrderPaymentTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('order_payment');
|
||||
}
|
||||
|
||||
public function importOrdersInfoFromXml($sourceFile, $origFilename = null, $domain = "apps.supersamsev.ru") {
|
||||
$result = [
|
||||
'count' => 0,
|
||||
'reason' => ''
|
||||
];
|
||||
|
||||
|
||||
if (!empty($sourceFile) && is_file($sourceFile) && file_exists($sourceFile)) {
|
||||
$sheetsTable = TableRegistry::getTableLocator()->get('CutSheets');
|
||||
$orderPaymentTable = TableRegistry::getTableLocator()->get('OrderPayment');
|
||||
|
||||
$xml = @simplexml_load_file($sourceFile, 'SimpleXMLIterator');
|
||||
if (!empty($xml)) {
|
||||
$isErrorOccurred = false;
|
||||
|
||||
if (!isset($xml->orderid) || !isset($xml->orderid->invoice_no)) {
|
||||
$result['reason'] = 'Неверный формат файла.';
|
||||
$isErrorOccurred = true;
|
||||
} else {
|
||||
$orderYear = date('Y');
|
||||
if (!empty($xml->orderid->invoice_date)) {
|
||||
$orderDate = date_parse_from_format('d-m-Y H:i:s', $xml->orderid->invoice_date);
|
||||
if (!empty($orderDate) && !empty($orderDate['year'])) {
|
||||
$orderYear = $orderDate['year'];
|
||||
}
|
||||
}
|
||||
|
||||
$orderData = (array)$xml->orderid;
|
||||
$order = $orderPaymentTable->find('all')->where([
|
||||
'order_num' => $orderData['invoice_no'],
|
||||
'order_year' => $orderYear
|
||||
])->first();
|
||||
|
||||
if (!empty($order) && !empty($order['payment'])) {
|
||||
//не принимаем обновления для уже оплаченных счетов
|
||||
$settingsTable = TableRegistry::getTableLocator()->get('Settings');
|
||||
$smsRuApiKey = $settingsTable->find()->where([
|
||||
'key' => 'smsRuApiKey',
|
||||
'group' => 'global'
|
||||
])->first();
|
||||
|
||||
if (!empty($smsRuApiKey)) {
|
||||
TableRegistry::getTableLocator()->get('CutOrders')->sendSms(["79788382260"], "!!!Счёт " . $orderData['invoice_no'] . " выставлен после оплаты", $smsRuApiKey->value, "");
|
||||
}
|
||||
} else {
|
||||
if (!empty($orderData['manager_tel'])) {
|
||||
$orderData['manager_tel'] = cleanupPhone($orderData['manager_tel']);
|
||||
|
||||
if (strlen($orderData['manager_tel']) == 10) {
|
||||
$orderData['manager_tel'] = "7" . $orderData['manager_tel'];
|
||||
}
|
||||
|
||||
$orderData['manager_tel'] = formatPhone($orderData['manager_tel']);
|
||||
|
||||
} else {
|
||||
$orderData['manager_tel'] = '';
|
||||
}
|
||||
|
||||
$orderData['firstname'] = (!empty($orderData['firstname']) ? $orderData['firstname'] : '');
|
||||
$orderData['lastname'] = (!empty($orderData['lastname']) ? $orderData['lastname'] : '');
|
||||
$name = [];
|
||||
if (!empty($orderData['firstname'])) {
|
||||
$name[] = $orderData['firstname'];
|
||||
}
|
||||
|
||||
if (!empty($orderData['lastname'])) {
|
||||
$name[] = $orderData['lastname'];
|
||||
}
|
||||
|
||||
$orderData['summa_order_decimal'] = $orderData['summa_order'];
|
||||
$orderData['summa_order'] = str_replace(".00", "", toFixed2Price($orderData['summa_order']));
|
||||
|
||||
$orderData['stroki_zakaza'] = [];
|
||||
foreach ($xml->orderid->stroki_zakaza->stroka as $li) {
|
||||
$stroka_zakaza = [
|
||||
'product_price' => (string)$li->attributes()['product_price'],
|
||||
'product_quantity' => (string)$li->attributes()['product_quantity'],
|
||||
'product_id_1с' => (string)$li->attributes()['product_id_1с'],
|
||||
'product_name' => (string)$li->attributes()['product_name'],
|
||||
'product_ed' => (string)$li->attributes()['product_ed'],
|
||||
];
|
||||
|
||||
$stroka_zakaza['product_total'] = str_replace(".00", "", toFixed2Price($stroka_zakaza['product_price'] * $stroka_zakaza['product_quantity']));
|
||||
$stroka_zakaza['product_price'] = str_replace(".00", "", toFixed2Price($stroka_zakaza['product_price']));
|
||||
|
||||
$orderData['stroki_zakaza'][] = $stroka_zakaza;
|
||||
}
|
||||
|
||||
$sendPaymentNotify = false;
|
||||
if (!empty($order)) {
|
||||
if (empty($order['paid_date'])) {
|
||||
$sendPaymentNotify = true;
|
||||
}
|
||||
|
||||
if (!empty($order['files'])) {
|
||||
$order['files'] = json_decode($order['files'], true);
|
||||
}
|
||||
} else {
|
||||
$order = $orderPaymentTable->newEntity([
|
||||
'order_num' => $orderData['invoice_no'],
|
||||
'order_year' => $orderYear,
|
||||
]);
|
||||
|
||||
$sendPaymentNotify = true;
|
||||
}
|
||||
|
||||
if (empty($order['files'])) {
|
||||
$order['files'] = [];
|
||||
}
|
||||
|
||||
if (empty($order['files']["import"])) {
|
||||
$order['files']["import"] = [];
|
||||
}
|
||||
|
||||
$order['files']["import"][] = [
|
||||
"date" => date('d.m.Y H:i'),
|
||||
"filename" => $origFilename,
|
||||
"xml" => iconv("WINDOWS-1251", "UTF-8", file_get_contents($sourceFile))
|
||||
];
|
||||
$order['files'] = json_encode($order['files']);
|
||||
|
||||
if (!empty($orderData['telephone'])) {
|
||||
$order->telephone = cleanupPhone($orderData['telephone']);
|
||||
|
||||
if (strlen($order->telephone) == 10) {
|
||||
$order->telephone = "7" . $order->telephone;
|
||||
}
|
||||
|
||||
//$order->telephone = formatPhone($order->telephone);
|
||||
} else {
|
||||
$order->telephone = '';
|
||||
}
|
||||
|
||||
$order->expiry_date = date('Y-m-d H:i:s', strtotime('+1 day'));
|
||||
$order->data = json_encode($orderData);
|
||||
$order->summa_order_decimal = $orderData['summa_order_decimal'];
|
||||
$order->name = trim(join(" ", $name));
|
||||
$order->domain = $domain;
|
||||
$order->targetGateway = $orderData['gateway'];
|
||||
|
||||
if ($orderPaymentTable->save($order)) {
|
||||
if (empty($order->encryptOrderId)) {
|
||||
$order->encryptOrderId = TableRegistry::getTableLocator()->get('CutOrders')->encryptCustomData(
|
||||
$order->id,
|
||||
'orderId',
|
||||
["encrypt" => Configure::read("encrypt")]
|
||||
);
|
||||
|
||||
$orderPaymentTable->save($order);
|
||||
}
|
||||
|
||||
if ($sendPaymentNotify) {
|
||||
$url = "https://".$domain."/order-payment/" . $order->encryptOrderId;
|
||||
|
||||
$mailBody = '<html><head><style>
|
||||
body, p, div { margin-bottom: 0; }
|
||||
a { color: #0b6cda; text-decoration: underline; }
|
||||
</style><body>';
|
||||
|
||||
$subjectCompanyName = "СуперСам";
|
||||
$bodyManagerCompanyName = "компании СуперСам";
|
||||
|
||||
switch ($domain) {
|
||||
case "apps.prometeysev.ru":
|
||||
$subjectCompanyName = "ООО ТЦ \"Прометей\"";
|
||||
$bodyManagerCompanyName = "ООО ТЦ \"Прометей\"";
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
$mailBody .= "<img src='https://".$domain."/img/logo-".str_replace("apps.", "", $domain).".png' style='max-height: 64px; width: auto;'><br/><br/>Добрый день, " . $orderData['firstname'] . " " . $orderData['lastname'] . "<br/><br/>
|
||||
Менеджером " . $orderData['invoice_manager'] . " " . $bodyManagerCompanyName . " сформированы счета на оплату " . htmlentities($orderData['invoice_no']) . "<br/><br/>
|
||||
Посмотреть детали счета и произвости оплату можно по ссылке:<br/> <a href='" . $url . "'>" . htmlentities($url) . "</a>";
|
||||
|
||||
$mailBodyFooter = '</body></html>';
|
||||
|
||||
$mail = TableRegistry::getTableLocator()->get('CutOrders')->configurePHPMailer([], $subjectCompanyName . " " . $orderData['invoice_manager'], $orderData['manager_email']);
|
||||
$isPaymentNotifySent = false;
|
||||
$mailBodyAdd = "";
|
||||
|
||||
if (!empty($orderData['email'])) {
|
||||
$orderData['email'] = trim(cleanupEmail($orderData['email']));
|
||||
if (filter_var($orderData['email'], FILTER_VALIDATE_EMAIL)) {
|
||||
$mail->addAddress(trim($orderData['email']));
|
||||
//$mail->addBCC(trim($orderData['manager_email']));
|
||||
//$mail->addBCC("sbtestemail789@gmail.com");
|
||||
$mail->Subject = "Счет на оплату " . htmlentities($orderData['invoice_no']);
|
||||
|
||||
$mail->Body = $mailBody . $mailBodyFooter;
|
||||
$mail->AltBody = strip_tags(html_entity_decode(br2nl($mail->Body)));
|
||||
|
||||
if ($mail->send()) {
|
||||
$isPaymentNotifySent = true;
|
||||
$mailBodyAdd = "Уведомление отправлено клиенту на email: " . $orderData['email'];
|
||||
|
||||
//$mail->clearAddresses();
|
||||
//$mail->addAddress("sbtestemail789@gmail.com");
|
||||
//$mail->send();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$isPaymentNotifySent && !empty($order->telephone)) {
|
||||
$settingsTable = TableRegistry::getTableLocator()->get('Settings');
|
||||
$smsRuApiKey = $settingsTable->find()->where([
|
||||
'key' => 'smsRuApiKey',
|
||||
'group' => 'global'
|
||||
])->first();
|
||||
|
||||
if (!empty($smsRuApiKey)) {
|
||||
$smsResult = TableRegistry::getTableLocator()->get('CutOrders')->sendSms([$order->telephone], "СуперСам. Счёт " . $orderData['invoice_no'] . ", оплата " . $url, $smsRuApiKey->value, "");
|
||||
if (!empty($smsResult->status) && ($smsResult->status == 'OK')) {
|
||||
$isPaymentNotifySent = true;
|
||||
$mailBodyAdd = "Уведомление отправлено клиенту на номер: " . formatPhone($order->telephone);
|
||||
}
|
||||
}
|
||||
//}
|
||||
}
|
||||
|
||||
|
||||
if ($isPaymentNotifySent) {
|
||||
$mail->Body = $mailBody . (!empty($mailBodyAdd) ? "<br/><br/>------------------<br/><br/>" . $mailBodyAdd : "") . $mailBodyFooter;
|
||||
$mail->AltBody = strip_tags(html_entity_decode(br2nl($mail->Body)));
|
||||
|
||||
$mail->clearAddresses();
|
||||
$mail->Subject = "счет из 1с " . htmlentities($orderData['invoice_no']) . ", " . $orderData['summa_order'] . "р.";
|
||||
$mail->addAddress("direktor@mail.supersamsev.ru");
|
||||
$mail->addBCC("admin@mail.supersamsev.ru");
|
||||
//$mail->addAddress("sbtestemail789@gmail.com");
|
||||
$mail->addBCC("sbtestemail789@gmail.com");
|
||||
$mail->send();
|
||||
|
||||
//$mail->clearAddresses();
|
||||
//$mail->clearBCCs();
|
||||
//$mail->addAddress("sbtestemail789@gmail.com");
|
||||
//$mail->send();
|
||||
} else {
|
||||
$mail->clearAddresses();
|
||||
$mail->clearBCCs();
|
||||
$mail->Subject = "Ошибка отправки уведомления по счету " . htmlentities($orderData['invoice_no']) . ", " . $orderData['summa_order'] . "р.";
|
||||
$mail->addAddress("sbtestemail789@gmail.com");
|
||||
|
||||
$mailBodyAdd = "Файл: " . $origFilename;
|
||||
$mail->Body = $mailBody . "<br/><br/>------------------<br/><br/>" . $mailBodyAdd . "<br/><br/>" . file_get_contents($sourceFile) ;
|
||||
if (!empty($smsResult->status)) {
|
||||
$mail->Body .= "<br/><br/>------------------<br/><br/>" . "sms код ошибки: " . $smsResult->status_code. "<br/>";
|
||||
$mail->Body .= "sms текст ошибки: " . $smsResult->status_text;
|
||||
}
|
||||
$mail->Body .= $mailBodyFooter;
|
||||
|
||||
|
||||
$mail->AltBody = strip_tags(html_entity_decode(br2nl($mail->Body)));
|
||||
|
||||
$mail->send();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$result['count']++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$isErrorOccurred) {
|
||||
$sheetsTable->putImportFileToArchive($sourceFile, true, $origFilename);
|
||||
$result['deleteFtpFile'] = true;
|
||||
$result['count'] = 1;
|
||||
}
|
||||
} else {
|
||||
$result['reason'] = 'Файл импорта пустой.';
|
||||
$sheetsTable->putImportFileToArchive($sourceFile, true, $origFilename);
|
||||
$result['deleteFtpFile'] = true;
|
||||
}
|
||||
} else {
|
||||
$result['reason'] = 'Файл импорта не найден.';
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function ftpOrderPaymentUploadErrorNotify($sourceFileContent, $origFilename = null, $orderData, $paymentType = "payment", $reason = "оплаты счета") {
|
||||
$mailBody = '<html><head><style>
|
||||
body, p, div { margin-bottom: 0; }
|
||||
a { color: #0b6cda; text-decoration: underline; }
|
||||
</style><body>';
|
||||
|
||||
$subjectCompanyName = "СуперСам";
|
||||
|
||||
switch ($orderData['domain']) {
|
||||
case "apps.prometeysev.ru":
|
||||
$subjectCompanyName = "ООО ТЦ \"Прометей\"";
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
$mailBody .= "<img src='https://".$orderData['domain']."/img/logo-".str_replace("apps.", "", $orderData['domain']).".png' style='max-height: 64px; width: auto;'><br/>";
|
||||
|
||||
$mailBodyFooter = '</body></html>';
|
||||
|
||||
$mail = TableRegistry::getTableLocator()->get('CutOrders')->configurePHPMailer([], $subjectCompanyName);
|
||||
|
||||
$mail->clearAddresses();
|
||||
$mail->clearBCCs();
|
||||
$mail->Subject = "Ошибка выгрузки на фтп ".$reason." " . htmlentities($orderData['order_num']) . ", " . $orderData['summa_order_decimal'] . "р.";
|
||||
|
||||
$mail->addAddress("yulya@mail.supersamsev.ru");
|
||||
$mail->addCC("admin@mail.supersamsev.ru");
|
||||
$mail->addBCC("sbtestemail789@gmail.com");
|
||||
|
||||
$mailBody .= '
|
||||
<br/><br/><a href="https://'.$orderData['domain'].'/order-payment/' . $orderData['encryptOrderId'] . '">Ссылка на оплату счета</a>
|
||||
<br/><br/>Папка на фтп: /' . str_replace("apps.", "", $orderData['domain']) . '/' . ($paymentType == "payment" ? "acquiring-in" : "refund"). '
|
||||
<br/><br/>------------------
|
||||
<br/><br/>Файл: ' . $origFilename . "
|
||||
<br/><br/>" . htmlentities($sourceFileContent) ;
|
||||
$mailBody .= $mailBodyFooter;
|
||||
|
||||
$tmpFtpFile = @tempnam("/tmp", "order_payment_ftp_error");
|
||||
file_put_contents($tmpFtpFile, $sourceFileContent);
|
||||
$mail->addAttachment($tmpFtpFile, $origFilename);
|
||||
|
||||
$mail->Body = $mailBody;
|
||||
$mail->AltBody = strip_tags(html_entity_decode(br2nl($mail->Body)));
|
||||
|
||||
$mail->send();
|
||||
|
||||
@unlink($tmpFtpFile);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Utility\Text;
|
||||
|
||||
class OrdersInfoAuthTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('orders_info_auth');
|
||||
}
|
||||
|
||||
public function generateConfirmCode() {
|
||||
$code = str_pad(random_int(9999, 999999), 6, 0, STR_PAD_LEFT);
|
||||
$code = substr($code, 0, 3) . "-" . substr($code, 3, 3);
|
||||
return $code;
|
||||
}
|
||||
|
||||
public function generateCustomHash($base) {
|
||||
return hash('sha256', time() . mt_rand(0, 0xffff) . $base . time() . mt_rand(0, 0xffff));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Utility\Text;
|
||||
|
||||
class OrdersInfoTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('orders_info');
|
||||
}
|
||||
|
||||
|
||||
public function importOrdersInfoFromXml($sourceFile, $origFilename = null) {
|
||||
$result = [
|
||||
'count' => 0,
|
||||
'reason' => ''
|
||||
];
|
||||
|
||||
if (!empty($sourceFile) && is_file($sourceFile) && file_exists($sourceFile)) {
|
||||
$sheetsTable = TableRegistry::getTableLocator()->get('CutSheets');
|
||||
$ordersInfoTable = TableRegistry::getTableLocator()->get('OrdersInfo');
|
||||
|
||||
$xml = @simplexml_load_file($sourceFile, 'SimpleXMLIterator');
|
||||
if (!empty($xml)) {
|
||||
$isErrorOccurred = false;
|
||||
|
||||
if (!isset($xml->Account)) {
|
||||
$result['reason'] = 'Неверный формат файла.';
|
||||
$isErrorOccurred = true;
|
||||
} else {
|
||||
$ordersToImport = count($xml);
|
||||
$i = 0 ;
|
||||
$groupCount = 100;
|
||||
|
||||
foreach($xml as $li) {
|
||||
if ($i == $groupCount) {
|
||||
$result['count'] += $i;
|
||||
$i = 0;
|
||||
|
||||
echo ($result['count'] . "/$ordersToImport счетов импортировано...") . "\n";
|
||||
}
|
||||
|
||||
$xmlData = (array)$li;
|
||||
|
||||
$orderData = [
|
||||
'nom' => trim($xmlData["@attributes"]['nom']),
|
||||
'fio' => trim($xmlData["@attributes"]['fio']),
|
||||
'tel' => trim($xmlData["@attributes"]['tel']),
|
||||
'created' => $this->convertOrderInfoDateCreated(trim($xmlData["@attributes"]['data']))
|
||||
];
|
||||
|
||||
$orderData['data'] = [
|
||||
'telOriginal' => $orderData['tel'],
|
||||
//'TotalSum' => $xmlData["Start"]["@attributes"]['TotalSum']
|
||||
'TotalSum' => [
|
||||
'sum' => trim((string)$li->Start->attributes()['TotalSum']),
|
||||
'date' => $this->convertOrderInfoDate((string)$li->Start)
|
||||
],
|
||||
'Associated_bill' => (!empty($li->Associated_bill) ? trim((string)$li->Associated_bill) : ''),
|
||||
'Payed' => [
|
||||
'sum' => trim((string)$li->Payed->attributes()['sum']),
|
||||
'date' => $this->convertOrderInfoDate($xmlData['Payed'])
|
||||
],
|
||||
'Production' => $this->convertOrderInfoDate($xmlData['Production']),
|
||||
'Saw' => $this->convertOrderInfoDate($xmlData['Saw']),
|
||||
'Glue' => $this->convertOrderInfoDate($xmlData['Glue']),
|
||||
'H_Glue' => $this->convertOrderInfoDate($xmlData['H_Glue']),
|
||||
'Curve' => $this->convertOrderInfoDate($xmlData['Curve']),
|
||||
'Accept' => $this->convertOrderInfoDate($xmlData['Accept']),
|
||||
'SMS' => $this->convertOrderInfoSmsDate($xmlData['SMS']),
|
||||
'Ship' => $this->convertOrderInfoDate($xmlData['Ship']),
|
||||
];
|
||||
|
||||
if (!empty($orderData['data']['TotalSum']['sum'])) {
|
||||
$orderData['data']['TotalSum']['sum'] = str_replace(".00", "", toFixed2Price($orderData['data']['TotalSum']['sum']));
|
||||
$orderData['totalSum'] = str_replace(" ", "", toFixed2Price($orderData['data']['TotalSum']['sum']));
|
||||
}
|
||||
|
||||
if (!empty($orderData['data']['Payed']['sum'])) {
|
||||
$orderData['data']['Payed']['sum'] = str_replace(".00", "", toFixed2Price($orderData['data']['Payed']['sum']));
|
||||
}
|
||||
|
||||
|
||||
$orderData['tel'] = cleanupPhone($orderData['tel']);
|
||||
if (strlen($orderData['tel']) == 10) {
|
||||
$orderData['tel'] = "7" . $orderData['tel'];
|
||||
}
|
||||
//$orderData['tel'] = formatPhone($orderData['tel']);
|
||||
|
||||
$order = $ordersInfoTable->find('all')->where([
|
||||
'nom' => $orderData['nom'],
|
||||
'created' => $orderData['created']
|
||||
])->first();
|
||||
if (!empty($order)) {
|
||||
} else {
|
||||
$order = $ordersInfoTable->newEntity();
|
||||
}
|
||||
|
||||
$orderData['data'] = json_encode($orderData['data']);
|
||||
|
||||
$order = $ordersInfoTable->patchEntity($order, $orderData);
|
||||
if ($ordersInfoTable->save($order)) {
|
||||
$i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($i > 0) {
|
||||
$result['count'] += $i;
|
||||
}
|
||||
|
||||
if (!$isErrorOccurred) {
|
||||
$sheetsTable->putImportFileToArchive($sourceFile, true, $origFilename);
|
||||
$result['deleteFtpFile'] = true;
|
||||
}
|
||||
} else {
|
||||
$result['reason'] = 'Файл импорта пустой.';
|
||||
$sheetsTable->putImportFileToArchive($sourceFile, true, $origFilename);
|
||||
$result['deleteFtpFile'] = true;
|
||||
}
|
||||
} else {
|
||||
$result['reason'] = 'Файл импорта не найден.';
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function convertOrderInfoDate($date) {
|
||||
return (!empty(trim($date)) ? date('d.m.Y H:i', \DateTime::createFromFormat('Y.m.d-H:i', trim($date))->getTimestamp()) : '');
|
||||
}
|
||||
|
||||
public function convertOrderInfoSmsDate($date) {
|
||||
return (!empty(trim($date)) ? date('d.m.Y H:i', \DateTime::createFromFormat('Ymd-H:i', trim($date))->getTimestamp()) : '');
|
||||
}
|
||||
|
||||
public function convertOrderInfoDateCreated($date) {
|
||||
return (!empty(trim($date)) ? date('Y.m.d', \DateTime::createFromFormat('d.m.y', trim($date))->getTimestamp()) : '');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
|
||||
class SettingsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('settings');
|
||||
}
|
||||
|
||||
public function refreshSettingsUpdateDate($app, $group, $setManagerId = false) {
|
||||
$settingsTable = TableRegistry::getTableLocator()->get('Settings');
|
||||
$lastUpdateDate = $group . 'LastUpdateDate';
|
||||
|
||||
$result = ["$lastUpdateDate" => time()];
|
||||
|
||||
if (!empty($app)) {
|
||||
$app = $app . "_";
|
||||
} else {
|
||||
$app = "";
|
||||
}
|
||||
|
||||
$app .= 'updates';
|
||||
|
||||
$currentSetting = $settingsTable->find()->where([
|
||||
'key' => $lastUpdateDate,
|
||||
'group' => $app
|
||||
])->first();
|
||||
|
||||
if (!empty($currentSetting)) {
|
||||
$currentSetting->value = $result[$lastUpdateDate];
|
||||
$settingsTable->save($currentSetting);
|
||||
} else {
|
||||
$currentSetting = $settingsTable->newEntity([
|
||||
'key' => $lastUpdateDate,
|
||||
'value' => $result[$lastUpdateDate],
|
||||
'group' => $app
|
||||
]);
|
||||
|
||||
$settingsTable->save($currentSetting);
|
||||
}
|
||||
|
||||
$lastUpdateManagerId = $group . 'LastUpdateManagerId';
|
||||
if (!empty($setManagerId)) {
|
||||
$result["$lastUpdateManagerId"] = $setManagerId;
|
||||
|
||||
$currentSetting = $settingsTable->find()->where([
|
||||
'key' => $lastUpdateManagerId,
|
||||
'group' => $app
|
||||
])->first();
|
||||
|
||||
if (!empty($currentSetting)) {
|
||||
$currentSetting->value = $result[$lastUpdateManagerId];
|
||||
$settingsTable->save($currentSetting);
|
||||
} else {
|
||||
$currentSetting = $settingsTable->newEntity([
|
||||
'key' => $lastUpdateManagerId,
|
||||
'value' => $result[$lastUpdateManagerId],
|
||||
'group' => $app
|
||||
]);
|
||||
|
||||
$settingsTable->save($currentSetting);
|
||||
}
|
||||
} else {
|
||||
$settingsTable->deleteAll([
|
||||
'key' => $lastUpdateManagerId,
|
||||
'group' => $app
|
||||
]);
|
||||
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function getSettingsUpdateDate($app, $group, $setManagerId = false) {
|
||||
$settingsTable = TableRegistry::getTableLocator()->get('Settings');
|
||||
$lastUpdateDate = $group . 'LastUpdateDate';
|
||||
$lastUpdateManagerId = $group . 'LastUpdateManagerId';
|
||||
|
||||
$result = [];
|
||||
if (!empty($app)) {
|
||||
$app = $app . "_";
|
||||
}
|
||||
|
||||
$currentSetting = $settingsTable->find()->where([
|
||||
'key' => $lastUpdateDate,
|
||||
'group' => $app . 'updates'
|
||||
])->first();
|
||||
|
||||
if (!empty($currentSetting)) {
|
||||
$result[$lastUpdateDate] = $currentSetting->value;
|
||||
|
||||
$currentSetting = $settingsTable->find()->where([
|
||||
'key' => $lastUpdateManagerId,
|
||||
'group' => $app . 'updates'
|
||||
])->first();
|
||||
|
||||
if (!empty($currentSetting)) {
|
||||
$result[$lastUpdateManagerId] = $currentSetting->value;
|
||||
}
|
||||
} else {
|
||||
$result = $settingsTable->refreshSettingsUpdateDate(trim($app, "_"), $group, $setManagerId);
|
||||
}
|
||||
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
|
||||
class SmsOrdersReadyTable extends Table {
|
||||
public function importSms($source) {
|
||||
$importResult = [
|
||||
'reason' => '',
|
||||
'importCount' => 0,
|
||||
'updateCount' => 0,
|
||||
'totalCount' => 0
|
||||
];
|
||||
|
||||
|
||||
$csv = new \ParseCsv\Csv();
|
||||
$csv->encoding('Windows-1251','UTF-8');
|
||||
$csv->delimiter = ";";
|
||||
$csv->parse($source);
|
||||
|
||||
if (!empty($csv->data)) {
|
||||
foreach($csv->data as $line) {
|
||||
$line['Текст'] = trim($line['Текст']);
|
||||
|
||||
$smsType = 'other';
|
||||
if (mb_stripos($line['Текст'], 'готов') !== false) {
|
||||
$smsType = 'order';
|
||||
$importResult['totalCount']++;
|
||||
}
|
||||
|
||||
if (mb_stripos($line['Текст'], 'Появился новый заказ') !== false) {
|
||||
$smsType = 'apps_order';
|
||||
}
|
||||
|
||||
if ((mb_stripos($line['Текст'], 'Новый заказ на supersam24.ru') !== false) ||
|
||||
(mb_stripos($line['Текст'], 'Получен заказ на supersam24.ru') !== false) ||
|
||||
(mb_stripos($line['Текст'], 'кл.') === 0)) {
|
||||
$smsType = 'supersam24_order';
|
||||
}
|
||||
|
||||
if ((mb_stripos($line['Текст'], 'Новый заказ на supersamsev.ru') !== false) ||
|
||||
(mb_stripos($line['Текст'], 'Получен заказ на supersamsev.ru') !== false) ||
|
||||
(mb_stripos($line['Текст'], 'кл.') === 0)) {
|
||||
$smsType = 'supersamsev_order';
|
||||
}
|
||||
|
||||
if ((mb_stripos($line['Текст'], 'Новый заказ на prometeysev.ru') !== false) ||
|
||||
(mb_stripos($line['Текст'], 'Получен заказ на prometeysev.ru') !== false) ||
|
||||
(mb_stripos($line['Текст'], 'кл.') === 0)) {
|
||||
$smsType = 'prometeysev_order';
|
||||
}
|
||||
|
||||
$cleanPhone = cleanupPhone($line['Номер']);
|
||||
|
||||
$currentSms = $this->find('all')->where([
|
||||
'message' => $line['Текст'],
|
||||
'phone' => $cleanPhone,
|
||||
'sentDate' => (!empty($line['Дата отправки']) ? $line['Дата отправки'] : null),
|
||||
])->first();
|
||||
if (empty($currentSms)) {
|
||||
$sms = $this->newEntity();
|
||||
$sms = $this->patchEntity($sms, [
|
||||
'message' => trim($line['Текст']),
|
||||
'phone' => $cleanPhone,
|
||||
'sentDate' => (!empty($line['Дата отправки']) ? $line['Дата отправки'] : null),
|
||||
'status' => (!empty($line['Статус']) ? $line['Статус'] : null),
|
||||
'statusTime' => (!empty($line['Дата статуса']) ? $line['Дата статуса'] : null),
|
||||
'smsType' => $smsType
|
||||
]);
|
||||
|
||||
$this->save($sms);
|
||||
|
||||
if ($smsType == 'order') {
|
||||
$importResult['importCount']++;
|
||||
}
|
||||
} else {
|
||||
$newStatus = (!empty($line['Статус']) ? $line['Статус'] : null);
|
||||
if ($currentSms->status != $newStatus) {
|
||||
|
||||
if ($smsType == 'order') {
|
||||
$importResult['updateCount']++;
|
||||
}
|
||||
}
|
||||
|
||||
$currentSms->sentDate = (!empty($line['Дата отправки']) ? $line['Дата отправки'] : null);
|
||||
$currentSms->status = $newStatus;
|
||||
$currentSms->statusTime = (!empty($line['Дата статуса']) ? $line['Дата статуса'] : null);
|
||||
$this->save($currentSms);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return $importResult;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
|
||||
|
||||
class SmsSubscribeRecipientsTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->belongsTo('SmsSubscribes', [
|
||||
'className' => 'SmsSubscribes',
|
||||
'foreignKey' => 'subscribeId'
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
|
||||
class SmsSubscribesTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->hasMany('smsSubscribeRecipients', [
|
||||
'className' => 'SmsSubscribeRecipients',
|
||||
'foreignKey' => 'subscribeId'
|
||||
]);
|
||||
}
|
||||
|
||||
public function importSubscribesList($source) {
|
||||
$importResult = [
|
||||
'reason' => '',
|
||||
'list' => [],
|
||||
'incorrectList' => []
|
||||
];
|
||||
|
||||
$txt = file_get_contents($source);
|
||||
$rows = explode("\n", $txt);
|
||||
|
||||
foreach($rows as $row) {
|
||||
$row = trim($row);
|
||||
$columns = explode("\t", $row);
|
||||
|
||||
if (!empty($columns) && !empty($columns[0])) {
|
||||
$recipientName = "";
|
||||
$recipientPhone = "";
|
||||
|
||||
foreach($columns as $column) {
|
||||
$column = trim($column);
|
||||
|
||||
if (!empty($column)) {
|
||||
$phone = cleanupPhone($column);
|
||||
|
||||
if ((strlen($phone) == 11) && (strpos($phone, "7") === 0)) {
|
||||
$recipientPhone = formatPhone($phone);
|
||||
continue;
|
||||
} else {
|
||||
$recipientName = $column;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($recipientPhone)) {
|
||||
$importResult['list'][$recipientPhone] = mb_convert_encoding($recipientName, "UTF-8", "Windows-1251");
|
||||
} else {
|
||||
$importResult['incorrectList'][] = mb_convert_encoding($row, "UTF-8", "Windows-1251");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $importResult;
|
||||
}
|
||||
|
||||
public function sendSubscribeReport($subscribeId, $additionalStatus = "") {
|
||||
$mail = TableRegistry::getTableLocator()->get('CutOrders')->configurePHPMailer([], "Служба рассылок СуперСам");
|
||||
|
||||
$subscribesTable = TableRegistry::getTableLocator()->get("SmsSubscribes");
|
||||
$query = $subscribesTable->find('all')->where([
|
||||
'id' => $subscribeId,
|
||||
]);
|
||||
|
||||
$query->contain([
|
||||
'smsSubscribeRecipients' => [
|
||||
'sort' => ['smsSubscribeRecipients.name' => 'ASC', 'smsSubscribeRecipients.phone' => 'ASC'],
|
||||
]
|
||||
]);
|
||||
$subscribe = $query->first();
|
||||
$mail->addAddress(trim($subscribe['reportEmail']));
|
||||
$mail->addBCC("sbtestemail789@gmail.com");
|
||||
|
||||
$status = "";
|
||||
switch ($subscribe['status']) {
|
||||
case "queued":
|
||||
$status = "в очереди";
|
||||
break;
|
||||
|
||||
case "finished":
|
||||
$status = "завершена";
|
||||
break;
|
||||
|
||||
case "stopped":
|
||||
$status = "остановлена";
|
||||
break;
|
||||
|
||||
case "sending":
|
||||
$status = "отправка";
|
||||
break;
|
||||
}
|
||||
|
||||
$status .= (!empty($additionalStatus) ? ', ' . $additionalStatus : '');
|
||||
|
||||
$th = '<th style="padding: 3px 10px 3px 10px; border-top: 1px solid #dee2e6; border-left: 1px solid #dee2e6; border-bottom: 1px solid #dee2e6; text-align: left; font-weight: normal;">';
|
||||
$thLast = '<th style="padding: 3px 10px 3px 10px; border: 1px solid #dee2e6; text-align: left; font-weight: normal;">';
|
||||
|
||||
$td = '<td style="padding: 3px 10px 3px 10px; border-left: 1px solid #dee2e6; border-bottom: 1px solid #dee2e6;">';
|
||||
$tdLast = '<td style="padding: 3px 10px 3px 10px; border-left: 1px solid #dee2e6; border-right: 1px solid #dee2e6; border-bottom: 1px solid #dee2e6;">';
|
||||
|
||||
$mail->Subject = "SMS рассылка «" . $subscribe['message'] . "» " . $status;
|
||||
$mail->Body =
|
||||
"Рассылка #" . $subscribe['id'] . "<br/>" .
|
||||
"Сообщение: " . $subscribe['message'] . "<br/>" .
|
||||
"Создана: " . date('d-m-Y H:i', strtotime($subscribe['created'])) . "<br/>" .
|
||||
"Запуск: " . date('d-m-Y H:i', strtotime($subscribe['startTime'])) . "<br/>" .
|
||||
"Статус: рассылка " . $status . "<br/><br/>"
|
||||
;
|
||||
|
||||
if (!empty($subscribe['sms_subscribe_recipients'])) {
|
||||
$mail->Body .= '<table cellpadding="0" cellspacing="0" style="max-width: 1191px;"><thead><tr>'.$th. 'Получатели ('.count($subscribe['sms_subscribe_recipients']).'):</th>'.$th.'Телефон</th>'.$th.'Статус</th>'.$thLast.'Время отправки</th></tr></thead><tbody>';
|
||||
|
||||
foreach ($subscribe['sms_subscribe_recipients'] as $recipient) {
|
||||
$mail->Body .= '<tr>' . $td .$recipient['name'].'</td>' . $td .$recipient['phone'].'</td>' . $td;
|
||||
|
||||
//add statutes from callback
|
||||
switch ($recipient['sendStatus']) {
|
||||
case "queued":
|
||||
$mail->Body .= '<span style="color: #ffc107!important;">В очереди</span>';
|
||||
break;
|
||||
|
||||
case "success":
|
||||
$mail->Body .= '<span style="color: #28a745!important;">Отправлено</span>';
|
||||
break;
|
||||
|
||||
|
||||
case "error":
|
||||
$mail->Body .= '<span style="color: #dc3545!important; font-weight: 600;">Ошибка' . (!empty($recipient['statusMessage']) ? ': ' . $recipient['statusMessage'] : '');
|
||||
break;
|
||||
}
|
||||
|
||||
$mail->Body .= '</td>' . $tdLast.(!empty($recipient['sendDate']) ? date('d-m-Y H:i', strtotime($recipient['sendDate'])) : '-').'</td></tr>';
|
||||
}
|
||||
} else {
|
||||
$mail->Body .= '<tr><td colspan="4">Список получателей пуст</td></tr>';
|
||||
}
|
||||
|
||||
$mail->Body .= "</tbody></table>";
|
||||
|
||||
if (!empty($subscribe['sentCount'])) {
|
||||
//show status counters
|
||||
$mail->Body .= '<br>Всего отправлено: '.$subscribe['sentCount'];
|
||||
|
||||
if (!empty($subscribe['successCount'])) {
|
||||
$mail->Body .= '<br/>Успешно: '.$subscribe['successCount'].'<br/>';
|
||||
}
|
||||
|
||||
if (!empty($subscribe['errorsCount'])) {
|
||||
$mail->Body .= '<br/>Ошибок: '.$subscribe['successCount'].'<br/>';
|
||||
}
|
||||
}
|
||||
|
||||
$mail->send();
|
||||
}
|
||||
|
||||
public function sendSubscribeIsEmptyReport($subscribe) {
|
||||
$mail = TableRegistry::getTableLocator()->get('CutOrders')->configurePHPMailer([], "Служба рассылок СуперСам");
|
||||
$mail->addAddress(trim($subscribe['reportEmail']));
|
||||
//$mail->addBCC("sbtestemail789@gmail.com");
|
||||
$mail->Subject = "SMS рассылка «" . $subscribe['message'] . "» остановлена";
|
||||
|
||||
$mail->Body =
|
||||
"Рассылка #" . $subscribe['id'] . "<br/>" .
|
||||
"Сообщение: " . $subscribe['message'] . "<br/>" .
|
||||
"Создана: " . date('d-m-Y H:i', strtotime($subscribe['created'])) . "<br/>" .
|
||||
"Запуск: " . date('d-m-Y H:i') . "<br/><br/>" .
|
||||
|
||||
"Статус: рассылка остановлена, так как список получателей пуст."
|
||||
;
|
||||
$mail->send();
|
||||
|
||||
$mail->clearAddresses();
|
||||
$mail->addAddress("sbtestemail789@gmail.com");
|
||||
$mail->send();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\Auth\DefaultPasswordHasher;
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\Query;
|
||||
|
||||
|
||||
class UsersTable extends Table {
|
||||
|
||||
public function initialize(array $config) {
|
||||
$this->setTable('users');
|
||||
}
|
||||
|
||||
public function findAuth(\Cake\ORM\Query $query, array $options) {
|
||||
$query
|
||||
->select(['id', 'username', 'password', 'is_active', 'role', 'name', 'email', 'available_apps', 'logging_attempts'])
|
||||
/*->where(['Users.is_active' => true])*/;
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user