Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
manager.php
1<?php
2
3namespace Bitrix\Sale\Cashbox;
4
13use Bitrix\Sale;
14
15Loc::loadMessages(__FILE__);
16
21final class Manager
22{
23 /* ignored all errors, warnings */
25 /* trace only errors */
26 const LEVEL_TRACE_E_ERROR = Errors\Error::LEVEL_TRACE;
27 /* trace only errors, warnings */
28 const LEVEL_TRACE_E_WARNING = Errors\Warning::LEVEL_TRACE;
29
30 const DEBUG_MODE = false;
31 const CACHE_ID = 'BITRIX_CASHBOX_LIST';
32 const TTL = 31536000;
33 const CHECK_STATUS_AGENT = '\Bitrix\Sale\Cashbox\Manager::updateChecksStatus();';
34
35 private const EVENT_ON_BEFORE_CASHBOX_ADD = 'onBeforeCashboxAdd';
36
41 public static function getListWithRestrictions(CollectableEntity $entity)
42 {
43 $result = array();
44
45 $dbRes = CashboxTable::getList(array(
46 'select' => array('*'),
47 'filter' => array('ACTIVE' => 'Y'),
48 'order' => array('SORT' => 'ASC', 'NAME' => 'ASC')
49 ));
50
51 while ($cashbox = $dbRes->fetch())
52 {
53 if (Restrictions\Manager::checkService($cashbox['ID'], $entity) === Restrictions\Manager::SEVERITY_NONE)
54 $result[$cashbox['ID']] = $cashbox;
55 }
56
57 return $result;
58 }
59
60 private static function getCashboxByPayment(Sale\Payment $payment): array
61 {
62 $service = $payment->getPaySystem();
63 if ($service && $service->isSupportPrintCheck())
64 {
66 $cashboxClass = $service->getCashboxClass();
67 $kkm = $cashboxClass::getKkmValue($service);
68
69 return self::getList([
70 'filter' => [
71 '=ACTIVE' => 'Y',
72 '=HANDLER' => $cashboxClass,
73 '=KKM_ID' => $kkm,
74 ],
75 ])->fetch();
76 }
77
78 return [];
79 }
80
85 public static function getAvailableCashboxList(Check $check): array
86 {
87 $cashboxList = [];
88 $firstIteration = true;
89
90 $payment = CheckManager::getPaymentByCheck($check);
91 if ($payment && self::canPaySystemPrint($payment))
92 {
93 $cashbox = self::getCashboxByPayment($payment);
94 if ($cashbox)
95 {
96 $cashboxList[] = $cashbox;
97 }
98 }
99 else
100 {
101 $entities = $check->getEntities();
102 foreach ($entities as $entity)
103 {
104 $items = self::getListWithRestrictions($entity);
105 if ($firstIteration)
106 {
107 $cashboxList = $items;
108 $firstIteration = false;
109 }
110 else
111 {
112 $cashboxList = array_intersect_assoc($items, $cashboxList);
113 }
114 }
115
116 foreach ($cashboxList as $key => $cashbox)
117 {
118 if (self::isPaySystemCashbox($cashbox['HANDLER']))
119 {
120 unset($cashboxList[$key]);
121 }
122 }
123 }
124
125 return $cashboxList;
126 }
127
135 public static function getList(array $parameters = [])
136 {
137 return CashboxTable::getList($parameters);
138 }
139
148 public static function getRestHandlersList()
149 {
150 $result = [];
151
152 $handlerList = CashboxRestHandlerTable::getList()->fetchAll();
153 foreach ($handlerList as $handler)
154 {
155 $result[$handler['CODE']] = $handler;
156 }
157
158 return $result;
159 }
160
165 public static function getObjectById($id)
166 {
167 static $cashboxObjects = array();
168
169 if ((int)$id <= 0)
170 {
171 return null;
172 }
173
174 if (!isset($cashboxObjects[$id]))
175 {
176 $data = static::getCashboxFromCache($id);
177 if ($data)
178 {
179 $cashbox = Cashbox::create($data);
180 if ($cashbox === null)
181 {
182 return null;
183 }
184
185 $cashboxObjects[$id] = $cashbox;
186 }
187 }
188
189 return $cashboxObjects[$id] ?? null;
190 }
191
198 public static function chooseCashbox($cashboxList)
199 {
200 $index = rand(0, count($cashboxList)-1);
201
202 return $cashboxList[$index];
203 }
204
208 public static function getConnectionLink()
209 {
210 $context = Main\Application::getInstance()->getContext();
211 $scheme = $context->getRequest()->isHttps() ? 'https' : 'http';
212 $server = $context->getServer();
213 $domain = $server->getServerName();
214
215 if (preg_match('/^(?<domain>.+):(?<port>\d+)$/', $domain, $matches))
216 {
217 $domain = $matches['domain'];
218 $port = $matches['port'];
219 }
220 else
221 {
222 $port = $server->getServerPort();
223 }
224 $port = in_array($port, array(80, 443)) ? '' : ':'.$port;
225
226 return sprintf('%s://%s%s/bitrix/tools/sale_check_print.php?hash=%s', $scheme, $domain, $port, static::generateHash());
227 }
228
232 private static function generateHash()
233 {
234 $hash = md5(base64_encode(time()));
235 CashboxConnectTable::add(array('HASH' => $hash, 'ACTIVE' => 'Y'));
236
237 return $hash;
238 }
239
243 public static function getListFromCache()
244 {
245 $cacheManager = Main\Application::getInstance()->getManagedCache();
246
247 if($cacheManager->read(self::TTL, self::CACHE_ID))
248 $cashboxList = $cacheManager->get(self::CACHE_ID);
249
250 if (empty($cashboxList))
251 {
252 $cashboxList = array();
253
254 $dbRes = CashboxTable::getList();
255 while ($data = $dbRes->fetch())
256 $cashboxList[$data['ID']] = $data;
257
258 $cacheManager->set(self::CACHE_ID, $cashboxList);
259 }
260
261 return $cashboxList;
262 }
263
268 public static function getCashboxFromCache($cashboxId)
269 {
270 $cashboxList = static::getListFromCache();
271 if (isset($cashboxList[$cashboxId]))
272 return $cashboxList[$cashboxId];
273
274 return array();
275 }
276
282 public static function buildZReportQuery($cashboxId, $id)
283 {
284 $cashbox = Manager::getObjectById($cashboxId);
285 if ($cashbox->getField('USE_OFFLINE') === 'Y')
286 return array();
287
288 return $cashbox->buildZReportQuery($id);
289 }
290
295 public static function buildChecksQuery($cashboxIds)
296 {
297 $result = array();
298 $checks = CheckManager::getPrintableChecks($cashboxIds);
299 foreach ($checks as $item)
300 {
301 $check = CheckManager::create($item);
302 if ($check !== null)
303 {
304 $printResult = static::buildConcreteCheckQuery($check->getField('CASHBOX_ID'), $check);
305 if ($printResult)
306 $result[] = $printResult;
307 }
308 }
309
310 return $result;
311 }
312
318 public static function buildConcreteCheckQuery($cashboxId, Check $check)
319 {
320 $cashbox = static::getObjectById($cashboxId);
321 if ($cashbox)
322 {
323 return $cashbox->buildCheckQuery($check);
324 }
325
326 return [];
327 }
328
333 public static function add(array $data)
334 {
335 $event = new Main\Event('sale', self::EVENT_ON_BEFORE_CASHBOX_ADD, $data);
336 $event->send();
337 $eventResults = $event->getResults();
338 foreach ($eventResults as $eventResult)
339 {
340 $data = array_merge($data, $eventResult->getParameters());
341 }
342 $addResult = CashboxTable::add($data);
343
344 $cacheManager = Main\Application::getInstance()->getManagedCache();
345 $cacheManager->clean(Manager::CACHE_ID);
346
347 if (
348 is_subclass_of($data['HANDLER'], ICheckable::class)
349 || (
350 is_subclass_of($data['HANDLER'], ICorrection::class)
351 && $data['HANDLER']::isCorrectionOn()
352 )
353 )
354 {
355 static::addCheckStatusAgent();
356 }
357
358 return $addResult;
359 }
360
364 private static function addCheckStatusAgent()
365 {
366 \CAgent::AddAgent(static::CHECK_STATUS_AGENT, "sale", "N", 120, "", "Y");
367 }
368
374 public static function update($primary, array $data)
375 {
376 $updateResult = CashboxTable::update($primary, $data);
377
378 $cacheManager = Main\Application::getInstance()->getManagedCache();
379
380 $service = self::getObjectById($primary);
381 if ($service && self::isPaySystemCashbox($service->getField('HANDLER')))
382 {
384 $cashboxClass = $service->getField('HANDLER');
385 if ($cashboxClass::CACHE_ID)
386 {
387 $cacheManager->clean($cashboxClass::CACHE_ID);
388 }
389 }
390
391 $cacheManager->clean(Manager::CACHE_ID);
392
393 if (is_subclass_of($data['HANDLER'], '\Bitrix\Sale\Cashbox\ICheckable'))
394 {
395 static::addCheckStatusAgent();
396 }
397
398 return $updateResult;
399 }
400
405 public static function delete($primary)
406 {
407 $service = self::getObjectById($primary);
408 $deleteResult = CashboxTable::delete($primary);
409 $cacheManager = Main\Application::getInstance()->getManagedCache();
410
411 if ($primary == Cashbox1C::getId())
412 {
413 $cacheManager->clean(Cashbox1C::CACHE_ID);
414 }
415
416 if ($service && self::isPaySystemCashbox($service->getField('HANDLER')))
417 {
419 $cashboxClass = $service->getField('HANDLER');
420 if ($cashboxClass::CACHE_ID)
421 {
422 $cacheManager->clean($cashboxClass::CACHE_ID);
423 }
424 }
425
426 $cacheManager->clean(Manager::CACHE_ID);
427
428 return $deleteResult;
429 }
430
434 public static function isSupportedFFD105()
435 {
437
438 $cashboxList = static::getListFromCache();
439 foreach ($cashboxList as $cashbox)
440 {
441 if ($cashbox['ACTIVE'] === 'N')
442 continue;
444 $handler = $cashbox['HANDLER'];
445 $isRestHandler = $handler === '\Bitrix\Sale\Cashbox\CashboxRest';
446 if ($isRestHandler)
447 {
448 $handlerCode = $cashbox['SETTINGS']['REST']['REST_CODE'];
449 $restHandlers = self::getRestHandlersList();
450 $currentHandler = $restHandlers[$handlerCode];
451 if ($currentHandler['SETTINGS']['SUPPORTS_FFD105'] !== 'Y')
452 {
453 return false;
454 }
455 }
456 elseif (
457 !is_callable(array($handler, 'isSupportedFFD105')) ||
458 !$handler::isSupportedFFD105()
459 )
460 {
461 return false;
462 }
463 }
464
465 return true;
466 }
467
468 public static function isEnabledPaySystemPrint(): bool
469 {
471
472 $cashboxList = self::getListFromCache();
473 foreach ($cashboxList as $cashbox)
474 {
475 if ($cashbox['ACTIVE'] === 'N')
476 {
477 continue;
478 }
479
480 if (self::isPaySystemCashbox($cashbox['HANDLER']))
481 {
482 return true;
483 }
484 }
485
486 return false;
487 }
488
493 public static function canPaySystemPrint(Sale\Payment $payment): bool
494 {
495 $service = $payment->getPaySystem();
496
497 return $service
498 && $service->isSupportPrintCheck()
499 && $service->canPrintCheck()
500 && $service->canPrintCheckSelf($payment)
501 ;
502 }
503
508 public static function updateChecksStatus()
509 {
510 $cashboxList = static::getListFromCache();
511 if (!$cashboxList)
512 {
513 return '';
514 }
515
516 $availableCashboxList = [];
517 foreach ($cashboxList as $item)
518 {
519 $cashbox = Cashbox::create($item);
520 if (
521 $cashbox instanceof ICheckable
522 || $cashbox->isCorrection()
523 )
524 {
525 $availableCashboxList[$item['ID']] = $cashbox;
526 }
527 }
528
529 if (!$availableCashboxList)
530 {
531 return '';
532 }
533
534 $parameters = [
535 'filter' => [
536 '=STATUS' => 'P',
537 '@CASHBOX_ID' => array_keys($availableCashboxList),
538 '=CASHBOX.ACTIVE' => 'Y'
539 ],
540 'limit' => 5
541 ];
542 $dbRes = CheckManager::getList($parameters);
543 while ($checkInfo = $dbRes->fetch())
544 {
546 $cashbox = $availableCashboxList[$checkInfo['CASHBOX_ID']];
547 if ($cashbox)
548 {
549 $check = CheckManager::getObjectById($checkInfo['ID']);
550
551 if ($check instanceof CorrectionCheck)
552 {
553 $result = $cashbox->checkCorrection($check);
554 }
555 elseif ($check instanceof Check)
556 {
557 $result = $cashbox->check($check);
558 }
559 else
560 {
561 continue;
562 }
563
564 if (!$result->isSuccess())
565 {
566 foreach ($result->getErrors() as $error)
567 {
568 if ($error instanceof Errors\Warning)
569 {
570 Logger::addWarning($error->getMessage(), $cashbox->getField('ID'));
571 }
572 else
573 {
574 Logger::addError($error->getMessage(), $cashbox->getField('ID'));
575 }
576 }
577 }
578 }
579 }
580
581 return static::CHECK_STATUS_AGENT;
582 }
583
594 public static function writeToLog($cashboxId, Main\Error $error)
595 {
596 if ($error instanceof Errors\Warning)
597 {
598 Logger::addWarning($error->getMessage(), $cashboxId);
599 }
600 else
601 {
602 Logger::addError($error->getMessage(), $cashboxId);
603 }
604 }
605
610 public static function isCashboxChecksExist($cashboxId): bool
611 {
612 $params = [
613 'filter' => [
614 'STATUS' => 'Y',
615 'CASHBOX_ID' => $cashboxId,
616 ],
617 'limit' => 1,
618 ];
619 $result = CheckManager::getList($params);
620
621 return (bool)$result->fetch();
622 }
623
628 public static function deactivateCashbox($cashboxId): Main\ORM\Data\UpdateResult
629 {
630 return self::update($cashboxId, ['ACTIVE' => 'N']);
631 }
632
637 public static function isPaySystemCashbox(string $cashboxClassName): bool
638 {
639 return is_subclass_of($cashboxClassName, CashboxPaySystem::class);
640 }
641}
create()
static loadMessages($file)
Definition loc.php:64
static getList(array $parameters=array())
static getPaymentByCheck(Check $check)
static getList(array $parameters=array())
static create(array $settings)
static addWarning(?string $message, $cashboxId=null)
Definition logger.php:34
static addError(?string $message, $cashboxId=null)
Definition logger.php:25
static getAvailableCashboxList(Check $check)
Definition manager.php:85
static buildConcreteCheckQuery($cashboxId, Check $check)
Definition manager.php:318
static buildChecksQuery($cashboxIds)
Definition manager.php:295
static buildZReportQuery($cashboxId, $id)
Definition manager.php:282
static isCashboxChecksExist($cashboxId)
Definition manager.php:610
static add(array $data)
Definition manager.php:333
static getCashboxFromCache($cashboxId)
Definition manager.php:268
static getListWithRestrictions(CollectableEntity $entity)
Definition manager.php:41
static canPaySystemPrint(Sale\Payment $payment)
Definition manager.php:493
static writeToLog($cashboxId, Main\Error $error)
Definition manager.php:594
static isPaySystemCashbox(string $cashboxClassName)
Definition manager.php:637
static deactivateCashbox($cashboxId)
Definition manager.php:628
static chooseCashbox($cashboxList)
Definition manager.php:198
static getList(array $parameters=[])
Definition manager.php:135