diff --git a/LICENSE b/LICENSE index 5093005..1d1b842 100644 --- a/LICENSE +++ b/LICENSE @@ -1,7 +1,9 @@ DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 - Copyright (C) 2018 Anthony Axenov (Антон Аксенов) + Copyright (C) 2018 Anthony Axenov (Антон Аксенов) , + Alexey Kopylov (Алексей Копылов) , + LLC Alt-team (ООО "Альт-тим") Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long diff --git a/README.md b/README.md index aed310d..4e761c5 100644 --- a/README.md +++ b/README.md @@ -2,41 +2,31 @@ ## Содержимое репозитория -- `./dreamkas-opencart3.ocmod/` - директория с исходным кодом модифицированного мной модуля -- `./dreamkas-opencart3.ocmod.zip` - модифицированный модуль, готовый к установке +- `./src/` - директория с исходным кодом модифицированного мной модуля +- `./dreamkas-opencart-3.ocmod.zip` - модифицированный модуль, готовый к установке - `./dreamkas-f opencart.ocmod.zip` - исходный модуль для OpenCart 2.3, на котором основана данная модификация ## Описание Модификация тестировалась на **OpenCart 3.0.2.0**. + Модуль устанавливается, удаляется, настройки сохраняются, читаются. -Судя по отзывам ([первый](http://blog.anthonyaxenov.ru/2018/05/09/%d0%bc%d0%be%d0%b4%d1%83%d0%bb%d1%8c-%d0%b8%d0%bd%d1%82%d0%b5%d0%b3%d1%80%d0%b0%d1%86%d0%b8%d0%b8-dreamkas-%d0%b4%d0%bb%d1%8f-opencart-3-0-2-0/#comment-103), [второй](https://help.dreamkas.ru/hc/ru/articles/115005504689-%D0%9F%D0%BE%D0%B4%D0%BA%D0%BB%D1%8E%D1%87%D0%B8%D1%82%D1%8C-%D0%BA%D0%B0%D1%81%D1%81%D1%83-%D0%BA-OpenCart)), полученный модуль в целом работает, за исключением одного момента: не отображаются статусы фискализации. -У меня лично нет возможности полноценно проверить насколько качественно работает этот модуль: для этого нужны реальные заказы и покупки. -Проект, в рамках которого я работал над этим модулем, я больше не поддерживаю. +Статусы фискализации не сразу отображаются на главной странице заказов пока не зайдешь в сам заказ. -Вся основная логика модуля прописана здесь: -`upload/catalog/controller/extension/module/dreamkas.php` - -Этот файл я не трогал. -Я лишь восстановил возможность установить, удалить и настроить модуль. +Вся основная логика модуля прописана здесь: `upload/catalog/controller/extension/module/dreamkas.php` ## Краткая информация об изменениях -Основано на модуле _[dreamkas-f opencart.ocmod.zip](https://help.dreamkas.ru/hc/ru/article_attachments/115010763145/dreamkas-f_opencart.ocmod.zip)_. +Основано на модуле _[dreamkas-f opencart.ocmod.zip](https://help.dreamkas.ru/hc/ru/article_attachments/115010763145/dreamkas-f_opencart.ocmod.zip)_ от команды alt-team.ru. -Этот архив предоставляется самими сотрудниками Dreamkas. -Он включен в репозиторий для истории. +Этот архив предоставляется самими сотрудниками Dreamkas. Он включен в репозиторий для истории. -Ниже вкратце описаны мои правки, но чтобы узнать детальные изменения, то можете заморочиться с diff-ами. +## Важное замечание относительно НДС -1. Шаблон (`upload/admin/view/template/extension/module/dreamkas.twig`): - 1. переписан с языка php на язык шаблонизатора Twig - 2. изменено расширение с .tpl на .twig -2. Страница настроек: - 1. удалены большие куски закомментированного и нерабочего (?) кода - 2. исправлено получение списка установленных платёжных систем в настройках - 3. форматирование кода (`upload/admin/controller/extension/module/dreamkas.php`) +В этом устаревшем модуле до сих пор существует НДС 18/180. + +**Важно знать, что с 1 января 2019 эти ставки были заменены на НДС 20/120!** ## Полезные ссылки @@ -54,9 +44,10 @@ ЛЮБЫЕ МАНИПУЛЯЦИИ С МОДУЛЕМ — НА ВАШ СТРАХ И РИСК. -Я вижу, что люди используют мою модификацию. Но у меня нет никакого интереса и необходимости в этом. Многие вещи об OpenCart, продуктах Dreamkas и этом модуле уже забыты. Поэтому, и поскольку проект изначально не мой, лично я развивать его точно не буду. +У меня нет возможности полноценно проверить насколько качественно работает этот модуль: для этого нужны реальные заказы и покупки. +Проект, в рамках которого я работал над этим модулем, я больше не поддерживаю. -Этот репозиторий появился только потому, что на фоне наплевательского отношения со стороны Dreamkas мне случайно удалось сделать из совсем нерабочей вещи почти рабочую. +У меня нет никакого интереса и необходимости в этом. Многие вещи об OpenCart, продуктах Dreamkas и этом модуле уже забыты. Поэтому, и поскольку проект изначально не мой, лично я развивать его точно не буду. Берите и используйте. Не работает — штош. Если у вас есть какие-то доработки — pull-requests are welcome. Но лучше сделайте форк этого репозитория и развивайте проект дальше самостоятельно. @@ -65,14 +56,19 @@ [WTFPL](LICENSE) Аргументирую: + 1. Компания Dreamkas распространяет свои модули без какой-либо лицензии. -2. [Код этих модулей не был написан компанией Dreamkas](https://help.dreamkas.ru/hc/ru/articles/115005504689/comments/360000156078), а в этом случае исключительные авторские права Dreamkas на этот код должны быть оговорены только в рамках правовых отношений с подрядчиком. +2. [Код модуля был написан командой alt-team, а не компанией Dreamkas](https://help.dreamkas.ru/hc/ru/articles/115005504689/comments/360000156078). В этом случае исключительные авторские права Dreamkas на этот код должны быть оговорены только в рамках правовых отношений с командой alt-team. 3. Этот модуль находится в открытом доступе в разделе поддержки Dreamkas. Ни [лицензионное соглашение](https://dreamkas.ru/content/kluch-oferta.pdf), ни [договор-оферта](https://dreamkas.ru/content/dogovor-oferta-clients.pdf), публично представленные на сайте Dreamkas: - * не содержат условий использования, изменения и распространения пользователями этого модуля; - * неприменимы для этого случая (см. п. 2) + - не содержат условий использования, изменения и распространения пользователями этого модуля; + - неприменимы для этого случая (см. п. 2) +4. [Политика обновлений компании alt-team](https://www.alt-team.ru/upgrade-policy.html) не распространяется на модуль интеграции Dreamkas и Opencart, т.к. этот модуль не продаётся на их сайте; +5. В исходном коде модуля нигде прямо не указан копирайт в соответствии со статьёй 1271 ГК РФ. Исходя из этого, делаю выводы: -1. Компания Dreamkas никоим образом не заявляет о своих правах на код модуля, об условиях его использования, распространения и изменения. Поэтому я вправе сделать это самостоятельно, так как код был изменён мной. -2. **[Лицензия WTFPL v2](LICENSE)** как никакая другая лучше подходит для этого случая. -Я готов обсудить вопросы лицензии и изменить условия, если вам есть что сказать по существу. +1. Компания Dreamkas и команда alt-team никоим образом не заявляют о своих правах на код модуля, об условиях его использования, распространения и изменения. Поэтому я вправе сделать это самостоятельно. +2. **[Лицензия WTFPL v2](LICENSE)** как никакая другая лучше подходит для этого случая. +3. Компания Альт-тим должна быть упомянута в тексте лицензии среди прочих авторов исходного кода, т.к. в файле `dreamkas-f opencart.ocmod.zip/install.xml` встречается её упоминание. + +Я готов обсудить и изменить эти условия, если вам есть что сказать по существу. diff --git a/dreamkas-opencart-3.ocmod.zip b/dreamkas-opencart-3.ocmod.zip new file mode 100644 index 0000000..eee7930 Binary files /dev/null and b/dreamkas-opencart-3.ocmod.zip differ diff --git a/dreamkas-opencart3.ocmod.zip b/dreamkas-opencart3.ocmod.zip deleted file mode 100644 index 44fe044..0000000 Binary files a/dreamkas-opencart3.ocmod.zip and /dev/null differ diff --git a/dreamkas-opencart3.ocmod/install.xml b/dreamkas-opencart3.ocmod/install.xml deleted file mode 100644 index 75a4e14..0000000 --- a/dreamkas-opencart3.ocmod/install.xml +++ /dev/null @@ -1,170 +0,0 @@ - - - Dreamkas 2.3.x - Dreamkas 2.3.x - 1.00 - Alt-team - https://www.alt-team.ru/ - - - - - ]]> - - -
- -
- - ]]>
-
-
- - - db->query("DELETE FROM " . DB_PREFIX . "product_description WHERE product_id = '" . (int)$product_id . "'"); - ]]> - db->query("UPDATE " . DB_PREFIX . "product SET dk_tax_type = '" . $this->db->escape($data['dk_tax_type']) . "' WHERE product_id = '" . (int)$product_id . "'"); - } - ]]> - - - - - load->model('catalog/recurring'); - ]]> - request->post['dk_tax_type'])) { - $data['dk_tax_type'] = $this->request->post['dk_tax_type']; - } elseif (!empty($product_info['dk_tax_type'])) { - $data['dk_tax_type'] = $product_info['dk_tax_type']; - } else { - $data['dk_tax_type'] = ''; - } - ]]> - - - - - - ]]> - Статус фискализации - ]]> - - - - ]]> - - ]]> - - - - - - ]]> - - - - - - ]]> - - - - - model_sale_order->getOrders($filter_data); - ]]> - db->query("SELECT dk_status FROM " . DB_PREFIX . "dreamkas WHERE order_id = '" . (int)$result['order_id']. "'"); - ]]> - - - $result['shipping_code'],]]> - !empty($dkquery->row['dk_status'])?$dkquery->row['dk_status']:'', - ]]> - - - language->get('tab_additional');]]> - db->query("SELECT order_status_id FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int)$order_id . "'"); - $status = $query->row['order_status_id']; - - $query = $this->db->query("SELECT payment_code FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int)$order_id . "'"); - $payment_code = $query->row['payment_code']; - - if ($status == $this->config->get('dreamkas_paid_order') && in_array($payment_code, $this->config->get('dreamkas_payments_ids'))) { - - $query = $this->db->query("SELECT dk_id FROM " . DB_PREFIX . "dreamkas WHERE order_id = '" . (int)$order_id. "'"); - if(!empty($query->row['dk_id'])) { - $dk_id = $query->row['dk_id']; - $ch = curl_init(); - $access_token = $this->config->get('dreamkas_access_token'); - - curl_setopt($ch, CURLOPT_HTTPHEADER, array( - "Content-Type: application/json", - "Authorization: Bearer $access_token" - )); - - curl_setopt($ch, CURLOPT_URL, "https://kabinet.dreamkas.ru/api/operations/".$dk_id); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); - curl_setopt($ch, CURLOPT_HEADER, FALSE); - $response = curl_exec($ch); - curl_close($ch); - - $response = json_decode($response, true); - - if((substr($response['status'], 0, 1)==4)) { - $this->log->write('Dreamkas debug: ' . json_encode($response)); - } elseif(!empty($response['data']['error'])) { - $this->log->write('Dreamkas debug: ' . json_encode($response['data']['error'])); - } else { - $dk_date = empty($response['createdAt'])?$response['completedAt']:$response['createdAt']; - $this->db->query("UPDATE `" . DB_PREFIX . "dreamkas` SET `order_id` = '" . (int)$order_id . "', `dk_id` = '".$response['id']."', `dk_date` ='".$dk_date."', `dk_status` = '" .$response['status']. "' WHERE order_id = '" . (int)$order_id. "'"); - } - } - } - - $query = $this->db->query("SELECT dk_status FROM " . DB_PREFIX . "dreamkas WHERE order_id = '" . (int)$order_id. "'"); - if(!empty($query->row['dk_status'])) { - $data['dk_status'] = $query->row['dk_status']; - } else { - $data['dk_status']=''; - } - $this->load->language('extension/module/dreamkas'); - $data['entry_dk_status'] = $this->language->get('entry_dk_status'); - ]]> - - -
\ No newline at end of file diff --git a/dreamkas-opencart3.ocmod/upload/admin/view/template/extension/module/dreamkas.tpl b/dreamkas-opencart3.ocmod/upload/admin/view/template/extension/module/dreamkas.tpl deleted file mode 100644 index 444c898..0000000 --- a/dreamkas-opencart3.ocmod/upload/admin/view/template/extension/module/dreamkas.tpl +++ /dev/null @@ -1,127 +0,0 @@ - -
- -
- -
- -
- -
-
-

-
-
-
-
- -
- - -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
- -
- -
- -
-
- -
- -
-
- -
- -
- -
-
-
- - -
- -
- -
-
-
-
-
-
-
- diff --git a/dreamkas-opencart3.ocmod/upload/admin/view/template/extension/module/dreamkas.twig b/dreamkas-opencart3.ocmod/upload/admin/view/template/extension/module/dreamkas.twig deleted file mode 100644 index 173f5d0..0000000 --- a/dreamkas-opencart3.ocmod/upload/admin/view/template/extension/module/dreamkas.twig +++ /dev/null @@ -1,120 +0,0 @@ -{{ header }} -{{ column_left }} -
- -
- {% if error_warning %} -
{{ error_warning }} - -
- {% endif %} -
-
-

{{ text_edit }}

-
-
-
- -
- -
- - {% if error_access_token %} -
{{ error_access_token }}
- {% endif %} -
-
- -
- -
- -
-
- -
- -
- -
-
- -
- -
- -
-
- -
- -
- -
-
- -
- -
-
- {% for type in paymenttypes %} -
- -
- {% endfor %} -
-
-
- -
- -
- -
-
-
-
-
-
-
-{{ footer }} diff --git a/dreamkas-opencart3.ocmod/upload/catalog/controller/extension/module/dreamkas.php b/dreamkas-opencart3.ocmod/upload/catalog/controller/extension/module/dreamkas.php deleted file mode 100644 index f39ffcf..0000000 --- a/dreamkas-opencart3.ocmod/upload/catalog/controller/extension/module/dreamkas.php +++ /dev/null @@ -1,120 +0,0 @@ -load->language('extension/module/dreamkas'); - $order_id = $data[0]; - $query = $this->db->query("SELECT order_status_id FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int) $order_id . "'"); - $status = $query->row['order_status_id']; - $query = $this->db->query("SELECT payment_code FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int) $order_id . "'"); - $payment_code = $query->row['payment_code']; - - if ($status == $this->config->get('dreamkas_paid_order') && - in_array($payment_code, $this->config->get('dreamkas_payments_ids'))) - { - $this->load->model('checkout/order'); - $order_info = $this->model_checkout_order->getOrder($order_id); - $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int) $order_id . "'"); - $products = $query->rows; - $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int) $order_id . "' AND code = 'shipping' ORDER BY sort_order"); - $shipping = $query->rows; - $tax_type = $this->config->get('dreamkas_tax_type'); - $tax_sum = 0; - $items = array(); - foreach ($products as $product) { - $query = $this->db->query("SELECT dk_tax_type FROM " . DB_PREFIX . "product WHERE product_id = '" . (int) $product['product_id'] . "'"); - $dk_tax_type = $query->row; - $product_tax_type = empty($dk_tax_type['dk_tax_type']) ? $tax_type : $dk_tax_type['dk_tax_type']; - $items[] = array( - "name" => $product['name'], - "type" => "COUNTABLE", - "quantity" => $product['quantity'], - "price" => ($product['price'] + $product['tax']) * 100, - "priceSum" => ($product['total'] + $product['tax'] * $product['quantity']) * 100, - "tax" => "$product_tax_type", - "taxSum" => 0, //$product['tax']*100*$product['quantity'] - ); - $tax_sum += $product['tax'] * $product['quantity']; - } - - if (!empty($shipping)) { - $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int) $order_id . "' AND code = 'tax' ORDER BY sort_order"); - $tax_total = reset($query->rows); - if (!empty($tax_total['value'])) { - $shipping_tax = $tax_total['value'] - $tax_sum; - } else { - $shipping_tax = 0; - } - foreach ($shipping as $_shipping) { - if ($_shipping['value'] > 0) { - $items[] = array( - "name" => 'Доставка', - "type" => "COUNTABLE", - "quantity" => 1, - "price" => ($_shipping['value'] + $shipping_tax) * 100, - "priceSum" => ($_shipping['value'] + $shipping_tax) * 100, - "tax" => "$tax_type", - "taxSum" => 0, //$shipping_tax*100 - ); - } - } - } - - $request = array( - "deviceId" => $this->config->get('dreamkas_device_id'), - "type" => "SALE", - "timeout" => 180, - "taxMode" => $this->config->get('dreamkas_tax_mode'), - "positions" => $items, - "payments" => array( - array( - "sum" => $order_info['total'] * 100, - "type" => "CASHLESS", - ), - ), - "attributes" => array( - "email" => $order_info['email'], - "phone" => $order_info['telephone'], //"+71239994499" - ), - "total" => array( - "priceSum" => $order_info['total'] * 100, - ), - ); - - $ch = curl_init(); - $access_token = $this->config->get('dreamkas_access_token'); - curl_setopt($ch, CURLOPT_HTTPHEADER, array( - "Content-Type: application/json", - "Authorization: Bearer $access_token", - )); - curl_setopt($ch, CURLOPT_URL, "https://kabinet.dreamkas.ru/api/receipts"); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_HEADER, false); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request)); - $response = curl_exec($ch); - curl_close($ch); - - if (!empty($response)) { - $response = json_decode($response, true); - if ((substr($response['status'], 0, 1) == 4)) { - $this->log->write('Dreamkas debug: ' . json_encode($response)); - } else { - $dk_date = empty($response['createdAt']) ? $response['completedAt'] : $response['createdAt']; - $query = $this->db->query("SELECT order_id FROM " . DB_PREFIX . "dreamkas WHERE order_id = '" . (int) $order_id . "'"); - $exist_order_id = $query->rows; - if (empty($exist_order_id)) { - $this->db->query("INSERT INTO `" . DB_PREFIX . "dreamkas` SET `order_id` = '" . (int) $order_id . "', `dk_id` = '" . $response['id'] . "', `dk_date` ='" . $dk_date . "', `dk_status` = '" . $response['status'] . "'"); - } else { - $this->db->query("UPDATE `" . DB_PREFIX . "dreamkas` SET `order_id` = '" . (int) $order_id . "', `dk_id` = '" . $response['id'] . "', `dk_date` ='" . $dk_date . "', `dk_status` = '" . $response['status'] . "' WHERE order_id = '" . (int) $order_id . "'"); - } - } - } - } - } - } - -} diff --git a/src/install.xml b/src/install.xml new file mode 100644 index 0000000..2406835 --- /dev/null +++ b/src/install.xml @@ -0,0 +1,164 @@ + + + Dreamkas 3.x + Dreamkas 3.x + 1.02 + Anthony Axenov, Alexey Kopylov (based on code by alt-team.ru) + https://github.com/anthonyaxenov/dreamkas-opencart-3 + + + + {{ entry_price }}]]> + + +
+ +
+ + ]]> +
+
+
+ + + db->query("DELETE FROM " . DB_PREFIX . "product_description WHERE product_id = '" . (int)$product_id . "'");]]> + db->query("UPDATE " . DB_PREFIX . "product SET dk_tax_type = '" . $this->db->escape($data['dk_tax_type']) . "' WHERE product_id = '" . (int)$product_id . "'"); + } + ]]> + + + + + + load->model('catalog/recurring');]]> + request->post['dk_tax_type'])) { + $data['dk_tax_type'] = $this->request->post['dk_tax_type']; + } elseif (!empty($product_info['dk_tax_type'])) { + $data['dk_tax_type'] = $product_info['dk_tax_type']; + } else { + $data['dk_tax_type'] = ''; + } + ]]> + + + + + + {{ column_action }}]]> + Статус фискализации]]> + + + {{ order.date_modified }}]]> + {{order.dk_status}}]]> + + + + + {{ text_affiliate }} + ]]> + + {{ entry_dk_status }} +{% if dk_status %} {{dk_status }} {%endif%} + + + + ]]> + + + + + + model_sale_order->getOrders($filter_data); + ]]> + + db->query("SELECT dk_status FROM " . DB_PREFIX . "dreamkas WHERE order_id = '" . (int)$result['order_id']. "'"); + ]]> + + + + $result['shipping_code'],]]> + !empty($dkquery->row['dk_status'])?$dkquery->row['dk_status']:'', + ]]> + + + language->get('date_format_short'), strtotime($order_info['date_added']));]]> + db->query("SELECT order_status_id FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int)$order_id . "'"); + $status = $query->row['order_status_id']; + + $query = $this->db->query("SELECT payment_code FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int)$order_id . "'"); + $payment_code = $query->row['payment_code']; + + if ($status == $this->config->get('dreamkas_paid_order') && in_array($payment_code, $this->config->get('dreamkas_payments_ids'))) { + + $query = $this->db->query("SELECT dk_id FROM " . DB_PREFIX . "dreamkas WHERE order_id = '" . (int)$order_id. "'"); + if(!empty($query->row['dk_id'])) { + $dk_id = $query->row['dk_id']; + $ch = curl_init(); + $access_token = $this->config->get('dreamkas_access_token'); + + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + "Content-Type: application/json", + "Authorization: Bearer $access_token" + )); + + curl_setopt($ch, CURLOPT_URL, "https://kabinet.dreamkas.ru/api/operations/".$dk_id); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); + curl_setopt($ch, CURLOPT_HEADER, FALSE); + $response = curl_exec($ch); + curl_close($ch); + + $response = json_decode($response, true); + + if((substr($response['status'], 0, 1)==4)) { + $this->log->write('Dreamkas debug: ' . json_encode($response)); + } elseif(!empty($response['data']['error'])) { + $this->log->write('Dreamkas debug: ' . json_encode($response['data']['error'])); + } else { + $dk_date = empty($response['createdAt'])?$response['completedAt']:$response['createdAt']; + $this->db->query("UPDATE `" . DB_PREFIX . "dreamkas` SET `order_id` = '" . (int)$order_id . "', `dk_id` = '".$response['id']."', `dk_date` ='".$dk_date."', `dk_status` = '" .$response['status']. "' WHERE order_id = '" . (int)$order_id. "'"); + } + } + } + + $query = $this->db->query("SELECT dk_status FROM " . DB_PREFIX . "dreamkas WHERE order_id = '" . (int)$order_id. "'"); + if(!empty($query->row['dk_status'])) { + $data['dk_status'] = $query->row['dk_status']; + } else { + $data['dk_status'] = ''; + } + $this->load->language('extension/module/dreamkas'); + $data['entry_dk_status'] = $this->language->get('entry_dk_status'); + ]]> + + + +
\ No newline at end of file diff --git a/dreamkas-opencart3.ocmod/upload/admin/controller/extension/module/dreamkas.php b/src/upload/admin/controller/extension/module/dreamkas.php similarity index 65% rename from dreamkas-opencart3.ocmod/upload/admin/controller/extension/module/dreamkas.php rename to src/upload/admin/controller/extension/module/dreamkas.php index be55078..47a846d 100644 --- a/dreamkas-opencart3.ocmod/upload/admin/controller/extension/module/dreamkas.php +++ b/src/upload/admin/controller/extension/module/dreamkas.php @@ -1,8 +1,10 @@ load->language('extension/module/dreamkas'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('setting/setting'); @@ -10,10 +12,21 @@ class ControllerExtensionModuleDreamkas extends Controller { if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { $this->model_setting_setting->editSetting('dreamkas', $this->request->post); $this->session->data['success'] = $this->language->get('text_success'); - //$this->response->redirect($this->url->link('extension/extension', 'user_token=' . $this->session->data['user_token'], 'SSL')); - $this->response->redirect($this->url->link('extension/module/dreamkas', 'user_token=' . $this->session->data['user_token'], 'SSL')); + //$this->response->redirect($this->url->link('extension/extension', 'token=' . $this->session->data['token'], 'SSL')); + $this->response->redirect($this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true)); } - + /* + if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { + if (!isset($this->request->get['module_id'])) { + $this->model_extension_module->addModule('dreamkas', $this->request->post); + } else { + $this->model_extension_module->editModule($this->request->get['module_id'], $this->request->post); + } + //$this->cache->delete('product'); + $this->session->data['success'] = $this->language->get('text_success'); + $this->response->redirect($this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', true)); + } + */ $data['heading_title'] = $this->language->get('heading_title'); $data['text_edit'] = $this->language->get('text_edit'); $data['text_enabled'] = $this->language->get('text_enabled'); @@ -37,7 +50,15 @@ class ControllerExtensionModuleDreamkas extends Controller { $data['text_tax_nds_18'] = $this->language->get('text_tax_nds_18'); $data['text_tax_nds_10_calculated'] = $this->language->get('text_tax_nds_10_calculated'); $data['text_tax_nds_18_calculated'] = $this->language->get('text_tax_nds_18_calculated'); - + /* + fnr($this); + $data['entry_name'] = $this->language->get('entry_name'); + $data['entry_limit'] = $this->language->get('entry_limit'); + $data['entry_image'] = $this->language->get('entry_image'); + $data['entry_width'] = $this->language->get('entry_width'); + $data['entry_height'] = $this->language->get('entry_height'); + $data['entry_status'] = $this->language->get('entry_status'); + */ $data['button_save'] = $this->language->get('button_save'); $data['button_cancel'] = $this->language->get('button_cancel'); @@ -66,14 +87,14 @@ class ControllerExtensionModuleDreamkas extends Controller { ); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_extension'), - 'href' => $this->url->link('extension/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true) + 'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true) ); $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('extension/module/dreamkas', 'user_token=' . $this->session->data['user_token'], true) ); $data['action'] = $this->url->link('extension/module/dreamkas', 'user_token=' . $this->session->data['user_token'], true); - $data['cancel'] = $this->url->link('extension/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true); + $data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true); if (isset($this->request->get['module_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) { $module_info = $this->model_extension_module->getModule($this->request->get['module_id']); @@ -124,14 +145,40 @@ class ControllerExtensionModuleDreamkas extends Controller { //Get payments $this->load->model('setting/extension'); - $paymenttypes = $this->model_setting_extension->getInstalled('payment'); + $extensions = $this->model_setting_extension->getInstalled('payment'); + foreach ($extensions as $key => $value) { + if (!is_file(DIR_APPLICATION . 'controller/extension/payment/' . $value . '.php') && !is_file(DIR_APPLICATION . 'controller/payment/' . $value . '.php')) { + $this->model_extension_extension->uninstall('payment', $value); + unset($extensions[$key]); + } + } - foreach ($paymenttypes as $type) { - $this->load->language('extension/payment/' . $type, 'extension'); - $data['paymenttypes'][] = array( - 'code' => $type, - 'name' => $this->language->get('extension')->get('heading_title'), - ); + $data['extensions'] = array(); + + // Compatibility code for old extension folders + $files = glob(DIR_APPLICATION . 'controller/{extension/payment,payment}/*.php', GLOB_BRACE); + if ($files) { + foreach ($files as $file) { + $extension = basename($file, '.php'); + $this->load->language('extension/payment/' . $extension); + $text_link = $this->language->get('text_' . $extension); + if ($text_link != 'text_' . $extension) { + $link = $this->language->get('text_' . $extension); + } else { + $link = ''; + } + $data['extensions'][] = array( + 'name' => $this->language->get('heading_title'), + 'code' => $extension, + 'link' => $link, + 'status' => $this->config->get($extension . '_status') ? $this->language->get('text_enabled') : $this->language->get('text_disabled'), + 'sort_order' => $this->config->get($extension . '_sort_order'), + 'install' => $this->url->link('extension/extension/payment/install', 'user_token=' . $this->session->data['user_token'] . '&extension=' . $extension, true), + 'uninstall' => $this->url->link('extension/extension/payment/uninstall', 'user_token=' . $this->session->data['user_token'] . '&extension=' . $extension, true), + 'installed' => in_array($extension, $extensions), + 'edit' => $this->url->link('extension/payment/' . $extension, 'user_token=' . $this->session->data['user_token'], true) + ); + } } if (isset($this->request->post['dreamkas_status'])) { @@ -145,7 +192,8 @@ class ControllerExtensionModuleDreamkas extends Controller { $this->response->setOutput($this->load->view('extension/module/dreamkas', $data)); } - protected function validate() { + protected function validate() + { if (!$this->user->hasPermission('modify', 'extension/module/dreamkas')) { $this->error['warning'] = $this->language->get('error_permission'); } @@ -161,7 +209,8 @@ class ControllerExtensionModuleDreamkas extends Controller { return !$this->error; } - public function install() { + public function install() + { $this->load->model('setting/event'); $this->model_setting_event->addEvent('dreamkas', 'catalog/model/checkout/order/addOrderHistory/after', 'extension/module/dreamkas'); $this->db->query(" @@ -173,12 +222,14 @@ class ControllerExtensionModuleDreamkas extends Controller { PRIMARY KEY (`order_id`) ) ENGINE=MyISAM DEFAULT COLLATE=utf8_general_ci "); - $this->db->query("ALTER TABLE `" . DB_PREFIX . "product` ADD `dk_tax_type` VARCHAR(50) NOT NULL DEFAULT ''"); + $this->db->query(" + ALTER TABLE `" . DB_PREFIX . "product` ADD `dk_tax_type` VARCHAR(50) NOT NULL DEFAULT '' + "); } - public function uninstall() { + public function uninstall() + { $this->load->model('setting/event'); - $this->db->query("ALTER TABLE `" . DB_PREFIX . "product` DROP `dk_tax_type`;"); $this->model_setting_event->deleteEvent('dreamkas'); } -} \ No newline at end of file +} diff --git a/dreamkas-opencart3.ocmod/upload/admin/language/ru-ru/extension/module/dreamkas.php b/src/upload/admin/language/ru-ru/extension/module/dreamkas.php similarity index 100% rename from dreamkas-opencart3.ocmod/upload/admin/language/ru-ru/extension/module/dreamkas.php rename to src/upload/admin/language/ru-ru/extension/module/dreamkas.php diff --git a/src/upload/admin/language/russian/module/dreamkas.php b/src/upload/admin/language/russian/module/dreamkas.php new file mode 100644 index 0000000..f4aa231 --- /dev/null +++ b/src/upload/admin/language/russian/module/dreamkas.php @@ -0,0 +1,39 @@ + + +
+ {% if error_warning %} +
+ {{ error_warning }} + +
+ {% endif %} +
+
+

+ {{text_edit}} +

+
+
+
+ +
+ +
+ + {% if error_access_token %} +
{{error_access_token}}
+ {% endif %} +
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+
+ {% for type in extensions %} +
+ +
+ {% endfor %} +
+
+
+ +
+ +
+ +
+
+ +
+
+
+
+ +{{ footer }} diff --git a/src/upload/catalog/controller/extension/module/dreamkas.php b/src/upload/catalog/controller/extension/module/dreamkas.php new file mode 100644 index 0000000..fa6f231 --- /dev/null +++ b/src/upload/catalog/controller/extension/module/dreamkas.php @@ -0,0 +1,123 @@ +session->data, $route, $data); + if (!empty($data[0])) { + $this->load->language('extension/module/dreamkas'); + $order_id = $data[0]; + $query = $this->db->query("SELECT order_status_id FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int) $order_id . "'"); + $status = $query->row['order_status_id']; + $query = $this->db->query("SELECT payment_code FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int) $order_id . "'"); + $payment_code = $query->row['payment_code']; + // fn_write_r($data, $status, $this->config->get('dreamkas_paid_order'), $payment_code, $this->config->get('dreamkas_payments_ids')); + // if (in_array($status, $this->config->get('sms_alert_processing_status'))) { + if ($status == $this->config->get('dreamkas_paid_order') && in_array($payment_code, $this->config->get('dreamkas_payments_ids'))) { + $this->load->model('checkout/order'); + $order_info = $this->model_checkout_order->getOrder($order_id); + $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int) $order_id . "'"); + $products = $query->rows; + $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int) $order_id . "' AND code = 'shipping' ORDER BY sort_order"); + $shipping = $query->rows; + $tax_type = $this->config->get('dreamkas_tax_type'); + $tax_sum = 0; + $items = array(); + foreach ($products as $product) { + $query = $this->db->query("SELECT dk_tax_type FROM " . DB_PREFIX . "product WHERE product_id = '" . (int) $product['product_id'] . "'"); + $dk_tax_type = $query->row; + $product_tax_type = empty($dk_tax_type['dk_tax_type']) ? $tax_type : $dk_tax_type['dk_tax_type']; + $items[] = array( + "name" => $product['name'], + "type" => "COUNTABLE", + "quantity" => $product['quantity'], + "price" => ($product['price'] + $product['tax']) * 100, + "priceSum" => ($product['total'] + $product['tax'] * $product['quantity']) * 100, + "tax" => "$product_tax_type", + "taxSum" => 0 // $product['tax'] * 100 * $product['quantity'] + ); + $tax_sum += $product['tax'] * $product['quantity']; + } + if (!empty($shipping)) { + $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int) $order_id . "' AND code = 'tax' ORDER BY sort_order"); + $tax_total = reset($query->rows); + if (!empty($tax_total['value'])) { + $shipping_tax = $tax_total['value'] - $tax_sum; + } else { + $shipping_tax = 0; + } + foreach ($shipping as $_shipping) { + if ($_shipping['value'] > 0) { + $items[] = array( + "name" => 'Доставка', + "type" => "COUNTABLE", + "quantity" => 1, + "price" => ($_shipping['value'] + $shipping_tax) * 100, + "priceSum" => ($_shipping['value'] + $shipping_tax) * 100, + "tax" => "$tax_type", + "taxSum" => 0 // $shipping_tax * 100 + ); + } + } + } + // fn_write_die($order_id, $tax_sum, $query, $items, $shipping); + $request = array( + "deviceId" => $this->config->get('dreamkas_device_id'), + "type" => "SALE", + "timeout" => 180, + "taxMode" => $this->config->get('dreamkas_tax_mode'), + "positions" => $items, + "payments" => array( + array( + "sum" => $order_info['total'] * 100, + "type" => "CASHLESS" + ) + ), + "attributes" => array( + "email" => $order_info['email'], + "phone" => $order_info['telephone'] // "+71239994499" + ), + "total" => array( + "priceSum" => $order_info['total'] * 100 + ) + ); + // fn_write_die($request, $products, $shipping, $order_info); + $ch = curl_init(); + $access_token = $this->config->get('dreamkas_access_token'); + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + "Content-Type: application/json", + "Authorization: Bearer " . $access_token + )); + curl_setopt($ch, CURLOPT_URL, "https://kabinet.dreamkas.ru/api/receipts"); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); + curl_setopt($ch, CURLOPT_HEADER, FALSE); + curl_setopt($ch, CURLOPT_POST, TRUE); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request)); + $response = curl_exec($ch); + curl_close($ch); + if (!empty($response)) { + $response = json_decode($response, true); + // $response = json_decode('{"id": "5956889136fdd7733f19cfe6","createdAt": "2017-06-20 12:01:47.990Z","status": "PENDING"}', true); + if ((substr($response['status'], 0, 1) == 4)) { + $this->log->write('Dreamkas debug: ' . json_encode($response)); + } else { + $dk_date = empty($response['createdAt']) ? $response['completedAt'] : $response['createdAt']; + $query = $this->db->query("SELECT order_id FROM " . DB_PREFIX . "dreamkas WHERE order_id = '" . (int) $order_id . "'"); + $exist_order_id = $query->rows; + if (empty($exist_order_id)) { + $this->db->query("INSERT INTO `" . DB_PREFIX . "dreamkas` SET `order_id` = '" . (int) $order_id . "', `dk_id` = '" . $response['id'] . "', `dk_date` ='" . $dk_date . "', `dk_status` = '" . $response['status'] . "'"); + } else { + $this->db->query("UPDATE `" . DB_PREFIX . "dreamkas` SET `order_id` = '" . (int) $order_id . "', `dk_id` = '" . $response['id'] . "', `dk_date` ='" . $dk_date . "', `dk_status` = '" . $response['status'] . "' WHERE order_id = '" . (int) $order_id . "'"); + } + } + } + } + } + } +}