Перейти до вмісту
Пошук в
  • Детальніше...
Шукати результати, які ...
Шукати результати в ...

перестали приходить письма о заказе


pewpewpew

Recommended Posts

Братцы такая проблема не приходят письма с сайта, вот ошибка: Может кто знает в чем дело...?

PHP Notice: Undefined index: email in /home/u137250325/public_html/catalog/view/theme/9responsive_red/template/module/fastorder.tpl on line 19

Надіслати
Поділитися на інших сайтах


Подскажите, кто знает, у меня тоже перестали приходить письма именно о заказе! о регистрации мне и покупателю приходят, а заказ - глухо, хостер говорит что с их стороны все ок....

Надіслати
Поділитися на інших сайтах


  • 2 years later...

Возникла проблема - перестали приходить письма о заказе.

В order.php встроена отправка в 1С, но давно и исправно работает. Она же отправляет письма и данные в таблицу "to_1c"

Сейчас заказы формируются, в админку попадают, но не отправляются пользователю на почту и не обрабатываются 1С

Листинг файла order.php в модели:

<?php
class ModelCheckoutOrder extends Model {	
	public function addOrder($data) {
        if($data['shipping_code'] == 'pickup_point.pickup_point') {
            $pickup_point_sql = "pickup_point = '" . (int)$data['shop_id'] . "', ";
        } else {
            $pickup_point_sql = '';
        }

		$this->db->query("INSERT INTO `" . DB_PREFIX . "order` SET invoice_prefix = '" . $this->db->escape($data['invoice_prefix']) . "', store_id = '" . (int)$data['store_id'] . "', store_name = '" . $this->db->escape($data['store_name']) . "', store_url = '" . $this->db->escape($data['store_url']) . "', customer_id = '" . (int)$data['customer_id'] . "', customer_group_id = '" . (int)$data['customer_group_id'] . "', firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', fax = '" . $this->db->escape($data['fax']) . "', payment_firstname = '" . $this->db->escape($data['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($data['payment_lastname']) . "', payment_company = '" . $this->db->escape($data['payment_company']) . "', payment_company_id = '" . $this->db->escape($data['payment_company_id']) . "', payment_tax_id = '" . $this->db->escape($data['payment_tax_id']) . "', payment_address_1 = '" . $this->db->escape($data['payment_address_1']) . "', payment_address_2 = '" . $this->db->escape($data['payment_address_2']) . "', payment_city = '" . $this->db->escape($data['payment_city']) . "', payment_postcode = '" . $this->db->escape($data['payment_postcode']) . "', payment_country = '" . $this->db->escape($data['payment_country']) . "', payment_country_id = '" . (int)$data['payment_country_id'] . "', payment_zone = '" . $this->db->escape($data['payment_zone']) . "', payment_zone_id = '" . (int)$data['payment_zone_id'] . "', payment_address_format = '" . $this->db->escape($data['payment_address_format']) . "', payment_method = '" . $this->db->escape($data['payment_method']) . "', payment_code = '" . $this->db->escape($data['payment_code']) . "', shipping_firstname = '" . $this->db->escape($data['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($data['shipping_lastname']) . "', shipping_company = '" . $this->db->escape($data['shipping_company']) . "', shipping_address_1 = '" . $this->db->escape($data['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($data['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($data['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($data['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($data['shipping_country']) . "', shipping_country_id = '" . (int)$data['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($data['shipping_zone']) . "', shipping_zone_id = '" . (int)$data['shipping_zone_id'] . "', shipping_address_format = '" . $this->db->escape($data['shipping_address_format']) . "', shipping_method = '" . $this->db->escape($data['shipping_method']) . "', shipping_code = '" . $this->db->escape($data['shipping_code']) . "', ". $pickup_point_sql ." comment = '" . $this->db->escape($data['comment']) . "', total = '" . (float)$data['total'] . "', affiliate_id = '" . (int)$data['affiliate_id'] . "', commission = '" . (float)$data['commission'] . "', language_id = '" . (int)$data['language_id'] . "', currency_id = '" . (int)$data['currency_id'] . "', currency_code = '" . $this->db->escape($data['currency_code']) . "', currency_value = '" . (float)$data['currency_value'] . "', ip = '" . $this->db->escape($data['ip']) . "', forwarded_ip = '" .  $this->db->escape($data['forwarded_ip']) . "', user_agent = '" . $this->db->escape($data['user_agent']) . "', accept_language = '" . $this->db->escape($data['accept_language']) . "', date_added = NOW(), date_modified = NOW()");

		$order_id = $this->db->getLastId();

		foreach ($data['products'] as $product) { 
			$this->db->query("INSERT INTO " . DB_PREFIX . "order_product SET order_id = '" . (int)$order_id . "', product_id = '" . (int)$product['product_id'] . "', name = '" . $this->db->escape($product['name']) . "', model = '" . $this->db->escape($product['model']) . "', quantity = '" . (int)$product['quantity'] . "', price = '" . (float)$product['price'] . "', total = '" . (float)$product['total'] . "', tax = '" . (float)$product['tax'] . "', reward = '" . (int)$product['reward'] . "'");
 
			$order_product_id = $this->db->getLastId();

            $parent_option_value_id = 0;
            foreach($product['option'] as $option) {
                if($option['name'] == 'Размер') {
                    $parent_option_value_id = $option['option_value_id'];
                }
            }

			foreach ($product['option'] as $option) {
				$this->db->query("
				INSERT INTO " . DB_PREFIX . "order_option SET
				order_id = '" . (int)$order_id . "',
				order_product_id = '" . (int)$order_product_id . "',
				product_option_id = '" . (int)$option['product_option_id'] . "',
				product_option_value_id = '" . (int)$option['product_option_value_id'] . "',
				`option_value_id` = '" . (int)$parent_option_value_id . "',
				`name` = '" . $this->db->escape($option['name']) . "',
				`value` = '" . $this->db->escape($option['value']) . "',
				`type` = '" . $this->db->escape($option['type']) . "'");
			}
				
			foreach ($product['download'] as $download) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "order_download SET order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', name = '" . $this->db->escape($download['name']) . "', filename = '" . $this->db->escape($download['filename']) . "', mask = '" . $this->db->escape($download['mask']) . "', remaining = '" . (int)($download['remaining'] * $product['quantity']) . "'");
			}	
		}
		
		foreach ($data['vouchers'] as $voucher) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "order_voucher SET order_id = '" . (int)$order_id . "', description = '" . $this->db->escape($voucher['description']) . "', code = '" . $this->db->escape($voucher['code']) . "', from_name = '" . $this->db->escape($voucher['from_name']) . "', from_email = '" . $this->db->escape($voucher['from_email']) . "', to_name = '" . $this->db->escape($voucher['to_name']) . "', to_email = '" . $this->db->escape($voucher['to_email']) . "', voucher_theme_id = '" . (int)$voucher['voucher_theme_id'] . "', message = '" . $this->db->escape($voucher['message']) . "', amount = '" . (float)$voucher['amount'] . "'");
		}
			
		foreach ($data['totals'] as $total) {
            if(!isset($total['certification_pin'])) {
                $total['certification_pin'] = NULL;
            }

			$this->db->query("INSERT INTO " . DB_PREFIX . "order_total SET order_id = '" . (int)$order_id . "', code = '" . $this->db->escape($total['code']) . "', title = '" . $this->db->escape($total['title']) . "', text = '" . $this->db->escape($total['text']) . "', `value` = '" . (float)$total['value'] . "', `certification_pin` = '" . (int)$total['certification_pin'] . "', sort_order = '" . (int)$total['sort_order'] . "'");
		}	

		return $order_id;
	}

	public function getOrder($order_id) {
		$order_query = $this->db->query("SELECT *, (SELECT os.name FROM `" . DB_PREFIX . "order_status` os WHERE os.order_status_id = o.order_status_id AND os.language_id = o.language_id) AS order_status FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int)$order_id . "'");
			
		if ($order_query->num_rows) {
			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['payment_country_id'] . "'");
			
			if ($country_query->num_rows) {
				$payment_iso_code_2 = $country_query->row['iso_code_2'];
				$payment_iso_code_3 = $country_query->row['iso_code_3'];
			} else {
				$payment_iso_code_2 = '';
				$payment_iso_code_3 = '';				
			}
			
			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['payment_zone_id'] . "'");
			
			if ($zone_query->num_rows) {
				$payment_zone_code = $zone_query->row['code'];
			} else {
				$payment_zone_code = '';
			}			
			
			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['shipping_country_id'] . "'");
			
			if ($country_query->num_rows) {
				$shipping_iso_code_2 = $country_query->row['iso_code_2'];
				$shipping_iso_code_3 = $country_query->row['iso_code_3'];
			} else {
				$shipping_iso_code_2 = '';
				$shipping_iso_code_3 = '';				
			}
			
			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['shipping_zone_id'] . "'");
			
			if ($zone_query->num_rows) {
				$shipping_zone_code = $zone_query->row['code'];
			} else {
				$shipping_zone_code = '';
			}
			
			$this->load->model('localisation/language');
			
			$language_info = $this->model_localisation_language->getLanguage($order_query->row['language_id']);
			
			if ($language_info) {
				$language_code = $language_info['code'];
				$language_filename = $language_info['filename'];
				$language_directory = $language_info['directory'];
			} else {
				$language_code = '';
				$language_filename = '';
				$language_directory = '';
			}
		 			
			return array(
				'order_id'                => $order_query->row['order_id'],
				'invoice_no'              => $order_query->row['invoice_no'],
				'invoice_prefix'          => $order_query->row['invoice_prefix'],
				'store_id'                => $order_query->row['store_id'],
				'store_name'              => $order_query->row['store_name'],
				'store_url'               => $order_query->row['store_url'],				
				'customer_id'             => $order_query->row['customer_id'],
				'firstname'               => $order_query->row['firstname'],
				'lastname'                => $order_query->row['lastname'],
				'telephone'               => $order_query->row['telephone'],
				'fax'                     => $order_query->row['fax'],
				'email'                   => $order_query->row['email'],
				'payment_firstname'       => $order_query->row['payment_firstname'],
				'payment_lastname'        => $order_query->row['payment_lastname'],				
				'payment_company'         => $order_query->row['payment_company'],
				'payment_company_id'      => $order_query->row['payment_company_id'],
				'payment_tax_id'          => $order_query->row['payment_tax_id'],
				'payment_address_1'       => $order_query->row['payment_address_1'],
				'payment_address_2'       => $order_query->row['payment_address_2'],
				'payment_postcode'        => $order_query->row['payment_postcode'],
				'payment_city'            => $order_query->row['payment_city'],
				'payment_zone_id'         => $order_query->row['payment_zone_id'],
				'payment_zone'            => $order_query->row['payment_zone'],
				'payment_zone_code'       => $payment_zone_code,
				'payment_country_id'      => $order_query->row['payment_country_id'],
				'payment_country'         => $order_query->row['payment_country'],	
				'payment_iso_code_2'      => $payment_iso_code_2,
				'payment_iso_code_3'      => $payment_iso_code_3,
				'payment_address_format'  => $order_query->row['payment_address_format'],
				'payment_method'          => $order_query->row['payment_method'],
				'payment_code'            => $order_query->row['payment_code'],
				'shipping_firstname'      => $order_query->row['shipping_firstname'],
				'shipping_lastname'       => $order_query->row['shipping_lastname'],				
				'shipping_company'        => $order_query->row['shipping_company'],
				'shipping_address_1'      => $order_query->row['shipping_address_1'],
				'shipping_address_2'      => $order_query->row['shipping_address_2'],
				'shipping_postcode'       => $order_query->row['shipping_postcode'],
				'shipping_city'           => $order_query->row['shipping_city'],
				'shipping_zone_id'        => $order_query->row['shipping_zone_id'],
				'shipping_zone'           => $order_query->row['shipping_zone'],
				'shipping_zone_code'      => $shipping_zone_code,
				'shipping_country_id'     => $order_query->row['shipping_country_id'],
				'shipping_country'        => $order_query->row['shipping_country'],	
				'shipping_iso_code_2'     => $shipping_iso_code_2,
				'shipping_iso_code_3'     => $shipping_iso_code_3,
				'shipping_address_format' => $order_query->row['shipping_address_format'],
				'shipping_method'         => $order_query->row['shipping_method'],
				'shipping_code'           => $order_query->row['shipping_code'],
                'pickup_point'            => $order_query->row['pickup_point'],
				'comment'                 => $order_query->row['comment'],
				'total'                   => $order_query->row['total'],
				'order_status_id'         => $order_query->row['order_status_id'],
				'order_status'            => $order_query->row['order_status'],
				'language_id'             => $order_query->row['language_id'],
				'language_code'           => $language_code,
				'language_filename'       => $language_filename,
				'language_directory'      => $language_directory,
				'currency_id'             => $order_query->row['currency_id'],
				'currency_code'           => $order_query->row['currency_code'],
				'currency_value'          => $order_query->row['currency_value'],
				'ip'                      => $order_query->row['ip'],
				'forwarded_ip'            => $order_query->row['forwarded_ip'], 
				'user_agent'              => $order_query->row['user_agent'],	
				'accept_language'         => $order_query->row['accept_language'],				
				'date_modified'           => $order_query->row['date_modified'],
				'date_added'              => $order_query->row['date_added']
			);
		} else {
			return false;	
		}
    }

	public function confirm($order_id, $order_status_id, $comment = '', $notify = false) {
		$order_info = $this->getOrder($order_id);
		 
		if ($order_info && !$order_info['order_status_id']) {
			// Fraud Detection
			if ($this->config->get('config_fraud_detection')) {
				$this->load->model('checkout/fraud');
				
				$risk_score = $this->model_checkout_fraud->getFraudScore($order_info);
				
				if ($risk_score > $this->config->get('config_fraud_score')) {
					$order_status_id = $this->config->get('config_fraud_status_id');
				}
			}

			// Ban IP
			$status = false;
			
			$this->load->model('account/customer');
			
			if ($order_info['customer_id']) {
				$results = $this->model_account_customer->getIps($order_info['customer_id']);
				
				foreach ($results as $result) {
					if ($this->model_account_customer->isBanIp($result['ip'])) {
						$status = true;
						
						break;
					}
				}
			} else {
				$status = $this->model_account_customer->isBanIp($order_info['ip']);
			}
			
			if ($status) {
				$order_status_id = $this->config->get('config_order_status_id');
			}		
				
			$this->db->query("UPDATE `" . DB_PREFIX . "order` SET order_status_id = '" . (int)$order_status_id . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'");

			$this->db->query("INSERT INTO " . DB_PREFIX . "order_history SET order_id = '" . (int)$order_id . "', order_status_id = '" . (int)$order_status_id . "', notify = '1', comment = '" . $this->db->escape(($comment && $notify) ? $comment : '') . "', date_added = NOW()");

			$order_product_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");


            foreach ($order_product_query->rows as $order_product) {
                $stock = 0;

                $this->db->query("UPDATE " . DB_PREFIX . "product SET quantity = (quantity - " . (int)$order_product['quantity'] . ") WHERE product_id = '" . (int)$order_product['product_id'] . "' AND subtract = '1'");
				
				$order_option_query = $this->db->query("
				SELECT * FROM " . DB_PREFIX . "order_option
				WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$order_product['order_product_id'] . "'");

                $option_array = array();

				foreach ($order_option_query->rows as $option) {
					$this->db->query("UPDATE " . DB_PREFIX . "product_option_value SET quantity = (quantity - " . (int)$order_product['quantity'] . ") WHERE product_option_value_id = '" . (int)$option['product_option_value_id'] . "' AND subtract = '1'");
                    if($option['name'] == 'Цвет') {
                        $this->db->query("UPDATE `" . DB_PREFIX . "product_option_value_to_option_value` SET `quantity` = (quantity - " . (int)$order_product['quantity'] . ") WHERE `product_option_value_id` = '" . (int)$option['product_option_value_id'] . "' AND `product_option_id` = '" . (int)$option['product_option_id'] . "' AND `option_value_id` = '" . $option['option_value_id'] . "' AND `product_id` = '" . $order_product['product_id'] . "'");
                    }
                }

                $quantity = 0;
                $stocks = $this->db->query("SELECT `quantity` FROM `" . DB_PREFIX . "product_option_value_to_option_value` WHERE `product_id` = '" . $order_product['product_id'] . "'");
                foreach($stocks->rows as $stock)
                {
                    $quantity += (int)$stock['quantity'];
                }

                if($quantity == 0) {
                    $this->db->query("UPDATE `" . DB_PREFIX . "product` SET `status` = 0 WHERE `product_id` = '" . (int)$order_product['product_id'] . "' AND `offline_shop` = '0'");
                }
            }


            $this->cache->delete('product');
			
			// Downloads
			$order_download_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_download WHERE order_id = '" . (int)$order_id . "'");
			
			// Gift Voucher
			$this->load->model('checkout/voucher');
			
			$order_voucher_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_voucher WHERE order_id = '" . (int)$order_id . "'");
			
			foreach ($order_voucher_query->rows as $order_voucher) {
				$voucher_id = $this->model_checkout_voucher->addVoucher($order_id, $order_voucher);
				
				$this->db->query("UPDATE " . DB_PREFIX . "order_voucher SET voucher_id = '" . (int)$voucher_id . "' WHERE order_voucher_id = '" . (int)$order_voucher['order_voucher_id'] . "'");
			}			
			
			// Send out any gift voucher mails
			if ($this->config->get('config_complete_status_id') == $order_status_id) {
				$this->model_checkout_voucher->confirm($order_id);
			}
					
			// Order Totals			
			$order_total_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_total` WHERE order_id = '" . (int)$order_id . "' ORDER BY sort_order ASC");
			
			foreach ($order_total_query->rows as $order_total) {
				$this->load->model('total/' . $order_total['code']);
				
				if (method_exists($this->{'model_total_' . $order_total['code']}, 'confirm')) {
					$this->{'model_total_' . $order_total['code']}->confirm($order_info, $order_total);
				}
			}
			
			// Send out order confirmation mail
			$language = new Language($order_info['language_directory']);
			$language->load($order_info['language_filename']);
			$language->load('mail/order');
		 
			$order_status_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_status WHERE order_status_id = '" . (int)$order_status_id . "' AND language_id = '" . (int)$order_info['language_id'] . "'");
			
			if ($order_status_query->num_rows) {
				$order_status = $order_status_query->row['name'];	
			} else {
				$order_status = '';
			}
			
			$subject = sprintf($language->get('text_new_subject'), $order_info['store_name'], $order_id);
		
			// HTML Mail
			$template = new Template();
			
			$template->data['title'] = sprintf($language->get('text_new_subject'), html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'), $order_id);
			
			$template->data['text_greeting'] = sprintf($language->get('text_new_greeting'), html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'));
			$template->data['text_link'] = $language->get('text_new_link');
			$template->data['text_download'] = $language->get('text_new_download');
			$template->data['text_order_detail'] = $language->get('text_new_order_detail');
			$template->data['text_instruction'] = $language->get('text_new_instruction');
			$template->data['text_order_id'] = $language->get('text_new_order_id');
			$template->data['text_date_added'] = $language->get('text_new_date_added');
			$template->data['text_payment_method'] = $language->get('text_new_payment_method');	
			$template->data['text_shipping_method'] = $language->get('text_new_shipping_method');
			$template->data['text_email'] = $language->get('text_new_email');
			$template->data['text_telephone'] = $language->get('text_new_telephone');
			$template->data['text_ip'] = $language->get('text_new_ip');
			$template->data['text_payment_address'] = $language->get('text_new_payment_address');
			$template->data['text_shipping_address'] = $language->get('text_new_shipping_address');
			$template->data['text_product'] = $language->get('text_new_product');
			$template->data['text_model'] = $language->get('text_new_model');
			$template->data['text_quantity'] = $language->get('text_new_quantity');
			$template->data['text_price'] = $language->get('text_new_price');
			$template->data['text_total'] = $language->get('text_new_total');
			$template->data['text_footer'] = $language->get('text_new_footer');
			$template->data['text_powered'] = $language->get('text_new_powered');
			
			$template->data['logo'] = $this->config->get('config_url') . 'image/' . $this->config->get('config_logo');		
			$template->data['store_name'] = $order_info['store_name'];
			$template->data['store_url'] = $order_info['store_url'];
			$template->data['customer_id'] = $order_info['customer_id'];
			$template->data['link'] = $order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_id;
			
			if ($order_download_query->num_rows) {
				$template->data['download'] = $order_info['store_url'] . 'index.php?route=account/download';
			} else {
				$template->data['download'] = '';
			}
			
			$template->data['order_id'] = $order_id;
			$template->data['date_added'] = date($language->get('date_format_short'), strtotime($order_info['date_added']));    	
			$template->data['payment_method'] = $order_info['payment_method'];
			$template->data['shipping_method'] = $order_info['shipping_method'];
			$template->data['email'] = $order_info['email'];
			$template->data['telephone'] = $order_info['telephone'];
			$template->data['ip'] = $order_info['ip'];
			
			if ($comment && $notify) {
				$template->data['comment'] = nl2br($comment);
			} else {
				$template->data['comment'] = '';
			}
						
			if ($order_info['payment_address_format']) {
				$format = $order_info['payment_address_format'];
			} else {
				$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}
			
			$find = array(
				'{firstname}',
				'{lastname}',
				'{company}',
				'{address_1}',
				'{address_2}',
				'{city}',
				'{postcode}',
				'{zone}',
				'{zone_code}',
				'{country}'
			);
		
			$replace = array(
				'firstname' => $order_info['payment_firstname'],
				'lastname'  => $order_info['payment_lastname'],
				'company'   => $order_info['payment_company'],
				'address_1' => $order_info['payment_address_1'],
				'address_2' => $order_info['payment_address_2'],
				'city'      => $order_info['payment_city'],
				'postcode'  => $order_info['payment_postcode'],
				'zone'      => $order_info['payment_zone'],
				'zone_code' => $order_info['payment_zone_code'],
				'country'   => $order_info['payment_country']  
			);
		
			$template->data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));						
									
			if ($order_info['shipping_address_format']) {
				$format = $order_info['shipping_address_format'];
			} else {
				$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}
			
			$find = array(
				'{firstname}',
				'{lastname}',
				'{company}',
				'{address_1}',
				'{address_2}',
				'{city}',
				'{postcode}',
				'{zone}',
				'{zone_code}',
				'{country}'
			);
		
			$replace = array(
				'firstname' => $order_info['shipping_firstname'],
				'lastname'  => $order_info['shipping_lastname'],
				'company'   => $order_info['shipping_company'],
				'address_1' => $order_info['shipping_address_1'],
				'address_2' => $order_info['shipping_address_2'],
				'city'      => $order_info['shipping_city'],
				'postcode'  => $order_info['shipping_postcode'],
				'zone'      => $order_info['shipping_zone'],
				'zone_code' => $order_info['shipping_zone_code'],
				'country'   => $order_info['shipping_country']  
			);
		
			$template->data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
			
			// Products
			$template->data['products'] = array();
				
			foreach ($order_product_query->rows as $product) {
				$option_data = array();
				
				$order_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$product['order_product_id'] . "'");
				
				foreach ($order_option_query->rows as $option) {
					if ($option['type'] != 'file') {
						$value = $option['value'];
					} else {
						$value = utf8_substr($option['value'], 0, utf8_strrpos($option['value'], '.'));
					}
					
					$option_data[] = array(
						'name'  => $option['name'],
						'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
					);					
				}
			  
				$template->data['products'][] = array(
					'name'     => $product['name'],
					'model'    => $product['model'],
					'option'   => $option_data,
					'quantity' => $product['quantity'],
					'price'    => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
					'total'    => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value'])
				);
			}
	
			// Vouchers
			$template->data['vouchers'] = array();
			
			foreach ($order_voucher_query->rows as $voucher) {
				$template->data['vouchers'][] = array(
					'description' => $voucher['description'],
					'amount'      => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']),
				);
			}
	
			$template->data['totals'] = $order_total_query->rows;
			
			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/mail/order.tpl')) {
				$html = $template->fetch($this->config->get('config_template') . '/template/mail/order.tpl');
			} else {
				$html = $template->fetch('default/template/mail/order.tpl');
			}
			
			// Text Mail
			$text  = sprintf($language->get('text_new_greeting'), html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8')) . "\n\n";
			$text .= $language->get('text_new_order_id') . ' ' . $order_id . "\n";
			$text .= $language->get('text_new_date_added') . ' ' . date($language->get('date_format_short'), strtotime($order_info['date_added'])) . "\n";
			$text .= $language->get('text_new_order_status') . ' ' . $order_status . "\n\n";
			
			if ($comment && $notify) {
				$text .= $language->get('text_new_instruction') . "\n\n";
				$text .= $comment . "\n\n";
			}
			
			// Products
			$text .= $language->get('text_new_products') . "\n";
			
			foreach ($order_product_query->rows as $product) {
				$text .= $product['quantity'] . 'x ' . $product['name'] . ' (' . $product['model'] . ') ' . html_entity_decode($this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value']), ENT_NOQUOTES, 'UTF-8') . "\n";
				
				$order_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . $product['order_product_id'] . "'");
				
				foreach ($order_option_query->rows as $option) {
					$text .= chr(9) . '-' . $option['name'] . ' ' . (utf8_strlen($option['value']) > 20 ? utf8_substr($option['value'], 0, 20) . '..' : $option['value']) . "\n";
				}
			}
			
			foreach ($order_voucher_query->rows as $voucher) {
				$text .= '1x ' . $voucher['description'] . ' ' . $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']);
			}
						
			$text .= "\n";
			
			$text .= $language->get('text_new_order_total') . "\n";
			
			foreach ($order_total_query->rows as $total) {
				$text .= $total['title'] . ': ' . html_entity_decode($total['text'], ENT_NOQUOTES, 'UTF-8') . "\n";
			}			
			
			$text .= "\n";
			
			if ($order_info['customer_id']) {
				$text .= $language->get('text_new_link') . "\n";
				$text .= $order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_id . "\n\n";
			}
		
			if ($order_download_query->num_rows) {
				$text .= $language->get('text_new_download') . "\n";
				$text .= $order_info['store_url'] . 'index.php?route=account/download' . "\n\n";
			}
			
			// Comment
			if ($order_info['comment']) {
				$text .= $language->get('text_new_comment') . "\n\n";
				$text .= $order_info['comment'] . "\n\n";
			}

			$text .= $language->get('text_new_footer') . "\n\n";
		
			$mail = new Mail(); 
			$mail->protocol = $this->config->get('config_mail_protocol');
			$mail->parameter = $this->config->get('config_mail_parameter');
			$mail->hostname = $this->config->get('config_smtp_host');
			$mail->username = $this->config->get('config_smtp_username');
			$mail->password = $this->config->get('config_smtp_password');
			$mail->port = $this->config->get('config_smtp_port');
			$mail->timeout = $this->config->get('config_smtp_timeout');			
			$mail->setTo($order_info['email']);
			$mail->setFrom($this->config->get('config_email'));
			$mail->setSender($order_info['store_name']);
			$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
			$mail->setHtml($html);
			$mail->setText(html_entity_decode($text, ENT_QUOTES, 'UTF-8'));
			$mail->send();

			// Admin Alert Mail
			if ($this->config->get('config_alert_mail')) {
				$subject = sprintf($language->get('text_new_subject'), html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'), $order_id);
				
				// Text 
				$text  = $language->get('text_new_received') . "\n\n";
				$text .= $language->get('text_new_order_id') . ' ' . $order_id . "\n";
				$text .= $language->get('text_new_date_added') . ' ' . date($language->get('date_format_short'), strtotime($order_info['date_added'])) . "\n";
				$text .= $language->get('text_new_order_status') . ' ' . $order_status . "\n\n";
				$text .= $language->get('text_new_products') . "\n";
				
				foreach ($order_product_query->rows as $product) {
					$text .= $product['quantity'] . 'x ' . $product['name'] . ' (' . $product['model'] . ') ' . html_entity_decode($this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value']), ENT_NOQUOTES, 'UTF-8') . "\n";
					
					$order_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . $product['order_product_id'] . "'");
					
					foreach ($order_option_query->rows as $option) {
						if ($option['type'] != 'file') {
							$value = $option['value'];
						} else {
							$value = utf8_substr($option['value'], 0, utf8_strrpos($option['value'], '.'));
						}
											
						$text .= chr(9) . '-' . $option['name'] . ' ' . (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value) . "\n";
					}
				}
				
				foreach ($order_voucher_query->rows as $voucher) {
					$text .= '1x ' . $voucher['description'] . ' ' . $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']);
				}
							
				$text .= "\n";

				$text .= $language->get('text_new_order_total') . "\n";
				
				foreach ($order_total_query->rows as $total) {
					$text .= $total['title'] . ': ' . html_entity_decode($total['text'], ENT_NOQUOTES, 'UTF-8') . "\n";
				}			
				
				$text .= "\n";
				
				if ($order_info['comment']) {
					$text .= $language->get('text_new_comment') . "\n\n";
					$text .= $order_info['comment'] . "\n\n";
				}
			
				$mail = new Mail(); 
				$mail->protocol = $this->config->get('config_mail_protocol');
				$mail->parameter = $this->config->get('config_mail_parameter');
				$mail->hostname = $this->config->get('config_smtp_host');
				$mail->username = $this->config->get('config_smtp_username');
				$mail->password = $this->config->get('config_smtp_password');
				$mail->port = $this->config->get('config_smtp_port');
				$mail->timeout = $this->config->get('config_smtp_timeout');
				$mail->setTo($this->config->get('config_email'));
				$mail->setFrom($this->config->get('config_email'));
				$mail->setSender($order_info['store_name']);
				$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
				$mail->setText(html_entity_decode($text, ENT_QUOTES, 'UTF-8'));
				$mail->send();
				
				// Send to additional alert emails
				$emails = explode(',', $this->config->get('config_alert_emails'));
				
				foreach ($emails as $email) {
					if ($email && preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $email)) {
						$mail->setTo($email);
						$mail->send();
					}
				}				
			}		

			// Send Admins SMS if configure
			if ($this->config->get('config_sms_alert')) {
				$options = array(
					'to'       => $this->config->get('config_sms_to'),
					'copy'     => $this->config->get('config_sms_copy'),
					'from'     => $this->config->get('config_sms_from'),
					'username' => $this->config->get('config_sms_gate_username'),
					'password' => $this->config->get('config_sms_gate_password'),
					'message'  => str_replace(array('{ID}', '{DATE}', '{TIME}', '{SUM}', '{PHONE}'), 
											  array($order_id, date('d.m.Y'), date('H:i'), floatval($order_info['total']), $order_info['telephone']), 
											  $this->config->get('config_sms_message'))
				);

				$this->load->library('sms');

				$sms = new Sms($this->config->get('config_sms_gatename'), $options);
				$sms->send();
			}

            // Export to 1C
            if(SEND_TO_1C)
            {
                $customer_data = array(
                    'name' => $order_info['firstname'],
                    'telephone' => $order_info['telephone'],
                    'email' => $order_info['email'],
                    'address' => $order_info['shipping_postcode'] . ', ' . $order_info['shipping_zone'] . ', ' . $order_info['shipping_city'] . ', ' . $order_info['shipping_address_1'] . ' ' . $order_info['shipping_address_2']
                );

                $xml_customer_data = "<fio><![CDATA[" . $customer_data['name'] . "]]></fio>";
                $xml_customer_data .= "<tel><![CDATA[" . $customer_data['telephone'] . "]]></tel>";
                $xml_customer_data .= "<email><![CDATA[" . $customer_data['email'] . "]]></email>";
                $xml_customer_data .= "<address><![CDATA[" . $customer_data['address'] . "]]></address>";

                $shipping = array(
                    'ems.ems' => 'ems', // доставка EMS
                    'ems_cash.ems_cash' => 'ems', // то же самое
                    'pickup.pickup' => 'pickup', // самовывоз из офиса
                    'pickup_point.pickup_point' => 'pickup', // самовывоз из магазина
                    'flat.flat' => 'courier', // доставка курьером
                    'russianpost.russianpost' => 'russianpost', // почтой россии
                    'russianpost_cash.russianpost_cash' => 'russianpost',
                    'megapolis.megapolis' => 'ems',
                    'megapolis_cash.megapolis_cash' => 'ems',
                    'megapolis_rp.megapolis_rp' => 'russianpost',
                    'megapolis_rp_cash.megapolis_rp_cash' => 'russianpost'
                );

                $payment = array(
                    'cod' => 'cash', // наличными при получении
                    'sberbank_transfer' => 'cashless', // безналичным путем
                    'paymentf' => 'ems_paymentforward', // наложенным платежом
                    'platron' => 'platron' // платрон
                );

                $shipp_match = $this->search_by_key($order_info['shipping_code'], $shipping);
                // ищем совпадение
                if($shipp_match){
                    $shipping_method = $shipp_match;
                } else {
                    $shipping_method = 'Уточните у клиента';
                }

                $toShop = '';

                if($shipping_method == 'pickup') {
                    $shops = $this->config->get('pickup_point_shops');
                    foreach ($shops as $shop) {
                        if(isset($order_info['pickup_point']) && $shop['shop_number'] == $order_info['pickup_point']) {
                            $toShop = $shop['shop_number'];
                        }
                    }
                }

                $paym_match = $this->search_by_key($order_info['payment_code'], $payment);

                if($paym_match) {
                    $payment_method = $paym_match;
                } else {
                    $payment_method = 'Уточните у клиента';
                }

                $certification = '';
                $certification_sale = 0;

                $certification_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_total` WHERE `code` = 'certification' AND `order_id` = '" . (int)$order_id . "'");
                if($certification_query->num_rows) {
                    $start = strpos($certification_query->row['title'], '(') + 1;
                    $end = strrpos($certification_query->row['title'], ')');

                    if ($start && $end) {
                        $certification = substr($certification_query->row['title'], $start, $end - $start);
                        $certification_sale = abs($certification_query->row['value']);
                    }

                    $this->db->query("UPDATE `" . DB_PREFIX . "order_total` SET `certification_pin` = 'xxxx' WHERE `code` = 'certification' AND `order_id` = '" . (int)$order_id . "'");
                }


                // Получаем дисконтную карту
                $discount_card_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_total` WHERE `code`='discount_card' AND `order_id`='" . (int)$order_id . "'");

                if($discount_card_query->num_rows) {
                    $mch = array();
                    preg_match('/([\d]+)/i', $discount_card_query->row['title'], $mch);
                    $discount_card = $mch[0];
                } else {
                    $discount_card = '';
                }

                // Order Totals
				
//промокупон начало
/*
$diskprc_total_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_total` WHERE `code` = 'coupon' AND `order_id` = '" . (int)$order_id . "'");
foreach ($diskprc_total_query->rows as $order_total) {
    if ($order_total['code'] == "coupon") {
        $match_p = array();
        if(preg_match('/\((.+)\)/', $order_total['title'], $m)) {
            $order_coupon = $m[1];
			$order_prc = $this->db->query("SELECT * FROM `" . DB_PREFIX . "coupon` WHERE `code` = '".$order_coupon."'");
			$discPrc = $order_prc->row['discount'];
        }
    }
}
*/
//промокупон конец
				
                $order_total_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_total` WHERE order_id = '" . (int)$order_id . "' ORDER BY sort_order ASC");

                $privilege = false;
                $privilege_str = '';

                foreach ($order_total_query->rows as $order_total) {
                    if ($order_total['code'] == "coupon") {
                        $match_p = array();
                        if(preg_match('/Каталог привилегий.*\(([0-9]+)\)/ui', $order_total['title'], $match_p)) {
                            $privilege = $match_p[1];
                            $db2 = new DB(DB_DRIVER, DB_HOSTNAME, DB_GIFT_USERNAME, DB_GIFT_PASSWORD, DB_GIFT_DATABASE);
                            $getPromoCatalog = $db2->query("SELECT `promo_id`, `promo_code`, `promo_catalog` FROM `gt_promo` WHERE `promo_code` = '" . (int)$privilege . "'");
                            $privilege_str = $privilege . ';' . $getPromoCatalog->row['promo_catalog'];
                        }
						if(preg_match('/\((.+)\)/', $order_total['title'], $match_p)) {
							$order_coupon = $match_p[1];
							$order_prc = $this->db->query("SELECT * FROM `" . DB_PREFIX . "coupon` WHERE `code` = '".$order_coupon."'");
							$discPrc = $order_prc->row['discount'];
						}
                    }
                }

                $sale = array();

                foreach ($order_total_query->rows as $order_total) {
                    if ($order_total['code'] == "sale_from_quantity") {
                        foreach($order_product_query->rows as $result) {
                            $product_query = $this->db->query("
                            SELECT `sale_type` FROM `" . DB_PREFIX . "product` WHERE `product_id` = '" . $result['product_id'] . "'
                            ");
                            if($product_query->num_rows && $product_query->row['sale_type'] == 0) {
                                $sale[$result['product_id']] = $result['price'] * 0.2;
                            }
                        }
                    }
                }

                if($shipping_method == 'pickup') {
                    $i = 1;

                    // Discounts
                    $count_products = count($order_product_query->rows);

                    $disc = 0;

                    $shippingCost = 0;

                    foreach ($order_total_query->rows as $order_total) {
                        if ($order_total['code'] == "discount") {
                            $disc += abs($order_total['value']);
                        }

//                        if ($order_total['code'] == "sale_from_quantity") {
//                            $disc += abs($order_total['value']);
//                        }
//                        if ($order_total['code'] == "coupon") {
//                            $disc += abs($order_total['value']);
//                        }
                        if ($order_total['code'] == "shipping") {
                            $shippingCost = $order_total['value'];
                        }
                        if($order_total['code'] == 'points') {
                            $disc += abs($order_total['value']);
                        }
                    }


                    // TODO: при оплате баллами, если баллы покрывают 100% заказа, сделать балансировку, чтобы в 1С приходила нулевая цена, а не минусовая
                    // TODO: сейчас баллы делятся на кол-во товаров и распределяются равными частями между товарами, что не совсем правильно
                    if($disc > 0) {
                        $disc_for_product = $disc / $count_products;
                    } else {
                        $disc_for_product = 0;
                    }

                    foreach($order_product_query->rows as $result) {

                        $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><order>";
                        $xml .= "<number>тдм" . $order_id . '-' . $i . "</number>";
                        $xml .= "<originalNumber>" . $order_id . "</originalNumber>";
                        $xml .= "<onlineShop>milabel</onlineShop>";
                        //if(isset($xml_not_reg)){
                        $xml .= $xml_customer_data;
                        //} else {
                        //$xml .= "<customer>" . $results_customer["customer_id_1c"] . "</customer>";
                        //$xml .= "<address><![CDATA[" . $order_info['shipping_postcode'] . ', ' . $order_info['shipping_zone'] . ', ' . $order_info['shipping_city'] . ', ' . $order_info['shipping_address_1'] . ' ' . $order_info['shipping_address_2'] . " " . $order_info['payment_address_2'] . "]]></address>";
                        //}
                        $xml .= "<payment><![CDATA[" . $payment_method . "]]></payment>";
                        $xml .= "<shipping><![CDATA[" . $shipping_method . "]]></shipping>";
                        $xml .= "<shop><![CDATA[" . $toShop . "]]></shop>";
                        $xml .= '<certification>' . $certification . '</certification>';
                        $xml .= '<certification_sale>' . $certification_sale . '</certification_sale>';
                        $xml .= "<discCard><![CDATA[" . $discount_card . "]]></discCard>";
                        $xml .= "<promo>" . $privilege_str . "</promo>";
						$xml .= "<discPrc>" . $discPrc . "</discPrc>";
                        $xml .= "<products>";
                        $xml .= "<product>";
                        foreach ($order_total_query->rows as $order_total) {
                            if ($order_total['code'] == 'coupon' && empty($privilege_str)) {
                                $coupon = preg_replace('/Купон \(([A-Z0-9]+)\):/ui', '$1', $order_total['title']);

                                // Получаем все coupon_product
                                $coupon_products_query = $this->db->query("
                                SELECT * FROM `" . DB_PREFIX . "coupon_product` WHERE `coupon_id` = (SELECT `coupon_id` FROM `" . DB_PREFIX . "coupon` WHERE `code` = '" . $coupon . "')
                                ");

                                $coupon_products = array();
                                foreach($coupon_products_query->rows as $row){
                                    $coupon_products[] = $row['product_id'];
                                }

                                if(in_array($result['product_id'], $coupon_products))
                                {
                                    $coupon_info = $this->db->query("SELECT * FROM `" . DB_PREFIX . "coupon` WHERE `coupon_id` = '" . $coupon_products_query->row['coupon_id'] . "'");

                                    if($coupon_info->row['type'] == 'P') {
                                        $result['price'] = $result['price'] - ($result['price'] / 100 * $coupon_info->row['discount']);
                                    } elseif($coupon_info->row['type'] == 'F') {
                                        $result['price'] = $result['price'] - $coupon_info->row['discount'];
                                    }
                                }
                            } elseif ($order_total['code'] == "sale_from_quantity" && array_key_exists($result['product_id'], $sale)) {
                                $result['price'] -= $sale[$result['product_id']];
                            }

                            if(!empty($privilege_str)) {
                                $coupon = preg_replace('/Купон \(([A-Z0-9]+)\):/ui', '$1', $order_total['title']);
                                $count_products = unserialize($order_total['promo_products']);

                                if(in_array($result['product_id'], $count_products)) {
                                    $result['price'] = $result['price'] - ($result['price'] * 0.05);
                                }
                            }
                        }
                        $order_product_post = $this->db->query("SELECT id_post FROM " . DB_PREFIX . "product WHERE product_id = '" . $result['product_id'] . "'");
                        if ($order_product_post->num_rows) {
                            $xml .= "<id>" . $order_product_post->row['id_post'] . "</id>";
                            $order_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . $result['order_product_id'] . "'");
                            foreach ($order_option_query->rows as $option) {
                                if($option['name'] == 'Размер') {
                                    $size = $option['value'];
                                    $xml .= "<size><![CDATA[" . $size . "]]></size>";
                                }
                                if($option['name'] == 'Цвет') {
                                    $color = $option['value'];
                                    $xml .= "<color><![CDATA[". $color ."]]></color>";
                                }
                            }
                            $xml .= "<sklad>" . $result['quantity'] . "</sklad>";
                            $xml .= "<wholesale>" . $result['price'] . "</wholesale>";

                            $xml .= "</product>";
                        }
                        $xml .= "</products>";

                        $xml .= "<disc>" . $disc_for_product . "</disc>";

                        $xml .= "<shippingCost>" . $shippingCost . "</shippingCost>";
                        $xml .= "<comment><![CDATA[" . $order_info['comment'] . "]]></comment>";
                        $xml .= "</order>";

                        $ap = array('inputXML' => $xml);
                        $ap = serialize($ap);
                        $this->db->query("INSERT INTO `" . DB_PREFIX . "to_1c` SET `object_type` = 'order', `object_id` = '" . (int)$order_id . '-' . $i  . "', `query` = '" . $this->db->escape($ap) . "'");

                        $i++;
                    }
                } else {
                    $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><order>";
                    $xml .= "<number>тдм" . $order_id . "</number>";
                    $xml .= "<originalNumber>" . $order_id . "</originalNumber>";
                    $xml .= "<onlineShop>milabel</onlineShop>";
                    //if(isset($xml_not_reg)){
                    $xml .= $xml_customer_data;
                    //} else {
                    //$xml .= "<customer>" . $results_customer["customer_id_1c"] . "</customer>";
                    //$xml .= "<address><![CDATA[" . $order_info['shipping_postcode'] . ', ' . $order_info['shipping_zone'] . ', ' . $order_info['shipping_city'] . ', ' . $order_info['shipping_address_1'] . ' ' . $order_info['shipping_address_2'] . " " . $order_info['payment_address_2'] . "]]></address>";
                    //}
                    $xml .= "<payment><![CDATA[" . $payment_method . "]]></payment>";
                    $xml .= "<shipping><![CDATA[" . $shipping_method . "]]></shipping>";
                    $xml .= "<shop><![CDATA[" . $toShop . "]]></shop>";
                    $xml .= '<certification>' . $certification . '</certification>';
                    $xml .= '<certification_sale>' . $certification_sale . '</certification_sale>';
                    $xml .= "<discCard><![CDATA[" . $discount_card . "]]></discCard>";
                    $xml .= "<promo>" . $privilege_str . "</promo>";
					$xml .= "<discPrc>" . $discPrc . "</discPrc>";
                    $xml .= "<products>";
                    foreach ($order_product_query->rows as $result) {
                        $xml .= "<product>";
                        foreach ($order_total_query->rows as $order_total) {
                            if ($order_total['code'] == 'coupon' && empty($privilege_str)) {
                                $coupon = preg_replace('/Купон \(([A-Z0-9]+)\):/ui', '$1', $order_total['title']);

                                // Получаем все coupon_product
                                $coupon_products_query = $this->db->query("
                                SELECT * FROM `" . DB_PREFIX . "coupon_product` WHERE `coupon_id` = (SELECT `coupon_id` FROM `" . DB_PREFIX . "coupon` WHERE `code` = '" . $coupon . "')
                                ");

                                $coupon_products = array();
                                foreach($coupon_products_query->rows as $row){
                                    $coupon_products[] = $row['product_id'];
                                }

                                if(in_array($result['product_id'], $coupon_products))
                                {
                                    $coupon_info = $this->db->query("SELECT * FROM `" . DB_PREFIX . "coupon` WHERE `coupon_id` = '" . $coupon_products_query->row['coupon_id'] . "'");

                                    if($coupon_info->row['type'] == 'P') {
                                        $result['price'] = $result['price'] - ($result['price'] / 100 * $coupon_info->row['discount']);
                                    } elseif($coupon_info->row['type'] == 'F') {
                                        $result['price'] = $result['price'] - $coupon_info->row['discount'];
                                    }
                                }
                            } elseif ($order_total['code'] == "sale_from_quantity" && array_key_exists($result['product_id'], $sale)) {
                                $result['price'] -= $sale[$result['product_id']];
                            }

                            if(!empty($privilege_str)) {
                                $coupon = preg_replace('/Купон \(([A-Z0-9]+)\):/ui', '$1', $order_total['title']);
                                $count_products = unserialize($order_total['promo_products']);

                                if($count_products && in_array($result['product_id'], $count_products)) {
                                    $result['price'] = $result['price'] - ($result['price'] * 0.05);
                                }
                            }
                        }
                        $order_product_post = $this->db->query("SELECT id_post FROM " . DB_PREFIX . "product WHERE product_id = '" . $result['product_id'] . "'");
                        if ($order_product_post->num_rows) {
                            $xml .= "<id>" . $order_product_post->row['id_post'] . "</id>";

                            $order_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . $result['order_product_id'] . "'");
                            foreach ($order_option_query->rows as $option) {
                                if($option['name'] == 'Размер') {
                                    $size = $option['value'];
                                    $xml .= "<size><![CDATA[" . $size . "]]></size>";
                                }
                                if($option['name'] == 'Цвет') {
                                    $color = $option['value'];
                                    $xml .= "<color><![CDATA[". $color ."]]></color>";
                                }
                            }
                            $xml .= "<sklad>" . $result['quantity'] . "</sklad>";
                            $xml .= "<wholesale>" . $result['price'] . "</wholesale>";
                            $xml .= "</product>";
                        }

                    }
                    $xml .= "</products>";
                    $disc = 0;
                    $shippingCost = 0;
                    foreach ($order_total_query->rows as $order_total) {
                        if ($order_total['code'] == "discount") {
                            $disc += abs($order_total['value']);
                        }
//                        if ($order_total['code'] == "sale_from_quantity") {
//                            $disc += abs($order_total['value']);
//                        }
//                        if ($order_total['code'] == "coupon") {
//                            $disc += abs($order_total['value']);
//                        }
                        if ($order_total['code'] == "shipping") {
                            $shippingCost = $order_total['value'];
                            if($shipping_method == 'courier' && $payment_method == 'platron')
                            {
                                $shippingCost = 0;
                            }
                        }
                        if($order_total['code'] == 'points') {
                            $order_total['value'] = abs($order_total['value']);
                            $disc += $order_total['value'];
                        }
                    }
                    $xml .= "<disc>" . $disc . "</disc>";
                    $xml .= "<shippingCost>" . $shippingCost . "</shippingCost>";
                    $xml .= "<comment><![CDATA[" . $order_info['comment'] . "]]></comment>";
                    $xml .= "</order>";

                    $ap = array('inputXML' => $xml);
                    $ap = serialize($ap);
                    $this->db->query("INSERT INTO `" . DB_PREFIX . "to_1c` SET `object_type` = 'order', `object_id` = '" . (int)$order_id  . "', `query` = '" . $this->db->escape($ap) . "'");
                }
            }
		}
	}

    private function search_by_key($needle, $array) {

        foreach ($array as $key => $val) {
            if(preg_match('/pickup(.*)/', $needle)) {
                $needle = 'pickup.pickup';
            }
            if(strtolower($needle) == strtolower($key)) {
                return $val;
            }
        }

        return FALSE;

    }
	
	public function update($order_id, $order_status_id, $comment = '', $notify = false) {
		$order_info = $this->getOrder($order_id);

		if ($order_info && $order_info['order_status_id']) {
			// Fraud Detection
			if ($this->config->get('config_fraud_detection')) {
				$this->load->model('checkout/fraud');
				
				$risk_score = $this->model_checkout_fraud->getFraudScore($order_info);
				
				if ($risk_score > $this->config->get('config_fraud_score')) {
					$order_status_id = $this->config->get('config_fraud_status_id');
				}
			}			

			// Ban IP
			$status = false;
			
			$this->load->model('account/customer');
			
			if ($order_info['customer_id']) {
								
				$results = $this->model_account_customer->getIps($order_info['customer_id']);
				
				foreach ($results as $result) {
					if ($this->model_account_customer->isBanIp($result['ip'])) {
						$status = true;
						
						break;
					}
				}
			} else {
				$status = $this->model_account_customer->isBanIp($order_info['ip']);
			}
			
			if ($status) {
				$order_status_id = $this->config->get('config_order_status_id');
			}		
						
			$this->db->query("UPDATE `" . DB_PREFIX . "order` SET order_status_id = '" . (int)$order_status_id . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'");
		
			$this->db->query("INSERT INTO " . DB_PREFIX . "order_history SET order_id = '" . (int)$order_id . "', order_status_id = '" . (int)$order_status_id . "', notify = '" . (int)$notify . "', comment = '" . $this->db->escape($comment) . "', date_added = NOW()");
	
			// Send out any gift voucher mails
			if ($this->config->get('config_complete_status_id') == $order_status_id) {
				$this->load->model('checkout/voucher');
	
				$this->model_checkout_voucher->confirm($order_id);
			}	
	
			if ($notify) {
				$language = new Language($order_info['language_directory']);
				$language->load($order_info['language_filename']);
				$language->load('mail/order');
			
				$subject = sprintf($language->get('text_update_subject'), html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'), $order_id);
	
				$message  = $language->get('text_update_order') . ' ' . $order_id . "\n";
				$message .= $language->get('text_update_date_added') . ' ' . date($language->get('date_format_short'), strtotime($order_info['date_added'])) . "\n\n";
				
				$order_status_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_status WHERE order_status_id = '" . (int)$order_status_id . "' AND language_id = '" . (int)$order_info['language_id'] . "'");
				
				if ($order_status_query->num_rows) {
					$message .= $language->get('text_update_order_status') . "\n\n";
					$message .= $order_status_query->row['name'] . "\n\n";					
				}
				
				if ($order_info['customer_id']) {
					$message .= $language->get('text_update_link') . "\n";
					$message .= $order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_id . "\n\n";
				}
				
				if ($comment) { 
					$message .= $language->get('text_update_comment') . "\n\n";
					$message .= $comment . "\n\n";
				}
					
				$message .= $language->get('text_update_footer');

				$mail = new Mail();
				$mail->protocol = $this->config->get('config_mail_protocol');
				$mail->parameter = $this->config->get('config_mail_parameter');
				$mail->hostname = $this->config->get('config_smtp_host');
				$mail->username = $this->config->get('config_smtp_username');
				$mail->password = $this->config->get('config_smtp_password');
				$mail->port = $this->config->get('config_smtp_port');
				$mail->timeout = $this->config->get('config_smtp_timeout');				
				$mail->setTo($order_info['email']);
				$mail->setFrom($this->config->get('config_email'));
				$mail->setSender($order_info['store_name']);
				$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
				$mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
				$mail->send();
			}
		}
	}
}
?>

Змінено користувачем Helloween
Надіслати
Поділитися на інших сайтах


Закомментировал этот участок и все заработало:

if(preg_match('/Каталог привилегий.*\(([0-9]+)\)/ui', $order_total['title'], $match_p)) {
                            $privilege = $match_p[1];
                            $db2 = new DB(DB_DRIVER, DB_HOSTNAME, DB_GIFT_USERNAME, DB_GIFT_PASSWORD, DB_GIFT_DATABASE);
                            $getPromoCatalog = $db2->query("SELECT `promo_id`, `promo_code`, `promo_catalog` FROM `gt_promo` WHERE `promo_code` = '" . (int)$privilege . "'");
                            $privilege_str = $privilege . ';' . $getPromoCatalog->row['promo_catalog'];
                        }
Надіслати
Поділитися на інших сайтах


Створіть аккаунт або увійдіть для коментування

Ви повинні бути користувачем, щоб залишити коментар

Створити обліковий запис

Зареєструйтеся для отримання облікового запису. Це просто!

Зареєструвати аккаунт

Вхід

Уже зареєстровані? Увійдіть тут.

Вхід зараз
  • Зараз на сторінці   0 користувачів

    • Ні користувачів, які переглядиють цю сторінку

×
×
  • Створити...

Important Information

На нашому сайті використовуються файли cookie і відбувається обробка деяких персональних даних користувачів, щоб поліпшити користувальницький інтерфейс. Щоб дізнатися для чого і які персональні дані ми обробляємо перейдіть за посиланням . Якщо Ви натиснете «Я даю згоду», це означає, що Ви розумієте і приймаєте всі умови, зазначені в цьому Повідомленні про конфіденційність.