Bitrix-D7  20.5.0
sale/lib/cashbox/manager.php
См. документацию.
1 <?php
2 
3 namespace Bitrix\Sale\Cashbox;
4 
5 use Bitrix\Main;
13 
14 Loc::loadMessages(__FILE__);
15 
16 /**
17  * Class Manager
18  * @package Bitrix\Sale\Cashbox
19  */
20 final class Manager
21 {
22  /* ignored all errors, warnings */
24  /* trace only errors */
25  const LEVEL_TRACE_E_ERROR = Errors\Error::LEVEL_TRACE;
26  /* trace only errors, warnings */
28 
29  const DEBUG_MODE = false;
30  const CACHE_ID = 'BITRIX_CASHBOX_LIST';
31  const TTL = 31536000;
32  const CHECK_STATUS_AGENT = '\Bitrix\Sale\Cashbox\Manager::updateChecksStatus();';
33 
34  /**
35  * @param CollectableEntity $entity
36  * @return array
37  */
38  public static function getListWithRestrictions(CollectableEntity $entity)
39  {
40  $result = array();
41 
42  $dbRes = CashboxTable::getList(array(
43  'select' => array('*'),
44  'filter' => array('ACTIVE' => 'Y'),
45  'order' => array('SORT' => 'ASC', 'NAME' => 'ASC')
46  ));
47 
48  while ($cashbox = $dbRes->fetch())
49  {
50  if (Restrictions\Manager::checkService($cashbox['ID'], $entity) === Restrictions\Manager::SEVERITY_NONE)
51  $result[$cashbox['ID']] = $cashbox;
52  }
53 
54  return $result;
55  }
56 
57  /**
58  * @param array $parameters
59  * @return Main\ORM\Query\Result
60  * @throws Main\ArgumentException
61  * @throws Main\ObjectPropertyException
62  * @throws Main\SystemException
63  */
64  public static function getList(array $parameters = [])
65  {
66  return CashboxTable::getList($parameters);
67  }
68 
69  /**
70  * Returns a list of all the registered rest cashbox handlers
71  * Structure: handler code => handler data
72  * @return array
73  * @throws Main\ArgumentException
74  * @throws Main\ObjectPropertyException
75  * @throws Main\SystemException
76  */
77  public static function getRestHandlersList()
78  {
79  $result = [];
80 
81  $handlerList = CashboxRestHandlerTable::getList()->fetchAll();
82  foreach ($handlerList as $handler)
83  {
84  $result[$handler['CODE']] = $handler;
85  }
86 
87  return $result;
88  }
89 
90  /**
91  * @param $id
92  * @return Cashbox|ICheckable|null
93  */
94  public static function getObjectById($id)
95  {
96  static $cashboxObjects = array();
97 
98  if ((int)$id <= 0)
99  return null;
100 
101  if (!isset($cashboxObjects[$id]))
102  {
103  $data = static::getCashboxFromCache($id);
104  if ($data)
105  {
106  $cashbox = Cashbox::create($data);
107  if ($cashbox === null)
108  return null;
109 
110  $cashboxObjects[$id] = $cashbox;
111  }
112  }
113 
114  return $cashboxObjects[$id];
115  }
116 
117  /**
118  * @param $cashboxList
119  * @return mixed
120  */
121  public static function chooseCashbox($cashboxList)
122  {
123  $index = rand(0, count($cashboxList)-1);
124 
125  return $cashboxList[$index];
126  }
127 
128  /**
129  * @return string
130  */
131  public static function getConnectionLink()
132  {
133  $context = Main\Application::getInstance()->getContext();
134  $scheme = $context->getRequest()->isHttps() ? 'https' : 'http';
135  $server = $context->getServer();
136  $domain = $server->getServerName();
137 
138  if (preg_match('/^(?<domain>.+):(?<port>\d+)$/', $domain, $matches))
139  {
140  $domain = $matches['domain'];
141  $port = $matches['port'];
142  }
143  else
144  {
145  $port = $server->getServerPort();
146  }
147  $port = in_array($port, array(80, 443)) ? '' : ':'.$port;
148 
149  return sprintf('%s://%s%s/bitrix/tools/sale_check_print.php?hash=%s', $scheme, $domain, $port, static::generateHash());
150  }
151 
152  /**
153  * @return string
154  */
155  private static function generateHash()
156  {
157  $hash = md5(base64_encode(time()));
158  CashboxConnectTable::add(array('HASH' => $hash, 'ACTIVE' => 'Y'));
159 
160  return $hash;
161  }
162 
163  /**
164  * @return mixed
165  */
166  public static function getListFromCache()
167  {
168  $cacheManager = Main\Application::getInstance()->getManagedCache();
169 
170  if($cacheManager->read(self::TTL, self::CACHE_ID))
171  $cashboxList = $cacheManager->get(self::CACHE_ID);
172 
173  if (empty($cashboxList))
174  {
175  $cashboxList = array();
176 
177  $dbRes = CashboxTable::getList();
178  while ($data = $dbRes->fetch())
179  $cashboxList[$data['ID']] = $data;
180 
181  $cacheManager->set(self::CACHE_ID, $cashboxList);
182  }
183 
184  return $cashboxList;
185  }
186 
187  /**
188  * @param $cashboxId
189  * @return array
190  */
191  public static function getCashboxFromCache($cashboxId)
192  {
193  $cashboxList = static::getListFromCache();
194  if (isset($cashboxList[$cashboxId]))
195  return $cashboxList[$cashboxId];
196 
197  return array();
198  }
199 
200  /**
201  * @param $cashboxId
202  * @param $id
203  * @return array
204  */
205  public static function buildZReportQuery($cashboxId, $id)
206  {
207  $cashbox = Manager::getObjectById($cashboxId);
208  if ($cashbox->getField('USE_OFFLINE') === 'Y')
209  return array();
210 
211  return $cashbox->buildZReportQuery($id);
212  }
213 
214  /**
215  * @param $cashboxIds
216  * @return array
217  */
218  public static function buildChecksQuery($cashboxIds)
219  {
220  $result = array();
221  $checks = CheckManager::getPrintableChecks($cashboxIds);
222  foreach ($checks as $item)
223  {
224  $check = CheckManager::create($item);
225  if ($check !== null)
226  {
227  $printResult = static::buildConcreteCheckQuery($check->getField('CASHBOX_ID'), $check);
228  if ($printResult)
229  $result[] = $printResult;
230  }
231  }
232 
233  return $result;
234  }
235 
236  /**
237  * @param $cashboxId
238  * @param Check $check
239  * @return array
240  */
241  public static function buildConcreteCheckQuery($cashboxId, Check $check)
242  {
243  $cashbox = static::getObjectById($cashboxId);
244  if ($cashbox)
245  {
246  return $cashbox->buildCheckQuery($check);
247  }
248 
249  return [];
250  }
251 
252  /**
253  * @param array $data
254  * @return \Bitrix\Main\Entity\AddResult
255  */
256  public static function add(array $data)
257  {
258  $addResult = CashboxTable::add($data);
259 
260  $cacheManager = Main\Application::getInstance()->getManagedCache();
261  $cacheManager->clean(Manager::CACHE_ID);
262 
263  if (
264  is_subclass_of($data['HANDLER'], ICheckable::class)
265  || is_subclass_of($data['HANDLER'], ICorrection::class)
266  )
267  {
268  static::addCheckStatusAgent();
269  }
270 
271  return $addResult;
272  }
273 
274  /**
275  * @return void
276  */
277  private static function addCheckStatusAgent()
278  {
279  \CAgent::AddAgent(static::CHECK_STATUS_AGENT, "sale", "N", 120, "", "Y");
280  }
281 
282  /**
283  * @param $primary
284  * @param array $data
285  * @return \Bitrix\Main\Entity\UpdateResult
286  */
287  public static function update($primary, array $data)
288  {
289  $updateResult = CashboxTable::update($primary, $data);
290 
291  $cacheManager = Main\Application::getInstance()->getManagedCache();
292  $cacheManager->clean(Manager::CACHE_ID);
293 
294  if (is_subclass_of($data['HANDLER'], '\Bitrix\Sale\Cashbox\ICheckable'))
295  {
296  static::addCheckStatusAgent();
297  }
298 
299  return $updateResult;
300  }
301 
302  /**
303  * @param $primary
304  * @return \Bitrix\Main\Entity\DeleteResult
305  */
306  public static function delete($primary)
307  {
308  $deleteResult = CashboxTable::delete($primary);
309 
310  if ($primary == Cashbox1C::getId())
311  {
312  $cacheManager = Main\Application::getInstance()->getManagedCache();
313  $cacheManager->clean(Cashbox1C::CACHE_ID);
314  }
315 
316  $cacheManager = Main\Application::getInstance()->getManagedCache();
317  $cacheManager->clean(Manager::CACHE_ID);
318 
319  return $deleteResult;
320  }
321 
322  /**
323  * @return bool
324  */
325  public static function isSupportedFFD105()
326  {
327  Cashbox::init();
328 
329  $cashboxList = static::getListFromCache();
330  foreach ($cashboxList as $cashbox)
331  {
332  if ($cashbox['ACTIVE'] === 'N')
333  continue;
334  /** @var Cashbox $handler */
335  $handler = $cashbox['HANDLER'];
336  $isRestHandler = $handler === '\Bitrix\Sale\Cashbox\CashboxRest';
337  if ($isRestHandler)
338  {
339  $handlerCode = $cashbox['SETTINGS']['REST']['REST_CODE'];
340  $restHandlers = self::getRestHandlersList();
341  $currentHandler = $restHandlers[$handlerCode];
342  if ($currentHandler['SETTINGS']['SUPPORTS_FFD105'] !== 'Y')
343  {
344  return false;
345  }
346  }
347  elseif (
348  !is_callable(array($handler, 'isSupportedFFD105')) ||
349  !$handler::isSupportedFFD105()
350  )
351  {
352  return false;
353  }
354  }
355 
356  return true;
357  }
358 
359  /**
360  * @return string
361  * @throws Main\ArgumentException
362  */
363  public static function updateChecksStatus()
364  {
365  $cashboxList = static::getListFromCache();
366  if (!$cashboxList)
367  {
368  return '';
369  }
370 
371  $availableCashboxList = [];
372  foreach ($cashboxList as $item)
373  {
374  $cashbox = Cashbox::create($item);
375  if (
376  $cashbox instanceof ICheckable
377  || $cashbox instanceof ICorrection
378  )
379  {
380  $availableCashboxList[$item['ID']] = $cashbox;
381  }
382  }
383 
384  if (!$availableCashboxList)
385  {
386  return '';
387  }
388 
389  $parameters = [
390  'filter' => [
391  '=STATUS' => 'P',
392  '@CASHBOX_ID' => array_keys($availableCashboxList),
393  '=CASHBOX.ACTIVE' => 'Y'
394  ],
395  'limit' => 5
396  ];
397  $dbRes = CheckManager::getList($parameters);
398  while ($checkInfo = $dbRes->fetch())
399  {
400  /** @var Cashbox|ICheckable|ICorrection $cashbox */
401  $cashbox = $availableCashboxList[$checkInfo['CASHBOX_ID']];
402  if ($cashbox)
403  {
404  $check = CheckManager::getObjectById($checkInfo['ID']);
405 
406  if ($check instanceof CorrectionCheck)
407  {
408  $result = $cashbox->checkCorrection($check);
409  }
410  elseif ($check instanceof Check)
411  {
412  $result = $cashbox->check($check);
413  }
414  else
415  {
416  continue;
417  }
418 
419  if (!$result->isSuccess())
420  {
421  foreach ($result->getErrors() as $error)
422  {
423  if ($error instanceof Errors\Warning)
424  {
425  Logger::addWarning($error->getMessage(), $cashbox->getField('ID'));
426  }
427  else
428  {
429  Logger::addError($error->getMessage(), $cashbox->getField('ID'));
430  }
431  }
432  }
433  }
434  }
435 
436  return static::CHECK_STATUS_AGENT;
437  }
438 
439  /**
440  * @param $cashboxId
441  * @param Main\Error $error
442  * @throws Main\ArgumentNullException
443  * @throws Main\ArgumentOutOfRangeException
444  * @throws Main\ArgumentTypeException
445  * @throws Main\ObjectException
446  *
447  * @deprecated Use \Bitrix\Sale\Cashbox\Logger instead
448  */
449  public static function writeToLog($cashboxId, Main\Error $error)
450  {
451  if ($error instanceof Errors\Warning)
452  {
453  Logger::addWarning($error->getMessage(), $cashboxId);
454  }
455  else
456  {
457  Logger::addError($error->getMessage(), $cashboxId);
458  }
459  }
460 }
static getInstance()
Returns current instance of the Application.
static loadMessages($file)
Loads language messages for specified file in a lazy way.
Definition: loc.php:67
static getList(array $parameters=array())
Executes the query and returns selection by parameters of the query.
static delete($primary)
Deletes row in entity table by primary key.
static add(array $data)
Adds row to entity table.
static update($primary, array $data)
Updates row in entity table by primary key.
static create(array $settings)
Definition: cashbox.php:118
static getList(array $parameters=array())
static getPrintableChecks(array $cashboxIds, array $orderIds=array())
static create(array $settings)
static addError(string $message, $cashboxId=null)
static addWarning(string $message, $cashboxId=null)
static getRestHandlersList()
Returns a list of all the registered rest cashbox handlers Structure: handler code => handler data.
static buildConcreteCheckQuery($cashboxId, Check $check)
static buildZReportQuery($cashboxId, $id)
static getListWithRestrictions(CollectableEntity $entity)
static writeToLog($cashboxId, Main\Error $error)
static getList(array $parameters=[])
static update($primary, array $data)