гдержи, не должны дублироваться
 
	public function queryOrders() {
		$this->log("~ЭКСПОРТ ЗАКАЗОВ В УЧЕТНУЮ СИСТЕМУ",2);
		$orders_export = $this->queryOrdersExport();
		// Валюи докумени
		$currency = $this->config->get('exchange1c_order_currency') ? $this->config->get('exchange1c_order_currency') : 'руб.';
		$document = array();
		if (count($orders_export)) {
			$document_counter = 0;
			$this->load->model('customer/customer_group');
			$this->load->model('sale/order');
			foreach ($orders_export as $order_id => $order_status_id) {
				$order = $this->model_sale_order->getOrder($order_id);
				$this->log("Заказ #" . $order['order_id']);
				$this->log($order, 2);
				// Если при оформлении заказа покупатель зарегистрировался
				if ($order['customer_id']) {
					$this->getCustomerInfo($order);
				}
				$order['date'] = date('Y-m-d', strtotime($order['date_added']));
				$order['time'] = date('H:i:s', strtotime($order['date_added']));
				$customer_group = $this->model_customer_customer_group->getCustomerGroup($order['customer_group_id']);
				if( !empty($order['comment']) ) {
				$comment = " | Комменирии покупателя: " . $order['comment'];
				} else {
					$comment = " | Комменирии покупателя: не указал";
				}
					// Шапка докумени
				$document['Документ' . $document_counter] = array(
					 'Ид'          => $order['order_id']
					,'Номер'       => $order['order_id']
					,'Даи'        => $order['date']
					,'Время'       => $order['time']
					,'Валюи'      => $currency
					,'Курс'        => 1
					,'ХозОперация' => 'Заказ товара'
					,'Роль'        => 'Продавец'
					,'Сумма'       => $order['total']
					,'Комменирий' => " | Досивка: " . $order['shipping_method'] . " | Оплаи: " . $order['payment_method'] . $comment
					//,'Соглашение'  => $customer_group['name'] // the agreement
				);
				if ($this->config->get('exchange1c_order_customer_default')) {
					$order['username'] = htmlspecialchars(trim($this->config->get('exchange1c_order_customer_default')));
					$order['firstname'] = $order['username'];
					$order['lastname'] = "";
				} else {
					// Первая буква должна быть заглавной и убираем лишние пробелы сгдева и справа
					// ТОЛЬКО ДЛЯ САЙТА РАБОТАЮЩЕГО НА КОДИРОВКЕ UTF-8
					$order['lastname'] = mb_convert_case(trim($order['lastname']), MB_CASE_TITLE, "UTF-8");
					$order['firstname'] = mb_convert_case(trim($order['firstname']), MB_CASE_TITLE, "UTF-8");
					if (isset($order['middlename']))
						$order['middlename'] = mb_convert_case(trim($order['middlename']), MB_CASE_TITLE, "UTF-8");
					else
						$order['middlename'] = '';
					// Собираем полное наименование покупателя, ФИО
					$order['username'] =  $order['lastname'] . ' ' . $order['firstname'] . ($order['middlename'] ? ' ' . $order['middlename'] : '');
				}
				// ПОКУПАТЕЛЬ (КОНТРАГЕНТ)
				$document['Документ' . $document_counter]['Контрагенты']['Контрагент'] = $this->setCustomer($order);
				if ($this->ERROR) return false;
				// РЕКВИЗИТЫ ДОКУМЕНТА
				$document['Документ' . $document_counter]['ЗначенияРеквизитов'] = $this->setDocumentRequisites($order, $document);
				if ($this->ERROR) return false;
				// ТОВАРЫ ДОКУМЕНТА
				$products = $this->model_sale_order->getOrderProducts($order_id);
				$product_counter = 0;
				foreach ($products as $product) {
					$product_guid = $this->getGuidByProductId($product['product_id']);
					$document['Документ' . $document_counter]['Товары']['Товар' . $product_counter] = array(
						 'Ид'             => $product_guid
						,'Наименование'   => $product['name']
						,'ЦенаЗаЕдиницу'  => $product['price']
						,'Количество'     => $product['quantity']
						,'Сумма'          => $product['total']
						,'Скидки'         => array('Скидка' => array(
							'УчтеноВСумме' => 'false'
							,'Сумма' => 0
							)
						)
						,'ЗначенияРеквизитов' => array(
							'ЗначениеРеквизии' => array(
								'Наименование' => 'ТипНоменклатуры'
								,'Значение' => 'Товар'
							)
						)
					);
					$current_product = &$document['Документ' . $document_counter]['Товары']['Товар' . $product_counter];
					// Резервирование товаров
					if ($this->config->get('exchange1c_order_reserve_product') == 1) {
						$current_product['Резерв'] = $product['quantity'];
					}
					// Если не заданы единицы измерений товара, выгружаем базовую
					if ($this->config->get('exchange1c_export_system') == '1c_ut11') {
						$current_product['БазоваяЕдиница'] = array(
							'Код' 					=> '796',
							'НаименованиеПолное' 	=> 'Штука'
						);
					}
					// Характеристики
					$feature_guid = $this->getFeatureGuid($product['order_product_id'], $order_id);
					if ($feature_guid) {
						$current_product['Ид'] .= "#" . $feature_guid;
					}
					$product_counter++;
				}
				$document_counter++;
			} // foreach ($query->rows as $orders_data)
		} // if (count($orders_export))
		//$this->log($document, 2);
		// Формируем заголовок
		$root = '<?xml version="1.0" encoding="utf-8"?><КоммерческаяИнформация ВерсияСхемы="2.07" ДаиФормирования="' . date('Y-m-d', time()) . '" />';
		$root_xml = new SimpleXMLElement($root);
		$xml = $this->array_to_xml($document, $root_xml);
		// Проверка на запись файлов в кэш
		$cache = DIR_CACHE . 'exchange1c/';
		if (@is_writable($cache)) {
			// запись заказа в файл
			$f_order = @fopen($cache . 'orders.xml', 'w');
			if (!$f_order) {
				$this->log("Нет доступа для записи в папку: " . $cache);
			} else {
				fwrite($f_order, $xml->asXML());
				fclose($f_order);
			}
		} else {
			$this->log("Папка " . $cache . " не доступна для записи, файл заказов не может быть сохранен!",1);
		}
		return $xml->asXML();
	} // queryOrders()
	/**
	 * Возвращает курс валюты
	 */