1
0
mirror of synced 2024-11-25 14:56:09 +03:00

Программа лояльности

* New module structure (refactoring)
* Simple serializer and deserializer with models, new architecture
* Move logic to strategies
* Partial api client facade implementation (full implementation is not necessary for now)
* Loyalty feature installer
* Sms verification order (#167)
* Make updater self-sufficient
* Fix for order submit & fix for incorrect component rendering in the constructor
* Fix for loyalty personal area error handling
* Fix for cart component identity
* Fix for softlock when customer cannot be registered in loyalty

Co-authored-by: Сергей Чазов <45812598+Chazovs@users.noreply.github.com>
Co-authored-by: Sergey Chazov <oitv18@gmail.com>
This commit is contained in:
Pavel 2021-11-16 10:48:26 +03:00 committed by GitHub
parent a1d6e00d18
commit 5f69051859
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
467 changed files with 87501 additions and 2793 deletions

View File

@ -1,3 +1,6 @@
## 2021-11-12 v.6.0.0
* Добавлена поддержка программы лояльности
## 2021-10-15 v.5.8.4 ## 2021-10-15 v.5.8.4
* Исправление некорректной генерации каталога при повторных запусках генерации * Исправление некорректной генерации каталога при повторных запусках генерации

View File

@ -29,7 +29,8 @@ echo "Update version and date in the file \"version.php\""
for i in `find ./"$version" -type f -name '*.*'`; do for i in `find ./"$version" -type f -name '*.*'`; do
encoding=`file -b --mime-encoding "$i"` encoding=`file -b --mime-encoding "$i"`
if [ "$encoding" != "iso-8859-1" ] && [ "$encoding" != "binary" ]; then if [ "$encoding" != "iso-8859-1" ] && [ "$encoding" != "us-ascii" ] && [ "$encoding" != "binary" ]; then
echo "$i: converting from $encoding to cp1251"
result=$(iconv -f $encoding -t "cp1251" $i -o $i.cp1251 2>&1 > /dev/null) result=$(iconv -f $encoding -t "cp1251" $i -o $i.cp1251 2>&1 > /dev/null)
if [ ! -z "$result" ]; then if [ ! -z "$result" ]; then
echo "Errors in file $i" echo "Errors in file $i"

View File

@ -24,9 +24,7 @@ if (!$handle) {
$modifiedFiles = []; $modifiedFiles = [];
while (($buffer = fgets($handle)) !== false) { while (($buffer = fgets($handle)) !== false) {
$file = explode("\t", trim($buffer)); $modifiedFiles[] = new ModifiedFile($buffer);
$modifiedFile = new ModifiedFile($file[1], $file[0]{0});
$modifiedFiles[] = $modifiedFile;
} }
try { try {

View File

@ -5,6 +5,7 @@
"tests": "php vendor/bin/phpunit -c phpunit.xml.dist --whitelist=$BITRIX_PATH/bitrix/modules/intaro.retailcrm" "tests": "php vendor/bin/phpunit -c phpunit.xml.dist --whitelist=$BITRIX_PATH/bitrix/modules/intaro.retailcrm"
}, },
"description": "Integration module for Bitrix & RetailCRM", "description": "Integration module for Bitrix & RetailCRM",
"license": "MIT",
"type": "bitrix-module", "type": "bitrix-module",
"authors": [ "authors": [
{ {
@ -15,6 +16,7 @@
"require": { "require": {
"ext-json": "*", "ext-json": "*",
"ext-mbstring": "*", "ext-mbstring": "*",
"ext-tokenizer": "*",
"ext-xmlwriter": "*" "ext-xmlwriter": "*"
}, },
"require-dev": { "require-dev": {

573
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -29,18 +29,34 @@ class ModifiedFile
/** @var string */ /** @var string */
protected $filename; protected $filename;
/** @var string */
protected $oldFilename;
/** @var string */ /** @var string */
protected $modificator; protected $modificator;
/** @var int */
protected $percent;
/** /**
* ModifiedFile constructor. * ModifiedFile constructor.
* @param string $filename * @param string $source
* @param string $modificator
*/ */
public function __construct($filename, $modificator = self::Modified) public function __construct($source)
{ {
$this->filename = $filename; $params = explode("\t", trim($source));
$this->modificator = $modificator;
$this->filename = $params[1];
$this->modificator = $params[0][0];
if (strlen($params[0]) > 1) {
$this->percent = (int) substr($params[0], 1);
}
if (count($params) >= 3) {
$this->filename = $params[2];
$this->oldFilename = $params[1];
}
} }
/** /**
@ -90,4 +106,20 @@ class ModifiedFile
{ {
return $this->filename; return $this->filename;
} }
/**
* @return string
*/
public function getOldFilename()
{
return $this->oldFilename;
}
/**
* @return int
*/
public function getPercent()
{
return $this->percent;
}
} }

View File

@ -0,0 +1,307 @@
<?php
/**
* Class RetailcrmClasspathBuilder.
* Builds classpath for Bitrix autoloader. Contains some hardcoded things, which will go away when everything refactored.
*/
class RetailcrmClasspathBuilder
{
/**
* File extension as a string. Defaults to ".php".
* @var string
*/
protected $fileExt = 'php';
/**
* @var string $moduleId
*/
protected $moduleId = 'intaro.retailcrm';
/**
* The topmost directory where recursion should begin. Default: `classes/general`. Relative to the __DIR__.
* @var string
*/
protected $path = 'classes/general';
/**
* Do not include directory paths as namespaces.
* @var bool
*/
protected $disableNamespaces;
/**
* Bitrix document root
* @var string
*/
protected $documentRoot;
/**
* @var string
*/
protected $version;
/**
* @var array $result
*/
protected $result = [];
/**
* @var array $notIncluded
*/
protected $notIncluded = [];
/**
* These classes can be customized, in which case they would be replaced with files from
* directory <root>/bitrix/php_interface/retailcrm
*
* Array format:
* [
* 'class path with namespace' => 'file name'
* ]
*/
protected static $customizableClasses = [
'RestNormalizer' => 'RestNormalizer.php',
'Logger' => 'Logger.php',
'RetailCrm\ApiClient' => 'ApiClient_v5.php',
'RetailCrm\Http\Client' => 'Client.php',
'RCrmActions' => 'RCrmActions.php',
'RetailCrmUser' => 'RetailCrmUser.php',
'RetailCrmICML' => 'RetailCrmICML.php',
'RetailCrmInventories' => 'RetailCrmInventories.php',
'RetailCrmPrices' => 'RetailCrmPrices.php',
'RetailCrmCollector' => 'RetailCrmCollector.php',
'RetailCrmUa' => 'RetailCrmUa.php',
'RetailCrmEvent' => 'RetailCrmEvent.php',
'RetailCrmCorporateClient' => 'RetailCrmCorporateClient.php'
];
/**
* These classes can be customized, in which case they would be replaced with files from
* directory <root>/bitrix/php_interface/retailcrm
* Customized versions have fixed name, and original versions name depends on API version
*
* Array format:
* [
* 'class path with namespace' => ['customized file name', 'original file name with %s for API version']
* ]
*/
protected static $versionedClasses = [
'RetailCrm\ApiClient' => ['ApiClient.php', 'ApiClient_%s.php'],
'RetailCrmOrder' => ['RetailCrmOrder.php', 'RetailCrmOrder_%s.php'],
'RetailCrmHistory' => ['RetailCrmHistory.php', 'RetailCrmHistory_%s.php']
];
/**
* These classes will be ignored while loading from original files
*/
protected static $ignoredClasses = [
'ApiClient_v4.php',
'ApiClient_v5.php',
'RetailCrmOrder_v4.php',
'RetailCrmOrder_v5.php',
'RetailCrmHistory_v4.php',
'RetailCrmHistory_v5.php',
];
/**
* These namespaces are hardcoded.
*/
protected static $hardcodedNamespaces = [
'RetailCrm\Response\ApiResponse' => 'ApiResponse.php',
'RetailCrm\Exception\InvalidJsonException' => 'InvalidJsonException.php',
'RetailCrm\Exception\CurlException' => 'CurlException.php'
];
protected function buildCustomizableClasspath()
{
foreach (static::$customizableClasses as $className => $fileName) {
$customizedFile = $this->documentRoot . '/bitrix/php_interface/retailcrm/' . $fileName;
if (file_exists($customizedFile)) {
$this->result[$className] = $customizedFile;
} else {
$this->notIncluded[$className] = $fileName;
}
}
}
protected function buildVersionedClasspath()
{
foreach (static::$versionedClasses as $className => $fileNames) {
$customizedFile = $this->documentRoot . '/bitrix/php_interface/retailcrm/' . $fileNames[0];
if (file_exists($customizedFile)) {
$this->result[$className] = $customizedFile;
} else {
$this->notIncluded[$className] = sprintf($fileNames[1], $this->version);
}
}
}
/**
* Traverse through directories, build include paths
* @return $this
*/
public function build(): self
{
$directory = new RecursiveDirectoryIterator(
$this->getSearchPath(),
RecursiveDirectoryIterator::SKIP_DOTS
);
$fileIterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::LEAVES_ONLY);
$this->buildCustomizableClasspath();
$this->buildVersionedClasspath();
$notIncludedClasses = array_flip($this->notIncluded);
$hardcodedNamespaces = array_flip(static::$hardcodedNamespaces);
/** @var \SplFileObject $file */
foreach ($fileIterator as $file) {
$fileNameWithoutExt = str_ireplace('.' . $this->fileExt, '', $file->getFilename());
if ($file->getExtension() !== $this->fileExt) {
continue;
}
if (in_array($file->getFilename(), static::$customizableClasses)
|| in_array($file->getFilename(), static::$ignoredClasses)
) {
if (in_array($file->getFilename(), $this->notIncluded)) {
$this->result[$notIncludedClasses[$file->getFilename()]] = $this->getImportPath($file->getPathname());
}
continue;
}
if (in_array($file->getFilename(), static::$hardcodedNamespaces)) {
$this->result[$hardcodedNamespaces[$file->getFilename()]] = $this->getImportPath($file->getPathname());
} else {
$this->result[$this->getImportClass($fileNameWithoutExt, $file->getPath())] = $this->getImportPath($file->getPathname());
}
}
return $this;
}
/**
* Sets the $fileExt property
*
* @param string $fileExt The file extension used for class files. Default is "php".
*
* @return \RetailcrmClasspathBuilder
*/
public function setFileExt($fileExt)
{
$this->fileExt = $fileExt;
return $this;
}
/**
* @param string $documentRoot
*
* @return RetailcrmClasspathBuilder
*/
public function setDocumentRoot(string $documentRoot): RetailcrmClasspathBuilder
{
$this->documentRoot = $documentRoot;
return $this;
}
/**
* Sets the $path property
*
* @param string $path Top path to load files
*
* @return \RetailcrmClasspathBuilder
*/
public function setPath(string $path)
{
$this->path = $path;
return $this;
}
/**
* @param mixed $disableNamespaces
*
* @return RetailcrmClasspathBuilder
*/
public function setDisableNamespaces($disableNamespaces)
{
$this->disableNamespaces = $disableNamespaces;
return $this;
}
/**
* @param string $moduleId
*
* @return RetailcrmClasspathBuilder
*/
public function setModuleId(string $moduleId): RetailcrmClasspathBuilder
{
$this->moduleId = $moduleId;
return $this;
}
/**
* @param string $version
*
* @return RetailcrmClasspathBuilder
*/
public function setVersion(string $version): RetailcrmClasspathBuilder
{
$this->version = $version;
return $this;
}
/**
* @return array
*/
public function getResult(): array
{
return $this->result;
}
/**
* @return string
*/
protected function getSearchPath(): string
{
return __DIR__ . DIRECTORY_SEPARATOR . $this->path;
}
/**
* @param string $filePath
*
* @return string
*/
protected function getImportPath(string $filePath): string
{
return (string) str_ireplace(implode(DIRECTORY_SEPARATOR, [
$this->documentRoot,
'bitrix',
'modules',
$this->moduleId
]) . DIRECTORY_SEPARATOR, '', $filePath);
}
/**
* @param string $fileNameWithoutExt
* @param string $filePath
*
* @return string
*/
protected function getImportClass(string $fileNameWithoutExt, string $filePath): string
{
if ($this->disableNamespaces) {
return $fileNameWithoutExt;
}
$importClass = str_ireplace($this->getSearchPath(), '', $filePath). '\\' . $fileNameWithoutExt;
if (strlen($importClass) > 0 && $importClass[0] === '/') {
$importClass = '\\' . substr($importClass, 1);
}
return (string) str_replace(DIRECTORY_SEPARATOR, '\\', $importClass);
}
}

View File

@ -1814,7 +1814,18 @@ class ApiClient
{ {
$this->siteCode = $site; $this->siteCode = $site;
} }
/**
* @return \RetailCrm\Response\ApiResponse
*/
public function getCredentials(): ApiResponse
{
return $this->client->makeRequest(
'/credentials',
Client::METHOD_GET
);
}
/** /**
* Check ID parameter * Check ID parameter
* *

View File

@ -29,6 +29,7 @@ class ApiClient
const VERSION = 'v5'; const VERSION = 'v5';
protected $client; protected $client;
protected $unversionedClient;
/** /**
* Site code * Site code
@ -50,10 +51,13 @@ class ApiClient
$url .= '/'; $url .= '/';
} }
$url = $url . 'api/' . self::VERSION; $versionedUrl = $url . 'api/' . self::VERSION;
$unversionedUrl = $url . 'api';
$this->client = new Client($url, array('apiKey' => $apiKey)); $this->client = new Client($versionedUrl, array('apiKey' => $apiKey));
$this->siteCode = $site; $this->siteCode = $site;
$this->unversionedClient = new Client($unversionedUrl, ['apiKey' => $apiKey]);
} }
/** /**
@ -240,11 +244,11 @@ class ApiClient
return $this->client->makeRequest( return $this->client->makeRequest(
'/customers-corporate/fix-external-ids', '/customers-corporate/fix-external-ids',
Client::METHOD_POST, Client::METHOD_POST,
array('customerCorporate' => json_encode($ids)) array('customersCorporate' => json_encode($ids))
); );
} }
/* /**
* Upload array of the customers corporate * Upload array of the customers corporate
* *
* @param array $customers array of customers * @param array $customers array of customers
@ -608,20 +612,15 @@ class ApiClient
/** /**
* Create corporate customer address * Create corporate customer address
* *
* @param string $id corporate customer identifier * @param string $id corporate customer identifier
* @param array $address (default: array()) * @param array $address (default: array())
* @param string $by (default: 'externalId') * @param string $by (default: 'externalId')
* @param string $site (default: null) * @param null $site (default: null)
*
* @throws \InvalidArgumentException
* @throws \RetailCrm\Exception\CurlException
* @throws \RetailCrm\Exception\InvalidJsonException
* *
* @return \RetailCrm\Response\ApiResponse * @return \RetailCrm\Response\ApiResponse
*/ */
public function customersCorporateAddressesCreate($id, array $address = [], $by = 'externalId', $site = null) public function customersCorporateAddressesCreate($id, array $address = [], $by = 'externalId', $site = null): ApiResponse
{ {
/* @noinspection PhpUndefinedMethodInspection */
return $this->client->makeRequest( return $this->client->makeRequest(
"/customers-corporate/$id/addresses/create", "/customers-corporate/$id/addresses/create",
Client::METHOD_POST, Client::METHOD_POST,
@ -830,7 +829,7 @@ class ApiClient
* *
* @return ApiResponse * @return ApiResponse
*/ */
public function ordersCreate(array $order, $site = null) public function ordersCreate(array $order, $site = null): ApiResponse
{ {
if (!count($order)) { if (!count($order)) {
throw new InvalidArgumentException( throw new InvalidArgumentException(
@ -841,7 +840,7 @@ class ApiClient
return $this->client->makeRequest( return $this->client->makeRequest(
'/orders/create', '/orders/create',
Client::METHOD_POST, Client::METHOD_POST,
$this->fillSite($site, array('order' => json_encode($order))) $this->fillSite($site, ['order' => json_encode($order)])
); );
} }
@ -966,7 +965,7 @@ class ApiClient
* *
* @return ApiResponse * @return ApiResponse
*/ */
public function ordersEdit(array $order, $by = 'externalId', $site = null) public function ordersEdit(array $order, $by = 'externalId', $site = null): ApiResponse
{ {
if (!count($order)) { if (!count($order)) {
throw new InvalidArgumentException( throw new InvalidArgumentException(
@ -987,7 +986,7 @@ class ApiClient
Client::METHOD_POST, Client::METHOD_POST,
$this->fillSite( $this->fillSite(
$site, $site,
array('order' => json_encode($order), 'by' => $by) ['order' => json_encode($order), 'by' => $by]
) )
); );
} }
@ -2932,4 +2931,186 @@ class ApiClient
return $params; return $params;
} }
/**
* @param array $request
* @param int $checkId
* @return \RetailCrm\Response\ApiResponse
*/
public function checkStatusPlVerification(array $request, int $checkId): ApiResponse
{
return $this->client->makeRequest(
"/verification/sms/$checkId/status",
Client::METHOD_GET,
$request
);
}
/**
* @param array $request
* @return \RetailCrm\Response\ApiResponse
*/
public function loyaltyOrderApply(array $request): ApiResponse
{
return $this->client->makeRequest(
"/orders/loyalty/apply",
Client::METHOD_POST,
[
'site' => $request['site'],
'order' => json_encode($request['order']),
'bonuses' => $request['bonuses'],
]
);
}
/**
* @param array $request
* @return \RetailCrm\Response\ApiResponse
*/
public function loyaltyOrderCalculate(array $request): ApiResponse
{
return $this->client->makeRequest(
"/loyalty/calculate",
Client::METHOD_POST,
[
'site' => json_encode($request['site']),
'order' => json_encode($request['order']),
'bonuses' => $request['bonuses']
]
);
}
/**
* @return \RetailCrm\Response\ApiResponse
*/
public function getCredentials(): ApiResponse
{
return $this->unversionedClient->makeRequest(
"/credentials",
Client::METHOD_GET
);
}
/**
* @param array $request
* @return \RetailCrm\Response\ApiResponse
*/
public function createLoyaltyAccount(array $request): ApiResponse
{
return $this->client->makeRequest(
"/loyalty/account/create",
Client::METHOD_POST,
[
'loyaltyAccount' => json_encode($request['loyaltyAccount']),
'site' => $request['site'],
]
);
}
/**
* @param int $loyaltyId
* @return \RetailCrm\Response\ApiResponse
*/
public function activateLoyaltyAccount(int $loyaltyId): ApiResponse
{
return $this->client->makeRequest(
"/loyalty/account/".$loyaltyId."/activate",
Client::METHOD_POST
);
}
/**
* @param array $request
* @return \RetailCrm\Response\ApiResponse
*/
public function sendVerificationCode(array $request): ApiResponse
{
return $this->client->makeRequest(
"/verification/sms/confirm",
Client::METHOD_POST,
[
'verification'=> json_encode($request['verification'])
]
);
}
/**
* @param array $request
* @return \RetailCrm\Response\ApiResponse
*/
public function getLoyaltyAccounts(array $request): ApiResponse
{
return $this->client->makeRequest(
"/loyalty/accounts",
Client::METHOD_GET,
$request
);
}
/**
* @param int $loyaltyId
* @return \RetailCrm\Response\ApiResponse
*/
public function getLoyaltyLoyalty(int $loyaltyId): ApiResponse
{
return $this->client->makeRequest(
'/loyalty/loyalties/' . $loyaltyId,
Client::METHOD_GET
);
}
/**
* @return \RetailCrm\Response\ApiResponse
*/
public function getLoyaltyLoyalties(): ApiResponse
{
return $this->client->makeRequest(
'/loyalty/loyalties',
Client::METHOD_GET
);
}
/**
* @param array $request
* @param int $accountId
*
* @return \RetailCrm\Response\ApiResponse
*/
public function editLoyaltyAccount(array $request, int $accountId): ApiResponse
{
return $this->client->makeRequest(
'/loyalty/account/' . $accountId . '/edit',
Client::METHOD_POST,
[
'loyaltyAccount'=> json_encode($request['loyaltyAccount']),
'id' => $request['id']
]
);
}
/**
* @param array $request
* @return \RetailCrm\Response\ApiResponse
*/
protected function confirmLpVerificationBySMS(array $request): ApiResponse
{
return $this->client->makeRequest(
'/verification/sms/confirm',
Client::METHOD_POST,
$request
);
}
/**
* @param array $request
* @return \RetailCrm\Response\ApiResponse
*/
public function sendSmsForLpVerification(array $request): ApiResponse
{
return $this->client->makeRequest(
'/verification/sms/send',
Client::METHOD_POST,
$request
);
}
} }

View File

@ -25,8 +25,8 @@ class Logger
public static function getInstance($logPath = '/bitrix/modules/intaro.retailcrm/log', $files = 3) public static function getInstance($logPath = '/bitrix/modules/intaro.retailcrm/log', $files = 3)
{ {
if (empty(self::$instance) if (empty(self::$instance)
|| self::$instance instanceof Logger || (self::$instance instanceof self
&& (self::$instance->logPath != $logPath || self::$instance->files != $files) && (self::$instance->logPath !== $logPath || self::$instance->files !== $files))
) { ) {
self::$instance = new Logger($logPath, $files); self::$instance = new Logger($logPath, $files);
} }
@ -40,12 +40,12 @@ class Logger
* @param string $logPath * @param string $logPath
* @param int $files * @param int $files
*/ */
private function __construct($logPath = '/bitrix/modules/intaro.retailcrm/log', $files = 3) public function __construct($logPath = '/bitrix/modules/intaro.retailcrm/log', $files = 3)
{ {
$this->logPath = $logPath; $this->logPath = $logPath;
$this->files = $files; $this->files = $files;
} }
public function write($dump, $file = 'info') public function write($dump, $file = 'info')
{ {
$rsSites = CSite::GetList($by, $sort, array('DEF' => 'Y')); $rsSites = CSite::GetList($by, $sort, array('DEF' => 'Y'));
@ -53,19 +53,19 @@ class Logger
if (!is_dir($ar['ABS_DOC_ROOT'] . $this->logPath . '/')) { if (!is_dir($ar['ABS_DOC_ROOT'] . $this->logPath . '/')) {
mkdir($ar['ABS_DOC_ROOT'] . $this->logPath . '/'); mkdir($ar['ABS_DOC_ROOT'] . $this->logPath . '/');
} }
$file = $ar['ABS_DOC_ROOT'] . $this->logPath . '/' . $file . '.log'; $file = $ar['ABS_DOC_ROOT'] . $this->logPath . '/' . $file . '.log';
$data['TIME'] = date('Y-m-d H:i:s'); $data['TIME'] = date('Y-m-d H:i:s');
$data['DATA'] = $dump; $data['DATA'] = $dump;
$f = fopen($file, "a+"); $f = fopen($file, "a+");
fwrite($f, print_r($data, true)); fwrite($f, print_r($data, true));
fclose($f); fclose($f);
// if filesize more than 5 Mb rotate it // if filesize more than 5 Mb rotate it
if (filesize($file) > 5242880) { if (filesize($file) > 5242880) {
$this->rotate($file); $this->rotate($file);
} }
} }
private function rotate($file) private function rotate($file)
@ -105,5 +105,4 @@ class Logger
{ {
file_put_contents($file, ''); file_put_contents($file, '');
} }
} }

View File

@ -1,5 +1,6 @@
<?php <?php
use Intaro\RetailCrm\Component\ServiceLocator;
use Bitrix\Sale\Delivery\Services\EmptyDeliveryService; use Bitrix\Sale\Delivery\Services\EmptyDeliveryService;
use Bitrix\Sale\Internals\OrderPropsTable; use Bitrix\Sale\Internals\OrderPropsTable;
use Bitrix\Sale\Internals\StatusTable; use Bitrix\Sale\Internals\StatusTable;
@ -9,13 +10,17 @@ use RetailCrm\Exception\InvalidJsonException;
use Intaro\RetailCrm\Service\ManagerService; use Intaro\RetailCrm\Service\ManagerService;
IncludeModuleLangFile(__FILE__); IncludeModuleLangFile(__FILE__);
require_once __DIR__ . '/../../lib/component/servicelocator.php';
require_once __DIR__ . '/../../lib/service/utils.php';
class RCrmActions class RCrmActions
{ {
public static $MODULE_ID = 'intaro.retailcrm'; public static $MODULE_ID = 'intaro.retailcrm';
public static $CRM_ORDER_FAILED_IDS = 'order_failed_ids'; public static $CRM_ORDER_FAILED_IDS = 'order_failed_ids';
public static $CRM_API_VERSION = 'api_version'; public static $CRM_API_VERSION = 'api_version';
public const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED'; public const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED';
/** /**
* @return array * @return array
*/ */
@ -23,7 +28,7 @@ class RCrmActions
{ {
$arSites = []; $arSites = [];
$rsSites = CSite::GetList($by, $sort, ['ACTIVE' => 'Y']); $rsSites = CSite::GetList($by, $sort, ['ACTIVE' => 'Y']);
while ($ar = $rsSites->Fetch()) { while ($ar = $rsSites->Fetch()) {
$arSites[] = $ar; $arSites[] = $ar;
} }
@ -183,13 +188,13 @@ class RCrmActions
public static function eventLog($auditType, $itemId, $description) public static function eventLog($auditType, $itemId, $description)
{ {
CEventLog::Add(array( CEventLog::Add([
'SEVERITY' => 'SECURITY', 'SEVERITY' => 'SECURITY',
'AUDIT_TYPE_ID' => $auditType, 'AUDIT_TYPE_ID' => $auditType,
'MODULE_ID' => self::$MODULE_ID, 'MODULE_ID' => self::$MODULE_ID,
'ITEM_ID' => $itemId, 'ITEM_ID' => $itemId,
'DESCRIPTION' => $description, 'DESCRIPTION' => $description,
)); ]);
} }
/** /**
@ -202,7 +207,7 @@ class RCrmActions
{ {
RetailCrmOrder::uploadOrders(); RetailCrmOrder::uploadOrders();
$failedIds = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, 0)); $failedIds = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, 0));
if (is_array($failedIds) && !empty($failedIds)) { if (is_array($failedIds) && !empty($failedIds)) {
RetailCrmOrder::uploadOrders(50, true); RetailCrmOrder::uploadOrders(50, true);
} }
@ -237,23 +242,14 @@ class RCrmActions
* working with nested arrs * working with nested arrs
* *
* @param array $arr * @param array $arr
*
* @return array * @return array
*/ */
public static function clearArr($arr) public static function clearArr(array $arr): array
{ {
if (is_array($arr) === false) { /** @var \Intaro\RetailCrm\Service\Utils $utils */
return $arr; $utils = ServiceLocator::getOrCreate(\Intaro\RetailCrm\Service\Utils::class);
} return $utils->clearArray($arr);
$result = array();
foreach ($arr as $index => $node ) {
$result[ $index ] = is_array($node) === true ? self::clearArr($node) : trim($node);
if ($result[ $index ] == '' || $result[ $index ] === null || count($result[ $index ]) < 1) {
unset($result[ $index ]);
}
}
return $result;
} }
/** /**
@ -261,13 +257,12 @@ class RCrmActions
* @param array|bool|\SplFixedArray|string $str in SITE_CHARSET * @param array|bool|\SplFixedArray|string $str in SITE_CHARSET
* *
* @return array|bool|\SplFixedArray|string $str in utf-8 * @return array|bool|\SplFixedArray|string $str in utf-8
* @global $APPLICATION
*/ */
public static function toJSON($str) public static function toJSON($str)
{ {
global $APPLICATION; /** @var \Intaro\RetailCrm\Service\Utils $utils */
$utils = ServiceLocator::getOrCreate(\Intaro\RetailCrm\Service\Utils::class);
return $APPLICATION->ConvertCharset($str, SITE_CHARSET, 'utf-8'); return $utils->toUTF8($str);
} }
/** /**
@ -275,13 +270,12 @@ class RCrmActions
* @param string|array|\SplFixedArray $str in utf-8 * @param string|array|\SplFixedArray $str in utf-8
* *
* @return array|bool|\SplFixedArray|string $str in SITE_CHARSET * @return array|bool|\SplFixedArray|string $str in SITE_CHARSET
* @global $APPLICATION
*/ */
public static function fromJSON($str) public static function fromJSON($str)
{ {
global $APPLICATION; /** @var \Intaro\RetailCrm\Service\Utils $utils */
$utils = ServiceLocator::getOrCreate(\Intaro\RetailCrm\Service\Utils::class);
return $APPLICATION->ConvertCharset($str, 'utf-8', SITE_CHARSET); return $utils->fromUTF8($str);
} }
/** /**

View File

@ -172,4 +172,12 @@ class ApiResponse implements \ArrayAccess
return $this->response[$offset]; return $this->response[$offset];
} }
/**
* @return array
*/
public function getResponseBody()
{
return $this->response;
}
} }

View File

@ -9,8 +9,12 @@
* @package RetailCRM * @package RetailCRM
*/ */
use Intaro\RetailCrm\Component\ConfigProvider;
IncludeModuleLangFile(__FILE__); IncludeModuleLangFile(__FILE__);
require_once __DIR__ . '/../../lib/component/configprovider.php';
/** /**
* PHP version 5.3 * PHP version 5.3
* *
@ -19,840 +23,6 @@ IncludeModuleLangFile(__FILE__);
* @category RetailCRM * @category RetailCRM
* @package RetailCRM * @package RetailCRM
*/ */
class RetailcrmConfigProvider class RetailcrmConfigProvider extends ConfigProvider
{ {
/** @var bool|null|string */
private static $apiUrl;
/** @var bool|null|string */
private static $apiKey;
/** @var bool|null|string */
private static $catalogBasePrice;
/** @var bool|null|string */
private static $currency;
/** @var bool|null|string */
private static $orderDimensions;
/** @var bool|null|string */
private static $corporateClientName;
/** @var bool|null|string */
private static $corporateClientAddress;
/** @var bool|null|string */
private static $corporateClient;
/** @var bool|null|string $shipmentDeducted */
private static $shipmentDeducted;
/** @var array $sitesList */
private static $sitesList;
/** @var array $sitesListCorporate */
private static $sitesListCorporate;
/** @var bool|null|string $orderNumbers */
private static $orderNumbers;
/** @var array $orderTypes */
private static $orderTypes;
/** @var array $deliveryTypes */
private static $deliveryTypes;
/** @var array $paymentTypes */
private static $paymentTypes;
/** @var array $integrationPayment */
private static $integrationPayment;
/** @var array $paymentStatuses */
private static $paymentStatuses;
/** @var array $payment */
private static $payment;
/** @var array $orderProps */
private static $orderProps;
/** @var array $legalDetails */
private static $legalDetails;
/** @var array $contragentTypes */
private static $contragentTypes;
/** @var array $cancellableOrderPaymentStatuses */
private static $cancellableOrderPaymentStatuses;
/** @var array $customFields */
private static $customFields;
/** @var array $infoblocksInventories */
private static $infoblocksInventories;
/** @var array $stores */
private static $stores;
/** @var array $shops */
private static $shops;
/**
* @return bool|string|null
*/
public static function getApiUrl()
{
if (self::isEmptyNotZero(static::$apiUrl)) {
static::$apiUrl = static::getOption(RetailcrmConstants::CRM_API_HOST_OPTION);
}
return static::$apiUrl;
}
/**
* @return bool|string|null
*/
public static function getApiKey()
{
if (self::isEmptyNotZero(static::$apiKey)) {
static::$apiKey = static::getOption(RetailcrmConstants::CRM_API_KEY_OPTION);
}
return static::$apiKey;
}
/**
* getCorporateClientName
*
* @return bool|string|null
*/
public static function getCorporateClientName()
{
if (self::isEmptyNotZero(static::$corporateClientName)) {
static::$corporateClientName = static::getUnserializedOption(RetailcrmConstants::CRM_CORP_NAME);
}
return static::$corporateClientName;
}
/**
* getCorporateClientAddress
*
* @return bool|string|null
*/
public static function getCorporateClientAddress()
{
if (self::isEmptyNotZero(static::$corporateClientAddress)) {
static::$corporateClientAddress = static::getUnserializedOption(RetailcrmConstants::CRM_CORP_ADDRESS);
}
return static::$corporateClientAddress;
}
/**
* getCorporateClient
*
* @return bool|string|null
*/
public static function getCorporateClientStatus()
{
if (self::isEmptyNotZero(static::$corporateClient)) {
static::$corporateClient = static::getOption(RetailcrmConstants::CRM_CC);
}
return static::$corporateClient;
}
/**
* getSitesList
*
* @return array
*/
public static function getSitesList()
{
if (self::isEmptyNotZero(static::$sitesList)) {
static::$sitesList = static::getUnserializedOption(RetailcrmConstants::CRM_SITES_LIST);
}
return static::$sitesList;
}
/**
* getSitesListCorporate
*
* @return array
*/
public static function getSitesListCorporate()
{
if (self::isEmptyNotZero(static::$sitesListCorporate)) {
static::$sitesListCorporate = static::getUnserializedOption(
RetailcrmConstants::CRM_SITES_LIST_CORPORATE
);
}
return static::$sitesListCorporate;
}
/**
* isOnlineConsultantEnabled
*
* @return bool
*/
public static function isOnlineConsultantEnabled()
{
return static::getOption(RetailcrmConstants::CRM_ONLINE_CONSULTANT) === 'Y';
}
/**
* getOnlineConsultantScript
*
* @return string
*/
public static function getOnlineConsultantScript()
{
return trim(static::getOption(RetailcrmConstants::CRM_ONLINE_CONSULTANT_SCRIPT, ""));
}
/**
* setOnlineConsultant
*
* @param string $value
*/
public static function setOnlineConsultant($value)
{
static::setOption(RetailcrmConstants::CRM_ONLINE_CONSULTANT, $value);
}
/**
* @return bool|string|null
*/
public static function getCrmPurchasePrice()
{
return static::getOption(RetailcrmConstants::CRM_PURCHASE_PRICE_NULL);
}
public static function getProtocol()
{
return static::getOption(RetailcrmConstants::PROTOCOL);
}
/**
* @return string
*/
public static function getSiteName(): string
{
$siteName = COption::GetOptionString('main', 'site_name');
if (!$siteName) {
return '';
}
return $siteName;
}
/**
* @return mixed
*/
public static function getUsersMap()
{
return static::getUnserializedOption(RetailcrmConstants::CRM_USERS_MAP);
}
/**
* @param array|null $userMap
*
* @return bool
*/
public static function setUsersMap(?array $userMap): bool
{
return static::setOption(RetailcrmConstants::CRM_USERS_MAP, serialize($userMap));
}
/**
* @param $profileId
*
* @return false|string|null
*/
public static function getCrmBasePrice($profileId)
{
return self::getOption(RetailcrmConstants::CRM_CATALOG_BASE_PRICE . '_' . $profileId, 1);
}
public static function setProfileBasePrice($profileId, $priceTypes): void
{
self::setOption(
RetailcrmConstants::CRM_CATALOG_BASE_PRICE . '_' . $profileId,
htmlspecialchars(trim($priceTypes))
);
}
/**
* @return string
*/
public static function getDefaultIcmlPath(): string
{
return (COption::GetOptionString(
'catalog',
'export_default_path',
'/bitrix/catalog_export/'))
. 'retailcrm.xml';
}
/**
* setOnlineConsultantScript
*
* @param string $value
*/
public function setOnlineConsultantScript($value)
{
static::setOption(RetailcrmConstants::CRM_ONLINE_CONSULTANT_SCRIPT, $value);
}
/**
* getOrderTypes
*
* @return array
*/
public static function getOrderTypes()
{
if (self::isEmptyNotZero(static::$orderTypes)) {
static::$orderTypes = static::getUnserializedOption(RetailcrmConstants::CRM_ORDER_TYPES_ARR);
}
return static::$orderTypes;
}
/**
* setOrderTypes
*
* @param array $orderTypesArr
*/
public static function setOrderTypes($orderTypesArr)
{
static::setOption(RetailcrmConstants::CRM_ORDER_TYPES_ARR, serialize(RCrmActions::clearArr($orderTypesArr)));
}
/**
* getDeliveryTypes
*
* @return array
*/
public static function getDeliveryTypes()
{
if (self::isEmptyNotZero(static::$deliveryTypes)) {
static::$deliveryTypes = static::getUnserializedOption(RetailcrmConstants::CRM_DELIVERY_TYPES_ARR);
}
return static::$deliveryTypes;
}
/**
* setDeliveryTypes
*
* @param array $deliveryTypesArr
*/
public static function setDeliveryTypes($deliveryTypesArr)
{
static::setOption(RetailcrmConstants::CRM_DELIVERY_TYPES_ARR, serialize(RCrmActions::clearArr($deliveryTypesArr)));
}
/**
* getPaymentTypes
*
* @return array
*/
public static function getPaymentTypes()
{
if (self::isEmptyNotZero(static::$paymentTypes)) {
static::$paymentTypes = static::getUnserializedOption(RetailcrmConstants::CRM_PAYMENT_TYPES);
}
return static::$paymentTypes;
}
/**
* getIntegrationPaymentTypes
*
* @return array
*/
public static function getIntegrationPaymentTypes(): array
{
if (self::isEmptyNotZero(static::$integrationPayment)) {
$option = static::getUnserializedOption(RetailcrmConstants::CRM_INTEGRATION_PAYMENT);
static::$integrationPayment = is_array($option) ? $option : [];
}
return static::$integrationPayment;
}
/**
* setIntegrationPaymentTypes
* @param $integrationPayment
*/
public static function setIntegrationPaymentTypes($integrationPayment)
{
static::setOption(RetailcrmConstants::CRM_INTEGRATION_PAYMENT, serialize(RCrmActions::clearArr($integrationPayment)));
}
/**
* setIntegrationDelivery
* @param $deliveryIntegrationCode
*/
public static function setIntegrationDelivery($deliveryIntegrationCode)
{
static::setOption(RetailcrmConstants::CRM_INTEGRATION_DELIVERY, serialize(RCrmActions::clearArr($deliveryIntegrationCode)));
}
/**
* setPaymentTypes
*
* @param array $paymentTypesArr
*/
public static function setPaymentTypes($paymentTypesArr)
{
static::setOption(RetailcrmConstants::CRM_PAYMENT_TYPES, serialize(RCrmActions::clearArr($paymentTypesArr)));
}
/**
* getPaymentStatuses
*
* @return array
*/
public static function getPaymentStatuses()
{
if (self::isEmptyNotZero(static::$paymentStatuses)) {
static::$paymentStatuses = static::getUnserializedOption(RetailcrmConstants::CRM_PAYMENT_STATUSES);
}
return static::$paymentStatuses;
}
/**
* getPaymentStatuses
*
* @param array $paymentStatusesArr
*/
public static function setPaymentStatuses($paymentStatusesArr)
{
static::setOption(RetailcrmConstants::CRM_PAYMENT_STATUSES, serialize(RCrmActions::clearArr($paymentStatusesArr)));
}
/**
* getPayment
*
* @return array
*/
public static function getPayment()
{
if (self::isEmptyNotZero(static::$payment)) {
static::$payment = static::getUnserializedOption(RetailcrmConstants::CRM_PAYMENT);
}
return static::$payment;
}
/**
* getOrderProps
*
* @return array
*/
public static function getOrderProps()
{
if (self::isEmptyNotZero(static::$orderProps)) {
static::$orderProps = static::getUnserializedOption(RetailcrmConstants::CRM_ORDER_PROPS);
}
return static::$orderProps;
}
/**
* getLegalDetails
*
* @return array
*/
public static function getLegalDetails()
{
if (self::isEmptyNotZero(static::$legalDetails)) {
static::$legalDetails = static::getUnserializedOption(RetailcrmConstants::CRM_LEGAL_DETAILS);
}
return static::$legalDetails;
}
/**
* getContragentTypes
*
* @return array
*/
public static function getContragentTypes()
{
if (self::isEmptyNotZero(static::$contragentTypes)) {
static::$contragentTypes = static::getUnserializedOption(RetailcrmConstants::CRM_CONTRAGENT_TYPE);
}
return static::$contragentTypes;
}
/**
* setContragentTypes
*
* @param array $contragentTypeArr
*/
public static function setContragentTypes($contragentTypeArr)
{
static::setOption(RetailcrmConstants::CRM_CONTRAGENT_TYPE, serialize(RCrmActions::clearArr($contragentTypeArr)));
}
/**
* getCustomFields
*
* @return array
*/
public static function getCustomFields()
{
if (self::isEmptyNotZero(static::$customFields)) {
static::$customFields = static::getUnserializedOption(RetailcrmConstants::CRM_CUSTOM_FIELDS);
}
return static::$customFields;
}
/**
* getCancellableOrderPaymentStatuses
*
* @return array
*/
public static function getCancellableOrderPaymentStatuses()
{
if (self::isEmptyNotZero(static::$cancellableOrderPaymentStatuses)) {
static::$cancellableOrderPaymentStatuses = static::getUnserializedOption(
RetailcrmConstants::CRM_CANCEL_ORDER
);
}
return static::$cancellableOrderPaymentStatuses;
}
/**
* getLastOrderId
*
* @return bool|string|null
*/
public static function getLastOrderId()
{
return static::getOption(RetailcrmConstants::CRM_ORDER_LAST_ID);
}
/**
* getSendPaymentAmount
*
* @return bool|string|null
*/
public static function getSendPaymentAmount()
{
return static::getOption(RetailcrmConstants::SEND_PAYMENT_AMOUNT);
}
/**
* setSendPaymentAmount
*
* @param string $value
*/
public static function setSendPaymentAmount($value)
{
static::setOption(RetailcrmConstants::SEND_PAYMENT_AMOUNT, $value);
}
/**
* Returns true if payment amount should be sent from CMS to RetailCRM.
*
* @return bool|string|null
*/
public static function shouldSendPaymentAmount()
{
return static::getSendPaymentAmount() === 'Y';
}
/**
* setLastOrderId
*
* @param $id
*/
public static function setLastOrderId($id)
{
static::setOption(RetailcrmConstants::CRM_ORDER_LAST_ID, $id);
}
/**
* getFailedOrdersIds
*
* @return array
*/
public static function getFailedOrdersIds()
{
return static::getUnserializedOption(RetailcrmConstants::CRM_ORDER_FAILED_IDS);
}
/**
* setFailedOrdersIds
*
* @param $ids
*/
public static function setFailedOrdersIds($ids)
{
static::setOption(RetailcrmConstants::CRM_ORDER_FAILED_IDS, serialize($ids));
}
/**
* getOrderNumbers
*
* @return bool|string|null
*/
public static function getOrderNumbers()
{
if (self::isEmptyNotZero(self::$orderNumbers)) {
self::$orderNumbers = static::getOption(RetailcrmConstants::CRM_ORDER_NUMBERS);
}
return self::$orderNumbers;
}
/**
* getOrderHistoryDate
*
* @return bool|string|null
*/
public static function getOrderHistoryDate()
{
return static::getOption(RetailcrmConstants::CRM_ORDER_HISTORY_DATE);
}
/**
* Returns customers history since ID
*
* @return int
*/
public static function getCustomersHistorySinceId()
{
return (int) static::getOption(RetailcrmConstants::CRM_CUSTOMERS_HISTORY_SINCE_ID);
}
/**
* Sets new customers history since ID
*
* @param int $sinceId
*/
public static function setCustomersHistorySinceId($sinceId)
{
static::setOption(RetailcrmConstants::CRM_CUSTOMERS_HISTORY_SINCE_ID, $sinceId);
}
/**
* getCatalogBasePrice
*
* @return bool|string|null
*/
public static function getCatalogBasePrice()
{
if (self::isEmptyNotZero(static::$catalogBasePrice)) {
static::$catalogBasePrice = static::getOption(RetailcrmConstants::CRM_CATALOG_BASE_PRICE);
}
return static::$catalogBasePrice;
}
/**
* @param $profileId
*
* @return false|string|null
*/
public static function getCatalogBasePriceByProfile($profileId)
{
return COption::GetOptionString(
RetailcrmConstants::MODULE_ID,
RetailcrmConstants::CRM_CATALOG_BASE_PRICE . '_' . $profileId,
0
);
}
/**
* getOrderDimensions
*
* @return bool|string|null
*/
public static function getOrderDimensions()
{
if (self::isEmptyNotZero(static::$orderDimensions)) {
static::$orderDimensions = static::getOption(RetailcrmConstants::CRM_ORDER_DIMENSIONS, 'N');
}
return static::$orderDimensions;
}
/**
* getCurrency
*
* @return bool|string|null
*/
public static function getCurrency()
{
if (self::isEmptyNotZero(static::$currency)) {
static::$currency = static::getOption(RetailcrmConstants::CRM_CURRENCY);
}
return static::$currency;
}
/**
* Returns currency from settings. If it's not set - returns Bitrix base currency.
*
* @return bool|string|null
*/
public static function getCurrencyOrDefault()
{
return self::getCurrency() ? self::getCurrency() : \Bitrix\Currency\CurrencyManager::getBaseCurrency();
}
/**
* getInfoblocksInventories
*
* @return array
*/
public static function getInfoblocksInventories()
{
if (self::isEmptyNotZero(static::$infoblocksInventories)) {
static::$infoblocksInventories = static::getUnserializedOption(
RetailcrmConstants::CRM_IBLOCKS_INVENTORIES
);
}
return static::$infoblocksInventories;
}
/**
* getStores
*
* @return array
*/
public static function getStores()
{
if (self::isEmptyNotZero(static::$stores)) {
static::$stores = static::getUnserializedOption(RetailcrmConstants::CRM_STORES);
}
return static::$stores;
}
/**
* getShops
*
* @return array
*/
public static function getShops()
{
if (self::isEmptyNotZero(static::$shops)) {
static::$shops = static::getUnserializedOption(RetailcrmConstants::CRM_SHOPS);
}
return static::$shops;
}
/**
* getShipmentDeducted
*
* @return bool|string|null
*/
public static function getShipmentDeducted()
{
if (self::isEmptyNotZero(static::$shipmentDeducted)) {
static::$shipmentDeducted = static::getOption(RetailcrmConstants::CRM_SHIPMENT_DEDUCTED);
}
return static::$shipmentDeducted;
}
/**
* isPhoneRequired
*
* @return bool|string|null
*/
public static function isPhoneRequired()
{
return COption::GetOptionString("main", "new_user_phone_required") === 'Y';
}
/**
* Return integration_delivery option
*
* @return mixed
*/
public static function getCrmIntegrationDelivery()
{
return static::getUnserializedOption(RetailcrmConstants::CRM_INTEGRATION_DELIVERY);
}
/**
* Wraps Bitrix COption::GetOptionString(...)
*
* @param string $option
* @param int|string $def
*
* @return bool|string|null
*/
private static function getOption($option, $def = 0)
{
return COption::GetOptionString(
RetailcrmConstants::MODULE_ID,
$option,
$def
);
}
/**
* setOption
*
* @param $name
* @param string $value
* @param bool $desc
* @param string $site
*/
private static function setOption($name, string $value = '', bool $desc = false, string $site = ''): bool
{
return COption::SetOptionString(
RetailcrmConstants::MODULE_ID,
$name,
$value,
$desc,
$site
);
}
/**
* Wraps Bitrix unserialize(COption::GetOptionString(...))
*
* @param string $option
* @param int|string $def
*
* @return mixed
*/
private static function getUnserializedOption($option, $def = 0)
{
return unserialize(static::getOption($option, $def));
}
/**
* Returns true if value is empty and not zero (0 - digit)
*
* @param mixed $value
*
* @return bool
*/
private static function isEmptyNotZero($value)
{
return empty($value) && $value !== 0;
}
} }

View File

@ -9,8 +9,12 @@
* @package RetailCRM * @package RetailCRM
*/ */
use Intaro\RetailCrm\Component\Constants;
IncludeModuleLangFile(__FILE__); IncludeModuleLangFile(__FILE__);
require_once __DIR__ . '/../../lib/component/constants.php';
/** /**
* PHP version 5.3 * PHP version 5.3
* *
@ -19,63 +23,6 @@ IncludeModuleLangFile(__FILE__);
* @category RetailCRM * @category RetailCRM
* @package RetailCRM * @package RetailCRM
*/ */
class RetailcrmConstants class RetailcrmConstants extends Constants
{ {
public const MODULE_ID = 'intaro.retailcrm';
public const CRM_API_HOST_OPTION = 'api_host';
public const CRM_API_KEY_OPTION = 'api_key';
public const CRM_ORDER_TYPES_ARR = 'order_types_arr';
public const CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr';
public const CRM_DELIVERY_SERVICES_ARR = 'deliv_services_arr';
public const CRM_PAYMENT_TYPES = 'pay_types_arr';
public const CRM_INTEGRATION_PAYMENT = 'integration_payment';
public const CRM_PAYMENT_STATUSES = 'pay_statuses_arr';
public const CRM_PAYMENT = 'payment_arr'; //order payment Y/N
public const CRM_ORDER_LAST_ID = 'order_last_id';
public const CRM_ORDER_SITES = 'sites_ids';
public const CRM_ORDER_DISCHARGE = 'order_discharge';
public const CRM_SITES_LIST = 'sites_list';
public const CRM_ORDER_PROPS = 'order_props';
public const CRM_LEGAL_DETAILS = 'legal_details';
public const CRM_CUSTOM_FIELDS = 'custom_fields';
public const CRM_CONTRAGENT_TYPE = 'contragent_type';
public const CRM_SITES_LIST_CORPORATE = 'shops-corporate';
public const CRM_ORDER_NUMBERS = 'order_numbers';
public const CRM_CANCEL_ORDER = 'cansel_order';
public const CRM_INVENTORIES_UPLOAD = 'inventories_upload';
public const CRM_STORES = 'stores';
public const CRM_SHOPS = 'shops';
public const CRM_IBLOCKS_INVENTORIES = 'iblocks_inventories';
public const CRM_PRICES_UPLOAD = 'prices_upload';
public const CRM_PRICES = 'prices';
public const CRM_PRICE_SHOPS = 'price_shops';
public const CRM_IBLOCKS_PRICES = 'iblock_prices';
public const CRM_COLLECTOR = 'collector';
public const CRM_COLL_KEY = 'coll_key';
public const CRM_UA = 'ua';
public const CRM_UA_KEYS = 'ua_keys';
public const CRM_DISCOUNT_ROUND = 'discount_round';
public const CRM_CC = 'cc';
public const CRM_CORP_SHOPS = 'shops-corporate';
public const CRM_CORP_NAME = 'nickName-corporate';
public const CRM_CORP_ADDRESS = 'adres-corporate';
public const CRM_API_VERSION = 'api_version';
public const CRM_CURRENCY = 'currency';
public const CRM_ADDRESS_OPTIONS = 'address_options';
public const CRM_DIMENSIONS = 'order_dimensions';
public const PROTOCOL = 'protocol';
public const CRM_ORDER_FAILED_IDS = 'order_failed_ids';
public const CRM_CUSTOMERS_HISTORY_SINCE_ID = 'customer_history';
public const CRM_ORDER_HISTORY_DATE = 'order_history_date';
public const CRM_CATALOG_BASE_PRICE = 'catalog_base_price';
public const CRM_ORDER_DIMENSIONS = 'order_dimensions';
public const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED';
public const CRM_INTEGRATION_DELIVERY = 'integration_delivery';
public const CRM_SHIPMENT_DEDUCTED = 'shipment_deducted';
public const SEND_PAYMENT_AMOUNT = 'send_payment_amount';
public const CRM_ONLINE_CONSULTANT = 'online_consultant';
public const CRM_ONLINE_CONSULTANT_SCRIPT = 'online_consultant_script';
public const CRM_PURCHASE_PRICE_NULL = 'purchasePrice_null';
public const CRM_USERS_MAP = 'crm_users_map';
public const BITRIX_USER_ID_PREFIX = 'bitrixUserId-';
} }

View File

@ -11,6 +11,8 @@
IncludeModuleLangFile(__FILE__); IncludeModuleLangFile(__FILE__);
require_once __DIR__ . '/../../lib/component/dependencyloader.php';
/** /**
* PHP version 5.3 * PHP version 5.3
* *
@ -19,80 +21,6 @@ IncludeModuleLangFile(__FILE__);
* @category RetailCRM * @category RetailCRM
* @package RetailCRM * @package RetailCRM
*/ */
class RetailcrmDependencyLoader class RetailcrmDependencyLoader extends \Intaro\RetailCrm\Component\DependencyLoader
{ {
/** @var int */
const LEGACY_LOADER = 0;
/** @var int */
const D7_LOADER = 1;
/** @var int $loader */
private static $loader = self::D7_LOADER;
/**
* Loads dependencies
*
* @return bool
*/
public static function loadDependencies()
{
foreach (self::getDependencies() as $dependency) {
if (self::LEGACY_LOADER == self::$loader) {
if (!CModule::IncludeModule($dependency)) {
RCrmActions::eventLog(
__CLASS__ . '::' . __METHOD__,
$dependency,
'module not found'
);
return false;
}
} else {
try {
if (!\Bitrix\Main\Loader::includeModule($dependency)) {
RCrmActions::eventLog(
__CLASS__ . '::' . __METHOD__,
$dependency,
'module not found'
);
return false;
}
} catch (\Bitrix\Main\LoaderException $exception) {
RCrmActions::eventLog(
__CLASS__ . '::' . __METHOD__,
$dependency,
sprintf('error while trying to load module: %s', $exception->getMessage())
);
return false;
}
}
}
return true;
}
/**
* Set loader mode. Use RetailcrmDependencyLoader::LEGACY_LOADER or RetailcrmDependencyLoader::D7_LOADER
*
* @param $loader
*/
public static function setLoader($loader)
{
if (in_array($loader, array(self::LEGACY_LOADER, self::D7_LOADER))) {
self::$loader = $loader;
}
}
/**
* Returns array of required modules names
*
* @return array<string>
*/
public static function getDependencies()
{
return array("iblock", "sale", "catalog");
}
} }

View File

@ -3,22 +3,36 @@
use Bitrix\Main\Context\Culture; use Bitrix\Main\Context\Culture;
use Intaro\RetailCrm\Service\ManagerService; use Intaro\RetailCrm\Service\ManagerService;
use Bitrix\Sale\Payment; use Bitrix\Sale\Payment;
use RetailCrm\ApiClient; use Bitrix\Catalog\Model\Event;
use Bitrix\Main\UserTable;
use Bitrix\Sale\Order;
use Intaro\RetailCrm\Component\ConfigProvider;
use Intaro\RetailCrm\Model\Api\Response\OrdersCreateResponse;
use Intaro\RetailCrm\Model\Api\Response\OrdersEditResponse;
/** /**
* Class RetailCrmEvent * Class RetailCrmEvent
*/ */
class RetailCrmEvent class RetailCrmEvent
{ {
protected static $MODULE_ID = 'intaro.retailcrm'; protected static $MODULE_ID = 'intaro.retailcrm';
protected static $CRM_API_HOST_OPTION = 'api_host'; protected static $CRM_API_HOST_OPTION = 'api_host';
protected static $CRM_API_KEY_OPTION = 'api_key'; protected static $CRM_API_KEY_OPTION = 'api_key';
protected static $CRM_PAYMENT_TYPES = 'pay_types_arr'; protected static $CRM_ORDER_TYPES_ARR = 'order_types_arr';
protected static $CRM_PAYMENT_STATUSES = 'pay_statuses_arr'; protected static $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr';
protected static $CRM_PAYMENT = 'payment_arr'; //order payment Y/N protected static $CRM_PAYMENT_TYPES = 'pay_types_arr';
protected static $CRM_CUSTOM_FIELDS = 'custom_fields'; protected static $CRM_PAYMENT_STATUSES = 'pay_statuses_arr';
protected static $CRM_CONTRAGENT_TYPE = 'contragent_type'; protected static $CRM_PAYMENT = 'payment_arr';
protected static $CRM_SITES_LIST = 'sites_list'; protected static $CRM_ORDER_LAST_ID = 'order_last_id';
protected static $CRM_ORDER_PROPS = 'order_props';
protected static $CRM_LEGAL_DETAILS = 'legal_details';
protected static $CRM_CUSTOM_FIELDS = 'custom_fields';
protected static $CRM_CONTRAGENT_TYPE = 'contragent_type';
protected static $CRM_ORDER_FAILED_IDS = 'order_failed_ids';
protected static $CRM_SITES_LIST = 'sites_list';
protected static $CRM_CC = 'cc';
protected static $CRM_CORP_NAME = 'nickName-corporate';
protected static $CRM_CORP_ADRES = 'adres-corporate';
/** /**
* @param $arFields * @param $arFields
@ -31,22 +45,22 @@ class RetailCrmEvent
if (isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']) { if (isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']) {
return false; return false;
} }
if (!$arFields['RESULT']) { if (!$arFields['RESULT']) {
return false; return false;
} }
$optionsSitesList = RetailcrmConfigProvider::getSitesList(); $optionsSitesList = RetailcrmConfigProvider::getSitesList();
$api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey()); $api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey());
$resultOrder = RetailCrmUser::customerEdit($arFields, $api, $optionsSitesList); $resultOrder = RetailCrmUser::customerEdit($arFields, $api, $optionsSitesList);
if (!$resultOrder) { if (!$resultOrder) {
RCrmActions::eventLog('RetailCrmEvent::OnAfterUserUpdate', 'RetailCrmUser::customerEdit', 'error update customer'); RCrmActions::eventLog('RetailCrmEvent::OnAfterUserUpdate', 'RetailCrmUser::customerEdit', 'error update customer');
} }
return true; return true;
} }
/** /**
* onUpdateOrder * onUpdateOrder
* *
@ -59,19 +73,19 @@ class RetailCrmEvent
$GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = false; $GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = false;
return; return;
} }
$GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = true; $GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = true;
if (($arFields['CANCELED'] === 'Y') if (($arFields['CANCELED'] === 'Y')
&& (sizeof($arFields['BASKET_ITEMS']) == 0) && (sizeof($arFields['BASKET_ITEMS']) == 0)
&& (sizeof($arFields['ORDER_PROP']) == 0) && (sizeof($arFields['ORDER_PROP']) == 0)
) { ) {
$GLOBALS['ORDER_DELETE_USER_ADMIN'] = true; $GLOBALS['ORDER_DELETE_USER_ADMIN'] = true;
} }
return; return;
} }
/** /**
* orderDelete * orderDelete
* *
@ -80,67 +94,28 @@ class RetailCrmEvent
public function orderDelete($event) public function orderDelete($event)
{ {
$GLOBALS['RETAILCRM_ORDER_DELETE'] = true; $GLOBALS['RETAILCRM_ORDER_DELETE'] = true;
return; return;
} }
/** /**
* @param $event * @param $event
* *
* @return bool * @return array|bool|OrdersCreateResponse|OrdersEditResponse|null
* @throws \Bitrix\Main\ArgumentException
* @throws \Bitrix\Main\ObjectPropertyException * @throws \Bitrix\Main\ObjectPropertyException
* @throws \Bitrix\Main\SystemException * @throws \Bitrix\Main\SystemException
* @throws \Bitrix\Main\ArgumentException * @throws \Exception
*/ */
public function orderSave($event) public static function orderSave($event)
{ {
if (true == $GLOBALS['ORDER_DELETE_USER_ADMIN']) { if (!static::checkConfig()) {
return false; return null;
}
if ($GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] === false
&& $GLOBALS['RETAILCRM_ORDER_DELETE'] === true
) {
return false;
}
if ($GLOBALS['RETAIL_CRM_HISTORY'] === true) {
return false;
}
if (!CModule::IncludeModule('iblock')) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'iblock', 'module not found');
return false;
}
if (!CModule::IncludeModule('sale')) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'sale', 'module not found');
return false;
}
if (!CModule::IncludeModule('catalog')) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'catalog', 'module not found');
return false;
}
//exists getParameter("ENTITY")
if (method_exists($event, 'getId')) {
$obOrder = $event;
} elseif (method_exists($event, 'getParameter')) {
$obOrder = $event->getParameter('ENTITY');
} else {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'events', 'event error');
return false;
} }
$arOrder = RetailCrmOrder::orderObjToArr($obOrder); $arOrder = static::getOrderArray($event);
$api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey()); $api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey());
//params //params
$optionsOrderTypes = RetailcrmConfigProvider::getOrderTypes(); $optionsOrderTypes = RetailcrmConfigProvider::getOrderTypes();
$optionsDelivTypes = RetailcrmConfigProvider::getDeliveryTypes(); $optionsDelivTypes = RetailcrmConfigProvider::getDeliveryTypes();
@ -152,10 +127,9 @@ class RetailCrmEvent
$optionsLegalDetails = RetailcrmConfigProvider::getLegalDetails(); $optionsLegalDetails = RetailcrmConfigProvider::getLegalDetails();
$optionsContragentType = RetailcrmConfigProvider::getContragentTypes(); $optionsContragentType = RetailcrmConfigProvider::getContragentTypes();
$optionsCustomFields = RetailcrmConfigProvider::getCustomFields(); $optionsCustomFields = RetailcrmConfigProvider::getCustomFields();
//corp cliente swich //corp cliente swich
$optionCorpClient = RetailcrmConfigProvider::getCorporateClientStatus(); $optionCorpClient = RetailcrmConfigProvider::getCorporateClientStatus();
$arParams = RCrmActions::clearArr([ $arParams = RCrmActions::clearArr([
'optionsOrderTypes' => $optionsOrderTypes, 'optionsOrderTypes' => $optionsOrderTypes,
'optionsDelivTypes' => $optionsDelivTypes, 'optionsDelivTypes' => $optionsDelivTypes,
@ -168,32 +142,35 @@ class RetailCrmEvent
'optionsSitesList' => $optionsSitesList, 'optionsSitesList' => $optionsSitesList,
'optionsCustomFields' => $optionsCustomFields, 'optionsCustomFields' => $optionsCustomFields,
]); ]);
//many sites? //many sites?
if ($optionsSitesList) { if ($optionsSitesList) {
if (array_key_exists($arOrder['LID'], $optionsSitesList) && $optionsSitesList[$arOrder['LID']] !== null) { if (array_key_exists($arOrder['LID'], $optionsSitesList) && $optionsSitesList[$arOrder['LID']] !== null) {
$site = $optionsSitesList[$arOrder['LID']]; $site = $optionsSitesList[$arOrder['LID']];
} else { } else {
return false; return null;
} }
} elseif (!$optionsSitesList) { } elseif (!$optionsSitesList) {
$site = null; $site = null;
} }
//new order? //new order?
$orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arOrder['ID'], $site); $orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arOrder['ID'], $site);
if (isset($orderCrm['order'])) { if (isset($orderCrm['order'])) {
$methodApi = 'ordersEdit'; $methodApi = 'ordersEdit';
$arParams['crmOrder'] = $orderCrm['order']; $arParams['crmOrder'] = $orderCrm['order'];
} else { } else {
$methodApi = 'ordersCreate'; $methodApi = 'ordersCreate';
} }
$orderCompany = null; $orderCompany = null;
if ('Y' === $optionCorpClient) {
if (true === RetailCrmCorporateClient::isCorpTookExternalId((string) $arOrder['USER_ID'], $api)) { if (
RetailCrmCorporateClient::setPrefixForExternalId((string) $arOrder['USER_ID'], $api); ('Y' === $optionCorpClient)
} && true === RetailCrmCorporateClient::isCorpTookExternalId((string)$arOrder['USER_ID'], $api)
) {
RetailCrmCorporateClient::setPrefixForExternalId((string) $arOrder['USER_ID'], $api);
} }
//TODO эта управляющая конструкция по функционалу дублирует RetailCrmOrder::createCustomerForOrder. //TODO эта управляющая конструкция по функционалу дублирует RetailCrmOrder::createCustomerForOrder.
@ -207,34 +184,34 @@ class RetailCrmEvent
$userCorp = []; $userCorp = [];
$corpName = RetailcrmConfigProvider::getCorporateClientName(); $corpName = RetailcrmConfigProvider::getCorporateClientName();
$corpAddress = RetailcrmConfigProvider::getCorporateClientAddress(); $corpAddress = RetailcrmConfigProvider::getCorporateClientAddress();
foreach ($arOrder['PROPS']['properties'] as $prop) { foreach ($arOrder['PROPS']['properties'] as $prop) {
if ($prop['CODE'] === $corpName) { if ($prop['CODE'] === $corpName) {
$nickName = $prop['VALUE'][0]; $nickName = $prop['VALUE'][0];
} }
if ($prop['CODE'] === $corpAddress) { if ($prop['CODE'] === $corpAddress) {
$address = $prop['VALUE'][0]; $address = $prop['VALUE'][0];
} }
if (!empty($optionsLegalDetails) if (!empty($optionsLegalDetails)
&& $search = array_search($prop['CODE'], $optionsLegalDetails[$arOrder['PERSON_TYPE_ID']]) && $search = array_search($prop['CODE'], $optionsLegalDetails[$arOrder['PERSON_TYPE_ID']])
) { ) {
$contragent[$search] = $prop['VALUE'][0];//legal order data $contragent[$search] = $prop['VALUE'][0];//legal order data
} }
} }
if (!empty($contragentType)) { if (!empty($contragentType)) {
$contragent['contragentType'] = $contragentType; $contragent['contragentType'] = $contragentType;
} }
$customersCorporate = false; $customersCorporate = false;
$response = $api->customersCorporateList(['companyName' => $nickName]); $response = $api->customersCorporateList(['companyName' => $nickName]);
if ($response && $response->getStatusCode() == 200) { if ($response && $response->getStatusCode() == 200) {
$customersCorporate = $response['customersCorporate']; $customersCorporate = $response['customersCorporate'];
$singleCorp = reset($customersCorporate); $singleCorp = reset($customersCorporate);
if (!empty($singleCorp)) { if (!empty($singleCorp)) {
$userCorp['customerCorporate'] = $singleCorp; $userCorp['customerCorporate'] = $singleCorp;
$companiesResponse = $api->customersCorporateCompanies( $companiesResponse = $api->customersCorporateCompanies(
@ -245,7 +222,7 @@ class RetailCrmEvent
'id', 'id',
$site $site
); );
if ($companiesResponse && $companiesResponse->isSuccessful()) { if ($companiesResponse && $companiesResponse->isSuccessful()) {
$orderCompany = array_reduce( $orderCompany = array_reduce(
$companiesResponse['companies'], $companiesResponse['companies'],
@ -253,7 +230,7 @@ class RetailCrmEvent
if (is_array($item) && $item['name'] === $nickName) { if (is_array($item) && $item['name'] === $nickName) {
$carry = $item; $carry = $item;
} }
return $carry; return $carry;
}, },
null null
@ -266,35 +243,35 @@ class RetailCrmEvent
'ApiClient::customersCorporateList', 'ApiClient::customersCorporateList',
'error during fetching corporate customers' 'error during fetching corporate customers'
); );
return false; return null;
} }
//user //user
$userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arOrder['USER_ID'], $site); $userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arOrder['USER_ID'], $site);
if (!isset($userCrm['customer'])) { if (!isset($userCrm['customer'])) {
$arUser = Bitrix\Main\UserTable::getById($arOrder['USER_ID'])->fetch(); $arUser = UserTable::getById($arOrder['USER_ID'])->fetch();
if (!empty($address)) { if (!empty($address)) {
$arUser['PERSONAL_STREET'] = $address; $arUser['PERSONAL_STREET'] = $address;
} }
$resultUser = RetailCrmUser::customerSend($arUser, $api, 'individual', true, $site); $resultUser = RetailCrmUser::customerSend($arUser, $api, 'individual', true, $site);
if (!$resultUser) { if (!$resultUser) {
RCrmActions::eventLog( RCrmActions::eventLog(
__CLASS__ . '::' . __METHOD__, __CLASS__ . '::' . __METHOD__,
'RetailCrmUser::customerSend', 'RetailCrmUser::customerSend',
'error during creating customer' 'error during creating customer'
); );
return false; return null;
} }
$userCrm = ['customer' => ['externalId' => $arOrder['USER_ID']]]; $userCrm = ['customer' => ['externalId' => $arOrder['USER_ID']]];
} }
if (!isset($userCorp['customerCorporate'])) { if (!isset($userCorp['customerCorporate'])) {
$resultUserCorp = RetailCrmCorporateClient::clientSend( $resultUserCorp = RetailCrmCorporateClient::clientSend(
$arOrder, $arOrder,
@ -304,23 +281,23 @@ class RetailCrmEvent
false, false,
$site $site
); );
Logger::getInstance()->write($resultUserCorp, 'resultUserCorp'); Logger::getInstance()->write($resultUserCorp, 'resultUserCorp');
if (!$resultUserCorp) { if (!$resultUserCorp) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmCorporateClient::clientSend', 'error during creating client'); RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmCorporateClient::clientSend', 'error during creating client');
return false; return null;
} }
$arParams['customerCorporate'] = $resultUserCorp; $arParams['customerCorporate'] = $resultUserCorp;
$arParams['orderCompany'] = $resultUserCorp['mainCompany'] ?? null; $arParams['orderCompany'] = $resultUserCorp['mainCompany'] ?? null;
$customerCorporateAddress = []; $customerCorporateAddress = [];
$customerCorporateCompany = []; $customerCorporateCompany = [];
$addressResult = null; $addressResult = null;
$companyResult = null; $companyResult = null;
if (!empty($address)) { if (!empty($address)) {
//TODO address builder add //TODO address builder add
$customerCorporateAddress = [ $customerCorporateAddress = [
@ -328,24 +305,24 @@ class RetailCrmEvent
'isMain' => true, 'isMain' => true,
'text' => $address, 'text' => $address,
]; ];
$addressResult = $api->customersCorporateAddressesCreate($resultUserCorp['id'], $customerCorporateAddress, 'id', $site); $addressResult = $api->customersCorporateAddressesCreate($resultUserCorp['id'], $customerCorporateAddress, 'id', $site);
} }
$customerCorporateCompany = [ $customerCorporateCompany = [
'name' => $nickName, 'name' => $nickName,
'isMain' => true, 'isMain' => true,
'contragent' => $contragent, 'contragent' => $contragent,
]; ];
if (!empty($addressResult)) { if (!empty($addressResult)) {
$customerCorporateCompany['address'] = [ $customerCorporateCompany['address'] = [
'id' => $addressResult['id'], 'id' => $addressResult['id'],
]; ];
} }
$companyResult = $api->customersCorporateCompaniesCreate($resultUserCorp['id'], $customerCorporateCompany, 'id', $site); $companyResult = $api->customersCorporateCompaniesCreate($resultUserCorp['id'], $customerCorporateCompany, 'id', $site);
$customerCorporateContact = [ $customerCorporateContact = [
'isMain' => true, 'isMain' => true,
'customer' => [ 'customer' => [
@ -353,26 +330,26 @@ class RetailCrmEvent
'site' => $site, 'site' => $site,
], ],
]; ];
if (!empty($companyResult)) { if (!empty($companyResult)) {
$orderCompany = [ $orderCompany = [
'id' => $companyResult['id'], 'id' => $companyResult['id'],
]; ];
$customerCorporateContact['companies'] = [ $customerCorporateContact['companies'] = [
[ [
'company' => $orderCompany, 'company' => $orderCompany,
], ],
]; ];
} }
$api->customersCorporateContactsCreate( $api->customersCorporateContactsCreate(
$resultUserCorp['id'], $resultUserCorp['id'],
$customerCorporateContact, $customerCorporateContact,
'id', 'id',
$site $site
); );
$arParams['orderCompany'] = array_merge( $arParams['orderCompany'] = array_merge(
$customerCorporateCompany, $customerCorporateCompany,
['id' => $companyResult['id']] ['id' => $companyResult['id']]
@ -385,44 +362,61 @@ class RetailCrmEvent
$api, $api,
$site = null $site = null
); );
$arParams['customerCorporate'] = $userCorp['customerCorporate']; $arParams['customerCorporate'] = $userCorp['customerCorporate'];
if (!empty($orderCompany)) { if (!empty($orderCompany)) {
$arParams['orderCompany'] = $orderCompany; $arParams['orderCompany'] = $orderCompany;
} }
} }
$arParams['contactExId'] = $userCrm['customer']['externalId']; $arParams['contactExId'] = $userCrm['customer']['externalId'];
} else { } else {
//user //user
$userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arOrder['USER_ID'], $site); $userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arOrder['USER_ID'], $site);
if (!isset($userCrm['customer'])) { if (!isset($userCrm['customer'])) {
$arUser = Bitrix\Main\UserTable::getById($arOrder['USER_ID'])->fetch(); $arUser = Bitrix\Main\UserTable::getById($arOrder['USER_ID'])->fetch();
$resultUser = RetailCrmUser::customerSend($arUser, $api, $optionsContragentType[$arOrder['PERSON_TYPE_ID']], true, $site); $resultUser = RetailCrmUser::customerSend(
$arUser,
$api,
$optionsContragentType[$arOrder['PERSON_TYPE_ID']],
true,
$site
);
if (!$resultUser) { if (!$resultUser) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmUser::customerSend', 'error during creating customer'); RCrmActions::eventLog(
'RetailCrmEvent::orderSave',
return false; 'RetailCrmUser::customerSend',
} 'error during creating customer'
);
return null;
}http://localhost/personal/cart/
} }
} }
if (isset($arOrder['RESPONSIBLE_ID']) && !empty($arOrder['RESPONSIBLE_ID'])) { if (isset($arOrder['RESPONSIBLE_ID']) && !empty($arOrder['RESPONSIBLE_ID'])) {
$managerService = ManagerService::getInstance(); $managerService = ManagerService::getInstance();
$arParams['managerId'] = $managerService->getManagerCrmId($arOrder['RESPONSIBLE_ID']); $arParams['managerId'] = $managerService->getManagerCrmId($arOrder['RESPONSIBLE_ID']);
} }
//order //order
$resultOrder = RetailCrmOrder::orderSend($arOrder, $api, $arParams, true, $site, $methodApi); $resultOrder = RetailCrmOrder::orderSend($arOrder, $api, $arParams, true, $site, $methodApi);
if (!$resultOrder) { if (!$resultOrder) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmOrder::orderSend', 'error during creating order'); RCrmActions::eventLog(
'RetailCrmEvent::orderSave',
return false; 'RetailCrmOrder::orderSend',
'error during creating order'
);
return null;
} }
return true; return $resultOrder;
} }
/** /**
* @param \Bitrix\Sale\Payment $event * @param \Bitrix\Sale\Payment $event
* *
@ -433,22 +427,22 @@ class RetailCrmEvent
public function paymentSave(Payment $event) public function paymentSave(Payment $event)
{ {
$apiVersion = COption::GetOptionString(self::$MODULE_ID, 'api_version', 0); $apiVersion = COption::GetOptionString(self::$MODULE_ID, 'api_version', 0);
/** @var \Bitrix\Sale\Order $order */ /** @var \Bitrix\Sale\Order $order */
$order = $event->getCollection()->getOrder(); $order = $event->getCollection()->getOrder();
if ((isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']) if ((isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY'])
|| $apiVersion !== 'v5' || $apiVersion !== 'v5'
|| $order->isNew() || $order->isNew()
) { ) {
return false; return false;
} }
$optionsSitesList = RetailcrmConfigProvider::getSitesList(); $optionsSitesList = RetailcrmConfigProvider::getSitesList();
$optionsPaymentTypes = RetailcrmConfigProvider::getPaymentTypes(); $optionsPaymentTypes = RetailcrmConfigProvider::getPaymentTypes();
$optionsPayStatuses = RetailcrmConfigProvider::getPayment(); $optionsPayStatuses = RetailcrmConfigProvider::getPayment();
$integrationPaymentTypes = RetailcrmConfigProvider::getIntegrationPaymentTypes(); $integrationPaymentTypes = RetailcrmConfigProvider::getIntegrationPaymentTypes();
$arPayment = [ $arPayment = [
'ID' => $event->getId(), 'ID' => $event->getId(),
'ORDER_ID' => $event->getField('ORDER_ID'), 'ORDER_ID' => $event->getField('ORDER_ID'),
@ -458,7 +452,7 @@ class RetailCrmEvent
'LID' => $order->getSiteId(), 'LID' => $order->getSiteId(),
'DATE_PAID' => $event->getField('DATE_PAID'), 'DATE_PAID' => $event->getField('DATE_PAID'),
]; ];
if ($optionsSitesList) { if ($optionsSitesList) {
if (array_key_exists($arPayment['LID'], $optionsSitesList) && $optionsSitesList[$arPayment['LID']] !== null) { if (array_key_exists($arPayment['LID'], $optionsSitesList) && $optionsSitesList[$arPayment['LID']] !== null) {
$site = $optionsSitesList[$arPayment['LID']]; $site = $optionsSitesList[$arPayment['LID']];
@ -468,14 +462,14 @@ class RetailCrmEvent
} elseif (!$optionsSitesList) { } elseif (!$optionsSitesList) {
$site = null; $site = null;
} }
$api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey()); $api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey());
$orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arPayment['ORDER_ID'], $site); $orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arPayment['ORDER_ID'], $site);
if (isset($orderCrm['order'])) { if (isset($orderCrm['order'])) {
$payments = $orderCrm['order']['payments']; $payments = $orderCrm['order']['payments'];
} }
if ($payments) { if ($payments) {
foreach ($payments as $payment) { foreach ($payments as $payment) {
if (isset($payment['externalId'])) { if (isset($payment['externalId'])) {
@ -488,16 +482,16 @@ class RetailCrmEvent
} }
} }
} }
if (!empty($arPayment['PAY_SYSTEM_ID']) && isset($optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']])) { if (!empty($arPayment['PAY_SYSTEM_ID']) && isset($optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']])) {
$paymentToCrm = [ $paymentToCrm = [
'type' => $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']], 'type' => $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']],
]; ];
if (!empty($arPayment['ID'])) { if (!empty($arPayment['ID'])) {
$paymentToCrm['externalId'] = RCrmActions::generatePaymentExternalId($arPayment['ID']); $paymentToCrm['externalId'] = RCrmActions::generatePaymentExternalId($arPayment['ID']);
} }
$isIntegrationPayment $isIntegrationPayment
= RetailCrmService::isIntegrationPayment($arPayment['PAY_SYSTEM_ID'] ?? null); = RetailCrmService::isIntegrationPayment($arPayment['PAY_SYSTEM_ID'] ?? null);
@ -509,15 +503,15 @@ class RetailCrmEvent
$paymentToCrm['paidAt'] = $arPayment['DATE_PAID']; $paymentToCrm['paidAt'] = $arPayment['DATE_PAID'];
} }
} }
if (!empty($optionsPayStatuses[$arPayment['PAID']]) && !$isIntegrationPayment) { if (!empty($optionsPayStatuses[$arPayment['PAID']]) && !$isIntegrationPayment) {
$paymentToCrm['status'] = $optionsPayStatuses[$arPayment['PAID']]; $paymentToCrm['status'] = $optionsPayStatuses[$arPayment['PAID']];
} }
if (!empty($arPayment['ORDER_ID'])) { if (!empty($arPayment['ORDER_ID'])) {
$paymentToCrm['order']['externalId'] = $arPayment['ORDER_ID']; $paymentToCrm['order']['externalId'] = $arPayment['ORDER_ID'];
} }
if (RetailcrmConfigProvider::shouldSendPaymentAmount()) { if (RetailcrmConfigProvider::shouldSendPaymentAmount()) {
$paymentToCrm['amount'] = $arPayment['SUM']; $paymentToCrm['amount'] = $arPayment['SUM'];
} }
@ -525,9 +519,9 @@ class RetailCrmEvent
RCrmActions::eventLog('RetailCrmEvent::paymentSave', 'payments', 'OrderID = ' . $arPayment['ID'] . '. Payment not found.'); RCrmActions::eventLog('RetailCrmEvent::paymentSave', 'payments', 'OrderID = ' . $arPayment['ID'] . '. Payment not found.');
return false; return false;
} }
$arPaymentExtId = RCrmActions::generatePaymentExternalId($arPayment['ID']); $arPaymentExtId = RCrmActions::generatePaymentExternalId($arPayment['ID']);
if (array_key_exists($arPaymentExtId, $paymentsExternalIds)) { if (array_key_exists($arPaymentExtId, $paymentsExternalIds)) {
$paymentData = $paymentsExternalIds[$arPaymentExtId]; $paymentData = $paymentsExternalIds[$arPaymentExtId];
} elseif (array_key_exists($arPayment['ID'], $paymentsExternalIds)) { } elseif (array_key_exists($arPayment['ID'], $paymentsExternalIds)) {
@ -535,7 +529,7 @@ class RetailCrmEvent
} else { } else {
$paymentData = []; $paymentData = [];
} }
if (empty($paymentData)) { if (empty($paymentData)) {
RCrmActions::apiMethod($api, 'ordersPaymentCreate', __METHOD__, $paymentToCrm, $site); RCrmActions::apiMethod($api, 'ordersPaymentCreate', __METHOD__, $paymentToCrm, $site);
} elseif ($paymentData['type'] == $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']]) { } elseif ($paymentData['type'] == $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']]) {
@ -547,7 +541,7 @@ class RetailCrmEvent
); );
return false; return false;
} }
$paymentToCrm['externalId'] = $paymentData['externalId']; $paymentToCrm['externalId'] = $paymentData['externalId'];
RCrmActions::apiMethod($api, 'paymentEditByExternalId', __METHOD__, $paymentToCrm, $site); RCrmActions::apiMethod($api, 'paymentEditByExternalId', __METHOD__, $paymentToCrm, $site);
} elseif ($paymentData['type'] != $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']]) { } elseif ($paymentData['type'] != $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']]) {
@ -559,10 +553,10 @@ class RetailCrmEvent
); );
RCrmActions::apiMethod($api, 'ordersPaymentCreate', __METHOD__, $paymentToCrm, $site); RCrmActions::apiMethod($api, 'ordersPaymentCreate', __METHOD__, $paymentToCrm, $site);
} }
return true; return true;
} }
/** /**
* @param \Bitrix\Sale\Payment $event * @param \Bitrix\Sale\Payment $event
* *
@ -571,22 +565,22 @@ class RetailCrmEvent
public function paymentDelete(Payment $event): void public function paymentDelete(Payment $event): void
{ {
$apiVersion = COption::GetOptionString(self::$MODULE_ID, 'api_version', 0); $apiVersion = COption::GetOptionString(self::$MODULE_ID, 'api_version', 0);
if ((isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']) if ((isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY'])
|| $apiVersion != 'v5' || $apiVersion !== 'v5'
|| !$event->getId() || !$event->getId()
) { ) {
return; return;
} }
$optionsSitesList = RetailcrmConfigProvider::getSitesList(); $optionsSitesList = RetailcrmConfigProvider::getSitesList();
$arPayment = [ $arPayment = [
'ID' => $event->getId(), 'ID' => $event->getId(),
'ORDER_ID' => $event->getField('ORDER_ID'), 'ORDER_ID' => $event->getField('ORDER_ID'),
'LID' => $event->getCollection()->getOrder()->getSiteId(), 'LID' => $event->getCollection()->getOrder()->getSiteId(),
]; ];
if ($optionsSitesList) { if ($optionsSitesList) {
if (array_key_exists($arPayment['LID'], $optionsSitesList) && $optionsSitesList[$arPayment['LID']] !== null) { if (array_key_exists($arPayment['LID'], $optionsSitesList) && $optionsSitesList[$arPayment['LID']] !== null) {
$site = $optionsSitesList[$arPayment['LID']]; $site = $optionsSitesList[$arPayment['LID']];
@ -596,12 +590,10 @@ class RetailCrmEvent
} elseif (!$optionsSitesList) { } elseif (!$optionsSitesList) {
$site = null; $site = null;
} }
$api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0); $api = new RetailCrm\ApiClient(ConfigProvider::getApiUrl(), ConfigProvider::getApiKey());
$api_key = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_KEY_OPTION, 0);
$api = new ApiClient($api_host, $api_key);
$orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arPayment['ORDER_ID'], $site); $orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arPayment['ORDER_ID'], $site);
if (isset($orderCrm['order']['payments']) && $orderCrm['order']['payments']) { if (isset($orderCrm['order']['payments']) && $orderCrm['order']['payments']) {
foreach ($orderCrm['order']['payments'] as $payment) { foreach ($orderCrm['order']['payments'] as $payment) {
if (isset($payment['externalId']) if (isset($payment['externalId'])
@ -613,4 +605,50 @@ class RetailCrmEvent
} }
} }
} }
/**
* @return bool
*/
private static function checkConfig(): bool
{
if (true == $GLOBALS['ORDER_DELETE_USER_ADMIN']) {
return false;
}
if ($GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] === false
&& $GLOBALS['RETAILCRM_ORDER_DELETE'] === true
) {
return false;
}
if ($GLOBALS['RETAIL_CRM_HISTORY'] === true) {
return false;
}
if (!RetailcrmDependencyLoader::loadDependencies()) {
return false;
}
return true;
}
/**
* @param \Bitrix\Sale\Order|\Bitrix\Main\Event $event
*
* @throws \Bitrix\Main\SystemException
*/
private static function getOrderArray($event): ?array
{
if ($event instanceof Order) {
$obOrder = $event;
} elseif ($event instanceof Event) {
$obOrder = $event->getParameter('ENTITY');
} else {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'events', 'event error');
return null;
}
return RetailCrmOrder::orderObjToArr($obOrder);
}
} }

View File

@ -4,7 +4,7 @@ require_once($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/prolog_be
$GLOBALS['APPLICATION']->RestartBuffer(); $GLOBALS['APPLICATION']->RestartBuffer();
$moduleId = 'intaro.retailcrm'; $moduleId = 'intaro.retailcrm';
$historyTime = 'history_time'; $historyTime = 'history_time';
$idOrderCRM = (int)$_REQUEST['idOrderCRM']; $idOrderCRM = (int) $_REQUEST['idOrderCRM'];
if (CModule::IncludeModule($moduleId) && $idOrderCRM && $idOrderCRM > 0) { if (CModule::IncludeModule($moduleId) && $idOrderCRM && $idOrderCRM > 0) {
$timeBd = COption::GetOptionString($moduleId, $historyTime, 0); $timeBd = COption::GetOptionString($moduleId, $historyTime, 0);

View File

@ -9,7 +9,7 @@ class RetailCrmHistory
public static $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr'; public static $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr';
public static $CRM_PAYMENT_TYPES = 'pay_types_arr'; public static $CRM_PAYMENT_TYPES = 'pay_types_arr';
public static $CRM_PAYMENT_STATUSES = 'pay_statuses_arr'; public static $CRM_PAYMENT_STATUSES = 'pay_statuses_arr';
public static $CRM_PAYMENT = 'payment_arr'; //order payment Y/N public static $CRM_PAYMENT = 'payment_arr';
public static $CRM_ORDER_LAST_ID = 'order_last_id'; public static $CRM_ORDER_LAST_ID = 'order_last_id';
public static $CRM_SITES_LIST = 'sites_list'; public static $CRM_SITES_LIST = 'sites_list';
public static $CRM_ORDER_PROPS = 'order_props'; public static $CRM_ORDER_PROPS = 'order_props';
@ -751,7 +751,7 @@ class RetailCrmHistory
if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) { if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) {
$objects = simplexml_load_file($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml'); $objects = simplexml_load_file($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml');
foreach ($objects->fields->field as $object) { foreach ($objects->fields->field as $object) {
$fields[(string)$object["group"]][(string)$object["id"]] = (string)$object; $fields[(string) $object["group"]][(string) $object["id"]] = (string) $object;
} }
} }
$customers = array(); $customers = array();
@ -804,7 +804,7 @@ class RetailCrmHistory
if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) { if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) {
$objects = simplexml_load_file($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml'); $objects = simplexml_load_file($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml');
foreach ($objects->fields->field as $object) { foreach ($objects->fields->field as $object) {
$fields[(string)$object["group"]][(string)$object["id"]] = (string)$object; $fields[(string) $object["group"]][(string) $object["id"]] = (string) $object;
} }
} }
$orders = array(); $orders = array();

View File

@ -2,7 +2,10 @@
use Bitrix\Main\ArgumentException; use Bitrix\Main\ArgumentException;
use Bitrix\Main\ArgumentNullException; use Bitrix\Main\ArgumentNullException;
use Bitrix\Main\ArgumentOutOfRangeException;
use Bitrix\Main\Context; use Bitrix\Main\Context;
use Bitrix\Main\NotSupportedException;
use Bitrix\Main\SystemException;
use Bitrix\Sale\Basket; use Bitrix\Sale\Basket;
use Bitrix\Sale\Delivery\Services\EmptyDeliveryService; use Bitrix\Sale\Delivery\Services\EmptyDeliveryService;
use Bitrix\Sale\Delivery\Services\Manager; use Bitrix\Sale\Delivery\Services\Manager;
@ -11,7 +14,11 @@ use Bitrix\Sale\Internals\PaymentTable;
use Bitrix\Sale\Location\Search\Finder; use Bitrix\Sale\Location\Search\Finder;
use Bitrix\Sale\Order; use Bitrix\Sale\Order;
use Bitrix\Sale\OrderUserProperties; use Bitrix\Sale\OrderUserProperties;
use Bitrix\Sale\Payment;
use Intaro\RetailCrm\Service\ManagerService; use Intaro\RetailCrm\Service\ManagerService;
use Intaro\RetailCrm\Component\ConfigProvider;
use Intaro\RetailCrm\Component\Constants;
use Intaro\RetailCrm\Component\Handlers\EventsHandlers;
IncludeModuleLangFile(__FILE__); IncludeModuleLangFile(__FILE__);
class RetailCrmHistory class RetailCrmHistory
@ -532,7 +539,7 @@ class RetailCrmHistory
continue; continue;
} }
$site = self::getSite($order['site']); $site = self::getSite($order['site']);
if (null === $site) { if (null === $site) {
@ -1229,7 +1236,7 @@ class RetailCrmHistory
return false; return false;
} }
/** /**
* @param string $shopCode * @param string $shopCode
* *
@ -1238,18 +1245,18 @@ class RetailCrmHistory
public static function getSite(string $shopCode): ?string public static function getSite(string $shopCode): ?string
{ {
$optionsSitesList = RetailcrmConfigProvider::getSitesList(); $optionsSitesList = RetailcrmConfigProvider::getSitesList();
if ($optionsSitesList) { if ($optionsSitesList) {
$searchResult = array_search($shopCode, $optionsSitesList, true); $searchResult = array_search($shopCode, $optionsSitesList, true);
return is_string($searchResult) ? $searchResult : null; return is_string($searchResult) ? $searchResult : null;
} }
$defaultSite = CSite::GetDefSite(); $defaultSite = CSite::GetDefSite();
return is_string($defaultSite) ? $defaultSite : null; return is_string($defaultSite) ? $defaultSite : null;
} }
/** /**
* @param $array * @param $array
* @param $value * @param $value
@ -1493,7 +1500,7 @@ class RetailCrmHistory
return $orders; return $orders;
} }
/** /**
* Filters out history by these terms: * Filters out history by these terms:
* - Changes from current API key will be added only if CMS changes are more actual than history. * - Changes from current API key will be added only if CMS changes are more actual than history.
@ -1512,7 +1519,7 @@ class RetailCrmHistory
$history = []; $history = [];
$organizedHistory = []; $organizedHistory = [];
$notOurChanges = []; $notOurChanges = [];
foreach ($historyEntries as $entry) { foreach ($historyEntries as $entry) {
if (!isset($entry[$recordType]['externalId'])) { if (!isset($entry[$recordType]['externalId'])) {
if ($entry['source'] == 'api' if ($entry['source'] == 'api'
@ -1522,23 +1529,23 @@ class RetailCrmHistory
) { ) {
continue; continue;
} }
$history[] = $entry; $history[] = $entry;
continue; continue;
} }
$externalId = $entry[$recordType]['externalId']; $externalId = $entry[$recordType]['externalId'];
$field = $entry['field']; $field = $entry['field'];
if (!isset($organizedHistory[$externalId])) { if (!isset($organizedHistory[$externalId])) {
$organizedHistory[$externalId] = []; $organizedHistory[$externalId] = [];
} }
if (!isset($notOurChanges[$externalId])) { if (!isset($notOurChanges[$externalId])) {
$notOurChanges[$externalId] = []; $notOurChanges[$externalId] = [];
} }
if ($entry['source'] == 'api' if ($entry['source'] == 'api'
&& isset($entry['apiKey']['current']) && isset($entry['apiKey']['current'])
&& $entry['apiKey']['current'] == true && $entry['apiKey']['current'] == true
@ -1553,38 +1560,42 @@ class RetailCrmHistory
$notOurChanges[$externalId][$field] = true; $notOurChanges[$externalId][$field] = true;
} }
} }
unset($notOurChanges); unset($notOurChanges);
foreach ($organizedHistory as $historyChunk) { foreach ($organizedHistory as $historyChunk) {
$history = array_merge($history, $historyChunk); $history = array_merge($history, $historyChunk);
} }
return $history; return $history;
} }
/** /**
* Update shipment in order * Update shipment in order
* *
* @param order object * @param \Bitrix\Sale\Order $bitrixOrder
* @param options delivery types * @param array $optionsDelivTypes
* @param order from crm * @param array $crmOrder
* *
* @return void * @return bool|null
* @throws \Bitrix\Main\ArgumentException
* @throws \Bitrix\Main\ArgumentNullException
* @throws \Bitrix\Main\ObjectNotFoundException
* @throws \Bitrix\Main\SystemException
*/ */
public static function deliveryUpdate(Bitrix\Sale\Order $order, $optionsDelivTypes, $orderCrm) public static function deliveryUpdate(Bitrix\Sale\Order $bitrixOrder, $optionsDelivTypes, $crmOrder)
{ {
if (!$order instanceof Bitrix\Sale\Order) { if (!$bitrixOrder instanceof Bitrix\Sale\Order) {
return false; return false;
} }
if ($order->getId()) { if ($bitrixOrder->getId()) {
$update = true; $update = true;
} else { } else {
$update = false; $update = false;
} }
$crmCode = $orderCrm['delivery']['code'] ?? false; $crmCode = $crmOrder['delivery']['code'] ?? false;
$noDeliveryId = EmptyDeliveryService::getEmptyDeliveryServiceId(); $noDeliveryId = EmptyDeliveryService::getEmptyDeliveryServiceId();
if ($crmCode === false || !isset($optionsDelivTypes[$crmCode])) { if ($crmCode === false || !isset($optionsDelivTypes[$crmCode])) {
@ -1592,9 +1603,9 @@ class RetailCrmHistory
} else { } else {
$deliveryId = $optionsDelivTypes[$crmCode]; $deliveryId = $optionsDelivTypes[$crmCode];
if (isset($orderCrm['delivery']['service']['code'])) { if (isset($crmOrder['delivery']['service']['code'])) {
$deliveryCode = Manager::getCodeById($deliveryId); $deliveryCode = Manager::getCodeById($deliveryId);
$serviceCode = $orderCrm['delivery']['service']['code']; $serviceCode = $crmOrder['delivery']['service']['code'];
$service = Manager::getService($deliveryId); $service = Manager::getService($deliveryId);
if (is_object($service)) { if (is_object($service)) {
@ -1608,7 +1619,7 @@ class RetailCrmHistory
if ($deliveryCode) { if ($deliveryCode) {
try { try {
$deliveryService = Manager::getObjectByCode($deliveryCode . ':' . $serviceCode); $deliveryService = Manager::getObjectByCode($deliveryCode . ':' . $serviceCode);
} catch (Bitrix\Main\SystemException $systemException) { } catch (SystemException $systemException) {
RCrmActions::eventLog('RetailCrmHistory::deliveryEdit', '\Bitrix\Sale\Delivery\Services\Manager::getObjectByCode', $systemException->getMessage()); RCrmActions::eventLog('RetailCrmHistory::deliveryEdit', '\Bitrix\Sale\Delivery\Services\Manager::getObjectByCode', $systemException->getMessage());
} }
@ -1620,31 +1631,33 @@ class RetailCrmHistory
} }
$delivery = Manager::getObjectById($deliveryId); $delivery = Manager::getObjectById($deliveryId);
$shipmentColl = $order->getShipmentCollection(); $shipmentColl = $bitrixOrder->getShipmentCollection();
if ($delivery) { if ($delivery) {
if (!$update) { if (!$update) {
$shipment = $shipmentColl->createItem($delivery); $shipment = $shipmentColl->createItem($delivery);
$shipment->setFields(array( $shipment->setFields(array(
'BASE_PRICE_DELIVERY' => $orderCrm['delivery']['cost'], 'BASE_PRICE_DELIVERY' => $crmOrder['delivery']['cost'],
'CURRENCY' => $order->getCurrency(), 'CURRENCY' => $bitrixOrder->getCurrency(),
'DELIVERY_NAME' => $delivery->getName(), 'DELIVERY_NAME' => $delivery->getName(),
'CUSTOM_PRICE_DELIVERY' => 'Y' 'CUSTOM_PRICE_DELIVERY' => 'Y'
)); ));
} else { } else {
foreach ($shipmentColl as $shipment) { foreach ($shipmentColl as $shipment) {
if (!$shipment->isSystem()) { if (!$shipment->isSystem()) {
$shipment->setFields(array( $shipment->setFields(array(
'BASE_PRICE_DELIVERY' => $orderCrm['delivery']['cost'], 'BASE_PRICE_DELIVERY' => $crmOrder['delivery']['cost'],
'CURRENCY' => $order->getCurrency(), 'CURRENCY' => $bitrixOrder->getCurrency(),
'DELIVERY_ID' => $deliveryId, 'DELIVERY_ID' => $deliveryId,
'DELIVERY_NAME' => $delivery->getName(), 'DELIVERY_NAME' => $delivery->getName(),
'CUSTOM_PRICE_DELIVERY' => 'Y' 'CUSTOM_PRICE_DELIVERY' => 'Y'
)); ));
} }
} }
} }
} }
return true;
} }
/** /**
@ -1703,11 +1716,11 @@ class RetailCrmHistory
if (!$shipment->isSystem()) { if (!$shipment->isSystem()) {
try { try {
$shipment->tryUnreserve(); $shipment->tryUnreserve();
} catch (Main\ArgumentOutOfRangeException $ArgumentOutOfRangeException) { } catch (ArgumentOutOfRangeException $ArgumentOutOfRangeException) {
RCrmActions::eventLog('RetailCrmHistory::unreserveShipment', '\Bitrix\Sale\Shipment::tryUnreserve()', $ArgumentOutOfRangeException->getMessage()); RCrmActions::eventLog('RetailCrmHistory::unreserveShipment', '\Bitrix\Sale\Shipment::tryUnreserve()', $ArgumentOutOfRangeException->getMessage());
return false; return false;
} catch (Main\NotSupportedException $NotSupportedException) { } catch (NotSupportedException $NotSupportedException) {
RCrmActions::eventLog('RetailCrmHistory::unreserveShipment', '\Bitrix\Sale\Shipment::tryUnreserve()', $NotSupportedException->getMessage()); RCrmActions::eventLog('RetailCrmHistory::unreserveShipment', '\Bitrix\Sale\Shipment::tryUnreserve()', $NotSupportedException->getMessage());
return false; return false;
@ -1748,7 +1761,7 @@ class RetailCrmHistory
$nowPaymentId = RCrmActions::getFromPaymentExternalId($paymentCrm['externalId']); $nowPaymentId = RCrmActions::getFromPaymentExternalId($paymentCrm['externalId']);
$nowPayment = $paymentsList[$nowPaymentId]; $nowPayment = $paymentsList[$nowPaymentId];
//update data //update data
if ($nowPayment instanceof \Bitrix\Sale\Payment) { if ($nowPayment instanceof Payment) {
$nowPayment->setField('SUM', $paymentCrm['amount']); $nowPayment->setField('SUM', $paymentCrm['amount']);
if ($optionsPayTypes[$paymentCrm['type']] != $nowPayment->getField('PAY_SYSTEM_ID')) { if ($optionsPayTypes[$paymentCrm['type']] != $nowPayment->getField('PAY_SYSTEM_ID')) {
$nowPayment->setField('PAY_SYSTEM_ID', $optionsPayTypes[$paymentCrm['type']]); $nowPayment->setField('PAY_SYSTEM_ID', $optionsPayTypes[$paymentCrm['type']]);

View File

@ -14,30 +14,29 @@ class RetailUser extends CUser
if ($arUser = $rsUser->Fetch()) { if ($arUser = $rsUser->Fetch()) {
return $arUser['ID']; return $arUser['ID'];
} else {
$retailUser = new CUser;
$userPassword = uniqid();
$arFields = [
"NAME" => 'retailcrm',
"LAST_NAME" => 'retailcrm',
"EMAIL" => 'retailcrm@retailcrm.com',
"LOGIN" => 'retailcrm',
"LID" => "ru",
"ACTIVE" => "Y",
"GROUP_ID" => [2],
"PASSWORD" => $userPassword,
"CONFIRM_PASSWORD" => $userPassword,
];
$id = $retailUser->Add($arFields);
if (!$id) {
return null;
} else {
return $id;
}
} }
$retailUser = new CUser;
$userPassword = uniqid();
$arFields = [
'NAME' => 'retailcrm',
'LAST_NAME' => 'retailcrm',
'EMAIL' => 'retailcrm@retailcrm.com',
'LOGIN' => 'retailcrm',
'LID' => 'ru',
'ACTIVE' => 'Y',
'GROUP_ID' => [2],
'PASSWORD' => $userPassword,
'CONFIRM_PASSWORD' => $userPassword,
];
$id = $retailUser->Add($arFields);
if (!$id) {
return null;
}
return $id;
} }
} }

View File

@ -9,7 +9,7 @@ class RetailCrmOrder
public static $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr'; public static $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr';
public static $CRM_PAYMENT_TYPES = 'pay_types_arr'; public static $CRM_PAYMENT_TYPES = 'pay_types_arr';
public static $CRM_PAYMENT_STATUSES = 'pay_statuses_arr'; public static $CRM_PAYMENT_STATUSES = 'pay_statuses_arr';
public static $CRM_PAYMENT = 'payment_arr'; //order payment Y/N public static $CRM_PAYMENT = 'payment_arr';
public static $CRM_ORDER_LAST_ID = 'order_last_id'; public static $CRM_ORDER_LAST_ID = 'order_last_id';
public static $CRM_SITES_LIST = 'sites_list'; public static $CRM_SITES_LIST = 'sites_list';
public static $CRM_ORDER_PROPS = 'order_props'; public static $CRM_ORDER_PROPS = 'order_props';

View File

@ -8,9 +8,14 @@ use Bitrix\Sale\Internals\Fields;
use Bitrix\Sale\Internals\OrderTable; use Bitrix\Sale\Internals\OrderTable;
use Bitrix\Sale\Location\LocationTable; use Bitrix\Sale\Location\LocationTable;
use Bitrix\Sale\Order; use Bitrix\Sale\Order;
use Intaro\RetailCrm\Component\Factory\ClientFactory;
use Intaro\RetailCrm\Component\ServiceLocator;
use Intaro\RetailCrm\Service\LoyaltyService;
use RetailCrm\ApiClient; use RetailCrm\ApiClient;
use Intaro\RetailCrm\Service\ManagerService; use Intaro\RetailCrm\Service\ManagerService;
use Intaro\RetailCrm\Service\LoyaltyAccountService;
use RetailCrm\Response\ApiResponse; use RetailCrm\Response\ApiResponse;
use Intaro\RetailCrm\Component\ConfigProvider;
IncludeModuleLangFile(__FILE__); IncludeModuleLangFile(__FILE__);
@ -29,7 +34,7 @@ class RetailCrmOrder
* @param null $site * @param null $site
* @param string $methodApi * @param string $methodApi
* *
* @return boolean|array * @return array|false|\Intaro\RetailCrm\Model\Api\Response\OrdersCreateResponse|\Intaro\RetailCrm\Model\Api\Response\OrdersEditResponse|null
* @throws \Bitrix\Main\ArgumentException * @throws \Bitrix\Main\ArgumentException
* @throws \Bitrix\Main\ObjectPropertyException * @throws \Bitrix\Main\ObjectPropertyException
* @throws \Bitrix\Main\SystemException * @throws \Bitrix\Main\SystemException
@ -43,12 +48,12 @@ class RetailCrmOrder
string $methodApi = 'ordersEdit' string $methodApi = 'ordersEdit'
) { ) {
if (!$api || empty($arParams)) { // add cond to check $arParams if (!$api || empty($arParams)) { // add cond to check $arParams
return false; return null;
} }
if (empty($arOrder)) { if (empty($arOrder)) {
RCrmActions::eventLog('RetailCrmOrder::orderSend', 'empty($arFields)', 'incorrect order'); RCrmActions::eventLog('RetailCrmOrder::orderSend', 'empty($arFields)', 'incorrect order');
return false; return null;
} }
$dimensionsSetting = RetailcrmConfigProvider::getOrderDimensions(); $dimensionsSetting = RetailcrmConfigProvider::getOrderDimensions();
@ -161,7 +166,7 @@ class RetailCrmOrder
//deliverys //deliverys
if (array_key_exists($arOrder['DELIVERYS'][0]['id'], $arParams['optionsDelivTypes'])) { if (array_key_exists($arOrder['DELIVERYS'][0]['id'], $arParams['optionsDelivTypes'])) {
$order['delivery']['code'] = $arParams['optionsDelivTypes'][$arOrder['DELIVERYS'][0]['id']]; $order['delivery']['code'] = $arParams['optionsDelivTypes'][$arOrder['DELIVERYS'][0]['id']];
if (isset($arOrder['DELIVERYS'][0]['service']) && $arOrder['DELIVERYS'][0]['service'] != '') { if (isset($arOrder['DELIVERYS'][0]['service']) && $arOrder['DELIVERYS'][0]['service'] != '') {
$order['delivery']['service']['code'] = $arOrder['DELIVERYS'][0]['service']; $order['delivery']['service']['code'] = $arOrder['DELIVERYS'][0]['service'];
} }
@ -176,7 +181,7 @@ class RetailCrmOrder
$response = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $order['externalId']); $response = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $order['externalId']);
if (isset($response['order'])) { if (isset($response['order'])) {
foreach ($response['order']['items'] as $k => $item) { foreach ($response['order']['items'] as $k => $item) {
$externalId = $k ."_". $item['offer']['externalId']; $externalId = $k .'_'. $item['offer']['externalId'];
$orderItems[$externalId] = $item; $orderItems[$externalId] = $item;
} }
} }
@ -192,7 +197,7 @@ class RetailCrmOrder
$itemId = $orderItems[$externalId]['id']; $itemId = $orderItems[$externalId]['id'];
$key = array_search('bitrix', array_column($externalIds, 'code')); $key = array_search('bitrix', array_column($externalIds, 'code'));
if ($externalIds[$key]['code'] === 'bitrix') { if ($externalIds[$key]['code'] === 'bitrix') {
$externalIds[$key] = [ $externalIds[$key] = [
'code' => 'bitrix', 'code' => 'bitrix',
@ -203,13 +208,31 @@ class RetailCrmOrder
'code' => 'bitrix', 'code' => 'bitrix',
'value' => $externalId, 'value' => $externalId,
]; ];
} }
$keyBasketId = array_search('bitrixBasketId', array_column($externalIds, 'code'));
if ($externalIds[$keyBasketId]['code'] === 'bitrixBasketId') {
$externalIds[$keyBasketId] = [
'code' => 'bitrixBasketId',
'value' => $product['ID'],
];
} else {
$externalIds[] = [
'code' => 'bitrixBasketId',
'value' => $product['ID'],
];
}
} else { //create } else { //create
$externalIds = [ $externalIds = [
[ [
'code' => 'bitrix', 'code' => 'bitrix',
'value' => $externalId, 'value' => $externalId,
] ],
[
'code' => 'bitrixBasketId',
'value' => $product['ID'],
],
]; ];
} }
@ -228,7 +251,7 @@ class RetailCrmOrder
} }
$catalogProduct = CCatalogProduct::GetByID($product['PRODUCT_ID']); $catalogProduct = CCatalogProduct::GetByID($product['PRODUCT_ID']);
if (is_null($catalogProduct['PURCHASING_PRICE']) === false) { if (is_null($catalogProduct['PURCHASING_PRICE']) === false) {
if ($catalogProduct['PURCHASING_CURRENCY'] && $currency != $catalogProduct['PURCHASING_CURRENCY']) { if ($catalogProduct['PURCHASING_CURRENCY'] && $currency != $catalogProduct['PURCHASING_CURRENCY']) {
$purchasePrice = CCurrencyRates::ConvertCurrency( $purchasePrice = CCurrencyRates::ConvertCurrency(
@ -243,9 +266,25 @@ class RetailCrmOrder
$item['purchasePrice'] = $purchasePrice; $item['purchasePrice'] = $purchasePrice;
} }
$discount = (double) $product['DISCOUNT_PRICE'];
$dpItem = $product['BASE_PRICE'] - $product['PRICE'];
if ( $dpItem > 0 && $discount <= 0) {
$discount = $dpItem;
}
$item['discountManualPercent'] = 0; $item['discountManualPercent'] = 0;
$item['initialPrice'] = (double) $product['BASE_PRICE'];
if ($product['BASE_PRICE'] >= $product['PRICE']) {
if (
$product['BASE_PRICE'] >= $product['PRICE']
&& $methodApi === 'ordersEdit'
&& ConfigProvider::getLoyaltyProgramStatus() === 'Y'
) {
/** @var LoyaltyService $service */
$service = ServiceLocator::get(LoyaltyService::class);
$item['discountManualAmount'] = $service->getInitialDiscount((int) $externalId) ?? $discount;
} elseif ($product['BASE_PRICE'] >= $product['PRICE']) {
$item['discountManualAmount'] = self::getDiscountManualAmount($product); $item['discountManualAmount'] = self::getDiscountManualAmount($product);
$item['initialPrice'] = (double) $product['BASE_PRICE']; $item['initialPrice'] = (double) $product['BASE_PRICE'];
} else { } else {
@ -276,7 +315,7 @@ class RetailCrmOrder
//payments //payments
$payments = []; $payments = [];
foreach ($arOrder['PAYMENTS'] as $payment) { foreach ($arOrder['PAYMENTS'] as $payment) {
$isIntegrationPayment = RetailCrmService::isIntegrationPayment($payment['PAY_SYSTEM_ID'] ?? null); $isIntegrationPayment = RetailCrmService::isIntegrationPayment($payment['PAY_SYSTEM_ID'] ?? null);
@ -340,8 +379,21 @@ class RetailCrmOrder
Logger::getInstance()->write($order, 'orderSend'); Logger::getInstance()->write($order, 'orderSend');
if ($send && !RCrmActions::apiMethod($api, $methodApi, __METHOD__, $order, $site)) { if (ConfigProvider::getLoyaltyProgramStatus() === 'Y' && LoyaltyAccountService::getLoyaltyPersonalStatus()) {
return false; $order['privilegeType'] = 'loyalty_level';
}
/** @var \Intaro\RetailCrm\Component\ApiClient\ClientAdapter $client */
$client = ClientFactory::createClientAdapter();
if ($send) {
if ($methodApi === 'ordersCreate') {
return $client->createOrder($order, $site);
}
if ($methodApi === 'ordersEdit') {
return $client->editOrder($order, $site);
}
} }
return $order; return $order;
@ -354,7 +406,7 @@ class RetailCrmOrder
* @param bool $failed -- flag to export failed orders * @param bool $failed -- flag to export failed orders
* @param array|null $orderList * @param array|null $orderList
* *
* @return boolean * @return bool
* @throws \Bitrix\Main\ArgumentException * @throws \Bitrix\Main\ArgumentException
* @throws \Bitrix\Main\ArgumentNullException * @throws \Bitrix\Main\ArgumentNullException
* @throws \Bitrix\Main\ObjectPropertyException * @throws \Bitrix\Main\ObjectPropertyException
@ -381,7 +433,7 @@ class RetailCrmOrder
$orderIds = $orderList; $orderIds = $orderList;
} else { } else {
$dbOrder = OrderTable::GetList([ $dbOrder = OrderTable::GetList([
'order' => ["ID" => "ASC"], 'order' => ['ID' => 'ASC'],
'filter' => ['>ID' => $lastUpOrderId], 'filter' => ['>ID' => $lastUpOrderId],
'limit' => $pSize, 'limit' => $pSize,
'select' => ['ID'], 'select' => ['ID'],
@ -433,7 +485,6 @@ class RetailCrmOrder
$arCustomer = []; $arCustomer = [];
$arCustomerCorporate = []; $arCustomerCorporate = [];
$order = self::orderObjToArr($bitrixOrder); $order = self::orderObjToArr($bitrixOrder);
$user = UserTable::getById($order['USER_ID'])->fetch();
$site = self::getCrmShopCodeByLid($order['LID'], $arParams['optionsSitesList']); $site = self::getCrmShopCodeByLid($order['LID'], $arParams['optionsSitesList']);
if (null === $site && count($arParams['optionsSitesList']) > 0) { if (null === $site && count($arParams['optionsSitesList']) > 0) {
@ -474,7 +525,7 @@ class RetailCrmOrder
return false; return false;
} }
if ('Y' == RetailcrmConfigProvider::getCorporateClientStatus()) { if ('Y' === RetailcrmConfigProvider::getCorporateClientStatus()) {
$cachedCorporateIds = []; $cachedCorporateIds = [];
foreach ($ordersPack as $lid => $lidOrdersList) { foreach ($ordersPack as $lid => $lidOrdersList) {
@ -497,7 +548,7 @@ class RetailCrmOrder
if ($failed == true && $failedIds !== false && count($failedIds) > 0) { if ($failed == true && $failedIds !== false && count($failedIds) > 0) {
RetailcrmConfigProvider::setFailedOrdersIds(array_diff($failedIds, $recOrders)); RetailcrmConfigProvider::setFailedOrdersIds(array_diff($failedIds, $recOrders));
} elseif ($lastUpOrderId < max($recOrders) && $orderList === false) { } elseif (count($orderList) === 0 && $lastUpOrderId < max($recOrders)) {
RetailcrmConfigProvider::setLastOrderId(max($recOrders)); RetailcrmConfigProvider::setLastOrderId(max($recOrders));
} }
} }
@ -709,7 +760,7 @@ class RetailCrmOrder
foreach ($pack as $key => $itemLoad) { foreach ($pack as $key => $itemLoad) {
$site = self::getCrmShopCodeByLid($key, $optionsSitesList); $site = self::getCrmShopCodeByLid($key, $optionsSitesList);
if (null === $site && count($optionsSitesList) > 0) { if (null === $site && count($optionsSitesList) > 0) {
continue; continue;
} }
@ -839,14 +890,14 @@ class RetailCrmOrder
$sumDifference = $product->get('BASE_PRICE') - $product->get('PRICE'); $sumDifference = $product->get('BASE_PRICE') - $product->get('PRICE');
return $sumDifference > 0 ? $sumDifference : 0.0; return $sumDifference > 0 ? $sumDifference : 0.0;
} }
$discount = (double) $product->get('DISCOUNT_PRICE'); $discount = (double) $product->get('DISCOUNT_PRICE');
$dpItem = $product->get('BASE_PRICE') - $product->get('PRICE'); $dpItem = $product->get('BASE_PRICE') - $product->get('PRICE');
if ($dpItem > 0 && $discount <= 0) { if ($dpItem > 0 && $discount <= 0) {
return $dpItem; return $dpItem;
} }
return $discount; return $discount;
} }
} }

View File

@ -12,8 +12,7 @@ class RetailCrmService
*/ */
public static function unsetIntegrationDeliveryFields(array $order): array public static function unsetIntegrationDeliveryFields(array $order): array
{ {
$integrationDelivery = RetailcrmConfigProvider::getCrmIntegrationDelivery(); $integrationDelivery = RetailcrmConfigProvider::getCrmIntegrationDelivery();
if (isset($order['delivery']['code'])) { if (isset($order['delivery']['code'])) {
$deliveryCode = $order['delivery']['code']; $deliveryCode = $order['delivery']['code'];

View File

@ -61,7 +61,7 @@ class RetailCrmUser
return $customer; return $customer;
} }
public static function customerEdit($arFields, $api, $optionsSitesList = array()): bool public static function customerEdit($arFields, $api, $optionsSitesList = array()) : bool
{ {
if (empty($arFields)) { if (empty($arFields)) {
RCrmActions::eventLog('RetailCrmUser::customerEdit', 'empty($arFields)', 'incorrect customer'); RCrmActions::eventLog('RetailCrmUser::customerEdit', 'empty($arFields)', 'incorrect customer');

View File

@ -1 +1 @@
- Исправление некорректной генерации каталога при повторных запусках генерации - Добавлена поддержка программы лояльности

View File

@ -357,7 +357,7 @@ if ($STEP === 1) {
$arIBlock['OLD_PROPERTY_SKU_SELECT'], $arIBlock['OLD_PROPERTY_SKU_SELECT'],
$propertyKey $propertyKey
); );
echo $isSelected ? ' selected' : ''; echo $isSelected ? ' selected' : '';
?> ?>
> >
@ -377,7 +377,7 @@ if ($STEP === 1) {
<option value="<?=$prop['CODE']?>" <option value="<?=$prop['CODE']?>"
<?php <?php
echo $settingsService->getOptionClass($prop, false); echo $settingsService->getOptionClass($prop, false);
if (!$productSelected) { if (!$productSelected) {
$isSelected = $settingsService->isOptionSelected( $isSelected = $settingsService->isOptionSelected(
$prop, $prop,
@ -776,7 +776,7 @@ if ($STEP === 1) {
//Сохранение и выход //Сохранение и выход
if ($STEP === 2) { if ($STEP === 2) {
RetailcrmConfigProvider::setProfileBasePrice($_REQUEST['PROFILE_ID'], $_POST['price-types']); RetailcrmConfigProvider::setProfileBasePrice($_REQUEST['PROFILE_ID'], $_POST['price-types']);
$FINITE = true; $FINITE = true;
} }
?> ?>

View File

@ -1,43 +1,53 @@
<?php <?php
$server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot();
use Bitrix\Main\Context;
use Bitrix\Main\Loader;
use Intaro\RetailCrm\Component\ServiceLocator;
use Intaro\RetailCrm\Service\CookieService;
use Intaro\RetailCrm\Service\OrderLoyaltyDataService;
use Intaro\RetailCrm\Service\LoyaltyService;
use Intaro\RetailCrm\Service\LoyaltyAccountService;
use Intaro\RetailCrm\Service\CustomerService;
use Intaro\RetailCrm\Vendor\Doctrine\Common\Annotations\AnnotationReader;
use Intaro\RetailCrm\Vendor\Doctrine\Common\Annotations\AnnotationRegistry;
use \Intaro\RetailCrm\Component\Builder\Api\CustomerBuilder;
require_once __DIR__ . '/RetailcrmClasspathBuilder.php';
$retailcrmModuleId = 'intaro.retailcrm';
$server = Context::getCurrent()->getServer()->getDocumentRoot();
$version = COption::GetOptionString('intaro.retailcrm', 'api_version'); $version = COption::GetOptionString('intaro.retailcrm', 'api_version');
CModule::AddAutoloadClasses( $builder = new RetailcrmClasspathBuilder();
'intaro.retailcrm', // module name $builder->setDisableNamespaces(true)
array ( ->setDocumentRoot($server)
'RetailcrmDependencyLoader' => 'classes/general/RetailcrmDependencyLoader.php', ->setModuleId($retailcrmModuleId)
'RestNormalizer' => file_exists($server . '/bitrix/php_interface/retailcrm/RestNormalizer.php') ? '../../php_interface/retailcrm/RestNormalizer.php' : 'classes/general/RestNormalizer.php', ->setPath('classes')
'Logger' => file_exists($server . '/bitrix/php_interface/retailcrm/Logger.php') ? '../../php_interface/retailcrm/Logger.php' : 'classes/general/Logger.php', ->setVersion($version)
'RetailCrm\ApiClient' => file_exists($server . '/bitrix/php_interface/retailcrm/ApiClient.php') ? '../../php_interface/retailcrm/ApiClient.php' : 'classes/general/ApiClient_' . $version . '.php', ->build();
'RetailCrm\Http\Client' => file_exists($server . '/bitrix/php_interface/retailcrm/Client.php') ? '../../php_interface/retailcrm/Client.php' : 'classes/general/Http/Client.php',
'RCrmActions' => file_exists($server . '/bitrix/php_interface/retailcrm/RCrmActions.php') ? '../../php_interface/retailcrm/RCrmActions.php' : 'classes/general/RCrmActions.php', Loader::registerAutoLoadClasses('intaro.retailcrm', $builder->getResult());
'RetailCrmUser' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmUser.php') ? '../../php_interface/retailcrm/RetailCrmUser.php' : 'classes/general/user/RetailCrmUser.php', AnnotationRegistry::registerLoader('class_exists');
'RetailCrmOrder' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmOrder.php') ? '../../php_interface/retailcrm/RetailCrmOrder.php' : 'classes/general/order/RetailCrmOrder_' . $version . '.php',
'RetailCrmHistory' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmHistory.php') ? '../../php_interface/retailcrm/RetailCrmHistory.php' : 'classes/general/history/RetailCrmHistory_' . $version . '.php', ServiceLocator::registerServices([
'RetailCrmInventories' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmInventories.php') ? '../../php_interface/retailcrm/RetailCrmInventories.php' : 'classes/general/inventories/RetailCrmInventories.php', \Intaro\RetailCrm\Service\Utils::class,
'RetailCrmPrices' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmPrices.php') ? '../../php_interface/retailcrm/RetailCrmPrices.php' : 'classes/general/prices/RetailCrmPrices.php', Logger::class,
'RetailCrmCollector' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmCollector.php') ? '../../php_interface/retailcrm/RetailCrmCollector.php' : 'classes/general/collector/RetailCrmCollector.php', AnnotationReader::class,
'RetailCrmUa' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmUa.php') ? '../../php_interface/retailcrm/RetailCrmUa.php' : 'classes/general/ua/RetailCrmUa.php', CookieService::class,
'RetailCrmEvent' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmEvent.php') ? '../../php_interface/retailcrm/RetailCrmEvent.php' : 'classes/general/events/RetailCrmEvent.php', LoyaltyAccountService::class,
'RetailCrm\Response\ApiResponse' => 'classes/general/Response/ApiResponse.php', LoyaltyService::class,
'RetailCrm\Exception\InvalidJsonException' => 'classes/general/Exception/InvalidJsonException.php', CustomerService::class,
'RetailCrm\Exception\CurlException' => 'classes/general/Exception/CurlException.php', OrderLoyaltyDataService::class,
'RetailCrmCorporateClient' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmCorporateClient.php') ? '../../php_interface/retailcrm/RetailCrmCorporateClient.php' : 'classes/general/user/RetailCrmCorporateClient.php', CustomerBuilder::class
'RetailcrmConfigProvider' => 'classes/general/RetailcrmConfigProvider.php', ]);
'RetailcrmConstants' => 'classes/general/RetailcrmConstants.php',
'RetailcrmBuilderInterface' => 'classes/general/RetailcrmBuilderInterface.php', $arJsConfig = [
'CustomerBuilder' => 'classes/general/CustomerBuilder.php', 'intaro_countdown' => [
'CorporateCustomerBuilder' => 'classes/general/CorporateCustomerBuilder.php', 'js' => '/bitrix/js/intaro/sms.js',
'Customer' => 'classes/general/Model/Customer.php', 'rel' => [],
'CustomerAddress' => 'classes/general/Model/CustomerAddress.php', ],
'CustomerContragent' => 'classes/general/Model/CustomerContragent.php', ];
'BuyerProfile' => 'classes/general/Model/BuyerProfile.php',
'AdressBuilder' => 'classes/general/AdressBuilder.php', foreach ($arJsConfig as $ext => $arExt) {
'BuilderBase' => 'classes/general/BuilderBase.php', CJSCore::RegisterExt($ext, $arExt);
'AddressBuilder' => 'classes/general/AddressBuilder.php', }
'AbstractBuilder' => 'classes/general/AbstractBuilder.php',
'BaseModel' => 'classes/general/Model/BaseModel.php',
'RetailCrmService' => 'classes/general/services/RetailCrmService.php',
'RetailCrmOnlineConsultant' => 'classes/general/consultant/RetailCrmOnlineConsultant.php'
)
);

View File

@ -0,0 +1,59 @@
function getTimeRemaining(endtime) {
return Date.parse(endtime) - Date.parse(new Date());
}
function initializeClock(id, endtime) {
$('#countdownDiv').show();
$('#deadlineMessage').hide();
const timeInterval = setInterval(updateClock, 1000);
const clock = document.getElementById(id);
function updateClock() {
const time = getTimeRemaining(endtime);
if (time <= 0) {
$('#countdownDiv').hide();
$('#deadlineMessage').show();
clearInterval(timeInterval);
return true;
}
clock.innerText = String(time).slice(0, -3);
}
updateClock();
}
function resendRegisterSms(idInLoyalty) {
BX.ajax.runAction('intaro:retailcrm.api.loyalty.register.resendRegisterSms',
{
data: {
sessid: BX.bitrix_sessid(),
idInLoyalty: idInLoyalty
}
}
).then(function(response) {
$('#lpRegMsg').text(response.data.msg);
$('#checkIdField').val(response.data.form.fields.checkId.value);
initializeClock("countdown", response.data.resendAvailable);
});
}
function resendOrderSms(orderId) {
BX.ajax.runAction('intaro:retailcrm.api.loyalty.order.resendOrderSms',
{
data: {
sessid: BX.bitrix_sessid(),
orderId: orderId
}
}
).then(function(response) {
if (response.data.msg !== undefined) {
$('#msg').text(response.data.msg);
} else if (response.data.resendAvailable !== undefined) {
$('#checkIdVerify').val(response.data.checkId);
initializeClock("countdown", new Date(response.data.resendAvailable.date));
}
});
}

View File

@ -0,0 +1,16 @@
<?php
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
die();
}
$arComponentDescription = [
"NAME" => GetMessage("COMP_MAIN_USER_REGISTER_TITLE"),
"DESCRIPTION" => GetMessage("COMP_MAIN_USER_REGISTER_DESCR"),
"PATH" => [
"ID" => "utility",
"CHILD" => [
"ID" => "user",
"NAME" => GetMessage("MAIN_USER_GROUP_NAME"),
],
],
];

View File

@ -0,0 +1,4 @@
<?php
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
die();
}

View File

@ -0,0 +1,6 @@
<?php
if(!defined("B_PROLOG_INCLUDED")||B_PROLOG_INCLUDED!==true) {
die();
}
$this->IncludeComponentTemplate();

View File

@ -0,0 +1,4 @@
<?php
$MESS ['COMP_MAIN_USER_REGISTER_TITLE'] = "Регистрация в программе лояльности";
$MESS ['COMP_MAIN_USER_REGISTER_DESCR'] = "Управляемая регистрация в программе лояльности";
$MESS ['MAIN_USER_GROUP_NAME'] = "Пользователь";

View File

@ -0,0 +1,3 @@
<?php
$MESS ['INTARO_NOT_INSTALLED'] = "Модуль интеграции с RetailCRM не установлен";

View File

@ -0,0 +1,6 @@
<?php
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
die();
}
$arTemplateParameters = [];

View File

@ -0,0 +1,2 @@
<?php
$MESS ['USER_PROPERTY_NAME'] = "Название блока пользовательских свойств";

View File

@ -0,0 +1,27 @@
<?php
$MESS["main_register_sms"] = "Код подтверждения из СМС:";
$MESS["PERSONAL_PHONE"] = "Телефон";
$MESS["main_register_sms_send"] = "Отправить";
$MESS["UF_REG_IN_PL_INTARO"] = "Зарегистрироваться в программе лояльности";
$MESS["UF_AGREE_PL_INTARO"] = "программы лояльности:";
$MESS["I_AM_AGREE"] = "Я согласен с условиями";
$MESS["UF_PD_PROC_PL_INTARO"] = "обработки персональных данных:";
$MESS["LP_CARD_NUMBER"] = "Номер карты программы лояльности";
$MESS["SEND"] = "Отправить";
$MESS["TRY_AGAIN"] = "Попробовать снова";
$MESS["VERIFICATION_CODE"] = "Код подтверждения";
$MESS["SEND_VERIFICATION_CODE"] = "Отправьте код подтверждения";
$MESS["REG_LP_MESSAGE"] = "Для завершения регистрации в программе лояльности введите номер телефона и номер карты программы лояльности";
$MESS["YES"] = "Да";
$MESS["BONUS_CARD_NUMBER"] = "Номер карты лояльности (если есть):";
$MESS["SUCCESS_PL_REG"] = "Вы успешно зарегистрировались в программе лояльности.";
$MESS["LP_FIELDS_NOT_EXIST"] = "Ошибка установки модуля ПЛ. Отсутствуют UF поля для USER";
$MESS["REG_LP_ERROR"] = "Ошибка регистрации в Программе лояльности";
$MESS["REGISTER_CONTINUE"] = "Для завершения регистрации в программе лояльности заполните форму.";
$MESS["UF_CARD_NUM_INTARO"] = "Номер карты лояльности (если есть)";
$MESS["REGISTER_LP_TITLE"] = "Регистрация в программе лояльности";
$MESS["NOT_AUTHORIZED"] = "Вы не авторизованы на сайте. Для регистрации пройдите по <a href=\"./lp-register\">ссылке</a>";
$MESS["LP_NOT_ACTIVE"] = "Программа лояльности в данный момент не активна";
$MESS["SEC"] = "сек.";
$MESS["RESEND_SMS"] = "Отправить смс повторно";
$MESS["RESEND_POSSIBLE"] = "Повторная отправка смс возможна через";

View File

@ -0,0 +1,69 @@
<?php
use Bitrix\Main\ArgumentException;
use Bitrix\Main\Loader;
use Bitrix\Main\LoaderException;
use Bitrix\Main\ObjectPropertyException;
use Bitrix\Main\SystemException;
use Intaro\RetailCrm\Component\ConfigProvider;
use Intaro\RetailCrm\Component\Constants;
use Intaro\RetailCrm\Component\ServiceLocator;
use Intaro\RetailCrm\Repository\AgreementRepository;
use Intaro\RetailCrm\Service\CustomerService;
use Intaro\RetailCrm\Service\LoyaltyAccountService;
/** RetailCRM loyalty program start */
function checkLoadIntaro(): bool
{
try {
return Loader::includeModule('intaro.retailcrm');
} catch (LoaderException $e) {
return false;
}
}
if (checkLoadIntaro()) {
$arResult['LOYALTY_STATUS'] = ConfigProvider::getLoyaltyProgramStatus();
global $USER;
if ('Y' === $arResult['LOYALTY_STATUS'] && $USER->IsAuthorized()) {
/** @var CustomerService $customerService */
$customerService = ServiceLocator::get(CustomerService::class);
$customer = $customerService->createModel($USER->GetID());
$customerService->createCustomer($customer);
/* @var LoyaltyAccountService $service */
$service = ServiceLocator::get(LoyaltyAccountService::class);
$arResult['LP_REGISTER'] = $service->checkRegInLp();
}
$arResult['ACTIVATE'] = isset($_GET['activate'])
&& $_GET['activate'] === 'Y'
&& $arResult['LP_REGISTER']['form']['button']['action'] === 'activateAccount';
try {
$agreementPersonalData = AgreementRepository::getFirstByWhere(
['AGREEMENT_TEXT'],
[
['CODE', '=', 'AGREEMENT_PERSONAL_DATA_CODE'],
]
);
$agreementLoyaltyProgram = AgreementRepository::getFirstByWhere(
['AGREEMENT_TEXT'],
[
['CODE', '=', 'AGREEMENT_LOYALTY_PROGRAM_CODE'],
]
);
} catch (ObjectPropertyException | ArgumentException | SystemException $exception) {
Logger::getInstance()->write($exception->getMessage(), Constants::TEMPLATES_ERROR);
}
$arResult['AGREEMENT_PERSONAL_DATA'] = $agreementPersonalData['AGREEMENT_TEXT'];
$arResult['AGREEMENT_LOYALTY_PROGRAM'] = $agreementLoyaltyProgram['AGREEMENT_TEXT'];
} else {
AddMessage2Log(GetMessage('INTARO_NOT_INSTALLED'));
}
/** RetailCRM loyalty program end */

View File

@ -0,0 +1,229 @@
function serializeObject(array) {
const object = {};
$.each(array, function() {
if (object[this.name] !== undefined) {
if (!object[this.name].push) {
object[this.name] = [object[this.name]];
}
object[this.name].push(this.value || '');
} else {
object[this.name] = this.value || '';
}
});
return object;
}
function saveUserLpFields() {
const formArray = $('#lpRegFormInputs').serializeArray();
const formObject = serializeObject(formArray);
BX.ajax.runAction('intaro:retailcrm.api.loyalty.register.saveUserLpFields',
{
data: {
sessid: BX.bitrix_sessid(),
request: formObject
}
}
).then(
function(response) {
if (response.data.result === true) {
location.reload();
} else {
$('#errMsg').text(response.data.msg)
}
}
);
}
function resetUserLpFields() {
BX.ajax.runAction('intaro:retailcrm.api.loyalty.register.resetUserLpFields').then(
function(response) {
if (response.data.result === true) {
location.reload();
} else {
$('#errMsg').text(response.data.msg)
}
}
);
}
function activateAccount() {
let checkboxes = [];
let numbers = [];
let strings = [];
let dates = [];
let options = [];
let form = $('#lpRegFormInputs');
let emailViolation = false;
form.find(':input[type="email"]')
.each(
(index, value) => {
if (/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(value.value) !== true) {
emailViolation = true;
}
}
)
if (emailViolation) {
$('#errMsg').text('Проверьте правильность заполнения email')
return;
}
form.find(':checkbox')
.each(
(index, value) => {
checkboxes[index] = {
'code': value.name,
'value': value.checked,
}
}
)
form.find(':input[type="number"]')
.each(
(index, value) => {
numbers[index] = {
'code': value.name,
'value': value.value,
}
}
)
form.find(':input[type="string"], :input[type="text"], :input[type="email"], textarea')
.each(
(index, value) => {
strings[index] = {
'code': value.name,
'value': value.value,
}
}
)
form.find(':input[type="date"]')
.each(
(index, value) => {
dates[index] = {
'code': value.name,
'value': value.value,
}
}
)
form.find('select')
.each(
(index, value) => {
options[index] = {
'code': value.name,
'value': value.value,
}
}
)
let formObject = {
checkboxes: checkboxes,
numbers: numbers,
strings: strings,
dates: dates,
options: options
}
BX.ajax.runAction('intaro:retailcrm.api.loyalty.register.activateAccount',
{
data: {
sessid: BX.bitrix_sessid(),
allFields: formObject
}
}
).then(
function(response) {
if (response.data.status === 'activate') {
location.reload();
} else {
$('#errMsg').text(response.data.msg)
}
}
);
}
//TODO проверить - возможно, это мертвый метод
function addTelNumber(customerId) {
const phone = $('#loyaltyRegPhone').val();
const card = $('#loyaltyRegCard').val();
BX.ajax.runAction('intaro:retailcrm.api.loyalty.register.accountCreate',
{
data: {
sessid: BX.bitrix_sessid(),
request: {
phone: phone,
card: card,
customerId: customerId
}
}
}
).then(
function(response) {
if (response.data.status === 'error' && response.data.msg !== undefined) {
const msgBlock = $('#msg');
msgBlock.text(response.data.msg);
msgBlock.css('color', response.data.msgColor);
}
if (response.data.status === 'activate') {
const msgBlock = $('#regbody');
msgBlock.text(response.data.msg);
msgBlock.css('color', response.data.msgColor);
}
if (response.data.status === 'smsVerification') {
$('#verificationCodeBlock').show();
}
});
}
function sendVerificationCode() {
const verificationCode = $('#smsVerificationCodeField').val();
const checkId = $('#checkIdField').val();
BX.ajax.runAction('intaro:retailcrm.api.loyalty.register.activateLpBySms',
{
data: {
sessid: BX.bitrix_sessid(),
verificationCode: verificationCode,
checkId: checkId
}
}
).then(
function(response) {
if (response.data.status === 'error' && response.data.msg !== undefined) {
const msg = response.data.msg;
$('#errMsg').text(msg);
}
if (response.data.status === 'activate') {
const msgBlock = $('#regBody');
msgBlock.text(response.data.msg);
msgBlock.css('color', response.data.msgColor);
}
}
)
}
/** Управляет отображением блока с полями программы лояльности на странице регистрации. */
function lpFieldToggle() {
let phone = $('#personalPhone');
if ($('#checkbox_UF_REG_IN_PL_INTARO').is(':checked')) {
$('.lp_toggled_block').css('display', 'table-row');
$('.lp_agree_checkbox').prop('checked', true);
phone.prop('type', 'tel');
phone.attr('name', 'REGISTER[PERSONAL_PHONE]');
} else {
phone.removeAttr('name');
phone.prop('type', 'hidden');
$('.lp_agree_checkbox').prop('checked', false);
$('.lp_toggled_block').css('display', 'none');
}
}

View File

@ -0,0 +1,227 @@
<?php
/**
* Bitrix vars
* @param array $arParams
* @param array $arResult
* @param CBitrixComponentTemplate $this
* @global CUser $USER
* @global CMain $APPLICATION
*/
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
die();
}
$APPLICATION->SetTitle(GetMessage("REGISTER_LP_TITLE"));
if ($arResult["SHOW_SMS_FIELD"] == true) {
CJSCore::Init('phone_auth');
}
?>
<?php CUtil::InitJSCore(['ajax', 'jquery', 'popup']); ?>
<div id="uf_agree_pl_intaro_popup" style="display:none;">
<?=$arResult['AGREEMENT_LOYALTY_PROGRAM']?>
</div>
<div id="uf_pd_proc_pl_intaro_popup" style="display:none;">
<?=$arResult['AGREEMENT_PERSONAL_DATA']?>
</div>
<script>
BX.ready(function() {
const lpAgreementPopup = new BX.PopupWindow('lp_agreement_popup', window.body, {
autoHide: true,
offsetTop: 1,
offsetLeft: 0,
lightShadow: true,
closeIcon: true,
closeByEsc: true,
overlay: {
backgroundColor: 'grey', opacity: '30'
}
});
lpAgreementPopup.setContent(BX('uf_agree_pl_intaro_popup'));
BX.bindDelegate(
document.body, 'click', {className: 'lp_agreement_link'},
BX.proxy(function(e) {
if (!e)
e = window.event;
lpAgreementPopup.show();
return BX.PreventDefault(e);
}, lpAgreementPopup)
);
const personalDataAgreementPopup = new BX.PopupWindow('personal_data_agreement_popup', window.body, {
autoHide: true,
offsetTop: 1,
offsetLeft: 0,
lightShadow: true,
closeIcon: true,
closeByEsc: true,
overlay: {
backgroundColor: 'grey', opacity: '30'
}
});
personalDataAgreementPopup.setContent(BX('uf_pd_proc_pl_intaro_popup'));
BX.bindDelegate(
document.body, 'click', {className: 'personal_data_agreement_link'},
BX.proxy(function(e) {
if (!e)
e = window.event;
personalDataAgreementPopup.show();
return BX.PreventDefault(e);
}, personalDataAgreementPopup)
);
});
</script>
<div class="bx-auth-reg">
<?php if ($USER->IsAuthorized()): ?>
<?php if ('Y' === $arResult['LOYALTY_STATUS']): ?>
<?php $this->addExternalJs(SITE_TEMPLATE_PATH . '/script.js'); ?>
<div id="regBody">
<?php if (isset($arResult['LP_REGISTER']['msg'])) { ?>
<div id="lpRegMsg" class="lpRegMsg"><?=$arResult['LP_REGISTER']['msg']?></div>
<?php } ?>
<?php if (isset($arResult['LP_REGISTER']['form']['button']) && !isset($arResult['LP_REGISTER']['form']['fields'])) { ?>
<input type="button" onclick="<?=$arResult['LP_REGISTER']['form']['button']['action']?>()" value="<?=GetMessage('TRY_AGAIN')?>">
<?php } ?>
<?php
if (isset($arResult['LP_REGISTER']['form']['fields'])) { ?>
<div id="lpRegForm">
<div id="errMsg"></div>
<form id="lpRegFormInputs">
<?php
foreach ($arResult['LP_REGISTER']['form']['fields'] as $key => $field) {
?>
<label>
<input
name="<?=$key?>"
id="<?=$key?>Field"
type="<?=$field['type']?>"
<?php if (isset($field['value'])) { ?>
value="<?=$field['value']?>"
<?php } ?>
>
<?php
if ($key === 'UF_AGREE_PL_INTARO') { ?>
<?=GetMessage('I_AM_AGREE')?><a class="lp_agreement_link" href="javascript:void(0)">
<?php } ?>
<?php
if ($key === 'UF_PD_PROC_PL_INTARO') { ?>
<?=GetMessage('I_AM_AGREE')?><a class="personal_data_agreement_link" href="javascript:void(0)">
<?php } ?>
<?=GetMessage($key)?>
<?php
if ($key === 'UF_PD_PROC_PL_INTARO' || $key === 'UF_AGREE_PL_INTARO') { ?></a><?php } ?>
</label>
<br>
<?php
if ($field['type'] === 'checkbox') { ?>
<br>
<?php } ?>
<?php } ?>
<?php
if ($arResult['ACTIVATE'] === true) {
foreach ($arResult['LP_REGISTER']['form']['externalFields'] as $externalField) {
?>
<lable>
<?php
if ($externalField['type'] === 'string' || $externalField['type'] === 'date') { ?>
<input
name="<?=$externalField['code']?>"
id="external_<?=$externalField['code']?>"
type="<?=$externalField['type']?>"
>
<?=$externalField['name']?>
<?php } ?>
<?php
if ($externalField['type'] === 'boolean') { ?>
<input
name="<?=$externalField['code']?>"
id="external_<?=$externalField['code']?>"
type="checkbox"
>
<?=$externalField['name']?>
<?php } ?>
<?php
if ($externalField['type'] === 'text') { ?>
<textarea
name="<?=$externalField['code']?>"
id="external_<?=$externalField['code']?>"
cols="30"
rows="10"
></textarea>
<?=$externalField['name']?>
<?php } ?>
<?php
if ($externalField['type'] === 'integer' || $externalField['type'] === 'numeric') { ?>
<input
name="<?=$externalField['code']?>"
id="external_<?=$externalField['code']?>"
type="number"
>
<?=$externalField['name']?>
<?php } ?>
<?php
if ($externalField['type'] === 'email') { ?>
<input
name="<?=$externalField['code']?>"
id="external_<?=$externalField['code']?>"
type="email"
>
<?=$externalField['name']?>
<?php } ?>
<?php
if ($externalField['type'] === 'dictionary') { ?>
<select name="<?=$externalField['code']?>">
<?php
foreach ($externalField['dictionaryElements'] as $dictionaryElement) {
?>
<option value="<?=$dictionaryElement['code']?>"><?=$dictionaryElement['name']?> </option>
<?php
}
?>
</select>
<?=$externalField['name']?>
<?php } ?>
</lable>
<br>
<?php
}
}
?>
</form>
<?php
if (isset($arResult['LP_REGISTER']['resendAvailable']) && !empty($arResult['LP_REGISTER']['resendAvailable'])) {
CUtil::InitJSCore(['intaro_countdown']);
?>
<script>
$(function() {
const deadline = new Date('<?= $arResult['LP_REGISTER']['resendAvailable'] ?>');
initializeClock("countdown", deadline);
});
</script>
<div id="countdownDiv"> <?=GetMessage('RESEND_POSSIBLE')?> <span id="countdown"></span> <?=GetMessage('SEC')?></div>
<div id="deadlineMessage" style="display: none;">
<input type="button" onclick="resendRegisterSms(<?=$arResult['LP_REGISTER']['idInLoyalty']?>)" value="<?=GetMessage('RESEND_SMS')?>">
</div>
<?php } ?>
<input type="button" onclick="<?=$arResult['LP_REGISTER']['form']['button']['action']?>()" value="<?=GetMessage('SEND')?>">
</div>
<?php } ?>
</div>
<?php else: ?>
<?=GetMessage('LP_NOT_ACTIVE')?>
<?php endif; ?>
<?php else: ?>
<?=GetMessage('NOT_AUTHORIZED')?>
<?php endif; ?>
</div>

View File

@ -0,0 +1,16 @@
<?php
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
die();
}
$arComponentDescription = [
"NAME" => GetMessage("COMP_MAIN_USER_SCORE_TITLE"),
"DESCRIPTION" => GetMessage("COMP_MAIN_USER_SCORE_DESCR"),
"PATH" => [
"ID" => "utility",
"CHILD" => [
"ID" => "user",
"NAME" => GetMessage("MAIN_USER_GROUP_NAME"),
],
],
];

View File

@ -0,0 +1,4 @@
<?php
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
die();
}

View File

@ -0,0 +1,79 @@
<?php
use Bitrix\Main\Localization\Loc;
use Intaro\RetailCrm\Service\Exception\LpAccountsUnavailableException;
use Intaro\RetailCrm\Component\ConfigProvider;
use Intaro\RetailCrm\Component\ServiceLocator;
use Intaro\RetailCrm\Repository\UserRepository;
use Intaro\RetailCrm\Service\LoyaltyService;
use Bitrix\Main\Loader;
use Intaro\RetailCrm\Service\LoyaltyAccountService;
global $USER;
Loc::loadMessages(__FILE__);
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true || !$USER->IsAuthorized()) {
die(GetMessage('NOT_AUTHORIZED'));
}
try {
if (!Loader::includeModule('intaro.retailcrm')) {
die(GetMessage('MODULE_NOT_INSTALL'));
}
} catch (Throwable $exception) {
die(GetMessage('MODULE_NOT_INSTALL') . ': ' . $exception->getMessage());
}
require_once $_SERVER['DOCUMENT_ROOT']
. '/bitrix/modules/intaro.retailcrm/lib/service/exception/lpaccountsavailableexception.php';
try {
$arResult['LOYALTY_STATUS'] = ConfigProvider::getLoyaltyProgramStatus();
$arResult['PERSONAL_LOYALTY_STATUS'] = LoyaltyAccountService::getLoyaltyPersonalStatus();
$customer = UserRepository::getById($USER->GetID());
if (
$arResult['LOYALTY_STATUS'] === 'Y'
&& null !== $customer->getLoyalty()
&& $customer->getLoyalty()->getIdInLoyalty() > 0
) {
/* @var LoyaltyService $service */
$service = ServiceLocator::get(LoyaltyService::class);
$response = $service->getLoyaltyAccounts($customer->getLoyalty()->getIdInLoyalty());
if ($response !== null) {
$arResult['BONUS_COUNT'] = $response->amount;
$arResult['ACTIVE_STATUS'] = $response->status;
$arResult['CARD'] = $response->cardNumber !== ''
? $response->cardNumber
: GetMessage('CARD_NOT_LINKED');
$arResult['PHONE'] = $response->phoneNumber;
$arResult['REGISTER_DATE'] = $response->createdAt->format('Y-m-d');
$arResult['LOYALTY_LEVEL_NAME'] = $response->loyaltyLevel->name;
$arResult['LOYALTY_LEVEL_ID'] = $response->id;
$arResult['LL_PRIVILEGE_SIZE'] = $response->loyaltyLevel->privilegeSize;
$arResult['LL_PRIVILEGE_SIZE_PROMO'] = $response->loyaltyLevel->privilegeSizePromo;
$arResult['LOYALTY_LEVEL_TYPE'] = $response->loyaltyLevel->type;
$arResult['NEXT_LEVEL_SUM'] = (int)$response->nextLevelSum === 0
? GetMessage('TOP_LEVEL')
: (int) $response->nextLevelSum;
$arResult['ORDERS_SUM'] = (int)$response->ordersSum;
if (is_int($arResult['NEXT_LEVEL_SUM']) && is_int($arResult['ORDERS_SUM'])) {
$arResult['REMAINING_SUM'] = $arResult['NEXT_LEVEL_SUM'] - $arResult['ORDERS_SUM'];
}
}
$this->IncludeComponentTemplate();
} else {
require_once __DIR__ . '/register.php';
}
} catch (LpAccountsUnavailableException $exception) {
$arResult['ERRORS'] = GetMessage('LP_NOT_ACTUAL');
$this->IncludeComponentTemplate();
} catch (Throwable $exception) {
die(GetMessage('MODULE_NOT_INSTALL') . ': ' . $exception->getMessage());
}

View File

@ -0,0 +1,4 @@
<?php
$MESS ['COMP_MAIN_USER_SCORE_TITLE'] = "Личный кабинет программы лояльности RetailCRM";
$MESS ['COMP_MAIN_USER_SCORE_DESCR'] = "Личный кабинет участника программы лояльности RetailCRM";
$MESS ['MAIN_USER_GROUP_NAME'] = "Пользователь";

View File

@ -0,0 +1,11 @@
<?php
$MESS ['NOT_AUTHORIZED'] = 'Вы не авторизованы на сайте';
$MESS['YES'] = 'Да';
$MESS['NO'] = 'Нет';
$MESS['CARD_NOT_LINKED'] = 'Карта не привязана';
$MESS['TOP_LEVEL'] = 'вы достигли высшего уровня привилегий!';
$MESS['ERRORS'] = 'Обнаружена ошибка: ';
$MESS['LP_NOT_ACTUAL'] = 'Идентификатор вашего участия не обнаружен в программе лояльности.';
$MESS['MODULE_NOT_INSTALL']
= 'Программа лояльности недоступна. Возможно, модуль интеграции с RetailCRM не установлен';

View File

@ -0,0 +1,5 @@
<?php $APPLICATION->IncludeComponent(
'intaro:lp.register',
'',
[]
);

View File

@ -0,0 +1,6 @@
<?php
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
die();
}
$arTemplateParameters = [];

View File

@ -0,0 +1,2 @@
<?php
$MESS ['USER_PROPERTY_NAME'] = "Название блока пользовательских свойств";

View File

@ -0,0 +1,43 @@
<?php
$MESS['main_register_sms'] = 'Код подтверждения из СМС:';
$MESS['PERSONAL_PHONE'] = 'Телефон';
$MESS['main_register_sms_send'] = 'Отправить';
$MESS['UF_REG_IN_PL_INTARO'] = 'Зарегистрироваться в программе лояльности';
$MESS['UF_AGREE_PL_INTARO'] = 'программы лояльности:';
$MESS['I_AM_AGREE'] = 'Я согласен с условиями';
$MESS['UF_PD_PROC_PL_INTARO'] = 'обработки персональных данных:';
$MESS['LP_CARD_NUMBER'] = 'Номер карты программы лояльности';
$MESS['SEND'] = 'Отправить';
$MESS['VERIFICATION_CODE'] = 'Код подтверждения';
$MESS['SEND_VERIFICATION_CODE'] = 'Отправьте код подтверждения';
$MESS['REG_LP_MESSAGE'] = 'Для завершения регистрации в программе лояльности введите номер телефона и номер карты программы лояльности';
$MESS['YES'] = 'Да';
$MESS['BONUS_CARD_NUMBER'] = 'Номер карты лояльности (если есть):';
$MESS['SUCCESS_PL_REG'] = 'Вы успешно зарегистрировались в программе лояльности.';
$MESS['LP_FIELDS_NOT_EXIST'] = 'Ошибка установки модуля ПЛ. Отсутствуют UF поля для USER';
$MESS['REG_LP_ERROR'] = 'Ошибка регистрации в Программе лояльности';
$MESS['REGISTER_CONTINUE'] = 'Для завершения регистрации в программе лояльности заполните форму.';
$MESS['UF_CARD_NUM_INTARO'] = 'Номер карты лояльности (если есть)';
$MESS['REGISTER_LP_TITLE'] = 'Регистрация в программе лояльности';
$MESS['LOYALTY_LEVEL_ID'] = 'ID участия';
$MESS['ACTIVE'] = 'Активность аккаунта';
$MESS['LOYALTY_LEVEL_NAME'] = 'Название текущего уровня:';
$MESS['ORDERS_SUM'] = 'Сумма покупок за все время:';
$MESS['NEXT_LEVEL_SUM'] = 'Необходимая сумма покупок для перехода на следующий уровень:';
$MESS['BONUS_COUNT'] = 'Бонусов на счете:';
$MESS['CARD'] = 'Номер бонусной карты:';
$MESS['PHONE'] = 'Привязанный телефон:';
$MESS['REGISTER_DATE'] = 'Дата регистрации:';
$MESS['LOYALTY_LEVEL_TYPE'] = 'Правила текущего уровня:';
$MESS['BONUS_PERCENT'] = 'кешбек от стоимости';
$MESS['BONUS_CONVERTING'] = '1 бонус начисляется за каждые';
$MESS['PERSONAL_DISCOUNT'] = 'персональная скидка';
$MESS['EACH_RUB'] = 'рублей покупки';
$MESS['SIMPLE_PRODUCTS'] = 'Обычные товары:';
$MESS['SALE_PRODUCTS'] = 'Акционные товары:';
$MESS['REMAINING_SUM'] = 'Сумма, оставшаяся до перехода на следующий уровень:';
$MESS['ACTIVATE'] = 'Активировать';
$MESS['STATUS'] = 'Статус участия';
$MESS['STATUS_NOT_CONFIRMED'] = 'не подтверждено';
$MESS['STATUS_DEACTIVATED'] = 'деактивировано';
$MESS['STATUS_ACTIVE'] = 'активно';

View File

@ -0,0 +1,96 @@
<?php
/**
* Bitrix vars
*
* @var array $arResult
* @global CUser $USER
* @global CMain $APPLICATION
*/
if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) {
die();
}
?>
<p>
<?php if (isset($arResult['ERRORS'])) { ?>
<b><?=GetMessage('ERRORS')?></b> <?=$arResult['ERRORS']?><br>
<?php } ?>
<?php if (isset($arResult['LOYALTY_LEVEL_ID'])) { ?>
<b><?=GetMessage('LOYALTY_LEVEL_ID')?></b> <?=$arResult['LOYALTY_LEVEL_ID']?><br>
<?php } ?>
<?php if (isset($arResult['ACTIVE_STATUS'])) { ?>
<b><?=GetMessage('STATUS')?>: </b>
<?php if ($arResult['ACTIVE_STATUS'] === 'not_confirmed') { ?>
<?= GetMessage('STATUS_NOT_CONFIRMED')?>
<a href="/lp-register?activate=Y"> <?= GetMessage('ACTIVATE') ?></a>
<?php } ?>
<?php if ($arResult['ACTIVE_STATUS'] === 'deactivated') { ?>
<?=GetMessage('STATUS_DEACTIVATED')?>
<?php } ?>
<?php if ($arResult['ACTIVE_STATUS'] === 'activated') { ?>
<?= GetMessage('STATUS_ACTIVE')?>
<?php } ?>
<br>
<?php } ?>
<?php if (isset($arResult['LOYALTY_LEVEL_NAME'])) { ?>
<b><?=GetMessage('LOYALTY_LEVEL_NAME')?></b> <?=$arResult['LOYALTY_LEVEL_NAME']?><br>
<?php } ?>
<?php if (isset($arResult['ORDERS_SUM'])) { ?>
<b><?=GetMessage('ORDERS_SUM')?></b> <?=$arResult['ORDERS_SUM']?><br>
<?php } ?>
<?php if (isset($arResult['REMAINING_SUM'])) { ?>
<b><?=GetMessage('REMAINING_SUM')?></b> <?=$arResult['REMAINING_SUM']?><br>
<?php } ?>
<?php if (isset($arResult['BONUS_COUNT'])) { ?>
<b><?=GetMessage('BONUS_COUNT')?></b> <?=$arResult['BONUS_COUNT']?><br>
<?php } ?>
<?php if (isset($arResult['CARD'])) { ?>
<b><?=GetMessage('CARD')?></b> <?=$arResult['CARD']?><br>
<?php } ?>
<?php if (isset($arResult['PHONE'])) { ?>
<b><?=GetMessage('PHONE')?></b> <?=$arResult['PHONE']?><br>
<?php } ?>
<?php if (isset($arResult['REGISTER_DATE'])) { ?>
<b><?=GetMessage('REGISTER_DATE')?></b> <?=$arResult['REGISTER_DATE']?><br>
<?php } ?>
<?php if (isset($arResult['LOYALTY_LEVEL_TYPE'])) { ?>
<br><br><b><?=GetMessage('LOYALTY_LEVEL_TYPE')?></b><br>
<?php if (isset($arResult['NEXT_LEVEL_SUM'])) { ?>
<b><?=GetMessage('NEXT_LEVEL_SUM')?></b> <?=$arResult['NEXT_LEVEL_SUM']?><br>
<?php } ?>
<?php
switch ($arResult['LOYALTY_LEVEL_TYPE']) {
case 'bonus_percent':
?>
<b><?=GetMessage('SIMPLE_PRODUCTS')?></b>
<?=GetMessage('BONUS_PERCENT')?> <?=$arResult['LL_PRIVILEGE_SIZE']?>%<br>
<b><?=GetMessage('SALE_PRODUCTS')?></b>
<?=GetMessage('BONUS_PERCENT')?> <?=$arResult['LL_PRIVILEGE_SIZE_PROMO']?>%<br>
<?php
break;
case 'bonus_converting':
?>
<b><?=GetMessage('SIMPLE_PRODUCTS')?></b>
<?=GetMessage('BONUS_CONVERTING')?> <?=$arResult['LL_PRIVILEGE_SIZE']?> <?=GetMessage('EACH_RUB')?><br>
<b><?=GetMessage('SALE_PRODUCTS')?></b>
<?=GetMessage('BONUS_CONVERTING')?> <?=$arResult['LL_PRIVILEGE_SIZE_PROMO']?>
<?=GetMessage('EACH_RUB')?><br>
<?php
break;
case 'discount':
?>
<b><?=GetMessage('SIMPLE_PRODUCTS')?></b>
<?=GetMessage('PERSONAL_DISCOUNT')?> <?=$arResult['LL_PRIVILEGE_SIZE']?>%<br>
<b><?=GetMessage('SALE_PRODUCTS')?></b>
<?=GetMessage('PERSONAL_DISCOUNT')?> <?=$arResult['LL_PRIVILEGE_SIZE_PROMO']?>%<br>
<?php
break;
default: ?> - <?php
break;
}
?>
<?php } ?>
</p>

View File

@ -0,0 +1,16 @@
<?
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
$arComponentDescription = array(
"NAME" => GetMessage("COMP_MAIN_USER_REGISTER_TITLE"),
"DESCRIPTION" => GetMessage("COMP_MAIN_USER_REGISTER_DESCR"),
"ICON" => "/images/user_register.gif",
"PATH" => array(
"ID" => "utility",
"CHILD" => array(
"ID" => "user",
"NAME" => GetMessage("MAIN_USER_GROUP_NAME")
),
),
);
?>

View File

@ -0,0 +1,123 @@
<?if(!defined("B_PROLOG_INCLUDED")||B_PROLOG_INCLUDED!==true)die();
$arFormFields = array(
"EMAIL"=>1,
);
if(COption::GetOptionString("main", "new_user_phone_auth", "N") == "Y")
{
$arFormFields["PHONE_NUMBER"] = 1;
}
$arFormFields = array_merge($arFormFields, array(
"TITLE"=>1,
"NAME"=>1,
"SECOND_NAME"=>1,
"LAST_NAME"=>1,
"AUTO_TIME_ZONE"=>1,
"PERSONAL_PROFESSION"=>1,
"PERSONAL_WWW"=>1,
"PERSONAL_ICQ"=>1,
"PERSONAL_GENDER"=>1,
"PERSONAL_BIRTHDAY"=>1,
"PERSONAL_PHOTO"=>1,
"PERSONAL_PHONE"=>1,
"PERSONAL_FAX"=>1,
"PERSONAL_MOBILE"=>1,
"PERSONAL_PAGER"=>1,
"PERSONAL_STREET"=>1,
"PERSONAL_MAILBOX"=>1,
"PERSONAL_CITY"=>1,
"PERSONAL_STATE"=>1,
"PERSONAL_ZIP"=>1,
"PERSONAL_COUNTRY"=>1,
"PERSONAL_NOTES"=>1,
"WORK_COMPANY"=>1,
"WORK_DEPARTMENT"=>1,
"WORK_POSITION"=>1,
"WORK_WWW"=>1,
"WORK_PHONE"=>1,
"WORK_FAX"=>1,
"WORK_PAGER"=>1,
"WORK_STREET"=>1,
"WORK_MAILBOX"=>1,
"WORK_CITY"=>1,
"WORK_STATE"=>1,
"WORK_ZIP"=>1,
"WORK_COUNTRY"=>1,
"WORK_PROFILE"=>1,
"WORK_LOGO"=>1,
"WORK_NOTES"=>1,
));
if(!CTimeZone::Enabled())
unset($arFormFields["AUTO_TIME_ZONE"]);
$arUserFields = array();
foreach ($arFormFields as $value=>$dummy)
{
$arUserFields[$value] = "[".$value."] ".GetMessage("REGISTER_FIELD_".$value);
}
$arRes = $GLOBALS["USER_FIELD_MANAGER"]->GetUserFields("USER", 0, LANGUAGE_ID);
$userProp = array();
if (!empty($arRes))
{
foreach ($arRes as $key => $val)
$userProp[$val["FIELD_NAME"]] = (strLen($val["EDIT_FORM_LABEL"]) > 0 ? $val["EDIT_FORM_LABEL"] : $val["FIELD_NAME"]);
}
$arComponentParameters = array(
"PARAMETERS" => array(
"SHOW_FIELDS" => array(
"NAME" => GetMessage("REGISTER_SHOW_FIELDS"),
"TYPE" => "LIST",
"MULTIPLE" => "Y",
"ADDITIONAL_VALUES" => "N",
"VALUES" => $arUserFields,
"PARENT" => "BASE",
),
"REQUIRED_FIELDS" => array(
"NAME" => GetMessage("REGISTER_REQUIRED_FIELDS"),
"TYPE" => "LIST",
"MULTIPLE" => "Y",
"ADDITIONAL_VALUES" => "N",
"VALUES" => $arUserFields,
"PARENT" => "BASE",
),
"AUTH" => array(
"NAME" => GetMessage("REGISTER_AUTOMATED_AUTH"),
"TYPE" => "CHECKBOX",
"DEFAULT" => "Y",
"PARENT" => "ADDITIONAL_SETTINGS",
),
"USE_BACKURL" => array(
"NAME" => GetMessage("REGISTER_USE_BACKURL"),
"TYPE" => "CHECKBOX",
"DEFAULT" => "Y",
"PARENT" => "ADDITIONAL_SETTINGS",
),
"SUCCESS_PAGE" => array(
"NAME" => GetMessage("REGISTER_SUCCESS_PAGE"),
"TYPE" => "STRING",
"DEFAULT" => "",
"PARENT" => "ADDITIONAL_SETTINGS",
),
"SET_TITLE" => array(),
"USER_PROPERTY"=>array(
"PARENT" => "ADDITIONAL_SETTINGS",
"NAME" => GetMessage("USER_PROPERTY"),
"TYPE" => "LIST",
"VALUES" => $userProp,
"MULTIPLE" => "Y",
"DEFAULT" => array(),
),
),
);
?>

View File

@ -0,0 +1,384 @@
<?
/**
* Bitrix Framework
* @package bitrix
* @subpackage main
* @copyright 2001-2014 Bitrix
*/
/**
* Bitrix vars
* @global CMain $APPLICATION
* @global CUser $USER
* @global CDatabase $DB
* @global CUserTypeManager $USER_FIELD_MANAGER
* @param array $arParams
* @param array $arResult
* @param CBitrixComponent $this
*/
if(!defined("B_PROLOG_INCLUDED")||B_PROLOG_INCLUDED!==true) {
die();
}
global $USER_FIELD_MANAGER;
// apply default param values
$arDefaultValues = array(
"SHOW_FIELDS" => array(),
"REQUIRED_FIELDS" => array(),
"AUTH" => "Y",
"USE_BACKURL" => "Y",
"SUCCESS_PAGE" => "",
);
foreach ($arDefaultValues as $key => $value)
{
if (!is_set($arParams, $key))
$arParams[$key] = $value;
}
if(!is_array($arParams["SHOW_FIELDS"]))
$arParams["SHOW_FIELDS"] = array();
if(!is_array($arParams["REQUIRED_FIELDS"]))
$arParams["REQUIRED_FIELDS"] = array();
// if user registration blocked - return auth form
if (COption::GetOptionString("main", "new_user_registration", "N") == "N")
$APPLICATION->AuthForm(array());
$arResult["PHONE_REGISTRATION"] = (COption::GetOptionString("main", "new_user_phone_auth", "N") == "Y");
$arResult["PHONE_REQUIRED"] = ($arResult["PHONE_REGISTRATION"] && COption::GetOptionString("main", "new_user_phone_required", "N") == "Y");
$arResult["EMAIL_REGISTRATION"] = (COption::GetOptionString("main", "new_user_email_auth", "Y") <> "N");
$arResult["EMAIL_REQUIRED"] = ($arResult["EMAIL_REGISTRATION"] && COption::GetOptionString("main", "new_user_email_required", "Y") <> "N");
$arResult["USE_EMAIL_CONFIRMATION"] = (COption::GetOptionString("main", "new_user_registration_email_confirmation", "N") == "Y" && $arResult["EMAIL_REQUIRED"]? "Y" : "N");
$arResult["PHONE_CODE_RESEND_INTERVAL"] = CUser::PHONE_CODE_RESEND_INTERVAL;
// apply core fields to user defined
$arDefaultFields = array(
"LOGIN",
);
if($arResult["EMAIL_REQUIRED"])
{
$arDefaultFields[] = "EMAIL";
}
if($arResult["PHONE_REQUIRED"])
{
$arDefaultFields[] = "PHONE_NUMBER";
}
$arDefaultFields[] = "PASSWORD";
$arDefaultFields[] = "CONFIRM_PASSWORD";
$def_group = COption::GetOptionString("main", "new_user_registration_def_group", "");
if($def_group <> "")
$arResult["GROUP_POLICY"] = CUser::GetGroupPolicy(explode(",", $def_group));
else
$arResult["GROUP_POLICY"] = CUser::GetGroupPolicy(array());
$arResult["SHOW_FIELDS"] = array_unique(array_merge($arDefaultFields, $arParams["SHOW_FIELDS"]));
$arResult["REQUIRED_FIELDS"] = array_unique(array_merge($arDefaultFields, $arParams["REQUIRED_FIELDS"]));
// use captcha?
$arResult["USE_CAPTCHA"] = COption::GetOptionString("main", "captcha_registration", "N") == "Y" ? "Y" : "N";
// start values
$arResult["VALUES"] = array();
$arResult["ERRORS"] = array();
$arResult["SHOW_SMS_FIELD"] = false;
$register_done = false;
// register user
if ($_SERVER["REQUEST_METHOD"] == "POST" && $_REQUEST["register_submit_button"] <> '' && !$USER->IsAuthorized())
{
if(COption::GetOptionString('main', 'use_encrypted_auth', 'N') == 'Y')
{
//possible encrypted user password
$sec = new CRsaSecurity();
if(($arKeys = $sec->LoadKeys()))
{
$sec->SetKeys($arKeys);
$errno = $sec->AcceptFromForm(array('REGISTER'));
if($errno == CRsaSecurity::ERROR_SESS_CHECK)
$arResult["ERRORS"][] = GetMessage("main_register_sess_expired");
elseif($errno < 0)
$arResult["ERRORS"][] = GetMessage("main_register_decode_err", array("#ERRCODE#"=>$errno));
}
}
// check emptiness of required fields
foreach ($arResult["SHOW_FIELDS"] as $key)
{
if ($key != "PERSONAL_PHOTO" && $key != "WORK_LOGO")
{
$arResult["VALUES"][$key] = $_REQUEST["REGISTER"][$key];
if (in_array($key, $arResult["REQUIRED_FIELDS"]) && trim($arResult["VALUES"][$key]) == '')
$arResult["ERRORS"][$key] = GetMessage("REGISTER_FIELD_REQUIRED");
}
else
{
$_FILES["REGISTER_FILES_".$key]["MODULE_ID"] = "main";
$arResult["VALUES"][$key] = $_FILES["REGISTER_FILES_".$key];
if (in_array($key, $arResult["REQUIRED_FIELDS"]) && !is_uploaded_file($_FILES["REGISTER_FILES_".$key]["tmp_name"]))
$arResult["ERRORS"][$key] = GetMessage("REGISTER_FIELD_REQUIRED");
}
}
if(isset($_REQUEST["REGISTER"]["TIME_ZONE"]))
$arResult["VALUES"]["TIME_ZONE"] = $_REQUEST["REGISTER"]["TIME_ZONE"];
$USER_FIELD_MANAGER->EditFormAddFields("USER", $arResult["VALUES"]);
//this is a part of CheckFields() to show errors about user defined fields
if (!$USER_FIELD_MANAGER->CheckFields("USER", 0, $arResult["VALUES"]))
{
$e = $APPLICATION->GetException();
$arResult["ERRORS"][] = substr($e->GetString(), 0, -4); //cutting "<br>"
$APPLICATION->ResetException();
}
// check captcha
if ($arResult["USE_CAPTCHA"] == "Y")
{
if (!$APPLICATION->CaptchaCheckCode($_REQUEST["captcha_word"], $_REQUEST["captcha_sid"]))
$arResult["ERRORS"][] = GetMessage("REGISTER_WRONG_CAPTCHA");
}
if(count($arResult["ERRORS"]) > 0)
{
if(COption::GetOptionString("main", "event_log_register_fail", "N") === "Y")
{
$arError = $arResult["ERRORS"];
foreach($arError as $key => $error)
if(intval($key) == 0 && $key !== 0)
$arError[$key] = str_replace("#FIELD_NAME#", '"'.$key.'"', $error);
CEventLog::Log("SECURITY", "USER_REGISTER_FAIL", "main", false, implode("<br>", $arError));
}
}
else // if there's no any errors - create user
{
$arResult['VALUES']["GROUP_ID"] = array();
$def_group = COption::GetOptionString("main", "new_user_registration_def_group", "");
if($def_group != "")
$arResult['VALUES']["GROUP_ID"] = explode(",", $def_group);
$bConfirmReq = ($arResult["USE_EMAIL_CONFIRMATION"] === "Y");
$active = ($bConfirmReq || $arResult["PHONE_REQUIRED"]? "N": "Y");
$arResult['VALUES']["CHECKWORD"] = md5(CMain::GetServerUniqID().uniqid());
$arResult['VALUES']["~CHECKWORD_TIME"] = $DB->CurrentTimeFunction();
$arResult['VALUES']["ACTIVE"] = $active;
$arResult['VALUES']["CONFIRM_CODE"] = ($bConfirmReq? randString(8): "");
$arResult['VALUES']["LID"] = SITE_ID;
$arResult['VALUES']["LANGUAGE_ID"] = LANGUAGE_ID;
$arResult['VALUES']["USER_IP"] = $_SERVER["REMOTE_ADDR"];
$arResult['VALUES']["USER_HOST"] = @gethostbyaddr($_SERVER["REMOTE_ADDR"]);
if($arResult["VALUES"]["AUTO_TIME_ZONE"] <> "Y" && $arResult["VALUES"]["AUTO_TIME_ZONE"] <> "N")
$arResult["VALUES"]["AUTO_TIME_ZONE"] = "";
$bOk = true;
$events = GetModuleEvents("main", "OnBeforeUserRegister", true);
foreach($events as $arEvent)
{
if(ExecuteModuleEventEx($arEvent, array(&$arResult['VALUES'])) === false)
{
if($err = $APPLICATION->GetException())
$arResult['ERRORS'][] = $err->GetString();
$bOk = false;
break;
}
}
$ID = 0;
$user = new CUser();
if ($bOk)
{
$ID = $user->Add($arResult["VALUES"]);
}
if ((int) $ID > 0)
{
if($arResult["PHONE_REGISTRATION"] == true && $arResult['VALUES']["PHONE_NUMBER"] <> '')
{
//added the phone number for the user, now sending a confirmation SMS
list($code, $phoneNumber) = CUser::GeneratePhoneCode($ID);
$sms = new \Bitrix\Main\Sms\Event(
"SMS_USER_CONFIRM_NUMBER",
[
"USER_PHONE" => $phoneNumber,
"CODE" => $code,
]
);
$smsResult = $sms->send(true);
if(!$smsResult->isSuccess())
{
$arResult["ERRORS"] = array_merge($arResult["ERRORS"], $smsResult->getErrorMessages());
}
$arResult["SHOW_SMS_FIELD"] = true;
$arResult["SIGNED_DATA"] = \Bitrix\Main\Controller\PhoneAuth::signData(['phoneNumber' => $phoneNumber]);
}
else
{
$register_done = true;
// authorize user
if ($arParams["AUTH"] == "Y" && $arResult["VALUES"]["ACTIVE"] == "Y")
{
if (!$arAuthResult = $USER->Login($arResult["VALUES"]["LOGIN"], $arResult["VALUES"]["PASSWORD"]))
$arResult["ERRORS"][] = $arAuthResult;
}
}
$arResult['VALUES']["USER_ID"] = $ID;
$arEventFields = $arResult['VALUES'];
unset($arEventFields["PASSWORD"]);
unset($arEventFields["CONFIRM_PASSWORD"]);
$event = new CEvent;
$event->SendImmediate("NEW_USER", SITE_ID, $arEventFields);
if($bConfirmReq)
$event->SendImmediate("NEW_USER_CONFIRM", SITE_ID, $arEventFields);
}
else
{
$arResult["ERRORS"][] = $user->LAST_ERROR;
}
if(count($arResult["ERRORS"]) <= 0)
{
if(COption::GetOptionString("main", "event_log_register", "N") === "Y")
CEventLog::Log("SECURITY", "USER_REGISTER", "main", $ID);
}
else
{
if(COption::GetOptionString("main", "event_log_register_fail", "N") === "Y")
CEventLog::Log("SECURITY", "USER_REGISTER_FAIL", "main", $ID, implode("<br>", $arResult["ERRORS"]));
}
$events = GetModuleEvents("main", "OnAfterUserRegister", true);
foreach ($events as $arEvent)
ExecuteModuleEventEx($arEvent, array(&$arResult['VALUES']));
}
}
// verify phone code
if ($_SERVER["REQUEST_METHOD"] == "POST" && $_REQUEST["code_submit_button"] <> '' && !$USER->IsAuthorized())
{
if($_REQUEST["SIGNED_DATA"] <> '')
{
if(($params = \Bitrix\Main\Controller\PhoneAuth::extractData($_REQUEST["SIGNED_DATA"])) !== false)
{
if(($userId = CUser::VerifyPhoneCode($params['phoneNumber'], $_REQUEST["SMS_CODE"])))
{
$register_done = true;
if($arResult["PHONE_REQUIRED"])
{
//the user was added as inactive, now phone number is confirmed, activate them
$user = new CUser();
$user->Update($userId, ["ACTIVE" => "Y"]);
}
// authorize user
if ($arParams["AUTH"] == "Y")
{
//here should be login
$USER->Authorize($userId);
}
}
else
{
$arResult["ERRORS"][] = GetMessage("main_register_error_sms");
$arResult["SHOW_SMS_FIELD"] = true;
$arResult["SMS_CODE"] = $_REQUEST["SMS_CODE"];
$arResult["SIGNED_DATA"] = $_REQUEST["SIGNED_DATA"];
}
}
}
}
// if user is registered - redirect him to backurl or to success_page; currently added users too
if($register_done)
{
if($arParams["USE_BACKURL"] == "Y" && $_REQUEST["backurl"] <> '')
LocalRedirect($_REQUEST["backurl"]);
elseif($arParams["SUCCESS_PAGE"] <> '')
LocalRedirect($arParams["SUCCESS_PAGE"]);
}
$arResult["VALUES"] = htmlspecialcharsEx($arResult["VALUES"]);
// redefine required list - for better use in template
$arResult["REQUIRED_FIELDS_FLAGS"] = array();
foreach ($arResult["REQUIRED_FIELDS"] as $field)
$arResult["REQUIRED_FIELDS_FLAGS"][$field] = "Y";
// check backurl existance
$arResult["BACKURL"] = htmlspecialcharsbx($_REQUEST["backurl"]);
// get countries list
if (in_array("PERSONAL_COUNTRY", $arResult["SHOW_FIELDS"]) || in_array("WORK_COUNTRY", $arResult["SHOW_FIELDS"]))
$arResult["COUNTRIES"] = GetCountryArray();
// get date format
if (in_array("PERSONAL_BIRTHDAY", $arResult["SHOW_FIELDS"]))
$arResult["DATE_FORMAT"] = CLang::GetDateFormat("SHORT");
// ********************* User properties ***************************************************
$arResult["USER_PROPERTIES"] = array("SHOW" => "N");
$arUserFields = $USER_FIELD_MANAGER->GetUserFields("USER", 0, LANGUAGE_ID);
if (is_array($arUserFields) && count($arUserFields) > 0)
{
if (!is_array($arParams["USER_PROPERTY"]))
$arParams["USER_PROPERTY"] = array($arParams["USER_PROPERTY"]);
foreach ($arUserFields as $FIELD_NAME => $arUserField)
{
if (!in_array($FIELD_NAME, $arParams["USER_PROPERTY"]) && $arUserField["MANDATORY"] != "Y")
continue;
$arUserField["EDIT_FORM_LABEL"] = strLen($arUserField["EDIT_FORM_LABEL"]) > 0 ? $arUserField["EDIT_FORM_LABEL"] : $arUserField["FIELD_NAME"];
$arUserField["EDIT_FORM_LABEL"] = htmlspecialcharsEx($arUserField["EDIT_FORM_LABEL"]);
$arUserField["~EDIT_FORM_LABEL"] = $arUserField["EDIT_FORM_LABEL"];
$arResult["USER_PROPERTIES"]["DATA"][$FIELD_NAME] = $arUserField;
}
}
if (!empty($arResult["USER_PROPERTIES"]["DATA"]))
{
$arResult["USER_PROPERTIES"]["SHOW"] = "Y";
$arResult["bVarsFromForm"] = (count($arResult['ERRORS']) <= 0) ? false : true;
}
// ******************** /User properties ***************************************************
// initialize captcha
if ($arResult["USE_CAPTCHA"] == "Y")
$arResult["CAPTCHA_CODE"] = htmlspecialcharsbx($APPLICATION->CaptchaGetCode());
// set title
if ($arParams["SET_TITLE"] == "Y")
$APPLICATION->SetTitle(GetMessage("REGISTER_DEFAULT_TITLE"));
//time zones
$arResult["TIME_ZONE_ENABLED"] = CTimeZone::Enabled();
if($arResult["TIME_ZONE_ENABLED"])
$arResult["TIME_ZONE_LIST"] = CTimeZone::GetZones();
$arResult["SECURE_AUTH"] = false;
if(!CMain::IsHTTPS() && COption::GetOptionString('main', 'use_encrypted_auth', 'N') == 'Y')
{
$sec = new CRsaSecurity();
if(($arKeys = $sec->LoadKeys()))
{
$sec->SetKeys($arKeys);
$sec->AddToForm('regform', array('REGISTER[PASSWORD]', 'REGISTER[CONFIRM_PASSWORD]'));
$arResult["SECURE_AUTH"] = true;
}
}
// all done
$this->IncludeComponentTemplate();

Binary file not shown.

After

Width:  |  Height:  |  Size: 507 B

View File

@ -0,0 +1,4 @@
<?php
$MESS ['COMP_MAIN_USER_REGISTER_TITLE'] = "Настраиваемая регистрация RetailCRM";
$MESS ['COMP_MAIN_USER_REGISTER_DESCR'] = "Управляемая форма регистрации нового пользователя с функциями Программы лояльности";
$MESS ['MAIN_USER_GROUP_NAME'] = "Пользователь";

View File

@ -0,0 +1,48 @@
<?
$MESS ['REGISTER_SHOW_FIELDS'] = "Поля, которые показывать в форме";
$MESS ['REGISTER_REQUIRED_FIELDS'] = "Поля, обязательные для заполнения";
$MESS ['REGISTER_AUTOMATED_AUTH'] = "Автоматически авторизовать пользователей";
$MESS ['REGISTER_USE_BACKURL'] = "Отправлять пользователя по обратной ссылке, если она есть";
$MESS ['REGISTER_SUCCESS_PAGE'] = "Страница окончания регистрации";
$MESS ['REGISTER_FIELD_EMAIL'] = "Email";
$MESS ['REGISTER_FIELD_PHONE_NUMBER'] = "Номер телефона для регистрации";
$MESS ['REGISTER_FIELD_TITLE'] = "Обращение";
$MESS ['REGISTER_FIELD_NAME'] = "Имя";
$MESS ['REGISTER_FIELD_SECOND_NAME'] = "Отчество";
$MESS ['REGISTER_FIELD_LAST_NAME'] = "Фамилия";
$MESS ['REGISTER_FIELD_AUTO_TIME_ZONE'] = "Часовой пояс";
$MESS ['REGISTER_FIELD_PERSONAL_PROFESSION'] = "Профессия";
$MESS ['REGISTER_FIELD_PERSONAL_WWW'] = "WWW-страница";
$MESS ['REGISTER_FIELD_PERSONAL_ICQ'] = "ICQ";
$MESS ['REGISTER_FIELD_PERSONAL_GENDER'] = "Пол";
$MESS ['REGISTER_FIELD_PERSONAL_BIRTHDAY'] = "Дата рождения";
$MESS ['REGISTER_FIELD_PERSONAL_PHOTO'] = "Фотография";
$MESS ['REGISTER_FIELD_PERSONAL_PHONE'] = "Телефон";
$MESS ['REGISTER_FIELD_PERSONAL_FAX'] = "Факс";
$MESS ['REGISTER_FIELD_PERSONAL_MOBILE'] = "Мобильный";
$MESS ['REGISTER_FIELD_PERSONAL_PAGER'] = "Пейджер";
$MESS ['REGISTER_FIELD_PERSONAL_STREET'] = "Улица, дом";
$MESS ['REGISTER_FIELD_PERSONAL_MAILBOX'] = "Почтовый ящик";
$MESS ['REGISTER_FIELD_PERSONAL_CITY'] = "Город";
$MESS ['REGISTER_FIELD_PERSONAL_STATE'] = "Область / край";
$MESS ['REGISTER_FIELD_PERSONAL_ZIP'] = "Почтовый индекс";
$MESS ['REGISTER_FIELD_PERSONAL_COUNTRY'] = "Страна";
$MESS ['REGISTER_FIELD_PERSONAL_NOTES'] = "Дополнительные заметки";
$MESS ['REGISTER_FIELD_WORK_COMPANY'] = "Наименование компании";
$MESS ['REGISTER_FIELD_WORK_DEPARTMENT'] = "Департамент / Отдел";
$MESS ['REGISTER_FIELD_WORK_POSITION'] = "Должность";
$MESS ['REGISTER_FIELD_WORK_WWW'] = "WWW-страница";
$MESS ['REGISTER_FIELD_WORK_PHONE'] = "Телефон";
$MESS ['REGISTER_FIELD_WORK_FAX'] = "Факс";
$MESS ['REGISTER_FIELD_WORK_PAGER'] = "Пейджер";
$MESS ['REGISTER_FIELD_WORK_STREET'] = "Улица, дом";
$MESS ['REGISTER_FIELD_WORK_MAILBOX'] = "Почтовый ящик";
$MESS ['REGISTER_FIELD_WORK_CITY'] = "Город";
$MESS ['REGISTER_FIELD_WORK_STATE'] = "Область / край";
$MESS ['REGISTER_FIELD_WORK_ZIP'] = "Почтовый индекс";
$MESS ['REGISTER_FIELD_WORK_COUNTRY'] = "Страна";
$MESS ['REGISTER_FIELD_WORK_PROFILE'] = "Направления деятельности";
$MESS ['REGISTER_FIELD_WORK_LOGO'] = "Логотип компании";
$MESS ['REGISTER_FIELD_WORK_NOTES'] = "Дополнительные заметки";
$MESS ['USER_PROPERTY'] = "Показывать доп. свойства";
?>

View File

@ -0,0 +1,9 @@
<?
$MESS ['REGISTER_WRONG_CAPTCHA'] = "Неверно введено слово с картинки";
$MESS ['REGISTER_FIELD_REQUIRED'] = "Поле #FIELD_NAME# обязательно для заполнения";
$MESS ['REGISTER_DEFAULT_TITLE'] = "Регистрация нового пользователя";
$MESS ['REGISTER_USER_WITH_EMAIL_EXIST'] = "Пользователь с таким e-mail (#EMAIL#) уже существует.";
$MESS["main_register_sess_expired"]="Ваша сессия истекла, повторите попытку регистрации.";
$MESS["main_register_decode_err"]="Ошибка при дешифровании пароля (#ERRCODE#).";
$MESS["main_register_error_sms"] = "Неверный код подтверждения из СМС.";
?>

View File

@ -0,0 +1,11 @@
<?
$MESS ['SEF_MODE_TIP'] = "Опция включает поддержку ЧПУ.";
$MESS ['SHOW_FIELDS_TIP'] = "Настройка служит для выбора полей, которые будут выведены в форме регистрации в дополнение к стандартному набору(логину, паролю, e-mail). ";
$MESS ['REQUIRED_FIELDS_TIP'] = "Поля, выбранные в предыдущем пункте и отмеченные здесь, будут обязательными для заполнения в форме.";
$MESS ['AUTH_TIP'] = "При наличии установленной опции после регистрации пользователя он автоматически будет авторизован на сайте. В противном случае после регистрации пользователю будет предоставлена к заполнению форма авторизации.";
$MESS ['USE_BACKURL_TIP'] = "При наличии в адресной строке параметра <i>backurl</i> пользователь будет перенаправлен по указанной в этом параметре ссылке после заполнения формы регистрации. ";
$MESS ['SUCCESS_PAGE_TIP'] = "Можно указать ссылку на любую страницу на сайте, которая будет финальной страницей процедуры регистрации, и пользователь будет перенаправлен на нее в случае успешной регистрации. ";
$MESS ['SET_TITLE_TIP'] = "При отмеченной опции в качестве заголовка страницы будет установлено \"Регистрация нового пользователя\".";
$MESS ['SEF_FOLDER_TIP'] = "Указывается каталог, который будет отображаться в URL при переходе на создаваемую страницу.";
$MESS ['USER_PROPERTY_TIP'] = "Отметьте дополнительные свойства, которые необходимо отобразить в профиле пользователя.";
?>

View File

@ -0,0 +1,10 @@
<?
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
$arTemplateParameters = array(
"USER_PROPERTY_NAME"=>array(
"NAME" => GetMessage("USER_PROPERTY_NAME"),
"TYPE" => "STRING",
"DEFAULT" => "",
),
);
?>

Binary file not shown.

After

Width:  |  Height:  |  Size: 566 B

View File

@ -0,0 +1,3 @@
<?
$MESS ['USER_PROPERTY_NAME'] = "Название блока пользовательских свойств";
?>

View File

@ -0,0 +1,3 @@
<?php
$MESS ['INTARO_NOT_INSTALLED'] = "Модуль интеграции с RetailCRM не установлен";

View File

@ -0,0 +1,82 @@
<?php
$MESS["AUTH_REGISTER"] = "Регистрация";
$MESS["REGISTER_CAPTCHA_TITLE"] = "Защита от автоматической регистрации";
$MESS["REGISTER_CAPTCHA_PROMT"] = "Введите слово на картинке";
$MESS["AUTH_REQ"] = "Поля, обязательные для заполнения.";
$MESS["USER_DONT_KNOW"] = "(неизвестно)";
$MESS["USER_MALE"] = "Мужской";
$MESS["USER_FEMALE"] = "Женский";
$MESS["REGISTER_FIELD_LOGIN"] = "Логин (мин. 3 символа)";
$MESS["REGISTER_FIELD_EMAIL"] = "Email";
$MESS["REGISTER_FIELD_PASSWORD"] = "Пароль";
$MESS["REGISTER_FIELD_CONFIRM_PASSWORD"] = "Подтверждение пароля";
$MESS["REGISTER_FIELD_TITLE"] = "Обращение";
$MESS["REGISTER_FIELD_NAME"] = "Имя";
$MESS["REGISTER_FIELD_SECOND_NAME"] = "Отчество";
$MESS["REGISTER_FIELD_LAST_NAME"] = "Фамилия";
$MESS["REGISTER_FIELD_AUTO_TIME_ZONE"] = "Часовой пояс";
$MESS["REGISTER_FIELD_PERSONAL_PROFESSION"] = "Профессия";
$MESS["REGISTER_FIELD_PERSONAL_WWW"] = "WWW-страница";
$MESS["REGISTER_FIELD_PERSONAL_ICQ"] = "ICQ";
$MESS["REGISTER_FIELD_PERSONAL_GENDER"] = "Пол";
$MESS["REGISTER_FIELD_PERSONAL_BIRTHDAY"] = "Дата рождения";
$MESS["REGISTER_FIELD_PERSONAL_PHOTO"] = "Фотография";
$MESS["REGISTER_FIELD_PERSONAL_PHONE"] = "Телефон";
$MESS["PERSONAL_PHONE"] = "Телефон";
$MESS["REGISTER_FIELD_PERSONAL_FAX"] = "Факс";
$MESS["REGISTER_FIELD_PERSONAL_MOBILE"] = "Мобильный";
$MESS["REGISTER_FIELD_PERSONAL_PAGER"] = "Пейджер";
$MESS["REGISTER_FIELD_PERSONAL_STREET"] = "Улица, дом";
$MESS["REGISTER_FIELD_PERSONAL_MAILBOX"] = "Почтовый ящик";
$MESS["REGISTER_FIELD_PERSONAL_CITY"] = "Город";
$MESS["REGISTER_FIELD_PERSONAL_STATE"] = "Область / край";
$MESS["REGISTER_FIELD_PERSONAL_ZIP"] = "Почтовый индекс";
$MESS["REGISTER_FIELD_PERSONAL_COUNTRY"] = "Страна";
$MESS["REGISTER_FIELD_PERSONAL_NOTES"] = "Дополнительные заметки";
$MESS["REGISTER_FIELD_WORK_COMPANY"] = "Наименование компании";
$MESS["REGISTER_FIELD_WORK_DEPARTMENT"] = "Департамент / Отдел";
$MESS["REGISTER_FIELD_WORK_POSITION"] = "Должность";
$MESS["REGISTER_FIELD_WORK_WWW"] = "WWW-страница (работа)";
$MESS["REGISTER_FIELD_WORK_PHONE"] = "Телефон (работа)";
$MESS["REGISTER_FIELD_WORK_FAX"] = "Факс (работа)";
$MESS["REGISTER_FIELD_WORK_PAGER"] = "Пейджер (работа)";
$MESS["REGISTER_FIELD_WORK_STREET"] = "Улица, дом (работа)";
$MESS["REGISTER_FIELD_WORK_MAILBOX"] = "Почтовый ящик (работа)";
$MESS["REGISTER_FIELD_WORK_CITY"] = "Город (работа)";
$MESS["REGISTER_FIELD_WORK_STATE"] = "Область / край (работа)";
$MESS["REGISTER_FIELD_WORK_ZIP"] = "Почтовый индекс (работа)";
$MESS["REGISTER_FIELD_WORK_COUNTRY"] = "Страна (работа)";
$MESS["REGISTER_FIELD_WORK_PROFILE"] = "Направления деятельности";
$MESS["REGISTER_FIELD_WORK_LOGO"] = "Логотип компании";
$MESS["REGISTER_FIELD_WORK_NOTES"] = "Дополнительные заметки (работа)";
$MESS["REGISTER_FIELD_PHONE_NUMBER"] = "Номер телефона";
$MESS["REGISTER_EMAIL_WILL_BE_SENT"] = "На указанный в форме email придет запрос на подтверждение регистрации.";
$MESS["MAIN_REGISTER_AUTH"] = "Вы зарегистрированы на сайте и успешно авторизованы.";
$MESS["main_profile_time_zones_auto"] = "Автоматически определять часовой пояс:";
$MESS["main_profile_time_zones_auto_def"] = "(по умолчанию)";
$MESS["main_profile_time_zones_auto_yes"] = "Да, определить по браузеру";
$MESS["main_profile_time_zones_auto_no"] = "Нет, выбрать из списка";
$MESS["main_profile_time_zones_zones"] = "Часовой пояс:";
$MESS["AUTH_SECURE_NOTE"] = "Перед отправкой формы пароль будет зашифрован в браузере. Это позволит избежать передачи пароля в открытом виде.";
$MESS["AUTH_NONSECURE_NOTE"] = "Пароль будет отправлен в открытом виде. Включите JavaScript в браузере, чтобы зашифровать пароль перед отправкой.";
$MESS["main_register_sms"] = "Код подтверждения из СМС:";
$MESS["main_register_sms_send"] = "Отправить";
$MESS["UF_REG_IN_PL_INTARO"] = "Зарегистрироваться в программе лояльности";
$MESS["UF_AGREE_PL_INTARO"] = "программы лояльности:";
$MESS["I_AM_AGREE"] = "Я согласен с условиями";
$MESS["UF_PD_PROC_PL_INTARO"] = "обработки персональных данных:";
$MESS["LP_CARD_NUMBER"] = "Номер карты программы лояльности";
$MESS["SEND"] = "Отправить";
$MESS["VERIFICATION_CODE"] = "Код подтверждения";
$MESS["SEND_VERIFICATION_CODE"] = "Отправьте код подтверждения";
$MESS["REG_LP_MESSAGE"] = "Для завершения регистрации в программе лояльности введите номер телефона и номер карты программы лояльности";
$MESS["YES"] = "Да";
$MESS["BONUS_CARD_NUMBER"] = "Номер карты лояльности (если есть):";
$MESS["SUCCESS_PL_REG"] = "Вы успешно зарегистрировались в программе лояльности.";
$MESS["LP_FIELDS_NOT_EXIST"] = "Ошибка установки модуля ПЛ. Отсутствуют UF поля для USER";
$MESS["REG_LP_ERROR"] = "Ошибка регистрации в Программе лояльности";
$MESS["REGISTER_CONTINUE"] = "Для завершения регистрации в программе лояльности заполните форму.";
$MESS["UF_CARD_NUM_INTARO"] = "Номер карты лояльности (если есть)";
$MESS["SEC"] = "сек.";
$MESS["RESEND_SMS"] = "Отправить смс повторно";
$MESS["RESEND_POSSIBLE"] = "Повторная отправка смс возможна через";

View File

@ -0,0 +1,69 @@
<?php
use Bitrix\Main\ArgumentException;
use Bitrix\Main\Loader;
use Bitrix\Main\LoaderException;
use Bitrix\Main\ObjectPropertyException;
use Bitrix\Main\SystemException;
use Intaro\RetailCrm\Component\ConfigProvider;
use Intaro\RetailCrm\Component\Constants;
use Intaro\RetailCrm\Component\ServiceLocator;
use Intaro\RetailCrm\Repository\AgreementRepository;
use Intaro\RetailCrm\Service\CustomerService;
use Intaro\RetailCrm\Service\LoyaltyAccountService;
/** RetailCRM loyalty program start */
function checkLoadIntaro(): bool
{
try {
return Loader::includeModule('intaro.retailcrm');
} catch (LoaderException $e) {
return false;
}
}
if (checkLoadIntaro()) {
$arResult['LOYALTY_STATUS'] = ConfigProvider::getLoyaltyProgramStatus();
global $USER;
if ('Y' === $arResult['LOYALTY_STATUS'] && $USER->IsAuthorized()) {
/** @var CustomerService $customerService */
$customerService = ServiceLocator::get(CustomerService::class);
$customer = $customerService->createModel($USER->GetID());
$customerService->createCustomer($customer);
/* @var LoyaltyAccountService $service */
$service = ServiceLocator::get(LoyaltyAccountService::class);
$arResult['LP_REGISTER'] = $service->checkRegInLp();
}
$arResult['ACTIVATE'] = isset($_GET['activate'])
&& $_GET['activate'] === 'Y'
&& $arResult['LP_REGISTER']['form']['button']['action'] === 'activateAccount';
try {
$agreementPersonalData = AgreementRepository::getFirstByWhere(
['AGREEMENT_TEXT'],
[
['CODE', '=', 'AGREEMENT_PERSONAL_DATA_CODE'],
]
);
$agreementLoyaltyProgram = AgreementRepository::getFirstByWhere(
['AGREEMENT_TEXT'],
[
['CODE', '=', 'AGREEMENT_LOYALTY_PROGRAM_CODE'],
]
);
} catch (ObjectPropertyException | ArgumentException | SystemException $exception) {
Logger::getInstance()->write($exception->getMessage(), Constants::TEMPLATES_ERROR);
}
$arResult['AGREEMENT_PERSONAL_DATA'] = $agreementPersonalData['AGREEMENT_TEXT'];
$arResult['AGREEMENT_LOYALTY_PROGRAM'] = $agreementLoyaltyProgram['AGREEMENT_TEXT'];
} else {
AddMessage2Log(GetMessage('INTARO_NOT_INSTALLED'));
}
/** RetailCRM loyalty program end */

View File

@ -0,0 +1,256 @@
function serializeObject(array) {
const object = {};
$.each(array, function() {
if (object[this.name] !== undefined) {
if (!object[this.name].push) {
object[this.name] = [object[this.name]];
}
object[this.name].push(this.value || '');
} else {
object[this.name] = this.value || '';
}
});
return object;
}
function saveUserLpFields() {
const formArray = $('#lpRegFormInputs').serializeArray();
const formObject = serializeObject(formArray);
BX.ajax.runAction('intaro:retailcrm.api.loyalty.register.saveUserLpFields',
{
data: {
sessid: BX.bitrix_sessid(),
request: formObject
}
}
).then(
function(response) {
if (response.data.result === true) {
location.reload();
} else {
$('#errMsg').text(response.data.msg)
}
}
);
}
function activateAccount() {
let checkboxes = [];
let numbers = [];
let strings = [];
let dates = [];
let options = [];
let form = $('#lpRegFormInputs');
let emailViolation = false;
form.find(':input[type="email"]')
.each(
(index, value) => {
if (/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(value.value) !== true) {
emailViolation = true;
}
}
)
if (emailViolation) {
$('#errMsg').text('Проверьте правильность заполнения email')
return;
}
form.find(':checkbox')
.each(
(index, value) => {
checkboxes[index] = {
'code': value.name,
'value': value.checked,
}
}
)
form.find(':input[type="number"]')
.each(
(index, value) => {
numbers[index] = {
'code': value.name,
'value': value.value,
}
}
)
form.find(':input[type="string"], :input[type="text"], :input[type="email"], textarea')
.each(
(index, value) => {
strings[index] = {
'code': value.name,
'value': value.value,
}
}
)
form.find(':input[type="date"]')
.each(
(index, value) => {
dates[index] = {
'code': value.name,
'value': value.value,
}
}
)
form.find('select')
.each(
(index, value) => {
options[index] = {
'code': value.name,
'value': value.value,
}
}
)
let formObject = {
checkboxes: checkboxes,
numbers: numbers,
strings: strings,
dates: dates,
options: options
}
BX.ajax.runAction('intaro:retailcrm.api.loyalty.register.activateAccount',
{
data: {
sessid: BX.bitrix_sessid(),
allFields: formObject
}
}
).then(
function(response) {
if (response.data.status === 'activate') {
location.reload();
} else {
$('#errMsg').text(response.data.msg)
}
}
);
}
//TODO проверить - возможно, это мертвый метод
function addTelNumber(customerId) {
const phone = $('#loyaltyRegPhone').val();
const card = $('#loyaltyRegCard').val();
BX.ajax.runAction('intaro:retailcrm.api.loyalty.register.accountCreate',
{
data: {
sessid: BX.bitrix_sessid(),
request: {
phone: phone,
card: card,
customerId: customerId
}
}
}
).then(
function(response) {
if (response.data.status === 'error' && response.data.msg !== undefined) {
const msgBlock = $('#msg');
msgBlock.text(response.data.msg);
msgBlock.css('color', response.data.msgColor);
}
if (response.data.status === 'activate') {
const msgBlock = $('#regbody');
msgBlock.text(response.data.msg);
msgBlock.css('color', response.data.msgColor);
}
if (response.data.status === 'smsVerification') {
$('#verificationCodeBlock').show();
}
});
}
function sendVerificationCode() {
const verificationCode = $('#smsVerificationCodeField').val();
const checkId = $('#checkIdField').val();
BX.ajax.runAction('intaro:retailcrm.api.loyalty.register.activateLpBySms',
{
data: {
sessid: BX.bitrix_sessid(),
verificationCode: verificationCode,
checkId: checkId
}
}
).then(
function(response) {
if (response.data.status === 'error' && response.data.msg !== undefined) {
const msg = response.data.msg;
$('#errMsg').text(msg);
}
if (response.data.status === 'activate') {
const msgBlock = $('#regBody');
msgBlock.text(response.data.msg);
msgBlock.css('color', response.data.msgColor);
}
}
)
}
/** Управляет отображением блока с полями программы лояльности на странице регистрации. */
function lpFieldToggle() {
let phone = $('#personalPhone');
if ($('#checkbox_UF_REG_IN_PL_INTARO').is(':checked')) {
$('.lp_toggled_block').css('display', 'table-row');
$('.lp_agree_checkbox').prop('checked', true);
phone.prop('type', 'tel');
phone.attr('name', 'REGISTER[PERSONAL_PHONE]');
} else {
phone.removeAttr('name');
phone.prop('type', 'hidden');
$('.lp_agree_checkbox').prop('checked', false);
$('.lp_toggled_block').css('display', 'none');
}
}
function setCursorPosition(pos, e) {
e.focus();
if (e.setSelectionRange) e.setSelectionRange(pos, pos);
else if (e.createTextRange) {
const range = e.createTextRange();
range.collapse(true);
range.moveEnd("character", pos);
range.moveStart("character", pos);
range.select()
}
}
function mask(e) {
let matrix = this.placeholder,
i = 0,
def = matrix.replace(/\D/g, ""),
val = this.value.replace(/\D/g, "");
def.length >= val.length && (val = def);
matrix = matrix.replace(/[_\d]/g, function(a) {
return val.charAt(i++) || "_"
});
this.value = matrix;
i = matrix.lastIndexOf(val.substr(-1));
i < matrix.length && matrix != this.placeholder ? i++ : i = matrix.indexOf("_");
setCursorPosition(i, this)
}
window.addEventListener("DOMContentLoaded", function() {
const input = document.querySelector("#personalPhone");
if (input === null) {
return
}
input.addEventListener("input", mask, false);
input.focus();
setCursorPosition(3, input);
});

View File

@ -0,0 +1,8 @@
div.bx-auth-reg input.bx-auth-input {vertical-align:middle;}
div.bx-auth-reg span.bx-auth-secure {background-color:#FFFAE3; border:1px solid #DEDBC8; padding:2px; display:inline-block; vertical-align:middle;}
div.bx-auth-reg div.bx-auth-secure-icon {background-image:url(images/sec.png); background-repeat:no-repeat; background-position:center; width:19px; height:18px;}
div.bx-auth-reg div.bx-auth-secure-unlock {background-image:url(images/sec-unlocked.png);}
.lpRegMsg{
font-weight: bold;
}

View File

@ -0,0 +1 @@
div.bx-auth-reg input.bx-auth-input{vertical-align:middle}div.bx-auth-reg span.bx-auth-secure{background-color:#fffae3;border:1px solid #dedbc8;padding:2px;display:inline-block;vertical-align:middle}div.bx-auth-reg div.bx-auth-secure-icon{background-image:url(images/sec.png);background-repeat:no-repeat;background-position:center;width:19px;height:18px}div.bx-auth-reg div.bx-auth-secure-unlock{background-image:url(images/sec-unlocked.png)}.lpRegMsg{font-weight: bold}

View File

@ -0,0 +1,556 @@
<?php
/**
* Bitrix Framework
* @package bitrix
* @subpackage main
* @copyright 2001-2014 Bitrix
*/
/**
* Bitrix vars
* @param array $arParams
* @param array $arResult
* @param CBitrixComponentTemplate $this
* @global CUser $USER
* @global CMain $APPLICATION
*/
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
die();
}
if ($arResult["SHOW_SMS_FIELD"] == true) {
CJSCore::Init('phone_auth');
}
?>
<?php CUtil::InitJSCore(['ajax', 'jquery', 'popup']); ?>
<div id="uf_agree_pl_intaro_popup" style="display:none;">
<?=$arResult['AGREEMENT_LOYALTY_PROGRAM']?>
</div>
<div id="uf_pd_proc_pl_intaro_popup" style="display:none;">
<?=$arResult['AGREEMENT_PERSONAL_DATA']?>
</div>
<script>
BX.ready(function() {
const lpAgreementPopup = new BX.PopupWindow('lp_agreement_popup', window.body, {
autoHide: true,
offsetTop: 1,
offsetLeft: 0,
lightShadow: true,
closeIcon: true,
closeByEsc: true,
overlay: {
backgroundColor: 'grey', opacity: '30'
}
});
lpAgreementPopup.setContent(BX('uf_agree_pl_intaro_popup'));
BX.bindDelegate(
document.body, 'click', {className: 'lp_agreement_link'},
BX.proxy(function(e) {
if (!e)
e = window.event;
lpAgreementPopup.show();
return BX.PreventDefault(e);
}, lpAgreementPopup)
);
const personalDataAgreementPopup = new BX.PopupWindow('personal_data_agreement_popup', window.body, {
autoHide: true,
offsetTop: 1,
offsetLeft: 0,
lightShadow: true,
closeIcon: true,
closeByEsc: true,
overlay: {
backgroundColor: 'grey', opacity: '30'
}
});
personalDataAgreementPopup.setContent(BX('uf_pd_proc_pl_intaro_popup'));
BX.bindDelegate(
document.body, 'click', {className: 'personal_data_agreement_link'},
BX.proxy(function(e) {
if (!e)
e = window.event;
personalDataAgreementPopup.show();
return BX.PreventDefault(e);
}, personalDataAgreementPopup)
);
});
</script>
<div class="bx-auth-reg">
<?php if ($USER->IsAuthorized()): ?>
<p><?php echo GetMessage("MAIN_REGISTER_AUTH") ?></p>
<?php if ($arResult['LOYALTY_STATUS'] === 'Y'): ?>
<?php $this->addExternalJs(SITE_TEMPLATE_PATH . '/script.js'); ?>
<div id="regBody">
<?php if (isset($arResult['LP_REGISTER']['msg'])) { ?>
<div id="lpRegMsg" class="lpRegMsg"><?=$arResult['LP_REGISTER']['msg']?></div>
<?php } ?>
<?php
if (isset($arResult['LP_REGISTER']['form']['fields'])) { ?>
<div id="lpRegForm">
<div id="errMsg"></div>
<form id="lpRegFormInputs">
<?php
foreach ($arResult['LP_REGISTER']['form']['fields'] as $key => $field) {
if ($key === 'PERSONAL_PHONE') { ?>
<label>
<?=GetMessage($key)?>:
<input
id="personalPhone"
autofocus="autofocus"
required="required"
name="PERSONAL_PHONE"
pattern="([\+]*[0-9]{1}\s?[\(]*[0-9]{3}[\)]*\s?\d{3}[-]*\d{2}[-]*\d{2})"
placeholder="+_(___)___-__-__"
value="+_(___)___-__-__"
size="30"
type="tel"
>
</label>
<?php
continue;
} ?>
<label>
<input
name="<?=$key?>"
id="<?=$key?>Field"
type="<?=$field['type']?>"
<?php if (isset($field['value'])) { ?>
value="<?=$field['value']?>"
<?php } ?>
>
<?php
if ($key === 'UF_AGREE_PL_INTARO') { ?>
<?=GetMessage('I_AM_AGREE')?><a class="lp_agreement_link" href="javascript:void(0)">
<?php } ?>
<?php
if ($key === 'UF_PD_PROC_PL_INTARO') { ?>
<?=GetMessage('I_AM_AGREE')?><a class="personal_data_agreement_link" href="javascript:void(0)">
<?php } ?>
<?=GetMessage($key)?>
<?php
if ($key === 'UF_PD_PROC_PL_INTARO' || $key === 'UF_AGREE_PL_INTARO') { ?></a><?php } ?>
</label>
<br>
<?php
if ($field['type'] === 'checkbox') { ?>
<br>
<?php } ?>
<?php } ?>
<?php
if ($arResult['ACTIVATE'] === true) {
foreach ($arResult['LP_REGISTER']['form']['externalFields'] as $externalField) {
?>
<lable>
<?php
if ($externalField['type'] === 'string' || $externalField['type'] === 'date') { ?>
<input
name="<?=$externalField['code']?>"
id="external_<?=$externalField['code']?>"
type="<?=$externalField['type']?>"
>
<?=$externalField['name']?>
<?php } ?>
<?php
if ($externalField['type'] === 'boolean') { ?>
<input
name="<?=$externalField['code']?>"
id="external_<?=$externalField['code']?>"
type="checkbox"
>
<?=$externalField['name']?>
<?php } ?>
<?php
if ($externalField['type'] === 'text') { ?>
<textarea
name="<?=$externalField['code']?>"
id="external_<?=$externalField['code']?>"
cols="30"
rows="10"
></textarea>
<?=$externalField['name']?>
<?php } ?>
<?php
if ($externalField['type'] === 'integer' || $externalField['type'] === 'numeric') { ?>
<input
name="<?=$externalField['code']?>"
id="external_<?=$externalField['code']?>"
type="number"
>
<?=$externalField['name']?>
<?php } ?>
<?php
if ($externalField['type'] === 'email') { ?>
<input
name="<?=$externalField['code']?>"
id="external_<?=$externalField['code']?>"
type="email"
>
<?=$externalField['name']?>
<?php } ?>
<?php
if ($externalField['type'] === 'dictionary') { ?>
<select name="<?=$externalField['code']?>">
<?php
foreach ($externalField['dictionaryElements'] as $dictionaryElement) {
?>
<option value="<?=$dictionaryElement['code']?>"><?=$dictionaryElement['name']?> </option>
<?php
}
?>
</select>
<?=$externalField['name']?>
<?php } ?>
</lable>
<br>
<?php
}
}
?>
</form>
<?php
if (isset($arResult['LP_REGISTER']['resendAvailable']) && !empty($arResult['LP_REGISTER']['resendAvailable'])) {
CUtil::InitJSCore(['intaro_countdown']);
?>
<script>
$(function() {
const deadline = new Date('<?= $arResult['LP_REGISTER']['resendAvailable'] ?>');
initializeClock("countdown", deadline);
});
</script>
<div id="countdownDiv"> <?=GetMessage('RESEND_POSSIBLE')?> <span id="countdown"></span> <?=GetMessage('SEC')?></div>
<div id="deadlineMessage" style="display: none;">
<input type="button" onclick="resendRegisterSms(<?=$arResult['LP_REGISTER']['idInLoyalty']?>)" value="<?=GetMessage('RESEND_SMS')?>">
</div>
<?php } ?>
<input type="button" onclick="<?=$arResult['LP_REGISTER']['form']['button']['action']?>()" value="<?=GetMessage('SEND')?>">
</div>
<?php } ?>
</div>
<?php else: ?>
<?=GetMessage('LP_NOT_ACTIVE')?>
<?php endif; ?>
<?php else: ?>
<?
if (count($arResult["ERRORS"]) > 0):
foreach ($arResult["ERRORS"] as $key => $error) {
if (intval($key) == 0 && $key !== 0) {
$arResult["ERRORS"][$key] = str_replace("#FIELD_NAME#", "&quot;" . GetMessage("REGISTER_FIELD_" . $key) . "&quot;", $error);
}
}
ShowError(implode("<br />", $arResult["ERRORS"]));
elseif ($arResult["USE_EMAIL_CONFIRMATION"] === "Y"):
?>
<p><? echo GetMessage("REGISTER_EMAIL_WILL_BE_SENT") ?></p>
<? endif ?>
<? if ($arResult["SHOW_SMS_FIELD"] == true): ?>
<form method="post" action="<?=POST_FORM_ACTION_URI?>" name="regform">
<?
if ($arResult["BACKURL"] <> ''):
?>
<input type="hidden" name="backurl" value="<?=$arResult["BACKURL"]?>"/>
<?
endif;
?>
<input type="hidden" name="SIGNED_DATA" value="<?=htmlspecialcharsbx($arResult["SIGNED_DATA"])?>"/>
<table>
<tbody>
<tr>
<td><? echo GetMessage("main_register_sms") ?><span class="starrequired">*</span></td>
<td><input size="30" type="text" name="SMS_CODE" value="<?=htmlspecialcharsbx($arResult["SMS_CODE"])?>" autocomplete="off"/></td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td><input type="submit" name="code_submit_button" value="<? echo GetMessage("main_register_sms_send") ?>"/></td>
</tr>
</tfoot>
</table>
</form>
<script>
new BX.PhoneAuth({
containerId: 'bx_register_resend',
errorContainerId: 'bx_register_error',
interval: <?=$arResult["PHONE_CODE_RESEND_INTERVAL"]?>,
data:
<?=CUtil::PhpToJSObject([
'signedData' => $arResult["SIGNED_DATA"],
])?>,
onError:
function(response) {
var errorDiv = BX('bx_register_error');
var errorNode = BX.findChildByClassName(errorDiv, 'errortext');
errorNode.innerHTML = '';
for (var i = 0; i < response.errors.length; i++) {
errorNode.innerHTML = errorNode.innerHTML + BX.util.htmlspecialchars(response.errors[i].message) + '<br>';
}
errorDiv.style.display = '';
}
});
</script>
<div id="bx_register_error" style="display:none"><? ShowError("error") ?></div>
<div id="bx_register_resend"></div>
<? else: ?>
<form method="post" action="<?=POST_FORM_ACTION_URI?>" name="regform" enctype="multipart/form-data">
<?
if ($arResult["BACKURL"] <> ''):
?>
<input type="hidden" name="backurl" value="<?=$arResult["BACKURL"]?>"/>
<?
endif;
?>
<table>
<thead>
<tr>
<td colspan="2"><b><?=GetMessage("AUTH_REGISTER")?></b></td>
</tr>
</thead>
<tbody>
<? foreach ($arResult["SHOW_FIELDS"] as $FIELD): ?>
<? if ($FIELD == "AUTO_TIME_ZONE" && $arResult["TIME_ZONE_ENABLED"] == true): ?>
<tr>
<td><? echo GetMessage("main_profile_time_zones_auto") ?><? if ($arResult["REQUIRED_FIELDS_FLAGS"][$FIELD] == "Y"): ?><span class="starrequired">*</span><? endif ?></td>
<td>
<select name="REGISTER[AUTO_TIME_ZONE]" onchange="this.form.elements['REGISTER[TIME_ZONE]'].disabled=(this.value != 'N')">
<option value=""><? echo GetMessage("main_profile_time_zones_auto_def") ?></option>
<option value="Y"<?=$arResult["VALUES"][$FIELD] == "Y" ? " selected=\"selected\"" : ""?>><? echo GetMessage("main_profile_time_zones_auto_yes") ?></option>
<option value="N"<?=$arResult["VALUES"][$FIELD] == "N" ? " selected=\"selected\"" : ""?>><? echo GetMessage("main_profile_time_zones_auto_no") ?></option>
</select>
</td>
</tr>
<tr>
<td><? echo GetMessage("main_profile_time_zones_zones") ?></td>
<td>
<select name="REGISTER[TIME_ZONE]"<? if (!isset($_REQUEST["REGISTER"]["TIME_ZONE"])) echo 'disabled="disabled"' ?>>
<? foreach ($arResult["TIME_ZONE_LIST"] as $tz => $tz_name): ?>
<option value="<?=htmlspecialcharsbx($tz)?>"<?=$arResult["VALUES"]["TIME_ZONE"]
== $tz ? " selected=\"selected\"" : ""?>><?=htmlspecialcharsbx($tz_name)?></option>
<? endforeach ?>
</select>
</td>
</tr>
<? else: ?>
<tr>
<td><?=GetMessage("REGISTER_FIELD_" . $FIELD)?>:<? if ($arResult["REQUIRED_FIELDS_FLAGS"][$FIELD] == "Y"): ?><span class="starrequired">*</span><? endif ?></td>
<td><?
switch ($FIELD) {
case "PASSWORD":
?><input size="30" type="password" name="REGISTER[<?=$FIELD?>]" value="<?=$arResult["VALUES"][$FIELD]?>" autocomplete="off" class="bx-auth-input"/>
<? if ($arResult["SECURE_AUTH"]): ?>
<span class="bx-auth-secure" id="bx_auth_secure" title="<? echo GetMessage("AUTH_SECURE_NOTE") ?>" style="display:none">
<div class="bx-auth-secure-icon"></div>
</span>
<noscript>
<span class="bx-auth-secure" title="<? echo GetMessage("AUTH_NONSECURE_NOTE") ?>">
<div class="bx-auth-secure-icon bx-auth-secure-unlock"></div>
</span>
</noscript>
<script type="text/javascript">
document.getElementById('bx_auth_secure').style.display = 'inline-block';
</script>
<? endif ?>
<?
break;
case "CONFIRM_PASSWORD":
?><input size="30" type="password" name="REGISTER[<?=$FIELD?>]" value="<?=$arResult["VALUES"][$FIELD]?>" autocomplete="off" /><?
break;
case "PERSONAL_GENDER":
?><select name="REGISTER[<?=$FIELD?>]">
<option value=""><?=GetMessage("USER_DONT_KNOW")?></option>
<option value="M"<?=$arResult["VALUES"][$FIELD] == "M" ? " selected=\"selected\"" : ""?>><?=GetMessage("USER_MALE")?></option>
<option value="F"<?=$arResult["VALUES"][$FIELD] == "F" ? " selected=\"selected\"" : ""?>><?=GetMessage("USER_FEMALE")?></option>
</select><?
break;
case "PERSONAL_COUNTRY":
case "WORK_COUNTRY":
?><select name="REGISTER[<?=$FIELD?>]"><?
foreach ($arResult["COUNTRIES"]["reference_id"] as $key => $value) {
?>
<option value="<?=$value?>"<? if ($value
== $arResult["VALUES"][$FIELD]): ?> selected="selected"<? endif ?>><?=$arResult["COUNTRIES"]["reference"][$key]?></option>
<?
}
?></select><?
break;
case "PERSONAL_PHOTO":
case "WORK_LOGO":
?><input size="30" type="file" name="REGISTER_FILES_<?=$FIELD?>" /><?
break;
case "PERSONAL_NOTES":
case "WORK_NOTES":
?><textarea cols="30" rows="5" name="REGISTER[<?=$FIELD?>]"><?=$arResult["VALUES"][$FIELD]?></textarea><?
break;
default:
if ($FIELD == "PERSONAL_BIRTHDAY"):?><small><?=$arResult["DATE_FORMAT"]?></small><br/><?endif;
?><input size="30" type="text" name="REGISTER[<?=$FIELD?>]" value="<?=$arResult["VALUES"][$FIELD]?>" /><?
if ($FIELD == "PERSONAL_BIRTHDAY") {
$APPLICATION->IncludeComponent(
'bitrix:main.calendar',
'',
[
'SHOW_INPUT' => 'N',
'FORM_NAME' => 'regform',
'INPUT_NAME' => 'REGISTER[PERSONAL_BIRTHDAY]',
'SHOW_TIME' => 'N',
],
null,
["HIDE_ICONS" => "Y"]
);
}
?><?
} ?></td>
</tr>
<? endif ?>
<? endforeach ?>
<? // ********************* User properties ***************************************************?>
<? if ($arResult["USER_PROPERTIES"]["SHOW"] == "Y"): ?>
<tr>
<td colspan="2"><?=strlen(trim($arParams["USER_PROPERTY_NAME"])) > 0 ? $arParams["USER_PROPERTY_NAME"] : GetMessage("USER_TYPE_EDIT_TAB")?></td>
</tr>
<? foreach ($arResult["USER_PROPERTIES"]["DATA"] as $FIELD_NAME => $arUserField): ?>
<tr>
<td><?=$arUserField["EDIT_FORM_LABEL"]?>:<? if ($arUserField["MANDATORY"] == "Y"): ?><span class="starrequired">*</span><? endif; ?></td>
<td>
<? $APPLICATION->IncludeComponent(
"bitrix:system.field.edit",
$arUserField["USER_TYPE"]["USER_TYPE_ID"],
["bVarsFromForm" => $arResult["bVarsFromForm"], "arUserField" => $arUserField, "form_name" => "regform"], null, ["HIDE_ICONS" => "Y"]); ?></td>
</tr>
<? endforeach; ?>
<? endif; ?>
<?php if ($arResult['LOYALTY_STATUS'] === 'Y'): ?>
<tr>
<td></td>
<td>
<div class="fields boolean" id="main_UF_REG_IN_PL_INTARO">
<div class="fields boolean">
<input type="hidden" value="0" name="UF_REG_IN_PL_INTARO">
<label>
<input type="checkbox" value="1" name="UF_REG_IN_PL_INTARO" onchange="lpFieldToggle()" id="checkbox_UF_REG_IN_PL_INTARO"> <?=GetMessage("UF_REG_IN_PL_INTARO")?>
</label>
</div>
</div>
</td>
</tr>
<tr class="lp_toggled_block" style="display: none">
<td><?=GetMessage("BONUS_CARD_NUMBER")?></td>
<td><input size="30" type="text" name="UF_CARD_NUM_INTARO" value=""></td>
</tr>
<tr class="lp_toggled_block" style="display: none">
<td>
<?=GetMessage("REGISTER_FIELD_PERSONAL_PHONE")?>
</td>
<td>
<input
id="personalPhone"
autofocus="autofocus"
required="required"
pattern="([\+]*[0-9]{1}\s?[\(]*[0-9]{3}[\)]*\s?\d{3}[-]*\d{2}[-]*\d{2})"
placeholder="+_(___)___-__-__"
value="+_(___)___-__-__"
size="30"
type="hidden"
>
</td>
</tr>
<tr class="lp_toggled_block" style="display: none">
<td>
<div class="fields boolean" id="main_UF_AGREE_PL_INTARO">
<div class="fields boolean">
<input type="hidden" value="0" name="UF_AGREE_PL_INTARO">
<label>
<input class="lp_agree_checkbox" type="checkbox" value="1" name="UF_AGREE_PL_INTARO"> <?=GetMessage("YES")?>
</label>
</div>
</div>
</td>
<td>
<?=GetMessage("I_AM_AGREE")?> <a class="lp_agreement_link" href="javascript:void(0)"><?=GetMessage("UF_AGREE_PL_INTARO")?></a>
</td>
</tr>
<tr class="lp_toggled_block" style="display: none">
<td>
<div class="fields boolean" id="main_UF_PD_PROC_PL_INTARO">
<div class="fields boolean"><input type="hidden" value="0" name="UF_PD_PROC_PL_INTARO">
<label>
<input class="lp_agree_checkbox" type="checkbox" value="1" name="UF_PD_PROC_PL_INTARO"> <?=GetMessage("YES")?>
</label>
</div>
</div>
</td>
<td>
<?=GetMessage("I_AM_AGREE")?> <a class="personal_data_agreement_link" href="javascript:void(0)"><?=GetMessage("UF_PD_PROC_PL_INTARO")?></a>
</td>
</tr>
<?php endif; ?>
<? // ******************** /User properties ***************************************************?>
<?
/* CAPTCHA */
if ($arResult["USE_CAPTCHA"] == "Y") {
?>
<tr>
<td colspan="2"><b><?=GetMessage("REGISTER_CAPTCHA_TITLE")?></b></td>
</tr>
<tr>
<td></td>
<td>
<input type="hidden" name="captcha_sid" value="<?=$arResult["CAPTCHA_CODE"]?>"/>
<img src="/bitrix/tools/captcha.php?captcha_sid=<?=$arResult["CAPTCHA_CODE"]?>" width="180" height="40" alt="CAPTCHA"/>
</td>
</tr>
<tr>
<td><?=GetMessage("REGISTER_CAPTCHA_PROMT")?>:<span class="starrequired">*</span></td>
<td><input type="text" name="captcha_word" maxlength="50" value="" autocomplete="off"/></td>
</tr>
<?
}
/* !CAPTCHA */
?>
</tbody>
<tfoot>
<tr>
<td></td>
<td><input type="submit" name="register_submit_button" value="<?=GetMessage("AUTH_REGISTER")?>"/></td>
</tr>
</tfoot>
</table>
</form>
<p><? echo $arResult["GROUP_POLICY"]["PASSWORD_REQUIREMENTS"]; ?></p>
<? endif //$arResult["SHOW_SMS_FIELD"] == true ?>
<p><span class="starrequired">*</span><?=GetMessage("AUTH_REQ")?></p>
<? endif ?>
</div>

View File

@ -0,0 +1,16 @@
<?
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
$arComponentDescription = array(
"NAME" => GetMessage("SBB_DEFAULT_TEMPLATE_NAME"),
"DESCRIPTION" => GetMessage("SBB_DEFAULT_TEMPLATE_DESCRIPTION"),
"ICON" => "/images/sale_basket.gif",
"PATH" => array(
"ID" => "e-store",
"CHILD" => array(
"ID" => "sale_basket",
"NAME" => GetMessage("SBB_NAME")
)
),
);
?>

View File

@ -0,0 +1,455 @@
<?
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
/** @global array $arCurrentValues */
/** @var array $templateProperties */
use Bitrix\Main\Loader,
Bitrix\Catalog,
Bitrix\Iblock;
if (!Loader::includeModule('sale'))
return;
$arColumns = array(
"PREVIEW_PICTURE" => GetMessage("SBB_PREVIEW_PICTURE"),
"DETAIL_PICTURE" => GetMessage("SBB_DETAIL_PICTURE"),
"PREVIEW_TEXT" => GetMessage("SBB_PREVIEW_TEXT"),
"DISCOUNT" => GetMessage("SBB_BDISCOUNT"),
"WEIGHT" => GetMessage("SBB_BWEIGHT"),
"PROPS" => GetMessage("SBB_BPROPS"),
"DELETE" => GetMessage("SBB_BDELETE"),
"DELAY" => GetMessage("SBB_BDELAY"),
"TYPE" => GetMessage("SBB_BTYPE"),
"SUM" => GetMessage("SBB_BSUM")
);
$iblockIds = array();
$iblockNames = array();
if (Loader::includeModule('catalog'))
{
$parameters = array(
'select' => array('IBLOCK_ID', 'NAME' => 'IBLOCK.NAME'),
'order' => array('IBLOCK_ID' => 'ASC'),
);
$siteId = isset($_REQUEST['src_site']) && is_string($_REQUEST['src_site']) ? $_REQUEST['src_site'] : '';
$siteId = substr(preg_replace('/[^a-z0-9_]/i', '', $siteId), 0, 2);
if (!empty($siteId) && is_string($siteId))
{
$parameters['select']['SITE_ID'] = 'IBLOCK_SITE.SITE_ID';
$parameters['filter'] = array('SITE_ID' => $siteId);
$parameters['runtime'] = array(
'IBLOCK_SITE' => array(
'data_type' => 'Bitrix\Iblock\IblockSiteTable',
'reference' => array(
'ref.IBLOCK_ID' => 'this.IBLOCK_ID',
),
'join_type' => 'inner'
)
);
}
$catalogIterator = Catalog\CatalogIblockTable::getList($parameters);
while ($catalog = $catalogIterator->fetch())
{
$catalog['IBLOCK_ID'] = (int) $catalog['IBLOCK_ID'];
$iblockIds[] = $catalog['IBLOCK_ID'];
$iblockNames[$catalog['IBLOCK_ID']] = $catalog['NAME'];
}
unset($catalog, $catalogIterator);
$listProperties = array();
if (!empty($iblockIds))
{
$arProps = array();
$propertyIterator = Iblock\PropertyTable::getList(array(
'select' => array('ID', 'CODE', 'NAME', 'IBLOCK_ID', 'PROPERTY_TYPE'),
'filter' => array('@IBLOCK_ID' => $iblockIds, '=ACTIVE' => 'Y', '!=XML_ID' => CIBlockPropertyTools::XML_SKU_LINK),
'order' => array('IBLOCK_ID' => 'ASC', 'SORT' => 'ASC', 'ID' => 'ASC')
));
while ($property = $propertyIterator->fetch())
{
$property['ID'] = (int) $property['ID'];
$property['IBLOCK_ID'] = (int) $property['IBLOCK_ID'];
$property['CODE'] = (string) $property['CODE'];
if ($property['CODE'] == '')
{
$property['CODE'] = $property['ID'];
}
if ($property['PROPERTY_TYPE'] === 'L')
{
$listProperties[$property['CODE']] = $property['NAME'].' ['.$property['CODE'].']';
}
if (!isset($arProps[$property['CODE']]))
{
$arProps[$property['CODE']] = array(
'CODE' => $property['CODE'],
'TITLE' => $property['NAME'].' ['.$property['CODE'].']',
'ID' => array($property['ID']),
'IBLOCK_ID' => array($property['IBLOCK_ID'] => $property['IBLOCK_ID']),
'IBLOCK_TITLE' => array($property['IBLOCK_ID'] => $iblockNames[$property['IBLOCK_ID']]),
'COUNT' => 1
);
}
else
{
$arProps[$property['CODE']]['ID'][] = $property['ID'];
$arProps[$property['CODE']]['IBLOCK_ID'][$property['IBLOCK_ID']] = $property['IBLOCK_ID'];
if ($arProps[$property['CODE']]['COUNT'] < 2)
$arProps[$property['CODE']]['IBLOCK_TITLE'][$property['IBLOCK_ID']] = $iblockNames[$property['IBLOCK_ID']];
$arProps[$property['CODE']]['COUNT']++;
}
}
unset($property, $propertyIterator);
$propList = array();
foreach ($arProps as &$property)
{
$iblockList = '';
if ($property['COUNT'] > 1)
{
$iblockList = ($property['COUNT'] > 2 ? ' ( ... )' : ' ('.implode(', ', $property['IBLOCK_TITLE']).')');
}
$propList['PROPERTY_'.$property['CODE']] = $property['TITLE'].$iblockList;
}
unset($property, $arProps);
if (!empty($propList))
$arColumns = array_merge($arColumns, $propList);
unset($propList);
}
}
$arYesNo = array(
"Y" => GetMessage("SBB_DESC_YES"),
"N" => GetMessage("SBB_DESC_NO"),
);
$arComponentParameters = Array(
"GROUPS" => array(
"OFFERS_PROPS" => array(
"NAME" => GetMessage("SBB_OFFERS_PROPS"),
),
"IMAGE_SETTINGS" => array(
"NAME" => GetMessage("SBB_IMAGE_SETTINGS")
),
"GIFTS" => array(
"NAME" => GetMessage("SBB_GIFTS"),
),
'ANALYTICS_SETTINGS' => array(
'NAME' => GetMessage('SBB_ANALYTICS_SETTINGS'),
'SORT' => 11000
)
),
"PARAMETERS" => Array(
"PATH_TO_ORDER" => Array(
"NAME" => GetMessage("SBB_PATH_TO_ORDER"),
"TYPE" => "STRING",
"MULTIPLE" => "N",
"DEFAULT" => "/personal/order/make/",
"COLS" => 25,
"PARENT" => "ADDITIONAL_SETTINGS",
),
"HIDE_COUPON" => Array(
"NAME" => GetMessage("SBB_HIDE_COUPON"),
"TYPE" => "CHECKBOX",
"VALUES" => array(
"N" => GetMessage("SBB_DESC_NO"),
"Y" => GetMessage("SBB_DESC_YES")
),
"DEFAULT" => "N",
"PARENT" => "ADDITIONAL_SETTINGS",
),
"COLUMNS_LIST_EXT" => Array(
"NAME" => GetMessage("SBB_COLUMNS_LIST"),
"TYPE" => "LIST",
"MULTIPLE" => "Y",
"VALUES" => $arColumns,
"DEFAULT" => array('PREVIEW_PICTURE', 'DISCOUNT', 'DELETE', 'DELAY', 'TYPE', 'SUM'),
"COLS" => 25,
"SIZE" => 7,
"ADDITIONAL_VALUES" => "N",
"PARENT" => "VISUAL",
'REFRESH' => isset($templateProperties['COLUMNS_LIST_MOBILE']) ? 'Y' : 'N',
),
"COLUMNS_LIST_MOBILE" => array(),
"PRICE_VAT_SHOW_VALUE" => array(
"NAME" => GetMessage('SBB_VAT_SHOW_VALUE'),
"TYPE" => "CHECKBOX",
"MULTIPLE" => "N",
"DEFAULT" => "N",
"ADDITIONAL_VALUES" => "N",
"PARENT" => "ADDITIONAL_SETTINGS",
),
"USE_PREPAYMENT" => array(
"NAME" => GetMessage('SBB_USE_PREPAYMENT'),
"TYPE" => "CHECKBOX",
"MULTIPLE" => "N",
"DEFAULT" => "N",
"ADDITIONAL_VALUES" => "N",
"PARENT" => "ADDITIONAL_SETTINGS",
),
"QUANTITY_FLOAT" => array(
"NAME" => GetMessage('SBB_QUANTITY_FLOAT'),
"TYPE" => "CHECKBOX",
"MULTIPLE" => "N",
"DEFAULT" => "Y",
"ADDITIONAL_VALUES" => "N",
"PARENT" => "ADDITIONAL_SETTINGS",
),
"CORRECT_RATIO" => array(
"NAME" => GetMessage('SBB_CORRECT_RATIO'),
"TYPE" => "CHECKBOX",
"MULTIPLE" => "N",
"DEFAULT" => "Y",
"ADDITIONAL_VALUES" => "N",
"PARENT" => "ADDITIONAL_SETTINGS",
),
"AUTO_CALCULATION" => array(
"NAME" => GetMessage('SBB_AUTO_CALCULATION'),
"TYPE" => "CHECKBOX",
"MULTIPLE" => "N",
"DEFAULT" => "Y",
"ADDITIONAL_VALUES" => "N",
"PARENT" => "ADDITIONAL_SETTINGS",
),
"SET_TITLE" => Array(),
"ACTION_VARIABLE" => array(
"NAME" => GetMessage('SBB_ACTION_VARIABLE'),
"TYPE" => "STRING",
"MULTIPLE" => "N",
"DEFAULT" => "basketAction",
"ADDITIONAL_VALUES" => "N",
"PARENT" => "ADDITIONAL_SETTINGS",
),
'COMPATIBLE_MODE' => array(
'PARENT' => 'EXTENDED_SETTINGS',
'NAME' => GetMessage('SBB_COMPATIBLE_MODE'),
'TYPE' => 'CHECKBOX',
'DEFAULT' => 'Y'
),
"USE_GIFTS" => array(
"PARENT" => "GIFTS",
"NAME" => GetMessage("SBB_GIFTS_USE_GIFTS"),
"TYPE" => "CHECKBOX",
"DEFAULT" => "Y",
"REFRESH" => "Y",
),
),
);
foreach ($iblockIds as $iblockId)
{
$fileProperties = array('-' => GetMessage('SBB_DEFAULT'));
$propertyIterator = CIBlockProperty::getList(
array('SORT' => 'ASC', 'NAME' => 'ASC'),
array('IBLOCK_ID' => $iblockId, 'ACTIVE' => 'Y')
);
while ($property = $propertyIterator->fetch())
{
if ($property['PROPERTY_TYPE'] == 'F')
{
$property['ID'] = (int) $property['ID'];
$propertyName = '['.$property['ID'].']'.($property['CODE'] != '' ? '['.$property['CODE'].']' : '').' '.$property['NAME'];
if ($property['CODE'] == '')
{
$property['CODE'] = $property['ID'];
}
$fileProperties[$property['CODE']] = $propertyName;
}
}
$arComponentParameters['PARAMETERS']['ADDITIONAL_PICT_PROP_'.$iblockId] = array(
'NAME' => GetMessage('SBB_ADDITIONAL_IMAGE').' ['.$iblockNames[$iblockId].']',
'TYPE' => 'LIST',
'MULTIPLE' => 'N',
'VALUES' => $fileProperties,
'ADDITIONAL_VALUES' => 'N',
'PARENT' => 'IMAGE_SETTINGS'
);
}
$arComponentParameters['PARAMETERS']['BASKET_IMAGES_SCALING'] = array(
'NAME' => GetMessage('SBB_BASKET_IMAGES_SCALING'),
'TYPE' => 'LIST',
'VALUES' => array(
'standard' => GetMessage('SBB_STANDARD'),
'adaptive' => GetMessage('SBB_ADAPTIVE'),
'no_scale' => GetMessage('SBB_NO_SCALE')
),
'DEFAULT' => 'adaptive',
'PARENT' => 'IMAGE_SETTINGS'
);
// hack for correct sort
if (isset($templateProperties['COLUMNS_LIST_MOBILE']))
{
$visibleColumns = isset($arCurrentValues['COLUMNS_LIST_EXT'])
? $arCurrentValues['COLUMNS_LIST_EXT']
: $arComponentParameters['PARAMETERS']['COLUMNS_LIST_EXT']['DEFAULT'];
if (!empty($visibleColumns))
{
$templateProperties['COLUMNS_LIST_MOBILE']['VALUES'] = array();
foreach ($visibleColumns as $column)
{
$templateProperties['COLUMNS_LIST_MOBILE']['VALUES'][$column] = $arComponentParameters['PARAMETERS']['COLUMNS_LIST_EXT']['VALUES'][$column];
}
if (!isset($arCurrentValues["COLUMNS_LIST_MOBILE"]))
{
$templateProperties['COLUMNS_LIST_MOBILE']['DEFAULT'] = array_keys($templateProperties['COLUMNS_LIST_MOBILE']['VALUES']);
}
$arComponentParameters['PARAMETERS']['COLUMNS_LIST_MOBILE'] = $templateProperties['COLUMNS_LIST_MOBILE'];
}
else
{
unset($arComponentParameters['PARAMETERS']['COLUMNS_LIST_MOBILE']);
}
unset($templateProperties['COLUMNS_LIST_MOBILE']);
}
else
{
unset($arComponentParameters['PARAMETERS']['COLUMNS_LIST_MOBILE']);
}
if (isset($templateProperties['LABEL_PROP']))
{
$templateProperties['LABEL_PROP']['VALUES'] = $listProperties;
if (!empty($arCurrentValues['LABEL_PROP']))
{
$selected = array();
foreach ($arCurrentValues['LABEL_PROP'] as $name)
{
if (isset($listProperties[$name]))
{
$selected[$name] = $listProperties[$name];
}
}
$templateProperties['LABEL_PROP_MOBILE']['VALUES'] = $selected;
}
else
{
if (!empty($templateProperties['LABEL_PROP_MOBILE']))
{
$templateProperties['LABEL_PROP_MOBILE']['HIDDEN'] = 'Y';
}
if (!empty($templateProperties['LABEL_PROP_POSITION']))
{
$templateProperties['LABEL_PROP_POSITION']['HIDDEN'] = 'Y';
}
}
}
if(!Loader::includeModule('catalog'))
{
unset($arComponentParameters["PARAMETERS"]["USE_GIFTS"]);
unset($arComponentParameters["GROUPS"]["GIFTS"]);
}
elseif($arCurrentValues["USE_GIFTS"] === null && $arComponentParameters['PARAMETERS']['USE_GIFTS']['DEFAULT'] == 'Y' || $arCurrentValues["USE_GIFTS"] == "Y")
{
$arComponentParameters['PARAMETERS'] = array_merge(
$arComponentParameters['PARAMETERS'],
array(
"GIFTS_PLACE" => array(
"PARENT" => "GIFTS",
"NAME" => GetMessage("SGB_PARAMS_PLACE_GIFT"),
"TYPE" => "LIST",
"DEFAULT" => "BOTTOM",
"VALUES" => array(
"TOP" => GetMessage('SGB_PARAMS_PLACE_GIFT_TOP'),
"BOTTOM" => GetMessage('SGB_PARAMS_PLACE_GIFT_BOTTOM'),
),
),
"GIFTS_BLOCK_TITLE" => array(
"PARENT" => "GIFTS",
"NAME" => GetMessage("SGB_PARAMS_BLOCK_TITLE"),
"TYPE" => "STRING",
"DEFAULT" => GetMessage("SGB_PARAMS_BLOCK_TITLE_DEFAULT"),
),
"GIFTS_HIDE_BLOCK_TITLE" => array(
"PARENT" => "GIFTS",
"NAME" => GetMessage("SGB_PARAMS_HIDE_BLOCK_TITLE"),
"TYPE" => "CHECKBOX",
"DEFAULT" => "",
),
"GIFTS_TEXT_LABEL_GIFT" => array(
"PARENT" => "GIFTS",
"NAME" => GetMessage("SGB_PARAMS_TEXT_LABEL_GIFT"),
"TYPE" => "STRING",
"DEFAULT" => GetMessage("SGB_PARAMS_TEXT_LABEL_GIFT_DEFAULT"),
),
"GIFTS_PRODUCT_QUANTITY_VARIABLE" => array(
"PARENT" => "GIFTS",
"NAME" => GetMessage("CVP_PRODUCT_QUANTITY_VARIABLE"),
"TYPE" => "STRING",
"DEFAULT" => "quantity",
"HIDDEN" => (isset($arCurrentValues['USE_PRODUCT_QUANTITY']) && $arCurrentValues['USE_PRODUCT_QUANTITY'] == 'Y' ? 'N' : 'Y')
),
"GIFTS_PRODUCT_PROPS_VARIABLE" => array(
"PARENT" => "GIFTS",
"NAME" => GetMessage("CVP_PRODUCT_PROPS_VARIABLE"),
"TYPE" => "STRING",
"DEFAULT" => "prop",
"HIDDEN" => (isset($arCurrentValues['ADD_PROPERTIES_TO_BASKET']) && $arCurrentValues['ADD_PROPERTIES_TO_BASKET'] == 'N' ? 'Y' : 'N')
),
"GIFTS_SHOW_OLD_PRICE" => array(
"PARENT" => "GIFTS",
"NAME" => GetMessage("CVP_SHOW_OLD_PRICE"),
"TYPE" => "CHECKBOX",
"VALUES" => "Y",
),
'GIFTS_SHOW_DISCOUNT_PERCENT' => array(
'PARENT' => 'GIFTS',
'NAME' => GetMessage('CVP_SHOW_DISCOUNT_PERCENT'),
'TYPE' => 'CHECKBOX',
'DEFAULT' => 'Y'
),
'GIFTS_MESS_BTN_BUY' => array(
'PARENT' => 'GIFTS',
'NAME' => GetMessage('CVP_MESS_BTN_BUY_GIFT'),
'TYPE' => 'STRING',
'DEFAULT' => GetMessage('CVP_MESS_BTN_BUY_GIFT_DEFAULT')
),
'GIFTS_MESS_BTN_DETAIL' => array(
'PARENT' => 'GIFTS',
'NAME' => GetMessage('CVP_MESS_BTN_DETAIL'),
'TYPE' => 'STRING',
'DEFAULT' => GetMessage('CVP_MESS_BTN_DETAIL_DEFAULT')
),
"GIFTS_PAGE_ELEMENT_COUNT" => array(
"PARENT" => "GIFTS",
"NAME" => GetMessage("SGB_PAGE_ELEMENT_COUNT"),
"TYPE" => "STRING",
"DEFAULT" => "4",
),
'GIFTS_CONVERT_CURRENCY' => array(
'PARENT' => 'GIFTS',
'NAME' => GetMessage('CVP_CONVERT_CURRENCY'),
'TYPE' => 'CHECKBOX',
'DEFAULT' => 'N',
'REFRESH' => 'Y',
),
'GIFTS_HIDE_NOT_AVAILABLE' => array(
'PARENT' => 'GIFTS',
'NAME' => GetMessage('CVP_HIDE_NOT_AVAILABLE'),
'TYPE' => 'CHECKBOX',
'DEFAULT' => 'N',
),
)
);
}

View File

@ -0,0 +1,60 @@
<?php
define('STOP_STATISTICS', true);
define('NO_AGENT_CHECK', true);
define('NOT_CHECK_PERMISSIONS', true);
use Bitrix\Main\Loader;
use Bitrix\Main\Security\Sign\BadSignatureException;
use Bitrix\Main\Security\Sign\Signer;
if (isset($_REQUEST['site_id']) && is_string($_REQUEST['site_id']))
{
$siteID = trim($_REQUEST['site_id']);
if ($siteID !== '' && preg_match('/^[a-z0-9_]{2}$/i', $siteID) === 1)
{
define('SITE_ID', $siteID);
}
}
if (isset($_REQUEST['site_template_id']) && is_string($_REQUEST['site_template_id']))
{
$siteTemplateId = trim($_REQUEST['site_template_id']);
if ($siteTemplateId !== '')
{
define('SITE_TEMPLATE_ID', $siteTemplateId);
}
}
require_once($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/main/include/prolog_before.php');
$request = Bitrix\Main\Application::getInstance()->getContext()->getRequest();
$request->addFilter(new \Bitrix\Main\Web\PostDecodeFilter);
if (!check_bitrix_sessid() || !$request->isPost())
return;
if (!Loader::includeModule('sale') || !Loader::includeModule('catalog'))
return;
$params = array();
if ($request->get('via_ajax') === 'Y')
{
$signer = new Signer;
try
{
$params = $signer->unsign($request->get('signedParamsString'), 'sale.basket.basket');
$params = unserialize(base64_decode($params));
}
catch (BadSignatureException $e)
{
die('Bad signature.');
}
}
$APPLICATION->IncludeComponent(
'intaro:sale.basket.basket',
'.default',
$params
);

View File

@ -0,0 +1,227 @@
<pre>
Array
(
[INFO] => Array // массив с дополнительной справочной информацией (список статусов, платежных систем, служб доставок.)
(
[STATUS] => Array // массив со всеми статусами
(
[N] => Array // ключ массива - идентификатор статуса
(
[ID] => N // идентификатор статуса
[SORT] => 100 // индекс сортировки
[GROUP_ID] => 30 // группа пользователей, имеющая права на работу с этим статусом
[PERM_VIEW] => Y // права на просмотр заказов в данном статусе
[PERM_CANCEL] => N // права на отмену заказов в данном статусе
[PERM_DELIVERY] => N // права на разрешение доставки заказов в данном статусе
[PERM_PAYMENT] => N // права на оплату заказов в данном статусе
[PERM_STATUS] => N // права на перевод в этот статусе заказов
[PERM_UPDATE] => N // права на изменение заказов в данном статусе
[PERM_DELETE] => N // права на удаление заказов в данном статусе
[LID] => ru // язык статуса
[NAME] => Принят // название статуса
[DESCRIPTION] => // описание статуса
)
)
[PAY_SYSTEM] => Array // массив со всеми платежными системами текущего сайта
(
[1] => Array
(
[ID] => 1
[LID] => ru
[CURRENCY] => RUR
[NAME] => Наличные
[ACTIVE] => Y
[SORT] => 100
[DESCRIPTION] =>
)
)
[DELIVERY] => Array // массив со всеми службами доставки текущего сайта
(
[1] => Array
(
[ID] => 1
[NAME] => Курьерская
[LID] => ru
[PERIOD_FROM] => 0
[PERIOD_TO] => 3
[PERIOD_TYPE] => D
[WEIGHT_FROM] => 0
[WEIGHT_TO] => 5000
[ORDER_PRICE_FROM] => 0.00
[ORDER_PRICE_TO] => 1000.00
[ORDER_CURRENCY] => USD
[ACTIVE] => Y
[PRICE] => 60.00
[CURRENCY] => EUR
[SORT] => 100
[DESCRIPTION] =>
)
)
)
[ORDERS] => Array
(
[0] => Array
(
[ORDER] => Array
(
[ID] => 33
[LID] => ru
[PERSON_TYPE_ID] => 1
[PAYED] => N
[DATE_PAYED] =>
[EMP_PAYED_ID] =>
[CANCELED] => N
[DATE_CANCELED] =>
[EMP_CANCELED_ID] =>
[REASON_CANCELED] =>
[STATUS_ID] => F
[DATE_STATUS] => 11.01.2007 16:44:57
[PAY_VOUCHER_NUM] =>
[PAY_VOUCHER_DATE] =>
[EMP_STATUS_ID] => 10
[PRICE_DELIVERY] => 0.00
[ALLOW_DELIVERY] => Y
[DATE_ALLOW_DELIVERY] => 11.01.2007 16:44:57
[EMP_ALLOW_DELIVERY_ID] => 10
[PRICE] => 12450.00
[CURRENCY] => RUR
[DISCOUNT_VALUE] => 0.00
[SUM_PAID] => 0.00
[USER_ID] => 10
[PAY_SYSTEM_ID] => 1
[DELIVERY_ID] =>
[DATE_INSERT] => 11.01.2007 16:06:08
[DATE_INSERT_FORMAT] => 11.01.2007 16:06:08
[DATE_UPDATE] => 12.01.2007 13:01:20
[USER_DESCRIPTION] =>
[ADDITIONAL_INFO] =>
[PS_STATUS] =>
[PS_STATUS_CODE] =>
[PS_STATUS_DESCRIPTION] =>
[PS_STATUS_MESSAGE] =>
[PS_SUM] =>
[PS_CURRENCY] =>
[PS_RESPONSE_DATE] =>
[COMMENTS] =>
[TAX_VALUE] => 0.00
[STAT_GID] =>
[RECURRING_ID] =>
[RECOUNT_FLAG] => Y
[USER_LOGIN] => anton
[USER_NAME] => Anton
[USER_LAST_NAME] => Ezhkov
[USER_EMAIL] => anton@bitrixsoft.ru
[~ID] => 33
[~LID] => ru
[~PERSON_TYPE_ID] => 1
[~PAYED] => N
[~DATE_PAYED] =>
[~EMP_PAYED_ID] =>
[~CANCELED] => N
[~DATE_CANCELED] =>
[~EMP_CANCELED_ID] =>
[~REASON_CANCELED] =>
[~STATUS_ID] => F
[~DATE_STATUS] => 11.01.2007 16:44:57
[~PAY_VOUCHER_NUM] =>
[~PAY_VOUCHER_DATE] =>
[~EMP_STATUS_ID] => 10
[~PRICE_DELIVERY] => 0.00
[~ALLOW_DELIVERY] => Y
[~DATE_ALLOW_DELIVERY] => 11.01.2007 16:44:57
[~EMP_ALLOW_DELIVERY_ID] => 10
[~PRICE] => 12450.00
[~CURRENCY] => RUR
[~DISCOUNT_VALUE] => 0.00
[~SUM_PAID] => 0.00
[~USER_ID] => 10
[~PAY_SYSTEM_ID] => 1
[~DELIVERY_ID] =>
[~DATE_INSERT] => 11.01.2007 16:06:08
[~DATE_INSERT_FORMAT] => 11.01.2007 16:06:08
[~DATE_UPDATE] => 12.01.2007 13:01:20
[~USER_DESCRIPTION] =>
[~ADDITIONAL_INFO] =>
[~PS_STATUS] =>
[~PS_STATUS_CODE] =>
[~PS_STATUS_DESCRIPTION] =>
[~PS_STATUS_MESSAGE] =>
[~PS_SUM] =>
[~PS_CURRENCY] =>
[~PS_RESPONSE_DATE] =>
[~COMMENTS] =>
[~TAX_VALUE] => 0.00
[~STAT_GID] =>
[~RECURRING_ID] =>
[~RECOUNT_FLAG] => Y
[~USER_LOGIN] => anton
[~USER_NAME] => Anton
[~USER_LAST_NAME] => Ezhkov
[~USER_EMAIL] => anton@bitrixsoft.ru
[FORMATED_PRICE] => 12 450.00 р.
[CAN_CANCEL] => N
)
[BASKET_ITEMS] => Array
(
[0] => Array
(
[ID] => 51
[FUSER_ID] => 20
[ORDER_ID] => 33
[PRODUCT_ID] => 45414
[PRODUCT_PRICE_ID] => 49409
[PRICE] => 12450.00
[CURRENCY] => RUR
[DATE_INSERT] => 11.01.2007 16:05:50
[DATE_UPDATE] => 11.01.2007 16:05:50
[WEIGHT] => 0
[QUANTITY] => 1
[LID] => ru
[DELAY] => N
[NAME] => Битрикс: Управление сайтом - Малый бизнес (MySQL/OracleXE/MS SQL Express)
[CAN_BUY] => Y
[MODULE] => catalog
[CALLBACK_FUNC] => CatalogBasketCallback
[NOTES] =>
[ORDER_CALLBACK_FUNC] => CatalogBasketOrderCallback
[PAY_CALLBACK_FUNC] => CatalogPayOrderCallback
[CANCEL_CALLBACK_FUNC] => CatalogBasketCancelCallback
[DETAIL_PAGE_URL] =>
[DISCOUNT_PRICE] => 0.00
[CATALOG_XML_ID] =>
[PRODUCT_XML_ID] => 23740
[~ID] => 51
[~FUSER_ID] => 20
[~ORDER_ID] => 33
[~PRODUCT_ID] => 45414
[~PRODUCT_PRICE_ID] => 49409
[~PRICE] => 12450.00
[~CURRENCY] => RUR
[~DATE_INSERT] => 11.01.2007 16:05:50
[~DATE_UPDATE] => 11.01.2007 16:05:50
[~WEIGHT] => 0
[~QUANTITY] => 1
[~LID] => ru
[~DELAY] => N
[~NAME] => Битрикс: Управление сайтом - Малый бизнес (MySQL/OracleXE/MS SQL Express)
[~CAN_BUY] => Y
[~MODULE] => catalog
[~CALLBACK_FUNC] => CatalogBasketCallback
[~NOTES] =>
[~ORDER_CALLBACK_FUNC] => CatalogBasketOrderCallback
[~PAY_CALLBACK_FUNC] => CatalogPayOrderCallback
[~CANCEL_CALLBACK_FUNC] => CatalogBasketCancelCallback
[~DETAIL_PAGE_URL] =>
[~DISCOUNT_PRICE] => 0.00
[~CATALOG_XML_ID] =>
[~PRODUCT_XML_ID] => 23740
)
)
)
)
)
</pre>

Binary file not shown.

After

Width:  |  Height:  |  Size: 471 B

View File

@ -0,0 +1,4 @@
<?
$MESS ['SBB_DEFAULT_TEMPLATE_NAME'] = "RetailCRM Basket";
$MESS ['SBB_DEFAULT_TEMPLATE_DESCRIPTION'] = "Displays basket for the current user. Supports loyalty program.";
$MESS ['SBB_NAME'] = "Basket";

View File

@ -0,0 +1,75 @@
<?
$MESS["SBB_DESC_YES"] = "Yes";
$MESS["SBB_DESC_NO"] = "No";
$MESS["SBB_PATH_TO_ORDER"] = "Order page";
$MESS["SBB_HIDE_COUPON"] = "Hide upon entering coupon";
$MESS["SBB_COLUMNS_LIST"] = "Columns";
$MESS["SBB_BNAME"] = "Product name";
$MESS["SBB_BPROPS"] = "Product Item Properties";
$MESS["SBB_BPRICE"] = "Price";
$MESS["SBB_BSUM"] = "Total";
$MESS["SBB_BTYPE"] = "Price type";
$MESS["SBB_BQUANTITY"] = "Quantity";
$MESS["SBB_BDELETE"] = "Delete";
$MESS["SBB_BDELAY"] = "Hold";
$MESS["SBB_BWEIGHT"] = "Weight";
$MESS["SBB_BDISCOUNT"] = "Discount";
$MESS["SBB_WEIGHT_UNIT"] = "Weight unit";
$MESS["SBB_WEIGHT_UNIT_G"] = "g";
$MESS["SBB_WEIGHT_KOEF"] = "Grams in the unit of weight";
$MESS["SBB_VAT_SHOW_VALUE"] = "Show tax rate value";
$MESS["SBB_VAT_INCLUDE"] = "Include tax in price";
$MESS["SBB_USE_PREPAYMENT"] = "Use PayPal Express Checkout";
$MESS["SBB_QUANTITY_FLOAT"] = "Use fractional quantities";
$MESS["SBB_CORRECT_RATIO"] = "Automatically recalculate amount using fold coefficient";
$MESS["SBB_ACTION_VARIABLE"] = "Name of action variable";
$MESS["SBB_OFFERS_PROPS"] = "SKU Parameters";
$MESS["SBB_GIFTS"] = "\"Gifts\" Preferences";
$MESS["SBB_GIFTS_USE_GIFTS"] = "Show \"Gifts\" block";
$MESS["CVP_PAGE_ELEMENT_COUNT"] = "Items per page";
$MESS["CVP_PRODUCT_QUANTITY_VARIABLE"] = "Variable containing the product quantity";
$MESS["CVP_PRODUCT_PROPS_VARIABLE"] = "Variable containing the product properties";
$MESS["CVP_CONVERT_CURRENCY"] = "Use only one currency to show prices";
$MESS["CVP_HIDE_NOT_AVAILABLE"] = "Hide items not in stock";
$MESS["CVP_SHOW_NAME"] = "Show name";
$MESS["CVP_SHOW_IMAGE"] = "Show image";
$MESS["CVP_ADDITIONAL_IMAGE"] = "Additional image";
$MESS["CVP_SHOW_OLD_PRICE"] = "Show previous price";
$MESS["CVP_SHOW_DISCOUNT_PERCENT"] = "Show discount percent";
$MESS["CVP_MESS_BTN_BUY_GIFT"] = "\"Select\" button text";
$MESS["CVP_MESS_BTN_ADD_TO_BASKET"] = "\"Add to cart\" button text";
$MESS["CVP_MESS_BTN_DETAIL"] = "\"Details\" button text";
$MESS["CVP_MESS_NOT_AVAILABLE"] = "Product unavailable message";
$MESS["CVP_MESS_BTN_BUY_GIFT_DEFAULT"] = "Select";
$MESS["CVP_MESS_BTN_ADD_TO_BASKET_DEFAULT"] = "Add to cart";
$MESS["CVP_MESS_BTN_DETAIL_DEFAULT"] = "Details";
$MESS["CVP_MESS_NOT_AVAILABLE_DEFAULT"] = "Out of stock";
$MESS["SGB_PARAMS_BLOCK_TITLE"] = "Text for \"Gift\" title";
$MESS["SGB_PARAMS_BLOCK_TITLE_DEFAULT"] = "Select a gift";
$MESS["SGB_PARAMS_HIDE_BLOCK_TITLE"] = "Hide \"Gifts\" title";
$MESS["SGB_PAGE_ELEMENT_COUNT"] = "Number of items per row";
$MESS["SGB_PARAMS_TEXT_LABEL_GIFT"] = "Text for \"Gift\" label";
$MESS["SGB_PARAMS_TEXT_LABEL_GIFT_DEFAULT"] = "Gift";
$MESS["SBB_AUTO_CALCULATION"] = "Cart auto recalculation";
$MESS["SGB_PARAMS_PLACE_GIFT"] = "Show \"Gifts\" block";
$MESS["SGB_PARAMS_PLACE_GIFT_TOP"] = "above shopping cart";
$MESS["SGB_PARAMS_PLACE_GIFT_BOTTOM"] = "below shopping cart";
$MESS["PATH_TO_ORDER_TIP"] = "The path name of the order completion page. You can specify only the file name if the page is in the current directory.";
$MESS["HIDE_COUPON_TIP"] = "Select \"Yes\" to hide the coupon code input field in the basket page.";
$MESS["COLUMNS_LIST_TIP"] = "Selected fields will be used as columns titles in a basket contents table.";
$MESS["SET_TITLE_TIP"] = "Checking this option will set the page title to \"My Shopping Cart\".";
$MESS["PRICE_VAT_INCLUDE_TIP"] = "Checking this option specifies to include tax in the display prices.";
$MESS["PRICE_VAT_SHOW_VALUE_TIP"] = "Specifies to show the tax value.";
$MESS["SBB_PREVIEW_PICTURE"] = "Image";
$MESS["SBB_DETAIL_PICTURE"] = "Detailed image";
$MESS["SBB_PREVIEW_TEXT"] = "Short description";
$MESS["SBB_COMPATIBLE_MODE"] = "Enable compatibility mode";
$MESS["SBB_IMAGE_SETTINGS"] = "Image settings";
$MESS["SBB_ADDITIONAL_IMAGE"] = "Additional image";
$MESS["SBB_BASKET_IMAGES_SCALING"] = "Product image view mode";
$MESS["SBB_ADAPTIVE"] = "Adaptive";
$MESS["SBB_STANDARD"] = "Standard";
$MESS["SBB_NO_SCALE"] = "Don't resize";
$MESS["SBB_DEFAULT"] = "Default";
$MESS["SBB_ANALYTICS_SETTINGS"] = "Analytics Preferences";
?>

View File

@ -0,0 +1,10 @@
<?
$MESS["SALE_EMPTY_BASKET"] = "Your shopping cart is empty";
$MESS["SBB_PRODUCT_NOT_AVAILABLE"] = "#PRODUCT# is out of stock";
$MESS["SBB_PRODUCT_NOT_ENOUGH_QUANTITY"] = "The current stock of \"#PRODUCT#\" is insufficient (#NUMBER# is required)";
$MESS["SOA_TEMPL_ORDER_PS_ERROR"] = "The selected payment method failed. Please contact the site administrator or select another method.";
$MESS["SBB_TITLE"] = "My shopping cart";
$MESS["SALE_MODULE_NOT_INSTALL"] = "The e-Store module is not installed.";
$MESS["SBB_PRODUCT_QUANTITY_CHANGED"] = "Product quantity was changed";
$MESS["SBB_BASKET_ITEM_WRONG_AVAILABLE_QUANTITY"] = "Sorry, the product quantity you selected is currently unavailable.<br>Using the previous correct value.";
?>

View File

@ -0,0 +1,8 @@
<?
$MESS["SALE_MODULE_NOT_INSTALL"] = "e-Store module is not installed";
$MESS["SALE_EMPTY_BASKET"] = "Your shopping cart is empty";
$MESS["SBB_TITLE"] = "My shopping cart";
$MESS["SBB_PRODUCT_NOT_AVAILABLE"] = "#PRODUCT# is out of stock";
$MESS["SBB_PRODUCT_NOT_ENOUGH_QUANTITY"] = "The current stock of \"#PRODUCT#\" is insufficient (#NUMBER# is required)";
$MESS["SBB_PRODUCT_PRICE_NOT_FOUND"] = "Product price was not found.";
?>

View File

@ -0,0 +1,4 @@
<?
$MESS ['SBB_DEFAULT_TEMPLATE_NAME'] = "Корзина RetailCRM";
$MESS ['SBB_DEFAULT_TEMPLATE_DESCRIPTION'] = "Выводит корзину текущего пользователя (поддерживает программу лояльности)";
$MESS ['SBB_NAME'] = "Корзина";

View File

@ -0,0 +1,75 @@
<?
$MESS["SBB_DESC_YES"] = "Да";
$MESS["SBB_DESC_NO"] = "Нет";
$MESS["SBB_PATH_TO_ORDER"] = "Страница оформления заказа";
$MESS["SBB_HIDE_COUPON"] = "Спрятать поле ввода купона";
$MESS["SBB_COLUMNS_LIST"] = "Выводимые колонки";
$MESS["SBB_BNAME"] = "Название товара";
$MESS["SBB_PREVIEW_PICTURE"] = "Изображение";
$MESS["SBB_DETAIL_PICTURE"] = "Детальное изображение";
$MESS["SBB_PREVIEW_TEXT"] = "Краткое описание";
$MESS["SBB_BPROPS"] = "Свойства товара";
$MESS["SBB_BPRICE"] = "Цена";
$MESS["SBB_BSUM"] = "Сумма";
$MESS["SBB_BTYPE"] = "Тип цены";
$MESS["SBB_BQUANTITY"] = "Количество";
$MESS["SBB_BDELETE"] = "Удалить";
$MESS["SBB_BDELAY"] = "Отложить";
$MESS["SBB_BWEIGHT"] = "Вес";
$MESS["SBB_BDISCOUNT"] = "Скидка";
$MESS["SBB_WEIGHT_UNIT"] = "Единица веса";
$MESS["SBB_WEIGHT_UNIT_G"] = "г";
$MESS["SBB_WEIGHT_KOEF"] = "Коэффициент единицы к грамму";
$MESS["SBB_VAT_SHOW_VALUE"] = "Отображать значение НДС";
$MESS["SBB_VAT_INCLUDE"] = "Включать НДС в цену";
$MESS["SBB_USE_PREPAYMENT"] = "Использовать предавторизацию для оформления заказа (PayPal Express Checkout)";
$MESS["SBB_QUANTITY_FLOAT"] = "Использовать дробное значение количества";
$MESS["SBB_CORRECT_RATIO"] = "Автоматически рассчитывать количество товара кратное коэффициенту";
$MESS["SBB_ACTION_VARIABLE"] = "Название переменной действия";
$MESS["SBB_COMPATIBLE_MODE"] = "Включить режим совместимости";
$MESS["SBB_IMAGE_SETTINGS"] = "Настройки изображений";
$MESS["SBB_OFFERS_PROPS"] = "Настройка торговых предложений";
$MESS["SBB_ADDITIONAL_IMAGE"] = "Дополнительная картинка";
$MESS["SBB_BASKET_IMAGES_SCALING"] = "Режим отображения изображений товаров";
$MESS["SBB_ADAPTIVE"] = "Адаптивный";
$MESS["SBB_STANDARD"] = "Стандартный";
$MESS["SBB_NO_SCALE"] = "Без сжатия";
$MESS["SBB_DEFAULT"] = "По умолчанию";
$MESS["SBB_GIFTS"] = "Настройка \"Подарков\"";
$MESS["SBB_ANALYTICS_SETTINGS"] = "Настройки аналитики";
$MESS["SBB_GIFTS_USE_GIFTS"] = "Показывать блок \"Подарки\"";
$MESS["CVP_PAGE_ELEMENT_COUNT"] = "Количество элементов на странице";
$MESS["CVP_PRODUCT_QUANTITY_VARIABLE"] = "Название переменной, в которой передается количество товара";
$MESS["CVP_PRODUCT_PROPS_VARIABLE"] = "Название переменной, в которой передаются характеристики товара";
$MESS["CVP_CONVERT_CURRENCY"] = "Показывать цены в одной валюте";
$MESS["CVP_HIDE_NOT_AVAILABLE"] = "Не отображать товары, которых нет на складах";
$MESS["CVP_SHOW_NAME"] = "Показывать название";
$MESS["CVP_SHOW_IMAGE"] = "Показывать изображение";
$MESS["CVP_ADDITIONAL_IMAGE"] = "Дополнительная картинка";
$MESS["CVP_SHOW_OLD_PRICE"] = "Показывать старую цену";
$MESS["CVP_SHOW_DISCOUNT_PERCENT"] = "Показывать процент скидки";
$MESS["CVP_MESS_BTN_BUY_GIFT"] = "Текст кнопки \"Выбрать\"";
$MESS["CVP_MESS_BTN_ADD_TO_BASKET"] = "Текст кнопки \"Добавить в корзину\"";
$MESS["CVP_MESS_BTN_DETAIL"] = "Текст кнопки \"Подробнее\"";
$MESS["CVP_MESS_NOT_AVAILABLE"] = "Сообщение об отсутствии товара";
$MESS["CVP_MESS_BTN_BUY_GIFT_DEFAULT"] = "Выбрать";
$MESS["CVP_MESS_BTN_ADD_TO_BASKET_DEFAULT"] = "В корзину";
$MESS["CVP_MESS_BTN_DETAIL_DEFAULT"] = "Подробнее";
$MESS["CVP_MESS_NOT_AVAILABLE_DEFAULT"] = "Нет в наличии";
$MESS["SGB_PARAMS_BLOCK_TITLE"] = "Текст заголовка \"Подарки\"";
$MESS["SGB_PARAMS_BLOCK_TITLE_DEFAULT"] = "Выберите один из подарков";
$MESS["SGB_PARAMS_HIDE_BLOCK_TITLE"] = "Скрыть заголовок \"Подарки\"";
$MESS["SGB_PAGE_ELEMENT_COUNT"] = "Количество элементов в строке";
$MESS["SGB_PARAMS_TEXT_LABEL_GIFT"] = "Текст метки \"Подарка\"";
$MESS["SGB_PARAMS_TEXT_LABEL_GIFT_DEFAULT"] = "Подарок";
$MESS["SBB_AUTO_CALCULATION"] = "Автопересчет корзины";
$MESS["SGB_PARAMS_PLACE_GIFT"] = "Вывод блока \"Подарки\"";
$MESS["SGB_PARAMS_PLACE_GIFT_TOP"] = "Над корзиной";
$MESS["SGB_PARAMS_PLACE_GIFT_BOTTOM"] = "Под корзиной";
$MESS["PATH_TO_ORDER_TIP"] = "Путь к странице процедуры оформления заказа. Если страница находится в текущей директории, то достаточно указать ее название.";
$MESS["HIDE_COUPON_TIP"] = "Если \"Да\", то на странице с корзиной товаров поле для ввода купона на скидку показано не будет.";
$MESS["COLUMNS_LIST_TIP"] = "Выбираются поля, которые будут выведены в качестве названий колонок таблицы товаров.";
$MESS["SET_TITLE_TIP"] = "В качестве заголовка страницы будет установлено \"Моя корзина\".";
$MESS["PRICE_VAT_INCLUDE_TIP"] = "При отмеченной опции цены будут показаны с учетом НДС.";
$MESS["PRICE_VAT_SHOW_VALUE_TIP"] = "Опция служит для показа величины НДС.";
?>

View File

@ -0,0 +1,10 @@
<?
$MESS["SALE_MODULE_NOT_INSTALL"] = "Модуль \"Интернет-магазин\" не установлен.";
$MESS["SALE_EMPTY_BASKET"] = "Ваша корзина пуста";
$MESS["SBB_PRODUCT_NOT_AVAILABLE"] = "Товар #PRODUCT# не доступен для заказа";
$MESS["SBB_PRODUCT_NOT_ENOUGH_QUANTITY"] = "Для оформления заказа недостаточно товара \"#PRODUCT#\" в количестве #NUMBER#";
$MESS["SOA_TEMPL_ORDER_PS_ERROR"] = "Ошибка выбранного способа оплаты. Обратитесь к Администрации сайта, либо выберите другой способ оплаты.";
$MESS["SBB_TITLE"] = "Моя корзина";
$MESS["SBB_PRODUCT_QUANTITY_CHANGED"] = "Извините, но указанное ранее количество товара недоступно.<br>Установлено ближайшее доступное значение.";
$MESS["SBB_BASKET_ITEM_WRONG_AVAILABLE_QUANTITY"] = "Извините, но указанное количество товара в данный момент недоступно.<br>Установлено предыдущее корректное значение.";
?>

View File

@ -0,0 +1,8 @@
<?
$MESS["SALE_MODULE_NOT_INSTALL"] = "Модуль Интернет-магазин не установлен.";
$MESS["SALE_EMPTY_BASKET"] = "Ваша корзина пуста";
$MESS["SBB_TITLE"] = "Моя корзина";
$MESS["SBB_PRODUCT_NOT_AVAILABLE"] = "Товар #PRODUCT# не доступен для заказа";
$MESS["SBB_PRODUCT_NOT_ENOUGH_QUANTITY"] = "Для оформления заказа недостаточно товара \"#PRODUCT#\" в количество #NUMBER#";
$MESS["SBB_PRODUCT_PRICE_NOT_FOUND"] = "Не найдена цена продукта";
?>

View File

@ -0,0 +1,141 @@
function initDraggableOrderControl(params)
{
var data = JSON.parse(params.data);
if (data)
{
BX.loadScript('/bitrix/js/main/core/core_dragdrop.js', function(){
(function bx_dnd_order_waiter(){
if (!!BX.DragDrop)
window['dnd_parameter_' + params.propertyID] = new DragNDropOrderParameterControl(data, params);
else
setTimeout(bx_dnd_order_waiter, 50);
})();
});
}
}
function DragNDropOrderParameterControl(items, params)
{
var rand = BX.util.getRandomString(5);
this.params = params || {};
this.items = this.getSortedItems(items);
this.rootElementId = 'dnd_params_container_' + this.params.propertyID + '_' + rand;
this.dragItemClassName = 'dnd-order-draggable-item-' + this.params.propertyID + '-' + rand;
BX.loadCSS(this.getPath() + '/style.css?' + rand);
this.buildNodes();
this.initDragDrop();
}
DragNDropOrderParameterControl.prototype =
{
getPath: function()
{
var path = this.params.propertyParams.JS_FILE.split('/');
path.pop();
return path.join('/');
},
getSortedItems: function(items)
{
if (!items)
return [];
var inputValue = this.params.oInput.value || this.params.propertyParams.DEFAULT || '',
result = [],
k;
var values = inputValue.split(',');
for (k in values)
{
if (values.hasOwnProperty(k))
{
values[k] = BX.util.trim(values[k]);
if (items[values[k]])
{
result.push({
value: values[k],
message: items[values[k]]
});
}
}
}
for (k in items)
{
if (items.hasOwnProperty(k) && !BX.util.in_array(k, values))
{
result.push({
value: k,
message: items[k]
});
}
}
return result;
},
buildNodes: function()
{
var baseNode = BX.create('DIV', {
props: {className: 'dnd-order-draggable-control-container', id: this.rootElementId}
});
for (var k in this.items)
{
if (this.items.hasOwnProperty(k))
{
baseNode.appendChild(
BX.create('DIV', {
attrs: {'data-value': this.items[k].value},
props: {
className: 'dnd-order-draggable-control dnd-order-draggable-item ' + this.dragItemClassName
},
text: this.items[k].message
})
);
}
}
this.params.oCont.appendChild(baseNode);
},
initDragDrop: function()
{
if (BX.isNodeInDom(this.params.oCont))
{
this.dragdrop = BX.DragDrop.create({
dragItemClassName: this.dragItemClassName,
dragItemControlClassName: 'dnd-order-draggable-control',
sortable: {rootElem: BX(this.rootElementId)},
dragEnd: BX.delegate(function(eventObj, dragElement, event){
this.saveData();
}, this)
});
}
else
{
setTimeout(BX.delegate(this.initDragDrop, this), 50);
}
},
saveData: function()
{
var items = this.params.oCont.querySelectorAll('.' + this.dragItemClassName),
arr = [];
for (var k in items)
{
if (items.hasOwnProperty(k))
{
arr.push(items[k].getAttribute('data-value'));
}
}
this.params.oInput.value = arr.join(',');
}
};

View File

@ -0,0 +1 @@
{"version":3,"sources":["script.js"],"names":["initDraggableOrderControl","params","data","JSON","parse","BX","loadScript","bx_dnd_order_waiter","DragDrop","window","propertyID","DragNDropOrderParameterControl","setTimeout","items","rand","util","getRandomString","this","getSortedItems","rootElementId","dragItemClassName","loadCSS","getPath","buildNodes","initDragDrop","prototype","path","propertyParams","JS_FILE","split","pop","join","inputValue","oInput","value","DEFAULT","result","k","values","hasOwnProperty","trim","push","message","in_array","baseNode","create","props","className","id","appendChild","attrs","data-value","text","oCont","isNodeInDom","dragdrop","dragItemControlClassName","sortable","rootElem","dragEnd","delegate","eventObj","dragElement","event","saveData","querySelectorAll","arr","getAttribute"],"mappings":"AAAA,SAASA,0BAA0BC,GAElC,IAAIC,EAAOC,KAAKC,MAAMH,EAAOC,MAC7B,GAAIA,EACJ,CACCG,GAAGC,WAAW,wCAAyC,YACtD,SAAUC,IACT,KAAMF,GAAGG,SACRC,OAAO,iBAAmBR,EAAOS,YAAc,IAAIC,+BAA+BT,EAAMD,QAExFW,WAAWL,EAAqB,KAJlC,MAUH,SAASI,+BAA+BE,EAAOZ,GAE9C,IAAIa,EAAOT,GAAGU,KAAKC,gBAAgB,GAEnCC,KAAKhB,OAASA,MACdgB,KAAKJ,MAAQI,KAAKC,eAAeL,GAEjCI,KAAKE,cAAgB,wBAA0BF,KAAKhB,OAAOS,WAAa,IAAMI,EAC9EG,KAAKG,kBAAoB,4BAA8BH,KAAKhB,OAAOS,WAAa,IAAMI,EAEtFT,GAAGgB,QAAQJ,KAAKK,UAAY,cAAgBR,GAC5CG,KAAKM,aACLN,KAAKO,eAGNb,+BAA+Bc,WAE9BH,QAAS,WAER,IAAII,EAAOT,KAAKhB,OAAO0B,eAAeC,QAAQC,MAAM,KAEpDH,EAAKI,MAEL,OAAOJ,EAAKK,KAAK,MAGlBb,eAAgB,SAASL,GAExB,IAAKA,EACJ,SAED,IAAImB,EAAaf,KAAKhB,OAAOgC,OAAOC,OAASjB,KAAKhB,OAAO0B,eAAeQ,SAAW,GAClFC,KACAC,EAED,IAAIC,EAASN,EAAWH,MAAM,KAC9B,IAAKQ,KAAKC,EACV,CACC,GAAIA,EAAOC,eAAeF,GAC1B,CACCC,EAAOD,GAAKhC,GAAGU,KAAKyB,KAAKF,EAAOD,IAChC,GAAIxB,EAAMyB,EAAOD,IACjB,CACCD,EAAOK,MACNP,MAAOI,EAAOD,GACdK,QAAS7B,EAAMyB,EAAOD,QAM1B,IAAKA,KAAKxB,EACV,CACC,GAAIA,EAAM0B,eAAeF,KAAOhC,GAAGU,KAAK4B,SAASN,EAAGC,GACpD,CACCF,EAAOK,MACNP,MAAOG,EACPK,QAAS7B,EAAMwB,MAKlB,OAAOD,GAGRb,WAAY,WAEX,IAAIqB,EAAWvC,GAAGwC,OAAO,OACxBC,OAAQC,UAAW,wCAAyCC,GAAI/B,KAAKE,iBAGtE,IAAK,IAAIkB,KAAKpB,KAAKJ,MACnB,CACC,GAAII,KAAKJ,MAAM0B,eAAeF,GAC9B,CACCO,EAASK,YACR5C,GAAGwC,OAAO,OACTK,OAAQC,aAAclC,KAAKJ,MAAMwB,GAAGH,OACpCY,OACCC,UAAW,wDAA0D9B,KAAKG,mBAE3EgC,KAAMnC,KAAKJ,MAAMwB,GAAGK,YAMxBzB,KAAKhB,OAAOoD,MAAMJ,YAAYL,IAG/BpB,aAAc,WAEb,GAAInB,GAAGiD,YAAYrC,KAAKhB,OAAOoD,OAC/B,CACCpC,KAAKsC,SAAWlD,GAAGG,SAASqC,QAC3BzB,kBAAmBH,KAAKG,kBACxBoC,yBAA0B,8BAC1BC,UAAWC,SAAUrD,GAAGY,KAAKE,gBAC7BwC,QAAStD,GAAGuD,SAAS,SAASC,EAAUC,EAAaC,GACpD9C,KAAK+C,YACH/C,YAIL,CACCL,WAAWP,GAAGuD,SAAS3C,KAAKO,aAAcP,MAAO,MAInD+C,SAAU,WAET,IAAInD,EAAQI,KAAKhB,OAAOoD,MAAMY,iBAAiB,IAAMhD,KAAKG,mBACzD8C,KAED,IAAK,IAAI7B,KAAKxB,EACd,CACC,GAAIA,EAAM0B,eAAeF,GACzB,CACC6B,EAAIzB,KAAK5B,EAAMwB,GAAG8B,aAAa,gBAIjClD,KAAKhB,OAAOgC,OAAOC,MAAQgC,EAAInC,KAAK","file":""}

View File

@ -0,0 +1 @@
function initDraggableOrderControl(r){var t=JSON.parse(r.data);if(t){BX.loadScript("/bitrix/js/main/core/core_dragdrop.js",function(){(function a(){if(!!BX.DragDrop)window["dnd_parameter_"+r.propertyID]=new DragNDropOrderParameterControl(t,r);else setTimeout(a,50)})()})}}function DragNDropOrderParameterControl(r,t){var a=BX.util.getRandomString(5);this.params=t||{};this.items=this.getSortedItems(r);this.rootElementId="dnd_params_container_"+this.params.propertyID+"_"+a;this.dragItemClassName="dnd-order-draggable-item-"+this.params.propertyID+"-"+a;BX.loadCSS(this.getPath()+"/style.css?"+a);this.buildNodes();this.initDragDrop()}DragNDropOrderParameterControl.prototype={getPath:function(){var r=this.params.propertyParams.JS_FILE.split("/");r.pop();return r.join("/")},getSortedItems:function(r){if(!r)return[];var t=this.params.oInput.value||this.params.propertyParams.DEFAULT||"",a=[],e;var s=t.split(",");for(e in s){if(s.hasOwnProperty(e)){s[e]=BX.util.trim(s[e]);if(r[s[e]]){a.push({value:s[e],message:r[s[e]]})}}}for(e in r){if(r.hasOwnProperty(e)&&!BX.util.in_array(e,s)){a.push({value:e,message:r[e]})}}return a},buildNodes:function(){var r=BX.create("DIV",{props:{className:"dnd-order-draggable-control-container",id:this.rootElementId}});for(var t in this.items){if(this.items.hasOwnProperty(t)){r.appendChild(BX.create("DIV",{attrs:{"data-value":this.items[t].value},props:{className:"dnd-order-draggable-control dnd-order-draggable-item "+this.dragItemClassName},text:this.items[t].message}))}}this.params.oCont.appendChild(r)},initDragDrop:function(){if(BX.isNodeInDom(this.params.oCont)){this.dragdrop=BX.DragDrop.create({dragItemClassName:this.dragItemClassName,dragItemControlClassName:"dnd-order-draggable-control",sortable:{rootElem:BX(this.rootElementId)},dragEnd:BX.delegate(function(r,t,a){this.saveData()},this)})}else{setTimeout(BX.delegate(this.initDragDrop,this),50)}},saveData:function(){var r=this.params.oCont.querySelectorAll("."+this.dragItemClassName),t=[];for(var a in r){if(r.hasOwnProperty(a)){t.push(r[a].getAttribute("data-value"))}}this.params.oInput.value=t.join(",")}};

View File

@ -0,0 +1,58 @@
.dnd-order-draggable-control-container div.dnd-order-draggable-item{
width:120px;
vertical-align: middle;
line-height: 17px;
text-align: center;
background: #fff !important;
border:1px solid #c1c8d0;
cursor: grab;
cursor: -webkit-grab;
margin: 2px 0 5px;
border-radius: 2px;
padding: 5px 0;
box-shadow: inset 0 0 0 0 rgba(0,0,0,.2);
transition: box-shadow 250ms ease;
-webkit-animation: dnd-order-draggable-item .3s linear;
-moz-animation: dnd-order-draggable-item .3s linear;
-ms-animation: dnd-order-draggable-item .3s linear;
-o-animation: dnd-order-draggable-item .3s linear;
animation: dnd-order-draggable-item .3s linear;
}
.dnd-order-draggable-control-container div.dnd-order-draggable-item:active{
box-shadow: inset 0 0 15px 0 rgba(0,0,0,.2);
border-style:dashed
}
@-webkit-keyframes dnd-order-draggable-item {
0%,100%{ background: transparent;}
50%{ background: #cee28c;}
0%{-webkit-transform: translateX(75px); opacity: 0;}
100%{-webkit-transform: translateX(0); opacity: 1;}
}
@-moz-keyframes dnd-order-draggable-item {
0%,100%{ background: transparent;}
50%{ background: #cee28c;}
0%{-moz-transform: translateX(75px); opacity: 0;}
100%{-moz-transform: translateX(0); opacity: 1;}
}
@-ms-keyframes dnd-order-draggable-item {
0%,100%{ background: transparent;}
50%{ background: #cee28c;}
0%{-ms-transform: translateX(75px); opacity: 0;}
100%{-ms-transform: translateX(0); opacity: 1;}
}
@-o-keyframes dnd-order-draggable-item {
0%,100%{ background: transparent;}
50%{ background: #cee28c;}
0%{-o-transform: translateX(75px); opacity: 0;}
100%{-o-transform: translateX(0); opacity: 1;}
}
@keyframes dnd-order-draggable-item {
0%,100%{ background: transparent;}
50%{ background: #cee28c;}
0%{transform: translateX(75px); opacity: 0;}
100%{transform: translateX(0); opacity: 1;}
}

View File

@ -0,0 +1 @@
.dnd-order-draggable-control-container div.dnd-order-draggable-item{width:120px;vertical-align:middle;line-height:17px;text-align:center;background:#fff!important;border:1px solid #c1c8d0;cursor:grab;cursor:-webkit-grab;margin:2px 0 5px;border-radius:2px;padding:5px 0;box-shadow:inset 0 0 0 0 rgba(0,0,0,.2);transition:box-shadow 250ms ease;-webkit-animation:dnd-order-draggable-item .3s linear;-moz-animation:dnd-order-draggable-item .3s linear;-ms-animation:dnd-order-draggable-item .3s linear;-o-animation:dnd-order-draggable-item .3s linear;animation:dnd-order-draggable-item .3s linear}.dnd-order-draggable-control-container div.dnd-order-draggable-item:active{box-shadow:inset 0 0 15px 0 rgba(0,0,0,.2);border-style:dashed}@-webkit-keyframes dnd-order-draggable-item{0%,100%{background:transparent}50%{background:#cee28c}0%{-webkit-transform:translateX(75px);opacity:0}100%{-webkit-transform:translateX(0);opacity:1}}@-moz-keyframes dnd-order-draggable-item{0%,100%{background:transparent}50%{background:#cee28c}0%{-moz-transform:translateX(75px);opacity:0}100%{-moz-transform:translateX(0);opacity:1}}@-ms-keyframes dnd-order-draggable-item{0%,100%{background:transparent}50%{background:#cee28c}0%{-ms-transform:translateX(75px);opacity:0}100%{-ms-transform:translateX(0);opacity:1}}@-o-keyframes dnd-order-draggable-item{0%,100%{background:transparent}50%{background:#cee28c}0%{-o-transform:translateX(75px);opacity:0}100%{-o-transform:translateX(0);opacity:1}}@keyframes dnd-order-draggable-item{0%,100%{background:transparent}50%{background:#cee28c}0%{transform:translateX(75px);opacity:0}100%{transform:translateX(0);opacity:1}}

View File

@ -0,0 +1,105 @@
function initPositionControl(params)
{
var data = JSON.parse(params.data);
if (data)
{
window['pos_parameter_' + params.propertyID] = new PositionParameterControl(data, params);
}
}
function PositionParameterControl(data, params)
{
var rand = BX.util.getRandomString(5);
this.params = params || {};
this.positions = data.positions || {};
this.parentClassName = data.className ? ' ' + data.className : '';
this.selected = this.params.oInput.value || this.params.propertyParams.DEFAULT;
this.id = 'pos_params_container_' + this.params.propertyID + '_' + rand;
BX.loadCSS(this.getPath() + '/style.css?' + rand);
this.buildNodes();
this.saveData();
}
PositionParameterControl.prototype =
{
getPath: function()
{
var path = this.params.propertyParams.JS_FILE.split('/');
path.pop();
return path.join('/');
},
buildNodes: function()
{
var nodes = [];
for (var i in this.positions)
{
if (this.positions.hasOwnProperty(i))
{
nodes.push(
BX.create('DIV', {
attrs: {'data-value': this.positions[i]},
props: {
className: 'bx-pos-parameter bx-pos-parameter-' + this.positions[i]
+ (this.positions[i] == this.selected ? ' selected' : '')
},
events: {click: BX.proxy(this.selectPosition, this)}
})
);
}
}
this.params.oCont.appendChild(
BX.create('DIV', {
props: {className: 'bx-pos-parameter-container' + this.parentClassName},
children: [
BX.create('DIV', {children: nodes, props: {className: 'bx-pos-parameter-block'}}),
BX.create('DIV', {props: {className: 'bx-pos-parameter-decore'}}),
BX.create('DIV', {props: {className: 'bx-pos-parameter-decore'}}),
BX.create('DIV', {props: {className: 'bx-pos-parameter-decore'}}),
BX.create('DIV', {props: {className: 'bx-pos-parameter-decore'}}),
BX.create('DIV', {props: {className: 'bx-pos-parameter-decore'}})
]
})
);
},
selectPosition: function(event)
{
var target = BX.getEventTarget(event),
items = this.params.oCont.querySelectorAll('.bx-pos-parameter'),
value = target.getAttribute('data-value');
if (this.selected == value)
return;
this.selected = value;
for (var k in items)
{
if (items.hasOwnProperty(k))
{
if (items[k].getAttribute('data-value') == this.selected)
{
BX.addClass(items[k], 'selected');
}
else
{
BX.removeClass(items[k], 'selected');
}
}
}
this.saveData();
},
saveData: function()
{
this.params.oInput.value = this.selected;
}
};

View File

@ -0,0 +1 @@
{"version":3,"sources":["script.js"],"names":["initPositionControl","params","data","JSON","parse","window","propertyID","PositionParameterControl","rand","BX","util","getRandomString","this","positions","parentClassName","className","selected","oInput","value","propertyParams","DEFAULT","id","loadCSS","getPath","buildNodes","saveData","prototype","path","JS_FILE","split","pop","join","nodes","i","hasOwnProperty","push","create","attrs","data-value","props","events","click","proxy","selectPosition","oCont","appendChild","children","event","target","getEventTarget","items","querySelectorAll","getAttribute","k","addClass","removeClass"],"mappings":"AAAA,SAASA,oBAAoBC,GAE5B,IAAIC,EAAOC,KAAKC,MAAMH,EAAOC,MAC7B,GAAIA,EACJ,CACCG,OAAO,iBAAmBJ,EAAOK,YAAc,IAAIC,yBAAyBL,EAAMD,IAIpF,SAASM,yBAAyBL,EAAMD,GAEvC,IAAIO,EAAOC,GAAGC,KAAKC,gBAAgB,GAEnCC,KAAKX,OAASA,MACdW,KAAKC,UAAYX,EAAKW,cACtBD,KAAKE,gBAAkBZ,EAAKa,UAAY,IAAMb,EAAKa,UAAY,GAC/DH,KAAKI,SAAWJ,KAAKX,OAAOgB,OAAOC,OAASN,KAAKX,OAAOkB,eAAeC,QACvER,KAAKS,GAAK,wBAA0BT,KAAKX,OAAOK,WAAa,IAAME,EAEnEC,GAAGa,QAAQV,KAAKW,UAAY,cAAgBf,GAC5CI,KAAKY,aACLZ,KAAKa,WAGNlB,yBAAyBmB,WAExBH,QAAS,WAER,IAAII,EAAOf,KAAKX,OAAOkB,eAAeS,QAAQC,MAAM,KAEpDF,EAAKG,MAEL,OAAOH,EAAKI,KAAK,MAGlBP,WAAY,WAEX,IAAIQ,KAEJ,IAAK,IAAIC,KAAKrB,KAAKC,UACnB,CACC,GAAID,KAAKC,UAAUqB,eAAeD,GAClC,CACCD,EAAMG,KACL1B,GAAG2B,OAAO,OACTC,OAAQC,aAAc1B,KAAKC,UAAUoB,IACrCM,OACCxB,UAAW,qCAAuCH,KAAKC,UAAUoB,IAC9DrB,KAAKC,UAAUoB,IAAMrB,KAAKI,SAAW,YAAc,KAEvDwB,QAASC,MAAOhC,GAAGiC,MAAM9B,KAAK+B,eAAgB/B,WAMlDA,KAAKX,OAAO2C,MAAMC,YACjBpC,GAAG2B,OAAO,OACTG,OAAQxB,UAAW,6BAA+BH,KAAKE,iBACvDgC,UACCrC,GAAG2B,OAAO,OAAQU,SAAUd,EAAOO,OAAQxB,UAAW,4BACtDN,GAAG2B,OAAO,OAAQG,OAAQxB,UAAW,6BACrCN,GAAG2B,OAAO,OAAQG,OAAQxB,UAAW,6BACrCN,GAAG2B,OAAO,OAAQG,OAAQxB,UAAW,6BACrCN,GAAG2B,OAAO,OAAQG,OAAQxB,UAAW,6BACrCN,GAAG2B,OAAO,OAAQG,OAAQxB,UAAW,kCAMzC4B,eAAgB,SAASI,GAExB,IAAIC,EAASvC,GAAGwC,eAAeF,GAC9BG,EAAQtC,KAAKX,OAAO2C,MAAMO,iBAAiB,qBAC3CjC,EAAQ8B,EAAOI,aAAa,cAE7B,GAAIxC,KAAKI,UAAYE,EACpB,OAEDN,KAAKI,SAAWE,EAEhB,IAAK,IAAImC,KAAKH,EACd,CACC,GAAIA,EAAMhB,eAAemB,GACzB,CACC,GAAIH,EAAMG,GAAGD,aAAa,eAAiBxC,KAAKI,SAChD,CACCP,GAAG6C,SAASJ,EAAMG,GAAI,gBAGvB,CACC5C,GAAG8C,YAAYL,EAAMG,GAAI,cAK5BzC,KAAKa,YAGNA,SAAU,WAETb,KAAKX,OAAOgB,OAAOC,MAAQN,KAAKI","file":""}

View File

@ -0,0 +1 @@
function initPositionControl(e){var s=JSON.parse(e.data);if(s){window["pos_parameter_"+e.propertyID]=new PositionParameterControl(s,e)}}function PositionParameterControl(e,s){var t=BX.util.getRandomString(5);this.params=s||{};this.positions=e.positions||{};this.parentClassName=e.className?" "+e.className:"";this.selected=this.params.oInput.value||this.params.propertyParams.DEFAULT;this.id="pos_params_container_"+this.params.propertyID+"_"+t;BX.loadCSS(this.getPath()+"/style.css?"+t);this.buildNodes();this.saveData()}PositionParameterControl.prototype={getPath:function(){var e=this.params.propertyParams.JS_FILE.split("/");e.pop();return e.join("/")},buildNodes:function(){var e=[];for(var s in this.positions){if(this.positions.hasOwnProperty(s)){e.push(BX.create("DIV",{attrs:{"data-value":this.positions[s]},props:{className:"bx-pos-parameter bx-pos-parameter-"+this.positions[s]+(this.positions[s]==this.selected?" selected":"")},events:{click:BX.proxy(this.selectPosition,this)}}))}}this.params.oCont.appendChild(BX.create("DIV",{props:{className:"bx-pos-parameter-container"+this.parentClassName},children:[BX.create("DIV",{children:e,props:{className:"bx-pos-parameter-block"}}),BX.create("DIV",{props:{className:"bx-pos-parameter-decore"}}),BX.create("DIV",{props:{className:"bx-pos-parameter-decore"}}),BX.create("DIV",{props:{className:"bx-pos-parameter-decore"}}),BX.create("DIV",{props:{className:"bx-pos-parameter-decore"}}),BX.create("DIV",{props:{className:"bx-pos-parameter-decore"}})]}))},selectPosition:function(e){var s=BX.getEventTarget(e),t=this.params.oCont.querySelectorAll(".bx-pos-parameter"),a=s.getAttribute("data-value");if(this.selected==a)return;this.selected=a;for(var r in t){if(t.hasOwnProperty(r)){if(t[r].getAttribute("data-value")==this.selected){BX.addClass(t[r],"selected")}else{BX.removeClass(t[r],"selected")}}}this.saveData()},saveData:function(){this.params.oInput.value=this.selected}};

View File

@ -0,0 +1,295 @@
.bx-pos-parameter-container{
border:2px solid #A7ADB2;
width: 246px;
border-radius:2px;
background: #fff;
}
.bx-pos-parameter-block{
width: 246px;
height:202px;
position: relative;
background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNjYiIGhlaWdodD0iMTM1IiB2aWV3Qm94PSIwIDAgMTY2IDEzNSI+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNNTAuMDYgNzcuNTk2YzAgMTguMDY0IDE0LjY0NSAzMi43MDggMzIuNzEgMzIuNzA4IDE4LjA2MyAwIDMyLjcwNy0xNC42NDQgMzIuNzA3LTMyLjcwOFMxMDAuODMzIDQ0Ljg4OCA4Mi43NyA0NC44ODhjLTE4LjA2NSAwLTMyLjcxIDE0LjY0NC0zMi43MSAzMi43MDh6bTY4LjkyLTU2LjkwNEMxMTYuMzk0IDEwLjM0NiAxMDkgMCAxMDMuNDYgMEg2Mi4wNzhDNTUgMCA0OS4xNDQgMTAuMzQ2IDQ2LjU1NyAyMC42OTJoLTM2LjIxQzQuNjU2IDIwLjY5MiAwIDI1LjM0OCAwIDMxLjAzOHY5My4xMTVjMCA1LjY5IDQuNjU2IDEwLjM0NiAxMC4zNDYgMTAuMzQ2aDE0NC44NDZjNS42OSAwIDEwLjM0Ni00LjY1NiAxMC4zNDYtMTAuMzQ3VjMxLjAzOGMwLTUuNjktNC42NTYtMTAuMzQ2LTEwLjM0Ni0xMC4zNDZIMTE4Ljk4ek04Mi43NyAxMjIuMjU1Yy0yNC42NjUgMC00NC42Ni0xOS45OTQtNDQuNjYtNDQuNjYgMC0yNC42NjQgMTkuOTk0LTQ0LjY1OCA0NC42Ni00NC42NTggMjQuNjY0IDAgNDQuNjU4IDE5Ljk5NCA0NC42NTggNDQuNjYgMCAyNC42NjQtMTkuOTk0IDQ0LjY1OC00NC42NiA0NC42NTh6TTE1MS4xOSA0Ny43M0gxMzAuNVYzNy4zODZoMjAuNjkyVjQ3LjczeiIgb3BhY2l0eT0iLjA0Ii8+PC9zdmc+) no-repeat center;
background-size:66%;
margin-bottom:8px;
}
.bx-pos-parameter{
width:79px;
height: 64px;
position: absolute;
text-align: center !important;
-webkit-transition: background-color 250ms ease;
-moz-transition: background-color 250ms ease;
-ms-transition: background-color 250ms ease;
-o-transition: background-color 250ms ease;
transition: background-color 250ms ease;
cursor: pointer;
background-color: rgba(128,134,142,.06);
}
.bx-pos-parameter:hover,
.bx-pos-parameter.selected{background-color: rgba(256,166,35,.16);}
.bx-pos-parameter:after{
position: absolute;
width:16px;
height: 22px;
content: " ";
display: block;
opacity: .3;
background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIyMiIgdmlld0JveD0iMCAwIDE2IDIyIj48cGF0aCBmaWxsPSIjNTM1QzY5IiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xLjkxIDguNTcyYTEuMTEyIDEuMTEyIDAgMCAxLTEuNTg4IDAgMS4xNCAxLjE0IDAgMCAxIDAtMS41ODdsNi42NS02LjY1QTEuMTQgMS4xNCAwIDAgMSA3Ljc4MiAwYy4zMTYgMCAuNjAyLjEyOC44MS4zMzRsNi42NSA2LjY1YTEuMTEyIDEuMTEyIDAgMCAxIDAgMS41ODggMS4xMTIgMS4xMTIgMCAwIDEtMS41ODggMEw4LjkwOCAzLjgxdjE2LjkwNWMwIC42Mi0uNTA3IDEuMTEtMS4xMjYgMS4xMS0uNjIgMC0xLjExLS40OS0xLjExLTEuMTFWMy44MUwxLjkwOCA4LjU3M3oiLz48L3N2Zz4=);
background-repeat: no-repeat;
background-position: center;
-webkit-transition: opacity 250ms ease;
-moz-transition: opacity 250ms ease;
-ms-transition: opacity 250ms ease;
-o-transition: opacity 250ms ease;
transition: opacity 250ms ease;
}
.bx-pos-parameter:hover:after,
.bx-pos-parameter.selected:after{ opacity: 1;}
.bx-pos-parameter:before{
position: absolute;
width:50px;
height: 17px;
content: " ";
display: block;
opacity: 0;
background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1NyIgaGVpZ2h0PSIxOCIgdmlld0JveD0iMCAwIDU3IDE4Ij48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGZpbGw9IiNGRTU5NTciIGQ9Ik0wIDBoNTdsLTMgOSAzIDlIMHoiLz48cGF0aCBmaWxsPSIjRkZGIiBvcGFjaXR5PSIuNCIgZD0iTTYgN2g0M3Y0SDZ6Ii8+PC9nPjwvc3ZnPg==);
background-repeat: no-repeat;
background-position: center;
background-size: contain;
-webkit-transition: opacity 250ms ease;
-moz-transition: opacity 250ms ease;
-ms-transition: opacity 250ms ease;
-o-transition: opacity 250ms ease;
transition: opacity 250ms ease;
}
.bx-pos-parameter-block-circle .bx-pos-parameter:before{
background: #FF9C9F;
border: 5px solid #fe5957;
width: 20px;
height: 20px;
border-radius: 50%;
box-sizing: border-box;
}
.bx-pos-parameter:hover:before,
.bx-pos-parameter.selected:before{ opacity: 1;}
.bx-pos-parameter-top-left {
top: 0;
left: 0;
}
.bx-pos-parameter-top-left:after{
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
bottom:2px;
right:2px;
}
.bx-pos-parameter-top-left:before{
top:2px;
left:2px;
}
.bx-pos-parameter-top-center {
top: 0;
left: 50%;
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
transform: translateX(-50%);
}
.bx-pos-parameter-top-center:after{
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
transform: translateX(-50%);
bottom:2px;
left: 50%;
}
.bx-pos-parameter-top-center:before{
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
transform: translateX(-50%);
top:2px;
left: 50%;
}
.bx-pos-parameter-top-right {
top: 0;
right: 0;
}
.bx-pos-parameter-top-right:after{
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
bottom:2px;
left:2px;
}
.bx-pos-parameter-top-right:before{
top:2px;
right:2px;
}
.bx-pos-parameter-middle-left {
left: 0;
top: 50%;
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%);
}
.bx-pos-parameter-middle-left:after{
-webkit-transform: rotate(-90deg) translateX(70%);
-moz-transform: rotate(-90deg) translateX(70%);
-ms-transform: rotate(-90deg) translateX(70%);
-o-transform: rotate(-90deg) translateX(70%);
transform: rotate(-90deg) translateX(70%);
right:5px;
top: 50%;
}
.bx-pos-parameter-middle-left:before{
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%);
left:2px;
top: 50%;
}
.bx-pos-parameter-middle-center {
left: 50%;
top: 50%;
-webkit-transform: translateY(-50%) translateX(-50%);
-moz-transform: translateY(-50%) translateX(-50%);
-ms-transform: translateY(-50%) translateX(-50%);
-o-transform: translateY(-50%) translateX(-50%);
transform: translateY(-50%) translateX(-50%);
}
.bx-pos-parameter-middle-center:after{ display: none;}
.bx-pos-parameter-middle-center:before{
-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
-o-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
top:50%;
left: 50%;
}
.bx-pos-parameter-middle-right {
right: 0;
top: 50%;
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%);
}
.bx-pos-parameter-middle-right:after{
-webkit-transform: rotate(90deg) translateX(-70%);
-moz-transform: rotate(90deg) translateX(-70%);
-ms-transform: rotate(90deg) translateX(-70%);
-o-transform: rotate(90deg) translateX(-70%);
transform: rotate(90deg) translateX(-70%);
left:5px;
top: 50%;
}
.bx-pos-parameter-middle-right:before{
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%);
right:2px;
top: 50%;
}
.bx-pos-parameter-bottom-left {
bottom: 0;
left: 0;
}
.bx-pos-parameter-bottom-left:after{
-webkit-transform: rotate(-135deg) translateX(50%);
-moz-transform: rotate(-135deg) translateX(50%);
-ms-transform: rotate(-135deg) translateX(50%);
-o-transform: rotate(-135deg) translateX(50%);
transform: rotate(-135deg) translateX(50%);
right:2px;
top: 5px;
}
.bx-pos-parameter-bottom-left:before{
left:2px;
bottom: 2px;
}
.bx-pos-parameter-bottom-center {
bottom: 0;
left: 50%;
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
transform: translateX(-50%);
}
.bx-pos-parameter-bottom-center:after{
-webkit-transform: rotate(180deg) translateX(50%);
-moz-transform: rotate(180deg) translateX(50%);
-ms-transform: rotate(180deg) translateX(50%);
-o-transform: rotate(180deg) translateX(50%);
transform: rotate(180deg) translateX(50%);
top:2px;
left: 50%;
}
.bx-pos-parameter-bottom-center:before{
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
transform: translateX(-50%);
bottom:2px;
left: 50%;
}
.bx-pos-parameter-bottom-right {
bottom: 0;
right: 0;
}
.bx-pos-parameter-bottom-right:after{
-webkit-transform: rotate(135deg) translateX(-50%);
-moz-transform: rotate(135deg) translateX(-50%);
-ms-transform: rotate(135deg) translateX(-50%);
-o-transform: rotate(135deg) translateX(-50%);
transform: rotate(135deg) translateX(-50%);
left:2px;
top: 5px;
}
.bx-pos-parameter-bottom-right:before{
right:2px;
bottom: 2px;
}
.bx-pos-parameter.selected {
color: red;
}
.bx-pos-parameter-decore{
width:85%;
margin: 0 auto 5px;
height: 4px;
background: #F6F6F7;
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,379 @@
<?
if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED!==true) die();
use Bitrix\Main\Loader;
use Bitrix\Catalog;
use Bitrix\Iblock;
use Bitrix\Main\Web\Json;
CBitrixComponent::includeComponentClass($componentName);
$arTemplateParameters['COLUMNS_LIST_MOBILE'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_COLUMNS_LIST_MOBILE'),
'TYPE' => 'LIST',
'COLS' => 25,
'SIZE' => 7,
'MULTIPLE' => 'Y',
);
$themes = array();
if ($eshop = \Bitrix\Main\ModuleManager::isModuleInstalled('bitrix.eshop'))
{
$themes['site'] = GetMessage('CP_SBB_TPL_THEME_SITE');
}
$themeList = array(
'blue' => GetMessage('CP_SBB_TPL_THEME_BLUE'),
'green' => GetMessage('CP_SBB_TPL_THEME_GREEN'),
'red' => GetMessage('CP_SBB_TPL_THEME_RED'),
'yellow' => GetMessage('CP_SBB_TPL_THEME_YELLOW')
);
$dir = $_SERVER["DOCUMENT_ROOT"]."/bitrix/css/main/themes/";
if (is_dir($dir))
{
foreach ($themeList as $themeId => $themeName)
{
if (!is_file($dir.$themeId.'/style.css'))
continue;
$themes[$themeId] = $themeName;
}
}
$arTemplateParameters['DEFERRED_REFRESH'] = array(
'PARENT' => 'BASE',
'NAME' => GetMessage('CP_SBB_TPL_DEFERRED_REFRESH'),
'TYPE' => 'CHECKBOX',
'DEFAULT' => 'N'
);
$arTemplateParameters['USE_DYNAMIC_SCROLL'] = array(
'PARENT' => 'BASE',
'NAME' => GetMessage('CP_SBB_TPL_USE_DYNAMIC_SCROLL'),
'TYPE' => 'CHECKBOX',
'DEFAULT' => 'Y'
);
$arTemplateParameters['SHOW_FILTER'] = array(
'PARENT' => 'BASE',
'NAME' => GetMessage('CP_SBB_TPL_SHOW_FILTER'),
'TYPE' => 'CHECKBOX',
'DEFAULT' => 'Y'
);
$arTemplateParameters['SHOW_RESTORE'] = array(
'PARENT' => 'BASE',
'NAME' => GetMessage('CP_SBB_TPL_SHOW_RESTORE'),
'TYPE' => 'CHECKBOX',
'DEFAULT' => 'Y'
);
$arTemplateParameters['EMPTY_BASKET_HINT_PATH'] = [
'PARENT' => 'ADDITIONAL_SETTINGS',
"NAME" => GetMessage('CP_SBB_EMPTY_BASKET_HINT_PATH'),
"TYPE" => "STRING",
"DEFAULT" => "/"
];
$arTemplateParameters['TEMPLATE_THEME'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_TEMPLATE_THEME'),
'TYPE' => 'LIST',
'VALUES' => $themes,
'DEFAULT' => 'blue',
'ADDITIONAL_VALUES' => 'Y'
);
$arTemplateParameters['TOTAL_BLOCK_DISPLAY'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_TOTAL_BLOCK_DISPLAY'),
'TYPE' => 'LIST',
'VALUES' => array(
'top' => GetMessage('CP_SBB_TPL_TOTAL_BLOCK_DISPLAY_TOP'),
'bottom' => GetMessage('CP_SBB_TPL_TOTAL_BLOCK_DISPLAY_BOTTOM')
),
'DEFAULT' => array('top'),
'MULTIPLE' => 'Y'
);
$arTemplateParameters['DISPLAY_MODE'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_DISPLAY_MODE'),
'TYPE' => 'LIST',
'VALUES' => array(
'extended' => GetMessage('CP_SBB_TPL_DISPLAY_MODE_EXTENDED'),
'compact' => GetMessage('CP_SBB_TPL_DISPLAY_MODE_COMPACT')
),
'DEFAULT' => 'extended'
);
$arTemplateParameters['PRICE_DISPLAY_MODE'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_PRICE_DISPLAY_MODE'),
'TYPE' => 'CHECKBOX',
'DEFAULT' => 'Y'
);
$arTemplateParameters['SHOW_DISCOUNT_PERCENT'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_SHOW_DISCOUNT_PERCENT'),
'TYPE' => 'CHECKBOX',
'REFRESH' => 'Y',
'DEFAULT' => 'Y'
);
if (!isset($arCurrentValues['SHOW_DISCOUNT_PERCENT']) || $arCurrentValues['SHOW_DISCOUNT_PERCENT'] === 'Y')
{
$arTemplateParameters['DISCOUNT_PERCENT_POSITION'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_DISCOUNT_PERCENT_POSITION'),
'TYPE' => 'CUSTOM',
'JS_FILE' => CBitrixBasketComponent::getSettingsScript($componentPath, 'position'),
'JS_EVENT' => 'initPositionControl',
'JS_DATA' => Json::encode(
array(
'positions' => array(
'top-left', 'top-center', 'top-right',
'middle-left', 'middle-center', 'middle-right',
'bottom-left', 'bottom-center', 'bottom-right'
),
'className' => 'bx-pos-parameter-block-circle'
)
),
'DEFAULT' => 'bottom-right'
);
}
$arTemplateParameters['PRODUCT_BLOCKS_ORDER'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_PRODUCT_BLOCKS_ORDER'),
'TYPE' => 'CUSTOM',
'JS_FILE' => CBitrixBasketComponent::getSettingsScript($componentPath, 'dragdrop_order'),
'JS_EVENT' => 'initDraggableOrderControl',
'JS_DATA' => Json::encode(array(
'props' => GetMessage('CP_SBB_TPL_PRODUCT_BLOCK_PROPERTIES'),
'sku' => GetMessage('CP_SBB_TPL_PRODUCT_BLOCK_SKU'),
'columns' => GetMessage('CP_SBB_TPL_PRODUCT_BLOCK_COLUMNS')
)),
'DEFAULT' => 'props,sku,columns'
);
$arTemplateParameters['USE_PRICE_ANIMATION'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_USE_PRICE_ANIMATION'),
'TYPE' => 'CHECKBOX',
'DEFAULT' => 'Y'
);
$arTemplateParameters['LABEL_PROP'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_LABEL_PROP'),
'TYPE' => 'LIST',
'MULTIPLE' => 'Y',
'ADDITIONAL_VALUES' => 'N',
'COLS' => 25,
'SIZE' => 7,
'REFRESH' => 'Y'
);
if (!empty($arCurrentValues['LABEL_PROP']))
{
$arTemplateParameters['LABEL_PROP_MOBILE'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_LABEL_PROP_MOBILE'),
'TYPE' => 'LIST',
'MULTIPLE' => 'Y',
'ADDITIONAL_VALUES' => 'N',
'COLS' => 25,
'SIZE' => 7,
'REFRESH' => 'N',
);
$arTemplateParameters['LABEL_PROP_POSITION'] = array(
'PARENT' => 'VISUAL',
'NAME' => GetMessage('CP_SBB_TPL_LABEL_PROP_POSITION'),
'TYPE' => 'CUSTOM',
'JS_FILE' => CBitrixBasketComponent::getSettingsScript($componentPath, 'position'),
'JS_EVENT' => 'initPositionControl',
'JS_DATA' => Json::encode(
array(
'positions' => array(
'top-left', 'top-center', 'top-right',
'middle-left', 'middle-center', 'middle-right',
'bottom-left', 'bottom-center', 'bottom-right'
),
'className' => ''
)
),
'DEFAULT' => 'top-left'
);
}
if (Loader::includeModule('catalog') && !Iblock\Model\PropertyFeature::isEnabledFeatures())
{
$arSKU = false;
$boolSKU = false;
$arOfferProps = array();
$arSkuData = array();
// get iblock props from all catalog iblocks including sku iblocks
$arSkuIblockIDs = array();
$iterator = \Bitrix\Catalog\CatalogIblockTable::getList(array(
'select' => array('IBLOCK_ID', 'PRODUCT_IBLOCK_ID', 'SKU_PROPERTY_ID'),
'filter' => array('!=PRODUCT_IBLOCK_ID' => 0)
));
while ($row = $iterator->fetch())
{
$boolSKU = true;
$arSkuIblockIDs[] = $row['IBLOCK_ID'];
$arSkuData[$row['IBLOCK_ID']] = $row;
}
unset($row, $iterator);
// iblock props
$arProps = array();
foreach ($arSkuIblockIDs as $iblockID)
{
$dbProps = CIBlockProperty::GetList(
array(
"SORT"=>"ASC",
"NAME"=>"ASC"
),
array(
"IBLOCK_ID" => $iblockID,
"ACTIVE" => "Y",
"CHECK_PERMISSIONS" => "N",
)
);
while ($arProp = $dbProps->GetNext())
{
if ($arProp['ID'] == $arSkuData[$iblockID]["SKU_PROPERTY_ID"])
continue;
if ($arProp['XML_ID'] == 'CML2_LINK')
continue;
$strPropName = '['.$arProp['ID'].'] '.('' != $arProp['CODE'] ? '['.$arProp['CODE'].']' : '').' '.$arProp['~NAME'];
if ($arProp['PROPERTY_TYPE'] != 'F')
{
$arOfferProps[$arProp['CODE']] = $strPropName;
}
}
if (!empty($arOfferProps) && is_array($arOfferProps))
{
$arTemplateParameters['OFFERS_PROPS'] = array(
'PARENT' => 'OFFERS_PROPS',
'NAME' => GetMessage('CP_SBB_TPL_PROPERTIES_RECALCULATE_BASKET'),
'TYPE' => 'LIST',
'MULTIPLE' => 'Y',
'SIZE' => '7',
'ADDITIONAL_VALUES' => 'N',
'REFRESH' => 'N',
'DEFAULT' => '-',
'VALUES' => $arOfferProps
);
}
}
}
$arTemplateParameters['USE_ENHANCED_ECOMMERCE'] = array(
'PARENT' => 'ANALYTICS_SETTINGS',
'NAME' => GetMessage('CP_SBB_TPL_USE_ENHANCED_ECOMMERCE'),
'TYPE' => 'CHECKBOX',
'REFRESH' => 'Y',
'DEFAULT' => 'N'
);
if (isset($arCurrentValues['USE_ENHANCED_ECOMMERCE']) && $arCurrentValues['USE_ENHANCED_ECOMMERCE'] === 'Y')
{
if (Loader::includeModule('catalog'))
{
$arIblockIDs = array();
$arIblockNames = array();
$catalogIterator = Catalog\CatalogIblockTable::getList(array(
'select' => array('IBLOCK_ID', 'NAME' => 'IBLOCK.NAME'),
'order' => array('IBLOCK_ID' => 'ASC')
));
while ($catalog = $catalogIterator->fetch())
{
$catalog['IBLOCK_ID'] = (int) $catalog['IBLOCK_ID'];
$arIblockIDs[] = $catalog['IBLOCK_ID'];
$arIblockNames[$catalog['IBLOCK_ID']] = $catalog['NAME'];
}
unset($catalog, $catalogIterator);
if (!empty($arIblockIDs))
{
$arProps = array();
$propertyIterator = Iblock\PropertyTable::getList(array(
'select' => array('ID', 'CODE', 'NAME', 'IBLOCK_ID'),
'filter' => array('@IBLOCK_ID' => $arIblockIDs, '=ACTIVE' => 'Y', '!=XML_ID' => CIBlockPropertyTools::XML_SKU_LINK),
'order' => array('IBLOCK_ID' => 'ASC', 'SORT' => 'ASC', 'ID' => 'ASC')
));
while ($property = $propertyIterator->fetch())
{
$property['ID'] = (int) $property['ID'];
$property['IBLOCK_ID'] = (int) $property['IBLOCK_ID'];
$property['CODE'] = (string) $property['CODE'];
if ($property['CODE'] == '')
{
$property['CODE'] = $property['ID'];
}
if (!isset($arProps[$property['CODE']]))
{
$arProps[$property['CODE']] = array(
'CODE' => $property['CODE'],
'TITLE' => $property['NAME'].' ['.$property['CODE'].']',
'ID' => array($property['ID']),
'IBLOCK_ID' => array($property['IBLOCK_ID'] => $property['IBLOCK_ID']),
'IBLOCK_TITLE' => array($property['IBLOCK_ID'] => $arIblockNames[$property['IBLOCK_ID']]),
'COUNT' => 1
);
}
else
{
$arProps[$property['CODE']]['ID'][] = $property['ID'];
$arProps[$property['CODE']]['IBLOCK_ID'][$property['IBLOCK_ID']] = $property['IBLOCK_ID'];
if ($arProps[$property['CODE']]['COUNT'] < 2)
{
$arProps[$property['CODE']]['IBLOCK_TITLE'][$property['IBLOCK_ID']] = $arIblockNames[$property['IBLOCK_ID']];
}
$arProps[$property['CODE']]['COUNT']++;
}
}
unset($property, $propertyIterator, $arIblockNames, $arIblockIDs);
$propList = array();
foreach ($arProps as $property)
{
$iblockList = '';
if ($property['COUNT'] > 1)
{
$iblockList = ($property['COUNT'] > 2 ? ' ( ... )' : ' ('.implode(', ', $property['IBLOCK_TITLE']).')');
}
$propList['PROPERTY_'.$property['CODE']] = $property['TITLE'].$iblockList;
}
unset($property, $arProps);
}
}
$arTemplateParameters['DATA_LAYER_NAME'] = array(
'PARENT' => 'ANALYTICS_SETTINGS',
'NAME' => GetMessage('CP_SBB_TPL_DATA_LAYER_NAME'),
'TYPE' => 'STRING',
'DEFAULT' => 'dataLayer'
);
if (!empty($propList))
{
$arTemplateParameters['BRAND_PROPERTY'] = array(
'PARENT' => 'ANALYTICS_SETTINGS',
'NAME' => GetMessage('CP_SBB_TPL_BRAND_PROPERTY'),
'TYPE' => 'LIST',
'MULTIPLE' => 'N',
'DEFAULT' => '',
'VALUES' => array('' => '') + $propList
);
}
}

View File

@ -0,0 +1,581 @@
<?if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
/** @var array $arParams */
/** @var array $arResult */
/** @var array $arUrls */
/** @var array $arHeaders */
use Bitrix\Sale\DiscountCouponsManager;
if (!empty($arResult["ERROR_MESSAGE"]))
ShowError($arResult["ERROR_MESSAGE"]);
$bDelayColumn = false;
$bDeleteColumn = false;
$bWeightColumn = false;
$bPropsColumn = false;
$bPriceType = false;
if ($normalCount > 0):
?>
<div id="basket_items_list">
<div class="bx_ordercart_order_table_container">
<table id="basket_items">
<thead>
<tr>
<td class="margin"></td>
<?
foreach ($arResult["GRID"]["HEADERS"] as $id => $arHeader):
$arHeaders[] = $arHeader["id"];
// remember which values should be shown not in the separate columns, but inside other columns
if (in_array($arHeader["id"], array("TYPE")))
{
$bPriceType = true;
continue;
}
elseif ($arHeader["id"] == "PROPS")
{
$bPropsColumn = true;
continue;
}
elseif ($arHeader["id"] == "DELAY")
{
$bDelayColumn = true;
continue;
}
elseif ($arHeader["id"] == "DELETE")
{
$bDeleteColumn = true;
continue;
}
elseif ($arHeader["id"] == "WEIGHT")
{
$bWeightColumn = true;
}
if ($arHeader["id"] == "NAME"):
?>
<td class="item" colspan="2" id="col_<?=$arHeader["id"];?>">
<?
elseif ($arHeader["id"] == "PRICE"):
?>
<td class="price" id="col_<?=$arHeader["id"];?>">
<?
else:
?>
<td class="custom" id="col_<?=$arHeader["id"];?>">
<?
endif;
?>
<?=$arHeader["name"]; ?>
</td>
<?
endforeach;
if ($bDeleteColumn || $bDelayColumn):
?>
<td class="custom"></td>
<?
endif;
?>
<td class="margin"></td>
</tr>
</thead>
<tbody>
<?
$skipHeaders = array('PROPS', 'DELAY', 'DELETE', 'TYPE');
foreach ($arResult["GRID"]["ROWS"] as $k => $arItem):
if ($arItem["DELAY"] == "N" && $arItem["CAN_BUY"] == "Y"):
?>
<tr id="<?=$arItem["ID"]?>"
data-item-name="<?=$arItem["NAME"]?>"
data-item-brand="<?=$arItem[$arParams['BRAND_PROPERTY']."_VALUE"]?>"
data-item-price="<?=$arItem["PRICE"]?>"
data-item-currency="<?=$arItem["CURRENCY"]?>"
>
<td class="margin"></td>
<?
foreach ($arResult["GRID"]["HEADERS"] as $id => $arHeader):
if (in_array($arHeader["id"], $skipHeaders)) // some values are not shown in the columns in this template
continue;
if ($arHeader["name"] == '')
$arHeader["name"] = GetMessage("SALE_".$arHeader["id"]);
if ($arHeader["id"] == "NAME"):
?>
<td class="itemphoto">
<div class="bx_ordercart_photo_container">
<?
if (strlen($arItem["PREVIEW_PICTURE_SRC"]) > 0):
$url = $arItem["PREVIEW_PICTURE_SRC"];
elseif (strlen($arItem["DETAIL_PICTURE_SRC"]) > 0):
$url = $arItem["DETAIL_PICTURE_SRC"];
else:
$url = $templateFolder."/images/no_photo.png";
endif;
if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?><a href="<?=$arItem["DETAIL_PAGE_URL"] ?>"><?endif;?>
<div class="bx_ordercart_photo" style="background-image:url('<?=$url?>')"></div>
<?if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?></a><?endif;?>
</div>
<?
if (!empty($arItem["BRAND"])):
?>
<div class="bx_ordercart_brand">
<img alt="" src="<?=$arItem["BRAND"]?>" />
</div>
<?
endif;
?>
</td>
<td class="item">
<h2 class="bx_ordercart_itemtitle">
<?if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?><a href="<?=$arItem["DETAIL_PAGE_URL"] ?>"><?endif;?>
<?=$arItem["NAME"]?>
<?if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?></a><?endif;?>
</h2>
<div class="bx_ordercart_itemart">
<?
if ($bPropsColumn):
foreach ($arItem["PROPS"] as $val):
if (is_array($arItem["SKU_DATA"]))
{
$bSkip = false;
foreach ($arItem["SKU_DATA"] as $propId => $arProp)
{
if ($arProp["CODE"] == $val["CODE"])
{
$bSkip = true;
break;
}
}
if ($bSkip)
continue;
}
echo htmlspecialcharsbx($val["NAME"]).":&nbsp;<span>".$val["VALUE"]."</span><br/>";
endforeach;
endif;
?>
</div>
<?
if (is_array($arItem["SKU_DATA"]) && !empty($arItem["SKU_DATA"])):
$propsMap = array();
foreach ($arItem["PROPS"] as $propValue)
{
if (empty($propValue) || !is_array($propValue))
continue;
$propsMap[$propValue['CODE']] = (isset($propValue['~VALUE']) ? $propValue['~VALUE'] : $propValue['VALUE']);
}
unset($propValue);
foreach ($arItem["SKU_DATA"] as $propId => $arProp):
$selectedIndex = 0;
// if property contains images or values
$isImgProperty = false;
if (!empty($arProp["VALUES"]) && is_array($arProp["VALUES"]))
{
$counter = 0;
foreach ($arProp["VALUES"] as $id => $arVal)
{
$counter++;
if (isset($propsMap[$arProp['CODE']]))
{
if ($propsMap[$arProp['CODE']] == $arVal['NAME'] || $propsMap[$arProp['CODE']] == $arVal['XML_ID'])
$selectedIndex = $counter;
}
if (!empty($arVal["PICT"]) && is_array($arVal["PICT"])
&& !empty($arVal["PICT"]['SRC']))
{
$isImgProperty = true;
}
}
unset($counter);
}
$countValues = count($arProp["VALUES"]);
if ($countValues > 5)
{
$full = "full";
$fullWidth = ($countValues*20).'%';
$itemWidth = (100/$countValues).'%';
}
else
{
$full = "";
$fullWidth = '100%';
$itemWidth = '20%';
}
$marginLeft = 0;
if ($countValues > 5 && $selectedIndex > 5)
$marginLeft = ((5 - $selectedIndex)*20).'%';
if ($isImgProperty): // iblock element relation property
?>
<div class="bx_item_detail_scu_small_noadaptive <?=$full?>">
<span class="bx_item_section_name_gray">
<?=htmlspecialcharsbx($arProp["NAME"])?>:
</span>
<div class="bx_scu_scroller_container">
<div class="bx_scu">
<ul id="prop_<?=$arProp["CODE"]?>_<?=$arItem["ID"]?>"
style="width: <?=$fullWidth; ?>; margin-left: <?=$marginLeft; ?>"
class="sku_prop_list"
>
<?
$counter = 0;
foreach ($arProp["VALUES"] as $valueId => $arSkuValue):
$counter++;
$selected = ($selectedIndex == $counter ? ' bx_active' : '');
?>
<li style="width: <?=$itemWidth; ?>; padding-top: <?=$itemWidth; ?>;"
class="sku_prop<?=$selected?>"
data-sku-selector="Y"
data-value-id="<?=$arSkuValue["XML_ID"]?>"
data-sku-name="<?=htmlspecialcharsbx($arSkuValue["NAME"]); ?>"
data-element="<?=$arItem["ID"]?>"
data-property="<?=$arProp["CODE"]?>"
>
<a href="javascript:void(0)" class="cnt"><span class="cnt_item" style="background-image:url(<?=$arSkuValue["PICT"]["SRC"];?>)"></span></a>
</li>
<?
endforeach;
unset($counter);
?>
</ul>
</div>
<div class="bx_slide_left" onclick="leftScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
<div class="bx_slide_right" onclick="rightScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
</div>
</div>
<?
else:
?>
<div class="bx_item_detail_size_small_noadaptive <?=$full?>">
<span class="bx_item_section_name_gray">
<?=htmlspecialcharsbx($arProp["NAME"])?>:
</span>
<div class="bx_size_scroller_container">
<div class="bx_size">
<ul id="prop_<?=$arProp["CODE"]?>_<?=$arItem["ID"]?>"
style="width: <?=$fullWidth; ?>; margin-left: <?=$marginLeft; ?>;"
class="sku_prop_list"
>
<?
if (!empty($arProp["VALUES"]))
{
$counter = 0;
foreach ($arProp["VALUES"] as $valueId => $arSkuValue):
$counter++;
$selected = ($selectedIndex == $counter ? ' bx_active' : '');
$skuValueName = htmlspecialcharsbx($arSkuValue['NAME']);
?>
<li style="width: <?=$itemWidth; ?>;"
class="sku_prop<?=$selected?>"
data-sku-selector="Y"
data-value-id="<?=($arProp['TYPE'] == 'S' && $arProp['USER_TYPE'] == 'directory' ? $arSkuValue['XML_ID'] : $skuValueName); ?>"
data-sku-name="<?=$skuValueName; ?>"
data-element="<?=$arItem["ID"]?>"
data-property="<?=$arProp["CODE"]?>"
>
<a href="javascript:void(0)" class="cnt"><?=$skuValueName; ?></a>
</li>
<?
unset($skuValueName);
endforeach;
unset($counter);
}
?>
</ul>
</div>
<div class="bx_slide_left" onclick="leftScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
<div class="bx_slide_right" onclick="rightScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
</div>
</div>
<?
endif;
endforeach;
endif;
?>
</td>
<?
elseif ($arHeader["id"] == "QUANTITY"):
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<div class="centered">
<table cellspacing="0" cellpadding="0" class="counter">
<tr>
<td>
<?
$ratio = isset($arItem["MEASURE_RATIO"]) ? $arItem["MEASURE_RATIO"] : 0;
$useFloatQuantity = ($arParams["QUANTITY_FLOAT"] == "Y") ? true : false;
$useFloatQuantityJS = ($useFloatQuantity ? "true" : "false");
?>
<input
type="text"
size="3"
id="QUANTITY_INPUT_<?=$arItem["ID"]?>"
name="QUANTITY_INPUT_<?=$arItem["ID"]?>"
maxlength="18"
style="max-width: 50px"
value="<?=$arItem["QUANTITY"]?>"
onchange="updateQuantity('QUANTITY_INPUT_<?=$arItem["ID"]?>', '<?=$arItem["ID"]?>', <?=$ratio?>, <?=$useFloatQuantityJS?>)"
>
</td>
<?
if (!isset($arItem["MEASURE_RATIO"]))
{
$arItem["MEASURE_RATIO"] = 1;
}
if (
floatval($arItem["MEASURE_RATIO"]) != 0
):
?>
<td id="basket_quantity_control">
<div class="basket_quantity_control">
<a href="javascript:void(0);" class="plus" onclick="setQuantity(<?=$arItem["ID"]?>, <?=$arItem["MEASURE_RATIO"]?>, 'up', <?=$useFloatQuantityJS?>);"></a>
<a href="javascript:void(0);" class="minus" onclick="setQuantity(<?=$arItem["ID"]?>, <?=$arItem["MEASURE_RATIO"]?>, 'down', <?=$useFloatQuantityJS?>);"></a>
</div>
</td>
<?
endif;
if (isset($arItem["MEASURE_TEXT"]))
{
?>
<td style="text-align: left"><?=htmlspecialcharsbx($arItem["MEASURE_TEXT"])?></td>
<?
}
?>
</tr>
</table>
</div>
<input type="hidden" id="QUANTITY_<?=$arItem['ID']?>" name="QUANTITY_<?=$arItem['ID']?>" value="<?=$arItem["QUANTITY"]?>" />
</td>
<?
elseif ($arHeader["id"] == "PRICE"):
?>
<td class="price">
<div class="current_price" id="current_price_<?=$arItem["ID"]?>">
<?=$arItem["PRICE_FORMATED"]?>
</div>
<div class="old_price" id="old_price_<?=$arItem["ID"]?>">
<?if (floatval($arItem["DISCOUNT_PRICE_PERCENT"]) > 0):?>
<?=$arItem["FULL_PRICE_FORMATED"]?>
<?endif;?>
</div>
<?if ($bPriceType && strlen($arItem["NOTES"]) > 0):?>
<div class="type_price"><?=GetMessage("SALE_TYPE")?></div>
<div class="type_price_value"><?=$arItem["NOTES"]?></div>
<?endif;?>
</td>
<?
elseif ($arHeader["id"] == "DISCOUNT"):
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<div id="discount_value_<?=$arItem["ID"]?>"><?=$arItem["DISCOUNT_PRICE_PERCENT_FORMATED"]?></div>
</td>
<?
elseif ($arHeader["id"] == "WEIGHT"):
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<?=$arItem["WEIGHT_FORMATED"]?>
</td>
<?
else:
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<?
if ($arHeader["id"] == "SUM"):
?>
<div id="sum_<?=$arItem["ID"]?>">
<?
endif;
echo $arItem[$arHeader["id"]];
if ($arHeader["id"] == "SUM"):
?>
</div>
<?
endif;
?>
</td>
<?
endif;
endforeach;
if ($bDelayColumn || $bDeleteColumn):
?>
<td class="control">
<?
if ($bDeleteColumn):
?>
<a href="<?=str_replace("#ID#", $arItem["ID"], $arUrls["delete"])?>"
onclick="return deleteProductRow(this)">
<?=GetMessage("SALE_DELETE")?>
</a>
<br />
<?
endif;
if ($bDelayColumn):
?>
<a href="<?=str_replace("#ID#", $arItem["ID"], $arUrls["delay"])?>"><?=GetMessage("SALE_DELAY")?></a>
<?
endif;
?>
</td>
<?
endif;
?>
<td class="margin"></td>
</tr>
<?
endif;
endforeach;
?>
</tbody>
</table>
</div>
<input type="hidden" id="column_headers" value="<?=htmlspecialcharsbx(implode($arHeaders, ","))?>" />
<input type="hidden" id="offers_props" value="<?=htmlspecialcharsbx(implode($arParams["OFFERS_PROPS"], ","))?>" />
<input type="hidden" id="action_var" value="<?=htmlspecialcharsbx($arParams["ACTION_VARIABLE"])?>" />
<input type="hidden" id="quantity_float" value="<?=($arParams["QUANTITY_FLOAT"] == "Y") ? "Y" : "N"?>" />
<input type="hidden" id="price_vat_show_value" value="<?=($arParams["PRICE_VAT_SHOW_VALUE"] == "Y") ? "Y" : "N"?>" />
<input type="hidden" id="hide_coupon" value="<?=($arParams["HIDE_COUPON"] == "Y") ? "Y" : "N"?>" />
<input type="hidden" id="use_prepayment" value="<?=($arParams["USE_PREPAYMENT"] == "Y") ? "Y" : "N"?>" />
<input type="hidden" id="auto_calculation" value="<?=($arParams["AUTO_CALCULATION"] == "N") ? "N" : "Y"?>" />
<div class="bx_ordercart_order_pay">
<div class="bx_ordercart_order_pay_left" id="coupons_block">
<?
if ($arParams["HIDE_COUPON"] != "Y")
{
?>
<div class="bx_ordercart_coupon">
<span><?=GetMessage("STB_COUPON_PROMT")?></span><input type="text" id="coupon" name="COUPON" value="" onchange="enterCoupon();">&nbsp;<a class="bx_bt_button bx_big" href="javascript:void(0)" onclick="enterCoupon();" title="<?=GetMessage('SALE_COUPON_APPLY_TITLE'); ?>"><?=GetMessage('SALE_COUPON_APPLY'); ?></a>
</div><?
if (!empty($arResult['COUPON_LIST']))
{
foreach ($arResult['COUPON_LIST'] as $oneCoupon)
{
$couponClass = 'disabled';
switch ($oneCoupon['STATUS'])
{
case DiscountCouponsManager::STATUS_NOT_FOUND:
case DiscountCouponsManager::STATUS_FREEZE:
$couponClass = 'bad';
break;
case DiscountCouponsManager::STATUS_APPLYED:
$couponClass = 'good';
break;
}
?><div class="bx_ordercart_coupon"><input disabled readonly type="text" name="OLD_COUPON[]" value="<?=htmlspecialcharsbx($oneCoupon['COUPON']);?>" class="<? echo $couponClass; ?>"><span class="<? echo $couponClass; ?>" data-coupon="<? echo htmlspecialcharsbx($oneCoupon['COUPON']); ?>"></span><div class="bx_ordercart_coupon_notes"><?
if (isset($oneCoupon['CHECK_CODE_TEXT']))
{
echo (is_array($oneCoupon['CHECK_CODE_TEXT']) ? implode('<br>', $oneCoupon['CHECK_CODE_TEXT']) : $oneCoupon['CHECK_CODE_TEXT']);
}
?></div></div><?
}
unset($couponClass, $oneCoupon);
}
}
else
{
?>&nbsp;<?
}
?>
</div>
<div class="bx_ordercart_order_pay_right">
<table class="bx_ordercart_order_sum">
<?if ($bWeightColumn && floatval($arResult['allWeight']) > 0):?>
<tr>
<td class="custom_t1"><?=GetMessage("SALE_TOTAL_WEIGHT")?></td>
<td class="custom_t2" id="allWeight_FORMATED"><?=$arResult["allWeight_FORMATED"]?>
</td>
</tr>
<?endif;?>
<?if ($arParams["PRICE_VAT_SHOW_VALUE"] == "Y"):?>
<tr>
<td><?echo GetMessage('SALE_VAT_EXCLUDED')?></td>
<td id="allSum_wVAT_FORMATED"><?=$arResult["allSum_wVAT_FORMATED"]?></td>
</tr>
<?
$showTotalPrice = (float) $arResult["DISCOUNT_PRICE_ALL"] > 0;
?>
<tr style="display: <?=($showTotalPrice ? 'table-row' : 'none'); ?>;">
<td class="custom_t1"></td>
<td class="custom_t2" style="text-decoration:line-through; color:#828282;" id="PRICE_WITHOUT_DISCOUNT">
<?=($showTotalPrice ? $arResult["PRICE_WITHOUT_DISCOUNT"] : ''); ?>
</td>
</tr>
<?
if (floatval($arResult['allVATSum']) > 0):
?>
<tr>
<td><?echo GetMessage('SALE_VAT')?></td>
<td id="allVATSum_FORMATED"><?=$arResult["allVATSum_FORMATED"]?></td>
</tr>
<?
endif;
?>
<?endif;?>
<tr>
<td class="fwb"><?=GetMessage("SALE_TOTAL")?></td>
<td class="fwb" id="allSum_FORMATED"><?=str_replace(" ", "&nbsp;", $arResult["allSum_FORMATED"])?></td>
</tr>
</table>
<div style="clear:both;"></div>
</div>
<div style="clear:both;"></div>
<div class="bx_ordercart_order_pay_center">
<?if ($arParams["USE_PREPAYMENT"] == "Y" && strlen($arResult["PREPAY_BUTTON"]) > 0):?>
<?=$arResult["PREPAY_BUTTON"]?>
<span><?=GetMessage("SALE_OR")?></span>
<?endif;?>
<?
if ($arParams["AUTO_CALCULATION"] != "Y")
{
?>
<a href="javascript:void(0)" onclick="updateBasket();" class="checkout refresh"><?=GetMessage("SALE_REFRESH")?></a>
<?
}
?>
<a href="javascript:void(0)" onclick="checkOut();" class="checkout"><?=GetMessage("SALE_ORDER")?></a>
</div>
</div>
</div>
<?
else:
?>
<div id="basket_items_list">
<table>
<tbody>
<tr>
<td style="text-align:center">
<div class=""><?=GetMessage("SALE_NO_ITEMS");?></div>
</td>
</tr>
</tbody>
</table>
</div>
<?
endif;

View File

@ -0,0 +1,85 @@
<?if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>
<b><?= GetMessage("SALE_OTLOG_TITLE")?></b><br /><br />
<table class="sale_basket_basket data-table">
<tr>
<?if (in_array("NAME", $arParams["COLUMNS_LIST"])):?>
<th align="center"><?= GetMessage("SALE_NAME")?></th>
<?endif;?>
<?if (in_array("PROPS", $arParams["COLUMNS_LIST"])):?>
<th align="center"><?= GetMessage("SALE_PROPS")?></th>
<?endif;?>
<?if (in_array("PRICE", $arParams["COLUMNS_LIST"])):?>
<th align="center"><?= GetMessage("SALE_PRICE")?></th>
<?endif;?>
<?if (in_array("TYPE", $arParams["COLUMNS_LIST"])):?>
<th align="center"><?= GetMessage("SALE_PRICE_TYPE")?></th>
<?endif;?>
<?if (in_array("QUANTITY", $arParams["COLUMNS_LIST"])):?>
<th align="center"><?= GetMessage("SALE_QUANTITY")?></th>
<?endif;?>
<?if (in_array("DELETE", $arParams["COLUMNS_LIST"])):?>
<th align="center"><?= GetMessage("SALE_DELETE")?></th>
<?endif;?>
<?if (in_array("DELAY", $arParams["COLUMNS_LIST"])):?>
<th align="center"><?= GetMessage("SALE_OTLOG")?></th>
<?endif;?>
<?if (in_array("WEIGHT", $arParams["COLUMNS_LIST"])):?>
<th align="center"><?= GetMessage("SALE_WEIGHT")?></th>
<?endif;?>
</tr>
<?
foreach($arResult["ITEMS"]["DelDelCanBuy"] as $arBasketItems)
{
?>
<tr>
<?if (in_array("NAME", $arParams["COLUMNS_LIST"])):?>
<td><?
if (strlen($arBasketItems["DETAIL_PAGE_URL"])>0):
?><a href="<?echo $arBasketItems["DETAIL_PAGE_URL"] ?>"><?
endif;
?><b><?echo $arBasketItems["NAME"]?></b><?
if (strlen($arBasketItems["DETAIL_PAGE_URL"])>0):
?></a><?
endif;
?></td>
<?endif;?>
<?if (in_array("PROPS", $arParams["COLUMNS_LIST"])):?>
<td>
<?
foreach($arBasketItems["PROPS"] as $val)
{
echo $val["NAME"].": ".$val["VALUE"]."<br />";
}
?>
</td>
<?endif;?>
<?if (in_array("PRICE", $arParams["COLUMNS_LIST"])):?>
<td align="right"><?=$arBasketItems["PRICE_FORMATED"]?></td>
<?endif;?>
<?if (in_array("TYPE", $arParams["COLUMNS_LIST"])):?>
<td><?echo $arBasketItems["NOTES"]?></td>
<?endif;?>
<?if (in_array("QUANTITY", $arParams["COLUMNS_LIST"])):?>
<td align="center"><?echo $arBasketItems["QUANTITY"]?></td>
<?endif;?>
<?if (in_array("DELETE", $arParams["COLUMNS_LIST"])):?>
<td align="center"><input type="checkbox" name="DELETE_<?echo $arBasketItems["ID"] ?>" value="Y"></td>
<?endif;?>
<?if (in_array("DELAY", $arParams["COLUMNS_LIST"])):?>
<td align="center"><input type="checkbox" name="DELAY_<?echo $arBasketItems["ID"] ?>" value="Y" checked></td>
<?endif;?>
<?if (in_array("WEIGHT", $arParams["COLUMNS_LIST"])):?>
<td align="right"><?echo $arBasketItems["WEIGHT_FORMATED"] ?></td>
<?endif;?>
</tr>
<?
}
?>
</table>
<br />
<div width="30%">
<input type="submit" value="<?= GetMessage("SALE_REFRESH")?>" name="BasketRefresh"><br />
<small><?= GetMessage("SALE_REFRESH_DESCR")?></small><br />
</div>
<br />
<?

View File

@ -0,0 +1,339 @@
<?if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
/** @var array $arParams */
/** @var array $arResult */
/** @var array $arUrls */
/** @var array $arHeaders */
$bPriceType = false;
$bDelayColumn = false;
$bDeleteColumn = false;
$bWeightColumn = false;
$bPropsColumn = false;
?>
<div id="basket_items_delayed" class="bx_ordercart_order_table_container" style="display:none">
<table id="delayed_items">
<thead>
<tr>
<td class="margin"></td>
<?
foreach ($arResult["GRID"]["HEADERS"] as $id => $arHeader):
if (in_array($arHeader["id"], array("TYPE"))) // some header columns are shown differently
{
$bPriceType = true;
continue;
}
elseif ($arHeader["id"] == "PROPS")
{
$bPropsColumn = true;
continue;
}
elseif ($arHeader["id"] == "DELAY")
{
continue;
}
elseif ($arHeader["id"] == "DELETE")
{
$bDeleteColumn = true;
continue;
}
elseif ($arHeader["id"] == "WEIGHT")
{
$bWeightColumn = true;
}
if ($arHeader["id"] == "NAME"):
?>
<td class="item" colspan="2">
<?
elseif ($arHeader["id"] == "PRICE"):
?>
<td class="price">
<?
else:
?>
<td class="custom">
<?
endif;
?>
<?=$arHeader["name"]; ?>
</td>
<?
endforeach;
if ($bDeleteColumn || $bDelayColumn):
?>
<td class="custom"></td>
<?
endif;
?>
<td class="margin"></td>
</tr>
</thead>
<tbody>
<?
$skipHeaders = array('PROPS', 'DELAY', 'DELETE', 'TYPE');
foreach ($arResult["GRID"]["ROWS"] as $k => $arItem):
if ($arItem["DELAY"] == "Y" && $arItem["CAN_BUY"] == "Y"):
?>
<tr id="<?=$arItem["ID"]?>">
<td class="margin"></td>
<?
foreach ($arResult["GRID"]["HEADERS"] as $id => $arHeader):
if (in_array($arHeader["id"], $skipHeaders)) // some values are not shown in columns in this template
continue;
if ($arHeader["id"] == "NAME"):
?>
<td class="itemphoto">
<div class="bx_ordercart_photo_container">
<?
if (strlen($arItem["PREVIEW_PICTURE_SRC"]) > 0):
$url = $arItem["PREVIEW_PICTURE_SRC"];
elseif (strlen($arItem["DETAIL_PICTURE_SRC"]) > 0):
$url = $arItem["DETAIL_PICTURE_SRC"];
else:
$url = $templateFolder."/images/no_photo.png";
endif;
if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?><a href="<?=$arItem["DETAIL_PAGE_URL"] ?>"><?endif;?>
<div class="bx_ordercart_photo" style="background-image:url('<?=$url?>')"></div>
<?if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?></a><?endif;?>
</div>
<?
if (!empty($arItem["BRAND"])):
?>
<div class="bx_ordercart_brand">
<img alt="" src="<?=$arItem["BRAND"]?>" />
</div>
<?
endif;
?>
</td>
<td class="item">
<h2 class="bx_ordercart_itemtitle">
<?if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?><a href="<?=$arItem["DETAIL_PAGE_URL"] ?>"><?endif;?>
<?=$arItem["NAME"]?>
<?if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?></a><?endif;?>
</h2>
<div class="bx_ordercart_itemart">
<?
if ($bPropsColumn):
foreach ($arItem["PROPS"] as $val):
if (is_array($arItem["SKU_DATA"]))
{
$bSkip = false;
foreach ($arItem["SKU_DATA"] as $propId => $arProp)
{
if ($arProp["CODE"] == $val["CODE"])
{
$bSkip = true;
break;
}
}
if ($bSkip)
continue;
}
echo htmlspecialcharsbx($val["NAME"]).":&nbsp;<span>".$val["VALUE"]."<span><br/>";
endforeach;
endif;
?>
</div>
<?
if (is_array($arItem["SKU_DATA"])):
$propsMap = array();
foreach ($arItem["PROPS"] as $propValue)
{
if (empty($propValue) || !is_array($propValue))
continue;
$propsMap[$propValue['CODE']] = (isset($propValue['~VALUE']) ? $propValue['~VALUE'] : $propValue['VALUE']);
}
unset($propValue);
foreach ($arItem["SKU_DATA"] as $propId => $arProp):
$selectedIndex = 0;
// is image property
$isImgProperty = false;
if (!empty($arProp["VALUES"]) && is_array($arProp["VALUES"]))
{
$counter = 0;
foreach ($arProp["VALUES"] as $id => $arVal)
{
$counter++;
if (isset($propsMap[$arProp['CODE']]))
{
if ($propsMap[$arProp['CODE']] == $arVal['NAME'] || $propsMap[$arProp['CODE']] == $arVal['XML_ID'])
$selectedIndex = $counter;
}
if (isset($arVal["PICT"]) && !empty($arVal["PICT"]))
{
$isImgProperty = true;
}
}
unset($counter);
}
$countValues = count($arProp["VALUES"]);
if ($countValues > 5)
{
$full = "full";
$fullWidth = ($countValues*20).'%';
$itemWidth = (100/$countValues).'%';
}
else
{
$full = "";
$fullWidth = '100%';
$itemWidth = '20%';
}
$marginLeft = 0;
if ($countValues > 5 && $selectedIndex > 5)
$marginLeft = ((5 - $selectedIndex)*20).'%';
if ($isImgProperty):
?>
<div class="bx_item_detail_scu_small_noadaptive <?=$full?>">
<span class="bx_item_section_name_gray">
<?=htmlspecialcharsbx($arProp["NAME"])?>:
</span>
<div class="bx_scu_scroller_container">
<div class="bx_scu">
<ul id="prop_<?=$arProp["CODE"]?>_<?=$arItem["ID"]?>" style="width: <?=$fullWidth; ?>; margin-left: <?=$marginLeft; ?>">
<?
$counter = 0;
foreach ($arProp["VALUES"] as $valueId => $arSkuValue):
$counter++;
$selected = ($selectedIndex == $counter ? ' class="bx_active"' : '');
?>
<li style="width: <?=$itemWidth; ?>; padding-top: <?=$itemWidth; ?>;"<?=$selected?>>
<a href="javascript:void(0)" class="cnt"><span class="cnt_item" style="background-image:url(<?=$arSkuValue["PICT"]["SRC"]; ?>)"></span></a>
</li>
<?
endforeach;
unset($counter);
?>
</ul>
</div>
<div class="bx_slide_left" onclick="leftScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
<div class="bx_slide_right" onclick="rightScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
</div>
</div>
<?
else:
?>
<div class="bx_item_detail_size_small_noadaptive <?=$full?>">
<span class="bx_item_section_name_gray">
<?=htmlspecialcharsbx($arProp["NAME"]);?>:
</span>
<div class="bx_size_scroller_container">
<div class="bx_size">
<ul id="prop_<?=$arProp["CODE"]?>_<?=$arItem["ID"]?>" style="width: <?=$fullWidth; ?>; margin-left: <?=$marginLeft; ?>;">
<?
$counter = 0;
foreach ($arProp["VALUES"] as $valueId => $arSkuValue):
$counter++;
$selected = ($selectedIndex == $counter ? ' class="bx_active"' : '');
?>
<li style="width: <?=$itemWidth; ?>;"<?=$selected?>>
<a href="javascript:void(0);" class="cnt"><?=htmlspecialcharsbx($arSkuValue["NAME"]); ?></a>
</li>
<?
endforeach;
unset($counter);
?>
</ul>
</div>
<div class="bx_slide_left" onclick="leftScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
<div class="bx_slide_right" onclick="rightScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
</div>
</div>
<?
endif;
endforeach;
endif;
?>
<input type="hidden" name="DELAY_<?=$arItem["ID"]?>" value="Y"/>
</td>
<?
elseif ($arHeader["id"] == "QUANTITY"):
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<div style="text-align: center;">
<?echo $arItem["QUANTITY"];
if (isset($arItem["MEASURE_TEXT"]))
echo "&nbsp;".htmlspecialcharsbx($arItem["MEASURE_TEXT"]);
?>
</div>
</td>
<?
elseif ($arHeader["id"] == "PRICE"):
?>
<td class="price">
<?if (doubleval($arItem["DISCOUNT_PRICE_PERCENT"]) > 0):?>
<div class="current_price"><?=$arItem["PRICE_FORMATED"]?></div>
<div class="old_price"><?=$arItem["FULL_PRICE_FORMATED"]?></div>
<?else:?>
<div class="current_price"><?=$arItem["PRICE_FORMATED"];?></div>
<?endif?>
<?if ($bPriceType && strlen($arItem["NOTES"]) > 0):?>
<div class="type_price"><?=GetMessage("SALE_TYPE")?></div>
<div class="type_price_value"><?=$arItem["NOTES"]?></div>
<?endif;?>
</td>
<?
elseif ($arHeader["id"] == "DISCOUNT"):
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<?=$arItem["DISCOUNT_PRICE_PERCENT_FORMATED"]?>
</td>
<?
elseif ($arHeader["id"] == "WEIGHT"):
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<?=$arItem["WEIGHT_FORMATED"]?>
</td>
<?
else:
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<?=$arItem[$arHeader["id"]]?>
</td>
<?
endif;
endforeach;
if ($bDelayColumn || $bDeleteColumn):
?>
<td class="control">
<a href="<?=str_replace("#ID#", $arItem["ID"], $arUrls["add"])?>"><?=GetMessage("SALE_ADD_TO_BASKET")?></a><br />
<?
if ($bDeleteColumn):
?>
<a href="<?=str_replace("#ID#", $arItem["ID"], $arUrls["delete"])?>"><?=GetMessage("SALE_DELETE")?></a><br />
<?
endif;
?>
</td>
<?
endif;
?>
<td class="margin"></td>
</tr>
<?
endif;
endforeach;
?>
</tbody>
</table>
</div>

View File

@ -0,0 +1,325 @@
<?if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
/** @var array $arParams */
/** @var array $arResult */
/** @var array $arUrls */
/** @var array $arHeaders */
$bPriceType = false;
$bDelayColumn = false;
$bDeleteColumn = false;
$bPropsColumn = false;
?>
<div id="basket_items_not_available" class="bx_ordercart_order_table_container" style="display:none">
<table>
<thead>
<tr>
<td class="margin"></td>
<?
foreach ($arResult["GRID"]["HEADERS"] as $id => $arHeader):
if (!in_array($arHeader["id"], array("NAME", "PROPS", "PRICE", "TYPE", "QUANTITY", "DELETE", "WEIGHT")))
continue;
if (in_array($arHeader["id"], array("TYPE")))
{
$bPriceType = true;
continue;
}
elseif ($arHeader["id"] == "PROPS") // some header columns are shown differently
{
$bPropsColumn = true;
continue;
}
elseif ($arHeader["id"] == "DELETE")
{
$bDeleteColumn = true;
continue;
}
elseif ($arHeader["id"] == "WEIGHT")
{
$bWeightColumn = true;
}
if ($arHeader["id"] == "NAME"):
?>
<td class="item" colspan="2">
<?
elseif ($arHeader["id"] == "PRICE"):
?>
<td class="price">
<?
else:
?>
<td class="custom">
<?
endif;
?>
<?=$arHeader["name"]; ?>
</td>
<?
endforeach;
if ($bDeleteColumn || $bDelayColumn):
?>
<td class="custom"></td>
<?
endif;
?>
<td class="margin"></td>
</tr>
</thead>
<tbody>
<?
$needHeaders = array('NAME', 'PRICE', 'QUANTITY', 'WEIGHT');
foreach ($arResult["GRID"]["ROWS"] as $k => $arItem):
if (isset($arItem["NOT_AVAILABLE"]) && $arItem["NOT_AVAILABLE"] == true):
?>
<tr>
<td class="margin"></td>
<?
foreach ($arResult["GRID"]["HEADERS"] as $id => $arHeader):
if (!in_array($arHeader["id"], $needHeaders))
continue;
if ($arHeader["id"] == "NAME"):
?>
<td class="itemphoto">
<div class="bx_ordercart_photo_container">
<?
if (strlen($arItem["PREVIEW_PICTURE_SRC"]) > 0):
$url = $arItem["PREVIEW_PICTURE_SRC"];
elseif (strlen($arItem["DETAIL_PICTURE_SRC"]) > 0):
$url = $arItem["DETAIL_PICTURE_SRC"];
else:
$url = $templateFolder."/images/no_photo.png";
endif;
if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?><a href="<?=$arItem["DETAIL_PAGE_URL"] ?>"><?endif;?>
<div class="bx_ordercart_photo" style="background-image:url('<?=$url?>')"></div>
<?if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?></a><?endif;?>
</div>
<?
if (!empty($arItem["BRAND"])):
?>
<div class="bx_ordercart_brand">
<img alt="" src="<?=$arItem["BRAND"]?>" />
</div>
<?
endif;
?>
</td>
<td class="item">
<h2 class="bx_ordercart_itemtitle">
<?if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?><a href="<?=$arItem["DETAIL_PAGE_URL"] ?>"><?endif;?>
<?=$arItem["NAME"]?>
<?if (strlen($arItem["DETAIL_PAGE_URL"]) > 0):?></a><?endif;?>
</h2>
<div class="bx_ordercart_itemart">
<?
if ($bPropsColumn):
foreach ($arItem["PROPS"] as $val):
if (is_array($arItem["SKU_DATA"]))
{
$bSkip = false;
foreach ($arItem["SKU_DATA"] as $propId => $arProp)
{
if ($arProp["CODE"] == $val["CODE"])
{
$bSkip = true;
break;
}
}
if ($bSkip)
continue;
}
echo htmlspecialcharsbx($val["NAME"]).":&nbsp;<span>".$val["VALUE"]."<span><br/>";
endforeach;
endif;
?>
</div>
<?
if (is_array($arItem["SKU_DATA"])):
$propsMap = array();
foreach ($arItem["PROPS"] as $propValue)
{
if (empty($propValue) || !is_array($propValue))
continue;
$propsMap[$propValue['CODE']] = $propValue['VALUE'];
}
unset($propValue);
foreach ($arItem["SKU_DATA"] as $propId => $arProp):
$selectedIndex = 0;
// is image property
$isImgProperty = false;
if (!empty($arProp["VALUES"]) && is_array($arProp["VALUES"]))
{
$counter = 0;
foreach ($arProp["VALUES"] as $id => $arVal)
{
$counter++;
if (isset($propsMap[$arProp['CODE']]))
{
if ($propsMap[$arProp['CODE']] == $arVal['NAME'] || $propsMap[$arProp['CODE']] == $arVal['XML_ID'])
$selectedIndex = $counter;
}
if (isset($arVal["PICT"]) && !empty($arVal["PICT"]))
{
$isImgProperty = true;
}
}
unset($counter);
}
$countValues = count($arProp["VALUES"]);
$full = ($countValues > 5) ? "full" : "";
$marginLeft = 0;
if ($countValues > 5 && $selectedIndex > 5)
$marginLeft = ((5 - $selectedIndex)*20).'%';
if ($isImgProperty):
?>
<div class="bx_item_detail_scu_small_noadaptive <?=$full?>">
<span class="bx_item_section_name_gray">
<?=htmlspecialcharsbx($arProp["NAME"])?>:
</span>
<div class="bx_scu_scroller_container">
<div class="bx_scu">
<ul id="prop_<?=$arProp["CODE"]?>_<?=$arItem["ID"]?>" style="width: 200%; margin-left: <?=$marginLeft; ?>">
<?
$counter = 0;
foreach ($arProp["VALUES"] as $valueId => $arSkuValue):
$counter++;
$selected = ($selectedIndex == $counter ? ' class="bx_active"' : '');
?>
<li style="width:10%;"<?=$selected?>>
<a href="javascript:void(0)" class="cnt"><span class="cnt_item" style="background-image:url(<?=$arSkuValue["PICT"]["SRC"];?>)"></span></a>
</li>
<?
endforeach;
unset($counter);
?>
</ul>
</div>
<div class="bx_slide_left" onclick="leftScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
<div class="bx_slide_right" onclick="rightScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
</div>
</div>
<?
else:
?>
<div class="bx_item_detail_size_small_noadaptive <?=$full?>">
<span class="bx_item_section_name_gray">
<?=htmlspecialcharsbx($arProp["NAME"])?>:
</span>
<div class="bx_size_scroller_container">
<div class="bx_size">
<ul id="prop_<?=$arProp["CODE"]?>_<?=$arItem["ID"]?>" style="width: 200%; margin-left: <?=$marginLeft; ?>">
<?
$counter = 0;
foreach ($arProp["VALUES"] as $valueId => $arSkuValue):
$counter++;
$selected = ($selectedIndex == $counter ? ' class="bx_active"' : '');
?>
<li style="width:10%;"<?=$selected?>>
<a href="javascript:void(0);" class="cnt"><?=$arSkuValue["NAME"]?></a>
</li>
<?
endforeach;
unset($counter);
?>
</ul>
</div>
<div class="bx_slide_left" onclick="leftScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
<div class="bx_slide_right" onclick="rightScroll('<?=$arProp["CODE"]?>', <?=$arItem["ID"]?>, <?=$countValues?>);"></div>
</div>
</div>
<?
endif;
endforeach;
endif;
?>
</td>
<?
elseif ($arHeader["id"] == "QUANTITY"):
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<div style="text-align: center;">
<?echo $arItem["QUANTITY"];
if (isset($arItem["MEASURE_TEXT"]))
echo "&nbsp;".htmlspecialcharsbx($arItem["MEASURE_TEXT"]);
?>
</div>
</td>
<?
elseif ($arHeader["id"] == "PRICE"):
?>
<td class="price">
<?if (doubleval($arItem["DISCOUNT_PRICE_PERCENT"]) > 0):?>
<div class="current_price"><?=$arItem["PRICE_FORMATED"]?></div>
<div class="old_price"><?=$arItem["FULL_PRICE_FORMATED"]?></div>
<?else:?>
<div class="current_price"><?=$arItem["PRICE_FORMATED"];?></div>
<?endif?>
<?if ($bPriceType && strlen($arItem["NOTES"]) > 0):?>
<div class="type_price"><?=GetMessage("SALE_TYPE")?></div>
<div class="type_price_value"><?=$arItem["NOTES"]?></div>
<?endif;?>
</td>
<?
elseif ($arHeader["id"] == "DISCOUNT"):
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<?=$arItem["DISCOUNT_PRICE_PERCENT_FORMATED"]?>
</td>
<?
elseif ($arHeader["id"] == "WEIGHT"):
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<?=$arItem["WEIGHT_FORMATED"]?>
</td>
<?
else:
?>
<td class="custom">
<span><?=$arHeader["name"]; ?>:</span>
<?=$arItem[$arHeader["id"]]?>
</td>
<?
endif;
endforeach;
if ($bDelayColumn || $bDeleteColumn):
?>
<td class="control">
<a href="<?=str_replace("#ID#", $arItem["ID"], $arUrls["add"])?>"><?=GetMessage("SALE_ADD_TO_BASKET")?></a><br />
<?
if ($bDeleteColumn):
?>
<a href="<?=str_replace("#ID#", $arItem["ID"], $arUrls["delete"])?>"><?=GetMessage("SALE_DELETE")?></a><br />
<?
endif;
?>
</td>
<?
endif;
?>
<td class="margin"></td>
</tr>
<?
endif;
endforeach;
?>
</tbody>
</table>
</div>

Some files were not shown because too many files have changed in this diff Show More