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

Не изменяется статус модуля доставки.


Djeff78

Recommended Posts

Пытаюсь переделать модуль доставки ( С 3.0 на 2.3 ) https://boxberry.ru/business_solutions/it_solutions/1169729/

Контроллер и tpl в админке переделал - типо работает но вот проблемка - статус модуля на странице Дополнения/Доставка - не включается

Хотя при этом заходя в модуль статус стоит тот при котором сохранял - он в базе oc_setting есть и изменяется 0/1 - в зависимости что сохранить.

А вот на общей странице ни как - выключен постоянно и порядок сортировки так же не появляется там ( хотя тоже пишет все в базу )

Что не так?

Сам контроллер

Спойлер

<?php

use Boxberry\Client\Client;

if (!class_exists('Client')) {
    require_once DIR_SYSTEM . 'library/boxberry/autoload.php';
}
class ShippingBoxberry extends Controller
{	
    private $error = array();

    public $fields = [
        'text_enabled',
        'text_disabled',
        'text_api_token',
        'text_api_url',
		'text_widget_url',
        'text_status',
        'text_sort_order',
        'text_weight',
        'text_weight_min',
        'text_weight_max',
		'text_length_id',
		'text_weight_id',
        'button_save',
        'button_cancel',
        'text_height',
        'text_width',
        'text_depth',
        'text_size',
        'text_pickup_status',
        'text_pickup_prepaid_status',
        'text_courier_delivery_status',
        'text_courier_delivery_prepaid_status',
        'text_pickup_sucrh',
        'text_pickup_prepaid_sucrh',
        'text_courier_delivery_sucrh',
        'text_courier_delivery_prepaid_sucrh',
        'text_order_status',
		'text_sucrh',
		'text_sucrh_yes',
		'text_sucrh_no'
    ];

    public function index()
    {
        $this->load->language('extension/shipping/boxberry');
        $language = $this->language;
        $this->document->setTitle($this->language->get('heading_title'));
		$this->load->model('localisation/order_status');
        $this->load->model('setting/setting');

        $data['token'] = $this->session->data['token'];
        $data['route'] = "extension/shipping/boxberry";
		
		// Переменные
		$data['heading_title'] = $this->language->get('heading_title');
		$data['tab_general'] = $this->language->get('tab_general');
		$data['text_edit'] = $this->language->get('text_edit');
		$data['text_enabled'] = $this->language->get('text_enabled');
		$data['text_disabled'] = $this->language->get('text_disabled');

		//Ссылки для формы и кнопки "cancel"		
		$data['action'] = $this->url->link("extension/shipping/boxberry", 'token=' . $this->session->data['token'] . '&type=shipping', true);
        $data['cancel'] = $this->url->link("extension/extension", 'token=' . $this->session->data['token'] . '&type=shipping', true);

		//Переменная со статусом модуля
        if (isset($this->request->post['shipping_boxberry_status'])) {
			$data['shipping_boxberry_status'] = $this->request->post['shipping_boxberry_status'];
		} else {
			$data['shipping_boxberry_status'] = $this->config->get('shipping_boxberry_status');
		}
		
		
        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
            $this->load->model('localisation/weight_class');
            $client = new Client();
            $client->setKey($this->request->post['shipping_boxberry_api_token']);
            $client->setApiUrl($this->request->post['shipping_boxberry_api_url']);
            $keyIntegration = $client->getKeyIntegration();
            try {
                $response = $client->execute($keyIntegration);
                $this->request->post['shipping_boxberry_widget_key'] = $response->getKeyIntegration();
                $this->model_setting_setting->editSetting('shipping_boxberry', $this->request->post);
                $this->session->data['success'] = $language->get('text_success');
				$this->response->redirect($this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=shipping', true));
            } 
			catch (Exception $e) {
                if ($e->getMessage()=='Ошибка обращения к сервису доставки Boxberry'){
                    $this->error['warning'] = 'Указан неверный URL API сервиса';
                } elseif ($e->getMessage()=='Нет доступа'){
                    $this->error['warning'] = 'Указан неверный API-токен';
                } elseif ($e->getMessage()=='Ваша учетная запись заблокирована'){
                    $this->error['warning'] = 'Учетная запись с данным API-токеном заблокирована';
                }

            }
        }
        foreach ($this->fields as $field) {
            $data[$field] = $language->get($field);
        }
        $data['error_warning'] = isset($this->error['warning']) ? $this->error['warning'] : '';
        $data['breadcrumbs'] = [
            [
                'text' => $language->get('text_home'),
                'href' => $this->url->link("common/dashboard", 'token=' . $this->session->data['token'] . '&type=shipping', true)
            ],
            [
                'text' => $language->get('text_shipping'),
                'href' => $this->url->link("extension/extension",
                'token=' . $this->session->data['token'] . '&type=shipping', true)
            ],
            [
                'text' => $language->get('heading_title'),
                'href' => $this->url->link("extension/shipping/boxberry", 'token=' . $this->session->data['token'] . '&type=shipping', true)
            ]
        ];
				
		
        $this->fields = [
            ['name' => 'shipping_boxberry_api_url', 'default' => isset($this->request->post['shipping_boxberry_api_url']) ? $this->request->post['shipping_boxberry_api_url'] : 'https://api.boxberry.de/json.php'],
            ['name' => 'shipping_boxberry_widget_url', 'default' =>  isset($this->request->post['shipping_boxberry_widget_url']) ? $this->request->post['shipping_boxberry_widget_url'] :'https://points.boxberry.de/js/boxberry.js'],
            ['name' => 'shipping_boxberry_api_token', 'default' => isset($this->request->post['shipping_boxberry_api_token']) ? $this->request->post['shipping_boxberry_api_token'] : ''],
            ['name' => 'shipping_boxberry_sort_order', 'default' =>isset($this->request->post['shipping_boxberry_sort_order']) ? $this->request->post['shipping_boxberry_sort_order'] : ''],
            ['name' => 'shipping_boxberry_weight', 'default' => isset($this->request->post['shipping_boxberry_weight']) ? $this->request->post['shipping_boxberry_weight'] : ''],
            ['name' => 'shipping_boxberry_weight_min', 'default' => isset($this->request->post['shipping_boxberry_weight_min']) ? $this->request->post['shipping_boxberry_weight_min'] : ''],
            ['name' => 'shipping_boxberry_weight_max', 'default' => isset($this->request->post['shipping_boxberry_weight_max']) ? $this->request->post['shipping_boxberry_weight_max'] : ''],
            ['name' => 'shipping_boxberry_size', 'default' => isset($this->request->post['shipping_boxberry_size']) ? $this->request->post['shipping_boxberry_size'] : ''],
            ['name' => 'shipping_boxberry_width', 'default' => isset($this->request->post['shipping_boxberry_width']) ? $this->request->post['shipping_boxberry_width'] : ''],
            ['name' => 'shipping_boxberry_height', 'default' => isset($this->request->post['shipping_boxberry_height']) ? $this->request->post['shipping_boxberry_height'] : ''],
            ['name' => 'shipping_boxberry_depth', 'default' => isset($this->request->post['shipping_boxberry_depth']) ? $this->request->post['shipping_boxberry_depth'] : ''],
            ['name' => 'shipping_boxberry_order_status', 'default' => isset($this->request->post['shipping_boxberry_order_status']) ? $this->request->post['shipping_boxberry_order_status'] : ''],
            ['name' => 'shipping_boxberry_weight_class_id', 'default' => isset($this->request->post['shipping_boxberry_weight_class_id']) ? $this->request->post['shipping_boxberry_weight_class_id'] :'' ],
            ['name' => 'shipping_boxberry_length_class_id', 'default' => isset($this->request->post['shipping_boxberry_length_class_id']) ? $this->request->post['shipping_boxberry_length_class_id'] :'' ],
            ['name' => 'shipping_boxberry_pickup_status', 'default' => isset($this->request->post['shipping_boxberry_pickup_status']) ? $this->request->post['shipping_boxberry_pickup_status'] : ''],
            ['name' => 'shipping_boxberry_pickup_prepaid_status', 'default' => isset($this->request->post['shipping_boxberry_pickup_prepaid_status']) ? $this->request->post['shipping_boxberry_pickup_prepaid_status'] : ''],
            ['name' => 'shipping_boxberry_courier_delivery_status', 'default' => isset($this->request->post['shipping_boxberry_courier_delivery_status']) ? $this->request->post['shipping_boxberry_courier_delivery_status'] : ''],
            ['name' => 'shipping_boxberry_courier_delivery_prepaid_status', 'default' => isset($this->request->post['shipping_boxberry_courier_delivery_prepaid_status']) ? $this->request->post['shipping_boxberry_courier_delivery_prepaid_status'] : ''],
            ['name' => 'shipping_boxberry_pickup_sucrh', 'default' =>isset($this->request->post['shipping_boxberry_pickup_sucrh']) ? $this->request->post['shipping_boxberry_pickup_sucrh'] : '1'],
            ['name' => 'shipping_boxberry_pickup_prepaid_sucrh', 'default' => isset($this->request->post['shipping_boxberry_pickup_prepaid_sucrh']) ? $this->request->post['shipping_boxberry_pickup_prepaid_sucrh'] : '1'],
            ['name' => 'shipping_boxberry_courier_delivery_sucrh', 'default' => isset($this->request->post['shipping_boxberry_courier_delivery_sucrh']) ? $this->request->post['shipping_boxberry_courier_delivery_sucrh'] : '1'],
            ['name' => 'shipping_boxberry_courier_delivery_prepaid_sucrh', 'default' => isset($this->request->post['shipping_boxberry_courier_delivery_prepaid_sucrh']) ? $this->request->post['shipping_boxberry_courier_delivery_prepaid_sucrh'] : '1'],
            ['name' => 'shipping_boxberry_pickup_name', 'default' => isset($this->request->post['shipping_boxberry_pickup_name']) ? $this->request->post['shipping_boxberry_pickup_name'] : $language->get('text_pickup_description')],
            ['name' => 'shipping_boxberry_pickup_prepaid_name', 'default' => isset($this->request->post['shipping_boxberry_pickup_prepaid_name']) ? $this->request->post['shipping_boxberry_pickup_prepaid_name'] : $language->get('text_pickup_prepaid_description')],
            ['name' => 'shipping_boxberry_courier_delivery_name', 'default' => isset($this->request->post['shipping_boxberry_courier_delivery_name']) ? $this->request->post['shipping_boxberry_courier_delivery_name'] : $language->get('text_courier_delivery_description')],
            ['name' => 'shipping_boxberry_courier_delivery_prepaid_name', 'default' => isset($this->request->post['shipping_boxberry_courier_delivery_prepaid_name']) ? $this->request->post['shipping_boxberry_courier_delivery_prepaid_name'] : $language->get('text_courier_delivery_prepaid_description')]

        ];
				
        $config = $this->config;
        foreach ($this->fields as $field) {
            $fieldName = $field['name'];
            $configValue = $config->get($fieldName);
            $data[$fieldName] = isset($this->request->post[$fieldName]) ? $this->request->post[$fieldName] : null;
            $data[$fieldName] = $data[$fieldName] === null ? $configValue : null;
            $data[$fieldName] = $data[$fieldName] === null ? $field['default'] : $data[$fieldName];
        }
        $this->load->model('localisation/weight_class');
        $this->load->model('localisation/length_class');
        $data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');
        $data['weight_ids'] = $this->model_localisation_weight_class->getWeightClasses();
        $data['length_ids'] = $this->model_localisation_length_class->getLengthClasses();

        $this->response->setOutput($this->load->view("extension/shipping/boxberry", $data));
    }
	
	
	//Обязательный метод в контроллере, он запускается для проверки разрешено ли пользователю изменять настройки данного модуля
    protected function validate()
    {
        if (!$this->user->hasPermission('modify', "extension/shipping/boxberry")) {
            $this->error['warning'] = $this->language->get('error_permission');
        }
        if (!$this->request->post['shipping_boxberry_api_token']) {
            $this->error['warning'] = $this->language->get('error_api_key');
        }
        if (!$this->request->post['shipping_boxberry_api_url']) {
            $this->error['warning'] = 'Не указан Url для API сервиса!';
        }
        if (!$this->request->post['shipping_boxberry_weight']) {
            $this->error['warning'] = 'Не указан вес по умолчанию!';
        }
        if (!$this->request->post['shipping_boxberry_widget_url']) {
            $this->error['warning'] = 'Не указан Url для виджета';
        }
        return !$this->error;
    }

    public function install()
    {
        $this->load = $this->load;
        $this->load->model('user/user_group');
        $this->model_user_user_group->addPermission($this->user->getGroupId(), 'access', 'sale/boxberry');
        $this->load->model('extension/event');
        $this->model_extension_event->deleteEvent('boxberry_order_status_edit');
        $this->model_extension_event->addEvent('boxberry_order_status_edit', 'catalog/model/checkout/order/addOrderHistory/after', 'event/boxberry/addOrderHistory', 1, 1);

        $this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "boxberry_cities` (
      `code` VARCHAR(128) NOT NULL,
      `name` VARCHAR(128),
      `region` VARCHAR(128),
      `data` text,
      PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;");

        $this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "boxberry_deliveries` (
      `order_id` int(10) NOT NULL,      
      `im_id` VARCHAR(45),
      `label` VARCHAR(100),
      `boxberry_to_point` VARCHAR(15),
      `address` VARCHAR(100),
      `error` VARCHAR(255),
      PRIMARY KEY (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;");

        $this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "boxberry_points` (
      `code` VARCHAR(128) NOT NULL,
      `city_code` VARCHAR(128),
      `data` text,
      `expired` datetime,
      `prepaid` tinyint(1),
      PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;");

        $this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "boxberry_zips` (
      `zip` VARCHAR(15) NOT NULL,
      `expired` datetime,
      PRIMARY KEY (`zip`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;");

        $this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "boxberry_expired` (
      `table` VARCHAR(128) NOT NULL,
      `expired` datetime,
      PRIMARY KEY (`table`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;");
    }

    public function uninstall()
    {
        $this->load->model('user/user_group');
        $this->model_user_user_group->removePermission($this->user->getGroupId(), 'access', 'sale/boxberry');
        $this->load->model('extension/event');
        $this->model_extension_event->deleteEvent('boxberry_order_status_edit');

        $db = $this->db;
        $db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "boxberry_cities`;");
        $db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "boxberry_deliveries`;");
        $db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "boxberry_points`;");
        $db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "boxberry_zips`;");
        $db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "boxberry_expired`;");
    }
}

class ControllerExtensionShippingBoxberry extends ShippingBoxberry
{
}

class ControllerShippingBoxberry extends ShippingBoxberry
{
}

?>

 

 

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


Менял

if (isset($this->request->post['shipping_boxberry_status'])) {
            $data['shipping_boxberry_status'] = $this->request->post['shipping_boxberry_status'];
        } else {
            $data['shipping_boxberry_status'] = $this->config->get('shipping_boxberry_status');
        }

На

if (isset($this->request->post['boxberry_status'])) {
            $data['boxberry_status'] = $this->request->post['boxberry_status'];
        } else {
            $data['boxberry_status'] = $this->config->get('boxberry_status');
        }

Ну и в tpl соответственно на <?php if ($boxberry_status) { ?>

 

Он тогда в базе oc_setting не создает его

( я специально откат делал ) Якобы с 0 ставлю модуль.

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


.tpl

<select name="boxberry_status" class="form-control">
       <?php if ($boxberry_status) { ?>
           <option value="1" selected="selected"><?php echo $text_enabled; ?></option>
           <option value="0"><?php echo $text_disabled; ?></option>
           <?php } else { ?>
           <option value="1"><?php echo $text_enabled; ?></option>
           <option value="0" selected="selected"><?php echo $text_disabled; ?></option>
           <?php } ?>
</select>

.php

		//Переменная со статусом модуля
        if (isset($this->request->post['boxberry_status'])) {
			$data['boxberry_status'] = $this->request->post['boxberry_status'];
		} else {
			$data['boxberry_status'] = $this->config->get('boxberry_status');
		}

Вот так пробую - вообще не создает записи в базе

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


Не знаю на сколько это правильно - но заработало вот так

После

$this->model_setting_setting->editSetting('shipping_boxberry', $this->request->post);

Добавил еще

$this->model_setting_setting->editSetting('boxberry', $this->request->post);

 

Наверное правильнее вообще во всем контроллере избавится от shipping_

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


Да и в остальных убрал - как выше ( ну не совсем в остальных ) Только у статуса модуля убрал ее.

Он вообще был вот так изначально

 $this->fields = [
            ['name' => 'shipping_boxberry_api_url', 'default' => isset($this->request->post['shipping_boxberry_api_url']) ? $this->request->post['shipping_boxberry_api_url'] : 'https://api.boxberry.de/json.php'],
            ['name' => 'shipping_boxberry_widget_url', 'default' =>  isset($this->request->post['shipping_boxberry_widget_url']) ? $this->request->post['shipping_boxberry_widget_url'] :'https://points.boxberry.de/js/boxberry.js'],
            ['name' => 'shipping_boxberry_api_token', 'default' => isset($this->request->post['shipping_boxberry_api_token']) ? $this->request->post['shipping_boxberry_api_token'] : ''],
............................................................. и так далее - здесь и был статус

Я его вынес отдельно.

И в нем убрал shipping_ 

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


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

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

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

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

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

Вхід

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

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

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

Important Information

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