1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
currency_rate.php
См. документацию.
1<?php
2
7
9
11{
12 protected static array $currentCache = [];
13
14 public static function CheckFields($ACTION, &$arFields, $ID = 0)
15 {
16 global $APPLICATION, $DB;
17 global $USER;
18
19 $arMsg = [];
20
21 if ('UPDATE' !== $ACTION && 'ADD' !== $ACTION)
22 {
23 return false;
24 }
25 if (!is_array($arFields))
26 {
27 return false;
28 }
29 if (array_key_exists('ID', $arFields))
30 {
31 unset($arFields['ID']);
32 }
33
34 if ('UPDATE' == $ACTION && 0 >= intval($ID))
35 $arMsg[] = array('id' => 'ID','text' => GetMessage('BT_MOD_CURR_ERR_RATE_ID_BAD'));
36
37 if (!isset($arFields["CURRENCY"]))
38 $arMsg[] = array('id' => 'CURRENCY','text' => GetMessage('BT_MOD_CURR_ERR_RATE_CURRENCY_ABSENT'));
39 else
40 $arFields["CURRENCY"] = mb_substr($arFields["CURRENCY"], 0, 3);
41
42 if (empty($arFields['DATE_RATE']))
43 $arMsg[] = array('id' => 'DATE_RATE','text' => GetMessage('BT_MOD_CURR_ERR_RATE_DATE_ABSENT'));
44 elseif (!$DB->IsDate($arFields['DATE_RATE']))
45 $arMsg[] = array('id' => 'DATE_RATE','text' => GetMessage('BT_MOD_CURR_ERR_RATE_DATE_FORMAT_BAD'));
46
47 if (is_set($arFields, 'RATE_CNT') || 'ADD' == $ACTION)
48 {
49 if (!isset($arFields['RATE_CNT']))
50 {
51 $arMsg[] = array('id' => 'RATE_CNT', 'text' => GetMessage('BT_MOD_CURR_ERR_RATE_RATE_CNT_ABSENT'));
52 }
53 else
54 {
55 $arFields['RATE_CNT'] = (int)$arFields['RATE_CNT'];
56 if ($arFields['RATE_CNT'] <= 0)
57 $arMsg[] = array('id' => 'RATE_CNT', 'text' => GetMessage('BT_MOD_CURR_ERR_RATE_RATE_CNT_BAD'));
58 }
59 }
60 if (is_set($arFields['RATE']) || 'ADD' == $ACTION)
61 {
62 if (!isset($arFields['RATE']))
63 {
64 $arMsg[] = array('id' => 'RATE','text' => GetMessage('BT_MOD_CURR_ERR_RATE_RATE_ABSENT'));
65 }
66 else
67 {
68 $arFields['RATE'] = (float)$arFields['RATE'];
69 if (!($arFields['RATE'] > 0))
70 {
71 $arMsg[] = array('id' => 'RATE','text' => GetMessage('BT_MOD_CURR_ERR_RATE_RATE_BAD'));
72 }
73 }
74 }
75 if ($ACTION == 'ADD')
76 {
77 if ($arFields['CURRENCY'] == Currency\CurrencyManager::getBaseCurrency())
78 {
79 $arMsg[] = array('id' => 'CURRENCY', 'text' => GetMessage('BT_MOD_CURR_ERR_RATE_FOR_BASE_CURRENCY'));
80 } else
81 {
82 if (!isset($arFields['BASE_CURRENCY']) || !Currency\CurrencyManager::checkCurrencyID($arFields['BASE_CURRENCY']))
83 $arFields['BASE_CURRENCY'] = Currency\CurrencyManager::getBaseCurrency();
84 }
85 if ($arFields['CURRENCY'] == $arFields['BASE_CURRENCY'])
86 {
87 $arMsg[] = array('id' => 'CURRENCY', 'text' => GetMessage('BT_MOD_CURR_ERR_RATE_FOR_SELF_CURRENCY'));
88 }
89 }
90
91 $userId = 0;
92 if (isset($USER) && $USER instanceof CUser)
93 {
94 $userId = (int)$USER->GetID();
95 }
96
97 $arFields['~TIMESTAMP_X'] = $DB->GetNowFunction();
98 $arFields['MODIFIED_BY'] = (int)($arFields['MODIFIED_BY'] ?? $userId);
99 if ($arFields['MODIFIED_BY'] < 0)
100 {
101 $arFields['MODIFIED_BY'] = $userId;
102 }
103 if ($ACTION === 'ADD')
104 {
105 $arFields['~DATE_CREATE'] = $arFields['~TIMESTAMP_X'];
106 $arFields['CREATED_BY'] = (int)($arFields['CREATED_BY'] ?? $userId);
107 if ($arFields['CREATED_BY'] < 0)
108 {
109 $arFields['CREATED_BY'] = $userId;
110 }
111 }
112
113 if (!empty($arMsg))
114 {
115 $obError = new CAdminException($arMsg);
116 $APPLICATION->ResetException();
117 $APPLICATION->ThrowException($obError);
118
119 return false;
120 }
121
122 return true;
123 }
124
125 public static function Add($arFields)
126 {
127 global $DB;
128 global $APPLICATION;
130 global $stackCacheManager;
131
132 $arMsg = [];
133
134 foreach (GetModuleEvents("currency", "OnBeforeCurrencyRateAdd", true) as $arEvent)
135 {
136 if (ExecuteModuleEventEx($arEvent, array(&$arFields))===false)
137 return false;
138 }
139
141 {
142 return false;
143 }
144
145 CTimeZone::Disable();
147 'select' => ['ID'],
148 'filter' => [
149 '=CURRENCY' => $arFields['CURRENCY'],
150 '=BASE_CURRENCY' => $arFields['BASE_CURRENCY'],
151 '=DATE_RATE' => DateTime::createFromUserTime($arFields['DATE_RATE']),
152 ],
153 ]);
154 CTimeZone::Enable();
155 if ($existRate)
156 {
157 $arMsg[] = array("id"=>"DATE_RATE", "text"=> GetMessage("ERROR_ADD_REC2"));
158 $e = new CAdminException($arMsg);
159 $APPLICATION->ThrowException($e);
160
161 return false;
162 }
163
164 $stackCacheManager->Clear('currency_rate');
165
166 $ID = $DB->Add('b_catalog_currency_rate', $arFields);
167
171 self::$currentCache = [];
172
173 foreach (GetModuleEvents('currency', 'OnCurrencyRateAdd', true) as $arEvent)
174 {
175 ExecuteModuleEventEx($arEvent, [$ID, $arFields]);
176 }
177
178 return $ID;
179 }
180
181 public static function Update($ID, $arFields)
182 {
183 global $DB;
184 global $APPLICATION;
186 global $stackCacheManager;
187
188 $ID = (int)$ID;
189 if ($ID <= 0)
190 {
191 return false;
192 }
193 $arMsg = [];
194
195 foreach (GetModuleEvents("currency", "OnBeforeCurrencyRateUpdate", true) as $arEvent)
196 {
197 if (ExecuteModuleEventEx($arEvent, [$ID, &$arFields]) === false)
198 {
199 return false;
200 }
201 }
202
204 {
205 return false;
206 }
207
208 CTimeZone::Disable();
210 'select' => ['ID'],
211 'filter' => [
212 '=CURRENCY' => $arFields['CURRENCY'],
213 '=BASE_CURRENCY' => $arFields['BASE_CURRENCY'],
214 '=DATE_RATE' => DateTime::createFromUserTime($arFields['DATE_RATE']),
215 '!=ID' => $ID,
216 ],
217 ]);
218 CTimeZone::Enable();
219
220 if ($existRate)
221 {
222 $arMsg[] = [
223 'id' => 'DATE_RATE',
224 'text' => GetMessage('ERROR_ADD_REC2'),
225 ];
226 $e = new CAdminException($arMsg);
227 $APPLICATION->ThrowException($e);
228
229 return false;
230 }
231
232 $strUpdate = $DB->PrepareUpdate('b_catalog_currency_rate', $arFields);
233 if (!empty($strUpdate))
234 {
235 $strSql = "UPDATE b_catalog_currency_rate SET ".$strUpdate." WHERE ID = ".$ID;
236 $DB->Query($strSql);
237
238 $stackCacheManager->Clear('currency_rate');
242 self::$currentCache = [];
243 }
244 foreach (GetModuleEvents('currency', 'OnCurrencyRateUpdate', true) as $arEvent)
245 {
246 ExecuteModuleEventEx($arEvent, [$ID, $arFields]);
247 }
248
249 return true;
250 }
251
252 public static function Delete($ID)
253 {
254 global $APPLICATION;
256 global $stackCacheManager;
257
258 $ID = (int)$ID;
259 if ($ID <= 0)
260 {
261 return false;
262 }
263
264 foreach (GetModuleEvents('currency', 'OnBeforeCurrencyRateDelete', true) as $arEvent)
265 {
266 if (ExecuteModuleEventEx($arEvent, [$ID]) === false)
267 {
268 return false;
269 }
270 }
271
273 'select' => [
274 'ID',
275 'CURRENCY',
276 ],
277 'filter' => ['=ID' => $ID],
278 ]);
279 if (!is_array($arFields))
280 {
281 $arMsg = array('id' => 'ID', 'text' => GetMessage('BT_MOD_CURR_ERR_RATE_CANT_DELETE_ABSENT_ID'));
282 $e = new CAdminException($arMsg);
283 $APPLICATION->ThrowException($e);
284 return false;
285 }
286
288 if (!$result->isSuccess())
289 {
290 self::convertErrors($result);
291
292 return false;
293 }
294
295 $stackCacheManager->Clear('currency_rate');
299 self::$currentCache = [];
300
301 foreach(GetModuleEvents('currency', 'OnCurrencyRateDelete', true) as $arEvent)
302 {
303 ExecuteModuleEventEx($arEvent, [$ID]);
304 }
305
306 return true;
307 }
308
309 public static function GetByID($ID)
310 {
311 global $DB;
312
313 $ID = (int)$ID;
314 if ($ID <= 0)
315 return false;
316 $strSql = "SELECT C.*, ".$DB->DateToCharFunction("C.DATE_RATE", "SHORT")." as DATE_RATE FROM b_catalog_currency_rate C WHERE ID = ".$ID;
317 $db_res = $DB->Query($strSql);
318
319 if ($res = $db_res->Fetch())
320 return $res;
321
322 return false;
323 }
324
325 public static function GetList($by = 'date', $order = 'asc', $arFilter = [])
326 {
327 global $DB;
328
329 $mysqlEdition = $DB->type === 'MYSQL';
330 $arSqlSearch = array();
331
332 if(!is_array($arFilter))
333 $filter_keys = array();
334 else
335 $filter_keys = array_keys($arFilter);
336
337 for ($i=0, $intCount = count($filter_keys); $i < $intCount; $i++)
338 {
339 $val = (string)$DB->ForSql($arFilter[$filter_keys[$i]]);
340 if ($val === '')
341 continue;
342
343 $key = $filter_keys[$i];
344 if ($key[0]=="!")
345 {
346 $key = substr($key, 1);
347 $bInvert = true;
348 }
349 else
350 $bInvert = false;
351
352 switch(strtoupper($key))
353 {
354 case "CURRENCY":
355 $arSqlSearch[] = "C.CURRENCY = '".$val."'";
356 break;
357 case "DATE_RATE":
358 $arSqlSearch[] = "(C.DATE_RATE ".($bInvert? "<" : ">=")." ".($mysqlEdition? "CAST(" : "").$DB->CharToDateFunction($DB->ForSql($val), "SHORT").($mysqlEdition? " AS DATE)" : "").($bInvert? "" : " OR C.DATE_RATE IS NULL").")";
359 break;
360 }
361 }
362
363 $strSqlSearch = "";
364 for($i=0, $intCount = count($arSqlSearch); $i < $intCount; $i++)
365 {
366 if($i>0)
367 $strSqlSearch .= " AND ";
368 else
369 $strSqlSearch = " WHERE ";
370
371 $strSqlSearch .= " (".$arSqlSearch[$i].") ";
372 }
373
374 $strSql = "SELECT C.ID, C.CURRENCY, C.RATE_CNT, C.RATE, ".$DB->DateToCharFunction("C.DATE_RATE", "SHORT")." as DATE_RATE FROM b_catalog_currency_rate C ".
375 $strSqlSearch;
376
377 if (strtolower($by) == "curr") $strSqlOrder = " ORDER BY C.CURRENCY ";
378 elseif (strtolower($by) == "rate") $strSqlOrder = " ORDER BY C.RATE ";
379 else
380 {
381 $strSqlOrder = " ORDER BY C.DATE_RATE ";
382 }
383
384 if (strtolower($order) == "desc")
385 $strSqlOrder .= " desc ";
386
387 $strSql .= $strSqlOrder;
388 $res = $DB->Query($strSql);
389
390 return $res;
391 }
392
393 public static function ConvertCurrency($valSum, $curFrom, $curTo, $valDate = "")
394 {
395 return (float)$valSum * static::GetConvertFactorEx($curFrom, $curTo, $valDate);
396 }
397
407 public static function GetConvertFactor($curFrom, $curTo, $valDate = "")
408 {
409 return static::GetConvertFactorEx($curFrom, $curTo, $valDate);
410 }
411
418 public static function GetConvertFactorEx($curFrom, $curTo, $valDate = "")
419 {
421 global $stackCacheManager;
422
423 $curFrom = (string)$curFrom;
424 $curTo = (string)$curTo;
425 if($curFrom === '' || $curTo === '')
426 return 0;
427 if ($curFrom == $curTo)
428 return 1;
429
430 $valDate = (string)$valDate;
431 if ($valDate === '')
432 $valDate = date("Y-m-d");
433 list($dpYear, $dpMonth, $dpDay) = explode("-", $valDate, 3);
434 $dpDay += 1;
435 if($dpYear < 2038 && $dpYear > 1970)
436 $valDate = date("Y-m-d", mktime(0, 0, 0, $dpMonth, $dpDay, $dpYear));
437 else
438 $valDate = date("Y-m-d");
439
440 $curFromRate = 0;
441 $curFromRateCnt = 0;
442 $curToRate = 1;
443 $curToRateCnt = 1;
444
445 if (defined("CURRENCY_SKIP_CACHE") && CURRENCY_SKIP_CACHE)
446 {
447 if ($res = static::_get_last_rates($valDate, $curFrom))
448 {
449 $curFromRate = (float)$res["RATE"];
450 $curFromRateCnt = (int)$res["RATE_CNT"];
451 if ($curFromRate <= 0)
452 {
453 $curFromRate = (float)$res["AMOUNT"];
454 $curFromRateCnt = (int)$res["AMOUNT_CNT"];
455 }
456 }
457
458 if ($res = static::_get_last_rates($valDate, $curTo))
459 {
460 $curToRate = (float)$res["RATE"];
461 $curToRateCnt = (int)$res["RATE_CNT"];
462 if ($curToRate <= 0)
463 {
464 $curToRate = (float)$res["AMOUNT"];
465 $curToRateCnt = (int)$res["AMOUNT_CNT"];
466 }
467 }
468 }
469 else
470 {
471 $cacheTime = CURRENCY_CACHE_DEFAULT_TIME;
472 if (defined("CURRENCY_CACHE_TIME"))
473 $cacheTime = (int)CURRENCY_CACHE_TIME;
474
475 $cacheKey = 'C_R_'.$valDate.'_'.$curFrom.'_'.$curTo;
476
477 $stackCacheManager->SetLength("currency_rate", 10);
478 $stackCacheManager->SetTTL("currency_rate", $cacheTime);
479 if ($stackCacheManager->Exist("currency_rate", $cacheKey))
480 {
481 $arResult = $stackCacheManager->Get("currency_rate", $cacheKey);
482 }
483 else
484 {
485 if (!isset(self::$currentCache[$cacheKey]))
486 {
487 if ($res = static::_get_last_rates($valDate, $curFrom))
488 {
489 $curFromRate = (float)$res["RATE"];
490 $curFromRateCnt = (int)$res["RATE_CNT"];
491 if ($curFromRate <= 0)
492 {
493 $curFromRate = (float)$res["AMOUNT"];
494 $curFromRateCnt = (int)$res["AMOUNT_CNT"];
495 }
496 }
497
498 if ($res = static::_get_last_rates($valDate, $curTo))
499 {
500 $curToRate = (float)$res["RATE"];
501 $curToRateCnt = (int)$res["RATE_CNT"];
502 if ($curToRate <= 0)
503 {
504 $curToRate = (float)$res["AMOUNT"];
505 $curToRateCnt = (int)$res["AMOUNT_CNT"];
506 }
507 }
508
509 self::$currentCache[$cacheKey] = array(
510 "curFromRate" => $curFromRate,
511 "curFromRateCnt" => $curFromRateCnt,
512 "curToRate" => $curToRate,
513 "curToRateCnt" => $curToRateCnt
514 );
515
516 $stackCacheManager->Set("currency_rate", $cacheKey, self::$currentCache[$cacheKey]);
517 }
518 $arResult = self::$currentCache[$cacheKey];
519 }
520 $curFromRate = $arResult["curFromRate"];
521 $curFromRateCnt = $arResult["curFromRateCnt"];
522 $curToRate = $arResult["curToRate"];
523 $curToRateCnt = $arResult["curToRateCnt"];
524 }
525
526 if ($curFromRate == 0 || $curToRateCnt == 0 || $curToRate == 0 || $curFromRateCnt == 0)
527 return 0;
528
529 return $curFromRate*$curToRateCnt/$curToRate/$curFromRateCnt;
530 }
531
532 public static function _get_last_rates($valDate, $cur)
533 {
534 $baseCurrency = Currency\CurrencyManager::getBaseCurrency();
535 if ($baseCurrency === null)
536 {
537 return null;
538 }
539 $valDate = trim((string)$valDate);
540 $cur = trim((string)$cur);
541
542 if ($valDate === '' || !Currency\CurrencyManager::isCurrencyExist($cur))
543 {
544 return null;
545 }
546
548 'select' => [
549 'AMOUNT',
550 'AMOUNT_CNT',
551 'RATE' => 'RATE_TB.RATE',
552 'RATE_CNT' => 'RATE_TB.RATE_CNT',
553 'DATE_RATE' => 'RATE_TB.DATE_RATE',
554 ],
555 'filter' => [
556 '=CURRENCY' => $cur,
557 ],
558 'order' => [
559 'DATE_RATE' => 'DESC',
560 ],
561 'runtime' => [
562 'RATE_TB' => new ORM\Fields\Relations\Reference(
563 'RATE_TB',
564 Currency\CurrencyRateTable::class,
565 [
566 '=this.CURRENCY' => 'ref.CURRENCY',
567 '=ref.BASE_CURRENCY' => new SqlExpression('?s', $baseCurrency),
568 '<ref.DATE_RATE' => new SqlExpression('?s', $valDate),
569 ],
570 ['join' => ORM\Query\Join::TYPE_LEFT]
571 ),
572 ]
573 ]);
574
575 if ($result !== null)
576 {
577 unset($result['DATE_RATE']);
578 }
579
580 return $result;
581 }
582
583 private static function convertErrors(ORM\Data\Result $result): void
584 {
585 global $APPLICATION;
586
587 $oldMessages = [];
588 foreach ($result->getErrorMessages() as $errorText)
589 {
590 $oldMessages[] = ['text' => $errorText];
591 }
592 unset($errorText);
593
594 if (!empty($oldMessages))
595 {
596 $error = new CAdminException($oldMessages);
597 $APPLICATION->ThrowException($error);
598 unset($error);
599 }
600 unset($oldMessages);
601 }
602}
603
605{
606
607}
$db_res
Определения options_user_settings.php:8
global $APPLICATION
Определения include.php:80
$arResult
Определения generate_coupon.php:16
if(!is_object($USER)||! $USER->IsAuthorized()) $userId
Определения check_mail.php:18
static clearTagCache($currency)
Определения currencymanager.php:458
static updateBaseRates($updateCurrency='')
Определения currencymanager.php:488
static isCurrencyExist($currency)
Определения currencymanager.php:263
static checkCurrencyID($currency)
Определения currencymanager.php:35
static cleanCache()
Определения datamanager.php:1983
static getRow(array $parameters)
Определения datamanager.php:398
static delete($primary)
Определения datamanager.php:1644
const TYPE_LEFT
Определения join.php:21
static createFromUserTime($timeString)
Определения datetime.php:180
static Delete($ID)
Определения currency_rate.php:252
static array $currentCache
Определения currency_rate.php:12
static _get_last_rates($valDate, $cur)
Определения currency_rate.php:532
static Add($arFields)
Определения currency_rate.php:125
static GetByID($ID)
Определения currency_rate.php:309
static GetConvertFactor($curFrom, $curTo, $valDate="")
Определения currency_rate.php:407
static ConvertCurrency($valSum, $curFrom, $curTo, $valDate="")
Определения currency_rate.php:393
static CheckFields($ACTION, &$arFields, $ID=0)
Определения currency_rate.php:14
static GetList($by='date', $order='asc', $arFilter=[])
Определения currency_rate.php:325
static GetConvertFactorEx($curFrom, $curTo, $valDate="")
Определения currency_rate.php:418
static Update($ID, $arFields)
Определения currency_rate.php:181
Определения user.php:6037
const CURRENCY_CACHE_DEFAULT_TIME
Определения include.php:47
$arFields
Определения dblapprove.php:5
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$res
Определения filter_act.php:7
$result
Определения get_property_values.php:14
if($ajaxMode) $ID
Определения get_user.php:27
global $DB
Определения cron_frame.php:29
global $USER
Определения csv_new_run.php:40
$ACTION
Определения csv_new_setup.php:27
ExecuteModuleEventEx($arEvent, $arParams=[])
Определения tools.php:5214
GetModuleEvents($MODULE_ID, $MESSAGE_ID, $bReturnArray=false)
Определения tools.php:5177
IncludeModuleLangFile($filepath, $lang=false, $bReturnArray=false)
Определения tools.php:3778
is_set($a, $k=false)
Определения tools.php:2133
GetMessage($name, $aReplace=null)
Определения tools.php:3397
Определения aliases.php:105
Определения chain.php:3
$order
Определения payment.php:8
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
if(empty($signedUserToken)) $key
Определения quickway.php:257
$i
Определения factura.php:643
</p ></td >< td valign=top style='border-top:none;border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;padding:0cm 2.0pt 0cm 2.0pt;height:9.0pt'>< p class=Normal align=center style='margin:0cm;margin-bottom:.0001pt;text-align:center;line-height:normal'>< a name=ТекстовоеПоле54 ></a ><?=($taxRate > count( $arTaxList) > 0) ? $taxRate."%"
Определения waybill.php:936
$val
Определения options.php:1793
$error
Определения subscription_card_product.php:20
$arFilter
Определения user_search.php:106