HEX
Server: Apache/2.2.15 (CentOS)
System: Linux ip-10-0-2-146.eu-west-1.compute.internal 2.6.32-754.35.1.el6.centos.plus.x86_64 #1 SMP Sat Nov 7 11:33:42 UTC 2020 x86_64
User: root (0)
PHP: 5.6.40
Disabled: NONE
Upload Files
File: /www/exchange0old/exchange/admin/cron/calculate_credebtor_balances.php
<?php
if (php_sapi_name() != 'cli') {
//    exit();
}

$folders = explode(DIRECTORY_SEPARATOR, pathinfo(__FILE__, PATHINFO_DIRNAME));
array_pop($folders);
array_pop($folders);

include(implode(DIRECTORY_SEPARATOR, $folders) . '/Bin/init.php');
require_once(ROOT_FOLDER . 'Bin/Security.php');
include(ROOT_FOLDER . '/Bin/constants.php');
chdir(ROOT_FOLDER);

class CronCalculatingBalance
{
    /*
     * after currency rates are entered each morning (dynamic event)
     */
    const CALCULATING_BALANCE_EVENT_TYPE_CURRENCY_RATES = 1;

    /*
     * at 12:00pm each business day (static time)
     */
    const CALCULATING_BALANCE_EVENT_TYPE_12_00 = 2;

    /*
     * after authorisation of daily trades is completed (dynamic event, same moment when the NoA emails are sent out)
     */
    const CALCULATING_BALANCE_EVENT_TYPE_CLEARING = 3;

    /*
     * at 05:00pm (static time)
     */
    const CALCULATING_BALANCE_EVENT_TYPE_05_00 = 4;

    private function checkEvent()
    {
        Bin_Config::requireAdminModel('MRva', 'MSiteSetting');
        $rva = new Model_MRva();
        $db = Bin_Db::connect();
        $currentDate = date('Y-m-d');
        $eventType = 0;

        // check currency rates event
        $currencyRatesRows = $db->query('SELECT * FROM currency_rates
        WHERE DATE(currency_date) = :current_date', array(
            ':current_date' => $db->escapeValue($currentDate),
        ))->getNumRows();
        if ($currencyRatesRows > 1 and date('N') < 6
            and !$this->existEvent(CronCalculatingBalance::CALCULATING_BALANCE_EVENT_TYPE_CURRENCY_RATES)) {
            return CronCalculatingBalance::CALCULATING_BALANCE_EVENT_TYPE_CURRENCY_RATES;
        }

        // check 12:00 event
        if (date('H') >= 12 and !$rva->isNonBussines()
            and !$this->existEvent(CronCalculatingBalance::CALCULATING_BALANCE_EVENT_TYPE_12_00)) {
            return CronCalculatingBalance::CALCULATING_BALANCE_EVENT_TYPE_12_00;
        }

        // check clearing event
        $clearingDate = new DateTime(Model_MSiteSetting::getSetting('trades_clear_date', 'yesterday'));
        if ($clearingDate->format('Y-m-d') == $currentDate
            and !$this->existEvent(CronCalculatingBalance::CALCULATING_BALANCE_EVENT_TYPE_CLEARING)) {
            return CronCalculatingBalance::CALCULATING_BALANCE_EVENT_TYPE_CLEARING;
        }

        // check 05:00pm event
        if (date('H') >= 17
            and !$this->existEvent(CronCalculatingBalance::CALCULATING_BALANCE_EVENT_TYPE_05_00)) {
            return CronCalculatingBalance::CALCULATING_BALANCE_EVENT_TYPE_05_00;
        }

        return $eventType;
    }

    private function existEvent($eventType)
    {
        $db = Bin_Db::connect();
        $existEvent = $db->query('SELECT * FROM credebtor_balances_cron_requests
        WHERE DATE(start_time) = :current_date AND event_type = :event_type', array(
            ':current_date' => $db->escapeValue(date('Y-m-d')),
            ':event_type' => (int)$eventType,
        ))->getNumRows();

        return $existEvent > 0;
    }

    private function openRequest($eventType)
    {
        $db = Bin_Db::connect();
        $db->builder()->insert('credebtor_balances_cron_requests')->values(array(
            'event_type' => (int)$eventType,
            'status' => 0,
            'start_time' => new DateTime(),
        ))->execute();

        return $db->insertID();
    }

    private function closeRequest($requestId)
    {
        $db = Bin_Db::connect();
        $db->query('UPDATE credebtor_balances_cron_requests
        SET `status` = 1, end_time = :end_time
        WHERE request_id = :request_id', array(
            ':end_time' => $db->escapeValue(new DateTime()),
            ':request_id' => (int)$requestId,
        ));
    }

    public function calculateBalances()
    {
        $eventType = $this->checkEvent();
        if ($eventType > 0) {
            $requestId = $this->openRequest($eventType);

            include_once(ROOT_FOLDER . '/admin/classes/Model/statement_actions.php');

            Bin_Config::requireAdminModel('MHelpers');

            $db = Bin_Db::connect();

            $selectCredebtors = "SELECT debtor_id, type FROM debtors_detail";
            $result = $db->query($selectCredebtors)->getResultArray();

            $sa = new Statement_actions();
            foreach ($result as $res) {
                if ($res['type'] == 'creditor') {
                    $statement = $sa->getCreditorStatement($res['debtor_id']);
                    $balance = $statement['stat']['balance'];
                } else {
                    $statement = $sa->getDebtorStatement($res['debtor_id']);
                    $balance = $statement['stat']['ETR_Outstanding'];
                }
                $db->query('UPDATE credebtor_balances SET is_last = 0 WHERE debtor_id = :debtor_id', array(
                    ':debtor_id' => (int)$res['debtor_id'],
                ));
                $db->builder()->insert('credebtor_balances')->values(array(
                    'debtor_id' => (int)$res['debtor_id'],
                    'outstanding_balance' => round($balance, 2),
                    'calculation_date' => new DateTime(),
                    'is_last' => 1,
                ))->execute();
            }

            $this->closeRequest($requestId);
        }
    }
}

$class = new CronCalculatingBalance();
$class->calculateBalances();