/**
 * Резервирование средств через яндекс кассу.
 * 
 * @param type $type
 * @param type $data
 *
 * @return \xajaxResponse
 */
function quickPaymentReserveYandexKassa($type, $data)
{
    $uid = get_uid(false);
    $objResponse =& new xajaxResponse();
    $pay_methods = array(quickPaymentPopup::PAYMENT_TYPE_CARD => yandex_kassa::PAYMENT_AC, quickPaymentPopup::PAYMENT_TYPE_YA => yandex_kassa::PAYMENT_YD, quickPaymentPopup::PAYMENT_TYPE_WM => yandex_kassa::PAYMENT_WM, quickPaymentPopup::PAYMENT_TYPE_ALFACLICK => yandex_kassa::PAYMENT_AB, quickPaymentPopup::PAYMENT_TYPE_SBERBANK => yandex_kassa::PAYMENT_SB);
    if (!isset($pay_methods[$type])) {
        return $objResponse;
    }
    $reserve_id = intval(@$data['quick_payment_reserve_form']);
    $reserveInstance = ReservesModelFactory::getInstanceById($reserve_id);
    if (!$reserveInstance) {
        return $objResponse;
    }
    $reserve_data = $reserveInstance->getReserveData();
    if ($reserve_data['emp_id'] != $uid || !$reserveInstance->isEmpAllowFinance()) {
        return $objResponse;
    }
    //Если уже был платеж то обновляем страницу
    if (!$reserveInstance->isStatusNew()) {
        $objResponse->script('window.location.reload()');
        return $objResponse;
    }
    //Формируем заказ
    $bill = new billing($uid);
    $billReserveId = $bill->addServiceAndCheckout(ReservesModel::OPCODE_RESERVE, array('acc_sum' => $reserve_data['reserve_price'], 'reserve_data' => $reserve_data));
    $payment = $pay_methods[$type];
    $yandex_kassa = new yandex_kassa();
    $yandex_kassa->setShop(yandex_kassa::SHOPID_SBR);
    $html_form = $yandex_kassa->render($bill->getOrderPayedSum(), $bill->getAccId(), $payment, $billReserveId);
    $objResponse->script("\n        var qp_form_wrapper = \$\$('#quick_payment_reserve .__quick_payment_form');\n        if(qp_form_wrapper){    \n            qp_form_wrapper.set('html','{$html_form}');\n            qp_form_wrapper.getElement('form')[0].submit();\n        }\n    ");
    $_SESSION[quickPaymentPopup::QPP_REDIRECT] = $reserveInstance->getTypeUrl();
    return $objResponse;
}
function quickPRJGetYandexKassaLink($payment)
{
    $objResponse = new xajaxResponse();
    $bill = new billing(get_uid(false));
    $billReserveId = $bill->checkoutOrder();
    $sum = $bill->getRealPayedSum();
    $payed_sum = $bill->getOrderPayedSum();
    if ($sum > 0) {
        $_SESSION['quickprj_is_begin'] = 1;
        $yandex_kassa = new yandex_kassa();
        $html_form = $yandex_kassa->render($sum, $bill->account->id, $payment, $billReserveId);
        $objResponse->script('$("quick_pro_div_wait_txt").set("html", \'' . $html_form . '\');');
        $objResponse->script("\$('quick_pro_div_wait_txt').getElements('form')[0].submit();");
    }
    return $objResponse;
}
/**
 * Пополнение счета через яндекс кассу.
 * 
 * @param type $type - тип оплаты
 * @param type $data - данные по параметрам покупаемой услуги
 *
 * @return \xajaxResponse
 */
function quickPaymentAccountYandexKassa($type, $data)
{
    $is_error = true;
    $uid = get_uid(false);
    $objResponse =& new xajaxResponse();
    $price = (int) @$data['price'];
    $pay_methods = array(quickPaymentPopup::PAYMENT_TYPE_CARD => yandex_kassa::PAYMENT_AC, quickPaymentPopup::PAYMENT_TYPE_YA => yandex_kassa::PAYMENT_YD, quickPaymentPopup::PAYMENT_TYPE_WM => yandex_kassa::PAYMENT_WM, quickPaymentPopup::PAYMENT_TYPE_ALFACLICK => yandex_kassa::PAYMENT_AB, quickPaymentPopup::PAYMENT_TYPE_SBERBANK => yandex_kassa::PAYMENT_SB);
    if (!isset($pay_methods[$type])) {
        return $objResponse;
    }
    $allow = !sbr_meta::isFtJuri($uid);
    if ($allow) {
        $is_error = false;
        $billReserveId = null;
        $bill = new billing($uid);
        $minPrice = quickPaymentPopupAccount::PRICE_MIN;
        if ($bill->getAccSum() < 0) {
            $debt = abs($bill->getAccSum());
            $minPrice = $debt > $minPrice ? $debt : $minPrice;
            if ($price >= $minPrice) {
                $option = array('acc_sum' => $minPrice);
                //Автоматическая покупка услуги погашения задолженности
                $billReserveId = $bill->addServiceAndCheckout(135, $option);
            }
        }
        $payment = $pay_methods[$type];
        if ($price < $minPrice || $price > quickPaymentPopupAccount::PRICE_MAX || $payment == yandex_kassa::PAYMENT_WM && $price > quickPaymentPopupAccount::PRICE_MAX_WM) {
            $is_error = true;
        }
        if (!$is_error) {
            $yandex_kassa = new yandex_kassa();
            $html_form = $yandex_kassa->render($price, $bill->account->id, $payment, $billReserveId);
            $objResponse->script("\n                var qp_form_wrapper = \$\$('#quick_payment_account .__quick_payment_form');\n                if(qp_form_wrapper){    \n                    qp_form_wrapper.set('html','{$html_form}');\n                    qp_form_wrapper.getElement('form')[0].submit();\n                }\n            ");
            $link = '/bill/history/?period=3';
            //сохраняем в сессию куда перейти при успешной покупке
            $_SESSION[quickPaymentPopup::QPP_REDIRECT] = $link;
        }
    }
    // Показываем предупреждение в случае ошибки
    if ($is_error) {
        $objResponse->script("\n            var qp = window.quick_payment_factory.getQuickPayment('account');\n            if(qp) qp.show_error('Возникла ошибка при пополнении счета!');\n        ");
    }
    return $objResponse;
}
/**
 * Оплата через яндекс кассу.
 * 
 * @param type $type - тип оплаты
 * @param type $data - данные по параметрам покупаемой услуги
 *
 * @return \xajaxResponse
 */
function quickPaymentMasssendingYandexKassa($type, $data)
{
    $is_error = true;
    $uid = get_uid(false);
    $objResponse =& new xajaxResponse();
    $send_id = (int) $data['send_id'];
    $promo_code = (string) @$data['promo'];
    $pay_methods = array(quickPaymentPopup::PAYMENT_TYPE_CARD => yandex_kassa::PAYMENT_AC, quickPaymentPopup::PAYMENT_TYPE_YA => yandex_kassa::PAYMENT_YD, quickPaymentPopup::PAYMENT_TYPE_WM => yandex_kassa::PAYMENT_WM, quickPaymentPopup::PAYMENT_TYPE_ALFACLICK => yandex_kassa::PAYMENT_AB, quickPaymentPopup::PAYMENT_TYPE_SBERBANK => yandex_kassa::PAYMENT_SB);
    if (!isset($pay_methods[$type])) {
        return $objResponse;
    }
    $masssending = new masssending();
    $params = $masssending->getAccepted($send_id, $uid);
    if ($params) {
        $is_error = false;
        $bill = new billing(get_uid(false));
        //Допустимо использование промокодов
        $bill->setPromoCodes('SERVICE_MASSSENDING', $promo_code);
        $option = array('amount' => $params['pre_sum'], 'masssending_id' => $params['id']);
        //Формируем заказ
        $billReserveId = $bill->addServiceAndCheckout(masssending::OPER_CODE, $option);
        $payed_sum = $bill->getRealPayedSum();
        $payment = $pay_methods[$type];
        $yandex_kassa = new yandex_kassa();
        $html_form = $yandex_kassa->render($payed_sum, $bill->account->id, $payment, $billReserveId);
        $objResponse->script("\n            var qp_form_wrapper = \$\$('#quick_payment_masssending .__quick_payment_form');\n            if(qp_form_wrapper){    \n                qp_form_wrapper.set('html','{$html_form}');\n                qp_form_wrapper.getElement('form')[0].submit();\n            }\n        ");
        //сохранаем в сессию куда перейти при успешной покупке
        $_SESSION[quickPaymentPopup::QPP_REDIRECT] = '/bill/history/?period=3';
    }
    // Показываем предупреждение в случае ошибки
    if ($is_error) {
        $objResponse->script("\n            var qp = window.quick_payment_factory.getQuickPayment('masssending');\n            if(qp) qp.show_error('Возникла ошибка при оплате рассылки!');\n        ");
    }
    return $objResponse;
}
/**
 * Покупка услуги верификации по банковской карте через ЯКассу
 * в случае успешной покупки делается запрос на возврат 10 рублей.
 * 
 * @return \xajaxResponse
 */
function quickYandexKassaAC($fname, $lname)
{
    $objResponse = new xajaxResponse();
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/billing.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/yandex_kassa.php';
    $uid = get_uid(false);
    $bill = new billing($uid);
    //@todo: нужна проверка текущей верификации
    $option = array('uname' => change_q(substr(trim($fname), 0, 21)), 'usurname' => change_q(substr(trim($lname), 0, 21)));
    $billReserveId = $bill->addServiceAndCheckout(Verification::YKASSA_AC_OP_CODE, $option);
    $sum = $bill->getOrderPayedSum();
    $yandex_kassa = new yandex_kassa();
    $html_form = $yandex_kassa->render($sum, $bill->account->id, yandex_kassa::PAYMENT_AC, $billReserveId);
    $objResponse->script("\n        if (window.verification_popup) {\n            window.verification_popup.openWindowYandexKassaAC('{$html_form}');\n        }\n    ");
    $_SESSION['quickver_is_begin'] = 1;
    return $objResponse;
}
/**
 * Оплата через Плати потом.
 * 
 * @param type $type - тип оплаты
 * @param type $data - данные по параметрам покупаемой услуги
 *
 * @return \xajaxResponse
 */
function quickPaymentTservicebindPlatipotom($type, $data)
{
    $is_error = true;
    $uid = get_uid(false);
    $objResponse =& new xajaxResponse();
    $kind = (int) @$data['kind'];
    $tservice_id = (int) @$data['tservice_text_db_id'];
    $prof_id = (int) @$data['prof_id'];
    $is_prolong = (bool) @$data['is_prolong'];
    $promo_code = (string) @$data['promo'];
    $tservices_binds = new tservices_binds($kind);
    $tservices = new tservices($uid);
    $allow = $tservices_binds->isAllowBind($uid, $tservice_id, $kind, $prof_id);
    $valid = $tservices->isExists($tservice_id) && ($is_prolong ? !$allow : $allow);
    if ($valid) {
        $is_error = false;
        $bill = new billing($uid);
        //Допустимо использование промокодов
        $bill->setPromoCodes('SERVICE_TSERVICEBIND', $promo_code);
        $op_code = $tservices_binds->getOpCode();
        $option = array('weeks' => (int) @$data['weeks'], 'prof_id' => $prof_id, 'tservice_id' => $tservice_id, 'is_prolong' => $is_prolong);
        //Формируем заказ
        $billReserveId = $bill->addServiceAndCheckout($op_code, $option);
        $payed_sum = $bill->getRealPayedSum();
        $platipotom = new platipotom();
        $html_form = $platipotom->render($payed_sum, $bill->account->id, $billReserveId);
        if ($html_form) {
            $idx = quickPaymentPopupTservicebind::getPopupId($is_prolong ? $tservice_id : 0);
            $objResponse->script("\n                var qp_form_wrapper = \$\$('#" . $idx . " .__quick_payment_form');\n                if(qp_form_wrapper){    \n                    qp_form_wrapper.set('html','{$html_form}');\n                    qp_form_wrapper.getElement('form')[0].submit();\n                }\n            ");
            //сохранаем в сессию куда перейти при успешной покупке
            $redirect = (string) @$data['redirect'];
            $_SESSION[quickPaymentPopup::QPP_REDIRECT] = $redirect;
        }
    }
    // Показываем предупреждение в случае ошибки
    if ($is_error) {
        $idx = quickPaymentPopupTservicebind::getPopupId($is_prolong ? $tservice_id : 0);
        $action = $is_prolong ? 'продлении закрепления' : 'закреплении';
        $objResponse->script("\n            var qp = window.quick_payment_factory.getQuickPaymentById('tservicebind', '" . $idx . "');\n            if(qp) qp.show_error('Возникла ошибка при {$action} услуги!');\n        ");
    }
    return $objResponse;
}
    $tmpPrj->setAddedTopDays(4);
}
//Таким проект был в базе
$project = $tmpPrj->getProject();
//Юзер пытается купить скрытый
$tmpPrj->setProjectField('hide', 't');
//Записываются данные о скрытом и срочном. будут сохранены в кэш при $tmpPrj->fix()
$oproject = $project;
if ($tmpPrj->isEdit()) {
    $tmpPrj->setProjectField('o_hide', $oproject['hide']);
    $tmpPrj->setProjectField('o_urgent', $oproject['urgent']);
}
$tmpPrj->fix();
$account_sum = $account->sum;
$account_bonus_sum = $account->bonus_sum;
$bill = new billing($uid);
$bill->cancelAllNewAndReserved();
//Здесь впервые считается цена
if ($tmpPrj->getAmmount()) {
    $tmpProject = $tmpPrj->getProject();
    //Цена считается повторно, в $items формируется список услуг
    $price = $tmpPrj->getPrice($items, $__temp, true);
    $option = array('is_edit' => $tmpPrj->isEdit(), 'items' => $items, 'prj_id' => $project['id'], 'logo_id' => $logo['id'], 'logo_link' => $tmpProject['link']);
    if ($items['top']) {
        $option['addTop'] = $tmpPrj->getAddedTopDays();
    }
    if ($tmpPrj->isKonkurs()) {
        if (new_projects::isNewContestBudget()) {
            $cost = $tmpPrj->getCostRub();
            $op_code = new_projects::getContestTaxOpCode($tmpPrj->getCostRub(), is_pro());
            $items['contest']['no_pro'] = $tmpPrj->isEdit() ? 0 : new_projects::getContestTax($cost, is_pro());
Exemple #8
0
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/osmppay.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/billing.php';
if (isset($_POST['cancel'])) {
    $back_url = $_SESSION['referer'];
    unset($_SESSION['referer']);
    header("Location: {$back_url}");
    exit;
} elseif (isset($_POST['success'])) {
    $sum = $_SESSION['post_payment']['sum'];
    $bill = new billing(get_uid(false));
    $account = new osmppay();
    $error = $account->checkdeposit($op_id, $result, $sum, $bill->user['login'], rand(1, 999999999), date('YmdHis'));
    header('Location: /bill/');
    exit;
}
$bill = new billing(get_uid(false));
$bill->test = true;
$bill->setPaymentMethod('qiwi');
$created = $bill->error;
$_SESSION['post_payment'] = $_POST;
$_SESSION['referer'] = $_SERVER['HTTP_REFERER'];
?>

<h2>Тестовая оплата Терминалы OSMP</h2>
<p>
Оплата услуг аккаунт #<?php 
echo get_uid(false);
?>
, сумма оплаты <?php 
echo to_money($_POST['sum'], 2);
?>
 /**
  * Пересчитывает даты начала и окончания закрепления по операции.
  *
  * @param int   $uid
  * @param array $params
  *
  * @return type
  */
 private function recalcBindDates($uid, $params)
 {
     //Получаем коды операций, которые могли быть применены по данному закреплению
     $op_codes_allow = array();
     foreach ($this->op_codes_groups as $group) {
         $op_codes_in_group = billing::extendOpCodes($group);
         if (in_array($params['op_code'], $op_codes_in_group)) {
             $op_codes_allow = $op_codes_in_group;
         }
     }
     //Получаем информацию об остальных платежах по данному закреплению
     $sql2 = "SELECT bq.op_code, bq.op_count, bq.src_id, bq.option, bq.service, br.complete_time::timestamp as date\n            FROM bill_queue bq\n            INNER JOIN bill_reserve br ON bq.reserve_id = br.id\n            INNER JOIN account_operations ao ON br.ammount = -(ao.ammount) \n                AND br.complete_time::timestamp = ao.op_date::timestamp\n                AND ao.billing_id = (SELECT id FROM account WHERE uid = ?i)\n            WHERE bq.uid = ?i AND bq.op_code IN (?l)\n                AND ((bq.service = 'tservicebind' AND bq.src_id = ?i) OR (bq.service = 'tservicebindup' AND bq.src_id = ?i))\n                AND bq.status = 'complete' AND bq.id != ?i\n            ORDER BY br.complete_time ASC;";
     $operations = $this->db()->rows($sql2, $uid, $uid, $op_codes_allow, $params['prof_id'], $params['bind_id'], $params['op_id']);
     foreach ($operations as $operation) {
         $is_prolong = $is_up = false;
         //Устанавливаем даты начала при любой операции
         $date_start = DateTime::createFromFormat('Y-m-d H:i:s.u', $operation['date']);
         if ($operation['service'] == 'tservicebind') {
             $options = mb_unserialize($operation['option']);
             if ($options['tservice_id'] != $params['tservice_id']) {
                 continue;
             }
             $is_prolong = $options['is_prolong'];
         } else {
             $is_up = true;
         }
         if (!$is_prolong && !$is_up || !isset($date_stop)) {
             //Если покупка, то дату окончания считаем от даты покупки
             $date_stop = clone $date_start;
             $date_stop->add(new DateInterval('P' . $operation['op_count'] * 7 . 'D'));
         } elseif ($is_prolong) {
             //Если продление - продляем дату окончания
             $date_stop->add(new DateInterval('P' . $operation['op_count'] * 7 . 'D'));
         }
     }
     if (!isset($date_stop)) {
         $date_stop = clone $date_start;
     }
     return array('start' => $date_start->format('Y-m-d H:i:s'), 'stop' => $date_stop->format('Y-m-d H:i:s'));
 }
Exemple #10
0
        include $_SERVER['DOCUMENT_ROOT'] . "/bill/services/" . billing::getTemplateByService($service['service']);
    }
}
//if
if (!empty($bill->list_types_services['notused'])) {
    $notusedText = empty($bill->list_types_services['active']) && empty($bill->list_types_services['lately']) ? 'Вы можете заказать' : 'Вы также можете заказать';
    ?>
<h2 class="b-layout__title <?php 
    echo !($is_active || $is_lately) ? "" : "b-layout__title_padtop_50";
    ?>
"><?php 
    echo $notusedText;
    ?>
</h2><?php 
    foreach ($bill->list_types_services['notused'] as $service) {
        include $_SERVER['DOCUMENT_ROOT'] . "/bill/services/" . billing::getTemplateByService($service['service']);
    }
}
//if
?>

        <span id="wallet">
        <?php 
$popup_content = $_SERVER['DOCUMENT_ROOT'] . "/bill/widget/popups/popup.wallet.php";
include $_SERVER['DOCUMENT_ROOT'] . "/bill/widget/tpl.popup.php";
?>
        </span>
    </div>
    
<div class="b-layout__one b-layout__one_width_25ps b-layout__one_float_left b-layout__one_margleft_3ps b-layout__one_width_full_ipad">
    <?php 
Exemple #11
0
 public function __construct($id = null)
 {
     global $user;
     // if an ID is passed in we'll look up the cart from the database...it means this is
     // probably a completed order an admin is looking at it via the order admin interface.
     //if (empty($id)) {
     //    global $order;
     //} else {
     //$order = new order($id);
     //}
     /*
             // check for this users billing method object.  If it hasn't been created yet then lets do it now.
             if (empty($order->billingmethod)) {
                 $order->billingmethod[0] = new billingmethod();
                 $order->billingmethod[0]->update(array('orders_id'=>$order->id)); 
             } */
     //if (empty($order->billingmethod[0]->addresses_id) && $user->isLoggedIn()) {
     //if ($user->isLoggedIn()) {
     if ($id == null) {
         // since this is a new billingmethod object, lets initialize it with the users billing address.
         global $order;
         $address = new address();
         //FJD $defaultaddy = $address->find('first', 'user_id='.$user->id.' AND is_default=1');
         if (empty($order->billingmethod)) {
             $order->billingmethod[0] = new billingmethod();
             $order->billingmethod[0]->update(array('orders_id' => @$order->id));
             // @ added to ditch notice when ecom is off
         }
         $billingAddy = $address->find('first', 'user_id=' . $user->id . ' AND is_billing=1');
         $order->billingmethod[0]->setAddress($billingAddy);
     } else {
         $order = new order($id);
         if (empty($order->id)) {
             return false;
         }
     }
     //}
     $this->address = new address($order->billingmethod[0]->addresses_id);
     //$this->address = new address($order->billingmethod[0]->id);
     $this->available_calculators = billing::listAvailableCalculators();
     $this->selectable_calculators = $this->selectableCalculators();
     $this->calculator_views = $this->getCalcViews();
     // if there is only one available calculator we'll force it on the user
     // also if the user hasn't selected a calculator yet well set it to a default.
     $number_of_calculators = count($this->available_calculators);
     if ($number_of_calculators == 1 || empty($order->billingmethod[0]->billingcalculator_id)) {
         reset($this->available_calculators);
         $calcid = key($this->available_calculators);
         $order->billingmethod[0]->update(array('billingcalculator_id' => $calcid));
     }
     if ($number_of_calculators > 0) {
         $calcname = $this->available_calculators[$order->billingmethod[0]->billingcalculator_id];
         $this->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);
     } else {
         $this->calculator = null;
     }
     $this->billingmethod = $order->billingmethod[0];
     $options = unserialize($this->billingmethod->billing_options);
     $this->info = empty($this->calculator->id) ? '' : $this->calculator->userView($options);
     foreach ($this->available_calculators as $key => $item) {
         $calc = new $item($key);
         $this->form[$key] = $calc->userForm();
     }
     // eDebug($this->form, true);
 }
Exemple #12
0
 if (strtolower($_POST['pro_auto_prolong']) == 'on') {
     $user->setPROAutoProlong('on', $uid);
     $result['success'] = true;
     if (!WalletTypes::isWalletActive($uid)) {
         $result['wallet_popup'] = true;
     }
     echo json_encode($result);
     exit;
 }
 if (strtolower($_POST['pro_auto_prolong']) == 'off') {
     $user->setPROAutoProlong('off', $uid);
     echo json_encode(array('success' => true));
     exit;
 }
 if ($uid) {
     $bill = new billing($uid);
     $_SESSION['pro_last'] = payed::ProLast($_SESSION['login']);
     $_SESSION['pro_last'] = $_SESSION['pro_last']['is_freezed'] ? false : $_SESSION['pro_last']['cnt'];
     $_SESSION['is_was_pro'] = $_SESSION['pro_last'] ? true : payed::isWasPro($_SESSION['uid']);
     if ($_SESSION['pro_last']['is_freezed']) {
         $_SESSION['payed_to'] = $_SESSION['pro_last']['cnt'];
     }
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/account.php';
     $op_codes = new op_codes();
     $opcodes = $op_codes->getCodes('80,16,65');
     $user = new freelancer();
     $user->GetUser($_SESSION['login']);
     $account = new account();
     $ok = $account->GetInfo($uid, true);
     $u_is_pro_auto_prolong = $user->GetField($uid, $e, 'is_pro_auto_prolong', false);
     // Включено ли у юзера автоматическое продление PRO
Exemple #13
0
     $view_account = new account();
     $view_account->GetInfo($uid);
     $account_sum = $view_account->sum;
     $account_bonus_sum = $view_account->bonus_sum;
     $view_user_login = $tmpPrj->getAuthorLogin();
 }
 if ($action == 'save') {
     $_POST['logo_id'] = $_POST['logo_file_id'];
     if ($PDA && !$tmpPrj->getCategories()) {
         $cats = array();
         $cats[] = array('category_id' => $project['category'], 'subcategory_id' => $project['subcategory']);
         $tmpPrj->setCategories($cats);
     }
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/drafts.php";
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/billing.php";
     $bill = new billing($uid);
     $bill->clearOrders();
     $tmpProject = $tmpPrj->getProject();
     if ($tmpPrj->isVacancy()) {
         $initedState = $tmpProject['state'];
         $tmpPrj->setProjectField('old_state', $initedState);
         $tmpPrj->setProjectField('state', projects::STATE_PUBLIC);
     }
     if ($tmpPrj->getAmmount() && $account_bonus_sum < $tmpPrj->getAmmount()) {
         if (!$tmpPrj->isEdit()) {
             $tmpProject['uid'] = $uid;
             $tmpProject['draft_id'] = $draft_id;
             $tmpProject['project_profession0_columns'] = $_POST['project_profession0_columns'];
             $tmpProject['project_profession1_columns'] = $_POST['project_profession1_columns'];
             $tmpProject['project_profession2_columns'] = $_POST['project_profession2_columns'];
             $tmpProject['currency_db_id'] = $tmpProject['currency'];
Exemple #14
0
 /**
  * Функция для автооплаты (учитывает состояние личного счета).
  *
  * @param billing $bill    Объект биллинга (должен быть подготовлен резерв перед оплатой @see self::preparePayments())
  * @param float   $ammount Сумма для списывания
  */
 public static function autoPayed(billing $bill, $ammount)
 {
     if ($bill->reserved <= 0) {
         return false;
     }
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/wallet/wallet.php';
     $complete = false;
     $wallet = WalletTypes::initWalletByType($bill->user['uid']);
     // Пытаемся оплатить из личного счета иначе автооплатой если она включена
     // @todo при неудаче покупки пробовать ли оплатить через привязанный кошелек?
     if ($bill->acc['sum'] >= $ammount) {
         $bill->transaction = $bill->account->start_transaction($bill->user['uid'], 0);
         $complete = $bill->completeOrders($bill->reserved);
         if ($complete) {
             $bill->account->commit_transaction($bill->transaction, $bill->user['uid'], null);
         }
     } elseif (WalletTypes::checkWallet($wallet)) {
         if ($wallet->api->checkToken()) {
             // Проводим списывание денег
             $complete = $wallet->payment($ammount);
         } else {
             // Ключ не действителен сообщаем об этом владельцу
             $complete = false;
         }
     }
     // Если все плохо отменяем операции
     if (!$complete) {
         $success = $bill->setReserveStatus($bill->reserved, self::RESERVE_CANCEL_STATUS);
         if ($success) {
             $bill->updateOrderListStatus($bill->reserved, self::STATUS_DELETE);
         }
     }
     return $complete;
 }
Exemple #15
0
 /**
  * Посылает уведомление о том что включено автооплата с перечислением того что будет автоплачивать
  * Включение одного или нескольких автопродлений вместе с активацией способа оплаты
  *
  * @param $uids         Список ИД пользователей
  * @param null $connect
  * @return int
  */
 public function activateWallet($uids, $connect = NULL)
 {
     if (!is_array($uids)) {
         return;
     }
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/billing.php';
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/wallet/wallet.php';
     foreach ($uids as $uid) {
         if ((int) $uid <= 0) {
             continue;
         }
         // Мало ли
         $bill = new billing((int) $uid);
         if (substr($bill->user['subscr'], 15, 1) != '1') {
             continue;
         }
         $autopay = billing::getAllAutoPayed($uid);
         if (empty($autopay)) {
             continue;
         }
         // Автопродление не включено
         $wallet = walletTypes::initWalletByType($uid);
         if (!walletTypes::checkWallet($wallet)) {
             continue;
         }
         // Метод оплаты уже не действителен
         $walletName = str_replace("%WALLET%", $wallet->getWalletBySecure(), walletTypes::getNameWallet($wallet->data['type'], 2));
         $message = "Вы подключили {$walletName} в качестве средства оплаты при автопродлении следующих услуг:<br/><br/>";
         foreach ($autopay as $payed) {
             $message .= "-&nbsp;{$payed['name']} ({$payed['cost']} руб.)<br/>";
         }
         $message .= "<br/>";
         $message .= "Информацию о способах оплаты и автопродлении услуг, а также ответы на все интересующие вопросы вы можете найти в нашем <a href='http://feedback.fl.ru/{$this->_addUrlParams('b', '?')}'>сообществе поддержки</a>.";
         $this->subject = "FL.ru: Подключение нового способа оплаты";
         $this->recipient = "{$bill->user['uname']} {$bill->user['usurname']} [{$bill->user['login']}] <{$bill->user['email']}>";
         $this->message = $this->GetHtml($bill->user['uname'], $message, array('header' => 'default', 'footer' => 'default'), array('login' => $bill->user['login']));
         $this->send('text/html');
     }
     return $this->sended;
 }
Exemple #16
0
$customerNumber = 120824;
//$_GET['cn'];
$ammount = 569;
//$_GET['ammount'];
$invoiceId = 2000246796791.0;
//$_GET['invoiceId'];
$payments = 3;
$orderId = 367369;
$params['invoiceId'] = $invoiceId;
/*
3 => self::PAYMENT_YD,
6 => self::PAYMENT_AC,
10 => self::PAYMENT_WM,
16 => self::PAYMENT_AB,
17 => self::PAYMENT_SB
*/
$descr = "Платеж через Яндекс.Кассу. Сумма - {$ammount}, номер покупки - {$invoiceId}";
//------------------------------------------------------------------------------
//Заносим деньги на ЛС
$account = new account();
$error = $account->deposit($op_id, $customerNumber, $ammount, $descr, $payments, $ammount, 12);
if (!$error) {
    //Пробуем купить заказ за который занесли деньги выше
    if ($orderId > 0) {
        $billing = new billing($account->uid);
        $billing->buyOrder($orderId, 12, $params);
    }
    exit;
}
echo $error;
exit;
 /**
  * Переопределяем события после изменения статуса
  * резерва оплаты для заказов ТУ
  * 
  * @param type $new_status
  */
 public function afterChangeStatus($new_status)
 {
     $success = false;
     $time = time();
     switch ($new_status) {
         case self::STATUS_CANCEL:
             //Отмена заказа заказчиком то отменяем заказ если была попытка зарезервировать
             if ($_SESSION['uid'] == $this->reserve_data['emp_id']) {
                 require_once ABS_PATH . "/classes/billing.php";
                 $billing = new billing($this->reserve_data['emp_id']);
                 $billing->cancelReserveByOrder('reserves', $this->reserve_data['id']);
             }
             $success = true;
             break;
         case self::STATUS_ERR:
             $this->getOrderHistory()->reservePriceErr();
             break;
         case self::STATUS_RESERVE:
             //После успешного резервирования средств
             //переводим заказ в статус начала работы
             $src_id = @$this->reserve_data['src_id'];
             $success = $this->db()->update($this->TABLE_TSERVICE_ORDER, array('status' => TServiceOrderModel::STATUS_ACCEPT, 'accept_date' => date('Y-m-d H:i:s', $time)), 'id = ?i', $src_id);
             if ($success) {
                 $orderModel = TServiceOrderModel::model();
                 $order = $orderModel->getShortCard($src_id);
                 if ($order) {
                     //@todo: можно передать просто $this ?
                     $reserveInstance = ReservesModelFactory::getInstance(ReservesModelFactory::TYPE_TSERVICE_ORDER);
                     if ($reserveInstance) {
                         $reserveInstance->setSrcObject($orderModel);
                         $reserveInstance->setReserveData($this->reserve_data);
                         $order['reserve'] = $reserveInstance;
                     }
                     $this->getOrderHistory()->reservePriceSuccess($this->reserve_data['price']);
                     $order['reserve_data'] = $this->reserve_data;
                     $reservesSmail = new ReservesSmail();
                     $reservesSmail->attributes(array('order' => $order));
                     $reservesSmail->onReserveOrder();
                     //Генерируем документы
                     require_once ABS_PATH . '/classes/DocGen/DocGenReserves.php';
                     $doc = new DocGenReserves($order);
                     $doc->generateSpecification();
                 }
             }
             break;
         case self::STATUS_PAYED:
         case self::STATUS_ARBITRAGE:
             //@todo: генерируем документ когда резерв закрыт после всех выплат
             $src_id = @$this->reserve_data['src_id'];
             $orderModel = TServiceOrderModel::model();
             $order = $orderModel->getShortCard($src_id);
             if ($order) {
                 $this->getOrderHistory();
                 require_once ABS_PATH . '/classes/DocGen/DocGenReserves.php';
                 $order['reserve_data'] = $this->reserve_data;
                 $order['reserve'] = $this;
                 $doc = new DocGenReserves($order);
                 $doc->generateActServiceEmp();
                 $doc->generateAgentReport();
             }
         default:
             $success = true;
     }
     return $success;
 }
Exemple #18
0
    unset($_SESSION['referer']);
    header("Location: {$back_url}");
    exit;
} elseif (isset($_POST['success'])) {
    $sum = $_SESSION['post_payment']['sum'];
    $account = new account();
    $account->GetInfo($qiwipay->uid, true);
    $bill = $DB->row("SELECT * FROM qiwi_account WHERE account_id = ? order by id desc LIMIT 1", $account->id);
    $error = $qiwipay->completeBill($error, $bill, $sum);
    var_dump($error);
    var_dump($DB->sql);
    exit;
    header("Location: /bill/");
    exit;
}
$bill = new billing(get_uid(false));
$bill->test = true;
$bill->setPaymentMethod('qiwipurse');
$created = $bill->error;
$_SESSION['post_payment'] = $_POST;
$_SESSION['referer'] = $_SERVER['HTTP_REFERER'];
?>

<h2>Тестовая оплата QIWI.Purse</h2>
<p>
Оплата услуг аккаунт #<?php 
echo get_uid(false);
?>
, сумма оплаты <?php 
echo to_money($_POST['sum'], 2);
?>
 /**
  * Пересчитывает даты начала и окончания закрепления по операции
  * @param type $operation
  * @param type $uid
  * @return type
  */
 private function recalcBindDates($operation, $uid)
 {
     //Получаем коды операций, которые могли быть применены по данному закреплению
     $op_codes_allow = array();
     foreach ($this->op_code_groups as $group) {
         $op_codes_in_group = billing::extendOpCodes($group);
         if (in_array($operation['op_code'], $op_codes_in_group)) {
             $op_codes_allow = $op_codes_in_group;
         }
     }
     //Получаем информацию об остальных платежах по данному закреплению
     $sql2 = "SELECT bq.op_code, bq.op_count, br.complete_time::timestamp as date\n            FROM bill_queue bq\n            INNER JOIN bill_reserve br ON bq.reserve_id = br.id\n            INNER JOIN account_operations ao ON br.ammount = -(ao.ammount) \n                AND br.complete_time::timestamp = ao.op_date::timestamp\n                AND ao.billing_id = (SELECT id FROM account WHERE uid = ?i)\n            WHERE bq.uid = ?i AND bq.service IN ('frlbind', 'frlbindup')\n                AND bq.src_id = ?i AND bq.op_code IN (?l)\n                AND bq.status = 'complete' AND bq.id != ?i\n            ORDER BY br.complete_time ASC;";
     $operations = $this->db->rows($sql2, $uid, $uid, $operation['src_id'], $op_codes_allow, $operation['id']);
     foreach ($operations as $operation) {
         //Устанавливаем даты начала при любой операции
         $date_start = DateTime::createFromFormat("Y-m-d H:i:s.u", $operation['date']);
         $operation['op_code'] = billing::getOpCodeByDiscount($operation['op_code']);
         if (in_array($operation['op_code'], array(self::OP_CODE_CATALOG, self::OP_CODE_PROFGROUP, self::OP_CODE_PROF)) || !isset($date_stop)) {
             //Если покупка, то дату окончания считаем от даты покупки
             $date_stop = clone $date_start;
             $date_stop->add(new DateInterval('P' . $operation['op_count'] * 7 . 'D'));
         } else {
             //Если продление - продляем дату окончания
             if (in_array($operation['op_code'], array(self::OP_CODE_PROLONG_CATALOG, self::OP_CODE_PROLONG_PROFGROUP, self::OP_CODE_PROLONG_PROF))) {
                 $date_stop->add(new DateInterval('P' . $operation['op_count'] * 7 . 'D'));
             }
         }
     }
     if (!isset($date_start)) {
         $date_start = new DateTime('NOW');
     }
     if (!isset($date_stop)) {
         $date_stop = clone $date_start;
     }
     return array('start' => $date_start->format('Y-m-d H:i:s'), 'stop' => $date_stop->format('Y-m-d H:i:s'));
 }
Exemple #20
0
<?php

$g_page_id = "0|27";
$new_site_css = true;
require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/stdf.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/billing.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/bar_notify.php";
$main_path = $_SERVER['DOCUMENT_ROOT'];
if (!get_uid()) {
    header('Location: /fbd.php');
    exit;
}
$content = "{$main_path}/bill/send/content.php";
$header = "{$main_path}header.new.php";
$footer = "{$main_path}footer.new.html";
$js_file = array('billing.js');
$bill = new billing(get_uid(false));
$bill->setPage('send');
include "{$main_path}/template3.php";
Exemple #21
0
if ($_SESSION['quickbuypro_is_begin'] == 1) {
    echo '<html><body><script>window.close();</script></body></html>';
    exit;
}
if (__paramInit('string', 'quickprobuy', 'quickprobuy', null) == 1) {
    unset($_SESSION['quickpro_order']);
    echo '<html><body><script>window.close();</script></body></html>';
    exit;
}
//После неудачной оплаты по банковской карте за верификацию закрываем окно
if ($_SESSION['quickver_is_begin'] == 1) {
    unset($_SESSION['quickver_is_begin']);
    echo '<html><body><script>window.close();</script></body></html>';
    exit;
}
$bill = new billing(get_uid(0));
$action = __paramInit('string', null, 'action', null);
// заново оплатить
if ($action === 'pay') {
    $reserveID = __paramInit('string', null, 'reserve_id', null);
    if ($reserveID) {
        $success = $bill->setReserveStatus($reserveID, billing::RESERVE_CANCEL_STATUS);
        if ($success) {
            if ($bill->updateOrderListStatus($reserveID, billing::STATUS_NEW)) {
                header_location_exit('/bill/orders/');
            }
        }
    }
}
$bill->setPage('fail');
if (!count($bill->list_service)) {
/**
 * Оплата карусели через Плати потом
 * 
 * @param type $type
 * @param type $data
 * @return \xajaxResponse
 */
function quickPaymentProPlatipotom($type, $data)
{
    $uid = get_uid(false);
    $objResponse = new xajaxResponse();
    if (!($uid > 0)) {
        return $objResponse;
    }
    $is_emp = is_emp();
    $form = new ProForm($is_emp);
    if (!$form->isValid($data)) {
        $objResponse->script("\n            var qp = window.quick_ext_payment_factory.getQuickPayment('pro');\n            if(qp) qp.show_error('К сожалению, в процессе оплаты произошла ошибка, и платеж не был завершен. Попробуйте провести оплату еще раз.');\n        ");
        return $objResponse;
    }
    $data = $form->getValues();
    $opcode = $data['type'];
    $promo_code = isset($data['promo']) ? $data['promo'] : "";
    $bill = new billing($uid);
    //Допустимо использование промокодов
    $bill->setPromoCodes('SERVICE_PRO', $promo_code);
    //Формируем заказ
    $billReserveId = $bill->addServiceAndCheckout($opcode);
    $sum = $bill->getRealPayedSum();
    $platipotom = new platipotom(true);
    if ($sum > 0 && $sum <= $platipotom->getMaxPrice($bill->account->id)) {
        $html_form = $platipotom->render($sum, $bill->account->id, $billReserveId);
        if ($html_form) {
            $objResponse->script("\n                var qp = window.quick_ext_payment_factory.getQuickPayment('pro');\n                if (qp) qp.sendPaymentForm('{$html_form}');\n            ");
            //сохранаем в сессию куда перейти при успешной покупке
            $_SESSION[quickPaymentPopup::QPP_REDIRECT] = urldecode($_SESSION['ref_uri']);
            $payed_sum = $bill->getRealPayedSum();
            //@todo: функционал из старого попапа оплаты нужен рефакторинг
            $_SESSION['quickbuypro_is_begin'] = 1;
            $_SESSION['quickbuypro_success_opcode'] = $payed_sum;
            $_SESSION['quickbuypro_success_opcode2'] = $opcode;
            //$_SESSION['quickbuypro_redirect'] = $redirect;
        }
    }
    return $objResponse;
}
Exemple #23
0
    <div class="b-layout__one b-layout__one_width_25ps b-layout__one_padbot_30 b-layout__right_float_right b-layout__one_width_full_ipad b-layout_padbot_10_ipad">
       <?php 
include $_SERVER['DOCUMENT_ROOT'] . '/bill/widget/tpl.score.php';
?>
    </div>


    
    <div class="b-layout__one b-layout__one_float_left b-layout__one_width_72ps b-layout__one_width_full_ipad">
        <?php 
$pro_payed = payed::getPayedPROList(is_emp($bill->user['role']) ? 'emp' : 'frl');
foreach ($pro_payed as $p) {
    $pro_type[$p['opcode']] = $p;
}
foreach ($bill->list_service as $service) {
    include $_SERVER['DOCUMENT_ROOT'] . '/bill/payment/services/' . billing::getTemplateByService($service['service']);
}
$payment_sum = $bill->payed_sum['pay'];
//@todo везде поменять надо будет
?>

        <h2 class="b-layout__title b-layout__title_padtop_30">Способ платежа</h2>
        <div class="b-layout__txt b-layout__txt_fontsize_15 b-layout__txt_bold b-layout__txt_padbot_20">
            <?php 
if ($bill->type_menu_block == 'psys') {
    ?>
            <span id="active-systems" data-system="psys_systems">Платежные системы</span> &nbsp;&nbsp;&nbsp;
            <?php 
} else {
    ?>
            <a class="b-layout__link b-layout__link_bold b-layout__link_bordbot_dot_0f71c8" data-system="psys_systems" href="/bill/payment/?type=webmoney" >Платежные системы</a> &nbsp;&nbsp;&nbsp;
Exemple #24
0
 /**
  * Выполняет покупку.
  */
 public function order()
 {
     //Запрещаем вывод ошибок
     $this->db()->error_output = false;
     $orderid = $_GET['orderid'];
     if (!$orderid) {
         exit;
     }
     $json_data = array('status' => '0', 'time' => time());
     $payment = $this->getPayment($orderid);
     if ($payment) {
         $data = isset($_REQUEST['data']) && is_array($_REQUEST['data']) ? $_REQUEST['data'] : array();
         $sig = $this->getSig($payment['price'], $orderid, $payment['billing_id'], $data);
         if ($sig == $_GET['sig']) {
             $json_data['status'] = '1';
             $op_id = 0;
             //Занесли деньги
             $account = new account();
             $error = $account->deposit($op_id, $payment['billing_id'], $payment['price'], "Платеж через \"Плати потом\". Сумма - {$payment['price']}, номер покупки - {$orderid}", self::PAYMENT_CODE, $payment['price']);
             if (!$error) {
                 //Пробуем купить
                 $billing = new billing($account->uid);
                 $billing->buyOrder($payment['bill_reserve_id'], 12, array());
                 $this->db()->query("DELETE FROM {$this->TABLE} WHERE id = ?", $orderid);
                 $memBuff = new memBuff();
                 $memBuff->delete('platipotom_max_price_' . $account->uid);
             }
         }
     }
     return $json_data;
 }
Exemple #25
0
 /**
  * Получить наименование операции для вывода в таблице истории
  *
  * @param integer $bill_id		идентификатор операции
  * @param integer $uid			ID Пользователя
  * @return string				текстовое описание операции
  */
 public static function GetHistoryText(&$val)
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/billing.php";
     //Входной опкод может быть для скидки поэтому пробуем получить его оригинал услуги
     $original_op_code = $val['op_code'];
     $val['op_code'] = billing::getOpCodeByDiscount($val['op_code']);
     $html = $val['op_name'];
     if ($val['op_code'] == billing::RESERVE_OP_CODE) {
         $html .= ' &#160;&#160;&#160;<a class="b-layout__link b-layout__link_fontsize_11 b-layout__link_bordbot_dot_80 b-layout__link_inline-block b-layout__link_lineheight_1" href="javascript:void(0);" onclick="xajax_ShowReserveOrders(' . $val['id'] . ');">подробнее</a>';
     }
     if ($val['op_code'] == 16) {
         $html .= '(EMP)';
     }
     if ($val['op_code'] == 52) {
         $html .= '(FL)';
     }
     if ($val['op_code'] < 7 || in_array($val['op_code'], array(8, 11, 15, 16, 17, 18, 23, 24, 25, 33, 52, 63, 64, 66, 67, 68, 12, 38, 45, 47, 114, 131, 132, 48, 49, 50, 51, 69, 76, 80, 84, 83, 85, 118, 119, 120, 163, 164))) {
         $html .= ' &#160;&#160;&#160;<a class="b-layout__link b-layout__link_fontsize_11 b-layout__link_bordbot_dot_80 b-layout__link_inline-block b-layout__link_lineheight_1" href="javascript:void(0);" onclick="xajax_ShowBillComms(' . $val['id'] . ', 0, 1);">подробнее</a>';
     }
     /**
      * Платные опции проектов
      * @TODO Конструкция монструозная, конечно. Хотя делает простую вещь. Вынести в метод?
      * @todo Почему она вообще здесь и отрабатывает на каждую итерацию?
      * @todo Зачем вообще нужен этот метод?
      */
     if (in_array($val['op_code'], array(9, 53, 86, 106, 138, 139, 140, 141, 113, 192))) {
         //Если нет ИД проекта, парсим его из строки
         //Старые операции - с пробелом после №
         if (!$val['project_id']) {
             preg_match('~№ (\\d+)~', $val['comments'], $match);
             $val['project_id'] = $match[1];
         }
         //Не нашли, тогда новые - без пробела
         if (!$val['project_id']) {
             preg_match('~№(\\d+)~', $val['comments'], $match);
             $val['project_id'] = $match[1];
         }
         $parts = explode(' & ', $val['comments']);
         if (count($parts) == 2) {
             $words = explode(' ', $parts[0]);
             $projectNumber = false;
             foreach ($words as $key => &$word) {
                 if (strpos($word, '№') === false) {
                     continue;
                 }
                 $projectNumber = $key;
                 //Номер мог не записался в операцию, если покупка была при создании
                 if ($word == '№') {
                     $word .= $val['project_id'];
                 }
             }
             $html = '';
             $words[$projectNumber - 1] = '<a class="b-layout__link" href="/projects/' . $val['project_id'] . '">' . $words[$projectNumber - 1];
             $words[$projectNumber] .= '</a>';
             $html = implode(' ', $words);
             $val['comments'] = $parts[1];
         } else {
             $html = '<a class="b-layout__link" href="/projects/' . $val['project_id'] . '">' . $val['op_name'] . '</a>';
         }
     }
     //Платные места в каталоге
     if (in_array($val['op_code'], array(142, 143, 144))) {
         $html = $val['descr'];
     }
     //Поднятие платного места
     if (in_array($val['op_code'], array(10, 20, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162))) {
         $html = $val['descr'];
     }
     //Поднятие платного места
     if (in_array($val['op_code'], array(10, 19, 20))) {
         if ($val['descr']) {
             $html = $val['descr'];
         } else {
             //У старых платежей описание не заполнено
             $html = $val['op_name'] . ' &#160;&#160;&#160;<a class="b-layout__link b-layout__link_fontsize_11 b-layout__link_bordbot_dot_80 b-layout__link_inline-block b-layout__link_lineheight_1" href="javascript:void(0);" onclick="xajax_ShowBillComms(' . $val['id'] . ', 0, 1);">подробнее</a>';
         }
     }
     //Услуга по скидке, пока у нас только для PROFI
     //поэтому дописываем пометку
     if ($original_op_code != $val['op_code'] && !in_array($original_op_code, array(165, 166))) {
         $html .= '  (для profi)';
     }
     return $html;
 }
 public function actionIndex()
 {
     $limit = 20;
     $do = __paramInit('string', 'do', 'do', '');
     $page = __paramInit('int', 'page', 'page', 1);
     $filter = array();
     $filter_default = array('date' => date('d.m.Y', strtotime('-1 month')) . ' - ' . date('d.m.Y'));
     switch ($do) {
         case 'factura_delete':
             $nums = __paramInit('array', NULL, 'num', null);
             $this->billInvoicesAdminModel->deleteFactura($nums);
             break;
         case 'factura_update':
             $invoice_id = __paramInit('int', NULL, 'invoice_id', null);
             $file = $_FILES['new_file'];
             $this->billInvoicesAdminModel->updateFactura($invoice_id, $file);
             break;
         case 'factura':
             $nums = __paramInit('array', NULL, 'num', null);
             $dates = __paramInit('array', NULL, 'date', null);
             $this->billInvoicesAdminModel->addFactura($nums, $dates);
             break;
         case 'filter':
             $filter['do'] = $do;
             $filter['login'] = __paramInit('string', 'login', 'login', '');
             $filter['date'] = __paramInit('string', 'date', 'date', null);
             break;
             //Операция зачисления средств по счету
         //Операция зачисления средств по счету
         case 'pay':
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/account.php';
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/billing.php';
             $sums = __paramInit('array', NULL, 'sum', null);
             //@todo: слишком толстый контроллер
             //все ниже нужно было определить в модель
             $account = new account();
             $user = new users();
             if ($sums) {
                 $sAdmin = 'Запись добавил: ' . @$_SESSION['login'];
                 $sDate = date('c');
                 foreach ($sums as $user_id => $invoices) {
                     $user->GetUserByUID($user_id);
                     if (!$user->uid || !$account->GetInfo($user->uid, true) || empty($invoices)) {
                         continue;
                     }
                     $bill = new billing($user->uid);
                     foreach ($invoices as $invoice_id => $sum) {
                         $account_sum = $account->sum;
                         if (!is_numeric($sum) || $sum <= 0 || $account->sum + $sum < 0) {
                             continue;
                         }
                         $comments = sprintf("Безналичный перевод по счету Б-%06d", $invoice_id);
                         if (!$account->depositEx2($acc_op_id, $account->id, $sum, $sAdmin, $comments, 12, $sum, 4, $sDate)) {
                             $this->billInvoicesAdminModel->update($invoice_id, array('acc_op_id' => $acc_op_id));
                             //Автоматическая покупка услуги погашения задолженности
                             if ($account_sum < 0) {
                                 $payed_sum = abs($account_sum);
                                 $option = array('acc_sum' => $payed_sum);
                                 $billReserveId = $bill->addServiceAndCheckout(135, $option);
                                 if ($billReserveId) {
                                     $bill->buyOrder($billReserveId);
                                 }
                             }
                         }
                     }
                 }
                 $this->redirect('.');
             }
             break;
     }
     $this->billInvoicesAdminModel->setPage($limit, $page);
     $list = $this->billInvoicesAdminModel->setFilter($filter)->getInvoices();
     $count = $this->billInvoicesAdminModel->getInvoicesCnt();
     $filter_query = '';
     if (empty($filter)) {
         $filter = $filter_default;
     } else {
         $filter_query = http_build_query($filter) . '&';
     }
     $this->render('index', array('list' => $list, 'limit' => $limit, 'page' => $page, 'page_count' => $count, 'filter_query' => $filter_query, 'filter' => $filter));
 }
Exemple #27
0
<?php

require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/stdf.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/billing.php';
if (!get_uid(0)) {
    header_location_exit('/404.php');
}
$bill = new billing(get_uid(0));
$bill->setPage('success');
$js_file = array('billing.js');
$content = 'content.php';
$header = '../../header.new.php';
$footer = '../../footer.new.html';
include '../../template3.php';
Exemple #28
0
 /**
  * Выполняет платеж
  */
 private function addOperation()
 {
     global $DB;
     $DB->error_output = false;
     $shopParams = $this->getShopParams();
     $payment = $DB->row('
         SELECT 
             aoy.id,            
             aoy.descr,
             ao.id AS acc_op_id 
         FROM account_operations_yd AS aoy 
         LEFT JOIN account_operations AS ao ON ao.id = aoy.acc_op_id AND ao.billing_id = aoy.billing_id
         WHERE invoice_id = ?', $this->params['invoiceId']);
     //Пополнение и покупка уже были отвечаем успехом
     if ($payment['acc_op_id'] > 0) {
         return 0;
     }
     $DB->start();
     $op_id = 0;
     $data = array();
     $billing = null;
     $account = new account();
     //Заносим деньги на ЛС
     $error = $account->deposit($op_id, $this->params['customerNumber'], $shopParams['ammount'], $payment['descr'], array_search($this->params['paymentType'], $this->payments), $this->params['orderSumAmount'], $shopParams['op_code']);
     //Если все без ошибок и ЛС зачислены то пробуем купить заказ
     if (!$error && $op_id > 0) {
         $success = true;
         $data['acc_op_id'] = $op_id;
         //Пробуем купить заказ за который занесли деньги выше
         //Если заказ уже куплен или отменен то ничего не делаем но получим успех
         if ($this->params['orderId']) {
             $billing = new billing($account->uid);
             if ($success = $billing->buyOrder($this->params['orderId'], $shopParams['op_code'], $this->params)) {
                 $data['bill_reserve_id'] = $this->params['orderId'];
             }
         }
         //Фиксируем ID операции пополнения ЛС и ID купленного заказа при наличии
         if ($success) {
             $DB->update('account_operations_yd', $data, 'id = ?i', $payment['id']);
             $DB->commit();
             return 0;
         } else {
             $this->message = sprintf('Failed to purchase order #%s', $this->params['orderId']);
         }
     } else {
         $this->message = 'Failed deposit to account';
     }
     //Не удалось приобрести заказ откатываем транзакцию
     //и возвращаем ошибку что приводит к возврату средств
     $DB->rollback();
     //Если отказ принять деньги то и отменяем заказ
     //чтобы не висел в истории
     if ($billing && $this->params['orderId'] > 0) {
         $billing->cancelReserveById($this->params['orderId']);
     }
     //Ошибка, возврат средств
     return 100;
 }
Exemple #29
0
if (date('H') == 1) {
    $log->TRACE($mail->SendWarnings());
    // Отправляет предупреждению юзеру о том, что аккаунт ПРО истекает в ближайшие дни.
    $temp = new users();
    $rpath = '';
    $log->TRACE($temp->DropInactive());
    // Пишем статистику для админки #0003426
    $log->TRACE(stats::writeGeneralStat());
    // Пересчет цен работ фрилансеров в портфолио
    $log->TRACE(professions::calcAvgPrices());
}
if (date('H') == 2) {
    $log->TRACE($mail->ContestReminder());
    $log->TRACE($mail->ContestEndReminder());
    // отмена не оплаченных заказов
    $log->TRACE(billing::checkOldReserve());
}
//------------------------------------------------------------------------------
/**
 * Уведомления закреплений ТУ.
 */
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/tservices_smail.php';
$tservices_smail = new tservices_smail();
$log->TRACE($tservices_smail->remind24hEndBinds());
//за сутки
$log->TRACE($tservices_smail->remindBindsUp());
//если опустился ниже 4 позиции включительно
//------------------------------------------------------------------------------
//За сутки до завершения срока действия закрепления
$mail->remindFreelancerbindsProlong();
//После того, как закрепление опустилось ниже середины списка закреплений (и в списке больше одного закрепления)
Exemple #30
0
function ShowReserveOrders($id)
{
    require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/billing.php";
    $objResponse = new xajaxResponse();
    $uid = get_uid(false);
    if (!$uid) {
        return $objResponse;
    }
    $bill = new billing($uid);
    $info = $bill->getOrderInfo($id, 'comment');
    $info = array_map(create_function('$array', 'return $array["comment"];'), $info);
    if ($info) {
        $info = implode(", ", $info);
        $info .= ' &#160;&#160;&#160;<a class="b-layout__link b-layout__link_fontsize_11 b-layout__link_bordbot_dot_80 b-layout__link_inline-block b-layout__link_lineheight_1" onclick="xajax_ShowReserveText(' . $id . ');" href="javascript:void(0);">Скрыть</a>';
        $objResponse->assign("res" . $id, "innerHTML", $info);
    }
    return $objResponse;
}