1
0
Fork 0
mirror of synced 2025-04-20 01:21:01 +00:00

add copy template functionality

This commit is contained in:
Sergey Chazov 2020-10-08 16:15:07 +03:00
parent 0012f8edc7
commit a6ef4ab066
12 changed files with 346 additions and 65 deletions

View file

@ -2963,7 +2963,7 @@ class ApiClient
* @param int $checkId
* @return \RetailCrm\Response\ApiResponse
*/
protected function checkStatusPlVerification(array $request, int $checkId): ApiResponse
public function checkStatusPlVerification(array $request, int $checkId): ApiResponse
{
return $this->client->makeRequest(
"/verification/sms/$checkId/status",
@ -2971,4 +2971,17 @@ class ApiClient
$request
);
}
/**
* @param array $request
* @return \RetailCrm\Response\ApiResponse
*/
public function loyaltyOrderApply(array $request): ApiResponse
{
return $this->client->makeRequest(
"/api/v5/orders/loyalty/apply",
Client::METHOD_POST,
$request
);
}
}

View file

@ -1,4 +1,7 @@
<? use Intaro\RetailCrm\Component\ConfigProvider;
<?php
use Bitrix\Main\Loader;
use Intaro\RetailCrm\Component\ConfigProvider;
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) die();
@ -8,8 +11,10 @@ if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) die();
* @var SaleOrderAjax $component
*/
Loader::includeModule('intaro.retailcrm');
$arResult['LOYALTY_STATUS'] = ConfigProvider::getLoyaltyProgramStatus();
$arResult['AVAILABLE_BONUSES'] = 300;
$arResult['TOTAL_BONUSES_COUNT'] = 600;
$component = $this->__component;
$component::scaleImages($arResult['JS_DATA'], $arParams['SERVICES_IMAGES_SCALING']);
$component::scaleImages($arResult['JS_DATA'], $arParams['SERVICES_IMAGES_SCALING']);

View file

@ -20,9 +20,6 @@ use Bitrix\Sale\Internals\PaySystemActionTable;
use Bitrix\Sale\Delivery\Services\Manager;
use Bitrix\sale\EventActions;
use Bitrix\Sale\Internals\OrderTable;
use Bitrix\Sale\Internals\OrderPropsTable;
use Bitrix\Sale\Internals\PersonTypeTable;
use Intaro\RetailCrm\Component\Constants;
use \RetailCrm\ApiClient;
use RetailCrm\Exception\CurlException;
use Intaro\RetailCrm\Component\Loyalty\EventsHandlers;
@ -1316,6 +1313,22 @@ class intaro_retailcrm extends CModule
true,
false
);
$lpTemplatePath = $_SERVER['DOCUMENT_ROOT']
. '/local/templates/.default/components/bitrix/sale.order.ajax/intaro.retailcrm';
if (!file_exists($lpTemplatePath)){
$pathFrom = $_SERVER['DOCUMENT_ROOT']
. '/bitrix/modules/intaro.retailcrm/install/export/local/components/intaro/sale.order.ajax/templates/.default';
CopyDirFiles(
$pathFrom,
$lpTemplatePath,
true,
true,
false
);
}
}
public function DeleteFiles(): void

View file

@ -109,10 +109,12 @@ $MESS['PHONE_REQUIRED'] = "В настройках главного модуля
$MESS ['LOYALTY_PROGRAM_TITLE'] = 'Программа лояльности';
$MESS ['LOYALTY_PROGRAM_TOGGLE_MSG'] = 'Активность программы лояльности';
$MESS ['LP_CUSTOM_TEMP_CREATE_MSG'] = 'Создать шаблон intaro_retailCRM для компонента оформления заказа sale.order.ajax c функциями Программы лояльности';
$MESS ['LP_DEF_TEMP_CREATE_MSG'] = 'Заменить шаблон .default компонента sale.order.ajax шаблоном с функциями Программы лояльности. <br> Если в папке .local уже есть шаблон .default для sale.order.ajax, то он будет скопирован в папку .default_bak_#';
$MESS ['LP_CUSTOM_TEMP_CREATE_MSG'] = 'Создать шаблон intaro.retailCRM для компонента оформления заказа sale.order.ajax c функциями Программы лояльности. <br> <b>Внимение:</b> если шаблон уже существует, то он будет перезаписан';
$MESS ['LP_DEF_TEMP_CREATE_MSG'] = 'Заменить шаблон .default компонента sale.order.ajax шаблоном с функциями Программы лояльности. <br> Если в папке .local уже есть шаблон .default для sale.order.ajax, то он будет скопирован в папку .default_backup';
$MESS ['LP_CREATE_TEMPLATE'] = 'Создать шаблон';
$MESS ['LP_REPLACE_TEMPLATE'] = 'Заменить шаблон';
$MESS ['LP_SALE_ORDER_AJAX_HEAD'] = ' Управление компонентом Оформление заказа (sale.order.ajax)';
$MESS ['LP_TEMP_CHOICE_MSG'] = 'Выберите, в каких шаблонах сайта будет доступен шаблон компонента Оформление заказа с функциями Программы лояльности:';
$MESS ['CREATING_AN_ADDITIONAL_TEMPLATE'] = 'Создание дополнительного шаблона';
$MESS ['REPLACING_THE_STANDARD_TEMPLATE'] = 'Замена стандартного шаблона .default';

View file

@ -13,7 +13,9 @@ namespace Intaro\RetailCrm\Component\ApiClient\Traits;
use Intaro\RetailCrm\Component\Json\Deserializer;
use Intaro\RetailCrm\Component\Json\Serializer;
use Intaro\RetailCrm\Model\Api\Request\Order\Loyalty\OrderLoyaltyApplyRequest;
use Intaro\RetailCrm\Model\Api\Request\SmsVerification\SmsVerificationConfirmRequest;
use Intaro\RetailCrm\Model\Api\Response\Order\Loyalty\OrderLoyaltyApplyResponse;
use Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationConfirmResponse;
use Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationStatusRequest;
use Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationStatusResponse;
@ -47,4 +49,16 @@ trait LoyaltyTrait
return Deserializer::deserializeArray($response->getResponseBody(), SmsVerificationStatusResponse::class);
}
/**
* @param \Intaro\RetailCrm\Model\Api\Request\Order\Loyalty\OrderLoyaltyApplyRequest $request
* @return mixed
*/
public function loyaltyOrderApply(OrderLoyaltyApplyRequest $request): ?OrderLoyaltyApplyResponse
{
$serialized = Serializer::serializeArray($request);
$response = $this->client->loyaltyOrderApply($serialized);
return Deserializer::deserializeArray($response->getResponseBody(), OrderLoyaltyApplyResponse::class);
}
}

View file

@ -1,4 +1,5 @@
<?php
/**
* PHP version 7.1
*
@ -9,12 +10,18 @@
* @link http://retailcrm.ru
* @see http://retailcrm.ru/docs
*/
namespace Intaro\RetailCrm\Component\Loyalty;
use Bitrix\Main\ArgumentException;
use Bitrix\Main\Event;
use Bitrix\Main\HttpRequest;
use Bitrix\Main\ObjectPropertyException;
use Bitrix\Main\SystemException;
use Bitrix\Sale\PaySystem\Manager;
use Exception;
use Intaro\RetailCrm\Component\ConfigProvider;
use Intaro\RetailCrm\Repository\PaySystemActionRepository;
use Intaro\RetailCrm\Service\LoyaltyService;
/**
* Class EventsHandlers
@ -108,7 +115,7 @@ class EventsHandlers
$bonusInput = (int)$request->get('bonus-input');
$availableBonuses = (int)$request->get('available-bonuses');
if ($bonusInput > $availableBonuses) {
if ($bonusInput >= $availableBonuses) {
$arResult['LOYALTY']['ERROR'] = self::BONUS_ERROR_MSG;
$isBonusError = true;
}
@ -117,7 +124,7 @@ class EventsHandlers
$bonusInput > 0
&& $availableBonuses > 0
&& $isBonusError === false
&& $arResult['JS_DATA']['TOTAL']['ORDER_TOTAL_PRICE'] > $bonusInput
&& $arResult['JS_DATA']['TOTAL']['ORDER_TOTAL_PRICE'] >= $bonusInput
) {
$arResult['JS_DATA']['TOTAL']['ORDER_TOTAL_PRICE'] -= $bonusInput;
$arResult['JS_DATA']['TOTAL']['ORDER_TOTAL_PRICE_FORMATED'] = number_format($arResult['JS_DATA']['TOTAL']['ORDER_TOTAL_PRICE'], 0, ',', ' ');
@ -127,18 +134,44 @@ class EventsHandlers
}
/**
* Обработчик события, вызываемого ПОСЛЕ сохранения заказа
*
* @param \Bitrix\Main\Event $event
*/
public function OnSaleOrderSavedHandler(Event $event): void
{
/**@var \Bitrix\Sale\Order $order */
$order = $event->getParameter("ENTITY");
$oldValues = $event->getParameter("VALUES");
$isNew = $event->getParameter("IS_NEW");
if ($isNew)
{
$sum = $order->getPrice();
if (isset($_POST['bonus-input'], $_POST['available-bonuses'])
&& $isNew
&& (int)$_POST['available-bonuses'] >= (int)$_POST['bonus-input']) {
$orderId = $order->getId();
$bonusCount = $_POST['bonus-input'];
$service = new LoyaltyService();
$response = $service->sendBonusPayment($orderId, $bonusCount);
//TODO - заглушка до появления api на стороне CRM. После появления реального апи - убрать
$response->success=true;
if ($response->success) {
try {
$bonusPaySystem = PaySystemActionRepository::getFirstByWhere(['ID'], [['ACTION_FILE', '=', 'retailcrmbonus']]);
$paymentCollection = $order->getPaymentCollection();
if ($bonusPaySystem !== null) {
$service = Manager::getObjectById($bonusPaySystem->getId());
$newPayment = $paymentCollection->createItem($service);
$newPayment->setField('SUM', $bonusCount);
$newPayment->setPaid('Y');
$order->save();
}
} catch (ObjectPropertyException | ArgumentException | SystemException | Exception $e) {
AddMessage2Log('ERROR PaySystemActionRepository: ' . $e->getMessage());
}
}
}
}
}

View file

@ -34,22 +34,43 @@ class AdminPanel extends Controller
}
/**
* @return string[]
* @param $templates
* @param string $defreplace
* @return array
*/
public function createSaleTemplateAction($templates): array
public function createSaleTemplateAction($templates, $defreplace = 'N'): array
{
foreach ($templates as $template){
$templateName = $defreplace === 'Y' ? '.default' : Constants::MODULE_ID;
foreach ($templates as $template) {
$pathFrom = $_SERVER['DOCUMENT_ROOT']
. '/bitrix/modules/'
. Constants::MODULE_ID
. '/install/export/local/components/intaro/sale.order.ajax/templates/.default';
$pathTo = $_SERVER['DOCUMENT_ROOT']
. '/local/templates/'
. $template
. '/components/bitrix/sale.order.ajax/intaro.retailCRM';
$status = CopyDirFiles(
. $template['location']
. $template['name']
. '/components/bitrix/sale.order.ajax/'
. $templateName;
if ($defreplace === 'Y' && file_exists($pathTo)) {
$backPath = $_SERVER['DOCUMENT_ROOT']
. $template['location']
. $template['name']
. '/components/bitrix/sale.order.ajax/'
. $templateName.'_backup';
CopyDirFiles(
$pathTo,
$backPath,
true,
true,
false
);
}
$status = CopyDirFiles(
$pathFrom,
$pathTo,
true,
@ -57,16 +78,9 @@ class AdminPanel extends Controller
false
);
}
return [
'status' => $status,
];
}
/**
* @return string[]
*/
public function ReplaceDefSaleTemplateAction(): array
{
return ['status' => 'ok'];
}
}

View file

@ -0,0 +1,92 @@
<?php
/**
* PHP version 7.1
*
* @category Integration
* @package Intaro\RetailCrm\Model\Bitrix
* @author retailCRM <integration@retailcrm.ru>
* @license MIT
* @link http://retailcrm.ru
* @see http://retailcrm.ru/docs
*/
namespace Intaro\RetailCrm\Model\Bitrix;
use Bitrix\Main\ORM\Objectify\EntityObject;
use Bitrix\Sale\Internals\PaySystemActionTable;
/**
* Class PaySystemAction
*
* @package Intaro\RetailCrm\Model\Bitrix
*
* @method int getId()
* @method void setId(int $id)
* @method int getPaySystemId()
* @method void setPaySystemId(int $paySystemId)
* @method int getPersonTypeId()
* @method void setPersonTypeId(int $personTypeId)
* @method string getName()
* @method void setName(string $name)
* @method string getPsaName()
* @method void setPsaName(string $psaName)
* @method string getCode()
* @method void setCode(string $code)
* @method int getSort()
* @method void setSort(int $sort)
* @method string getActionFile()
* @method void setActionFile(string $actionFile)
* @method string getResultFile()
* @method void setResultFile(string $resultFile)
* @method string getDescription()
* @method void setDescription(string $description)
* @method bool getNewWindow()
* @method void setNewWindow(bool $newWindow)
* @method string getParams()
* @method void setParams(string $params)
* @method string getTarif()
* @method void setTarif(string $tarif)
* @method string getPsMode()
* @method void setPsMode(string $psMode)
* @method bool getHavePayment()
* @method void setHavePayment(bool $havePayment)
* @method bool getHaveAction()
* @method void setHaveAction(bool $haveAction)
* @method bool getHaveResult()
* @method void setHaveResult(bool $haveResult)
* @method bool getHavePrepay()
* @method void setHavePrepay(bool $havePrepay)
* @method bool getHavePrice()
* @method void setHavePrice(bool $havePrice)
* @method bool getHaveResultReceive()
* @method void setHaveResultReceive(bool $haveResultReceive)
* @method string getEncoding()
* @method void setEncoding(string $encoding)
* @method int getLogotip()
* @method void setLogotip(int $logotip)
* @method bool getActive()
* @method void setActive(bool $active)
* @method bool getAllowEditPayment()
* @method void setAllowEditPayment(bool $allowEditPayment)
* @method string getIsCash()
* @method void setIsCash(string $isCash)
* @method bool getAutoChange1c()
* @method void setAutoChange1c(bool $autoChange1c)
* @method bool getCanPrintCheck()
* @method void setCanPrintCheck(bool $canPrintCheck)
* @method string getEntityRegistryType()
* @method void setEntityRegistryType(string $entityRegistryType)
* @method string getXmlId()
* @method void setXmlId(string $xmlId)
*/
class PaySystemAction extends AbstractModelProxy
{
/**
* @return \Bitrix\Main\ORM\Objectify\EntityObject|null
* @throws \Bitrix\Main\ArgumentException
* @throws \Bitrix\Main\SystemException
*/
protected static function newObject(): ?EntityObject
{
return PaySystemActionTable::createObject();
}
}

View file

@ -0,0 +1,38 @@
<?php
/**
* PHP version 7.1
*
* @category Integration
* @package Intaro\RetailCrm\Repository
* @author retailCRM <integration@retailcrm.ru>
* @license MIT
* @link http://retailcrm.ru
* @see http://retailcrm.ru/docs
*/
namespace Intaro\RetailCrm\Repository;
use Bitrix\Sale\Internals\PaySystemActionTable;
/**
* Class PaySystemActionRepository
*
* @package Intaro\RetailCrm\Repository
*/
class PaySystemActionRepository extends AbstractRepository
{
/**
* @param array $select
* @param array $where
* @return \Intaro\RetailCrm\Model\Bitrix\PaySystemAction|null|\Bitrix\Sale\Internals\EO_PaySystemAction
* @throws \Bitrix\Main\ArgumentException
* @throws \Bitrix\Main\ObjectPropertyException
* @throws \Bitrix\Main\SystemException
*/
public static function getFirstByWhere(array $select, array $where)
{
return PaySystemActionTable::query()
->setSelect($select)
->where($where)
->fetchObject();
}
}

View file

@ -29,24 +29,25 @@ class TemplateRepository extends AbstractRepository
public static function getAllIds()
{
$scanDirs = [
$_SERVER['DOCUMENT_ROOT'] . self::BITRIX_TEMPLATE_DIR,
$_SERVER['DOCUMENT_ROOT'] . self::LOCAL_TEMPLATE_DIR,
self::BITRIX_TEMPLATE_DIR,
self::LOCAL_TEMPLATE_DIR,
];
$result = [];
$result = [];
foreach ($scanDirs as $scanDir) {
$handle = opendir($scanDir);
$handle = opendir($_SERVER['DOCUMENT_ROOT'] . '/' . $scanDir);
if ($handle) {
while (($file = readdir($handle)) !== false) {
if ($file === "." || $file === "..") {
continue;
}
if (is_dir($scanDir . '/' . $file)) {
$result[] = $file;
if (is_dir($_SERVER['DOCUMENT_ROOT'] . '/' . $scanDir . '/' . $file)) {
$result[] = [
'name' => $file,
'folder' => $scanDir,
];
}
}
closedir($handle);

View file

@ -0,0 +1,49 @@
<?php
/**
* PHP version 7.1
*
* @category Integration
* @package Intaro\RetailCrm\Service
* @author retailCRM <integration@retailcrm.ru>
* @license MIT
* @link http://retailcrm.ru
* @see http://retailcrm.ru/docs
*/
namespace Intaro\RetailCrm\Service;
use Intaro\RetailCrm\Component\Factory\ClientFactory;
use Intaro\RetailCrm\Model\Api\Request\Order\Loyalty\OrderLoyaltyApplyRequest;
/**
* Class LoyaltyService
*
* @package Intaro\RetailCrm\Service
*/
class LoyaltyService
{
/**
* @var \Intaro\RetailCrm\Component\ApiClient\ClientAdapter
*/
private $client;
/**
* LoyaltyService constructor.
*/
public function __construct()
{
$this->client = ClientFactory::createClientAdapter();
}
/**
* @param $orderId
* @param $bonusConunt
* @return \Intaro\RetailCrm\Model\Api\Response\Order\Loyalty\OrderLoyaltyApplyResponse|mixed|null
*/
public function sendBonusPayment($orderId, $bonusConunt){
$request = new OrderLoyaltyApplyRequest();
$request->order->id = $orderId;
$request->order->bonuses = $bonusConunt;
return $this->client->loyaltyOrderApply($request);
}
}

View file

@ -771,49 +771,48 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
<script type="text/javascript">
function createSaleTemplates() {
BX.ajax.runAction( 'intaro:retailcrm.api.adminpanel.createSaleTemplate',
BX.ajax.runAction('intaro:retailcrm.api.adminpanel.createSaleTemplate',
{
data: {
sessid: BX.bitrix_sessid(),
templates: ['.default']
sessid: BX.bitrix_sessid(),
templates: [
{
'location': '/local/templates/',
'name': '.default'
}
]
}
}
);
}
function editSaleTemplates(method){
function replaceDefaultSaleTemplates(){
let templates = [];
let i = 0;
$('#lp-templates input:checkbox:checked')
.each(
function(index, checkbox){
templates[i] = $(checkbox).val();
templates[i] = {
'name': $(checkbox).val(),
'location': $(checkbox).attr('templateFolder')
};
i++;
}
);
let requestAdress = 'intaro:retailcrm.api.adminpanel.' + method;
BX.ajax.runAction(requestAdress,
let requestAddress = 'intaro:retailcrm.api.adminpanel.createSaleTemplate';
BX.ajax.runAction(requestAddress,
{
data: {
sessid: BX.bitrix_sessid(),
templates: templates
templates: templates,
defreplace: 'Y'
}
}
);
}
function replaceDefSaleTemplate() {
console.log($('#lp-templates').serializeArray());
BX.ajax.runAction('intaro:retailcrm.api.adminpanel.replaceDefSaleTemplate',
{
data: {
sessid: BX.bitrix_sessid()
}
}
)
}
function switchPLStatus() {
BX.ajax.runAction('intaro:retailcrm.api.adminpanel.loyaltyprogramtoggle',
{
@ -1359,7 +1358,11 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
</tr>
<tr>
<td colspan="2">
<div style="text-align: center;"><h4>Создание дополнительного шаблона</h4></div>
<div style="text-align: center;">
<h4>
<?= GetMessage('CREATING_AN_ADDITIONAL_TEMPLATE') ?>
</h4>
</div>
<?php echo GetMessage('LP_CUSTOM_TEMP_CREATE_MSG'); ?>
<div style="text-align: center;">
<input type="button" onclick="createSaleTemplates()" class="adm-btn-save" value="<?php echo GetMessage('LP_CREATE_TEMPLATE'); ?>"/>
@ -1368,7 +1371,11 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
</tr>
<tr>
<td colspan="2">
<div style="text-align: center;"><h4>Замена стандартного шаблона</h4></div>
<div style="text-align: center;">
<h4>
<?= GetMessage('REPLACING_THE_STANDARD_TEMPLATE') ?>
</h4>
</div>
<?php echo GetMessage('LP_DEF_TEMP_CREATE_MSG'); ?>
<hr>
<?php echo GetMessage('LP_TEMP_CHOICE_MSG'); ?>
@ -1376,7 +1383,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
</tr>
<tr>
<td width="50%" >
<input type="button" onclick="editSaleTemplates('replaceDefSaleTemplate')" class="adm-btn-save" value="<?php echo GetMessage('LP_REPLACE_TEMPLATE'); ?>" />
<input type="button" onclick="replaceDefaultSaleTemplates()" class="adm-btn-save" value="<?php echo GetMessage('LP_REPLACE_TEMPLATE'); ?>" />
</td>
<td width="50%" >
<div id="lp-templates">
@ -1384,7 +1391,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
$templates = TemplateRepository::getAllIds();
foreach ($templates as $template) {
?>
<p><input type="checkbox" name="<?= $template?>" value="<?= $template?>"> <?= $template?></p>
<p><input type="checkbox" name="<?= $template['name']?>" value="<?= $template['name']?>" templateFolder="<?= $template['folder']?>"> <?= $template['name']?> (<?= $template['folder']?>)</p>
<?php } ?>
</div>
</td>