first commit

This commit is contained in:
2024-11-11 18:46:54 +01:00
commit a630d17338
25634 changed files with 4923715 additions and 0 deletions

Binary file not shown.

View File

@@ -0,0 +1,439 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
use x13allegro\Api\XAllegroApi;
use x13allegro\Api\DataProvider\AfterSaleServicesProvider;
use x13allegro\Api\DataProvider\MarketplacesProvider;
use x13allegro\Api\DataProvider\ResponsiblePersonsProvider;
use x13allegro\Api\Model\Marketplace\Enum\Marketplace;
use x13allegro\Exception\ModuleException;
final class AdminXAllegroAccountsController extends XAllegroController
{
/** @var XAllegroAccount */
public $object;
public function __construct()
{
$this->table = 'xallegro_account';
$this->identifier = 'id_xallegro_account';
$this->className = 'XAllegroAccount';
$this->multiple_fieldsets = true;
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroAccounts'));
$this->fields_list = array(
'id_xallegro_account' => array(
'title' => $this->l('ID'),
'align' => 'center',
'width' => 50,
'class' => 'fixed-width-xs'
),
'username' => array(
'title' => $this->l('Nazwa użytkownika'),
'width' => 300
),
'default' => array(
'title' => $this->l('Domyślny'),
'active' => 'default',
'width' => 100,
'class' => 'fixed-width-sm',
'align' => 'center',
'type' => 'bool'
),
'active' => array(
'title' => $this->l('Aktywny'),
'active' => 'active',
'width' => 100,
'class' => 'fixed-width-sm',
'align' => 'center',
'type' => 'bool'
),
'sandbox' => array(
'title' => $this->l('Sandbox'),
'width' => 100,
'class' => 'fixed-width-sm',
'align' => 'center',
'type' => 'bool',
'icon' => array(
'0' => array('class' => 'icon-remove'),
'1' => array('class' => 'icon-check')
),
),
'base_marketplace' => array(
'title' => $this->l('Rynek bazowy'),
'width' => 100,
'class' => 'fixed-width-xl',
'callback' => 'printMarketplace',
'search' => false
),
'expire_refresh' => array(
'title' => $this->l('Ważność autoryzacji'),
'callback' => 'printExpire',
'search' => false
)
);
$this->tpl_folder = 'x_allegro_accounts/';
if (Tools::isSubmit('cancelAuthorization')) {
(new XAllegroAccount(Tools::getValue('id_xallegro_account')))->resetAuthorization(false);
}
}
public function initPageHeaderToolbar()
{
if (empty($this->display))
{
$this->page_header_toolbar_btn['allegro_current'] = array(
'href' => $this->context->link->getAdminLink('AdminXAllegroAccounts') . '&addxallegro_account',
'desc' => $this->l('Dodaj nowe konto'),
'icon' => 'process-icon-new'
);
}
parent::initPageHeaderToolbar();
}
public function renderList()
{
$this->addRowAction('xAuthorize');
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->specificConfirmDelete = $this->l('Usunąć wybrane konto?') . '\n\n' .
$this->l('Spowoduje to usunięcie wszystkich powiązań ofert do produktów dla wybranego konta!');
if (!Tools::usingSecureMode() && Configuration::get('PS_SSL_ENABLED'))
{
$href = 'https://' . Tools::safeOutput(Tools::getServerName()) . Tools::safeOutput($_SERVER['REQUEST_URI']);
$this->errors[] = '<b>' . $this->l('Uwaga! SSL jest włączony.') . '</b><br>' .
$this->l('Aby poprawnie autoryzować konto Allegro zaloguj się do trybu bezpiecznego (https://)') .
': <a href="' . $href . '">' . $href .'</a>';
}
return parent::renderList();
}
public function renderForm()
{
$this->fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Dane integracji konta Allegro'),
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Nazwa użytkownika'),
'desc' => $this->l('Uzupełnij jedną z poniższych wartości') . ':'
. '<br> - ' . $this->l('ID konta Allegro')
. '<br> - ' . $this->l('login konta Allegro')
. '<br> - ' . $this->l('email przypisany do konta Allegro'),
'name' => 'username',
'size' => 30,
'class' => 'fixed-width-xxl',
'required' => true
),
array(
'type' => 'switch',
'label' => $this->l('Sandbox'),
'name' => 'sandbox',
'required' => false,
'class' => 't',
'is_bool' => true,
'values' => array(
array(
'id' => 'sandbox_on',
'value' => 1,
'label' => $this->l('Tak')
),
array(
'id' => 'sandbox_off',
'value' => 0,
'label' => $this->l('Nie')
)
),
'desc' => $this->l('Portal testowy Allegro')
),
array(
'type' => 'switch',
'label' => $this->l('Domyślne konto'),
'name' => 'default',
'required' => false,
'class' => 't',
'is_bool' => true,
'values' => array(
array(
'id' => 'default_on',
'value' => 1,
'label' => $this->l('Tak')
),
array(
'id' => 'default_off',
'value' => 0,
'label' => $this->l('Nie')
)
),
'desc' => $this->l('Automatycznie wybierane podczas wystawiania przedmiotów')
),
array(
'type' => 'switch',
'label' => $this->l('Aktywne konto'),
'name' => 'active',
'class' => 't',
'is_bool' => true,
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Tak')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('Nie')
)
),
'default_value' => 1
)
),
'submit' => array(
'title' => $this->l('Zapisz')
)
);
return parent::renderForm();
}
public function postProcess()
{
$allegroAccountId = (int)Tools::getValue($this->identifier);
$responsiblePerson = Tools::getValue('responsible_person');
if (Tools::isSubmit('submitAdd' . $this->table) && $allegroAccountId && !empty($responsiblePerson)) {
$configurationAccount = new XAllegroConfigurationAccount($allegroAccountId);
$configurationAccount->updateValue('RESPONSIBLE_PERSON_DEFAULT_ID', $responsiblePerson);
}
return parent::postProcess();
}
public function printExpire($id, $row)
{
$now = new DateTime();
$expire = new DateTime($row['expire_refresh']);
$interval = $now->diff($expire);
$days = (int)$interval->format('%R%a');
$hours = (int)$interval->format('%R%h');
if (($days < 1 && $hours < 1) || empty($row['access_token']) || empty($row['refresh_token'])) {
return '<span class="badge badge-danger">' . $this->l('autoryzuj konto') . '</span>';
}
else if ($days < 14) {
return '<span class="badge badge-warning">' . $this->l('niedługo wygaśnie') . '</span>';
}
return '<span class="badge badge-success">' . $this->l('zautoryzowane') . '</span>';
}
public function printMarketplace($id, $row)
{
if ($row['base_marketplace']) {
try {
return Marketplace::from($row['base_marketplace'])->getValueTranslated();
}
catch (\UnexpectedValueException $ex) {
return $this->l('Nieobsługiwany rynek') . ' (' . $row['base_marketplace'] . ')';
}
}
return '';
}
public function displayXAuthorizeLink($token = null, $id, $name = null)
{
$tpl = $this->context->smarty->createTemplate($this->module->getLocalPath() . 'views/templates/admin/' . $this->tpl_folder . 'helpers/list/action_authorize.tpl');
$tpl->assign(array(
'href' => $this->context->link->getAdminLink('AdminXAllegroAccounts') . '&authorize&id_xallegro_account=' . $id,
'action' => $this->l('Autoryzuj'),
'title' => $this->l('Autoryzacja użytkownika'),
'id_account' => $id
));
return $tpl->fetch();
}
public function ajaxProcessAuthorizeApplication()
{
$account = new XAllegroAccount(Tools::getValue('id_account'));
if (!Validate::isLoadedObject($account) || !$account->active) {
die(json_encode(array(
'success' => false,
'text' => $this->l('Autoryzacja konta Allegro: Konto nieaktywne.')
)));
}
try {
$result = (new XAllegroApi($account, false))->auth()->getDeviceCode();
$account->setDeviceCode($result);
$tpl = $this->context->smarty->createTemplate($this->module->getLocalPath() . 'views/templates/admin/' . $this->tpl_folder . 'helpers/list/action_authorize_modal.tpl');
$tpl->assign(array(
'accountAuthUrl' => $result->verification_uri_complete,
'redirectUrl' => $this->context->link->getAdminLink('AdminXAllegroAccounts'),
'configurationUrl' => $this->context->link->getAdminLink('AdminXAllegroConfiguration') . '#xallegro_configuration_fieldset_advanced_settings',
'id_account' => $account->id
));
$html = $tpl->fetch();
}
catch (Exception $ex) {
die(json_encode(array(
'success' => false,
'text' => (string)$ex
)));
}
die(json_encode(array(
'success' => true,
'html' => $html,
'interval' => $result->interval,
'username' => $account->username
)));
}
public function ajaxProcessAuthorizeApplicationCheck()
{
$account = new XAllegroAccount(Tools::getValue('id_account'));
if (!Validate::isLoadedObject($account) || !$account->active) {
die(json_encode([
'success' => false,
'text' => $this->l('Autoryzacja konta Allegro: Konto nieaktywne.')
]));
}
try {
$result = (new XAllegroApi($account, false))->auth()->authorizeDevice();
$clear = new StdClass();
$clear->user_code = null;
$clear->device_code = null;
$account = $account->setDeviceCode($clear)
->setRefreshToken($result);
$me = (new XAllegroApi($account))->account()->me();
$account = $account->setBaseMarketplace($me->baseMarketplace->id);
$accountIdentity = false;
if ($account->username == $me->id
|| $account->username == $me->login
|| $account->username == $me->email
) {
$accountIdentity = true;
}
// block authorization when typed username does not match Allegro account
if (!$accountIdentity) {
$account->resetAuthorization(false);
throw new ModuleException($this->l("Wpisana nazwa użytkownika ($account->username) nie jest tożsama ze zautoryzowanym kontem Allegro"));
}
// block authorization when Marketplace is not supported by module
//if (!Marketplace::isValid($me->baseMarketplace->id)) {
if ($me->baseMarketplace->id != XAllegroApi::MARKETPLACE_PL) {
$account->resetAuthorization(false);
throw new ModuleException($this->l("Nieobsługiwany rynek ({$me->baseMarketplace->id})"));
}
}
catch (Exception $ex) {
if ($ex->getCode() == 400) {
die(json_encode([
'success' => true,
'process' => true
]));
}
die(json_encode([
'success' => false,
'text' => (string)$ex
]));
}
$marketplacesProvider = new MarketplacesProvider($account->base_marketplace);
$configurationForm = false;
// if id_language is empty then authorization is performed for the first time
if (!$account->id_language) {
$emptyOption = [
'id' => '',
'name' => $this->l('-- wybierz --')
];
$afterSaleServices = [];
$responsiblePersons = [];
$responsiblePersons[] = $emptyOption;
$shopLanguages[] = $emptyOption;
foreach (Language::getLanguages() as $language) {
$marketplaceLanguage = $marketplacesProvider->getMarketplaceLanguage();
$shopLanguages[] = [
'id' => $language['id_lang'],
'name' => $language['name'],
'isMarketplaceLanguage' => (Validate::isLoadedObject($marketplaceLanguage) && $language['id_lang'] == $marketplaceLanguage->id)
];
}
try {
$api = new XAllegroApi($account);
$afterSaleServicesProvider = new AfterSaleServicesProvider($api);
$responsiblePersonsProvider = new ResponsiblePersonsProvider($api);
foreach ($afterSaleServicesProvider->getAllServices() as $afterSaleServiceGroup => $afterSaleService) {
$afterSaleServices[$afterSaleServiceGroup][] = $emptyOption;
foreach ($afterSaleService as $service) {
$afterSaleServices[$afterSaleServiceGroup][] = (array)$service;
}
}
foreach ($responsiblePersonsProvider->getResponsiblePersons() as $responsiblePerson) {
$responsiblePersons[] = [
'id' => $responsiblePerson->id,
'name' => $responsiblePerson->name
];
}
}
catch (Exception $ex) {}
$tpl = $this->context->smarty->createTemplate($this->module->getLocalPath() . 'views/templates/admin/' . $this->tpl_folder . 'helpers/list/action_authorize_configuration_modal.tpl');
$tpl->assign([
'formAction' => $this->context->link->getAdminLink('AdminXAllegroAccounts'),
'cancelAction' => $this->context->link->getAdminLink('AdminXAllegroAccounts') . '&id_xallegro_account=' . $account->id . '&cancelAuthorization',
'accountId' => $account->id,
'shopLanguages' => $shopLanguages,
'afterSaleServices' => $afterSaleServices,
'responsiblePersons' => $responsiblePersons
]);
$configurationForm = $tpl->fetch();
}
// return "process" false when done
die(json_encode([
'success' => true,
'process' => false,
'baseMarketplace' => $marketplacesProvider->getMarketplaceName(),
'configurationForm' => $configurationForm
]));
}
}

View File

@@ -0,0 +1,799 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
use x13allegro\Api\DataProvider\CategoriesProvider;
use x13allegro\Api\DataProvider\CategoriesParametersProvider;
use x13allegro\Form\CategoryParameters\CategoryParameters;
use x13allegro\Form\CategoryParameters\ParametersForm;
use x13allegro\Form\CategoryParameters\ParametersMapForm;
use x13allegro\Repository\PrestaShop\ManufacturerRepository;
use x13allegro\Repository\PrestaShop\ProductAttributeRepository;
use x13allegro\Repository\PrestaShop\ProductFeatureRepository;
final class AdminXAllegroAssocCategoriesController extends XAllegroController
{
protected $allegroAutoLogin = true;
private $allegroCategory;
private $allegroCategoryPath = array(null);
private $allegroCategoryNotExists = false;
/** @var XAllegroCategory */
public $object;
/** @var CategoriesProvider */
private $categoriesProvider;
/** @var CategoriesParametersProvider */
private $categoriesParametersProvider;
public function __construct()
{
$this->table = 'xallegro_category';
$this->identifier = 'id_xallegro_category';
$this->className = 'XAllegroCategory';
$this->multiple_fieldsets = true;
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroAssocCategories'));
$this->tpl_folder = 'x_allegro_categories/';
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?'),
'icon' => 'icon-trash'
)
);
}
public function init()
{
parent::init();
if (!$this->allegroApi) {
return;
}
$this->loadObject(true);
$this->categoriesProvider = new CategoriesProvider($this->allegroApi);
$this->categoriesParametersProvider = new CategoriesParametersProvider($this->allegroApi);
$is_mapped = false;
$categoryId = Tools::getValue('id_allegro_category');
if (is_array($categoryId)) {
$categoryId = end($categoryId);
}
if (!$categoryId && Validate::isLoadedObject($this->object)) {
$categoryId = $this->object->id_allegro_category;
if ($categoryId) {
$is_mapped = true;
}
}
if ($categoryId && !$this->ajax) {
$this->allegroCategory = $this->categoriesProvider->getCategoryDetails($categoryId);
if ($this->allegroCategory) {
// Inject allegroCategoryId to object
$this->object->id_allegro_category = $this->allegroCategory->id;
$this->allegroCategoryPath = array();
foreach ($this->categoriesProvider->getCategoriesPath($this->allegroCategory->id) as $id => $list) {
$this->allegroCategoryPath[] = array(
'id' => $id,
'name' => $this->categoriesProvider->getCategoryDetails($id)->name,
'list' => $list
);
}
}
else if ($is_mapped) {
$this->allegroCategoryNotExists = true;
}
}
}
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
$this->addJqueryPlugin('autocomplete');
$this->addJqueryUI('ui.sortable');
$this->addCSS($this->module->getPathUri() . 'views/js/select2/css/select2.min.css');
$this->addJS($this->module->getPathUri() . 'views/js/select2/js/select2.full.min.js');
}
public function initToolbar()
{
if ($this->display == 'add' || $this->display == 'edit') {
$this->toolbar_btn['save_and_stay'] = array(
'href' => self::$currentIndex . '&token=' . $this->token,
'desc' => $this->l('Zapisz i zostań'),
'class' => 'process-icon-save-and-stay '
);
}
parent::initToolbar();
}
public function renderList()
{
if (Tools::getValue('controller') == 'AdminXAllegroAssocCategories' && empty($this->errors) && empty($this->confirmations)) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroAssoc'));
}
$this->initToolbar();
if (method_exists($this, 'initPageHeaderToolbar')) {
$this->initPageHeaderToolbar();
}
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->fields_list = array(
'id_xallegro_category' => array(
'title' => $this->l('ID'),
'align' => 'center',
'width' => 50,
'class' => 'fixed-width-xs'
),
'name' => array(
'title' => $this->l('Nazwa powiązania'),
'search' => false,
),
'path' => array(
'title' => $this->l('Kategoria Allegro'),
'search' => false,
'filter' => false
),
'active' => array(
'title' => $this->l('Aktywny'),
'width' => 70,
'align' => 'center',
'active' => 'active',
'type' => 'bool',
'class' => 'fixed-width-sm'
),
'id_categories' => array(
'title' => $this->l('Ilość przypisanych kategorii'),
'align' => 'center',
'search' => false,
'filter' => false,
'callback_object' => $this,
'callback' => 'countCategories',
),
'categories' => array(
'title' => $this->l('Kategorie'),
'align' => 'center',
'search' => false,
'callback_object' => $this,
'callback' => 'renderCategories',
'tmpTableFilter' => true,
'filter_key' => 'categories'
)
);
return parent::renderList();
}
public function countCategories($value, $row)
{
return (!empty($row['id_categories']) ? count(explode(',', $row['id_categories'])) : '--');
}
public function renderCategories($value, $row)
{
if (empty($row['id_categories'])) {
return '';
}
$categories = Db::getInstance()->executeS('
SELECT cl.`name` category
FROM `'._DB_PREFIX_.'category_lang` cl
WHERE cl.`id_category` IN('.$row['id_categories'].')
AND cl.`id_lang` = '.$this->context->language->id.'
AND `id_shop` = '.$this->context->shop->id);
if (!$categories) {
return '';
}
$categories = array_map(function ($row) {
return $row['category'];
}, $categories);
$suffix = '';
if (count($categories) > 2) {
$suffix = ' [...]';
$categories = array_splice($categories, 0, 2);
}
return implode(', ', $categories).$suffix;
}
public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
{
$this->_select = 'a.id_allegro_category as categories';
// if (Tools::isSubmit('submitFilter'.$this->list_id) && !Tools::isSubmit('submitResetxallegro_category')) {
// if (Tools::getValue('xallegro_categoryFilter_name')) {
// $this->_where = 'AND a.name LIKE "%'.pSQL(Tools::getValue('xallegro_categoryFilter_name')).'%"';
// }
// }
parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);
}
public function renderForm()
{
if (!Validate::isLoadedObject($this->object)) {
$this->warnings[] = $this->l('Musisz zapisać tę ścieżkę kategorii przed mapowaniem parametrów i tagów.');
}
$allegroCategories = $this->categoriesProvider->getCategoriesList();
foreach ($this->allegroCategoryPath as $category) {
if (isset($category['list'])) {
$allegroCategories = array_merge($allegroCategories, $category['list']);
}
}
$this->fields_form[]['form'] = array(
'legend' => array(
'title' => $this->l('Kategoria Allegro')
),
'warning' => ($this->allegroCategoryNotExists ? $this->l('Zmapowana kategoria Allegro już nie istnieje.') : ''),
'input' => array(
array(
'type' => 'category',
'name' => 'id_allegro_category',
'categories' => $allegroCategories,
'path' => $this->allegroCategoryPath
)
),
'submit' => array(
'title' => $this->l('Zapisz'),
),
'buttons' => array(
'save-and-stay' => array(
'title' => $this->l('Zapisz i zostań'),
'name' => 'submitAdd' . $this->table . 'AndStay',
'type' => 'submit',
'class' => 'btn btn-default pull-right',
'icon' => 'process-icon-save'
)
)
);
$existingAssociations[] = [
'id' => 0,
'name' => '-- Wybierz kategorie --'
];
if (Validate::isLoadedObject($this->object)) {
foreach (XAllegroCategory::getExistingAssociations() as $association) {
if ($association['id_xallegro_category'] != $this->object->id) {
$existingAssociations[] = [
'id' => $association['id_xallegro_category'],
'name' => $association['id_xallegro_category'] .
(!empty($association['name']) ? ' (' . $association['name'] . ')' : '') . ': ' . $association['path']
];
}
}
}
$this->fields_form[]['form'] = array(
'legend' => array(
'title' => $this->l('Ustawienia podstawowe')
),
'input' => array(
array(
'type' => 'text',
'name' => 'name',
'label' => $this->l('Nazwa pomocnicza powiązania'),
'class' => 'fixed-width-xxl',
),
array(
'label' => $this->l('Aktywny'),
'type' => 'switch',
'name' => 'active',
'is_bool' => true,
'values' => array(
array('value' => 1, 'label' => $this->l('Tak')),
array('value' => 0, 'label' => $this->l('Nie'))
),
'default_value' => 1
),
array(
'label' => $this->l('Wybierz kategorie'),
'type' => 'select',
'name' => 'copy_parameters',
'copy_parameters' => true,
'class' => 'fixed-width-xxl no-chosen',
'options' => array(
'query' => $existingAssociations,
'id' => 'id',
'name' => 'name'
)
),
array(
'label' => $this->l('Tryb kopiowania'),
'type' => 'select',
'name' => 'copy_parameters_mode',
'copy_parameters' => true,
'class' => 'fixed-width-xxl no-chosen',
'options' => array(
'query' => array(
array('id' => XAllegroCategory::COPY_MODE_EMPTY, 'name' => $this->l('dodaj tylko parametry do niezmapowanych/nieprzypisanych parametrów z wybranej kategorii')),
array('id' => XAllegroCategory::COPY_MODE_ALL, 'name' => $this->l('dodaj wszystkie pasujące parametry z wybranej kategorii')),
array('id' => XAllegroCategory::COPY_MODE_OVERRIDE, 'name' => $this->l('nadpisz wszystkie parametry według wybranej kategorii'))
),
'id' => 'id',
'name' => 'name'
)
)
),
'submit' => array(
'title' => $this->l('Zapisz'),
),
'buttons' => array(
'save-and-stay' => array(
'title' => $this->l('Zapisz i zostań'),
'name' => 'submitAdd' . $this->table . 'AndStay',
'type' => 'submit',
'class' => 'btn btn-default pull-right',
'icon' => 'process-icon-save'
)
)
);
$parameters = array();
if ($this->allegroCategory && $this->allegroCategory->leaf) {
try {
$parameters = $this->categoriesParametersProvider->getParameters($this->allegroCategory->id);
}
catch (Exception $ex) {
$this->errors[] = (string)$ex;
}
}
$form = (new ParametersForm())
->setController($this)
->setLanguage($this->allegroApi->getAccount()->id_language)
->setCategory($this->object)
->setParameters($parameters)
->setMapButton(true)
->setFieldsValues(Tools::getValue('category_fields', []), Tools::getValue('category_ambiguous_fields', []));
$this->fields_form[]['form'] = array(
'legend' => array(
'title' => $this->l('Parametry kategorii')
),
'input' => array(),
'category_parameters' => $form->buildForm(),
'submit' => array(
'title' => $this->l('Zapisz'),
),
'buttons' => array(
'save-and-stay' => array(
'title' => $this->l('Zapisz i zostań'),
'name' => 'submitAdd' . $this->table . 'AndStay',
'type' => 'submit',
'class' => 'btn btn-default pull-right',
'icon' => 'process-icon-save'
)
)
);
$tagManager = new XAllegroHelperTagManager();
$tagManager->setMapType(XAllegroTagManager::MAP_CATEGORY);
$tagManager->setContainer('xallegro_category_form');
$this->fields_form[]['form'] = array(
'legend' => array(
'title' => $this->l('Tagi kategorii'),
),
'input' => array(
array(
'type' => 'tag-manager',
'name' => 'tag-manager',
'content' => (Validate::isLoadedObject($this->object) ? $tagManager->renderTagManager($this->object->tags) : '')
)
),
'submit' => array(
'title' => $this->l('Zapisz'),
),
'buttons' => array(
'save-and-stay' => array(
'title' => $this->l('Zapisz i zostań'),
'name' => 'submitAdd' . $this->table . 'AndStay',
'type' => 'submit',
'class' => 'btn btn-default pull-right',
'icon' => 'process-icon-save'
)
)
);
$root_category = Category::getRootCategory();
$root_category = array('id_category' => $root_category->id, 'name' => $root_category->name);
$cat_input = array(
'type' => 'categories',
'label' => $this->l('Kategoria'),
'name' => 'categoryBox',
'tree' => array(
'id' => 'categoryBox',
'root_category' => $root_category['id_category'],
'use_search' => true,
'use_checkbox' => true,
'use_radio' => false,
'selected_categories' => $this->object->id_categories
)
);
$this->fields_form[]['form'] = array(
'legend' => array(
'title' => $this->l('Kategoria w sklepie internetowym'),
),
'input' => array(
$cat_input
),
'submit' => array(
'title' => $this->l('Zapisz'),
),
'buttons' => array(
'save-and-stay' => array(
'title' => $this->l('Zapisz i zostań'),
'name' => 'submitAdd' . $this->table . 'AndStay',
'type' => 'submit',
'class' => 'btn btn-default pull-right',
'icon' => 'process-icon-save'
)
)
);
$this->tpl_form_vars['allegro_category_input'] = ($this->allegroCategory ? $this->allegroCategory->id : 0);
return parent::renderForm();
}
public function postProcess()
{
if (Tools::isSubmit('submitCopyParameters')) {
if (!Validate::isLoadedObject($this->object)) {
$this->errors[] = $this->l('Musisz najpierw zapisać tę ścieżkę kategorii.');
return false;
}
$xAllegroCategory = new XAllegroCategory(Tools::getValue('copy_parameters'));
if (!Validate::isLoadedObject($xAllegroCategory)) {
$this->errors[] = $this->l('Wybrano nieprawidłowe powiązanie kategorii.');
return false;
}
$parameters = [];
if ($this->allegroCategory) {
try {
$parameters = $this->categoriesParametersProvider->getParameters($this->allegroCategory->id);
}
catch (Exception $ex) {
$this->errors[] = (string)$ex;
return false;
}
}
if ($this->object->copyParameters($xAllegroCategory, $parameters, Tools::getValue('copy_parameters_mode'))) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroAssocCategories') .
'&conf=4&update' . $this->table . '&' . $this->identifier . '=' . $this->object->id);
}
else {
$this->errors[] = $this->l('Wystąpił błąd podczas kopiowania parametrów.');
}
}
else if (Tools::isSubmit('submitAdd' . $this->table)
|| Tools::isSubmit('submitAdd' . $this->table . 'AndStay')
) {
if (!$this->allegroCategory) {
$this->errors[] = $this->l('Nie wybrano kategorii Allegro.');
return false;
}
else if (!$this->allegroCategory->leaf) {
$this->errors[] = $this->l('Wybrana kategoria Allegro nie jest kategorią najniższego rzędu.');
return false;
}
$this->object->fields_values = [];
foreach (Tools::getValue('category_fields', []) as $id => $value) {
$this->object->fields_values[(int)$id] = $value;
}
$this->object->fields_ambiguous_values = [];
foreach (Tools::getValue('category_ambiguous_fields', []) as $id => $value) {
$this->object->fields_ambiguous_values[(int)$id] = $value;
}
foreach ($this->allegroCategoryPath as $categoryPath) {
$path[] = $categoryPath['name'];
}
foreach (Tools::getValue('xallegro_tag', array()) as $user_id => $tags) {
$this->object->tags[$user_id] = $tags;
}
$name = '';
if (Tools::getValue('name', 0) && Validate::isGenericName(Tools::getValue('name'))) {
$name = Tools::getValue('name');
}
$this->object->name = $name;
$this->object->path = (isset($path) ? implode(' > ', $path) : '');
$this->object->id_allegro_category = $this->allegroCategory->id;
$this->object->id_categories = Tools::getValue('categoryBox', []);
$this->object->active = Tools::getValue('active');
$this->object->save();
if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroAssocCategories') .
'&conf=4&update' . $this->table . '&' . $this->identifier . '=' . $this->object->id);
}
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroAssoc') . '&conf=4');
}
return parent::postProcess();
}
public function initContent()
{
if (!empty($this->errors)) {
$this->display = 'edit';
}
parent::initContent();
}
public function ajaxProcessGetCategories()
{
$parameters =
$categories =
$categoriesPath = array();
$isLeaf =
$categoriesFields = false;
$categoryId = Tools::getValue('id_allegro_category');
$category = $this->categoriesProvider->getCategoryDetails($categoryId);
if ((bool)Tools::getValue('full_path')) {
foreach ($this->categoriesProvider->getCategoriesPath($categoryId) as $id => $list) {
$categoriesPath[] = array(
'id' => $id,
'list' => $list
);
}
}
else {
$categories = $this->categoriesProvider->getCategoriesList($categoryId);
}
if ($category) {
$isLeaf = $category->leaf;
}
if ($isLeaf) {
try {
$parameters = $this->categoriesParametersProvider->getParameters($categoryId);
}
catch (Exception $ex) {}
if (!empty($parameters)) {
$categoriesFields = (new ParametersForm())
->setController($this)
->setCategory($this->object)
->setParameters($parameters)
->setMapButton(true)
->setFieldsValues()
->buildForm();
}
}
die(json_encode(array(
'last_node' => (int)$isLeaf,
'fields' => $categoriesFields,
'categories' => $categories,
'categories_array' => $categoriesPath
)));
}
public function ajaxProcessGetParameterMapForm()
{
$parameterId = Tools::getValue('parameterId');
try {
if (!Validate::isLoadedObject($this->object)) {
throw new Exception($this->l('Musisz zapisać tą sieżkę kategorii przed mapowaniem parametrów.'));
}
$category = $this->categoriesProvider->getCategoryDetails($this->object->id_allegro_category);
if ($category->leaf) {
$parameters = $this->categoriesParametersProvider->getParameters($this->object->id_allegro_category);
$parameter = array_reduce($parameters, function ($carry, $object) use ($parameterId) {
return $carry === null && $object->id == $parameterId ? $object : $carry;
});
if (!$parameter) {
throw new Exception($this->l('Nie znaleziono parametru w wybranej kategorii.'));
}
} else {
throw new Exception($this->l('Wybrana kategoria nie jest najniższego rzędu.'));
}
}
catch (Exception $ex) {
die(json_encode([
'success' => false,
'message' => (string)$ex
]));
}
$defaultParameterForm = (new ParametersForm())
->setController($this)
->setCategory($this->object)
->setParameters([$parameter])
->setFieldsValues()
->buildForm();
$isRangeValue = (isset($parameter->restrictions->range) && $parameter->restrictions->range);
$hasAmbiguousValue = CategoryParameters::hasAmbiguousValue($parameter);
$parameterDictionary = false;
$parameterRangeMapRules = false;
$parameterAmbiguousMapRules = false;
if ($parameter->type == 'dictionary') {
$parameterDictionary = $parameter->dictionary;
$parameterMapRules = ParametersMapForm::getDictionaryMapRules($parameter->name);
$parameterAmbiguousMapRules = ($hasAmbiguousValue ? ParametersMapForm::getAmbiguousMapRules() : false);
} else {
$parameterMapRules = ParametersMapForm::getTextMapRules();
if ($isRangeValue) {
$parameterRangeMapRules = ParametersMapForm::getRangeMapRules();
}
}
if ($hasAmbiguousValue) {
$ambiguousValue = CategoryParameters::getDictionaryByValueId($parameter->dictionary, $parameter->options->ambiguousValueId);
}
$tplModal = $this->context->smarty->createTemplate($this->module->getLocalPath() . 'views/templates/admin/' . $this->tpl_folder . 'helpers/form/parameter-map-form-modal.tpl');
$tplModal->assign([
'parameterId' => $parameter->id,
'parameterName' => $parameter->name,
'parameterType' => $parameter->type,
'parameterUnit' => $parameter->unit,
'isDictionary' => ($parameter->type == 'dictionary'),
'isRangeValue' => $isRangeValue,
'hasAmbiguousValue' => $hasAmbiguousValue,
'ambiguousValue' => (isset($ambiguousValue) ? $ambiguousValue->value : ''),
'categoryId' => $this->object->id,
'categoryPath' => $this->object->path,
'defaultParameterForm' => $defaultParameterForm,
'mapValuesForm' => (isset($this->object->fields_mapping[$parameter->id])
? ParametersMapForm::getMapValues($parameter, $this->object->fields_mapping[$parameter->id], $this->allegroApi->getAccount()->id_language) : [])
]);
die(json_encode([
'success' => true,
'html' => $tplModal->fetch(),
'parameterDictionary' => $parameterDictionary,
'parameterMapRules' => $parameterMapRules,
'parameterRangeMapRules' => $parameterRangeMapRules,
'parameterAmbiguousMapRules' => $parameterAmbiguousMapRules,
'parameterAmbiguousValueId' => ($hasAmbiguousValue ? $parameter->options->ambiguousValueId : false),
'searchCollection' => [
ParametersMapForm::RULE_DICTIONARY_MANUFACTURER => ManufacturerRepository::getAll(true, true),
ParametersMapForm::RULE_TEXT_ATTRIBUTE_GROUP => ProductAttributeRepository::getAllAttributeGroups($this->allegroApi->getAccount()->id_language, true),
ParametersMapForm::RULE_DICTIONARY_ATTRIBUTE_VALUE => ProductAttributeRepository::getAllAttributeValues($this->allegroApi->getAccount()->id_language, true, ': '),
ParametersMapForm::RULE_TEXT_FEATURE_GROUP => ProductFeatureRepository::getAllFeatureGroups($this->allegroApi->getAccount()->id_language, true),
ParametersMapForm::RULE_DICTIONARY_FEATURE_VALUE => ProductFeatureRepository::getAllFeatureValues($this->allegroApi->getAccount()->id_language, true, ': ')
]
]));
}
public function ajaxProcessSubmitParameterMap()
{
try {
if (!Validate::isLoadedObject($this->object)) {
throw new Exception($this->l('Musisz zapisać tą sieżkę kategorii przed mapowaniem parametrów.'));
}
foreach (Tools::getValue('category_fields', []) as $id => $value) {
$this->object->fields_values[(int)$id] = $value;
}
foreach (Tools::getValue('category_ambiguous_fields', []) as $id => $value) {
$this->object->fields_ambiguous_values[(int)$id] = $value;
}
$parameterMapId = (int)Tools::getValue('xallegro_parameter_id');
$this->object->fields_mapping[$parameterMapId] = [];
foreach (Tools::getValue('xallegro_parameter_map', []) as $map) {
$this->object->fields_mapping[$parameterMapId][] = $map;
}
$this->object->save();
$category = $this->categoriesProvider->getCategoryDetails($this->object->id_allegro_category);
if ($category->leaf) {
$parameters = $this->categoriesParametersProvider->getParameters($this->object->id_allegro_category);
$parameter = array_reduce($parameters, function ($carry, $object) use ($parameterMapId) {
return $carry === null && $object->id == $parameterMapId ? $object : $carry;
});
if (!$parameter) {
throw new Exception($this->l('Nie znaleziono parametru w wybranej kategorii.'));
}
} else {
throw new Exception($this->l('Wybrana kategoria nie jest najniższego rzędu.'));
}
}
catch (Exception $ex) {
die(json_encode([
'success' => false,
'message' => (string)$ex
]));
}
$parameterForm = (new ParametersForm())
->setController($this)
->setCategory($this->object)
->setParameters([$parameter])
->setFieldsValues()
->setMapButton(true)
->buildForm();
die(json_encode([
'success' => true,
'message' => $this->l('Zapisano mapowanie parametru'),
'parameterForm' => $parameterForm
]));
}
public function ajaxProcessSubmitCategoryFieldsValues()
{
try {
if (!Validate::isLoadedObject($this->object)) {
throw new Exception($this->l('Musisz zapisać tą sieżkę kategorii przed mapowaniem parametrów.'));
}
$this->object->fields_values = [];
foreach (Tools::getValue('category_fields', []) as $id => $value) {
$this->object->fields_values[(int)$id] = $value;
}
$this->object->fields_ambiguous_values = [];
foreach (Tools::getValue('category_ambiguous_fields', []) as $id => $value) {
$this->object->fields_ambiguous_values[(int)$id] = $value;
}
$this->object->save();
}
catch (Exception $ex) {
die(json_encode([
'success' => false,
'message' => (string)$ex
]));
}
die(json_encode([
'success' => true,
'message' => $this->l('Zapisano zmmiany w parametrach kategorii')
]));
}
}

View File

@@ -0,0 +1,161 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
final class AdminXAllegroAssocController extends XAllegroController
{
private $categoriesController;
private $manufacturersController;
public function __construct()
{
$this->table = 'xallegro_configuration';
$this->identifier = 'id_xallegro_configuration';
$this->className = 'XAllegroConfiguration';
parent::__construct();
$this->categoriesController = new AdminXAllegroAssocCategoriesController();
$this->categoriesController->token = $this->token;
$this->categoriesController->init();
$this->manufacturersController = new AdminXAllegroAssocManufacturersController();
$this->manufacturersController->token = $this->token;
$this->manufacturersController->init();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroAssoc'));
}
public function postProcess()
{
foreach ($_GET as $get => $value) {
// add, update, delete
if (preg_match('/^((?!id_).*)xallegro_(.*)$/', $get, $m)) {
if ($m[2] == 'category') {
$controller = $this->context->link->getAdminLink('AdminXAllegroAssocCategories');
$identifier = $this->categoriesController->identifier;
}
else if ($m[2] == 'manufacturer') {
$controller = $this->context->link->getAdminLink('AdminXAllegroAssocManufacturers');
$identifier = $this->manufacturersController->identifier;
}
else {
continue;
}
$url = $controller . '&' . $get . '&' . $identifier . '=' . Tools::getValue($identifier);
if (strpos($m[1], 'submitBulk') !== false) {
unset($_POST['token']);
$url .= '&' . http_build_query($_POST);
}
Tools::redirectAdmin($url);
}
unset($m);
}
return parent::postProcess();
}
public function initPageHeaderToolbar()
{
if (empty($this->display))
{
$this->page_header_toolbar_btn['allegro_current'] = array(
'href' => $this->context->link->getAdminLink('AdminXAllegroAssocCategories') . '&add' . $this->categoriesController->table,
'desc' => $this->l('Dodaj powiązanie kategorii'),
'icon' => 'process-icon-new'
);
$this->page_header_toolbar_btn['allegro_sold'] = array(
'href' => $this->context->link->getAdminLink('AdminXAllegroAssocManufacturers') . '&add' . $this->manufacturersController->table,
'desc' => $this->l('Dodaj powiązanie producenta'),
'icon' => 'process-icon-new'
);
}
parent::initPageHeaderToolbar();
}
public function init()
{
parent::init();
$this->getFieldsOptions();
}
public function beforeUpdateOptions()
{
$this->redirect_after = $this->context->link->getAdminLink('AdminXAllegroAssoc') . '&conf=6';
}
private function getFieldsOptions()
{
$this->fields_options = array(
'general' => array(
'title' => $this->l('Ustawienia globalnych powiązań'),
'image' => false,
'description' => $this->l('Dla poniższych parametrów moduł spróbuje ustawić wartość automatycznie, bazując na danych produktu PrestaShop.'),
'fields' => array(
'AUCTION_USE_EAN' => array(
'title' => $this->l('Automatyczne powiązanie pola "EAN"'),
'type' => 'bool'
),
'PARAMETERS_GLOBAL_ISBN' => array(
'title' => $this->l('Automatyczne powiązanie pola "ISBN"'),
'desc' => (version_compare(_PS_VERSION_, '1.7.0.0', '<')
? $this->l('Opcja dostępna od PrestaShop 1.7')
: $this->l('Bazuje na polu "ISBN" z PrestaShop. Powiązuje pola "ISBN" oraz "ISSN".')),
'type' => 'bool',
'disabled' => version_compare(_PS_VERSION_, '1.7.0.0', '<')
),
'PARAMETERS_GLOBAL_CONDITION' => array(
'title' => $this->l('Automatyczne powiązanie pola "Stan"'),
'type' => 'bool',
'desc' => $this->l('Bazuje na polu "Stan" z PrestaShop. Dotyczy tylko wartości "Nowy" i "Używany".')
),
'PARAMETERS_GLOBAL_REFERENCE' => array(
'title' => $this->l('Automatyczne powiązanie pola "Kod producenta"'),
'type' => 'bool',
'desc' => $this->l('Bazuje na polu "Indeks" z PrestaShop. Powiązuje pola "Kod producenta", "Numer katalogowy", "Numer katalogowy producenta", "Numer katalogowy części".')
),
'PARAMETERS_GLOBAL_MANUFACTURER' => array(
'title' => $this->l('Automatyczne powiązanie pola "Producent"'),
'type' => 'bool',
'desc' => $this->l('Bazuje na polu "Marka/Producent" z PrestaShop. Powiązuje pola "Marka", "Producent", "Producent części".')
)
),
'submit' => array(
'title' => $this->l('Zapisz')
)
)
);
}
public function initContent()
{
parent::initContent();
$messages = [
'confirmations',
'informations',
'warnings',
'errors'
];
foreach ($messages as $message) {
$this->{$message} = array_merge(
$this->{$message},
$this->categoriesController->{$message},
$this->manufacturersController->{$message}
);
}
}
public function renderList()
{
return $this->categoriesController->renderList() .
$this->manufacturersController->renderList();
}
}

View File

@@ -0,0 +1,206 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
final class AdminXAllegroAssocManufacturersController extends XAllegroController
{
/** @var XAllegroManufacturer */
public $object;
public function __construct()
{
$this->table = 'xallegro_manufacturer';
$this->identifier = 'id_xallegro_manufacturer';
$this->className = 'XAllegroManufacturer';
$this->multiple_fieldsets = true;
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroAssocManufacturers'));
$this->tpl_folder = 'x_allegro_manufacturers/';
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?'),
'icon' => 'icon-trash'
)
);
}
public function init()
{
parent::init();
$this->loadObject(true);
}
public function initToolbar()
{
if ($this->display == 'add' || $this->display == 'edit') {
$this->toolbar_btn['save_and_stay'] = array(
'href' => self::$currentIndex . '&token=' . $this->token,
'desc' => $this->l('Zapisz i zostań'),
'class' => 'process-icon-save-and-stay '
);
}
parent::initToolbar();
}
public function renderList()
{
if (Tools::getValue('controller') == 'AdminXAllegroAssocManufacturers' && empty($this->errors)) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroAssoc'));
}
$this->initToolbar();
if (method_exists($this, 'initPageHeaderToolbar')) {
$this->initPageHeaderToolbar();
}
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->_select = 'm.`name` as id_manufacturer';
$this->_join = 'JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON (a.`id_manufacturer` = m.`id_manufacturer`)';
$this->fields_list = array(
'id_manufacturer' => array(
'title' => $this->l('Producent'),
'search' => false,
'filter' => false
)
);
return parent::renderList();
}
public function renderForm()
{
if (!Validate::isLoadedObject($this->object)) {
$this->warnings[] = $this->l('Musisz zapisać tego producenta przed mapowaniem tagów.');
}
$manufacturers = array_merge(
array(
array(
'id_manufacturer' => 0,
'name' => $this->l('-- Wybierz --')
)
),
Manufacturer::getManufacturers(false, $this->allegroApi->getAccount()->id_language)
);
$this->fields_form[]['form'] = array(
'legend' => array(
'title' => $this->l('Producent')
),
'input' => array(
array(
'type' => 'select',
'label' => $this->l('Producent'),
'name' => 'id_manufacturer',
'required' => true,
'options' => array(
'query' => $manufacturers,
'id' => 'id_manufacturer',
'name' => 'name'
)
)
),
'submit' => array(
'title' => $this->l('Zapisz'),
),
'buttons' => array(
'save-and-stay' => array(
'title' => $this->l('Zapisz i zostań'),
'name' => 'submitAdd' . $this->table . 'AndStay',
'type' => 'submit',
'class' => 'btn btn-default pull-right',
'icon' => 'process-icon-save'
)
)
);
$tagManager = new XAllegroHelperTagManager();
$tagManager->setMapType(XAllegroTagManager::MAP_MANUFACTURER);
$tagManager->setContainer('xallegro_manufacturer_form');
$this->fields_form[]['form'] = array(
'legend' => array(
'title' => $this->l('Tagi producenta'),
),
'input' => array(
array(
'type' => 'tag-manager',
'name' => 'tag-manager',
'content' => (Validate::isLoadedObject($this->object) ? $tagManager->renderTagManager($this->object->tags) : '')
)
),
'submit' => array(
'title' => $this->l('Zapisz'),
),
'buttons' => array(
'save-and-stay' => array(
'title' => $this->l('Zapisz i zostań'),
'name' => 'submitAdd' . $this->table . 'AndStay',
'type' => 'submit',
'class' => 'btn btn-default pull-right',
'icon' => 'process-icon-save'
)
)
);
return parent::renderForm();
}
public function postProcess()
{
if (Tools::isSubmit('submitAdd' . $this->table)
|| Tools::isSubmit('submitAdd' . $this->table . 'AndStay')
) {
$id_manufacturer = Tools::getValue('id_manufacturer');
if (!$id_manufacturer) {
$this->errors[] = $this->l('Nie wybrano producenta.');
return false;
}
else if ((Validate::isLoadedObject($this->object)
&& $this->object->id_manufacturer != $id_manufacturer
&& XAllegroManufacturer::isAssigned($id_manufacturer))
|| (!Validate::isLoadedObject($this->object)
&& XAllegroManufacturer::isAssigned($id_manufacturer))
) {
$this->errors[] = $this->l('Posiadasz już powiązanie tego producenta.');
return false;
}
foreach (Tools::getValue('xallegro_tag', array()) as $user_id => $tags) {
$this->object->tags[$user_id] = $tags;
}
$this->object->id_manufacturer = $id_manufacturer;
$this->object->save();
if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroAssocManufacturers') .
'&conf=4&update' . $this->table . '&' . $this->identifier . '=' . $this->object->id);
}
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroAssoc') . '&conf=4');
}
return parent::postProcess();
}
public function initContent()
{
if (!empty($this->errors)) {
$this->display = 'edit';
}
parent::initContent();
}
}

View File

@@ -0,0 +1,272 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
/**
* @deprecated 6.4.0
*/
class AdminXAllegroAuctionsEditController extends XAllegroController
{
protected $allegroAutoLogin = true;
protected $_auctions = array();
public function __construct()
{
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroAuctionsEdit'));
$this->tpl_folder = 'x_allegro_auctions_edit/';
}
public function initToolbar()
{
parent::initToolbar();
$this->toolbar_btn['back'] = array(
'href' => $this->context->link->getAdminLink('AdminXAllegroAuctionsList') . '&show=' . Tools::getValue('show'),
'desc' => $this->l('Powrót do listy aukcji')
);
unset($this->toolbar_btn['new']);
}
public function initPageHeaderToolbar()
{
$this->page_header_toolbar_btn['xallegro_back'] = array(
'href' => $this->context->link->getAdminLink('AdminXAllegroAuctionsList') . '&show=' . Tools::getValue('show'),
'desc' => $this->l('Powrót do listy aukcji'),
'icon' => 'process-icon-arrow-left icon-arrow-left',
);
parent::initPageHeaderToolbar();
}
public function init()
{
parent::init();
$auctionsIds = XAllegroAuction::getIdAuctionsByAllegroId(explode(',', Tools::getValue('id_auction')));
$data = array();
if ($auctionsIds)
{
foreach ($auctionsIds as $id)
{
$auction = new XAllegroAuction($id['id_xallegro_auction']);
$auction->productObj = new Product($auction->id_product, true, $this->context->language->id, $auction->id_shop);
if (!Validate::isLoadedObject($auction->productObj)) {
$this->errors[] = sprintf($this->l('Aukcja %s, powiązanie odnosi się do nieistniejacego produktu.'), '<b>#' . $auction->id_auction . '</b>');
continue;
}
$item = $this->allegroApi->showItemInfoExt($auction->id_auction);
$auction->item = json_decode($auction->item);
// @todo fixme - pobiera aktualna cenne z Allegro
$auction->price_buy_now = $item->itemListInfoExt->itBuyNowPrice;
if (!$auction->item) {
$auction->item = new StdClass();
$auction->item->title = $item->itemListInfoExt->itName;
}
$combinations = $auction->productObj->getAttributesResume($this->context->language->id);
if ($combinations) {
foreach ($combinations as $combination) {
if ($combination['id_product_attribute'] == $auction->id_product_attribute) {
$auction->productObj->quantity = Product::getQuantity($auction->productObj->id, $combination['id_product_attribute']);
$auction->productObj->price_buy_now = XAllegroProduct::getProductStaticPrice($auction->productObj->id, $combination['id_product_attribute'], $this->context);
$auction->productObj->name_attribute = $combination['attribute_designation'];
break;
}
}
}
else {
$auction->productObj->quantity = Product::getQuantity($auction->productObj->id, 0);
$auction->productObj->price_buy_now = XAllegroProduct::getProductStaticPrice($auction->productObj->id, 0, $this->context);
}
$auction->productObj->price_buy_now_default = $auction->productObj->price_buy_now;
$auction->productObj->price_buy_now = XAllegroProduct::calculatePrice($auction->productObj->price_buy_now);
$auction->productObj->quantity_max = XAllegroApiTools::calculateMaxQuantity($auction->productObj->quantity);
$auction->productObj->quantity_oos = XAllegroProduct::setOOS($auction->productObj->out_of_stock);
$data[$auction->id_auction] = $auction;
}
}
$this->_auctions = $data;
}
public function initContent()
{
parent::initContent();
$this->context->smarty->assign(array(
'toolbar_title' => $this->toolbar_title,
'toolbar_btn' => $this->toolbar_btn,
'toolbar_scroll' => true,
'show' => Tools::getValue('show'),
'id_auction' => Tools::getValue('id_auction'),
'quantity_check' => (int)XAllegroConfiguration::get('QUANITY_CHECK'),
'price_markup' => (bool)(XAllegroConfiguration::get('MARKUP_PERCENT') || XAllegroConfiguration::get('MARKUP_VALUE')),
'auctions' => $this->_auctions,
'token' => $this->token
));
}
public function postProcess()
{
if (Tools::isSubmit('submitEditAuctions'))
{
if (!Tools::getValue('item')) {
$this->errors[] = $this->l('Nie wybrano żadnych przedmiotów.');
return parent::postProcess();
}
$newItem = Tools::getValue('item');
/** @var XAllegroAuction $auction */
foreach ($this->_auctions as &$auction)
{
$fields =
$confirmations =
$errors =
$not_changed = array();
$update_price = false;
$update = false;
$message = $this->l('Aukcja') . ' <strong>#' . $auction->id_auction . '</strong><br/>';
if (isset($newItem[$auction->id_auction])
&& isset($newItem[$auction->id_auction]['enabled'])
&& $newItem[$auction->id_auction]['enabled']
) {
if (abs($newItem[$auction->id_auction]['price_buy_now'] - $auction->price_buy_now) > 0.000001)
{
$old_price = $auction->price_buy_now;
$auction->price_buy_now = (float)str_replace(',', '.', $newItem[$auction->id_auction]['price_buy_now']);
$update_price = true;
}
if ((int)$newItem[$auction->id_auction]['quantity'] != (int)$auction->quantity)
{
$item = $this->allegroApi->showItemInfoExt($auction->id_auction);
$stock_available = StockAvailable::getQuantityAvailableByProduct($auction->id_product, $auction->id_product_attribute, $auction->id_shop);
$quantity_sold = $item->itemListInfoExt->itStartingQuantity - $item->itemListInfoExt->itQuantity;
$oldQuantity = (int)$auction->quantity;
$newQuantity = (int)$newItem[$auction->id_auction]['quantity'];
if ($newQuantity > $stock_available && XAllegroConfiguration::get('QUANITY_CHECK') && !(int)$newItem[$auction->id_auction]['quantity_oos']) {
$errors[] = $this->l('Podana ilość jest większą niż dostępna.');
}
else {
$fields[] = array(
'fid' => XAllegroApi::FIELD_QUANTITY,
'fvalueInt' => $newQuantity
);
$auction->quantity = (int)$newQuantity;
$auction->quantity_start = (int)($newQuantity + $quantity_sold);
$update = true;
}
}
}
if ($update || $update_price)
{
if ($update_price) {
$this->allegroApi->put('offers/{offerId}/change-price-commands/{commandId}', array(
'offerId' => $auction->id_auction,
'commandId' => UUID::uuid4()
), array(
'input' => array(
'buyNowPrice' => array(
'amount' => $auction->price_buy_now,
'currency' => 'PLN'
)
)
));
$response = $this->allegroApi->getResponse();
if (empty($response->output->errors)) {
$confirmations[] = $this->l('Nowa cena:') . ' ' . number_format($auction->price_buy_now, 2, ',', '') . 'zł';
XAllegroLogger::getInstance()
->setType('PUT')
->setCode('panel-price-allegro')
->setAuction($auction->id_auction)
->setAccount($this->allegroApi->account->id)
->setMessage(array(
'old_price' => $old_price,
'new_price' => $auction->price_buy_now
))
->log();
}
}
if ($update)
{
$fields = $this->allegroApi->fillEmptyFidValues($fields);
$result = $this->allegroApi->changeItemFields($auction->id_auction, $fields);
if ($result) {
foreach ($result->changedItem->itemFields->item as $item) {
if ($item->fid == XAllegroApi::FIELD_QUANTITY) {
$confirmations[] = $this->l('Nowa ilość dostepna ilość:') . ' ' . $item->fvalueInt;
}
}
XAllegroLogger::getInstance()
->setType('PUT')
->setCode('panel-auction-quantity')
->setAuction($auction->id_auction)
->setAccount($this->allegroApi->account->id)
->setMessage(array(
'old_quantity' => $oldQuantity,
'new_start_quantity' => (int)($newQuantity + $quantity_sold),
'new_quantity' => (int)$newQuantity
))
->log();
}
else {
$errors = array_merge($errors, $this->allegroApi->getErrors());
}
}
}
else {
$not_changed[] = $auction->id_auction;
}
if (empty($errors) && !in_array($auction->id_auction, $not_changed))
{
$auction->item = json_encode($auction->item);
$auction->save();
if (!empty($confirmations)) {
$this->confirmations[] = '<p>' . $message . implode('<br/>', $confirmations) . '<br/><br/>' .
$this->l('Zmiany będą widoczne na portalu Allegro w ciągu 5 minut.'). '</p>';
}
}
else {
$this->errors[] = '<p>' . $message . implode('<br/>', $errors) . '</p>';
}
}
if (!empty($not_changed)) {
$this->informations[] = $this->l('Nie wprowadzono zmian dla aukcji:') . ' ' . implode(', ', $not_changed);
}
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroAuctionsList') . '&show=' . Tools::getValue('show'));
}
return parent::postProcess();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,262 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
use x13allegro\Api\DataProvider\CarrierOperatorsProvider;
use x13allegro\Api\DataProvider\DeliveryMethodsProvider;
final class AdminXAllegroCarriersController extends XAllegroController
{
protected $allegroAutoLogin = true;
public function __construct()
{
$this->table = 'xallegro_carrier';
$this->multiple_fieldsets = true;
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroCarriers'));
$this->toolbar_title = $this->l('Przypisywanie przewoźników');
$this->tpl_folder = 'x_allegro_carriers/';
}
public function init()
{
parent::init();
$this->display = 'edit';
}
public function renderForm()
{
$carriers =
$deliveryMethods =
$carrierOperators =
$carriersAllegro = [];
foreach (Carrier::getCarriers($this->context->language->id, false, false, false, null, null) as $carrier) {
$carriers[] = [
'id' => $carrier['id_reference'],
'name' => $carrier['name']
];
}
try {
$dataProvider = new DeliveryMethodsProvider(
$this->allegroApi->sale()->deliveryMethods()->getAll()->deliveryMethods
);
$deliveryMethods = $dataProvider->getDeliveryMethods();
$deliveryMethods = $dataProvider->groupDeliveryMethods($deliveryMethods);
$carrierOperators = (new CarrierOperatorsProvider($this->allegroApi))->getCarriers();
}
catch (Exception $ex) {
$this->errors[] = (string)$ex;
}
foreach ($deliveryMethods as $type => $methods) {
foreach ($methods as $deliveryMethod) {
$carriersAllegro[$type][] = array(
'type' => 'select',
'label' => $deliveryMethod['name'],
'id_fields_shipment' => $deliveryMethod['id'],
'name' => 'id_fields_shipment[' . $deliveryMethod['id'] . '][id_carrier]',
'name_operator' => 'id_fields_shipment[' . $deliveryMethod['id'] . ']',
'class' => 'fixed-width-xxl',
'options' => array(
'query' => $carriers,
'id' => 'id',
'name' => 'name',
'default' => array(
'label' => $this->l('-- Wybierz --'),
'value' => 0
)
),
'options_operators' => array(
'query' => $carrierOperators,
'default' => array(
'label' => $this->l('-- Wybierz operatora przesyłki --'),
'value' => null
)
)
);
}
}
if (isset($carriersAllegro['free'])) {
$this->fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Darmowe opcje dostawy')
),
'input' => $carriersAllegro['free'],
'submit' => array(
'title' => $this->l('Zapisz')
)
);
}
if (isset($carriersAllegro['in_advance_courier'])) {
$this->fields_form[1]['form'] = array(
'legend' => array(
'title' => $this->l('Kurier - płatność z góry')
),
'input' => $carriersAllegro['in_advance_courier'],
'submit' => array(
'title' => $this->l('Zapisz')
)
);
}
if (isset($carriersAllegro['in_advance_package'])) {
$this->fields_form[2]['form'] = array(
'legend' => array(
'title' => $this->l('Paczka - płatność z góry')
),
'input' => $carriersAllegro['in_advance_package'],
'submit' => array(
'title' => $this->l('Zapisz')
)
);
}
if (isset($carriersAllegro['in_advance_letter'])) {
$this->fields_form[3]['form'] = array(
'legend' => array(
'title' => $this->l('List - płatność z góry')
),
'input' => $carriersAllegro['in_advance_letter'],
'submit' => array(
'title' => $this->l('Zapisz')
)
);
}
if (isset($carriersAllegro['in_advance_pos'])) {
$this->fields_form[4]['form'] = array(
'legend' => array(
'title' => $this->l('Odbiór w punkcie - płatność z góry')
),
'input' => $carriersAllegro['in_advance_pos'],
'submit' => array(
'title' => $this->l('Zapisz')
)
);
}
if (isset($carriersAllegro['cash_on_delivery_courier'])) {
$this->fields_form[5]['form'] = array(
'legend' => array(
'title' => $this->l('Kurier - płatność przy odbiorze')
),
'input' => $carriersAllegro['cash_on_delivery_courier'],
'submit' => array(
'title' => $this->l('Zapisz')
)
);
}
if (isset($carriersAllegro['cash_on_delivery_package'])) {
$this->fields_form[6]['form'] = array(
'legend' => array(
'title' => $this->l('Paczka - płatność przy odbiorze')
),
'input' => $carriersAllegro['cash_on_delivery_package'],
'submit' => array(
'title' => $this->l('Zapisz')
)
);
}
if (isset($carriersAllegro['cash_on_delivery_letter'])) {
$this->fields_form[7]['form'] = array(
'legend' => array(
'title' => $this->l('List - płatność przy odbiorze')
),
'input' => $carriersAllegro['cash_on_delivery_letter'],
'submit' => array(
'title' => $this->l('Zapisz')
)
);
}
if (isset($carriersAllegro['cash_on_delivery_pos'])) {
$this->fields_form[8]['form'] = array(
'legend' => array(
'title' => $this->l('Odbiór w punkcie - płatność przy odbiorze')
),
'input' => $carriersAllegro['cash_on_delivery_pos'],
'submit' => array(
'title' => $this->l('Zapisz')
)
);
}
if (isset($carriersAllegro['abroad'])) {
$this->fields_form[9]['form'] = array(
'legend' => array(
'title' => $this->l('Wysyłka za granicę - płatność z góry')
),
'input' => $carriersAllegro['abroad'],
'submit' => array(
'title' => $this->l('Zapisz')
)
);
}
return parent::renderForm();
}
public function postProcess()
{
if (Tools::isSubmit('submitAdd' . $this->table))
{
if ($this->tabAccess['edit'] !== '1') {
$this->errors[] = $this->l('Nie masz uprawnień do edycji w tym miejscu.');
}
else if (Tools::getValue('id_fields_shipment')) {
if (XAllegroCarrier::updateCarriers(Tools::getValue('id_fields_shipment'))) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroCarriers') . '&conf=4');
}
}
else {
$this->errors[] = $this->l('Nie przesłano przewożników');
}
}
$this->display = 'edit';
return true;
}
public function getFieldsValue($obj)
{
$assignedCarriers = XAllegroCarrier::getAll();
foreach ($this->fields_form as $fieldset) {
if (isset($fieldset['form']['input'])) {
foreach ($fieldset['form']['input'] as $input)
{
if (!isset($this->fields_value[$input['name']])) {
$this->fields_value[$input['name']] = (isset($assignedCarriers[$input['id_fields_shipment']])
? $assignedCarriers[$input['id_fields_shipment']]['id_carrier'] : 0);
}
if (!isset($this->fields_value[$input['name_operator'] . '[id_operator]'])) {
$this->fields_value[$input['name_operator'] . '[id_operator]'] = (isset($assignedCarriers[$input['id_fields_shipment']])
? $assignedCarriers[$input['id_fields_shipment']]['id_operator'] : '');
}
if (!isset($this->fields_value[$input['name_operator'] . '[operator_name]'])) {
$this->fields_value[$input['name_operator'] . '[operator_name]'] = (isset($assignedCarriers[$input['id_fields_shipment']])
? $assignedCarriers[$input['id_fields_shipment']]['operator_name'] : '');
}
}
}
}
return $this->fields_value;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,48 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
final class AdminXAllegroCustomPricesController extends XAllegroController
{
public function __construct()
{
parent::__construct();
}
public function ajaxProcessRefreshCustomPrices()
{
$product = new XAllegroProduct(null, (int) Tools::getValue('id_product'));
$customPricesForm = (new XAllegroHelperCustomPrices())
->setProduct($product)
->setAccountId((int) Tools::getValue('id_xallegro_account'))
->renderCustomPricesForm();
die(
json_encode(
array(
'result' => true,
'html' => $customPricesForm,
'message' => $this->l('Poprawnie zaktualizowano')
)
)
);
}
public function ajaxProcessDeleteCustomPrices()
{
$customPriceEntity = new XAllegroCustomPrice();
$customPriceEntity->setProductId((int) (int) Tools::getValue('id_product'));
$customPriceEntity->setAccountId((int) Tools::getValue('id_xallegro_account'));
$customPriceEntity->deletePrices(true);
die(
json_encode(
array(
'result' => true,
'message' => $this->l('Poprawnie skasowano ceny dedykowane'),
)
)
);
}
}

View File

@@ -0,0 +1,366 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
use x13allegro\Component\Configuration\ConfigurationDependencies;
use x13allegro\Component\Logger\LogLevel;
use x13allegro\Component\Logger\LogType;
use x13allegro\Repository\LoggerRepository;
final class AdminXAllegroLogController extends XAllegroController
{
public function __construct()
{
$this->table = 'xallegro_log';
$this->identifier = 'id_xallegro_log';
$this->explicitSelect = true;
$this->list_no_link = true;
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroLog'));
$accountList = [];
/** @var XAllegroAccount $account */
foreach (XAllegroAccount::getAll(false) as $account) {
$accountList[$account->id] = $account->username;
}
$this->fields_list = [
'level' => [
'title' => $this->l('Poziom'),
'class' => 'fixed-width-md',
'filter_key' => 'a!level',
'type' => 'select',
'list' => $this->getLogFilterList(LogLevel::class, 'level'),
'callback' => 'printLogLevel',
'orderby' => false
],
'type' => [
'title' => $this->l('Typ'),
'class' => 'fixed-width-xxl',
'filter_key' => 'a!type',
'type' => 'select',
'list' => $this->getLogFilterList(LogType::class, 'type'),
'callback' => 'printLogType',
'orderby' => false
],
'username' => [
'title' => $this->l('Konto Allegro'),
'class' => 'fixed-width-md',
'filter_key' => 'a!id_xallegro_account',
'type' => 'select',
'list' => $accountList,
'orderby' => false
],
'id_offer' => [
'title' => $this->l('Oferta'),
'class' => 'fixed-width-md',
'orderby' => false
],
'product' => [
'title' => $this->l('Produkt'),
'class' => 'fixed-width-xl',
'orderby' => false,
'search' => false
],
'order_reference' => [
'title' => $this->l('Zamówienie'),
'class' => 'fixed-width-md',
'filter_key' => 'o!reference',
'orderby' => false
],
'message' => [
'title' => $this->l('Wiadomość'),
'orderby' => false,
'search' => false
],
'counter' => [
'title' => $this->l('Licznik'),
'class' => 'center fixed-width-xs',
'search' => false,
'callback' => 'printCounter'
],
'last_occurrence' => [
'title' => $this->l('Data'),
'class' => 'fixed-width-lg',
'type' => 'datetime'
]
];
$this->fields_options = [
'general' => [
'title' => $this->l('Ustawienia powiadomień email'),
'description' => $this->l('Powiadomienia wysyłane są tylko dla zdarzeń który wystąpiły podczas uruchomienia pliku "sync.php"'),
'image' => false,
'fields' => [
'LOG_SEND' => [
'title' => $this->l('Wysyłaj powiadomienia o zdarzeniach'),
'type' => 'bool',
],
'LOG_SEND_LEVEL' => [
'title' => $this->l('Poziom zdarzenia dla którego wysyłać powiadomienia email'),
'type' => 'checkbox', // type checkbox uses json_decode
'choices' => [
['key' => LogLevel::INFO, 'name' => LogLevel::INFO()->getValueTranslated()],
['key' => LogLevel::ERROR, 'name' => LogLevel::ERROR()->getValueTranslated()],
['key' => LogLevel::EXCEPTION, 'name' => LogLevel::EXCEPTION()->getValueTranslated()]
],
'form_group_class' => ConfigurationDependencies::fieldDependsOn(
ConfigurationDependencies::fieldMatch(),
['LOG_SEND' => 1]
)
],
'LOG_SEND_EMAIL_LIST' => [
'title' => $this->l('Lista adresów email'),
'desc' => $this->l('Adresy emailowe podawaj w nowej linii'),
'type' => 'textarea',
'rows' => 4,
'auto_value' => false,
'value' => $this->printEmailList(),
'form_group_class' => ConfigurationDependencies::fieldDependsOn(
ConfigurationDependencies::fieldMatch(),
['LOG_SEND' => 1]
)
]
],
'submit' => [
'title' => $this->l('Zapisz')
]
]
];
$this->tpl_folder = 'x_allegro_log/';
}
public function renderList()
{
$this->_select .= '
a.`id_xallegro_log`,
a.`displayed`,
ac.`username`,
IF(a.`id_offer` = 0, NULL, a.`id_offer`) as `id_offer`,
CONCAT_WS(" - ", pl.`name`, GROUP_CONCAT(attrl.`name` ORDER BY attrg.`id_attribute_group` SEPARATOR " ")) as `product`';
$this->_join .= '
LEFT JOIN `' . _DB_PREFIX_ . 'xallegro_account` ac
ON (ac.`id_xallegro_account` = a.`id_xallegro_account`)
LEFT JOIN `' . _DB_PREFIX_ . 'orders` o
ON (o.`id_order` = a.`id_order`)
LEFT JOIN `' . _DB_PREFIX_ . 'product_shop` ps
ON (ps.`id_product` = a.`id_product`
AND ps.`id_shop` = a.`id_shop`)
LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl
ON (pl.`id_product` = ps.`id_product`
AND pl.`id_lang` = ' . (int)$this->context->language->id . ')
LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_shop` pas
ON (pas.`id_product_attribute` = a.`id_product_attribute`
AND pas.`id_shop` = a.`id_shop`)
LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac
ON (pac.`id_product_attribute` = pas.`id_product_attribute`)
LEFT JOIN `' . _DB_PREFIX_ . 'attribute` attr
ON (attr.`id_attribute` = pac.`id_attribute`)
LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` attrl
ON (attrl.`id_attribute` = attr.`id_attribute`
AND attrl.`id_lang` = ' . (int)$this->context->language->id . ')
LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` attrg
ON (attrg.`id_attribute_group` = attr.`id_attribute_group`)
LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` attrgl
ON (attrgl.`id_attribute_group` = attrg.`id_attribute_group`
AND attrgl.`id_lang` = ' . (int)$this->context->language->id . ')';
$this->_group = 'GROUP BY a.`id_xallegro_log`';
$this->_defaultOrderBy = 'last_occurrence';
$this->_defaultOrderWay = 'DESC';
$this->addRowAction('showDetails');
$this->tpl_list_vars['unreadLogsCount'] = LoggerRepository::getUnreadLogs();
return parent::renderList();
}
public function beforeUpdateOptions()
{
$this->redirect_after = $this->context->link->getAdminLink('AdminXAllegroLog') . '&conf=6';
$emailList = explode(';', str_replace(["\n", "\r", "\n\r", "\r\n", ","], ';', Tools::getValue('LOG_SEND_EMAIL_LIST', '')));
$_POST['LOG_SEND_EMAIL_LIST'] = array_values(array_filter(array_map('trim', $emailList)));
}
/**
* @param mixed $value
* @param array $row
* @return string
*/
public function printLogLevel($value, $row)
{
/** @var LogLevel $logLevel */
$logLevel = LogLevel::$value();
switch ($logLevel->getKey()) {
case LogLevel::ERROR:
$badge = 'badge-danger';
break;
case LogLevel::EXCEPTION:
$badge = 'badge-dark';
break;
default:
$badge = 'badge-info';
}
return '<span class="badge badge-x13allegro ' . $badge . '">' . $logLevel->getValueTranslated() . '</span>';
}
/**
* @param mixed $value
* @param array $row
* @return string
*/
public function printLogType($value, $row)
{
/** @var LogType $logLevel */
$logType = LogType::$value();
return $logType->getValueTranslated();
}
/**
* @param mixed $value
* @param array $row
* @return string
*/
public function printCounter($value, $row)
{
if (in_array($row['level'], [LogLevel::ERROR, LogLevel::EXCEPTION])) {
return '<span class="badge badge-danger">' . $value . '</span>';
}
return $value;
}
/**
* @return string
*/
public function printEmailList()
{
if ($value = XAllegroConfiguration::get('LOG_SEND_EMAIL_LIST')) {
$value = json_decode($value, true);
if (is_array($value)) {
return implode("\r", $value);
}
}
return '';
}
/**
* @param string $token
* @param string $id
* @param string|null $name
* @return string
*/
public function displayShowDetailsLink($token, $id, $name = null)
{
$listKey = array_search($id, array_column($this->_list, 'id_xallegro_log'));
$tpl = $this->context->smarty->createTemplate($this->module->getLocalPath() . 'views/templates/admin/' . $this->tpl_folder . 'helpers/list/action_show_details.tpl');
$tpl->assign([
'action' => $this->l('Szczegóły'),
'title' => $this->l('Pokaż wszystkie informacje z loga'),
'id' => $id,
'displayed' => $this->_list[$listKey]['displayed']
]);
return $tpl->fetch();
}
/**
* @return void
*/
public function ajaxProcessGetLogDetails()
{
$logDetails = LoggerRepository::getLogDetails(Tools::getValue('logId'));
$logDetails['level'] = $this->printLogLevel($logDetails['level'], []);
$logDetails['type'] = $this->printLogType($logDetails['type'], []);
$employee = new Employee($logDetails['id_employee']);
if (Validate::isLoadedObject($employee)) {
$logDetails['employee'] = "$employee->firstname $employee->lastname";
}
$allegroAccount = new XAllegroAccount($logDetails['id_xallegro_account']);
if (Validate::isLoadedObject($allegroAccount)) {
$logDetails['allegroAccount'] = $allegroAccount->username;
}
$order = new Order($logDetails['id_order']);
if (Validate::isLoadedObject($order)) {
$logDetails['order'] = $order->reference;
}
$product = new Product($logDetails['id_product'], false, $this->context->language->id, $logDetails['id_shop']);
if (Validate::isLoadedObject($product)) {
$logDetails['product'] = $product->name;
$productCombination = $product->getAttributeCombinationsById($logDetails['id_product_attribute'], $this->context->language->id);
if (!empty($productCombination)) {
$logDetails['product'] .= ' - ' . implode(' ', array_column($productCombination, 'attribute_name'));
}
}
$logMessage = json_decode($logDetails['message']);
if (json_last_error() === JSON_ERROR_NONE) {
$logDetails['isJson'] = true;
$logDetails['message'] = json_encode($logMessage, JSON_PRETTY_PRINT);
}
$tpl = $this->context->smarty->createTemplate($this->module->getLocalPath() . 'views/templates/admin/' . $this->tpl_folder . 'helpers/list/action_show_details_modal.tpl');
$tpl->assign($logDetails);
die(json_encode([
'html' => $tpl->fetch()
]));
}
/**
* @return void
*/
public function ajaxProcessMarkAsRead()
{
die(LoggerRepository::markAsRead(Tools::getValue('logId', [])));
}
/**
* @param string $class
* @param string $column
* @return array
*/
private function getLogFilterList($class, $column)
{
$result = Db::getInstance()->executeS('
SELECT DISTINCT(`' . $column . '`)
FROM `' . _DB_PREFIX_ . 'xallegro_log`'
);
if (!$result) {
return [];
}
$list = [];
foreach ($result as $row) {
/** @var \x13allegro\Component\Enum $enum */
$enum = $class::{$row[$column]}();
$enumTranslated = $enum->getValueTranslated();
if (!empty($enumTranslated)) {
$list[$enum->getKey()] = $enumTranslated;
}
}
return $list;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,104 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
use x13allegro\Exception\ModuleException;
final class AdminXAllegroOrderMainController extends XAllegroController
{
public function ajaxProcessSendFulfilmentStatus()
{
$orderId = (int)Tools::getValue('orderId');
$statusFulfillment = Tools::getValue('statusFulfillment', '');
$result = XAllegroSyncFulfillmentStatus::sendFulfillmentStatus($orderId, $statusFulfillment, true);
if ($result['status']) {
if ($result['revisionReload']) {
$this->module->sessionMessages->warnings($this->l('Zaktualizowano dane odnośnie zamówienia Allegro, możesz teraz zmienić jego status.'));
} else {
$this->module->sessionMessages->confirmations($this->l('Pomyślnie zaktualizowano status Allegro.'));
}
die(json_encode(array_merge($result, ['redirectLink' => $this->getRedirectLink($orderId)])));
}
die(json_encode($result));
}
public function ajaxProcessUploadInvoiceFile()
{
$invoiceType = Tools::getValue('invoiceType');
$order = new Order((int)Tools::getValue('orderId'));
try {
if (!Validate::isLoadedObject($order)) {
throw new UnexpectedValueException('Nie można znaleźć zamówienia w bazie danych.');
}
if ($invoiceType === 'file') {
if (empty($_FILES['invoiceFile'])) {
throw new UnexpectedValueException('Nie załączono pliku do przesłania.');
}
// use ImageManager because there is no other class in PrestaShop to validate uploaded file
if (!ImageManager::isCorrectImageFileExt($_FILES['invoiceFile']['name'], ['pdf'])
|| $_FILES['invoiceFile']['type'] !== 'application/pdf'
) {
throw new UnexpectedValueException('Przesłany plik nie jest dokumentem PDF.');
}
if ((int)filesize($_FILES['invoiceFile']['tmp_name']) > 3 * 1024 * 1024) {
throw new UnexpectedValueException('Przesłany plik jest większy niż limit 3MB.');
}
$invoiceFile = file_get_contents($_FILES['invoiceFile']['tmp_name']);
$invoiceFileName = $_FILES['invoiceFile']['name'];
$invoiceNumber = Tools::getValue('invoiceNumber', '');
}
else if ($invoiceType === 'prestashop') {
$prestaShopInvoice = XAllegroSyncInvoice::getPrestaShopInvoice($order, $this->context);
$invoiceFile = $prestaShopInvoice['invoiceFile'];
$invoiceFileName = $prestaShopInvoice['invoiceFileName'];
$invoiceNumber = $prestaShopInvoice['invoiceNumber'];
}
else {
throw new UnexpectedValueException('Wybrano nieprawidłowy typ dokumentu do wysłania.');
}
if (!XAllegroSyncInvoice::uploadOrderInvoice($order->id, $invoiceFile, $invoiceFileName, $invoiceNumber)) {
throw new UnexpectedValueException('Zamówienie nie jest powiązane z modułem Allegro.');
}
$this->module->sessionMessages->confirmations($this->l('Przesłano dowód zakupu do Allegro.'));
die(json_encode([
'result' => true,
'redirectLink' => $this->getRedirectLink($order->id)
]));
}
catch (Exception $ex) {
die(json_encode([
'result' => false,
'message' => ($ex instanceof ModuleException ? (string)$ex : $ex->getMessage())
]));
}
}
/**
* @param int $orderId
* @return string
*/
private function getRedirectLink($orderId)
{
$params = [
'vieworder' => 1,
'id_order' => $orderId
];
if (version_compare(_PS_VERSION_, '1.7.7.0', '>=')) {
return $this->context->link->getAdminLink('AdminOrders', true, $params);
}
return $this->context->link->getAdminLink('AdminOrders') . '&' . http_build_query($params);
}
}

View File

@@ -0,0 +1,545 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
use x13allegro\Api\DataProvider\CarrierOperatorsProvider;
use x13allegro\Api\Model\Order\CarrierOperator;
final class AdminXAllegroOrderShippingController extends XAllegroController
{
protected $allegroAutoLogin = true;
private $allegroOperators = [];
private $allegroShipments = [];
public function __construct()
{
$this->table = 'order';
$this->identifier = 'id_order';
$this->className = 'Order';
$this->list_no_link = true;
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroOrderShipping'));
$this->tpl_folder = 'x_allegro_order_shipping/';
}
public function init()
{
parent::init();
if ($this->allegroApi) {
try {
$deliveryMethods = $this->allegroApi->sale()->deliveryMethods()->getAll();
foreach ($deliveryMethods->deliveryMethods as $deliveryMethod) {
$this->allegroShipments[$deliveryMethod->id] = $deliveryMethod->name;
}
$carrierOperators = (new CarrierOperatorsProvider($this->allegroApi))->getCarriers();
foreach ($carrierOperators as $carrierOperator) {
$this->allegroOperators[$carrierOperator['id']] = $carrierOperator['name'];
}
}
catch (Exception $ex) {
$this->errors[] = (string)$ex;
}
}
$statuses = [];
foreach (OrderState::getOrderStates((int)$this->context->language->id) as $status) {
$statuses[$status['id_order_state']] = $status['name'];
}
$this->fields_list = array(
'id_order' => array(
'title' => $this->l('ID'),
'align' => 'text-center',
'class' => 'fixed-width-xs'
),
'reference' => array(
'title' => $this->l('Indeks')
),
'order_status' => array(
'title' => $this->l('Status zamówienia'),
'type' => 'select',
'color' => 'color',
'list' => $statuses,
'filter_key' => 'os!id_order_state',
'filter_type' => 'int',
'order_key' => 'order_status'
),
'allegro_shipment' => array(
'title' => $this->l('Metoda wysyłki'),
'orderby' => false,
'filter' => false,
'search' => false
),
'carrier_name' => array(
'title' => $this->l('Przewoźnik'),
'filter_key' => 'c!carrier_name',
'order_key' => 'carrier_name'
),
'operator_allegro' => array(
'title' => $this->l('Operator Allegro'),
'type' => 'select',
'list' => $this->allegroOperators,
'filter_key' => 'id_operator',
'filter_type' => 'select',
'order_key' => 'id_operator'
),
'tracking_number' => array(
'title' => $this->l('Numer śledzenia'),
'callback' => 'printTrackingNumber',
'filter_key' => 'oc!tracking_number',
'order_key' => 'tracking_number'
),
'send' => array(
'title' => $this->l('Wysłano'),
'align' => 'text-center',
'type' => 'bool',
'icon' => array(
'0' => array('class' => 'icon-remove color', 'src' => 'disabled.gif', 'alt' => $this->l('Niewysłane')),
'1' => array('class' => 'icon-check color', 'src' => 'enabled.gif', 'alt' => $this->l('Wysłane'))
),
'class' => 'fixed-width-xs',
'filter_key' => 'send'
),
'send_enabled' => array(
'title' => $this->l('Wysyłka'),
'align' => 'text-center',
'type' => 'bool',
'active' => 'send_enabled',
'icon' => array(
'0' => array('class' => 'icon-remove color', 'src' => 'disabled.gif', 'alt' => $this->l('Wyłączone')),
'1' => array('class' => 'icon-check color', 'src' => 'enabled.gif', 'alt' => $this->l('Włączone'))
),
),
'error' => array(
'title' => $this->l('Błędy'),
'align' => 'text-center',
'type' => 'int',
'search' => false,
'badge_danger' => true
),
);
$this->bulk_actions['xSendEnable'] = [
'icon' => 'icon-power-off text-success bulkSendEnable',
'text' => $this->l('Włącz wysyłanie')
];
$this->bulk_actions['xSendDisable'] = [
'icon' => 'icon-power-off text-danger bulkSendDisable',
'text' => $this->l('Wyłącz wysyłanie')
];
}
public function initPageHeaderToolbar()
{
$this->page_header_toolbar_btn['send_numbers'] = array(
'href' => '#',
'desc' => $this->l('Wyślij numery śledzenia'),
'icon' => 'process-icon-send icon-send',
'class' => 'xallegro-sync-shipping'
);
parent::initPageHeaderToolbar();
}
public function renderList()
{
$this->informations[] = $this->l('Aby wysłać numer śledzenia do Allegro z tej podstrony, konieczne jest zmapowanie przewoźnika w Twoim sklepie do operatora Allegro i uzupełnienie numeru na podglądzie zamówienia.');
$this->addRowAction('xSendNumber');
$this->addRowAction('xOrderView');
$this->addRowAction('xSendDisable');
$this->context->smarty->assign('new_shipping_info', (int)XAllegroConfiguration::get('NEW_SHIPPING_INFO'));
return parent::renderList();
}
public function getList($id_lang, $orderBy = null, $orderWay = null, $start = 0, $limit = null, $id_lang_shop = null)
{
$this->_select .= '
xo.`delivery_method`,
IFNULL(xcp.`id_operator`, xc.`id_operator`) as `id_operator`,
IFNULL(xcp.`operator_name`, xc.`operator_name`) as `operator_name`,
os.`color`,
osl.`name` AS `order_status`,
c.`carrier_name`,
oc.`tracking_number`,
xcp.`tracking_number` as `send_tracking_number`,
xcp.`send_enabled`,
IF(xcp.`error` > 0, xcp.`error`, "--") AS `error`,
IF(xcp.`error` > 0, 1, 0) AS `badge_danger`,
IFNULL(xcp.`send`, 0) as `send`';
$this->_join .= '
JOIN `' . _DB_PREFIX_ . 'xallegro_order` xo ON (a.`id_order` = xo.`id_order`)
LEFT JOIN `' . _DB_PREFIX_ . 'xallegro_carrier` xc ON (xo.`delivery_method` = xc.`id_fields_shipment`)
LEFT JOIN `' . _DB_PREFIX_ . 'xallegro_carrier_package_info` xcp ON (a.`id_order` = xcp.`id_order`)
LEFT JOIN `' . _DB_PREFIX_ . 'order_carrier` oc ON (oc.`id_order` = a.`id_order`)
LEFT JOIN `' . _DB_PREFIX_ . 'order_state` os ON (os.`id_order_state` = a.`current_state`)
LEFT JOIN `' . _DB_PREFIX_ . 'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = ' . (int)$this->context->language->id . ')
INNER JOIN (
SELECT o.`id_order`,
CASE WHEN carrier.`name` = "0"
THEN "' . pSQL(method_exists(Carrier::class, 'getCarrierNameFromShopName') ? Carrier::getCarrierNameFromShopName() : 'Click and collect') . '"
ELSE carrier.`name` END as `carrier_name`
FROM `' . _DB_PREFIX_ . 'carrier` carrier
LEFT JOIN `' . _DB_PREFIX_ . 'order_carrier` oc
ON (carrier.`id_carrier` = oc.`id_carrier`)
LEFT JOIN `' . _DB_PREFIX_ . 'orders` o
ON (o.`id_order` = oc.`id_order`)
) c ON (c.`id_order` = a.`id_order`)';
$this->_group = 'GROUP BY a.`id_order`';
$this->_orderBy = 'id_order';
$this->_orderWay = 'DESC';
parent::getList($id_lang, $orderBy, $orderWay, $start, $limit, $this->context->shop->id);
foreach ($this->_list as &$item) {
$item['allegro_shipment'] = (isset($this->allegroShipments[$item['delivery_method']]) ? $this->allegroShipments[$item['delivery_method']] : null);
$item['same_number'] = ($item['send'] && strcasecmp(trim($item['tracking_number']), trim($item['send_tracking_number'])) == 0);
$item['operator_allegro'] = null;
if (isset($this->allegroOperators[$item['id_operator']])) {
$item['operator_allegro'] = $this->allegroOperators[$item['id_operator']] . ($item['id_operator'] == CarrierOperator::OTHER()->getKey() ? ': ' . $item['operator_name'] : '');
}
}
}
public function processFilter()
{
// process parent and return when submitFilter
// this will set correct cookie filters values
if (isset($_POST) && count($_POST) && (int)Tools::getValue('submitFilter' . $this->list_id)) {
parent::processFilter();
return;
}
$filterCache = [];
$filters = [
'orderFilter_send',
'orderFilter_id_operator'
];
$cookiePrefix = $this->getCookieFilterPrefix();
foreach ($filters as $filter) {
$filterName = $cookiePrefix . $filter;
if (isset($this->context->cookie->{$filterName})) {
$filterValue = $this->context->cookie->{$filterName};
$filterCache[$filterName] = $filterValue;
// unset filters before process parent to avoid duplicates is sql query
unset($this->context->cookie->{$filterName});
switch ($filter) {
case 'orderFilter_send':
$this->_where .= ' AND IFNULL(xcp.`send`, 0) = ' . (int)$filterValue;
break;
case 'orderFilter_id_operator':
$this->_where .= ' AND IFNULL(xcp.`id_operator`, xc.`id_operator`) = "' . pSQL($filterValue) . '"';
break;
}
}
}
parent::processFilter();
if (!empty($filterCache)) {
foreach ($filterCache as $cookie => $value) {
$this->context->cookie->{$cookie} = $value;
}
}
}
public function postProcess()
{
if (Tools::isSubmit('send_number') && Tools::getValue('id_order')) {
$result = XAllegroSyncShipping::sendShippingNumber(Tools::getValue('id_order'), 'list');
if (!$result['result']) {
$this->errors[] = $this->l($result['message']);
}
else {
$this->module->sessionMessages->confirmations($this->l($result['message']));
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroOrderShipping'));
}
}
else if (Tools::getIsset('send_enabled' . $this->table) && Tools::getValue('id_order')) {
$orderId = (int)Tools::getValue('id_order');
foreach (XAllegroCarrier::getPackageInfo($orderId) as $packageInfo) {
if ($packageInfo['send'] && strcasecmp(trim($packageInfo['order_tracking_number']), trim($packageInfo['send_tracking_number'])) == 0) {
$this->module->sessionMessages->confirmations("Zamówienie <b>#$orderId</b> Numer śledzenia został już wysłany");
} else {
XAllegroCarrier::updateSendEnabled(!$packageInfo['send_enabled'], $orderId);
if (!$packageInfo['send_enabled']) {
$this->module->sessionMessages->confirmations("Zamówienie <b>#$orderId</b> Włączono wysyłanie");
} else {
$this->module->sessionMessages->confirmations("Zamówienie <b>#$orderId</b> Wyłączone wysyłanie");
}
}
}
}
else if (Tools::isSubmit('send_disable') && Tools::getValue('id_order')) {
XAllegroCarrier::updateSendEnabled((int)!Tools::getValue('send_disable'), Tools::getValue('id_order'));
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroOrderShipping') . '&conf=4');
}
return parent::postProcess();
}
public function processBulkXSendEnable()
{
$identifierList = Tools::getValue($this->list_id . 'Box', []);
if (empty($identifierList)) {
$this->errors[] = $this->l('Nie wybrano zamówienien do włączenia.');
} else {
foreach ($identifierList as $orderId) {
foreach (XAllegroCarrier::getPackageInfo($orderId) as $packageInfo) {
if ($packageInfo['send'] && strcasecmp(trim($packageInfo['order_tracking_number']), trim($packageInfo['send_tracking_number'])) == 0) {
$this->module->sessionMessages->confirmations("Zamówienie <b>#$orderId</b> Numer śledzenia został już wysłany");
} else {
XAllegroCarrier::updateSendEnabled(1, $orderId);
$this->module->sessionMessages->confirmations("Zamówienie <b>#$orderId</b> Włączono wysyłanie");
}
}
}
}
}
public function processBulkXSendDisable()
{
$identifierList = Tools::getValue($this->list_id . 'Box', []);
if (empty($identifierList)) {
$this->errors[] = $this->l('Nie wybrano zamówienien do wyłączenia.');
} else {
foreach ($identifierList as $orderId) {
foreach (XAllegroCarrier::getPackageInfo($orderId) as $packageInfo) {
if ($packageInfo['send'] && strcasecmp(trim($packageInfo['order_tracking_number']), trim($packageInfo['send_tracking_number'])) == 0) {
$this->module->sessionMessages->confirmations("Zamówienie <b>#$orderId</b> Numer śledzenia został już wysłany");
} else {
XAllegroCarrier::updateSendEnabled(0, $orderId);
$this->module->sessionMessages->confirmations("Zamówienie <b>#$orderId</b> Wyłączono wysyłanie");
}
}
}
}
}
public function printTrackingNumber($id, $row)
{
if ($row['send'] && $row['same_number']) {
return '<span class="badge badge-success">' . $row['send_tracking_number'] . '</span>';
}
else if ($row['send'] && !$row['same_number']) {
return $row['send_tracking_number'] . '&nbsp;<span class="badge badge-warning">' . $this->l('uaktualnij') . '</span>';
}
else if (!$row['carrier_name']) {
return '<span class="badge badge-danger">' . $this->l('brak przewoźnika') . '</span>';
}
else if (!$row['operator_allegro']) {
return '<span class="badge badge-danger">' . $this->l('uzupełnij operatora') . '</span>';
}
return $id;
}
public function displayXSendNumberLink($token = null, $id, $name = null)
{
$row = $this->findElementByKeyValue($this->_list, 'id_order', $id);
if (!$row['tracking_number'] || !$row['delivery_method'] || !$row['operator_allegro'] || $row['same_number'] || !$row['send_enabled']) {
return null;
}
$tpl = $this->context->smarty->createTemplate($this->module->getLocalPath() . 'views/templates/admin/' . $this->tpl_folder . 'helpers/list/action_send_number.tpl');
$tpl->assign(array(
'href' => $this->context->link->getAdminLink('AdminXAllegroOrderShipping') . '&send_number&id_order=' . (int)$id,
'is_send' => (bool)$row['send'],
'title' => (!$row['same_number'] && $row['send'] ? $this->l('Wyślij numer śledzenia ponownie') : $this->l('Wyślij numer śledzenia')),
'action' => (!$row['same_number'] && $row['send'] ? $this->l('Wyślij ponownie') : $this->l('Wyślij')),
));
return $tpl->fetch();
}
public function displayXSendDisableLink($token = null, $id, $name = null)
{
$row = $this->findElementByKeyValue($this->_list, 'id_order', $id);
if (!$row['delivery_method'] || ($row['send'] && $row['same_number'])) {
return null;
}
$tpl = $this->context->smarty->createTemplate($this->module->getLocalPath() . 'views/templates/admin/' . $this->tpl_folder . 'helpers/list/action_send_disabled.tpl');
$tpl->assign(array(
'href' => $this->context->link->getAdminLink('AdminXAllegroOrderShipping') . '&send_disable=' . (int)$row['send_enabled'] . '&id_order=' . (int)$id,
'icon' => ($row['send_enabled'] ? 'text-danger' : 'text-success'),
'title' => ($row['send_enabled'] ? $this->l('Wyłącz wysyłanie numeru śledzenia') : $this->l('Włącz wysyłanie numeru śledzenia')),
'action' => ($row['send_enabled'] ? $this->l('Wyłącz wysyłanie') : $this->l('Włącz wysyłanie'))
));
return $tpl->fetch();
}
public function displayXOrderViewLink($token = null, $id, $name = null)
{
$params = [
'vieworder' => 1,
'id_order' => $id
];
if (version_compare(_PS_VERSION_, '1.7.7.0', '>=')) {
$href = $this->context->link->getAdminLink('AdminOrders', true, $params);
} else {
$href = $this->context->link->getAdminLink('AdminOrders') . '&' . http_build_query($params);
}
$tpl = $this->context->smarty->createTemplate($this->module->getLocalPath() . 'views/templates/admin/' . $this->tpl_folder . 'helpers/list/action_view_order.tpl');
$tpl->assign(array(
'href' => $href,
'title' => $this->l('Zobacz zamówienie'),
'action' => $this->l('Zobacz zamówienie'),
));
return $tpl->fetch();
}
public function ajaxProcessSaveShippingInfo()
{
$error = false;
$order = new Order((int)Tools::getValue('id_order'));
$order_carrier = new OrderCarrier((int)Tools::getValue('id_order_carrier'));
$operator_id = Tools::getValue('operatorId');
$operator_name = Tools::getValue('operatorName');
if ($operator_id != CarrierOperator::OTHER()->getKey()) {
$operator_name = '';
}
if (!Validate::isLoadedObject($order)) {
$error = $this->l('Nie można znaleźć zamówienia w bazie danych.');
}
else if (!Validate::isLoadedObject($order_carrier)) {
$error = $this->l('Identyfikator przewoźnika jest nieprawidłowy.');
}
else if ($operator_id == CarrierOperator::OTHER()->getKey() && empty($operator_name)) {
$error = $this->l('Wybierając przewoźnika "Inny", należy podać jego nazwę.');
}
if ($error) {
die(json_encode(array(
'result' => false,
'message' => $error
)));
}
if (!XAllegroOrder::exists($order->id)) {
die(json_encode(array(
'result' => false,
'message' => $this->l('To zamówienie nie jest powiązane z Allegro.')
)));
}
XAllegroCarrier::updatePackageInfo($order_carrier->id, $order->id, $operator_id, $operator_name);
$adminUrl = $this->context->link->getAdminLink('AdminOrders') . '&conf=4&vieworder&id_order=' . $order->id;
if (version_compare(_PS_VERSION_, '1.7.7.0', '>=')) {
$adminUrl = $this->context->link->getAdminLink('AdminOders', true, array(
'route' => 'admin_orders_view',
'action' => 'view',
'orderId' => (int) $order->id,
));
}
die(json_encode(array(
'result' => true,
'redirect' => $adminUrl
)));
}
public function ajaxProcessSyncShippingNumbers()
{
$ids_added = Tools::getValue('ids_added', array());
$ids_not_added = Tools::getValue('ids_not_added', array());
$count = (int)Tools::getValue('count');
$offset = (int)Tools::getValue('offset');
if ($count == -1) {
$count = XAllegroSyncShipping::getCountSyncShipping();
}
$orders = XAllegroSyncShipping::getSyncShipping(false, $offset);
$offset++;
if (empty($orders)) {
if (empty($ids_added)) {
$this->module->sessionMessages->confirmations($this->l('Brak numerów do wysłania'));
} else {
foreach ($ids_added as $id) {
$this->module->sessionMessages->confirmations($id);
}
}
foreach ($ids_not_added as $id) {
$this->module->sessionMessages->errors($id);
}
die(json_encode(array(
'success' => false,
'link' => $this->context->link->getAdminLink('AdminXAllegroOrderShipping')
)));
}
foreach ($orders as $order) {
$result = XAllegroSyncShipping::sendShippingNumber($order['id_order'], 'list');
if (!$result['result']) {
$ids_not_added[] = 'Zamówienie <b>#' . $order['id_order'] . '</b> ' . $this->l($result['message']) . '<br>';
} else {
$ids_added[] = 'Zamówienie <b>#' . $order['id_order'] . '</b> ' . $this->l($result['message']) . '<br>';
}
}
die(json_encode(array(
'success' => true,
'count' => $count,
'offset' => $offset,
'ids_added' => $ids_added,
'ids_not_added' => $ids_not_added
)));
}
/**
* @param array $list
* @param string $key
* @param int $value
* @return mixed
*/
private function findElementByKeyValue(array $list, $key, $value)
{
foreach ($list as $item)
{
if (is_array($item) && isset($item[$key]) && $item[$key] == $value) {
return $item;
}
else if (is_object($item) && property_exists($item, $key) && $item->{$key} == $value) {
return $item;
}
}
return false;
}
}

View File

@@ -0,0 +1,111 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
final class AdminXAllegroPasController extends XAllegroController
{
private $profileController;
private $shippingRatesController;
protected $allegroAutoLogin = true;
protected $allegroAccountSwitch = true;
public function __construct()
{
parent::__construct();
$this->profileController = new AdminXAllegroPasProfileController();
$this->profileController->token = $this->token;
$this->profileController->init();
$this->shippingRatesController = new AdminXAllegroPasShippingRatesController();
$this->shippingRatesController->token = $this->token;
$this->shippingRatesController->init();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroPas'));
$this->tpl_folder = 'x_allegro_pas/';
}
public function init()
{
foreach ($_GET as $get => $value) {
// add, update, delete
if (preg_match('/^((?!id_).*)xallegro_(.*)$/', $get, $m)) {
if ($m[2] == 'delivery') {
$controller = $this->context->link->getAdminLink('AdminXAllegroPasProfile');
$identifier = $this->profileController->identifier;
}
else if ($m[2] == 'delivery_rate') {
$controller = $this->context->link->getAdminLink('AdminXAllegroPasShippingRates');
$identifier = $this->shippingRatesController->identifier;
}
else {
continue;
}
$url = $controller . '&' . $get . '&' . $identifier . '=' . Tools::getValue($identifier);
if (strpos($m[1], 'submitBulk') !== false) {
unset($_POST['token']);
$url .= '&' . http_build_query($_POST);
}
Tools::redirectAdmin($url);
}
unset($m);
}
parent::init();
}
public function initPageHeaderToolbar()
{
if (empty($this->display))
{
$this->page_header_toolbar_btn['allegro_delivery'] = array(
'href' => $this->context->link->getAdminLink('AdminXAllegroPasProfile') . '&add' . $this->profileController->table,
'desc' => $this->l('Dodaj nowy profil dostawy'),
'icon' => 'process-icon-new'
);
$this->page_header_toolbar_btn['allegro_delivery_rate'] = array(
'href' => $this->context->link->getAdminLink('AdminXAllegroPasShippingRates') . '&add' . $this->shippingRatesController->table,
'desc' => $this->l('Dodaj nowy cennik'),
'icon' => 'process-icon-new'
);
}
parent::initPageHeaderToolbar();
}
public function initContent()
{
parent::initContent();
$messages = [
'confirmations',
'informations',
'warnings',
'errors'
];
foreach ($messages as $message) {
$this->{$message} = array_merge(
$this->{$message},
$this->profileController->{$message},
$this->shippingRatesController->{$message}
);
}
}
public function renderList()
{
return $this->profileController->renderList() .
$this->shippingRatesController->renderList();
}
public function ajaxProcessUpdatePositions()
{
$this->shippingRatesController->ajaxProcessUpdatePositions();
}
}

View File

@@ -0,0 +1,236 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
final class AdminXAllegroPasProfileController extends XAllegroController
{
protected $allegroAutoLogin = true;
protected $allegroAccountSwitch = true;
/** @var XAllegroPas */
public $object;
public function __construct()
{
$this->table = 'xallegro_delivery';
$this->identifier = 'id_xallegro_delivery';
$this->className = 'XAllegroPas';
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroPasProfile'));
$this->tpl_folder = 'x_allegro_pas_profile/';
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?'),
'icon' => 'icon-trash'
)
);
}
public function renderList()
{
if (Tools::getValue('controller') == 'AdminXAllegroPasProfile' && empty($this->errors)) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroPas'));
}
$this->initToolbar();
if (method_exists($this, 'initPageHeaderToolbar')) {
$this->initPageHeaderToolbar();
}
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->fields_list = array(
'id_xallegro_delivery' => array(
'title' => $this->l('ID'),
'align' => 'center',
'width' => 50,
'class' => 'fixed-width-xs'
),
'name' => array(
'title' => $this->l('Nazwa profilu')
),
'default' => array(
'title' => $this->l('Domyślny'),
'active' => 'default',
'width' => 100,
'align' => 'center',
'type' => 'bool',
'class' => 'fixed-width-sm',
),
'active' => array(
'title' => $this->l('Aktywny'),
'active' => 'active',
'width' => 100,
'align' => 'center',
'type' => 'bool',
'class' => 'fixed-width-sm',
)
);
return parent::renderList();
}
public function renderForm()
{
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Profil dostawy'),
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Nazwa profilu'),
'name' => 'name',
'size' => 30,
'class' => 'fixed-width-xxl',
'required' => true
),
array(
'type' => 'select',
'label' => $this->l('Czas wysyłki'),
'name' => 'handling_time',
'required' => true,
'class' => 'fixed-width-xxl',
'options' => array(
'query' => XAllegroPas::getHandlingTimeOptions(),
'id' => 'id',
'name' => 'name'
)
),
array(
'type' => 'textarea',
'label' => $this->l('Dodatkowe informacje o dostawie'),
'name' => 'additional_info',
'class' => 'fixed-width-xxl',
'rows' => 5,
'cols' => 35
),
array(
'type' => 'select',
'label' => $this->l('Kraj'),
'name' => 'country_code',
'class' => 'fixed-width-xxl',
'required' => true,
'options' => array(
'query' => XAllegroPas::getCountryCodeOptions(),
'id' => 'id',
'name' => 'name'
)
),
array(
'type' => 'select',
'label' => $this->l('Województwo'),
'name' => 'province',
'required' => true,
'class' => 'fixed-width-xxl',
'options' => array(
'query' => XAllegroPas::getProvinceOptions(),
'id' => 'id',
'name' => 'name'
)
),
array(
'type' => 'text',
'label' => $this->l('Kod pocztowy'),
'name' => 'post_code',
'required' => true,
'size' => 12,
'class' => 'fixed-width-md',
),
array(
'type' => 'text',
'label' => $this->l('Miasto'),
'name' => 'city',
'class' => 'fixed-width-xxl',
'required' => true,
),
array(
'type' => 'select',
'label' => $this->l('Opcje faktury'),
'name' => 'invoice',
'class' => 'fixed-width-xxl',
'required' => true,
'options' => array(
'query' => XAllegroPas::getInvoiceOptions(),
'id' => 'id',
'name' => 'name'
)
),
array(
'type' => $this->bootstrap ? 'switch' : 'radio',
'label' => $this->l('Domyślny profil'),
'name' => 'default',
'class' => 't',
'is_bool' => true,
'values' => array(
array(
'id' => 'default_on',
'value' => 1,
'label' => $this->l('Tak')
),
array(
'id' => 'default_off',
'value' => 0,
'label' => $this->l('Nie')
)
)
),
array(
'type' => $this->bootstrap ? 'switch' : 'radio',
'label' => $this->l('Aktywny profil'),
'name' => 'active',
'class' => 't',
'is_bool' => true,
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Tak')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('Nie')
)
),
'default_value' => 1
)
),
'submit' => array(
'title' => $this->l('Zapisz')
)
);
return parent::renderForm();
}
public function postProcess()
{
if (Tools::isSubmit('submitAdd' . $this->table) && Tools::getValue('country_code') == 'PL') {
if (!Tools::getValue('province')) {
$this->errors[] = $this->l('Województwo jest wymagane dla kraju Polska');
}
if (!Tools::getValue('post_code')) {
$this->errors[] = $this->l('Kod pocztowy jest wymagany dla kraju Polska');
}
}
return parent::postProcess();
}
public function initContent()
{
if (!empty($this->errors)) {
$this->display = 'edit';
}
parent::initContent();
}
}

View File

@@ -0,0 +1,216 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
use x13allegro\Api\DataProvider\DeliveryMethodsProvider;
use x13allegro\Api\Model\ShippingRates\ShippingRate;
use x13allegro\Json\JsonMapBuilder;
final class AdminXAllegroPasShippingRatesController extends XAllegroController
{
protected $_default_pagination = 1000;
protected $allegroAutoLogin = true;
/** @var StdClass */
private $shippingRate;
public function __construct()
{
$this->table = 'xallegro_delivery_rate';
$this->identifier = 'id_xallegro_delivery_rate';
$this->list_id = 'xallegro_delivery_rate';
$this->multiple_fieldsets = true;
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroPasShippingRates'));
$this->tpl_folder = 'x_allegro_pas_shipping_rates/';
}
public function renderList()
{
if (Tools::getValue('controller') == 'AdminXAllegroPasShippingRates' && empty($this->errors)) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroPas'));
}
$this->initToolbar();
if (method_exists($this, 'initPageHeaderToolbar')) {
$this->initPageHeaderToolbar();
}
$this->addRowAction('edit');
$this->fields_list = array(
'name' => array(
'title' => $this->l('Cennik dostaw'),
'search' => false,
'orderby' => false
),
'default' => array(
'title' => $this->l('Domyślny'),
'active' => 'default',
'align' => 'center',
'type' => 'bool',
'class' => 'fixed-width-sm',
'search' => false,
'orderby' => false
)
);
return parent::renderList();
}
public function renderForm()
{
$id = Tools::getValue($this->identifier);
$deliveryMethods = array();
try {
$dataProvider = new DeliveryMethodsProvider(
$this->allegroApi->sale()->deliveryMethods()->getAll()->deliveryMethods
);
if ($id) {
$this->shippingRate = $this->allegroApi->sale()->shippingRates()->getDetails($id);
}
$deliveryMethods = $dataProvider->getDeliveryMethodsWithShippingRates($this->shippingRate, Tools::getValue('deliveryMethods', []));
$deliveryMethods = $dataProvider->groupDeliveryMethods($deliveryMethods);
}
catch (Exception $ex) {
$this->errors[] = (string)$ex;
}
$this->fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Cennik dostawy'),
),
'input' => array(
array(
'type' => 'hidden',
'name' => $this->identifier
),
array(
'type' => 'text',
'label' => $this->l('Nazwa cennika'),
'name' => 'name',
'size' => 30,
'class' => 'fixed-width-xxl',
'required' => true
)
),
'submit' => array(
'title' => $this->l('Zapisz')
)
);
$this->fields_form[1]['form'] = array(
'legend' => array(
'title' => $this->l('Opcje dostawy'),
),
'delivery_methods' => $deliveryMethods,
'submit' => array(
'title' => $this->l('Zapisz')
)
);
return parent::renderForm();
}
public function postProcess()
{
if (Tools::isSubmit('submitAdd' . $this->table))
{
$deliveryMethods = Tools::getValue('deliveryMethods');
$shippingRateId = Tools::getValue($this->identifier);
$shippingRateName = Tools::getValue('name');
if (!$deliveryMethods) {
$this->errors[] = $this->l('Nie wybrano żadnej metody dostawy');
}
else if (!$shippingRateName) {
$this->errors[] = $this->l('Nie podano nazwy cennika dostawy');
}
if (!empty($this->errors)) {
$this->display = 'edit';
return false;
}
/** @var ShippingRate $shippingRate */
$shippingRate = (new JsonMapBuilder('ShippingRate'))->map(new ShippingRate());
$shippingRate->name = $shippingRateName;
foreach ($deliveryMethods as $id => $deliveryMethod) {
if ($deliveryMethod['enabled']) {
$shippingRate->rate($id, $deliveryMethod['firstItemRate'], $deliveryMethod['nextItemRate'], $deliveryMethod['maxQuantityPerPackage']);
}
}
try {
if ($shippingRateId) {
$shippingRate->id = $shippingRateId;
$this->allegroApi->sale()->shippingRates()->update($shippingRate);
}
else {
$this->allegroApi->sale()->shippingRates()->create($shippingRate);
}
}
catch (Exception $ex) {
$this->errors[] = (string)$ex;
$this->display = 'edit';
return false;
}
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroPas') . '&conf=4');
}
else if (Tools::getIsset('active' . $this->table) || Tools::getIsset('default' . $this->table)) {
return (new XAllegroConfigurationAccount($this->allegroApi->getAccount()->id))
->updateValue('SHIPPING_RATE_DEFAULT_ID', Tools::getValue($this->identifier));
}
return parent::postProcess();
}
public function initContent()
{
if (!empty($this->errors)) {
$this->display = 'edit';
}
parent::initContent();
}
public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
{
try {
$shippingRateDefaultId = (new XAllegroConfigurationAccount($this->allegroApi->getAccount()->id))->get('SHIPPING_RATE_DEFAULT_ID');
$results = $this->allegroApi->sale()->shippingRates()->getAll()->shippingRates;
foreach ($results as $shippingRate) {
$this->_list[] = array(
$this->identifier => $shippingRate->id,
'name' => $shippingRate->name,
'default' => $shippingRate->id === $shippingRateDefaultId
);
}
}
catch (Exception $ex) {
$this->errors[] = (string)$ex;
}
$this->_listTotal = count($this->_list);
}
public function getFieldsValue($obj)
{
parent::getFieldsValue($obj);
$this->fields_value[$this->identifier] = (is_object($this->shippingRate) ? $this->shippingRate->id : null);
$this->fields_value['name'] = Tools::getValue('name', is_object($this->shippingRate) ? $this->shippingRate->name : null);
return $this->fields_value;
}
}

View File

@@ -0,0 +1,516 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
final class AdminXAllegroPerformController extends XAllegroController
{
protected $allegroAutoLogin = true;
protected $allegroAccountSwitch = true;
public function __construct()
{
$this->table = 'product';
$this->className = 'Product';
$this->identifier = 'id_product';
$this->lang = true;
$this->explicitSelect = true;
$this->list_no_link = true;
$this->_defaultOrderBy = 'id_product';
$this->_defaultOrderWay = 'ASC';
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroPerform'));
$this->fields_list = array(
'id_product' => array(
'title' => $this->l('ID'),
'align' => 'center',
'class' => 'fixed-width-xs',
'type' => 'int'
),
'image' => array(
'title' => $this->l('Zdjęcie'),
'align' => 'center',
'image' => 'p',
'class' => 'fixed-width-sm',
'orderby' => false,
'filter' => false,
'search' => false
),
'name' => array(
'title' => $this->l('Nazwa'),
'type' => 'auction_info',
'filter_key' => 'b!name',
'class' => 'fixed-width-xxl'
),
'reference' => array(
'title' => $this->l('Index'),
'filter_key' => 'a!reference',
'align' => 'left',
'class' => 'fixed-width-md'
)
);
if (Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_SHOP) {
$this->fields_list = array_merge($this->fields_list, array(
'shopname' => array(
'title' => $this->l('Domyślny sklep'),
'filter_key' => 'shop!name',
'class' => 'fixed-width-lg'
)
));
} else {
$this->fields_list = array_merge($this->fields_list, array(
'name_category' => array(
'title' => $this->l('Kategoria'),
'filter_key' => 'cl!name',
'class' => 'fixed-width-lg'
)
));
}
if (Configuration::get('PS_STOCK_MANAGEMENT')) {
$this->fields_list = array_merge($this->fields_list, array(
'sav_quantity' => array(
'title' => $this->l('Ilość'),
'type' => 'int',
'align' => 'text-right',
'class' => 'fixed-width-sm',
'filter_key' => 'sav!quantity',
'badge_danger' => true
)
));
}
$this->fields_list = array_merge($this->fields_list, array(
'price_final' => array(
'title' => $this->l('Cena ost.'),
'type' => 'price',
'align' => 'text-right',
'class' => 'fixed-width-sm',
'havingFilter' => true,
'search' => false
),
'active' => array(
'title' => $this->l('Akt.'),
'active' => 'status',
'filter_key' => 'sa!active',
'align' => 'text-center',
'type' => 'bool',
'class' => 'fixed-width-xs',
'search' => false
),
'allegro_status' => array(
'title' => $this->l('Wyst.'),
'icon' => array(
// ukrywamy ikone gdy produkt nie jest wystawiony
//'0' => array('class' => 'icon-remove', 'src' => 'disabled.gif', 'alt' => ''),
'1' => array('class' => 'icon-check', 'src' => 'enabled.gif', 'alt' => $this->l('Wystawiony')),
'2' => array('class' => 'icon-time', 'src' => 'time.gif', 'alt' => $this->l('Zaplanowany'))
),
'align' => 'text-center',
'class' => 'fixed-width-xs',
'orderby' => false,
'filter' => false,
'search' => false
)
));
$this->assignXFilters();
$this->tpl_folder = 'x_allegro_perform/';
$this->bulk_actions['xAllegro'] = array('icon' => 'icon-gavel bulkPerformAuctions', 'text' => $this->l('Wystaw zaznaczone'));
}
public function initProcess()
{
if (Tools::getIsset('sync_closed')) {
$count = (int)Tools::getValue('sync_closed');
$this->confirmations[] = $this->l('Zakończono synchronizację statusów ofert.') . '<br>' .
'<b>' .($count
? $this->l('Zaktualizowane statusy') . ': ' . (int)Tools::getValue('sync_closed')
: $this->l('Wszystkie oferty są aktualne!')
) . '</b>';
}
parent::initProcess();
}
public function renderList()
{
$this->addRowAction('xAllegro');
$this->addRowAction('xEdit');
return parent::renderList();
}
public function getList($id_lang, $orderBy = null, $orderWay = null, $start = 0, $limit = null, $id_lang_shop = null)
{
$id_shop = Shop::isFeatureActive() && Shop::getContext() == Shop::CONTEXT_SHOP ? (int)$this->context->shop->id : 'a.id_shop_default';
if (version_compare(_PS_VERSION_, '1.6.1.0', '<'))
{
$select_image = 'MAX(image_shop.`id_image`) AS id_image';
$join_image = '
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = a.`id_product`)
LEFT JOIN `'._DB_PREFIX_.'image_shop` image_shop ON (image_shop.`id_image` = i.`id_image` AND image_shop.`cover` = 1 AND image_shop.id_shop = ' . $id_shop . ')';
}
else {
$select_image = 'image_shop.`id_image` AS `id_image`';
$join_image = '
LEFT JOIN `'._DB_PREFIX_.'image_shop` image_shop ON (image_shop.`id_product` = a.`id_product` AND image_shop.`cover` = 1 AND image_shop.id_shop = ' . $id_shop . ')
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_image` = image_shop.`id_image`)';
}
$this->_select .= 'shop.`name` AS `shopname`, a.`id_shop_default`, ' . $select_image . ',
cl.`name` AS `name_category`, 0 AS `price_final`, taxRule.`price_tmp`, sav.`quantity` AS `sav_quantity`,
IF(sav.`quantity`<=0, 1, 0) AS `badge_danger`, 0 AS `allegro_status`';
$this->_join .= ' JOIN `'._DB_PREFIX_.'product_shop` sa ON (a.`id_product` = sa.`id_product` AND sa.id_shop = ' . $id_shop . ')
LEFT JOIN (
SELECT sa.`id_product`, sa.`price` * IF(t.`rate`, ((100 + (t.`rate`))/100), 1) as price_tmp
FROM `' . _DB_PREFIX_ . 'product_shop` sa
LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr
ON (sa.`id_tax_rules_group` = tr.`id_tax_rules_group`
AND tr.`id_country` = ' . (int)Configuration::get('PS_COUNTRY_DEFAULT') . '
AND tr.`id_state` = 0)
LEFT JOIN `' . _DB_PREFIX_ . 'tax` t
ON (t.`id_tax` = tr.`id_tax`)
) as taxRule
ON (taxRule.`id_product` = sa.`id_product`)
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (sa.`id_category_default` = cl.`id_category` AND b.`id_lang` = cl.`id_lang` AND cl.id_shop = ' . $id_shop . ')
LEFT JOIN `'._DB_PREFIX_.'shop` shop ON (shop.id_shop = ' . $id_shop . ')' .
$join_image .'
LEFT JOIN `'._DB_PREFIX_.'stock_available` sav ON (sav.`id_product` = a.`id_product` AND sav.`id_product_attribute` = 0' . StockAvailable::addSqlShopRestriction(null, null, 'sav') . ')';
if ($this->allegroCookie->{$this->getAllegroCookieFilter('Category')}) {
$filteredCategories = json_decode($this->allegroCookie->{$this->getAllegroCookieFilter('Category')}, true);
if (is_array($filteredCategories)) {
$this->_select .= ', cp.`position`';
$this->_join .= ' INNER JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_product` = a.`id_product` AND cp.`id_category` IN ('.implode(',', json_decode($this->allegroCookie->{$this->getAllegroCookieFilter('Category')}, true)).')) ';
}
}
if ($this->allegroCookie->{$this->getAllegroCookieFilter('Manufacturer')}) {
$this->_join .= ' INNER JOIN `'._DB_PREFIX_.'manufacturer` pm ON (a.`id_manufacturer` = pm.`id_manufacturer` AND pm.`active` = 1 AND pm.`id_manufacturer` IN(' . $this->allegroCookie->{$this->getAllegroCookieFilter('Manufacturer')} . '))';
}
if ($this->allegroCookie->{$this->getAllegroCookieFilter('Supplier')}) {
$this->_join .= ' INNER JOIN `'._DB_PREFIX_.'supplier` ps ON (a.`id_supplier` = ps.`id_supplier` AND ps.`active` = 1 AND ps.`id_supplier` IN(' . $this->allegroCookie->{$this->getAllegroCookieFilter('Supplier')} . '))';
}
if ($this->allegroCookie->{$this->getAllegroCookieFilter('PriceFrom')} > 0) {
$this->_where .= ' AND taxRule.`price_tmp` >= "' . pSQL((float)$this->allegroCookie->{$this->getAllegroCookieFilter('PriceFrom')}) . '"';
}
if ($this->allegroCookie->{$this->getAllegroCookieFilter('PriceTo')} > 0) {
$this->_where .= ' AND taxRule.`price_tmp` <= "' . pSQL((float)$this->allegroCookie->{$this->getAllegroCookieFilter('PriceTo')}) . '"';
}
if ($this->allegroCookie->{$this->getAllegroCookieFilter('QtyFrom')} > 0) {
$this->_where .= ' AND sav.`quantity` >= ' . (int)$this->allegroCookie->{$this->getAllegroCookieFilter('QtyFrom')};
}
if ($this->allegroCookie->{$this->getAllegroCookieFilter('QtyTo')} > 0) {
$this->_where .= ' AND sav.`quantity` <= ' . (int)$this->allegroCookie->{$this->getAllegroCookieFilter('QtyTo')};
}
if ($this->allegroCookie->{$this->getAllegroCookieFilter('Active')}) {
$this->_where .= ' AND sa.`active` = ' . ((int)$this->allegroCookie->{$this->getAllegroCookieFilter('Active')} - 1);
}
$this->_where .= ' AND (a.`reference` IS NULL OR a.`reference` NOT LIKE "x13allegro-empty-product")';
if ($this->allegroCookie->{$this->getAllegroCookieFilter('Performed')})
{
$this->_select .= ', COUNT(xaa.`id_xallegro_auction`) AS allegro_status_count, COUNT(DISTINCT xaa.`id_product_attribute`) AS allegro_status_combinations_count,
(SELECT COUNT(pa.`id_product_attribute`)
FROM `'._DB_PREFIX_.'product_attribute` pa
WHERE a.`id_product` = pa.`id_product`
) AS combinations,';
$this->_join .= 'LEFT JOIN `'._DB_PREFIX_.'xallegro_auction` xaa
ON (a.`id_product` = xaa.`id_product`
AND xaa.id_shop = ' . $id_shop . '
AND (xaa.`closed` = 0 OR xaa.`start` = 1)
AND xaa.`id_xallegro_account` = ' . $this->allegroApi->getAccount()->id . ')';
if ($this->allegroCookie->{$this->getAllegroCookieFilter('Performed')} == 1) {
$this->_having .= 'allegro_status_count > 0';
}
else if ($this->allegroCookie->{$this->getAllegroCookieFilter('Performed')} == 2) {
$this->_having .= 'allegro_status_count > 0 AND (combinations = 0 OR allegro_status_combinations_count = combinations)';
}
else if ($this->allegroCookie->{$this->getAllegroCookieFilter('Performed')} == 3) {
$this->_having .= 'allegro_status_count = 0';
}
else if ($this->allegroCookie->{$this->getAllegroCookieFilter('Performed')} == 4) {
$this->_having .= 'allegro_status_count = 0 OR (allegro_status_count > 0 AND allegro_status_combinations_count < combinations)';
}
}
$this->_group = 'GROUP BY a.`id_product`';
$orderByPriceFinal = (empty($orderBy) ? (Tools::getValue($this->table . 'Orderby') ? Tools::getValue($this->table . 'Orderby') : 'id_' . $this->table) : $orderBy);
$orderWayPriceFinal = (empty($orderWay) ? (Tools::getValue($this->table . 'Orderway') ? Tools::getValue($this->table . 'Orderway') : 'ASC') : $orderWay);
parent::getList($this->allegroApi->getAccount()->id_language, $orderBy, $orderWay, $start, $limit, $this->context->shop->id);
$auctions_info = XAllegroAuction::getAuctionsStatusDetail($this->allegroApi->getAccount()->id, $this->context->shop->id);
/* complete product data */
$nb = is_array($this->_list) ? count($this->_list) : 0;
if ($nb) {
$context = $this->context->cloneContext();
$context->shop = clone($context->shop);
for ($i = 0; $i < $nb; $i++) {
if (Context::getContext()->shop->getContext() != Shop::CONTEXT_SHOP) {
$context->shop = new Shop((int)$this->_list[$i]['id_shop_default']);
}
// convert price to final Currency
$this->_list[$i]['id_currency'] = $this->allegroApi->getCurrency()->id;
$this->_list[$i]['price_final'] =
XAllegroProduct::convertPrice(
XAllegroProduct::getProductStaticPrice(
$this->_list[$i]['id_product'],
0,
(new XAllegroConfigurationAccount($this->allegroApi->getAccount()->id))->get('AUCTION_PRICE_CUSTOMER_GROUP', true),
$this->context
),
$this->context->currency,
$this->allegroApi->getCurrency()
);
// get information about active offers
if (isset($auctions_info[$this->_list[$i]['id_product']])) {
$this->_list[$i]['auction_info'] = array(
'qty' => $auctions_info[$this->_list[$i]['id_product']]['qty'] - $auctions_info[$this->_list[$i]['id_product']]['planned_qty'],
'auctions_nb' => $auctions_info[$this->_list[$i]['id_product']]['auctions_nb'] - $auctions_info[$this->_list[$i]['id_product']]['planned_nb'],
'planned_qty' => $auctions_info[$this->_list[$i]['id_product']]['planned_qty'],
'planned_nb' => $auctions_info[$this->_list[$i]['id_product']]['planned_nb'],
'combinations_nb' => $auctions_info[$this->_list[$i]['id_product']]['combinations_nb'],
'combinations_total' => $auctions_info[$this->_list[$i]['id_product']]['combinations_total']
);
$this->_list[$i]['class'] = 'exposed';
}
$this->_list[$i]['allegro_status'] = 0;
if (isset($this->_list[$i]['auction_info'])) {
if ($this->_list[$i]['auction_info']['planned_nb'] > 0) {
$this->_list[$i]['allegro_status'] = 2;
}
else if ($this->_list[$i]['auction_info']['auctions_nb'] > 0) {
$this->_list[$i]['allegro_status'] = 1;
}
}
}
if ($orderByPriceFinal == 'price_final') {
if (strtolower($orderWayPriceFinal) == 'desc') {
uasort($this->_list, 'cmpPriceDesc');
} else {
uasort($this->_list, 'cmpPriceAsc');
}
}
}
}
private function assignXFilters()
{
if (Tools::getValue('reset_xFilter')) {
unset(
$this->allegroCookie->{$this->getAllegroCookieFilter('Category')},
$this->allegroCookie->{$this->getAllegroCookieFilter('PriceFrom')},
$this->allegroCookie->{$this->getAllegroCookieFilter('PriceTo')},
$this->allegroCookie->{$this->getAllegroCookieFilter('QtyFrom')},
$this->allegroCookie->{$this->getAllegroCookieFilter('QtyTo')},
$this->allegroCookie->{$this->getAllegroCookieFilter('Manufacturer')},
$this->allegroCookie->{$this->getAllegroCookieFilter('Supplier')},
$this->allegroCookie->{$this->getAllegroCookieFilter('Performed')},
$this->allegroCookie->{$this->getAllegroCookieFilter('Active')}
);
}
else if (Tools::isSubmit('submit_xFilter'))
{
if (is_numeric(Tools::getValue('productFilter_cl!name')))
{
$category = new Category((int)Tools::getValue('productFilter_cl!name'));
if (Validate::isLoadedObject($category) && $category->inShop($this->context->shop)) {
$_POST['productFilter_cl!name'] = $category->name[$this->allegroApi->getAccount()->id_language];
}
}
else {
if (Tools::getValue('xFilterCategory')) {
$xFilterCategory = Tools::getValue('xFilterCategory');
} else if ($this->allegroCookie->{$this->getAllegroCookieFilter('Category')}) {
$xFilterCategory = json_decode($this->allegroCookie->{$this->getAllegroCookieFilter('Category')}, true);
} else {
$xFilterCategory = false;
}
// sprawdzamy czy wybrane kategorie wystepuja w aktywnym sklepie
if ($xFilterCategory) {
$xFilterCategory = $this->existsInShop($xFilterCategory, $this->context->shop->id);
}
}
$this->allegroCookie->{$this->getAllegroCookieFilter('Category')} = (isset($xFilterCategory) && is_array($xFilterCategory) ? json_encode($xFilterCategory) : false);
$this->allegroCookie->{$this->getAllegroCookieFilter('PriceFrom')} = (float)Tools::getValue('xFilterPriceFrom');
$this->allegroCookie->{$this->getAllegroCookieFilter('PriceTo')} = (float)Tools::getValue('xFilterPriceTo');
$this->allegroCookie->{$this->getAllegroCookieFilter('QtyFrom')} = (int)Tools::getValue('xFilterQtyFrom');
$this->allegroCookie->{$this->getAllegroCookieFilter('QtyTo')} = (int)Tools::getValue('xFilterQtyTo');
// multi-filters
$this->allegroCookie->{$this->getAllegroCookieFilter('Manufacturer')} = trim(implode(',', Tools::getValue('xFilterManufacturer', [])), " ,");
$this->allegroCookie->{$this->getAllegroCookieFilter('Supplier')} = trim(implode(',', Tools::getValue('xFilterSupplier', [])), " ,");
$this->allegroCookie->{$this->getAllegroCookieFilter('Active')} = (int)Tools::getValue('xFilterActive');
$this->allegroCookie->{$this->getAllegroCookieFilter('Performed')} = (int)Tools::getValue('xFilterPerformed');
}
}
public function renderAllegroLink($id, $label, $url)
{
$allegro_status = (int) XAllegroAuction::getAuctionsStatus($id, null, $this->allegroApi->getAccount()->id, $this->context->shop->id);
if (0 == $allegro_status) {
$color = '';
$icon = 'AdminXAllegroMainDefault.png';
$txt = $label;
} else {
$color = 'color: #FF5A00;';
$icon = 'AdminXAllegroMain.png';
$txt = $this->l('Wystawiony').' ('.$allegro_status.')';
}
$tpl = $this->context->smarty->createTemplate(
$this->module->getLocalPath().'views/templates/admin/'.$this->tpl_folder.'helpers/list/action_xallegro.tpl'
);
$tpl->assign([
'href' => $url,
'button_txt' => $txt,
'title' => $this->l('Wystaw produkt na Allegro'),
'id' => $id,
'color' => $color,
'icon' => $icon,
'auction' => $allegro_status,
]);
return $tpl->fetch();
}
public function displayXAllegroLink($token = null, $id, $name = null)
{
$label = $this->l('Wystaw');
$url = $this->context->link->getAdminLink('AdminXAllegroMain').'&id_product='.$id;
return $this->renderAllegroLink($id, $label, $url);
}
public function displayXEditLink($token = null, $id, $name = null)
{
if (version_compare(_PS_VERSION_, '1.7.0.0', '>=')) {
$href = $this->context->link->getAdminLink('AdminProducts', true, array('id_product' => $id));
}
else {
$href = $this->context->link->getAdminLink('AdminProducts') . '&updateproduct&id_product=' . $id;
}
$tpl = $this->context->smarty->createTemplate($this->module->getLocalPath() . 'views/templates/admin/' . $this->tpl_folder . 'helpers/list/action_xedit.tpl');
$tpl->assign(array(
'href' => $href,
'action' => $this->l('Edytuj'),
'id' => $id
));
return $tpl->fetch();
}
public function processBulkXAllegro()
{
if (is_array($this->boxes) && !empty($this->boxes)) {
$this->redirect_after = $this->context->link->getAdminLink('AdminXAllegroMain')
. '&id_product=' . implode(',', array_map('intval', $this->boxes));
}
}
public function initContent($token = null)
{
if (!defined('X13_ALLEGRO_DISABLE_CATEGORY_TREE')) {
if (!$this->allegroCookie->{$this->getAllegroCookieFilter('Category')}) {
$selected_categories = [(int) Configuration::get('PS_ROOT_CATEGORY')];
} else {
$selected_categories = json_decode($this->allegroCookie->{$this->getAllegroCookieFilter('Category')}, true);
if (!is_array($selected_categories)) {
$selected_categories = [(int) Configuration::get('PS_ROOT_CATEGORY')];
}
}
$tree = new HelperTreeCategories('xFilterCategories', $this->l('Kategorie'));
$category_tree = $tree->setInputName('xFilterCategory')
->setUseCheckBox(true)
->setRootCategory(Category::getRootCategory()->id)
->setSelectedCategories($selected_categories)
->render();
}
else {
$category_tree = false;
}
$this->tpl_list_vars['category_tree'] = $category_tree;
$this->tpl_list_vars['manufacturers'] = Manufacturer::getManufacturers(false, $this->allegroApi->getAccount()->id_language);
$this->tpl_list_vars['suppliers'] = Supplier::getSuppliers(false, $this->allegroApi->getAccount()->id_language);
$this->tpl_list_vars['xFilterPriceFrom'] = (float)$this->allegroCookie->{$this->getAllegroCookieFilter('PriceFrom')};
$this->tpl_list_vars['xFilterPriceTo'] = (float)$this->allegroCookie->{$this->getAllegroCookieFilter('PriceTo')};
$this->tpl_list_vars['xFilterQtyFrom'] = (int)$this->allegroCookie->{$this->getAllegroCookieFilter('QtyFrom')};
$this->tpl_list_vars['xFilterQtyTo'] = (int)$this->allegroCookie->{$this->getAllegroCookieFilter('QtyTo')};
// multi-filters
$this->tpl_list_vars['xFilterManufacturer'] = explode(',', $this->allegroCookie->{$this->getAllegroCookieFilter('Manufacturer')});
$this->tpl_list_vars['xFilterSupplier'] = explode(',', $this->allegroCookie->{$this->getAllegroCookieFilter('Supplier')});
$this->tpl_list_vars['xFilterActive'] = (int)$this->allegroCookie->{$this->getAllegroCookieFilter('Active')};
$this->tpl_list_vars['xFilterPerformed'] = (int)$this->allegroCookie->{$this->getAllegroCookieFilter('Performed')};
parent::initContent();
}
/**
* Zwraca tylko te kategorie ktore przypisane sa do podanego id sklepu
*
* @param array $categories
* @param int $id_shop
* @return array
* @throws PrestaShopDatabaseException
*/
private function existsInShop(array $categories, $id_shop)
{
if (empty($categories)) {
return array();
}
$result = Db::getInstance()->executeS('
SELECT `id_category`
FROM `'._DB_PREFIX_.'category_shop`
WHERE `id_category` IN (' . implode(',', $categories) . ')
AND `id_shop` = ' . (int) $id_shop
);
$cats = array();
if (!$result) {
return $cats;
}
foreach ($result as $row) {
$cats[] = $row['id_category'];
}
return $cats;
}
}

View File

@@ -0,0 +1,111 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
use x13allegro\Repository\ProductCustomRepository;
final class AdminXAllegroProductsExtraController extends XAllegroController
{
/** @var XAllegroHelperProductExtra */
private $xHelperProduct;
public function init()
{
parent::init();
$product = new Product((int)Tools::getValue('productId'));
if (!Validate::isLoadedObject($product)) {
die(json_encode([
'result' => false,
'message' => $this->l('Musisz zapisać produkt przed zmianą ustawień Allegro')
]));
}
$this->xHelperProduct = new XAllegroHelperProductExtra(
new XAllegroProduct(null, $product->id)
);
}
public function ajaxProcessSaveProduct()
{
$this->xHelperProduct->setAccountId((int)Tools::getValue('xallegro_product_custom_account'));
$this->xHelperProduct->processProductExtra($this->errors);
Hook::exec('actionX13AllegroAdminProductsExtraSave', [
'id_product' => (int)Tools::getValue('productId')
]);
if (empty($this->errors)) {
die(json_encode([
'result' => true,
'message' => $this->l('Ustawienia Allegro zostały zapisane'),
'html' => $this->xHelperProduct->generateImagesAdditionalForm()
]));
}
else {
die(json_encode([
'result' => false,
'message' => $this->errors
]));
}
}
public function ajaxProcessChangeAccount()
{
$this->xHelperProduct->setAccountId((int)Tools::getValue('accountId'));
die(json_encode([
'html' => $this->xHelperProduct->generateProductCustomForm(),
]));
}
public function ajaxProcessDeleteCustomPrices()
{
ProductCustomRepository::deletePrices((int)Tools::getValue('productId'));
die(json_encode([
'result' => true,
'message' => $this->l('Poprawnie skasowano ceny dedykowane')
]));
}
public function ajaxProcessUploadAdditionalImage()
{
$this->xHelperProduct->processImagesAdditional($this->errors, Tools::getValue('imageAdditionalUpdate'))
->saveProduct();
if (empty($this->errors)) {
die(json_encode([
'result' => true,
'message' => $this->l('Dodano nowe zdjęcie'),
'html' => $this->xHelperProduct->generateImagesAdditionalForm()
]));
}
else {
die(json_encode([
'result' => false,
'message' => $this->errors
]));
}
}
public function ajaxProcessDeleteAdditionalImage()
{
$this->xHelperProduct->deleteImageAdditional($this->errors);
if (empty($this->errors)) {
die(json_encode([
'result' => true,
'message' => $this->l('Zdjęcie zostało usunięte'),
'html' => $this->xHelperProduct->generateImagesAdditionalForm()
]));
}
else {
die(json_encode([
'result' => false,
'message' => $this->errors
]));
}
}
}

View File

@@ -0,0 +1,246 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
use x13allegro\Api\Model\Marketplace\Enum\Marketplace;
use x13allegro\Component\Configuration\ConfigurationDependencies;
use x13allegro\Repository\FulfillmentStatusRepository;
final class AdminXAllegroStatusController extends XAllegroController
{
/** @var XAllegroStatus[] */
private $allegroOrderStates = [];
/** @var FulfillmentStatusRepository[] */
private $allegroFulfillmentStates = [];
public function __construct()
{
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroStatus'));
$this->toolbar_title = $this->l('Powiązania statusów zamowień');
$this->multiple_fieldsets = true;
$this->tpl_folder = 'x_allegro_status/';
}
public function init()
{
parent::init();
$this->display = 'edit';
$this->allegroOrderStates = XAllegroStatus::values();
$this->allegroFulfillmentStates = FulfillmentStatusRepository::values();
}
public function renderForm()
{
$statusByMarketplace = XAllegroConfiguration::get('ORDER_STATUS_BY_MARKETPLACE');
$orderStates = OrderState::getOrderStates($this->context->language->id);
$marketplaces = Marketplace::values();
// default Order states
$inputOrderStates = $this->prepareStatusesTab('default', $orderStates);
$tabOrderStates = null;
if ($statusByMarketplace) {
$tabOrderStates['marketplace_default'] = $this->l('Domyślny');
foreach ($marketplaces as $marketplace) {
$inputOrderStates = array_merge($inputOrderStates, $this->prepareStatusesTab($marketplace->getValue(), $orderStates));
$tabOrderStates['marketplace_' . $marketplace->getValue()] = $marketplace->getValueTranslated();
}
}
$inputAllegroStates = [];
foreach ($this->allegroFulfillmentStates as $fulfillmentState) {
$inputAllegroStates[] = [
'label' => $fulfillmentState->getValue(),
'type' => 'select',
'allegro_fulfillment' => $fulfillmentState->getKey(),
'name' => 'allegro_fulfillment[' . $fulfillmentState->getKey() . '][]',
'class' => 'fixed-width-xxl',
'options' => [
'query' => $orderStates,
'id' => 'id_order_state',
'name' => 'name'
]
];
}
$this->fields_form = [
[
'form' => [
'legend' => [
'title' => $this->l('Powiązania statusów PrestaShop')
],
'tabs' => $tabOrderStates,
'input' => $inputOrderStates,
'submit' => [
'title' => $this->l('Zapisz')
]
]
],
[
'form' => [
'legend' => [
'title' => $this->l('Powiązania statusów Allegro')
],
'input' => $inputAllegroStates,
'submit' => [
'title' => $this->l('Zapisz')
]
]
],
[
'form' => [
'legend' => [
'title' => $this->l('Dodatkowe ustawienia')
],
'input' => [
[
'label' => $this->l('Zmień status Allegro po przekazaniu numeru przewozowego'),
'name' => 'shipping_number_status',
'configName' => 'ORDER_ALLEGRO_SHIPPING_STATUS',
'type' => 'switch',
'values' => [
['id' => 'default_on', 'value' => 1, 'label' => $this->l('Tak')],
['id' => 'default_off', 'value' => 0, 'label' => $this->l('Nie')]
]
],
[
'label' => $this->l('Status Allegro po przekazaniu numeru przewozowego'),
'name' => 'shipping_number_status_fulfillment',
'configName' => 'ORDER_ALLEGRO_SHIPPING_STATUS_FULFILLMENT',
'type' => 'select',
'class' => 'fixed-width-xxl',
'options' => [
'query' => FulfillmentStatusRepository::toChoseList(),
'id' => 'id',
'name' => 'name'
],
'form_group_class' => ConfigurationDependencies::fieldDependsOn(
ConfigurationDependencies::fieldMatch(),
['shipping_number_status' => 1]
)
],
[
'label' => $this->l('Podziel statusy zamówień PrestaShop według rynków Allegro'),
'name' => 'status_by_marketplace',
'configName' => 'ORDER_STATUS_BY_MARKETPLACE',
'type' => 'switch',
'values' => [
['id' => 'default_on', 'value' => 1, 'label' => $this->l('Tak')],
['id' => 'default_off', 'value' => 0, 'label' => $this->l('Nie')]
]
]
],
'submit' => [
'title' => $this->l('Zapisz')
]
]
]
];
return parent::renderForm();
}
public function postProcess()
{
if (Tools::isSubmit('submitAdd' . $this->table)) {
if ($this->tabAccess['edit'] !== '1') {
$this->errors[] = $this->l('Nie masz uprawnień do edycji w tym miejscu.');
}
else {
if (XAllegroStatus::updateStatuses(Tools::getValue('allegro_status', []), (bool)Tools::getValue('status_by_marketplace'))
&& FulfillmentStatusRepository::updateStatuses(Tools::getValue('allegro_fulfillment', []))
&& XAllegroConfiguration::updateValue('ORDER_ALLEGRO_SHIPPING_STATUS', Tools::getValue('shipping_number_status'))
&& XAllegroConfiguration::updateValue('ORDER_ALLEGRO_SHIPPING_STATUS_FULFILLMENT', Tools::getValue('shipping_number_status_fulfillment'))
&& XAllegroConfiguration::updateValue('ORDER_STATUS_BY_MARKETPLACE', Tools::getValue('status_by_marketplace'))
) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroStatus') . '&conf=4');
}
$this->errors[] = $this->l('Wystąpił błąd podczas aktualizacji powiązań');
}
}
$this->display = 'edit';
return true;
}
public function getFieldsValue($obj)
{
foreach ($this->fields_form as $fieldset) {
if (isset($fieldset['form']['input'])) {
foreach ($fieldset['form']['input'] as $input) {
if (!isset($this->fields_value[$input['name']])) {
if (isset($input['allegro_status'])) {
$orderState = $this->allegroOrderStates[$input['allegro_status']]->getOrderState($input['allegro_marketplace'], $this->context->language->id, $input['allegro_marketplace'] != 'default');
$this->fields_value[$input['name'] . '[id_order_state]'] = (Validate::isLoadedObject($orderState) ? $orderState->id : null);
} else if (isset($input['allegro_fulfillment'])) {
$this->fields_value[$input['name']] = $this->allegroFulfillmentStates[$input['allegro_fulfillment']]->getAssignedOrderStatesIds();
} else if (isset($input['configName'])) {
$this->fields_value[$input['name']] = XAllegroConfiguration::get($input['configName']);
}
}
}
}
}
return $this->fields_value;
}
/**
* @param string $marketplaceId
* @param array $orderStates
* @return array
*/
private function prepareStatusesTab($marketplaceId, array $orderStates)
{
$inputOrderStates = [];
foreach ($this->allegroOrderStates as $allegroStatus) {
$state = $allegroStatus->getAllegroState($this->context->language->id);
$inputOrderStates[] = [
'label' => $allegroStatus->getValueTranslated(),
'hint' => ($allegroStatus->equals(XAllegroStatus::CANCELLED()) ? $this->l('Ten status nie przywraca ilości produktów, zamawiający może ponowić płatność') : null),
'allegro_status' => $allegroStatus->getKey(),
'allegro_marketplace' => $marketplaceId,
'name' => 'allegro_status[' . $marketplaceId . '][' . $allegroStatus->getKey() . ']',
'tab' => 'marketplace_' . $marketplaceId,
'class' => 'fixed-width-xxl',
'type' => 'select',
'options' => [
'query' => $this->prepareStatusesArray($state, $orderStates),
'id' => 'id_order_state',
'name' => 'name'
]
];
}
return $inputOrderStates;
}
/**
* @param OrderState $orderState
* @param array $statuses
* @return array
*/
private function prepareStatusesArray(OrderState $orderState, array $statuses)
{
$statusesArray = [];
foreach ($statuses as $status) {
$statusesArray[] = [
'id_order_state' => $status['id_order_state'],
'name' => $status['name'],
'disabled' => ($status['logable'] != $orderState->logable
|| $status['paid'] != $orderState->paid
|| $status['invoice'] != $orderState->invoice)
];
}
return $statusesArray;
}
}

View File

@@ -0,0 +1,106 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
use x13allegro\Api\XAllegroApi;
use x13allegro\Api\Model\Tag;
use x13allegro\Json\JsonMapBuilder;
final class AdminXAllegroTagManagerController extends XAllegroController
{
protected $allegroAutoLogin = true;
public function __construct()
{
parent::__construct();
}
public function ajaxProcessTagNew()
{
/** @var Tag $tag */
$tag = (new JsonMapBuilder('Tag'))->map(new Tag());
$tag->name = trim(substr(Tools::getValue('tagName'), 0, XAllegroApi::TAG_MAX_CHARS));
try {
$this->allegroApi->sale()->tags()->create($tag);
}
catch (Exception $ex) {
die(json_encode(array(
'result' => false,
'message' => (string)$ex
)));
}
switch (Tools::getValue('tagMapType'))
{
case XAllegroTagManager::MAP_PRODUCT:
$object = new XAllegroProduct(null, Tools::getValue('tagMapId'));
break;
case XAllegroTagManager::MAP_CATEGORY:
$object = new XAllegroCategory(Tools::getValue('tagMapId'));
break;
case XAllegroTagManager::MAP_MANUFACTURER:
$object = new XAllegroManufacturer(Tools::getValue('tagMapId'));
break;
case XAllegroTagManager::MAP_AUCTION:
$object = new XAllegroCategory(XAllegroCategory::getIdByAllegroCategory(Tools::getValue('tagMapId')));
break;
default:
die(json_encode(array(
'result' => false,
'message' => $this->l('Nieprawidłowy typ mapowania')
)));
}
die(json_encode(array(
'result' => true,
'message' => $this->l('Nowy tag został dodany'),
'html' => (new XAllegroHelperTagManager())->renderTagsTable($this->allegroApi, $object->tags)
)));
}
public function ajaxProcessTagSave()
{
/** @var Tag $tag */
$tag = (new JsonMapBuilder('Tag'))->map(new Tag());
$tag->id = Tools::getValue('tagId');
$tag->name = trim(substr(Tools::getValue('tagName'), 0, XAllegroApi::TAG_MAX_CHARS));
try {
$this->allegroApi->sale()->tags()->update($tag);
}
catch (Exception $ex) {
die(json_encode(array(
'result' => false,
'message' => (string)$ex
)));
}
die(json_encode(array(
'result' => true,
'message' => $this->l('Tag został zapisany')
)));
}
public function ajaxProcessTagDelete()
{
try {
$this->allegroApi->sale()->tags()->deleteTag(Tools::getValue('tagId'));
}
catch (Exception $ex) {
die(json_encode(array(
'result' => false,
'message' => (string)$ex
)));
}
die(json_encode(array(
'result' => true,
'message' => $this->l('Tag został usunięty')
)));
}
}

View File

@@ -0,0 +1,398 @@
<?php
require_once (dirname(__FILE__) . '/../../x13allegro.php');
use x13allegro\Api\XAllegroApi;
final class AdminXAllegroTemplatesController extends XAllegroController
{
/** @var XAllegroTemplate */
public $object;
public function __construct()
{
$this->table = 'xallegro_template';
$this->identifier = 'id_xallegro_template';
$this->className = 'XAllegroTemplate';
parent::__construct();
$this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminXAllegroTemplates'));
$this->fields_list = array(
'id_xallegro_template' => array(
'title' => $this->l('ID'),
'align' => 'center',
'width' => 20,
'class' => 'fixed-width-xs'
),
'name' => array(
'title' => $this->l('Nazwa szablonu'),
'width' => 'auto'
),
'default' => array(
'title' => $this->l('Domyślny'),
'width' => 70,
'class' => 'fixed-width-sm',
'align' => 'center',
'active' => 'default',
'type' => 'bool'
),
'active' => array(
'title' => $this->l('Aktywny'),
'width' => 70,
'align' => 'center',
'active' => 'active',
'type' => 'bool',
'class' => 'fixed-width-sm'
)
);
$this->addRowAction('edit');
$this->addRowAction('xduplicate');
$this->addRowAction('delete');
$this->tpl_folder = 'x_allegro_templates/';
}
public function initPageHeaderToolbar()
{
if (empty($this->display))
{
$this->page_header_toolbar_btn['allegro_current'] = array(
'href' => $this->context->link->getAdminLink('AdminXAllegroTemplates') . '&addxallegro_template',
'desc' => $this->l('Dodaj nowy szablon'),
'icon' => 'process-icon-new'
);
}
parent::initPageHeaderToolbar();
}
public function initToolbar()
{
if ($this->display == 'add' || $this->display == 'edit') {
$this->toolbar_btn['save_and_stay'] = array(
'href' => self::$currentIndex . '&token=' . $this->token,
'desc' => $this->l('Zapisz i zostań'),
'class' => 'process-icon-save-and-stay '
);
}
parent::initToolbar();
}
public function renderForm()
{
$this->loadObject(true);
$additional_images = array();
for ($i = 0; $i < X13_ALLEGRO_TEMPLATE_IMAGES_NB; $i++)
{
$image = null;
if (Validate::isLoadedObject($this->object) && isset($this->object->additional_images[$i]) && $this->object->additional_images[$i])
{
$ids = explode('_', $this->object->additional_images[$i]);
$link = $this->context->link->getAdminLink('AdminXAllegroTemplates') .
'&deleteAdditionalImage=' . $ids[1] . '&update' . $this->table . '&' . $this->identifier . '=' . $this->object->id;
list($width, $height) = getimagesize(X13_ALLEGRO_IMG_TEMPLATE . $this->object->additional_images[$i]);
$size = filesize(X13_ALLEGRO_IMG_TEMPLATE . $this->object->additional_images[$i]);
$image = '<img src="' . $this->context->shop->getBaseURL(Configuration::get('PS_SSL_ENABLED')) .
X13_ALLEGRO_IMG_TEMPLATE_URL . $this->object->additional_images[$i] . '" class="imgm img-thumbnail" style="max-width: 150px; float: left;">' .
'<span style="display: inline-block; margin-left: 6px;">' . $this->l('wymiary') . ': ' . $width . 'x' . $height . '<br>' .
$this->l('rozmiar') . ': ' . round($size/1024/1024, 2) . ' MB<br>' .
'<a href="' . $link . '" class="btn btn-default button" style="margin-top: 6px;">' . $this->l('Usuń zdjęcie') . '</a></span>';
}
$additional_images[] = array(
'type' => 'file',
'label' => $this->l('Dodatkowe zdjęcie') . ' ' . ($i+1),
'name' => 'additional_image_' . ($i+1),
'display_image' => true,
'image' => $image
);
}
$this->fields_form = array(
'tinymce' => false,
'legend' => array(
'title' => $this->l('Szablon'),
),
'input' =>
array_merge(
array(
array(
'type' => 'hidden',
'name' => $this->identifier
),
array(
'type' => 'text',
'label' => $this->l('Nazwa'),
'name' => 'name',
'size' => 30,
'required' => true
),
array(
'type' => 'new_content',
'label' => $this->l('Struktura szablonu'),
'name' => 'new_content',
'id' => 'new_content',
'rows' => 60,
'cols' => 100
)
),
$additional_images,
array (
array(
'type' => $this->bootstrap ? 'switch' : 'radio',
'label' => $this->l('Domyślny'),
'name' => 'default',
'required' => false,
'class' => 't',
'is_bool' => true,
'values' => array(
array(
'value' => 1,
'label' => $this->l('Tak')
),
array(
'value' => 0,
'label' => $this->l('Nie')
)
)
),
array(
'type' => $this->bootstrap ? 'switch' : 'radio',
'label' => $this->l('Aktywny'),
'name' => 'active',
'required' => false,
'class' => 't',
'is_bool' => true,
'values' => array(
array(
'value' => 1,
'label' => $this->l('Tak')
),
array(
'value' => 0,
'label' => $this->l('Nie')
)
),
'default_value' => 1
)
)
),
'submit' => array(
'title' => $this->l('Zapisz')
),
'buttons' => array(
'save-and-stay' => array(
'title' => $this->l('Zapisz i zostań'),
'name' => 'submitAdd' . $this->table . 'AndStay',
'type' => 'submit',
'class' => 'btn btn-default pull-right',
'icon' => 'process-icon-save'
)
)
);
$variables = array(
'auction_title' => $this->l('Tytuł oferty'),
'auction_description' => $this->l('Opis oferty (z ewentualnymi zmianami podczas wystawiania)'),
'auction_price' => $this->l('Cena "Kup Teraz"'),
'product_name' => $this->l('Nazwa produktu'),
'product_reference' => $this->l('Kod referencyjny (indeks)'),
'product_price' => $this->l('Cena produktu w sklepie'),
'product_price_base' => $this->l('Podstawowa cena produktu w sklepie (bez promocji i rabatów grupowych)'),
'product_ean13' => $this->l('Kod EAN13'),
'product_isbn' => $this->l('Kod ISBN (dostępny od PrestaShop 1.7)'),
'product_weight' => $this->l('Waga produktu'),
'product_attribute_name' => $this->l('Nazwa atrybutu (jeśli posiada)'),
'product_attribute_reference' => $this->l('Kod referencyjny (indeks) atrybutu (jeśli posiada)'),
'product_description' => $this->l('Opis produktu w sklepie'),
'product_description_short' => $this->l('Krótki opis produktu w sklepie'),
'product_description_additional_X' => $this->l('Dodatkowy opis produktu'),
'<span style="color: darkgrey; text-decoration: line-through;">product_description_custom</span>' => 'Używaj {product_description_additional_1}',
'product_features' => $this->l('Lista cech produktu. Aby wykluczyć wyświetlanie wybranych cech, dodaj ich identyfikatory według wzoru {product_features!X/Y/Z} (gdzie X,Y,Z to identyfikatory grup cech)'),
'product_attributes' => $this->l('Lista atrybutów wystawianego produktu'),
'product_attributes_all' => $this->l('Lista wszystkich dostępnych kombinacji produktu'),
'product_customization_fields' => $this->l('Lista pól dostosowywania produktu (wymagane pola zostaną oznaczone gwiazdką "*")'),
'product.POLE' => $this->l('Wartośc pola z tabeli product'),
'product_lang.POLE' => $this->l('Wartość pola z tabeli product_lang'),
'feature_name_X' => $this->l('Nazwa cechy o identyfikatorze X dla produktu'),
'feature_value_X' => $this->l('Wartość cechy o identyfikatorze X dla produktu'),
'attribute_name_X' => $this->l('Nazwa atrybutu o identyfikatorze X dla produktu'),
'attribute_value_X' => $this->l('Wartość atrybutu o identyfikatorze X dla produktu'),
'manufacturer_name' => $this->l('Nazwa producenta'),
'manufacturer_description' => $this->l('Opis producenta'),
'manufacturer_description_short' => $this->l('Krótki opis producenta')
);
$this->loadObject(true);
$this->context->smarty->assign(array(
'template_variables' => $variables,
'template_additional_images' => json_encode($this->object->additional_images ? $this->object->additional_images : array()),
'folder_admin' => basename(_PS_ADMIN_DIR_),
'new_content' => $this->object->content
));
return parent::renderForm();
}
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
$this->addCSS($this->module->getPathUri() . 'views/css/grideditor.css');
if (method_exists('Media', 'addJsDef')) {
Media::addJsDef(
[
'x13allegro_template_images_nb' => X13_ALLEGRO_TEMPLATE_IMAGES_NB
]
);
}
$this->addJqueryUI('ui.sortable');
$this->addJS($this->module->getPathUri() . 'views/js/tinymce/tinymce.min.js');
$this->addJS($this->module->getPathUri() . 'views/js/tinymce/jquery.tinymce.min.js');
$this->addJS($this->module->getPathUri() . 'views/js/jquery.grideditor.js');
}
public function postProcess()
{
if (Tools::isSubmit('deleteAdditionalImage')) {
$this->object = new XAllegroTemplate(Tools::getValue($this->identifier));
foreach (glob(X13_ALLEGRO_IMG_TEMPLATE . $this->object->id . '_' . (int)Tools::getValue('deleteAdditionalImage') . '_*') as $image) {
@unlink($image);
}
unset($this->object->additional_images[(int)Tools::getValue('deleteAdditionalImage')]);
$this->object->save();
}
if (Tools::isSubmit('submitAdd' . $this->table)
|| Tools::isSubmit('submitAdd' . $this->table . 'AndStay')
) {
$_POST['content'] = preg_replace("/<select[^>]*>(.*?)<\/select>/i", '', Tools::getValue('new_content'));
}
else if (Tools::isSubmit('duplicate' . $this->table))
{
$template = new XAllegroTemplate(Tools::getValue($this->identifier));
if (!Validate::isLoadedObject($template)) {
$this->errors[] = $this->l('Niepoprawny objekt');
}
else {
$newTemplate = clone $template;
$newTemplate->id = null;
$newTemplate->name .= ' - Kopia';
$newTemplate->default = false;
if ($newTemplate->add()) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroTemplates') . '&conf=19');
}
else {
$this->errors[] = $this->l('Wystąpił błąd podczas kopiowania szablonu.');
}
}
}
parent::postProcess();
if (!empty($_FILES) && Validate::isLoadedObject($this->object)) {
$this->object = new XAllegroTemplate(Tools::getValue($this->identifier));
$additional_images = array();
$new_images = false;
for ($i = 0; $i < X13_ALLEGRO_TEMPLATE_IMAGES_NB; $i++)
{
$index = 'additional_image_' . ($i+1);
$old_image = (isset($this->object->additional_images[$i]) ? $this->object->additional_images[$i] : null);
if (isset($_FILES[$index]) && $_FILES[$index]['size'] > 0)
{
$errors = array();
if (false !== ($validate = ImageManager::validateUpload($_FILES[$index]))) {
$errors[] = $validate;
}
if ($validate === false)
{
list($width, $height) = getimagesize($_FILES[$index]['tmp_name']);
$extension = strtolower(pathinfo($_FILES[$index]['name'], PATHINFO_EXTENSION));
if ($width < XAllegroApi::PHOTO_MIN_LENGTH && $height < XAllegroApi::PHOTO_MIN_LENGTH) {
$errors[] = sprintf($this->l('Dodatkowe zdjęcie %d musi posiadać dłuższy bok min. %d pikseli.'), ($i+1), XAllegroApi::PHOTO_MIN_LENGTH);
}
if ($width > XAllegroApi::PHOTO_MAX_LENGTH || $height > XAllegroApi::PHOTO_MAX_LENGTH) {
$errors[] = sprintf($this->l('Dodatkowe zdjęcie %d nie może być większe niż %d x %d pikseli.'), ($i+1), XAllegroApi::PHOTO_MAX_LENGTH, XAllegroApi::PHOTO_MAX_LENGTH);
}
if (!in_array($extension, array('jpg', 'png'))) {
$errors[] = sprintf($this->l('Dodatkowe zdjęcie %d nieprawidłowe rozszerzenie, dostępne rozszerzenia to: %s'), ($i+1), ' .jpg, .png');
}
}
if (empty($errors))
{
$name = $this->object->id . '_' . $i . '_' . (int)microtime(true) . '.' . $extension;
if ($old_image && file_exists(X13_ALLEGRO_IMG_TEMPLATE . $old_image)) {
unlink(X13_ALLEGRO_IMG_TEMPLATE . $old_image);
}
if (!is_dir(X13_ALLEGRO_IMG_TEMPLATE)) {
mkdir(X13_ALLEGRO_IMG_TEMPLATE, 0775, true);
}
$new_images = true;
$additional_images[$i] = $name;
@move_uploaded_file($_FILES[$index]['tmp_name'], X13_ALLEGRO_IMG_TEMPLATE . $name);
$this->module->sessionMessages->confirmations($this->l('Dodatkowe zdjęcie') . ' ' . ($i+1) . ': ' . $this->l('zapisano!'));
}
else {
$this->module->sessionMessages->errors(array_merge($this->errors, $errors));
$additional_images[$i] = $old_image;
}
}
else {
$additional_images[$i] = $old_image;
}
}
$this->object->additional_images = $additional_images;
$this->object->save();
if (!empty($errors)) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroTemplates') . '&update' . $this->table . '&' . $this->identifier . '=' . $this->object->id);
}
else if ($new_images) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminXAllegroTemplates') . '&conf=4&update' . $this->table . '&' . $this->identifier . '=' . $this->object->id);
}
}
}
public function displayXDuplicateLink($token = null, $id, $name = null)
{
$tpl = $this->context->smarty->createTemplate($this->module->getLocalPath() . 'views/templates/admin/' . $this->tpl_folder . 'helpers/list/action_xduplicate.tpl');
$tpl->assign(array(
'href' => $this->context->link->getAdminLink('AdminXAllegroTemplates') . '&duplicate' . $this->table . '&' . $this->identifier . '=' . $id,
'action' => $this->l('Skopiuj'),
'id' => $id
));
return $tpl->fetch();
}
}

View File

@@ -0,0 +1,11 @@
<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;