Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- require_once DOC_ROOT . 'classes/tools/Element/Element/Common.php';
- if (!class_exists('Element_Order')):
- define('ORDER_STATUS_CHANGED', -1);
- define('ORDER_STATUS_NEW', 0);
- define('ORDER_STATUS_PROCESSING', 1);
- define('ORDER_STATUS_COMPLETE', 2);
- define('ORDER_STATUS_FAILED', 3);
- define('ORDER_STATUS_OFFLINE', 4); // waiting for offline payment
- define('ORDER_STATUS_TIMEOUT', 5); // timeout
- define('ORDER_STATUS_CANCELLED', 6); // order canceled
- define('ORDER_STATUS_PARTIALLY', 7); // order paid partially
- define('ORDER_STATUS_COURIER', 8); // sent by courier
- define('ORDER_STATUS_PREPAY', 9); // prepay
- define('ORDER_STATUS_CASH', 10); // cash payment
- define('ORDER_CONFIRM_TIME', 15 * 60);
- class Element_Order extends Element_Common {
- private static $_mIdTopDJ = 41215;
- public $table_name = 't_order';
- public $cache = array();
- public $paymentTypes = array(
- 'card' => array(
- 'title' => 'ПриватБанк',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'PrivatBank',
- 'is_online' => 1
- ),
- 'platon' => array(
- 'title' => 'Платон',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'Platon',
- 'is_online' => 1
- ),
- 'webmoney' => array(
- 'title' => 'Webmoney',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'subtypes' => array(
- /*'wmu' => array(
- 'title' => 'WMU',
- 'currency' => array(
- '1' => 'WMU',
- '2' => 'WMU',
- '3' => 'WMU',
- ),
- ),
- 'wmz' => array(
- 'title' => 'WMZ',
- 'currency' => array(
- '1' => 'WMZ',
- '2' => 'WMZ',
- '3' => 'WMZ',
- ),
- ),*/
- 'wmr' => array(
- 'title' => 'WMR',
- 'currency' => array(
- 1 => 'WMR',
- 2 => 'WMR',
- 3 => 'WMR',
- ),
- ),
- ),
- 'class' => 'Webmoney',
- 'is_online' => 1
- ),
- 'WMTerminals' => array(
- 'title' => 'Webmoney (Терминал)',
- 'currency' => 'UAH',
- 'subtypes' => array(
- 'wmu' => array(
- 'title' => 'WMU',
- 'currency' => 'WMU',
- ),
- ),
- 'class' => 'Webmoney',
- 'is_online' => 1
- ),
- 'liqpay' => array(
- 'title' => 'LiqPAY',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'LiqPay',
- 'is_online' => 1
- ),
- 'pumb' => array(
- 'title' => 'Pumb',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'Pumb',
- 'is_online' => 1
- ),
- 'free' => array(
- 'title' => 'Бесплатно',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'subtypes' => array(
- 'test' => array(
- 'title' => 'Тест',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- ),
- 'real' => array(
- 'title' => 'Забрать билет',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- ),
- ), //, 'real' => 'UAH'
- 'class' => 'Free',
- 'is_online' => 0
- ),
- 'offline' => array(
- 'title' => 'Касса',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'Offline',
- 'is_online' => 0
- ),
- 'osmp' => array(
- 'title' => 'Qiwi',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'Osmp',
- 'is_online' => 1
- ),
- 'courier' => array(
- 'title' => 'Курьер',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'Courier',
- 'is_online' => 0
- ),
- 'easypay' => array(
- 'title' => 'EasyPay',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'EasyPay',
- 'is_online' => 1
- ),
- 'bass' => array(
- 'title' => 'ПриватБанк (Терминал)',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'Bass',
- 'is_online' => 1
- ),
- 'ibox' => array(
- 'title' => 'iBox',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'Ibox',
- 'is_online' => 1
- ),
- 'citypay' => array(
- 'title' => 'CityPay',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'Citypay',
- 'is_online' => 1
- ),
- 'certificate' => array(
- 'title' => 'Certificate',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'Certificate',
- 'is_online' => 0
- ),
- 'test' => array(
- 'title' => 'Тестовая оплата',
- 'currency' => array(
- 1 => 'UAH',
- 2 => 'EUR',
- 3 => 'UAH',
- ),
- 'class' => 'Test',
- 'is_online' => 1
- ),
- );
- public $paidStatuses = array(
- -1 => array(
- 'title' => 'Изменённый',
- ),
- 0 => array(
- 'title' => 'Не сформированный',
- ),
- 1 => array(
- 'title' => 'Отправлен на оплату',
- ),
- 2 => array(
- 'title' => 'Оплачено',
- ),
- 3 => array(
- 'title' => 'Не прошёл',
- ),
- 4 => array(
- 'title' => 'В ожидании оффлайн',
- ),
- 5 => array(
- 'title' => 'Просрочен',
- ),
- 6 => array(
- 'title' => 'Аннулирован',
- ),
- 7 => array(
- 'title' => 'Частичная оплата',
- ),
- 8 => array(
- 'title' => 'Оплата Курьеру',
- ),
- 9 => array(
- 'title' => 'Передоплата',
- ),
- 10 => array(
- 'title' => 'Оплата в кассе'
- )
- );
- public $deliveryTypes = array(
- 1 => array(
- 'title' => 'Электронный билет',
- ),
- 2 => array(
- 'title' => 'Курьер',
- ),
- 3 => array(
- 'title' => 'Забрать в кассе',
- ),
- );
- public $partners = array(
- 0 => array(
- 'title' => 'В-тикет',
- ),
- 1 => array(
- 'title' => 'Карабас',
- ),
- 10 => array(
- 'title' => 'Премьера',
- ),
- 11 => array(
- 'title' => 'Интернет-билет',
- ),
- 16 => array(
- 'title' => 'ФлешБокс',
- ),
- 17 => array(
- 'title' => 'Кассир24'
- )
- );
- public $currencyList = array('uah', 'usd', 'eur', 'byr', 'rur');
- public function __construct($options = array()) {
- $options['type'] = 'Order';
- if (!$GLOBALS['isSuper']) {
- unset($this->paymentTypes['card']['free']);
- }
- }
- public function create($eventInfo = false, $order_info) {
- $externalId = 0;
- if ($eventInfo['partner_id'] == 1) {
- $params = array(
- 'order_id' => $order_info['karabas_order_id'],
- 'auth' => $order_info['karabas_auth'],
- 'event_id' => $order_info['session_id']
- );
- if (false === ($externalId = $this->_karabasSubmitOrder($params))) {
- return false;
- }
- }
- if (!$GLOBALS['isLocal'] && !$GLOBALS['isTest'] && $order_info['payment'] == 'free') {
- return false;
- }
- // 1. Collecting data for creating order
- $patern = '/[^абвгґдеєжзиіїйклмнопрстуфхцчшщьюяАБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЬЮЯЁёЪъЫыЭэa-zA-Z\-]/';
- $orderData = array(
- 'event_id' => $eventInfo['id'],
- 'firstname' => preg_replace($patern, '', $order_info['firstname']),
- 'lastname' => preg_replace($patern, '', $order_info['lastname']),
- 'city_name' => ($order_info['country'] == 1 && $order_info['country-enter']) ? $order_info['country-enter'] : $order_info['city'],
- 'city_id' => $order_info['city_id'],
- 'email' => $order_info['email'],
- 'mobile' => $order_info['number'],
- 'seller_id' => $order_info['user_id'] ? $order_info['user_id'] : 0,
- 'ip_address' => get_real_ip(),
- 'date_created' => NOW,
- 'payment_type' => $order_info['delivery'] == 3 ? 'offline' : $order_info['payment'],
- 'payment_subtype' => $order_info['subpayment'][$order_info['payment']],
- 'secret_code' => $this->getSecretCode(),
- 'language_id' => $GLOBALS['lng']['id'],
- 'paid_status' => ORDER_STATUS_NEW,
- 'is_deposit' => 0,
- 'is_concert' => $order_info['is_concert'] ? 1 : 0,
- 'is_free' => isset($order_info['is_free']) && $order_info['is_free'] == 1 || $order_info['payment'] == 'free' ? 1 : 0,
- 'partner_id' => $eventInfo['partner_id'],
- 'external_id' => $externalId,
- 'sub_domain' => $order_info['sub_domain'],
- 'delivery_type' => in_array($order_info['delivery'], array_keys($this->deliveryTypes)) ? $order_info['delivery'] : 1,
- 'delivery_price' => 0,
- 'reserv_cancelling' => $order_info['delivery'] == 3 ? date("Y-m-d H:i:s", strtotime("+{$eventInfo['reservation_period']} HOURS")) : null
- );
- if (in_array($orderData['payment_type'], array('osmp', 'WMTerminals'))) {
- $hourExpired = 24;
- } else {
- if ($orderData['delivery_type'] == 3) {
- $hourExpired = $eventInfo['reservation_period'];
- } else {
- $hourExpired = 1;
- }
- }
- $dateExpired = date('Y-m-d H:i:s', strtotime('+' . $hourExpired . ' HOURS'));
- // 2. Detecting currency for order: currency for user and currency for billing
- if ($this->paymentTypes[$orderData['payment_type']]['subtypes']) {
- $orderData['price_currency'] = $this->paymentTypes[$orderData['payment_type']]['subtypes'][$orderData['payment_subtype']]['currency'][$GLOBALS['lng']['id']];
- } else {
- $orderData['price_currency'] = $this->paymentTypes[$orderData['payment_type']]['currency'][$GLOBALS['lng']['id']];
- // English version of site - payment only with card
- if ($GLOBALS['lng']['id'] == 2) {
- // User currency EUR
- $orderData['price_currency'] = 'EUR';
- // Billing currency UAH
- $orderData['billing_currency'] = 'UAH';
- }
- }
- if (!$orderData['billing_currency'])
- $orderData['billing_currency'] = $orderData['price_currency'];
- // 3. Loading fees for current tickets types
- $bookingFees = ginst('TicketTypePayment')->getByTicketTypes($eventInfo['ticketTypes']);
- $paymentCommission = array();
- // 4. Initial values or order
- $totals = array(
- 'subtotal' => 0,
- 'subtotal_billing' => 0,
- 'fee' => 0,
- 'fee_billing' => 0,
- );
- $discountsList = $itemsDiscounted = array();
- $orderItems = $orderPlaces = array();
- $total_discount = 0;
- $isCertificateDiscount = false;
- // 5. Checking if any discount exists and can be applied
- if ($eventInfo['discounts'] && $_SESSION['event-' . $eventInfo['id']]['discounts']) {
- $discountsList = ginst('Discount')->getCodes($eventInfo['id'], $_SESSION['event-' . $eventInfo['id']]['discounts']);
- if ($discountsList['res']['total_ticket'] == 12) {
- $isCertificateDiscount = true;
- }
- }
- // 6. Going throught the tickets without places
- $blockPlacesIds = array();
- $placesIds = array();
- if ($order_info['amount']) {
- foreach ($order_info['amount'] as $id => $am) {
- if (!$am)
- continue;
- if ($eventInfo['ticketTypes'][$id]) {
- $orderItems[$id] = $eventInfo['ticketTypes'][$id];
- } else {
- $orderItems[$id] = ginst('TicketType')->getById($id);
- }
- $orderItems[$id]['amount'] = $am;
- if ($eventInfo['partner_id'] == 10) {
- $ext_block_place_id = $GLOBALS['dbh']->getOne("SELECT external_id FROM t_ticket_type WHERE id = '{$id}'");
- $blockPlacesIds[$ext_block_place_id] = $am;
- }
- if($eventInfo['partner_id'] == 11 && $eventInfo['ib_scheme'] != 1){
- $ibreserv = ginst('InternetBilet')->addToFanzoneReserve($eventInfo['external_id'], $orderItems[$id]['external_id'], $am);
- if (!$ibreserv) {
- ginst('InternetBilet')->clearBasket($eventInfo['external_id']);
- return false;
- }
- $ibTickets[$id] = $ibreserv->result_details->ticket_ids;
- }
- if ($eventInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
- $tmpSeats = ginst('FlashBox')->getTicketTypeSeats($id, $am, $dateExpired);
- if (empty($tmpSeats)) {
- ginst('FlashBox')->updateTicketType($eventInfo['external_id']);
- return false;
- }
- $blockPlacesIds = array_merge($blockPlacesIds, $tmpSeats);
- foreach ($tmpSeats as $key => $tid) {
- $itemsDiscounted[$id][++$key]['external_id'] = $tid;
- }
- }
- // Calculating ticket price
- $orderItems[$id]['currency'] = $orderData['price_currency'];
- $orderItems[$id]['price'] = ceil(ginst('Currency')->convert($orderItems[$id]['price_single'], $orderData['price_currency'], $orderItems[$id]['price_currency']));
- $orderItems[$id]['currency_billing'] = $orderData['billing_currency'];
- $orderItems[$id]['price_billing'] = ceil(ginst('Currency')->convert($orderItems[$id]['price_single'], $orderData['billing_currency'], $orderItems[$id]['price_currency']));
- // Checking for fees
- if (empty($paymentCommission)) {
- $paymentCommission = $bookingFees[$id][$orderData['payment_type']];
- }
- if (in_array(ginst('TicketType')->getGroupId($id), array(6, 7))) {
- $childTicketTypeId = ginst('TicketTypeRelation')->getChildTicketTypeId($id);
- if ($eventInfo['ticketTypes'][$childTicketTypeId]) {
- $childTicketType = $eventInfo['ticketTypes'][$childTicketTypeId];
- } else {
- $childTicketType = ginst('TicketType')->getById($childTicketTypeId);
- }
- $subTypeAmount = $order_info['sub_amount'][$id][$childTicketTypeId];
- $orderItems[$id]['price_single'] = $orderItems[$id]['price'] =
- $orderItems[$id]['price_print_single'] = $orderItems[$id]['price_digital'] =
- $orderItems[$id]['price_billing'] =
- $subTypeAmount * $childTicketType['price_single'];
- $orderItems[$id]['subtypes_amount'] = $subTypeAmount;
- }
- /* Calculate discount */
- $tmpCount = 0;
- for ($i = 1; $i <= $am; $i++) {
- $params = array (
- 'id' => $id,
- 'price_single' => $orderItems[$id]['price_single'],
- 'price_currency' => $orderItems[$id]['price_currency'],
- 'price' => $orderItems[$id]['price'],
- 'order_price_currency' => $orderData['price_currency'],
- 'billing_currency' => $orderData['billing_currency'],
- 'iteration' => $tmpCount,
- );
- $discountInfo = Element_Discount::calcDiscount($discountsList, $params);
- $itemsDiscounted[$id][$i] = (!empty($itemsDiscounted[$id][$i])? array_merge($itemsDiscounted[$id][$i], $discountInfo) : $discountInfo);
- $total_discount += $itemsDiscounted[$id][$i]['discount'];
- $params['price'] -= $itemsDiscounted[$id][$i]['discount'];
- $itemsDiscounted[$id][$i] = array_merge($itemsDiscounted[$id][$i], Element_Commission::calcFee($bookingFees, $params));
- $totals['fee'] += $itemsDiscounted[$id][$i]['fee'];
- $totals['fee_billing'] += $itemsDiscounted[$id][$i]['fee_billing'];
- $tmpCount = $itemsDiscounted[$id][$i]['iteration'];
- }
- $totals['subtotal'] += $am * $orderItems[$id]['price'];
- $totals['subtotal_billing'] += $am * $orderItems[$id]['price_billing'];
- }
- }
- // 7. Going throught the karabas tickets
- if ($order_info['partner_id'] == 1) {
- $basket = ginst('Karabas')->getBasket(array(
- 'order_id' => $orderData['external_id'],
- '__auth' => $order_info['karabas_auth']
- ));
- if(empty($basket->items)) {
- ginst('Karabas')->changeOrder($orderData['external_id']);
- return false;
- }
- foreach ($basket->items as $itemElem) {
- if ($itemElem->event == $order_info['session_id']) {
- $type_id = 0;
- foreach ($eventInfo['ticketTypes'] as $ticketType) {
- if ($ticketType['title'] == $itemElem->zone && (int)$ticketType['price_single'] == (int)$itemElem->price) {
- $type_id = $ticketType['id'];
- $row = $ticketType;
- $row['extra'] = 'Ряд '.($itemElem->row ? $itemElem->row : '' ).', Место '.($itemElem->number ? $itemElem->number.' ' : '').'('.$itemElem->zone.')';
- break;
- }
- }
- if ($type_id == 0) {
- ginst('Karabas')->changeOrder($orderData['external_id']);
- return false;
- }
- $row['bar_code_type'] = 'code128';
- $row['bar_code'] = $itemElem->barCode;
- $row['type_place_id'] = 0;
- $row['currency'] = $orderData['price_currency'];
- $row['price'] = ceil(ginst('Currency')->convert($itemElem->price, $orderData['price_currency'], $row['price_currency']));
- $row['currency_billing'] = $orderData['billing_currency'];
- $row['price_billing'] = ceil(ginst('Currency')->convert($itemElem->price, $orderData['billing_currency'], $row['price_currency']));
- $row['external_id'] = $itemElem->id;
- $totals['subtotal'] += $row['price'];
- $totals['subtotal_billing'] += $row['price_billing'];
- $params = array (
- 'id' => $row['id'],
- 'price_single' => $row['price_single'],
- 'price_currency' => $row['price_currency'],
- 'price' => $row['price'],
- 'order_price_currency' => $orderData['price_currency'],
- 'billing_currency' => $orderData['billing_currency']
- );
- $row = array_merge($row, Element_Discount::calcDiscount($discountsList, $params));
- $total_discount += $row['discount'];
- // Checking for fees
- if(empty($paymentCommission)){
- $paymentCommission = $bookingFees[$type_id][$orderData['payment_type']];
- }
- $params['price'] -= $row['discount'];
- $row = array_merge($row, Element_Commission::calcFee($bookingFees, $params));
- $totals['fee'] += $row['fee'];
- $totals['fee_billing'] += $row['fee_billing'];
- $orderPlaces[] = $row;
- }
- }
- } elseif ($order_info['partner_id'] == 11 && $eventInfo['ib_scheme'] > 0) {
- /* Romko's and Dimosha gavnokod for InternetBillet scheme*/
- $booking = ginst('InternetBilet')->bookingSubmit($eventInfo['external_id']);
- $orderData['external_id'] = $booking->booking_id;
- foreach ($booking->places as $place) {
- foreach ($eventInfo['ticketTypes'] as $ticketType) {
- if ($ticketType['title'] == $place->place_sector && (int)$ticketType['price_single'] == (int)$place->price) {
- $type_id = $ticketType['id'];
- $row = $ticketType;
- $row['extra'] = 'Ряд '.($place->place_row_num ? $place->place_row_num : '' ).', Место '.($place->place_seat_num ? $place->place_seat_num.' ' : '').'('.$place->place_sector.')';
- break;
- }
- }
- $row['type_place_id'] = 0;
- $row['bar_code_type'] = 'code128';
- $row['bar_code'] = $place->barcode;
- $row['currency'] = $orderData['price_currency'];
- $row['price'] = ceil(ginst('Currency')->convert($place->price, $orderData['price_currency'], $row['price_currency']));
- $row['currency_billing'] = $orderData['billing_currency'];
- $row['price_billing'] = ceil(ginst('Currency')->convert($place->price, $orderData['billing_currency'], $row['price_currency']));
- $row['external_id'] = $place->ticket_id;
- $totals['subtotal'] += $row['price'];
- $totals['subtotal_billing'] += $row['price_billing'];
- $params = array (
- 'id' => $row['id'],
- 'price_single' => $row['price_single'],
- 'price_currency' => $row['price_currency'],
- 'price' => $row['price'],
- 'order_price_currency' => $orderData['price_currency'],
- 'billing_currency' => $orderData['billing_currency']
- );
- $row = array_merge($row, Element_Discount::calcDiscount($discountsList, $params));
- $total_discount += $row['discount'];
- if (empty($paymentCommission)) {
- $paymentCommission = $bookingFees[$type_id][$orderData['payment_type']];
- }
- $params['price'] -= $row['discount'];
- $row = array_merge($row, Element_Commission::calcFee($bookingFees, $params));
- $totals['fee'] += $row['fee'];
- $totals['fee_billing'] += $row['fee_billing'];
- $orderPlaces[] = $row;
- }
- } else {
- // 8. Going throught the tickets with places
- if (!empty($eventInfo['is_scheme'])) {
- if (!empty($order_info['place']) && is_array($order_info['place'])) {
- foreach ($order_info['place'] as $type_id => $type_places) {
- if ($eventInfo['ticketTypes'][$type_id]) {
- $ticketType = $eventInfo['ticketTypes'][$type_id];
- } else {
- $ticketType = ginst('TicketType')->getById($type_id);
- }
- $tmpCount = 0;
- foreach ($type_places as $type_place_id) {
- $row = $ticketType;
- if ($eventInfo['partner_id'] == 11 && $eventInfo['external_id'] > 0 && $eventInfo['ib_scheme'] != 1) {//input into basket of Internet bilet
- $row['external_id'] = $GLOBALS['dbh']->getOne("SELECT external_id FROM t_ticket_type_place WHERE id = {$type_place_id}");
- if (!ginst('InternetBilet')->addToHallReserve($row['external_id'])) {
- ginst('InternetBilet')->clearBasket($eventInfo['external_id']);
- return false;
- }
- }
- if ($eventInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
- if (false === ($ticket_id = $this->_flashBoxCheckPlace($type_place_id))) {
- return false;
- }
- $row['external_id'] = $blockPlacesIds[] = $ticket_id;
- }
- $row['type_place_id'] = $type_place_id;
- $row['currency'] = $orderData['price_currency'];
- $row['price'] = ceil(ginst('Currency')->convert($row['price_single'], $orderData['price_currency'], $row['price_currency']));
- $row['currency_billing'] = $orderData['billing_currency'];
- $row['price_billing'] = ceil(ginst('Currency')->convert($row['price_single'], $orderData['billing_currency'], $row['price_currency']));
- // Premiera :: collect external id's for places
- if ($order_info['partner_id'] == 10) {
- $ext_place_id = $GLOBALS['dbh']->getOne("
- SELECT vsp.external_id
- FROM t_venue_section_place AS vsp
- LEFT JOIN t_ticket_type_place AS ttp ON vsp.id = ttp.place_id
- WHERE ttp.id = '{$type_place_id}'
- ");
- if ($ext_place_id) {
- $row['extra_data'] = ginst('Premiera')->getPlaceData($eventInfo['external_id'], $ext_place_id);
- //$row['external_id'] = $ext_place_id;
- $placesIds[] = $ext_place_id;
- }
- }
- $params = array (
- 'id' => $row['id'],
- 'price_single' => $row['price_single'],
- 'price_currency' => $row['price_currency'],
- 'price' => $row['price'],
- 'order_price_currency' => $orderData['price_currency'],
- 'billing_currency' => $orderData['billing_currency'],
- 'iteration' => $tmpCount,
- );
- $disc = Element_Discount::calcDiscount($discountsList, $params);
- $tmpCount = $disc['iteration'];
- unset($disc['iteration']);
- $row = array_merge($row, $disc);
- $total_discount += $row['discount'];
- // Adding ticket price for subtotals
- $totals['subtotal'] += $row['price'];
- $totals['subtotal_billing'] += $row['price_billing'];
- // Checking for fees
- if (empty($paymentCommission)) {
- $paymentCommission = $bookingFees[$type_id][$orderData['payment_type']];
- }
- $params['price'] -= $row['discount'];
- $row = array_merge($row, Element_Commission::calcFee($bookingFees, $params));
- $totals['fee'] += $row['fee'];
- $totals['fee_billing'] += $row['fee_billing'];
- // Saving this ticket for future storring it to DB
- $orderPlaces[] = $row;
- }
- }
- }
- }
- if ($eventInfo['partner_id'] == 11 && $eventInfo['external_id'] > 0 && $eventInfo['ib_scheme'] != 1) {//submit order to Internet-bilet
- $orderData['external_id'] = ginst('InternetBilet')->bookingSubmit($eventInfo['external_id'])->booking_id;
- }
- }
- // Premiera :: send places for freezing
- if ($eventInfo['partner_id'] == 10) {
- $orderResult = ginst('Premiera')->submitOrder($eventInfo['external_id'], $placesIds, $blockPlacesIds);
- // success operation
- if (isset($orderResult->PlaceOrderResult->ErrorCode) && $orderResult->PlaceOrderResult->ErrorCode == 0 || empty($orderResult->PlaceOrderResult->orderList->OrderPlaceResultEx)) {
- $places = $orderResult->PlaceOrderResult->orderList->OrderPlaceResultEx;
- if (!is_array($places)) {
- $tmp = $places;
- $places = array();
- $places[] = $tmp;
- }
- $cnt = array();
- foreach ($places as $place) {
- foreach ($orderItems as $key => $oItem) {
- if ($place->sectionID == $oItem['external_id']) {
- $cnt[$key]++;
- if (empty($place->ticketCode) || empty($place->placeID)) {
- return false;
- }
- $itemsDiscounted[$key][$cnt[$key]]['bar_code'] = $place->ticketCode;
- $itemsDiscounted[$key][$cnt[$key]]['external_id'] = $place->placeID;
- $itemsDiscounted[$key][$cnt[$key]]['extra'] = $place->url;
- break;
- }
- }
- foreach ($orderPlaces as $key => $oPlace) {
- if ($place->sectionID == $oPlace['extra_data']['sectionID'] && $place->rowID == $oPlace['extra_data']['rowID'] && $place->position == $oPlace['extra_data']['position']) {
- if (empty($place->ticketCode) || empty($place->placeID)) {
- return false;
- }
- $orderPlaces[$key]['bar_code'] = $place->ticketCode;
- $orderPlaces[$key]['external_id'] = $place->placeID;
- $orderPlaces[$key]['extra'] = $place->url;
- break;
- }
- }
- }
- } else {
- ginst('Premiera')->logError(array('places' => $placesIds, 'fanzones' => $blockPlacesIds),$orderResult->PlaceOrderResult);
- return false;
- }
- }
- // submit tickets in the FlashBox system
- if ($order_info['partner_id'] == ginst('FlashBox')->getServerId()) {
- if (false === ($submitData = ginst('FlashBox')->submitOrder($blockPlacesIds, $hourExpired * 60))) {
- return false;
- }
- $orderData['external_id'] = $submitData->booking_code;
- }
- if (empty($orderItems) && empty($orderPlaces)) {
- return false;
- }
- $certificate = $this->checkCertificate(array(
- 'event' => $eventInfo,
- 'items' => $orderItems,
- 'places' => $orderPlaces
- ));
- if (!empty($certificate)) {
- $orderItems[$certificate['id']] = $certificate;
- }
- //add $total_discount
- $orderData['price_subtotal'] = $totals['subtotal'] - $total_discount;
- // count fees
- if(!empty($paymentCommission)){
- $feeInfo = $paymentCommission;
- $feePrice = 0;
- $payPrice = ginst('Currency')->convert($orderData['price_subtotal'], $feeInfo['fee_currency'], $orderData['price_currency']);
- if (!($orderData['city_id'] == 10184 && $orderData['payment_type'] == 'courier')) {
- if ($feeInfo['fee_type'] == 'percents' || $feeInfo['fee_type'] == 'both') {
- $feePrice = $feeInfo['fee_percents'] / 100 * $payPrice;
- }
- if ($feeInfo['fee_type'] == 'amount' || $feeInfo['fee_type'] == 'both') {
- $feePrice += $feeInfo['fee_single'];
- }
- if ($feeInfo['fee_type'] == 'percents_plus') {
- if($payPrice * $feeInfo['fee_percents'] / 100 > $feeInfo['fee_single']){
- $feePrice = $payPrice * $feeInfo['fee_percents'] / 100;
- } else{
- $feePrice = $feeInfo['fee_single'];
- }
- }
- }
- $fee = ginst('Currency')->convert($feePrice, $orderData['price_currency'], $feeInfo['fee_currency']);
- $fee_billing = ginst('Currency')->convert($feePrice, $orderData['billing_currency'], $feeInfo['fee_currency']);
- $totals['fee'] += $fee;
- $totals['fee_billing'] += $fee_billing;
- }
- $orderData['price_fee'] = ceil($totals['fee']);
- $orderData['price_total'] = $orderData['price_subtotal'] + $orderData['price_fee'];
- //fee -
- if ($discount_amount > $total_discount && $isCertificateDiscount) {
- $subtractFee = $discount_amount - $total_discount;
- if ($subtractFee < $orderData['delivery_price']) {
- $feeSubtract = $orderData['price_fee'] - $subtractFee;
- }
- else if ($subtractFee > $orderData['delivery_price']) {
- $feeSubtract = $orderData['price_fee'];
- }
- $feeSubtractBilling = $feeSubtract;
- $toTotalFeeBilling = 0;
- if ($orderData['price_fee'] != $orderData['billing_fee'] && $discount_amount > $total_discount) {
- $subtractFee = $discount_amount - $total_discount;
- if ($subtractFee < $orderData['delivery_price']) {
- $feeSubtractBilling = $orderData['price_fee'] - $subtractFee;
- }
- else if ($subtractFee > $orderData['delivery_price']) {
- $feeSubtractBilling = $orderData['price_fee'];
- }
- $toTotalFeeBilling = $feeSubtractBilling - $feeSubtract;
- }
- $orderData['price_total'] -= ($feeSubtract + $toTotalFeeBilling);
- $total_discount += $feeSubtract + $toTotalFeeBilling;
- }
- $orderData['discount'] = $total_discount;
- $total_discount_billing = ginst('Currency')->convert($total_discount, $orderData['billing_currency'], $orderData['price_currency']);
- $orderData['billing_price'] = $totals['subtotal_billing'] + ceil($totals['fee_billing']) - $total_discount_billing;
- //додавання ціни за доставку
- if ($order_info['delivery'] == 2) {
- $deliveryInfo = array();
- $deliveryExecuteData = array
- (
- 'country' => $order_info['country'],
- 'province' => $order_info['region'],
- 'city' => $order_info['city_id']
- );
- $delType = ginst('Delivery')->getDeliveryType($order_info['city_id']);
- $delPeriod = ginst('Delivery')->getDeliveryPeriod($delType, $order_info['city_id']);
- $orderData['delivery_expired'] = date('Y-m-d H:i', strtotime($orderData['date_created']) + 60 * 60 * 24 * $delPeriod);
- if ($order_info['city_id'] == 10184 || true) {
- $deliveryInfo = ginst('Delivery')->getMostExpressRates($eventInfo['id'], $order_info['city_id']);
- $freeDeliveryRate = $GLOBALS['dbh']->getOne("SELECT `value` FROM t_delivery_settings WHERE alias = 'free_delivery_kyiv'");
- if ($orderData['price_total'] >= $freeDeliveryRate && $order_info['city_id'] == 10184) {
- $deliveryInfo['deliveryPrice'] = '0.00';
- }
- $deliveryTmp = array
- (
- 'street' => $order_info['street'],
- 'house' => $order_info['house'],
- 'flat' => $order_info['flat'],
- 'zip' => $order_info['zip'],
- 'comment' => $order_info['comment'],
- 'street_id' => $order_info['street_id']
- );
- } else {
- $deliveryData = array
- (
- 'recipient_city' => $order_info['city'],
- 'public_price' => $orderData['billing_price'],
- 'delivery_typeid' => $order_info['delivery_subtype']
- );
- $deliveryInfo = ginst('Delivery')->getNewPostRates($deliveryData);
- if ($order_info['delivery_subtype'] == 3) {
- $deliveryTmp = array
- (
- 'street' => $order_info['street'],
- 'house' => $order_info['house'],
- 'flat' => $order_info['flat'],
- 'zip' => $order_info['zip']
- );
- } else {
- $deliveryTmp = array
- (
- 'ware_id' => $order_info['ware_id']
- );
- }
- }
- if (empty($deliveryInfo['deliveryPeriod']) || empty($deliveryInfo['deliveryPrice'])) return false;
- $GLOBALS['dbh']->autoExecute('t_address', $deliveryExecuteData + $deliveryTmp);
- $GLOBALS['dbh']->autoExecute('t_delivery', array(
- 'address_from' => '10184',
- 'address_to' => $GLOBALS['dbh']->getOne('SELECT LAST_INSERT_ID()'),
- 'd_date' => $orderData['date_created'],
- 'duration' => date("Y-m-d H:i:s", ltime() + $deliveryInfo['deliveryPeriod'] * 24 * 60 * 60),
- 'zone' => '1',
- 'courier_payment' => '1',
- 'status' => '1',
- ));
- $deliveryLastInsId = $GLOBALS['dbh']->getOne('SELECT LAST_INSERT_ID()');
- $orderData['delivery_price'] = ceil(ginst('Currency')->convert($deliveryInfo['deliveryPrice'], $orderData['price_currency'], $this->paymentTypes[$orderData['payment_type']]['currency'][$GLOBALS['lng']['id']]));
- $orderData['price_total'] += ceil(ginst('Currency')->convert($deliveryInfo['deliveryPrice'], $orderData['price_currency'], $this->paymentTypes[$orderData['payment_type']]['currency'][$GLOBALS['lng']['id']]));
- $orderData['billing_price'] += $orderData['delivery_price'];
- }
- if ($total_discount > 0 && $GLOBALS['lng']['id'] == 2) {
- $total_discount = ginst('Currency')->convert($total_discount, 'uah', 'eur');
- }
- $orderData['billing_fee'] = ceil($totals['fee_billing']);
- // for orders with zero price
- if ($orderData['price_total'] <= 0 && !$isCertificateDiscount && $total_discount > 0){
- $GLOBALS['cStatus']->setError($GLOBALS['smarty']->get_config_vars('form_field_error') . '<br/>'.$GLOBALS['smarty']->get_config_vars('form_wrong_discount'));
- return false;
- } elseif ($orderData['price_total'] <= 0 && $isCertificateDiscount) {
- $orderData['payment_type'] = 'certificate';
- $orderData['payment_subtype'] = '';
- } elseif ($orderData['price_total'] == 0 && !$isCertificateDiscount) {
- $orderData['is_free'] = 1;
- $orderData['payment_type'] = 'free';
- $orderData['payment_subtype'] = 'real';
- }
- // 9. If order is free - then price is zero
- if ($orderData['is_free'] || $orderData['price_total'] < 0 || ($orderData['price_total'] == 0 && $isCertificateDiscount)) {
- $orderData['billing_fee'] = '0.00';
- $orderData['billing_currency'] = 'UAH';
- $orderData['price_fee'] = '0.00';
- $orderData['price_total'] = '0.00';
- $orderData['price_subtotal'] = '0.00';
- $orderData['price_currency'] = $this->paymentTypes[$orderData['payment_type']]['currency'][$GLOBALS['lng']['id']];
- $orderData['delivery_price'] = '0.00';
- if ($orderData['is_free']) {
- $orderData['billing_price'] = '0.00';
- }
- else {
- if($orderData['delivery_price'] != 0) {
- $orderData['billing_price'] = (float) $orderData['billing_price'] + (float) $orderData['delivery_price'];
- $orderData['price_total'] = (float) $orderData['price_total'] + (float) $orderData['delivery_price'];
- } else {
- $orderData['billing_price'] = '0.00';
- }
- $negativeSum = true;
- }
- }
- // 10. Checking for promo - we have to save promo_id
- $orderData['promo_id'] = ginst('User')->promoExists();
- $orderData['is_external'] = (int) $_SESSION['token_user_id'];
- // Registration to concert.ua
- $userId = ginst('User')->checkUserByMail($orderData['email']);
- if ($userId == 0) {
- $pass = rand(10000000, 99999999);
- $userInfo = array(
- 'password' => $pass,
- 'mobile' => $orderData['mobile'],
- 'firstname' => $orderData['firstname'],
- 'lastname' => $orderData['lastname'],
- 'city_id' => (int)$orderData['city_id'],
- 'email' => $orderData['email'],
- 'date_added'=> NOW
- );
- $userId = ginst('User')->createUser($userInfo);
- if (!empty($_SESSION['token_user_id'])) {
- ginst('Notices')->userAuthInfo($userId);
- } else {
- ginst('Notices')->create_user($userInfo);
- }
- }
- $orderData['client_id'] = $userId;
- // 11. Creating new order
- $GLOBALS['dbh']->autoExecute('t_order', $orderData);
- // 12. Generating unique hash for order
- $orderData['id'] = $GLOBALS['dbh']->getOne('SELECT LAST_INSERT_ID()');
- $orderData['hash'] = md5($orderData['id'] . '-' . $eventInfo['merchant_secret'] . '-' . NOW . '-' . time());
- $GLOBALS['dbh']->autoExecute('t_order', array('hash' => $orderData['hash']), DB_AUTOQUERY_UPDATE, ' id = ' . $orderData['id']);
- if(empty($order_info['format'])) {
- $order_info['format'] = $eventInfo['ticket_format_id'];
- }
- // 12.а Додання номеру замовлення
- if (in_array($order_info['delivery'], array(2, 3))) {
- if ($order_info['delivery'] == 2) {
- $GLOBALS['dbh']->autoExecute('t_delivery', array('order_id' => $orderData['id']), DB_AUTOQUERY_UPDATE, ' id = ' . $deliveryLastInsId);
- }
- $ticketFormat = ginst('TicketFormat')->getById((int)$order_info['format']);
- if (empty($ticketFormat) || $ticketFormat['alias'] == 'a4' || $ticketFormat['is_a4'] == 0) {
- $order_info['format'] = ginst('TicketFormat')->getTicketFormatId('termonew');
- }
- }
- //12. b
- if ($eventInfo['extended_form']) {
- $imgPath = DOC_ROOT."/dynamic/user/extended";
- if (!is_dir($imgPath)) {
- mkdir($imgPath, 0777, true);
- }
- if ($orderData['is_concert']) {
- $ext = $order_info['photo_ext'];
- $ch = curl_init("http://www.concert.ua/dynamic/user/extended/" . md5($orderData['email']) . ".{$ext}");
- $fp = fopen("dynamic/user/extended/{$orderData['id']}.{$order_info['photo_ext']}", 'wb');
- curl_setopt($ch, CURLOPT_FILE, $fp);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_exec($ch);
- curl_close($ch);
- fclose($fp);
- } else {
- $ext = substr($_FILES['photo_ext']['name'], strrpos($_FILES['photo_ext']['name'], '.') + 1);
- $newName = sprintf($imgPath . '/%s.%s', $orderData['id'], $ext);
- move_uploaded_file($_FILES['photo_ext']['tmp_name'], $newName);
- }
- if ($eventInfo['id'] == 5313) {
- $GLOBALS['dbh']->autoExecute('t_kazantip', array(
- 'order_id' => $orderData['id'],
- 'lastname' => $orderData['lastname'],
- 'firstname' => $orderData['firstname'],
- 'patronymic' => $order_info['middlename'],
- 'photo_ext' => $ext,
- 'passport' => $order_info['passport'],
- 'email' => $orderData['email'],
- 'mobile' => $orderData['mobile'],
- 'sex' => $order_info['sex'],
- 'city' => $orderData['city_name'],
- 'country' => ginst('Country')->getCountryNameByCityId($orderData['city_id'])
- ));
- }
- }
- // 13. Storing tickets without places to DB
- $extraOrderData = array();
- if ($orderItems) {
- $extraOrderData['price_total'] = (float) $orderData['price_total'];
- $extraOrderData['billing_price'] = (float) $orderData['billing_price'];
- $extraOrderData['billing_fee'] = (float) $orderData['billing_fee'];
- $extraOrderData['price_fee'] = (float) $orderData['price_fee'];
- foreach ($orderItems as $k => $row){
- for ($i = 1; $i <= $row['amount']; $i++) {
- $fPrice = $row['price'];
- $fPriceBilling = $row['price_billing'];
- $GLOBALS['dbh']->autoExecute('t_ticket', array(
- 'type_id' => $row['id'],
- 'order_id' => $orderData['id'],
- 'bar_code' => (!empty($itemsDiscounted[$k][$i]['bar_code']) ? $itemsDiscounted[$k][$i]['bar_code'] : ''),
- 'reservation_id' => $row['reservation_id'],
- 'used_deposit_id' => 0,
- 'is_test' => 0,
- 'offline_comments' => $order_info['comment'],
- 'user_id' => $order_info['user_id'] ? $order_info['user_id'] : 0,
- 'is_offline' => $order_info['user_id'] ? 1 : 0,
- 'used_discount_code_id' => $itemsDiscounted[$k][$i]['used_discount_code_id'], //add
- 'format_id' => $row['group_id'] != 1 ? 1 : ($order_info['format'] ? $order_info['format'] : 1),
- 'is_hidden' => $order_info['is_hidden'] == 1 ? 1 : 0,
- 'price' => $row['price'] - (float) $itemsDiscounted[$k][$i]['discount'], //add $itemsDiscounted[$i]
- 'fee' => ($orderData['is_free'] ? 0 : (isset($itemsDiscounted[$k][$i]['fee']) ? $itemsDiscounted[$k][$i]['fee'] : $row['fee'])) ,
- 'currency' => $orderData['price_currency'],
- 'price_billing' => $row['price_billing'] - (float) $itemsDiscounted[$k][$i]['discount_billing'],
- 'fee_billing' => ($orderData['is_free'] ? 0 : (isset($itemsDiscounted[$k][$i]['fee_billing']) ? $itemsDiscounted[$k][$i]['fee_billing'] : $row['fee_billing'])),
- 'discount' => (float) $itemsDiscounted[$k][$i]['discount'],
- 'currency_billing' => $orderData['billing_currency'],
- 'ticket_date' => $order_info['ticket_date'],
- 'external_id' => $itemsDiscounted[$k][$i]['external_id'] ? $itemsDiscounted[$k][$i]['external_id'] : 0,
- 'extra' => $itemsDiscounted[$k][$i]['extra'] ? $itemsDiscounted[$k][$i]['extra'] : '',
- ));
- $ticketId = $GLOBALS['dbh']->getOne('SELECT LAST_INSERT_ID()');
- if($order_info['partner_id'] == 11 && $eventInfo['ib_scheme'] != 1){
- $GLOBALS['dbh']->autoExecute('t_ticket', array('external_id' => $ibTickets[$k][$i-1]), DB_AUTOQUERY_UPDATE, "id = {$ticketId}");
- }
- // check for package ticket type
- if ($row['group_id'] != 1) {
- $subItems = ginst('TicketTypeRelation')->getTicketTypeRelation($orderData['language_id'],$row['id']);
- if (!$subItems)
- continue;
- if (in_array($row['group_id'], array(6, 7))) {
- $subItems = array_fill(0, $row['subtypes_amount'], $subItems[0]);
- }
- if (!$orderData['is_free'] && !$orderData['is_deposit']) {
- $extraOrderData['billing_fee'] -= $row['fee_billing'];
- $extraOrderData['price_fee'] -= $row['fee'];
- $extraOrderData['price_total'] -= $row['fee'];
- $extraOrderData['billing_price'] -= $row['fee'];
- }
- $placeNumber = 0;
- foreach ($subItems as $key => $item) {
- $bookingFee = ginst('TicketTypePayment')->getByTicketTypes(array($item['type_id'] => 1));
- $item['price'] = ceil(ginst('Currency')->convert($item['price_single'], $orderData['price_currency'], $item['price_currency']));
- $item['price_billing'] = ceil(ginst('Currency')->convert($item['price_single'], $orderData['billing_currency'], $item['price_currency']));
- $feePrice = 0;
- $fPrice -= $item['price'];
- $fPriceBilling -= $item['price_billing'];
- $params = array (
- 'id' => $item['type_id'],
- 'price_single' => $orderItems[$id]['price_single'],
- 'price_currency' => $orderItems[$id]['price_currency'],
- 'price' => $item['price'],
- 'order_price_currency' => $orderData['price_currency'],
- 'billing_currency' => $orderData['billing_currency']
- );
- $data = Element_Commission::calcFee($bookingFees, $params);
- $item['fee'] += $data['fee'];
- $item['fee_billing'] += $data['fee_billing'];
- if (!$orderData['is_free']) {
- $extraOrderData['billing_fee'] += $item['fee_billing'];
- $extraOrderData['price_fee'] += $item['fee'];
- $extraOrderData['price_total'] += $item['fee'];
- $extraOrderData['billing_price'] += $item['fee_billing'];
- }
- $placeNumber += 1;
- $subTicketData = array(
- 'type_id' => $item['type_id'],
- 'order_id' => $orderData['id'],
- 'is_test' => 0,
- 'offline_comments' => $order_info['comment'],
- 'user_id' => $order_info['user_id'] ? $order_info['user_id'] : 0,
- 'is_offline' => $order_info['user_id'] ? 1 : 0,
- 'format_id' => $order_info['format'] ? $order_info['format'] : 1,
- 'is_hidden' => $order_info['is_hidden'] == 1 ? 1 : 0,
- 'price' => $item['price'],
- 'fee' => ($orderData['is_free']) ? 0 : $item['fee'],
- 'currency' => $orderData['price_currency'],
- 'price_billing' => $item['price_billing'],
- 'fee_billing' => ($orderData['is_free']) ? 0 : $item['fee_billing'],
- 'currency_billing' => $orderData['billing_currency'],
- 'parent_ticket_id' => $ticketId,
- 'ticket_date' => $order_info['ticket_date']
- );
- if (in_array($row['group_id'], array(6, 7))) {
- $subTicketData += array(
- 'place_number' => $placeNumber,
- 'parent_type_id' => $row['id']
- );
- }
- $GLOBALS['dbh']->autoExecute('t_ticket', $subTicketData);
- }
- if (in_array($row['group_id'], array(6, 7))) {
- $fPrice = $fPriceBilling = ceil(ginst('Currency')->convert(
- $row['tax_price'],
- $orderData['price_currency'],
- $row['tax_price_currency']
- ));
- if ($row['group_id'] == 7) {
- $fPrice *= $placeNumber;
- $fPriceBilling *= $placeNumber;
- }
- $extraOrderData['price_total'] += $fPrice;
- $extraOrderData['billing_price'] += $fPrice;
- $extraOrderData['tax_price'] = $fPrice;
- }
- $ticketData = array(
- //'is_detached' => 1,
- 'price' => $fPrice,
- 'fee' => 0,
- 'price_billing' => $fPriceBilling,
- 'fee_billing' => 0
- );
- if (in_array($row['group_id'], array(6, 7))) {
- $ticketData += array(
- 'places_amount' => $placeNumber
- );
- }
- // setting advanced ticket as detached to prevent second detaching
- $GLOBALS['dbh']->autoExecute('t_ticket', $ticketData, DB_AUTOQUERY_UPDATE, ' id = ' . $ticketId);
- }
- }
- }
- }
- // update order fee
- if (!empty($extraOrderData)) {
- $GLOBALS['dbh']->autoExecute('t_order', $extraOrderData, DB_AUTOQUERY_UPDATE, 'id = ' . $orderData['id']);
- }
- // 14. Storing tickets without places to DB
- if ($orderPlaces) {
- foreach ($orderPlaces as $row) {
- if ($orderData['partner_id'] == 0) {
- $row['bar_code'] = '';
- }
- // Create ticket
- $GLOBALS['dbh']->autoExecute('t_ticket', array(
- 'type_id' => $row['id'],
- 'order_id' => $orderData['id'],
- 'type_place_id' => $row['type_place_id'],
- 'bar_code' => (!empty($row['bar_code']) ? $row['bar_code'] : ''),
- 'bar_code_type' => (!empty($row['bar_code_type']) ? $row['bar_code_type'] : 'ean13'),
- 'reservation_id' => 0,
- 'used_deposit_id' => 0,
- 'is_test' => 0,
- 'offline_comments' => $order_info['comment'],
- 'user_id' => $order_info['user_id'] ? $order_info['user_id'] : 0,
- 'is_offline' => $order_info['user_id'] ? 1 : 0,
- 'used_discount_code_id' => $row['used_discount_code_id'], //add
- 'format_id' => $order_info['format'] ? $order_info['format'] : 1,
- 'is_hidden' => $order_info['is_hidden'] == 1 ? 1 : 0,
- 'price' => $row['price'] - (float) $row['discount'], //add $itemsDiscounted[$i]
- 'fee' => $orderData['is_free'] ? 0 : $row['fee'],
- 'currency' => $orderData['price_currency'],
- 'price_billing' => $row['price_billing'] - (float) $row['discount_billing'],
- 'fee_billing' => $orderData['is_free'] ? 0 : $row['fee_billing'],
- 'discount' => (float) $row['discount'],
- 'currency_billing' => $orderData['billing_currency'],
- 'ticket_date' => $order_info['ticket_date'],
- 'external_id' => $row['external_id'] ? $row['external_id'] : 0,
- 'extra' => $row['extra'] ? $row['extra'] : '',
- ));
- // Update place as reserved
- $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
- 'is_reserved' => 1,
- 'date_cancelling' => $dateExpired
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $row['type_place_id']);
- }
- }
- if ($orderData['price_total'] == 0 && (isset($negativeSum) || $isCertificateDiscount)) {
- ginst('Order')->apply($orderData['id'], false, array('sms_notify' => true, 'end_page_redirect' => true));
- $orderData['negative_sum'] = true;
- }
- if ($order_info['delivery'] == 1) {
- ginst('Api')->internalCreateBooking($orderData['id']);
- if (!empty($_SESSION['token_user_id'])) {
- $GLOBALS['dbh']->autoExecute('t_order', array(
- 'seller_id' => $_SESSION['token_user_id'],
- 'is_external' => $_SESSION['token_user_id']
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderData['id']);
- $GLOBALS['dbh']->autoExecute('t_ticket', array(
- 'user_id' => $_SESSION['token_user_id']
- ), DB_AUTOQUERY_UPDATE, ' order_id = ' . $orderData['id']);
- unset($_SESSION['token_user_id']);
- }
- }
- if ($eventInfo['partner_id'] == ginst('Kassir24')->getServerId()) {
- if (ginst('Kassir24')->submitOrder($orderData['id']) === false) {
- return false;
- }
- }
- unset($_SESSION['event-' . $eventInfo['id']]);
- unset($_SESSION['event-' . $eventInfo['id']]['discounts']);
- unset($_SESSION['reservation-' . $eventInfo['id']]);
- return $orderData;
- }
- public function duplicate($order_id = false) {
- if (!$order_id)
- return false;
- $orderInfo = $GLOBALS['dbh']->getRow('SELECT * FROM t_order WHERE id = ?', array($order_id));
- if ($orderInfo['partner_id'] == 1) {
- ginst('Karabas')->changeOrder($orderInfo['external_id']);
- return false;
- }
- $eventInfo = ginst('Event')->getById($orderInfo['event_id']);
- $newOrderInfo = $orderInfo;
- $newOrderInfo['secret_code'] = $this->getSecretCode();
- ginst('TicketTypePlace')->updateReservedPlaces();
- // 1. Creating new entry in t_order table
- unset($newOrderInfo['id']);
- $newOrderInfo['paid_status'] = ORDER_STATUS_NEW;
- $newOrderInfo['ip_address'] = get_real_ip();
- $newOrderInfo['date_created'] = NOW;
- $GLOBALS['dbh']->autoExecute('t_order', $newOrderInfo);
- $new_order_id = $newOrderInfo['id'] = $GLOBALS['dbh']->getOne('SELECT LAST_INSERT_ID()');
- $newOrderInfo['hash'] = md5($newOrderInfo['id'] . '-' . $eventInfo['merchant_secret'] . '-' . NOW . '-' . time());
- $GLOBALS['dbh']->autoExecute('t_order', array(
- 'hash' => $newOrderInfo['hash'],
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $newOrderInfo['id']);
- // 2. Creating new entries in t_ticket table
- $tickets = $GLOBALS['dbh']->getAll('SELECT * FROM t_ticket WHERE order_id = ?', array($order_id));
- $isGood = true;
- $ticketTypePlaceIds = array();
- foreach ($tickets as $ticket) {
- unset($ticket['id']);
- $ticket['order_id'] = $new_order_id;
- $ticket['is_canceled'] = 0;
- $GLOBALS['dbh']->autoExecute('t_ticket', $ticket);
- if (!$ticket['reservation_id'] && !$ticket['parent_ticket_id'] && !$ticket['used_deposit_id']) {
- // Checking for availibility and enough amount for purchase
- if (!isset($eventInfo['ticketTypes'][$ticket['type_id']]) || !$eventInfo['ticketTypes'][$ticket['type_id']]['cnt_max']) {
- $isGood = false;
- break;
- } else {
- $eventInfo['ticketTypes'][$ticket['type_id']]['cnt_max']--;
- }
- }
- if ($ticket['type_place_id']) {
- // We have to check that this place is available
- $tmp = $GLOBALS['dbh']->getRow('SELECT * FROM t_ticket_type_place WHERE id = ?', array($ticket['type_place_id']));
- if ($tmp['id'] && !$tmp['is_reserved'] && !$tmp['is_sold']) {
- $ticketTypePlaceIds[] = $ticket['type_place_id'];
- } else {
- $isGood = false;
- break;
- }
- }
- }
- if ($isGood) {
- // 3. Updating entries in t_ticket_type_place table
- if ($ticketTypePlaceIds) {
- $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
- 'is_reserved' => 1,
- 'date_cancelling' => $orderInfo['payment_type'] == 'osmp' ? date('Y-m-d H:i:s', strtotime('+24 HOURS')) : date('Y-m-d H:i:s', strtotime('+60 MINUTES')),
- ), DB_AUTOQUERY_UPDATE, ' id IN (' . implode(',', $ticketTypePlaceIds) . ')');
- }
- return $new_order_id;
- } else {
- // Deleting cloned order
- $GLOBALS['dbh']->query('DELETE FROM t_order WHERE id = ?', array($new_order_id));
- return false;
- }
- }
- public function get($order_id, $field_name = 'id', $is_cache = true, $is_force = false) {
- if (!$order_id)
- return;
- if ($this->cache[$order_id] && $is_cache)
- return $this->cache[$order_id];
- $tmp = $GLOBALS['dbh']->getRow('
- SELECT t_order.*, t_event.session_id, t_event.date_event
- FROM t_order
- LEFT JOIN t_event ON t_event.id = t_order.event_id
- WHERE t_order.' . $field_name . ' = ?', array($order_id));
- if (!$tmp['id'])
- return;
- $order_id = $tmp['id'];
- $orderInfo = $tmp;
- if (!$orderInfo['secret_code']) {
- $orderInfo['secret_code'] = $this->getSecretCode();
- $GLOBALS['dbh']->autoExecute($this->table_name, array(
- 'secret_code' => $orderInfo['secret_code'],
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $order_id);
- }
- if (!$orderInfo['id']) {
- unset($this->cache[$order_id]);
- return;
- }
- $orderInfo['items'] = $GLOBALS['dbh']->getAll('
- SELECT
- t_ticket_type.*, t_ticket.*, t_ticket_type_content.title,t_ticket_type.certificate_id AS cer_id, t_ticket_type_content.title_print, t_reservation.bar_code AS reservation_bar_code, t_ticket.price AS ticket_price, t_ticket.currency AS ticket_currency,
- t_event_content.title AS event_title,
- t_event.alias AS event_alias,
- t_ticket_deposit.id AS deposit_id, t_ticket_deposit.deposit_price, t_ticket_deposit.deposit_code,
- t_ticket_deposit.deposit_currency,
- t_discount_code.code AS discount_code, t_discount_event.is_percents, t_discount_event.amount AS discount_amount, t_discount_event.with_discount
- FROM
- t_ticket
- LEFT JOIN t_ticket_type ON (t_ticket_type.id = t_ticket.type_id)
- LEFT JOIN t_event ON (t_event.id = t_ticket_type.event_id)
- LEFT JOIN t_event_content ON (t_event_content.id = t_ticket_type.event_id AND t_event_content.language_id = ?)
- LEFT JOIN t_ticket_type_content ON (t_ticket_type.id = t_ticket_type_content.id AND t_ticket_type_content.language_id = ?)
- LEFT JOIN t_reservation ON (t_ticket.reservation_id = t_reservation.id)
- ' . ($orderInfo['is_deposit'] ? ' LEFT JOIN t_ticket_deposit ON (t_ticket.id = t_ticket_deposit.deposited_ticket_id ) ' : '
- LEFT JOIN t_ticket_deposit ON (t_ticket.used_deposit_id = t_ticket_deposit.id )
- ') . '
- LEFT JOIN t_discount_code ON (t_ticket.used_discount_code_id = t_discount_code.id )
- LEFT JOIN t_discount_event ON (t_discount_event.discount_id = t_discount_code.discount_id AND t_discount_event.event_id = t_event.id)
- WHERE
- t_ticket.order_id = ?
- ', array($orderInfo['language_id'], $orderInfo['language_id'], $orderInfo['id']));
- $orderInfo['packages'] = array();
- $orderInfo['items_unique'] = array();
- $orderInfo['items_count'] = 0;
- $orderInfo['places'] = array();
- $orderInfo['deposit_price_full'] = $orderInfo['deposit_price_left'] = '';
- $cur = '';
- foreach ($orderInfo['items'] as $k => $row) {
- if (!isset($orderInfo['tickets_format_id']) && $row['group_id'] == 1) {
- $orderInfo['tickets_format_id'] = $row['format_id'];
- }
- $orderInfo['groups'][$row['group_id']] = 1;
- $orderInfo['types'][$row['type_id']] = 1;
- $orderInfo['items_count']++;
- if (!isset($orderInfo['items_unique'][$row['type_id']])) {
- $orderInfo['items_unique'][$row['type_id']] = $row;
- $orderInfo['items_unique'][$row['type_id']]['amount'] = 1;
- } else {
- $orderInfo['items_unique'][$row['type_id']]['amount']++;
- }
- if ($row['group_id'] == 2) {
- $orderInfo['packages'][$row['id']] = $row;
- }
- if ($row['type_place_id']) {
- $orderInfo['places'][$row['type_place_id']] = array();
- }
- }
- if ($orderInfo['places']) {
- $orderInfo['places'] = ginst('Place')->getQuotaByIds(array_keys($orderInfo['places']));
- }
- $orderInfo['payment_title'] = $this->paymentTypes[$orderInfo['payment_type']]['title'];
- if ($orderInfo['payment_subtype']) {
- $orderInfo['currency_title'] = $this->paymentTypes[$orderInfo['payment_type']]['subtypes'][$orderInfo['payment_subtype']];
- } else {
- $orderInfo['currency_title'] = $this->paymentTypes[$orderInfo['payment_type']]['currency'];
- }
- $orderInfo['currency_title'] = $orderInfo['price_currency'];
- if (in_array($orderInfo['paid_status'], array(ORDER_STATUS_COMPLETE, ORDER_STATUS_COURIER, ORDER_STATUS_PREPAY)) && !$orderInfo['is_deposit']) {
- foreach ($orderInfo['items'] as $k => $row) {
- $bcImg = ginst('Barcode')->getImage(array(
- 'code' => $row['bar_code'],
- 'code_type' => $row['bar_code_type'],
- 'type' => 'ticket',
- 'is_force' => $is_force,
- ));
- $orderInfo['items'][$k]['bar_code_image'] = $bcImg['filename'];
- $orderInfo['items'][$k]['bar_code_image_vertical'] = $bcImg['filename_vert'];
- $orderInfo['items'][$k]['bar_code_image_vertical1'] = $bcImg['filename_vert1'];
- $orderInfo['items'][$k]['bar_code_image_large'] = $bcImg['filename_large'];
- $orderInfo['items'][$k]['bar_code_image_custom'] = $bcImg['filename_custom'];
- $orderInfo['items'][$k]['bar_code_image_custom1'] = $bcImg['filename_custom1'];
- $orderInfo['items'][$k] = ginst('TicketType')->fixFields($orderInfo['items'][$k]);
- }
- }
- $orderInfo['payment'] = $this->paymentTypes[$orderInfo['payment_type']];
- // Left to pay
- $orderInfo['price_left'] = $orderInfo['billing_price'] - $orderInfo['paid_total'];
- // Seconds left to confirm
- if ($orderInfo['paid_status'] == ORDER_STATUS_NEW) {
- $orderInfo['seconds_left'] = ORDER_CONFIRM_TIME + ( strtotime($orderInfo['date_created']) - strtotime(NOW) );
- }
- if ($orderInfo['delivery_type'] == 2) {
- if ($orderInfo['city_id'] == 10184 || true) {
- $orderInfo['addr'] = ginst('Delivery')->getMostExpressDeliveryContent($order_id);
- $orderInfo['manager_email'] = ginst('Delivery')->getManagerEmails();
- } else {
- $orderInfo['addr'] = ginst('Delivery')->getNewPostDeliveryContent($order_id);
- }
- $orderInfo['delivery_status'] = $GLOBALS['dbh']->getOne('SELECT
- name_ua
- FROM t_delivery_status AS ds
- LEFT JOIN t_most_express_content AS mec ON ds.`status` = mec.`code`
- WHERE ds.`order_id` = ? ORDER BY order_id DESC', array($orderInfo['id']));
- }
- $this->cache[$order_id] = $orderInfo;
- return $orderInfo;
- }
- /**
- * Returns short information by order
- *
- * @global object $dbh
- * @param int $orderId
- * @param array $fields - fields are necessary to get from table
- * @author y.stefanyuk
- * @return array
- */
- public function getShortInfo($orderId = null, $fields = array())
- {
- global $dbh;
- if (!$orderId || !$fields) {
- return;
- }
- $order = $dbh->getRow("
- SELECT " . implode(",", $fields). "
- FROM {$this->table_name}
- WHERE `id` = ?
- ", array($orderId));
- return $order;
- }
- public function apply($order_id, $response_message = "", $params = array(), $confirmOrder = array()) {
- if (!isset($params['email_notify']))
- $params['email_notify'] = true;
- if (!isset($params['generate_pdf']))
- $params['generate_pdf'] = true;
- $cache = true;
- if(!empty($params['false_cache'])){
- $cache = false;
- }
- $orderInfo = $this->get($order_id, 'id', $cache);
- $logFile = fopen(DOC_ROOT ."log/apply_". date("Y-F") .".log", "a");
- fwrite($logFile, "\n".date('Y-m-d H:i:s')."\n");
- fwrite($logFile, 'orderId: '.$order_id."\n");
- $debug = debug_backtrace();
- foreach($debug as $ind => $info) {
- fwrite($logFile, 'index: '.$ind."\n");
- fwrite($logFile, 'file: '.$info['file']."\n");
- if (!empty($info['args'])) {
- fwrite($logFile, 'args: '.serialize($info['args'])."\n");
- }
- }
- fclose($logFile);
- if ($orderInfo['paid_status'] == ORDER_STATUS_COMPLETE ||
- $orderInfo['paid_status'] == ORDER_STATUS_FAILED ||
- $orderInfo['paid_status'] == ORDER_STATUS_PREPAY
- )
- return;
- // 1. Updating status of order - for preventing duplicates of paid orders
- if ($orderInfo['partner_id'] == 10 && $orderInfo['paid_status'] != ORDER_STATUS_COURIER) {
- foreach ($orderInfo['items'] as $item) {
- $payTicketRes = ginst('Premiera')->payTicket($item['external_id']);
- if ($payTicketRes == 0) {
- $GLOBALS['dbh']->query("UPDATE `t_ticket` SET `bar_code_type` = 'code128' WHERE `external_id` = '{$item['external_id']}' AND `order_id` = '{$order_id}' ");
- } else {
- return false;
- }
- }
- }
- if ($orderInfo['delivery_type'] == 1) {
- if (in_array($orderInfo['paid_status'], array(ORDER_STATUS_NEW, ORDER_STATUS_PROCESSING, ORDER_STATUS_OFFLINE, ORDER_STATUS_PARTIALLY))) {
- if ($orderInfo['partner_id'] == 1) {
- if (!$this->karabasSetOrderStatus($orderInfo['id'])) {
- return false;
- }
- }
- if ($orderInfo['partner_id'] == 11) {
- if (!$this->ibConfirmOrder(array('ext_id' => $orderInfo['external_id'], 'order_id' => $orderInfo['id']), '1')) {
- return false;
- };
- }
- if ($orderInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
- if (!$this->_flashBoxConfirmOrder($order_id)) {
- return false;
- }
- }
- if ($orderInfo['partner_id'] == ginst('Kassir24')->getServerId()) {
- if (!ginst('Kassir24')->confirmOrder($order_id)) {
- return false;
- }
- }
- $GLOBALS['dbh']->autoExecute($this->table_name, array(
- 'paid_status' => ORDER_STATUS_COMPLETE,
- 'paid_description' => $response_message,
- 'date_confirmed' => NOW,
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
- } else {
- return;
- }
- } elseif ($orderInfo['delivery_type'] == 2) {
- if (in_array($orderInfo['paid_status'], array(ORDER_STATUS_PROCESSING, ORDER_STATUS_OFFLINE, ORDER_STATUS_PARTIALLY))) {
- if ($orderInfo['partner_id'] == 1) {
- if (!$this->karabasSetOrderStatus($orderInfo['id'])) {
- return false;
- }
- }
- if ($orderInfo['partner_id'] == 11) {
- if (!$this->ibConfirmOrder(array('ext_id' => $orderInfo['external_id'], 'order_id' => $orderInfo['id']), '2')) {
- return false;
- };
- }
- if ($orderInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
- if (!$this->_flashBoxConfirmOrder($order_id)) {
- return false;
- }
- }
- if ($orderInfo['partner_id'] == ginst('Kassir24')->getServerId()) {
- if (!ginst('Kassir24')->confirmOrder($order_id)) {
- return false;
- }
- }
- $GLOBALS['dbh']->autoExecute($this->table_name, array(
- 'paid_status' => ORDER_STATUS_PREPAY,
- 'paid_description' => $response_message,
- 'date_confirmed' => NOW,
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
- } elseif ($orderInfo['paid_status'] == ORDER_STATUS_COURIER) {
- if ($orderInfo['partner_id'] == 1) {
- if (!$this->karabasSetOrderStatus($orderInfo['id'])) {
- return false;
- }
- }
- if ($orderInfo['partner_id'] == 11) {
- if (!$this->ibConfirmOrder(array('ext_id' => $orderInfo['external_id'], 'order_id' => $orderInfo['id']), '3')) {
- return false;
- };
- }
- $GLOBALS['dbh']->autoExecute($this->table_name, array(
- 'paid_status' => ORDER_STATUS_COMPLETE,
- 'paid_description' => $response_message,
- 'date_confirmed' => NOW,
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
- return;
- } else {
- if ($orderInfo['partner_id'] == 1) {
- if (!$this->karabasSetOrderStatus($orderInfo['id'], 3)) {
- return false;
- }
- }
- if ($orderInfo['partner_id'] == 11) {
- $deliveryPeriod = 11;
- $deliveryDate = date('d.m.Y H:i', strtotime($orderInfo['date_created']) + 60 * 60 * 24 * $deliveryPeriod);
- $GLOBALS['dbh']->query("UPDATE `t_order` SET `delivery_expired` = STR_TO_DATE('{$deliveryDate}','%d.%m.%Y %H:%i') WHERE `id` = {$orderInfo['id']}");
- }
- if ($orderInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
- if (!$this->_flashBoxConfirmOrder($order_id)) {
- return false;
- }
- }
- if ($orderInfo['partner_id'] == ginst('Kassir24')->getServerId()) {
- if (!ginst('Kassir24')->confirmOrder($order_id)) {
- return false;
- }
- }
- $GLOBALS['dbh']->autoExecute($this->table_name, array(
- 'paid_status' => ORDER_STATUS_COURIER,
- 'paid_description' => $response_message,
- 'date_confirmed' => NOW,
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
- }
- } elseif ($orderInfo['delivery_type'] == 3) {
- if ($orderInfo['paid_status'] == ORDER_STATUS_CASH) {
- if ($orderInfo['partner_id'] == 1) {
- if (!$this->karabasSetOrderStatus($orderInfo['id'])) {
- return false;
- }
- }
- if ($orderInfo['partner_id'] == 11) {
- if (!$this->ibConfirmOrder(array('ext_id' => $orderInfo['external_id'], 'order_id' => $orderInfo['id']), '3')) {
- return false;
- };
- }
- if ($orderInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
- if (!$this->_flashBoxConfirmOrder($order_id)) {
- return false;
- }
- }
- if ($orderInfo['partner_id'] == ginst('Kassir24')->getServerId()) {
- if (!ginst('Kassir24')->confirmOrder($order_id)) {
- return false;
- }
- }
- $GLOBALS['dbh']->autoExecute($this->table_name, array(
- 'paid_status' => ORDER_STATUS_COMPLETE,
- 'date_confirmed' => NOW,
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
- return;
- } else {
- if ($orderInfo['partner_id'] == 1) {
- if (!$this->karabasSetOrderStatus($orderInfo['id'], 3)) {
- return false;
- }
- }
- if ($orderInfo['partner_id'] == 11) {
- $deliveryPeriod = 11;
- $deliveryDate = date('d.m.Y H:i', strtotime($orderInfo['date_created']) + 60 * 60 * 24 * $deliveryPeriod);
- $GLOBALS['dbh']->query("UPDATE `t_order` SET `delivery_expired` = STR_TO_DATE('{$deliveryDate}','%d.%m.%Y %H:%i') WHERE `id` = {$orderInfo['id']}");
- }
- $GLOBALS['dbh']->autoExecute('t_order', array(
- 'paid_status' => ORDER_STATUS_CASH,
- 'date_confirmed' => NOW,
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
- }
- }
- $ticketTypes = $eventInfo = $notifyAdmins = $newItems = $instructionFiles = array();
- if ($orderInfo['event_id'])
- $eventInfo = ginst('Event')->getById($orderInfo['event_id']);
- $orderInfo = $this->get($orderInfo['id'], 'id', false);
- $reservationId = 0;
- // 0. Going throught all items and checking for packages
- foreach ($orderInfo['items'] as $i => $row) {
- if ($row['group_id'] != 1 && $row['is_detached'] == 0) {
- if ($row['group_id'] == 2 && $row['cer_id'] > 0) {
- $result = ginst('TicketCertificate')->getCerCodes($row['cer_id'], $row['type_id']);
- $orderInfo['items'][$i]['bar_code'] = $result['code'];
- $orderInfo['items'][$i]['bar_code_type'] = $result['code_type'];
- $GLOBALS['dbh']->autoExecute('t_ticket', array(
- 'cert_id' => $result['id'],
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['items'][$i]['id']);
- $orderInfo['items'][$i]['cert_id'] = $result['id'];
- }
- // setting advanced ticket as detached to prevent second detaching
- $GLOBALS['dbh']->autoExecute('t_ticket', array(
- 'is_detached' => 1,
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $row['id']);
- }
- }
- foreach ($orderInfo['items'] as $i => $row) {
- // prevent applay ticket if it saled or reserved
- if (!empty($row['type_place_id'])) {
- $aPlace = ginst('TicketTypePlace')->getPlace($row['type_place_id']);
- if (!empty($aPlace) && $aPlace['is_sold'] == 1 && !in_array($orderInfo['partner_id'], array(16, 17))) {
- $GLOBALS['dbh']->autoExecute('t_ticket', array(
- 'is_canceled' => 1,
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $row['id']);
- continue;
- }
- }
- $orderInfo['items'][$i]['ticket_type'] = ginst('TicketType')->getById($row['type_id']);
- // Some tickets we dont need to print - so checking
- if ($orderInfo['items'][$i]['ticket_type']['is_print']) {
- $orderInfo['items'][$i]['date_printed'] = NOW;
- // 1. Generating barcode
- if (!$orderInfo['items'][$i]['bar_code'] && $orderInfo['partner_id'] == 0) {
- $barCode = ginst('Ticket')->getBarCode(array(
- 'type' => 'ticket',
- 'ticket_id' => $row['id'],
- 'ticket_type_id' => $row['type_id'],
- 'place_id' => $row['type_place_id'],
- 'code_type' => $orderInfo['items'][$i]['ticket_type']['code_type'],
- // 'is_test' => $orderInfo['is_test'] || $orderInfo['items'][$i]['is_test'] || $orderInfo['payment_type'] == 'free' ? 1 : 0,
- ));
- $orderInfo['items'][$i]['bar_code'] = $barCode['code'];
- $orderInfo['items'][$i]['bar_code_type'] = $barCode['type'];
- } else {
- if(empty($orderInfo['items'][$i]['cert_id'])){
- $orderInfo['items'][$i]['bar_code_type'] = $orderInfo['items'][$i]['ticket_type']['code_type'];
- }
- }
- $bcImg = ginst('Barcode')->getImage(array(
- 'code' => $orderInfo['items'][$i]['bar_code'],
- 'code_type' => $orderInfo['items'][$i]['bar_code_type'],
- 'type' => 'ticket',
- 'is_force' => true,
- ));
- $orderInfo['items'][$i]['bar_code_image'] = $bcImg['filename'];
- $orderInfo['items'][$i]['bar_code_image_vertical'] = $bcImg['filename_vert'];
- $orderInfo['items'][$i]['bar_code_image_vertical1'] = $bcImg['filename_vert1'];
- $orderInfo['items'][$i]['bar_code_image_large'] = $bcImg['filename_large'];
- $orderInfo['items'][$i]['bar_code_image_custom'] = $bcImg['filename_custom'];
- $orderInfo['items'][$i]['bar_code_image_custom1'] = $bcImg['filename_custom1'];
- if ($params['generate_pdf']) {
- // 2. Generating PDF
- $orderInfo['items'][$i]['pdf'] = ginst('Ticket')->generatePDF(array(
- 'event' => $eventInfo,
- 'order' => $orderInfo,
- 'ticket' => $orderInfo['items'][$i],
- 'is_filename' => 1,
- 'force' => $params['is_force'] ? 1 : 0,
- ), 'pdf');
- }
- if ($params['email_notify'] && $params['generate_pdf'] && $orderInfo['delivery_type'] == 1) {
- // 2.1. Attaching file to email
- $GLOBALS['oEmail']->attach($orderInfo['items'][$i]['pdf'], '', true);
- }
- // 3. Updating ticket as paid
- $GLOBALS['dbh']->autoExecute('t_ticket', array(
- 'bar_code' => $orderInfo['items'][$i]['bar_code'],
- 'bar_code_type' => $orderInfo['items'][$i]['bar_code_type'],
- 'date_printed' => $orderInfo['items'][$i]['date_printed'],
- 'is_printed' => 1,
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['items'][$i]['id']);
- /* Add ticket barcode as discount code to the discount */
- if (!empty($orderInfo['items'][$i]['ticket_type']['discount_id'])) {
- $discountCodeId = $GLOBALS['dbh']->getOne("SELECT id FROM t_discount_code WHERE discount_id = '{$orderInfo['items'][$i]['ticket_type']['discount_id']}' AND code = '{$orderInfo['items'][$i]['bar_code']}' ");
- if (empty($discountCodeId)) {
- $GLOBALS['dbh']->autoExecute('t_discount_code', array(
- 'discount_id' => $orderInfo['items'][$i]['ticket_type']['discount_id'],
- 'code' => $orderInfo['items'][$i]['bar_code'],
- 'date_created' => NOW,
- ));
- }
- }
- }
- // 4. Saving amount of each ticket type if it's not test ticket
- if (!$orderInfo['items'][$i]['is_test']) {
- if (!$ticketTypes[$orderInfo['items'][$i]['type_id']])
- $ticketTypes[$orderInfo['items'][$i]['type_id']] = 0;
- $ticketTypes[$orderInfo['items'][$i]['type_id']] += 1;
- }
- // 5. Saving notify emails
- if ($row['is_notify'] && $row['notify_email']) {
- $notifyAdmins[$row['notify_email']] = 1;
- }
- // 6. If used discount - then marking it as used
- if ($orderInfo['items'][$i]['used_discount_code_id']) {
- $discount = $GLOBALS['dbh']->getRow("
- SELECT dc.id, de.multi, de.ticket_amount
- FROM t_discount_code AS dc
- LEFT JOIN t_discount_event AS de ON de.discount_id = dc.discount_id AND de.event_id = '{$orderInfo['event_id']}'
- WHERE dc.id = '{$orderInfo['items'][$i]['used_discount_code_id']}' ");
- if ($discount['multi'] == 1 && $discount['ticket_amount'] == 0) {
- $GLOBALS['dbh']->query("UPDATE t_discount_code SET time_used = time_used + 1 WHERE id = '{$orderInfo['items'][$i]['used_discount_code_id']}'");
- } else {
- $GLOBALS['dbh']->query("UPDATE t_discount_code SET time_used = time_used + 1, is_used = '1', date_used = NOW() WHERE id = '{$orderInfo['items'][$i]['used_discount_code_id']}'");
- }
- }
- // 7. Some events used as discounts for others
- ginst('Discount')->tryAddCode($orderInfo['event_id'], $orderInfo['items'][$i]['bar_code']);
- // 8. Ticket with place
- if ($orderInfo['items'][$i]['type_place_id'] && !$orderInfo['items'][$i]['parent_ticket_id']) {
- // We have to mark the place as sold
- if ($orderInfo['delivery_type'] != 3) {
- $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
- 'is_sold' => 1,
- 'date_sold' => NOW,
- 'sold_ticket_id' => $orderInfo['items'][$i]['id'],
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['items'][$i]['type_place_id']);
- }
- }
- // 9. Instruction can present for ticket type
- if ($orderInfo['items'][$i]['instruction_file'] && !isset($instructionFiles[$orderInfo['items'][$i]['instruction_file']]) && $params['email_notify']) {
- // Preventing for duplicates
- $instructionFiles[$orderInfo['items'][$i]['instruction_file']] = 1;
- $instructionFile = DOC_ROOT . web_file(array(
- 'id' => $orderInfo['items'][$i]['type_id'],
- 'row' => ginst('TicketType')->fields['instruction_file'],
- 'name' => $orderInfo['items'][$i]['instruction_file'],
- ));
- // Attaching instruction to mail
- $GLOBALS['oEmail']->attach($instructionFile, $orderInfo['items'][$i]['instruction_file'], true);
- }
- // 10. Saving reservation_id if it's present
- if ($row['reservation_id']) {
- $reservationId = $row['reservation_id'];
- if (!$reservationIds[$row['reservation_id']])
- $reservationIds[$row['reservation_id']] = 1;
- else
- $reservationIds[$row['reservation_id']]++;
- }
- }
- if ($reservationId) {
- // 4. Marking as used reservation - if it's present in order
- $GLOBALS['dbh']->autoExecute('t_reservation', array(
- 'is_used' => 1,
- 'date_used' => NOW,
- 'order_id' => $orderInfo['id'],
- 'amount_used' => $reservationIds[$reservationId],
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $reservationId);
- }
- $orderInfo = $this->get($orderInfo['id'], 'id', false);
- if(empty($orderInfo['discount'])) {
- $discountInfo = $GLOBALS['dbh']->getRow("SELECT
- `de`.*
- FROM
- `t_discount_code` AS `dc`
- LEFT JOIN `t_discount_event` AS `de` ON `de`.`discount_id` = `dc`.`discount_id`
- WHERE
- `de`.`event_id` = '{$orderInfo['event_id']}'
- AND `dc`.`code` = '{$orderInfo['items'][$i]['discount_code']}';");
- $discount = 0;
- $usedDiscount = 0;
- if ($discountInfo['ticket_amount'] == 12) {
- foreach($orderInfo['items'] as $row_temp) {
- if ($usedDiscount >= $row_temp['discount_amount']) {
- continue;
- }
- $subtract = $row_temp['discount_amount'] - $usedDiscount;
- if ($subtract >= $row_temp['price_billing']) {
- $discount += $row_temp['price_billing'];
- $usedDiscount += $row_temp['price_billing'];
- }
- else if ($subtract < $row_temp['price_billing']) {
- $discount += $subtract;
- $usedDiscount += $subtract;
- }
- }
- $orderInfo['discount'] = ginst('Currency')->convert($discount, $orderInfo['price_currency'],'UAH');
- }
- }
- if (!($orderInfo['payment_type'] == 'offline' && $orderInfo['payment_subtype'] == 'pdf') && $params['email_notify'] ) {
- // 6. Send email to customer
- if ($orderInfo['delivery_type'] == 1) {
- if (isset($orderInfo['promo_id']) && !empty($orderInfo['promo_id'])){
- $orderInfo['promo_notify_email'] = $GLOBALS['dbh']->getOne("
- SELECT notify_email
- FROM t_user
- WHERE t_user.id = ".$orderInfo['promo_id']
- );
- $orderInfo['promo_name'] = $GLOBALS['dbh']->getOne("
- SELECT name
- FROM t_user
- WHERE t_user.id = ".$orderInfo['promo_id']
- );
- if(!empty($orderInfo['promo_name'])){
- $orderInfo['promo_name'] = toAscii($orderInfo['promo_name']);
- $orderInfo['promo_name'] = preg_replace('/\W+/','_',$orderInfo['promo_name']);
- }
- }
- ginst('Notices')->order_complete($orderInfo, $eventInfo, $discount_code);
- } elseif ($orderInfo['delivery_type'] == 2) {
- if ($orderInfo['city_id'] == 10184 || true) {
- ginst('Courier')->sendReport($orderInfo, $eventInfo);
- } else {
- $newpostOrderData = simplexml_load_string(ginst('Delivery')->createInvoice($orderInfo));
- $GLOBALS['dbh']->autoExecute('t_delivery', array('newpost_order_id' => (string)$newpostOrderData->order->attributes()->np_id), DB_AUTOQUERY_UPDATE, ' order_id = ' . $orderInfo['id']);
- }
- ginst('Notices')->delivery_report_user($orderInfo, $eventInfo);
- } elseif($orderInfo['delivery_type'] == 3) {
- ginst('Notices')->reservationComplete($orderInfo['id']);
- }
- }
- $discount = 0;
- // Визначення знижки і кількості товарів
- if(empty($orderInfo['discount'])) {
- if ($discountInfo['ticket_amount'] != 12) {
- foreach($orderInfo['items'] as $row_temp) {
- if ($row['is_percents'] == 0) {
- $discount += $row_temp['discount_amount'];
- } elseif ($discountInfo['is_percents'] == 1) {
- $discount += $row_temp['price_billing'] / 100 * $discountInfo['discount_amount'];
- }
- if (!($row['group_id'] == 2 && $row_temp['cert_id'] == 0)) {
- $orderInfo['items_count_user']++;
- }
- }
- $orderInfo['discount'] = ginst('Currency')->convert($discount, $orderInfo['price_currency'],'UAH');
- }
- }
- // 7. Notify administrators of ticket types
- if ($notifyAdmins && $params['email_notify'] && !$orderInfo['items'][0]['is_hidden'] && $orderInfo['payment_subtype'] <> 'test') {
- if (isset($orderInfo['promo_id']) && !empty($orderInfo['promo_id'])){
- $orderInfo['promo_site'] = ginst('User')->promoSite($orderInfo['promo_id']);
- } else {
- $orderInfo['promo_site'] = "v-ticket.com.ua";
- }
- $offline_user = array();
- if (!empty($orderInfo['items'][0]['user_id'])) {
- $offline_user = ginst('User')->info(array('id' => $orderInfo['items'][0]['user_id']));
- }
- $sNotifyAdmins = implode(',', array_keys($notifyAdmins));
- ginst('Notices')->order_notify($eventInfo, $orderInfo, $sNotifyAdmins);
- }
- // 8. SMS notify
- if ($params['sms_notify'] == true && $orderInfo['delivery_type'] == 1) {
- $textSms = $GLOBALS['dbh']->getOne("
- SELECT IFNULL(`nc1`.`sms`,`nc2`.`sms`) AS `sms`
- FROM `t_notices` AS `n`
- LEFT JOIN `t_notices_content` AS `nc1` ON `nc1`.`id` = `n`.`id` AND `nc1`.`language_id` = " . $GLOBALS['lng']['id'] . "
- LEFT JOIN `t_notices_content` AS `nc2` ON `nc2`.`id` = `n`.`id` AND `nc2`.`language_id` = 1
- WHERE `n`.`alias` = 'order_complete'
- ");
- $textSms = preg_replace('/%EMAIL%/', $orderInfo['email'], $textSms);
- $textSms = preg_replace('/%SENDTICKETS%/', (count($orderInfo['items']) > 1 ? ' otpravleny tvoi bilety' : ' otpravlen tvoj bilet'), $textSms);
- $textSms = preg_replace('/%THISTICKET%/', (count($orderInfo['items']) > 1 ? 'eti zhe bilety' : 'etot zhe bilet'), $textSms);
- $textSms = preg_replace('/%LINKTICKET%/', ginst('Order')->getQuickUrl($orderInfo), $textSms);
- $res = ginst('Sms')->send(
- $orderInfo['mobile'], $textSms, array(
- 'item_type' => 'order',
- 'item_id' => $orderInfo['id']
- )
- );
- } elseif ($orderInfo['delivery_type'] == 2) {
- if ($orderInfo['paid_status'] == ORDER_STATUS_COURIER) {
- $textSms = $GLOBALS['dbh']->getOne("
- SELECT IFNULL(`nc1`.`sms`,`nc2`.`sms`) AS `sms`
- FROM `t_notices` AS `n`
- LEFT JOIN `t_notices_content` AS `nc1` ON `nc1`.`id` = `n`.`id` AND `nc1`.`language_id` = " . $GLOBALS['lng']['id'] . "
- LEFT JOIN `t_notices_content` AS `nc2` ON `nc2`.`id` = `n`.`id` AND `nc2`.`language_id` = 1
- WHERE `n`.`alias` = 'delivery_report_user'
- ");
- $textSms = preg_replace('/%ORDER_ID%/', $orderInfo['id'], $textSms);
- $textSms = preg_replace('/%PERIOD%/', $orderInfo['addr']['period'], $textSms);
- $textSms = preg_replace('/%PRICE_TOTAL%/', $orderInfo['price_total'], $textSms);
- $res = ginst('Sms')->send(
- $orderInfo['mobile'], $textSms, array(
- 'item_type' => 'order',
- 'item_id' => $orderInfo['id']
- )
- );
- } else {
- $textSms = $GLOBALS['dbh']->getOne("
- SELECT IFNULL(`nc1`.`sms`,`nc2`.`sms`) AS `sms`
- FROM `t_notices` AS `n`
- LEFT JOIN `t_notices_content` AS `nc1` ON `nc1`.`id` = `n`.`id` AND `nc1`.`language_id` = " . $GLOBALS['lng']['id'] . "
- LEFT JOIN `t_notices_content` AS `nc2` ON `nc2`.`id` = `n`.`id` AND `nc2`.`language_id` = 1
- WHERE `n`.`alias` = 'delivery_report_user_prepay'
- ");
- $textSms = preg_replace('/%ORDER_ID%/', $orderInfo['id'], $textSms);
- $textSms = preg_replace('/%PERIOD%/', $orderInfo['addr']['period'], $textSms);
- $textSms = preg_replace('/%PRICE_TOTAL%/', $orderInfo['price_total'], $textSms);
- $res = ginst('Sms')->send(
- $orderInfo['mobile'], $textSms, array(
- 'item_type' => 'order',
- 'item_id' => $orderInfo['id']
- )
- );
- }
- } elseif($orderInfo['delivery_type'] == 3) {
- ginst('Offline')->sendSMS($orderInfo['id']);
- }
- // 9. Updating counters of selled tickets
- ginst('TicketType')->updateCounters($eventInfo['id']);
- // 10. Notification administrators about end of quote
- $ticketTypesInfo = ginst('TicketType')->culcTicketsRemainder($eventInfo['id']);
- if ($ticketTypesInfo) {
- //ginst('Notices')->quoteExpires($eventInfo['id'], $ticketTypesInfo);
- }
- // Спеціальний код відправки даних для ТиНаказанТіпа
- if ($orderInfo['event_id'] == 5313) {
- $kazantipInfo = $GLOBALS['dbh']->getRow("
- SELECT *
- FROM t_kazantip
- WHERE order_id = ?
- ", 0, array($orderInfo['id']));
- $res = ginst('RemoteConnection')->getData(array(
- 'url' => 'https://z-viza.kazantip.info/cgi-bin/remote.fcgi',
- 'post' => 1,
- 'header' => 1,
- 'ssl' => 0,
- 'params' => array (
- 'login' => 'concertua',
- 'passwd' => 'nHmnd2187fjKms',
- 'action' => 'add_online_paid_viza',
- 'number' => $orderInfo['items'][0]['bar_code'],
- 'client_category_id' => 13,
- 'country' => $kazantipInfo['country'],
- 'city' => $kazantipInfo['city'],
- 'email' => $kazantipInfo['email'],
- 'phone' => $kazantipInfo['mobile'],
- 'last_name' => $kazantipInfo['lastname'],
- 'first_name' => $kazantipInfo['firstname'],
- 'patronymic' => $kazantipInfo['patronymic'],
- 'passport' => $kazantipInfo['passport'],
- 'gender' => $kazantipInfo['sex'] ? 'male' : 'female',
- 'price' => $orderInfo['price_total'],
- 'foto' => "@" . DOC_ROOT . "dynamic/user/extended/{$orderInfo['id']}.{$kazantipInfo['photo_ext']}"
- )
- ));
- $kazantipRes = explode("|", $res);
- $kazantipSuccess = explode("=", $kazantipRes[0]);
- $kazantipDesc = 'Success';
- if (!$kazantipSuccess[1]) {
- $kazantipError = explode("=", $kazantipRes[1]);
- $kazantipDesc = $kazantipError[1];
- }
- $GLOBALS['dbh']->autoExecute('t_kazantip', array(
- 'success' => $kazantipSuccess[1],
- 'description' => $kazantipDesc,
- ), DB_AUTOQUERY_UPDATE, ' order_id = ' . $orderInfo['id']);
- mkdir(DOC_ROOT."log", '0775', true);
- $fres = fopen(DOC_ROOT."log/kazantip_".date("Y-F").".log", "a");
- fwrite($fres, date('Y-m-d H:i:s')."\n");
- fwrite($fres, $res ."\n\n");
- fclose($fres);
- }
- // 11. Appling the booking
- ginst('Api')->internalApplyBooking($orderInfo['id']);
- }
- public function resend($orderInfo, $params = array()) {
- $eventInfo = ginst('Event')->getById($orderInfo['event_id']);
- $instructionFiles = array();
- if (!$orderInfo['is_deposit']) {
- foreach ($orderInfo['items'] as $i => $row) {
- $bcImg = ginst('Barcode')->getImage(array(
- 'code' => $orderInfo['items'][$i]['bar_code'],
- 'code_type' => $orderInfo['items'][$i]['bar_code_type'],
- 'type' => 'ticket',
- ));
- $orderInfo['items'][$i]['bar_code_image'] = $bcImg['filename'];
- $orderInfo['items'][$i]['bar_code_image_vertical'] = $bcImg['filename_vert'];
- $orderInfo['items'][$i]['bar_code_image_vertical1'] = $bcImg['filename_vert1'];
- $orderInfo['items'][$i]['bar_code_image_large'] = $bcImg['filename_large'];
- $orderInfo['items'][$i]['bar_code_image_custom'] = $bcImg['filename_custom'];
- $orderInfo['items'][$i]['bar_code_image_custom1'] = $bcImg['filename_custom1'];
- $orderInfo['items'][$i]['ticket_type'] = ginst('TicketType')->getById($row['type_id']);
- $orderInfo['items'][$i]['pdf'] = ginst('Ticket')->generatePDF(array(
- 'event' => $eventInfo,
- 'order' => $orderInfo,
- 'ticket' => $orderInfo['items'][$i],
- 'force' => true,
- 'is_filename' => 1,
- ), 'pdf');
- if ($orderInfo['items'][$i]['instruction_file'] && !isset($instructionFiles[$orderInfo['items'][$i]['instruction_file']])) {
- // Preventing for duplicates
- $instructionFiles[$orderInfo['items'][$i]['instruction_file']] = 1;
- $instructionFile = DOC_ROOT . web_file(array(
- 'id' => $orderInfo['items'][$i]['type_id'],
- 'row' => ginst('TicketType')->fields['instruction_file'],
- 'name' => $orderInfo['items'][$i]['instruction_file'],
- ));
- // Attaching instruction to mail
- $GLOBALS['oEmail']->attach($instructionFile, $orderInfo['items'][$i]['instruction_file'], true);
- }
- if($orderInfo['delivery_type'] != 2){
- $GLOBALS['oEmail']->attach($orderInfo['items'][$i]['pdf'], '', true);
- }
- }
- }
- // 5. Send email to customer
- /**
- * TODO: for New Post!
- */
- if ($orderInfo['delivery_type'] == 2) {
- ginst('Courier')->sendReport($orderInfo);
- } else {
- // Attaching ticket
- ginst('Notices')->order_complete($orderInfo, $eventInfo, $discount_code);
- }
- $this->addLog(array(
- 'order_id' => $orderInfo['id'],
- 'action' => 'resend-email',
- 'info' => array(
- 'email' => $orderInfo['email'],
- 'subject' => $GLOBALS['oEmail']->sSubject,
- 'text' => $GLOBALS['oEmail']->text,
- 'text_html' => $GLOBALS['oEmail']->text_html,
- ),
- ));
- // 8. SMS notify
- if ($params['sms_notify'] == true) {
- // Generating shor url for order
- $shortUrl = ginst('Order')->shortUrl();
- $sms = $GLOBALS['dbh']->getOne("
- SELECT `nc`.`sms`
- FROM `t_notices` AS `n`
- LEFT JOIN `t_notices_content` AS `nc` ON `nc`.`id` = `n`.`id` AND `nc`.`language_id` = 1
- WHERE `n`.`alias` = 'order_resend'
- ");
- $sms = preg_replace('/%EMAIL%/', $orderInfo['email'], $sms);
- $sms = preg_replace('/%SENDTICKETS%/', (count($orderInfo['items']) > 1 ? 'otpravleny tvoi bilety' : 'otpravlen tvoj bilet'), $sms);
- $res = ginst('Sms')->send(
- $orderInfo['mobile'], $sms, array(
- 'item_type' => 'order',
- 'item_id' => $orderInfo['id']
- )
- );
- $this->addLog(array(
- 'order_id' => $orderInfo['id'],
- 'action' => 'resend-sms',
- 'info' => array(
- 'mobile' => $orderInfo['mobile'],
- 'text' => $sms,
- ),
- ));
- }
- }
- public function failed($order_id, $response_message) {
- $orderInfo = $this->get($order_id);
- if (
- $orderInfo['paid_status'] == ORDER_STATUS_COMPLETE ||
- $orderInfo['paid_status'] == ORDER_STATUS_FAILED
- )
- return;
- switch ($orderInfo['partner_id']) {
- case 1:
- ginst('Karabas')->cancelOrder($orderInfo['external_id'], 'failed order');
- break;
- case 10:
- ginst('Premiera')->cancelOrder($orderInfo['id']);
- break;
- case ginst('FlashBox')->getServerId():
- $this->_flashBoxCancelOrder($orderInfo['id']);
- break;
- case ginst('Kassir24')->getServerId():
- ginst('Kassir24')->cancelOrder($orderInfo['id']);
- break;
- }
- // 1. Updating status of order
- $GLOBALS['dbh']->autoExecute($this->table_name, array(
- 'paid_status' => ORDER_STATUS_FAILED,
- 'paid_description' => $response_message,
- 'date_confirmed' => NOW,
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
- $eventInfo = ginst('Event')->getById($orderInfo['event_id']);
- if ($orderInfo['payment_type'] == 'liqpay') {
- ginst('Notices')->order_failed($orderInfo);
- // 2. Sending notification about failing
- // $GLOBALS['oEmail']->send(array(
- // 'template' => 'order_failed',
- // 'to' => $orderInfo['email'],
- // 'data' => array(
- // 'eventInfo' => $eventInfo,
- // 'order' => $orderInfo,
- // ),
- // 'item_type' => 'order-failed',
- // 'item_id' => $orderInfo['id'],
- // ));
- }
- }
- public function checkSelectedLocation($order_info) {
- $res = true;
- if ($order_info['country'] == 'none' || $order_info['country'] == 'null' || $order_info['country'] == 'no data') {
- $res = false;
- }
- if ($order_info['region'] == 'none' || $order_info['region'] == 'null' || $order_info['region'] == 'no data') {
- $res = false;
- }
- if ($order_info['city_id'] == 'none' || $order_info['city_id'] == 'null' || $order_info['city_id'] == 'no data') {
- $res = false;
- }
- return $res;
- }
- public $userFields = array('firstname', 'lastname', 'city', 'email', 'number');
- public $addressFields = array('street', 'house', 'flat', 'zip');
- public function checkFields($eventInfo, $order_info, $errors = true) {
- $res = '';
- foreach ($this->userFields as $name) {
- if (!trim($order_info[$name])) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_' . $name) . ' ' . $GLOBALS['smarty']->get_config_vars('form_field_required');
- }
- }
- if (!in_array($order_info['delivery'], array_keys($this->deliveryTypes))
- || $order_info['delivery'] == 1 && $eventInfo['eticket_enabled'] == 0
- || $order_info['delivery'] == 2 && $eventInfo['delivery_enabled'] == 0
- || $order_info['delivery'] == 3 && $eventInfo['reservation_enabled'] == 0) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_delivery');
- }
- if ($order_info['delivery'] == 2) {
- /*if (($order_info['city_id'] == 10184 && in_array($order_info['delivery_subtype'], array(3,4)))
- || $order_info['city_id'] != 10184 && $order_info['delivery_subtype'] == 3) {*/
- foreach ($this->addressFields as $address) {
- if (!trim($order_info[$address])) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_' . $address);
- }
- }
- $deliveryData = ginst('Delivery')->getMostExpressRates($eventInfo['id'], $order_info['city_id']);
- if (!$deliveryData['deliveryPeriod']) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_date');
- }
- /*} else {
- if (empty($order_info['ware_id']) || $order_info['ware_id'] <= 0) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_waren');
- }
- }*/
- }
- // checking for correct mobile number
- if (!ginst('Sms')->checkNumber($order_info['number'])) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_number');
- }
- // checking email
- if (trim($order_info['email']) && !check_email($order_info['email'])) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_email');
- }
- if (in_array($order_info['delivery'], array_keys($this->deliveryTypes)) && $order_info['delivery'] != 3) {
- if (!$this->paymentTypes[$order_info['payment']] && !$GLOBALS['bIsAdmin']) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_payment');
- } elseif ($this->paymentTypes[$order_info['payment']]['subtypes'] && !$GLOBALS['bIsAdmin']) {
- if (!$this->paymentTypes[$order_info['payment']]['subtypes'][$order_info['subpayment'][$order_info['payment']]]) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_subpayment');
- }
- }
- }
- /*$forbiddenMail = array('mail.ru', 'ukr.net', 'inbox.ru', 'bk.ru', 'list.ru');
- // don't check email when order is in status delivery by courier
- if($order_info['delivery'] != 2){
- foreach ($forbiddenMail as $name) {
- if (strpos(strtolower($order_info['email']), '@' . $name) !== false) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_email_forbidden');
- break;
- }
- }
- }
- */
- if ($GLOBALS['bIsAdmin'] && !$order_info['types']) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_no_tickets_selected');
- }
- if (!empty($eventInfo['allFree']) && $eventInfo['allFree'] == 1) {
- $row = $GLOBALS['dbh']->getRow('SELECT * FROM t_order WHERE event_id = ? AND mobile = ? AND paid_status = 2 LIMIT 1', array($eventInfo['id'], $order_info['number']));
- if (!empty($row['id']) && !$GLOBALS['isLocal']) {
- // already in use mobile
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('order_mobile_number_already_in_use');
- }
- $row = $GLOBALS['dbh']->getRow('SELECT * FROM t_order WHERE event_id = ? AND email = ? AND paid_status = 2 LIMIT 1', array($eventInfo['id'], $order_info['email']));
- if (!empty($row['id']) && !$GLOBALS['isLocal']) {
- // already in use email
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('order_email_already_in_use');
- }
- $row = $GLOBALS['dbh']->getRow('SELECT * FROM t_order WHERE event_id = ? AND ip_address = ? AND paid_status = 2 LIMIT 1', array($eventInfo['id'], get_real_ip()));
- if (!empty($row['id']) /* && !$GLOBALS['isLocal'] */) {
- // already in use email
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('order_ip_already_in_use');
- }
- }
- if ($eventInfo['extended_form']) {
- if (!$order_info['is_concert']) {
- if ($_FILES['photo_ext']['error'] === 0) {
- preg_match('/\.(jpeg|png|jpg)$/i', $_FILES["photo_ext"]["name"], $match);
- if (empty($match[1])) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_photo_ext');
- } else {
- if ($_FILES['photo_ext']['size'] > 3 * 1024 * 1024) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_photo_ext');
- } else {
- $imageInfo = getimagesize($_FILES['photo_ext']['tmp_name']);
- if ($imageInfo[0] < 1024 || $imageInfo[1] < 768) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_photo_dimantion');
- }
- }
- }
- } else {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_photo');
- }
- }
- if (!trim($order_info['passport'])) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_passport');
- }
- if (!in_array($order_info['sex'], array(0, 1))) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_sex');
- }
- }
- if ($res && $errors) {
- $GLOBALS['cStatus']->setError('<br/>' . $res);
- }
- return $res ? false : true;
- }
- public function checkCountTickets($eventInfo, $order_info, $errors = true) {
- $res = '';
- // checking for correct ticket types selected and amounts
- $totalTickets = 0;
- if ($eventInfo['partner_id'] == 1 || ($eventInfo['partner_id'] == 11 && $eventInfo['ib_scheme'] > 0)) {
- $totalTickets = count($order_info['place']);
- } else {
- if (!empty($order_info['amount'])) {
- foreach ($order_info['amount'] as $id => $am) {
- $totalTickets += (int) $am;
- if ($am && !isset($eventInfo['ticketTypes'][$id])) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_tickets_selected');
- break;
- } elseif ($am > 10 || !empty($eventInfo['allFree']) && $eventInfo['allFree'] == 1 && $am > 2) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_tickets_amount') . ' ' . $eventInfo['ticketTypes'][$id]['title'];
- } elseif (isset($eventInfo['ticketTypes'][$id]['cnt_max']) && $am > $eventInfo['ticketTypes'][$id]['cnt_max'] && $eventInfo['ticketTypes'][$id]['cnt_max'] > 0) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_tickets_amount') . ' ' . $eventInfo['ticketTypes'][$id]['title'];
- }
- }
- }
- // checking for correct places selected
- if ($eventInfo['is_scheme'] && $order_info['place']) {
- $placesQuota = ginst('Place')->getQuota($eventInfo['id']);
- $reservedPlaces = '';
- $soldedPlaces = '';
- foreach ($order_info['place'] as $type_id => $places) {
- foreach ($places as $place_id) {
- if ($placesQuota[$place_id]['active_type'] == 0 || $placesQuota[$place_id]['is_soldout'] == 1) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_wrong_tickets_selected');
- break;
- } elseif (!(isset($placesQuota[$place_id]) && !$placesQuota[$place_id]['is_sold'])) {
- $soldedPlaces .= ($soldedPlaces ? ', ' : '' ) . $placesQuota[$place_id]['title_full'];
- } elseif ($placesQuota[$place_id]['is_reserved']) {
- $reservedPlaces .= ($reservedPlaces ? ', ' : '' ) . $placesQuota[$place_id]['title_full'];
- }
- $totalTickets += 1;
- }
- }
- if ($soldedPlaces) {
- $res .= ($res ? '<br/>' : '') . '• ' . sprintf($GLOBALS['smarty']->get_config_vars('form_wrong_tickets_selected_with_place_sold'), $soldedPlaces);
- }
- if ($reservedPlaces) {
- $res .= ($res ? '<br/>' : '') . '• ' . sprintf($GLOBALS['smarty']->get_config_vars('form_wrong_tickets_selected_with_place'), $reservedPlaces);
- }
- }
- }
- if (!$totalTickets) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_select_tickets_please');
- } elseif ($totalTickets > 10) {
- $res .= ($res ? '<br/>' : '') . '• ' . $GLOBALS['smarty']->get_config_vars('form_select_tickets_more_then10');
- }
- if ($res && $errors) {
- $GLOBALS['cStatus']->setError($res);
- }
- return $res ? false : true;
- }
- public function getSecretCode() {
- $code = '';
- while (1) {
- $code = rand(10000000, 99999999);
- $code .= rand(10, 99);
- $r = $GLOBALS['dbh']->getOne('SELECT id FROM t_order WHERE secret_code = ? LIMIT 1', array($code));
- if (!$r)
- break;
- }
- return $code;
- }
- public function checkSecretCode($code = false) {
- return preg_match('/^(\d{10})$/', $code);
- }
- public function getQuickUrl($orderInfo) {
- return "http://v-ticket.com.ua/q/" . $orderInfo['secret_code'] . "";
- }
- public function partiallyPay($order_id = false, $amount = 0, $currency = 'UAH') {
- if (!$order_id)
- return false;
- $orderInfo = $this->get($order_id);
- // Saving payment
- $GLOBALS['dbh']->autoExecute('t_order_payment', array(
- 'order_id' => $order_id,
- 'date_paid' => NOW,
- 'payment_type' => $orderInfo['payment_type'],
- 'amount' => $amount,
- 'currency' => $currency,
- ));
- // Updating order as partial paid
- $GLOBALS['dbh']->autoExecute('t_order', array(
- 'paid_status' => ORDER_STATUS_PARTIALLY,
- 'paid_total' => $orderInfo['paid_total'] + $amount,
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $order_id);
- ginst('TicketType')->updateCounters($orderInfo['event_id']);
- // Notify user about partially paid order
- $smsText = $GLOBALS['dbh']->getOne("
- SELECT `nc`.`sms`
- FROM `t_notices` AS `n`
- LEFT JOIN `t_notices_content` AS `nc` ON `nc`.`id` = `n`.`id` AND `nc`.`language_id` = 1
- WHERE `n`.`alias` = 'partiallyPay'
- ");
- $smsText = preg_replace('/%AMOUNT%/', sprintf('%0.2f', $amount), $smsText);
- $smsText = preg_replace('/%CHANGE%/', sprintf('%0.2f', $orderInfo['billing_price'] - $orderInfo['paid_total'] - $amount), $smsText);
- $smsText = preg_replace('/%SECRET_CODE%/', $orderInfo['secret_code'], $smsText);
- ginst('Sms')->send(
- $orderInfo['mobile'], $smsText, array(
- 'item_type' => 'order',
- 'item_id' => $orderInfo['id']
- )
- );
- }
- public function cancel($orderInfo = false, $reason_text = '', $new_status = ORDER_STATUS_CANCELLED) {
- switch ($orderInfo['partner_id']) {
- case 1:// remove ticket from basket if Karabas Event
- ginst('Karabas')->cancelOrder($orderInfo['external_id'], $reason_text);
- break;
- case 10: // cancel Premiera order tickets
- ginst('Premiera')->cancelOrder($orderInfo['id']);
- break;
- case 11:
- ginst('InternetBilet')->bookingCancel($orderInfo['external_id']);
- break;
- case ginst('FlashBox')->getServerId():
- $this->_flashBoxCancelOrder($orderInfo['id']);
- break;
- case ginst('Kassir24')->getServerId():
- if (!ginst('Kassir24')->refundOrder($orderInfo['id'])) {
- return false;
- }
- break;
- }
- //canceled New Post order
- if ($orderInfo['delivery_type'] == 2 && $orderInfo['city_id'] != 10184 && false) {
- ginst('Delivery')->cancelInvoice($orderInfo['addr']['np_order_id']);
- }
- if ($new_status == ORDER_STATUS_CANCELLED && !in_array($orderInfo['paid_status'], array(ORDER_STATUS_COMPLETE, ORDER_STATUS_COURIER, ORDER_STATUS_OFFLINE, ORDER_STATUS_PREPAY, ORDER_STATUS_CASH)))
- return false;
- // 1. Cancelling order
- $GLOBALS['dbh']->autoExecute('t_order', array(
- 'paid_status' => $new_status,
- 'date_cancelled' => NOW,
- 'cancelled_reason' => $reason_text,
- ), DB_AUTOQUERY_UPDATE, 'id = ' . $orderInfo['id']);
- // 2. Cancelling tickets
- if (!$orderInfo['items']) {
- $orderInfo = $this->get($orderInfo['id']);
- }
- if ($orderInfo['items']) {
- $tid = $pid = array();
- foreach ($orderInfo['items'] as $row) {
- $tid[] = $row['id'];
- if ($row['type_place_id']) {
- $pid[] = $row['type_place_id'];
- }
- }
- // Cancelling tickets
- if ($tid) {
- $GLOBALS['dbh']->autoExecute('t_ticket', array(
- 'is_canceled' => 1,
- ), DB_AUTOQUERY_UPDATE, 'id IN (' . implode(',', $tid) . ')');
- $GLOBALS['dbh']->autoExecute('t_barcode_external', array(
- 'is_used' => 0,
- 'date_used' => null,
- 'ticket_id' => null
- ), DB_AUTOQUERY_UPDATE, 'ticket_id IN (' . implode(',', $tid) . ')');
- }
- // Cancelling places
- if ($pid) {
- $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
- 'is_sold' => 0,
- 'is_reserved' => 0,
- ), DB_AUTOQUERY_UPDATE, 'id IN (' . implode(',', $pid) . ')');
- }
- }
- // 3. Updating counters of sold tickets
- ginst('TicketType')->updateCounters($orderInfo['event_id']);
- // 4. Cancelation of booking
- ginst('Api')->internalCancelBooking($orderInfo['id'], $reason_text);
- // 5. Logging about cancelling
- ginst('Order')->addLog(array(
- 'order_id' => $orderInfo['id'],
- 'action' => 'cancelled',
- 'info' => array(
- 'reason' => $reason_text,
- 'old_status' => $orderInfo['paid_status'],
- 'new_status' => $new_status,
- ),
- ));
- return true;
- }
- public static function getTopDJLogs($orderId = null)
- {
- $paymentInfo = array();
- topdjDB_connect();
- $merchantOrder = $GLOBALS['dbh2']->getRow('SELECT * FROM t_merchant_order WHERE merchant_id = ? AND merchant_order_id = ?', array(
- self::$_mIdTopDJ,
- $orderId
- ));
- if ($merchantOrder['id']) {
- $aMerchantOrderStatuses = array(
- 0 => 'Отправлен на оплату',
- 1 => 'Оплачен',
- 2 => 'Не прошёл',
- );
- $paymentInfo[] = array(
- 'title' => 'Создан заказ мерчанта на TopDJ',
- 'date_log' => $merchantOrder['date_created'],
- 'amount' => $merchantOrder['amount'],
- 'currency' => $merchantOrder['currency'],
- 'info' => 'ID: ' . $merchantOrder['id'] . '<br/>Статус: ' . $aMerchantOrderStatuses[$merchantOrder['paid_status']]
- );
- $paidOrderInfo = $GLOBALS['dbh2']->getRow('SELECT * FROM t_paid_order WHERE item_id = ? AND service_type = ?', array(
- $merchantOrder['id'],
- 'merchant-order'
- ));
- // $paidOrderInfo['id'] = 22190;
- // $txt = file_get_contents("http://topdj.ua/log/card_trans_2011-April.log");
- // $txt = explode("\n\n", $txt);
- // exit;
- if ($paidOrderInfo['id']) {
- $text = '';
- if ($paidOrderInfo['status'] <> 1) {
- // Trying to extract information about this order
- // $info = unserialize($paidOrderInfo['status_info']);
- if ($paidOrderInfo['payment_type'] == 'liqpay') {
- $text = '';
- } elseif ($paidOrderInfo['payment_type'] == 'card_uah') {
- // Extracting information from log
- $txt = file_get_contents("http://topdj.ua/log/card_trans_" . date("Y-F", strtotime($paidOrderInfo['date_created'])) . ".log");
- $txt = explode("\n\n", $txt);
- foreach ($txt as $t) {
- $t = explode("\n", $t);
- if ($t[0] == $paidOrderInfo['id']) {
- $t = unserialize($t[1]);
- $text = '<b>Ошибка на русском</b><br/>' . iconv('windows-1251', 'utf-8', $t['message'] . "<br/><br/>" . $t['other']['description_admin']);
- $text .= '<br/><br/><b>Ошибка на английском</b><br/>' . iconv('windows-1251', 'utf-8', $t['message_en'] . "<br/><br/>" . $t['other']['transaction']['ReasonCodeDesc']);
- break;
- }
- }
- }
- }
- $aTopDJOrderStatuses = array(
- 0 => 'Не сформирован',
- 1 => 'Успешно оплачен',
- 2 => 'Отправлен на оплату',
- 3 => 'Не прошёл',
- 4 => 'Ожидаем подтверждения',
- );
- $paymentInfo[] = array(
- 'title' => 'Создан заказ для оплаты через TopDJ',
- 'date_log' => $paidOrderInfo['date_created'],
- 'amount' => $paidOrderInfo['amount'],
- 'currency' => $paidOrderInfo['currency_code'],
- 'info' => 'ID: ' . $paidOrderInfo['id'] . '<br/>Статус: ' . $paidOrderInfo['status'] . ($text ? '<br/><br/>' . $text : '')
- );
- }
- }
- return $paymentInfo;
- }
- public static function getOrderSecretCode($value = null, $field = 'id')
- {
- if (!$value) return 0;
- $secretCode = $GLOBALS['dbh']->getOne("
- SELECT `secret_code`
- FROM `t_order`
- WHERE `$field` = ?", array($value)
- );
- return $secretCode;
- }
- public $sTableOrderLog = 't_order_log';
- public $aLogActions = array(
- 'liqpay-wait' => array(
- 'title' => 'Liqpay: Заказ переведён в статус "Wait Secure"',
- // 'info_template' => '%EMAIL%',
- ),
- 'failed' => array(
- 'title' => 'Оплата не прошла',
- 'info_template' => 'Причина: %MESSAGE%',
- ),
- 'cancelled' => array(
- 'title' => 'Аннулирован',
- 'info_template' => '%REASON%',
- ),
- 'manual-apply' => array(
- 'title' => 'Смена статуса вручную на: "Оплачено"',
- 'info_template' => 'Предыдущий статус: %STATUS%<br/>Причина: %REASON%',
- ),
- 'confirm-order' => array(
- 'title' => 'Смена статуса вручную на: "Оплачено"',
- 'info_template' => 'Предыдущий статус: %STATUS%',
- ),
- 'resend-email' => array(
- 'title' => 'Повторная отправка e-mail',
- 'info_template' => '%EMAIL%',
- ),
- 'resend-sms' => array(
- 'title' => 'Повторная отправка sms',
- 'info_template' => '%MOBILE%<br/>%TEXT%',
- ),
- 'change-email' => array(
- 'title' => 'Изменение e-mail',
- 'info_template' => 'Старый: %EMAIL_OLD%<br/>Новый: %EMAIL_NEW%',
- ),
- 'generate-pdf' => array(
- 'title' => 'Генерация билета',
- 'info_template' => 'Формат: %FORMAT%<br/>Штрих-код: %BAR_CODE%',
- ),
- 're-generate-pdf' => array(
- 'title' => 'Повторная генерация билета',
- 'info_template' => 'Формат: %FORMAT%<br/>Штрих-код: %BAR_CODE%',
- ),
- 'download-pdf' => array(
- 'title' => 'Скачать билет',
- 'info_template' => 'Формат: %FORMAT%<br/>Штрих-код: %BAR_CODE%',
- ),
- 'delete-reserve' => array(
- 'title' => 'Снятия с резерва',
- 'info_template' => 'Предыдущий статус: %STATUS%<br/>Причина: %REASON%',
- ),
- 'stop-selling' => array(
- 'title' => 'Продажа остановлена',
- 'info_template' => 'Предыдущий статус: %STATUS%',
- ),
- );
- public function addLog($params) {
- if (!$params['order_id'])
- return false;
- $GLOBALS['dbh']->autoExecute($this->sTableOrderLog, array(
- 'order_id' => $params['order_id'],
- 'user_id' => $params['user_id'] ? $params['user_id'] : $GLOBALS['aUser']['id'],
- 'ip_address' => get_real_ip(),
- 'action' => $params['action'],
- 'info' => serialize($params['info']),
- 'date_log' => formatTime('Y-m-d H:i:s', microtime()),
- ));
- }
- public function getLog($order_id = false) {
- $tmp = $GLOBALS['dbh']->getAll(
- '
- SELECT
- tol.*,
- t_user.firstname, t_user.lastname
- FROM
- ' . $this->sTableOrderLog . ' AS tol
- LEFT JOIN t_user oN (tol.user_id = t_user.id)
- WHERE
- tol.order_id = ?
- ORDER BY date_log DESC, id DESC
- ', array($order_id)
- );
- foreach ($tmp as $k => $row) {
- $tmp[$k]['info'] = unserialize($row['info']);
- $tmp[$k]['info_text'] = $this->aLogActions[$row['action']]['info_template'];
- foreach ($tmp[$k]['info'] as $n => $v) {
- $tmp[$k]['info_text'] = str_replace('%' . strtoupper($n) . '%', $v, $tmp[$k]['info_text']);
- }
- }
- return $tmp;
- }
- public function checkLog($order_id = false) {
- $tmp = $GLOBALS['dbh']->getRow('
- SELECT ol.action
- FROM t_order_log AS ol
- WHERE ol.order_id = ?
- ORDER BY ol.date_log DESC
- LIMIT 1
- ', array($order_id));
- if ($tmp['action'] == 'confirm-order')
- return true;
- else
- return false;
- }
- public function checkOrder($orderId = 0)
- {
- $orderInfo = $this->get($orderId);
- foreach ($orderInfo['items_unique'] as $typyId => $item) {
- $cntAvailable = $item['cnt_limit'] - $item['cnt_selled'] - $item['cnt_reserved'] -
- $item['cnt_stock'] - $item['cnt_booked'];
- if ($item['is_place'] == 0 && $cntAvailable < $item['amount']) {
- return false;
- }
- }
- return true;
- }
- /**
- * Submit Karabas Order
- *
- * @param array $params contains ID of the order, auth key and karabas event ID
- * @access private
- * @author Chak
- * @return int Order ID on success
- */
- private function _karabasSubmitOrder($params)
- {
- $basket = ginst('Karabas')->getBasket(array(
- 'order_id' => $params['order_id'],
- '__auth' => $params['auth']
- ));
- if (isset($basket->CommandStatus) && !empty($basket->CommandStatus) || !isset($basket->CommandStatus)) {
- return false;
- }
- $externalId = $basket->orderId;
- $isExternalId = $GLOBALS['dbh']->getOne("
- SELECT id
- FROM t_order
- WHERE partner_id = 1 AND external_id = ? ", array($externalId));
- if (isset($isExternalId)) {
- $data = ginst('Karabas')->changeOrder($externalId);
- return false;
- }
- // checking basket for tickets from another event
- if (!empty($basket->items)) {
- foreach ($basket->items as $item) {
- if ($item->event != $params['event_id']) {
- ginst('Karabas')->removeTicket(array(
- '__auth' => $params['auth'],
- 'ticket_id' => $item->id
- ));
- }
- }
- }
- $data = ginst('Karabas')->submitOrder($externalId);
- if (isset($data->CommandStatus) && $data->CommandStatus != 0 || !isset($data->CommandStatus)) {
- return false;
- }
- return $externalId;
- }
- /**
- * Set karabas order to the current status
- * @param int $orderId - order id
- * @param int $status - order status (1 - apply; 3 - delivery)
- * @return boolean true if success
- */
- private function karabasSetOrderStatus($orderId = 0, $status = 1)
- {
- $orderInfo = $this->get($orderId);
- // hardcode::start for Promoter Id 273 Национальный академический Театр Русской Драмы им. Леси Украинки
- $promoterId = $GLOBALS['dbh']->getOne("
- SELECT promoter_id
- FROM t_event
- WHERE id = ? ", array($orderInfo['event_id']));
- // hardcode::end
- $params = array (
- 'order_id' => $orderInfo['external_id'],
- 'format' => ($promoterId == 273 ? 8 : $orderInfo['items'][0]['format_id']),
- 'payment_type' => $orderInfo['payment_type']
- );
- if ($status == 1) {
- $statusOrder = ginst('Karabas')->confirmOrder($params);
- } else {
- $deliveryPeriod = ($orderInfo['city_id'] != 10184 ? $orderInfo['addr']['period'] + 5 : 4);
- $deliveryDate = $params['delivery_date'] = date('d.m.Y H:i', strtotime($orderInfo['date_created']) + 60 * 60 * 24 * $deliveryPeriod);
- $statusOrder = ginst('Karabas')->deliveryOrder($params);
- }
- if (!empty($statusOrder->status) && $statusOrder->status == $status) {
- if (!empty($statusOrder->tickets)) {
- foreach ($statusOrder->tickets as $ticket) {
- if (!empty($ticket->Barcode)) {
- $GLOBALS['dbh']->query("UPDATE t_ticket SET bar_code = '{$ticket->Barcode}', bar_code_type = 'code128' WHERE order_id = '{$orderInfo['id']}' AND external_id = '{$ticket->id}' ");
- }
- }
- }
- if ($statusOrder->status == 3) {
- $GLOBALS['dbh']->query("UPDATE `t_order` SET `delivery_expired` = STR_TO_DATE('{$deliveryDate}','%d.%m.%Y %H:%i') WHERE `id` = {$orderInfo['id']}");
- }
- } else {
- return false;
- }
- return true;
- }
- /**
- * Method return all orders in offline
- *
- * @access public
- * @author Yuriy Stefanyuk
- * @param int $eventId
- * @return array
- */
- public function getOfflineOrders($eventId = false)
- {
- if (!$eventId) return;
- $tmp = $GLOBALS['dbh']->getAll("
- SELECT id, lastname, firstname, city_name, email, mobile, price_total, secret_code,
- CASE partner_id
- WHEN 1 THEN 'Karabas'
- WHEN 10 THEN 'Premiera'
- WHEN 11 THEN 'Internet bilet'
- END AS partner_name,
- external_id
- FROM " . $this->table_name . "
- WHERE event_id = ? AND paid_status = 4
- ", array($eventId)
- );
- return $tmp;
- }
- /**
- * Method canceling all offline orders
- *
- * @access public
- * @author Yuriy Stefanyuk
- * @param int $eventId
- * @return void
- */
- public function cancelingOfflineOrders($eventId = false)
- {
- if (!$eventId) return;
- $mobiles = array();
- $event = ginst('Event')->getNotTerminatedEvents($eventId, 1);
- $offlineOrders = ginst('Order')->getOfflineOrders($event['id']);
- if (!$offlineOrders) return;
- foreach ($offlineOrders as $order) {
- ginst('Order')->addLog(array(
- 'order_id' => $order['id'],
- 'action' => 'stop-selling',
- 'info' => array(
- 'status' => 'Остановка продаж'
- ),
- ));
- if ($order['external_id'] > 0) {
- ginst('Karabas')->cancelOrder($order['external_id'], 'stop selling');
- $GLOBALS['dbh']->autoExecute('t_order', array(
- 'paid_status' => 6,
- 'cancelled_reason' => 'Продажа остановлена',
- ), DB_AUTOQUERY_UPDATE, 'id = '.$order['id']);
- $GLOBALS['dbh']->autoExecute('t_ticket', array(
- 'is_canceled' => 1,
- ), DB_AUTOQUERY_UPDATE, 'order_id = '.$order['id']);
- } else {
- $GLOBALS['dbh']->autoExecute('t_order', array(
- 'paid_status' => 6,
- 'cancelled_reason' => 'Продажа остановлена',
- ), DB_AUTOQUERY_UPDATE, 'id = '.$order['id']);
- $GLOBALS['dbh']->autoExecute('t_ticket', array(
- 'is_canceled' => 1,
- ), DB_AUTOQUERY_UPDATE, 'order_id = '.$order['id']);
- $tickets = $GLOBALS['dbh']->getCol("SELECT type_place_id FROM t_ticket WHERE order_id = " . $order['id'] . " AND type_place_id IS NOT NULL");
- $placesId = implode(",",$tickets);
- if (!empty($placesId)) {
- $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
- 'is_reserved' => 0,
- 'date_cancelling' => 'NULL',
- ), DB_AUTOQUERY_UPDATE, ' id IN ('.$placesId.') AND is_sold = 0 AND is_booking = 0');
- }
- }
- }
- }
- /**
- * Method return all orders in courier delivery
- *
- * @access public
- * @author Yuriy Stefanyuk
- * @param int $eventId
- * @return array
- */
- public function getCourierOrders($eventId = false)
- {
- if (!$eventId) return;
- $tmp = $GLOBALS['dbh']->getAll("
- SELECT DISTINCT
- `o`.`id`, `o`.`lastname`, `o`.`firstname`, `o`.`email`, `o`.`mobile`, `o`.`price_total`, `o`.`external_id`, LOWER(`o`.`billing_currency`) AS `billing_currency`,
- `ec`.`title`, `d`.`newpost_order_id` AS `np_order_id`, `nw`.address, `d`.`id` AS `delivery_id`,
- `cn`.`name` AS `country`, `c`.`name` AS `city`, `r`.`name` AS `province`,
- `a`.`street`, `a`.`house`, `a`.`flat`, `a`.`zip`, `a`.`ware_id`
- FROM
- `t_order` AS `o`
- INNER JOIN `t_event_content` AS `ec` ON `ec`.`id` = `o`.`event_id` AND `ec`.`language_id` = ?
- INNER JOIN `t_ticket` AS `t` ON `t`.`order_id` = `o`.`id`
- INNER JOIN `t_delivery` AS `d` ON `d`.`order_id` = `o`.`id`
- INNER JOIN `t_address` AS `a` ON `d`.`address_to` = `a`.`id`
- INNER JOIN `city` AS `c` ON `c`.`city_id` = `a`.`city`
- INNER JOIN `country` AS `cn` ON `cn`.`country_id` = `a`.`country`
- INNER JOIN `region` AS `r` ON `r`.`region_id` = `a`.`province`
- LEFT JOIN `t_newpost_warenhouse` AS `nw` ON `nw`.`ware_id` = `a`.`ware_id`
- WHERE
- `o`.`event_id` = ? AND `o`.`paid_status` = 8
- ORDER BY `o`.`date_created` DESC"
- , array($GLOBALS['lng']['id'],$eventId)
- );
- return $tmp;
- }
- public function ibConfirmOrder($params = array(), $str = ''){
- $confirmOrder = ginst('InternetBilet')->bookingConfirm($params['ext_id']);
- if(!$confirmOrder){
- return false;
- }
- if (!empty($confirmOrder->places)) {
- foreach($confirmOrder->places as $place){
- $GLOBALS['dbh']->autoExecute("t_ticket", array('bar_code' => $place->barcode, 'bar_code_type'=>'code128'), DB_AUTOQUERY_UPDATE, "order_id = '{$params['order_id']}' AND external_id = '{$place->ticket_id}'");
- }
- }
- return true;
- }
- private function _flashBoxConfirmOrder($orderId)
- {
- $order = $this->get($orderId);
- $tickets = ginst('FlashBox')->payTicket($order['external_id']);
- if (empty($tickets)) {
- //cancel order
- return false;
- }
- foreach ($order['items'] as $item) {
- foreach ($tickets->purchase_tickets as $ticket) {
- if ($ticket->ticket_id == $item['external_id'] && $ticket->purchase_status == 'ok') {
- $GLOBALS['dbh']->autoExecute("t_ticket", array(
- 'bar_code' => $ticket->baracode,
- 'bar_code_type' => 'code128'
- ), DB_AUTOQUERY_UPDATE, "order_id = '{$orderId}' AND external_id = '{$ticket->ticket_id}'");
- if (empty($item['type_place_id'])) {
- $GLOBALS['dbh']->autoExecute("t_ticket_type_seat", array(
- 'is_used' => 1,
- 'date_used' => NOW,
- 'ticket_id' => $item['id']
- ), DB_AUTOQUERY_UPDATE, "external_id = '{$ticket->ticket_id}' AND type_id = '{$item['type_id']}'");
- }
- break;
- }
- }
- }
- return true;
- }
- private function _flashBoxCancelOrder($orderId)
- {
- $order = $this->get($orderId);
- foreach ($order['items'] as $item) {
- $ticket = ginst('FlashBox')->removeTicket(array(
- 'ticket_id' => $item['external_id'],
- 'barcode' => $item['bar_code']
- ));
- if (empty($ticket)) {
- return false;
- }
- if (empty($item['type_place_id'])) {
- $GLOBALS['dbh']->autoExecute("t_ticket_type_seat", array(
- 'is_used' => 0
- ), DB_AUTOQUERY_UPDATE, "external_id = '{$ticket->ticket_id}' AND type_id = '{$item['type_id']}' AND ticket_id = '{$item['id']}'");
- }
- }
- return true;
- }
- /**
- * Check place for status on FlashBox system
- * @param int $placeId place ID on the scheme
- * @author Chak
- * @return int ticket id on success
- */
- private function _flashBoxCheckPlace($placeId = 0)
- {
- $id = $GLOBALS['dbh']->getOne("SELECT external_id FROM t_ticket_type_place WHERE id = ? ", array($placeId));
- $status = ginst('FlashBox')->getTicketStatus($id);
- if (empty($status) || $status->ticket_status != 'available') {
- if ($status->ticket_status == 'sold') {
- $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
- 'is_sold' => 1
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $placeId);
- } elseif ($status->ticket_status == 'booked') {
- $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
- 'is_reserved' => 1,
- 'date_cancelling' => null
- ), DB_AUTOQUERY_UPDATE, ' id = ' . $placeId);
- }
- return false;
- }
- return $status->ticket_id;
- }
- /**
- * Method updates all reserved order where date cancelling reservation < now
- *
- * @access public
- * @author Yuriy Stefanyuk
- * @param int $eventId
- * @return void
- */
- public function updateReservedOrders($eventId = null)
- {
- if (!$eventId) return;
- $orders = $GLOBALS['dbh']->getAll("SELECT * FROM t_order WHERE reserv_cancelling < NOW() AND paid_status = 10 AND event_id = ? ", array($eventId));
- if (!$orders) return;
- foreach ($orders as $order) {
- $this->cancel($order, 'Время для выкупа резервации закончилось', ORDER_STATUS_TIMEOUT);
- }
- }
- /**
- * Повертає всі продажі продавців церез сейл
- *
- * @global object $dbh
- * @global object $aUser
- * @param array $clause
- * @return array
- */
- public function getSaleOrders($clause)
- {
- global $dbh, $aUser;
- $sLimit = $clause['limit'];
- $sWhere = '';
- if (!$aUser['is_admin']) {
- $sWhere = " AND o.client_id = {$aUser['id']}";
- }
- if(!empty($clause['where'])) {
- $sWhere .= $clause['where'];
- }
- $ordersIds = $dbh->getCol("
- SELECT SQL_CALC_FOUND_ROWS
- o.id
- FROM t_order AS o
- INNER JOIN t_event AS e ON e.id = o.event_id
- INNER JOIN t_event_content AS ec ON (ec.id, ec.language_id) = ROW(e.id, 1)
- INNER JOIN t_venue_content AS vc ON (vc.id, vc.language_id) = ROW(e.venue_id, 1)
- WHERE o.payment_type = 'offline' {$sWhere}
- ORDER BY o.id DESC LIMIT {$sLimit}
- ");
- $totalOrders = $dbh->getOne('SELECT FOUND_ROWS()');
- if (empty($ordersIds)) {
- $ordersIds[] = 0;
- }
- $ordersInfo = $dbh->getAssoc("
- SELECT
- o.id, COUNT(t.id) AS ticket_cnt, o.firstname as client_firstname, o.lastname as client_lastname, o.price_total, o.mobile, o.email, o.paid_status,
- DATE_FORMAT(e.date_event, '%d.%m.%Y / %H:%i') AS date_event, ec.title AS event_title,
- vc.title AS venue_title, pc.title AS promoter_title,
- u.firstname, u.lastname, DATE_FORMAT(o.date_confirmed, '%d.%m.%Y %H:%i') as date_confirmed
- FROM t_order AS o
- LEFT JOIN t_ticket AS t ON t.order_id = o.id
- LEFT JOIN t_event AS e ON e.id = o.event_id
- LEFT JOIN t_event_content AS ec ON (ec.id, ec.language_id) = ROW(e.id, 1)
- LEFT JOIN t_venue AS v ON v.id = e.venue_id
- LEFT JOIN t_venue_content AS vc ON (vc.id, vc.language_id) = ROW(e.venue_id, 1)
- LEFT JOIN t_promoter AS p ON p.id = e.promoter_id
- LEFT JOIN t_promoter_content AS pc ON (pc.id, pc.language_id) = ROW(e.promoter_id, 1)
- LEFT JOIN t_user AS u ON u.id = o.client_id WHERE o.id IN (!) GROUP BY o.id ORDER BY o.id DESC
- ", 0, array(implode(', ', $ordersIds)));
- foreach ($ordersInfo as $orderId => $order) {
- $ordersInfo[$orderId]['paid_status'] = $this->paidStatuses[$order['paid_status']]['title'];
- }
- return array(
- 'orders' => $ordersInfo,
- 'totals' => $totalOrders
- );
- }
- /**
- * Assign special certificate for each ticket in the order
- * @param array $params input params
- * @return array certicate datas
- */
- public function checkCertificate($params = array())
- {
- $result = array();
- if (empty($params['event']['certificate_id'])) {
- return $result;
- }
- foreach ($params['event']['ticketTypes_all'] as $type) {
- if ($type['certificate_id'] == $params['event']['certificate_id']) {
- $result = $type;
- break;
- }
- }
- $amount = 0;
- if (!empty($params['items'])) {
- foreach($params['items'] as $item) {
- if ($item['group_id'] == 1) {
- $amount += $item['amount'];
- }
- }
- }
- if (!empty($params['places'])) {
- $amount += count($params['places']);
- }
- $result['amount'] = $amount;
- return $result;
- }
- }
- endif;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement