add empik module

This commit is contained in:
2025-05-30 09:08:26 +02:00
parent 87a41f4cfc
commit 56aa2cdc2d
1466 changed files with 138249 additions and 146 deletions

View File

@@ -12,127 +12,135 @@ if (!defined('_PS_VERSION_'))
exit;
}
class AddColumnInList extends Module {
public function __construct() {
$this->name = 'addcolumninlist';
$this->tab = 'administration';
$this->version = '2.0.1';
$this->author = 'Dominik Wójcicki';
$this->need_instance = 0;
$this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Add column in list product');
$this->description = $this->l('Dodatkowe filtorwanie produktów w Back Office');
$this->confirmUninstall = $this->l('Czy na pewno odinstalować moduł?');
class AddColumnInList extends Module
{
public function __construct()
{
$this->name = 'addcolumninlist';
$this->tab = 'administration';
$this->version = '2.0.1';
$this->author = 'Dominik Wójcicki';
$this->need_instance = 0;
$this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Add column in list product');
$this->description = $this->l('Dodatkowe filtorwanie produktów w Back Office');
$this->confirmUninstall = $this->l('Czy na pewno odinstalować moduł?');
}
public function install()
{
if (
!parent::install()
|| !$this->registerHook('displayAdminCatalogTwigProductFilter')
|| !$this->registerHook('actionAdminProductsListingFieldsModifier')
|| !$this->registerHook('ProductsListingFieldsModifier')
|| !$this->registerHook('ManufacturerPagination')
)
{
return false;
}
public function install() {
if (!parent::install()
|| !$this->registerHook('displayAdminCatalogTwigProductFilter')
|| !$this->registerHook('actionAdminProductsListingFieldsModifier')
|| !$this->registerHook('ProductsListingFieldsModifier')
|| !$this->registerHook('ManufacturerPagination')
) {
return false;
}
return true;
}
public function uninstall() {
return parent::uninstall();
}
public function hookManufacturerPagination()
{
}
public function uninstall()
{
return parent::uninstall();
}
public function hookManufacturerPagination()
{
return Tools::getValue('filter_column_manufacturer', '');
}
public function hookDisplayAdminCatalogTwigProductFilter($params)
{
}
$manufacturers = Manufacturer::getManufacturers();
$this->context->smarty->assign([
'filter_column_manufacturer' => Tools::getValue('filter_column_manufacturer', ''),
'filter_column_ean13' => Tools::getValue('filter_column_ean13', ''),
'manufacturers' => $manufacturers,
]);
return $this->display(__FILE__,'views/templates/hook/displayAdminCatalogTwigProductFilter.tpl');
return $this->render('@PrestaShopBundle/Admin/Common/pagination.html.twig', [
'filter_column_manufacturer' => Tools::getValue('filter_column_manufacturer', ''),
'filter_column_ean13' => Tools::getValue('filter_column_ean13', ''),
'manufacturers' => $manufacturers,
]);
public function hookDisplayAdminCatalogTwigProductFilter($params)
{
$manufacturers = Manufacturer::getManufacturers();
$this->context->smarty->assign([
'filter_column_manufacturer' => Tools::getValue('filter_column_manufacturer', ''),
'filter_column_ean13' => Tools::getValue('filter_column_ean13', ''),
'manufacturers' => $manufacturers,
]);
return $this->display(__FILE__, 'views/templates/hook/displayAdminCatalogTwigProductFilter.tpl');
return $this->render('@PrestaShopBundle/Admin/Common/pagination.html.twig', [
'filter_column_manufacturer' => Tools::getValue('filter_column_manufacturer', ''),
'filter_column_ean13' => Tools::getValue('filter_column_ean13', ''),
'manufacturers' => $manufacturers,
]);
}
public function hookActionAdminProductsListingFieldsModifier($params)
{
// EAN13
$params['sql_select']['ean13'] = [
'table' => 'p',
'field' => 'ean13',
'filtering' => \PrestaShop\PrestaShop\Adapter\Admin\AbstractAdminQueryBuilder::FILTERING_LIKE_BOTH
];
$ean13_filter = Tools::getValue('filter_column_ean13', false);
if ($ean13_filter && $ean13_filter != '')
{
$params['sql_where'][] .= "p.ean13 = " . $ean13_filter;
}
public function hookActionAdminProductsListingFieldsModifier($params)
// Cena zakupu
$params['sql_select']['wholesale_price'] = [
'table' => 'p',
'field' => 'wholesale_price',
'filtering' => \PrestaShop\PrestaShop\Adapter\Admin\AbstractAdminQueryBuilder::FILTERING_LIKE_BOTH
];
$wholesale_price_filter = Tools::getValue('filter_column_name_wholesale_price', false);
if ($wholesale_price_filter && $wholesale_price_filter != '')
{
// EAN13
$params['sql_select']['ean13'] = [
'table' => 'p',
'field' => 'ean13',
'filtering' => \PrestaShop\PrestaShop\Adapter\Admin\AbstractAdminQueryBuilder::FILTERING_LIKE_BOTH
];
$ean13_filter = Tools::getValue('filter_column_ean13', false);
if ($ean13_filter && $ean13_filter != '') {
$params['sql_where'][] .= "p.ean13 = ".$ean13_filter;
}
// Cena zakupu
$params['sql_select']['wholesale_price'] = [
'table' => 'p',
'field' => 'wholesale_price',
'filtering' => \PrestaShop\PrestaShop\Adapter\Admin\AbstractAdminQueryBuilder::FILTERING_LIKE_BOTH
];
$wholesale_price_filter = Tools::getValue('filter_column_name_wholesale_price',false);
if ($wholesale_price_filter && $wholesale_price_filter != '') {
$params['sql_where'][] .= " p.wholesale_price = ".$wholesale_price_filter;
}
// Marża
$params['sql_select']['trade_margin'] = [
'table' => 'p',
'field' => 'trade_margin',
'filtering' => \PrestaShop\PrestaShop\Adapter\Admin\AbstractAdminQueryBuilder::FILTERING_LIKE_BOTH
];
$trade_margin_filter = Tools::getValue('filter_column_trade_margin', false);
if ($trade_margin_filter && $trade_margin_filter != '') {
$params['sql_where'][] .= "p.trade_margin = ".$trade_margin_filter;
}
// Manufacturer
$params['sql_select']['manufacturer'] = [
"table" => "m",
"field" => "name",
"filtering" => \PrestaShop\PrestaShop\Adapter\Admin\AbstractAdminQueryBuilder::FILTERING_LIKE_BOTH
];
$params['sql_table']['m'] = [
"table" => "manufacturer",
"join" => "LEFT JOIN",
'on' => "p.`id_manufacturer` = m.`id_manufacturer`"
];
$manufacturer_filter = Tools::getValue('filter_column_manufacturer', false);
if ($manufacturer_filter && $manufacturer_filter != '') {
$params['sql_where'][] .= " p.id_manufacturer = ".$manufacturer_filter;
}
$params['sql_where'][] .= " p.wholesale_price = " . $wholesale_price_filter;
}
}
// Marża
$params['sql_select']['trade_margin'] = [
'table' => 'p',
'field' => 'trade_margin',
'filtering' => \PrestaShop\PrestaShop\Adapter\Admin\AbstractAdminQueryBuilder::FILTERING_LIKE_BOTH
];
$trade_margin_filter = Tools::getValue('filter_column_trade_margin', false);
if ($trade_margin_filter && $trade_margin_filter != '')
{
$params['sql_where'][] .= "p.trade_margin = " . $trade_margin_filter;
}
// Manufacturer
$params['sql_select']['manufacturer'] = [
"table" => "m",
"field" => "name",
"filtering" => \PrestaShop\PrestaShop\Adapter\Admin\AbstractAdminQueryBuilder::FILTERING_LIKE_BOTH
];
$params['sql_table']['m'] = [
"table" => "manufacturer",
"join" => "LEFT JOIN",
'on' => "p.`id_manufacturer` = m.`id_manufacturer`"
];
$manufacturer_filter = Tools::getValue('filter_column_manufacturer', false);
if ($manufacturer_filter && $manufacturer_filter != '')
{
$params['sql_where'][] .= " p.id_manufacturer = " . $manufacturer_filter;
}
}
}

1
modules/empikmarketplace/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
data/*.csv

View File

@@ -0,0 +1,34 @@
<?php
// include_once __DIR__.'/../../config/config.inc.php';
use Mirakl\MMP\Shop\Client\ShopApiClient;
use Mirakl\MMP\Shop\Request\Offer\GetOfferRequest;
include_once __DIR__ . '/vendor/autoload.php';
$client = new \Empik\Marketplace\API\EmpikClient(111, 222);
$url = 'https://stg1.marketplace.empik.com/';
$apiKey = 'Waynet123!Waynet';
try {
// Instantiating the Mirakl API Client
$api = new ShopApiClient($url, $apiKey);
// Building request
$request = new GetOfferRequest('OFFER_ID');
// Calling the API
$result = $api->getOffer($request);
var_dump($result); // \Mirakl\MMP\Shop\Domain\Offer\ShopOffer
// You can also retrieve raw response by using run() method of API client:
// $result = $api->run($request); // or $api->raw()->getOffer($request)
// var_dump($result); // returns \Psr\Http\Message\ResponseInterface
} catch (\Exception $e) {
// An exception is thrown if object requested is not found or if an error occurs
var_dump($e->getMessage());
}

View File

@@ -0,0 +1,60 @@
<?php
class EmpikAction extends ObjectModel
{
const ACTION_OTHER = 'OTHER';
const ACTION_PRODUCT_EXPORT = 'PRODUCT_EXPORT';
const ACTION_OFFER_EXPORT = 'OFFER_EXPORT';
const ACTION_PRODUCT_EXPORT_INCLUDE = 'PRODUCT_EXPORT_INCLUDE';
const ACTION_PRODUCT_EXPORT_EXCLUDE = 'PRODUCT_EXPORT_EXCLUDE';
const STATUS_NEW = 'NEW';
const STATUS_COMPLETED = 'COMPLETE';
public $id_shop;
public $action = self::ACTION_OTHER;
public $status = self::STATUS_NEW;
public $id_import;
public $import_count;
public $date_start;
public $date_end;
public static $definition = [
'table' => 'empik_action',
'primary' => 'id_empik_action',
'fields' => [
'id_shop' => [
'type' => self::TYPE_INT,
'validate' => 'isUnsignedInt',
'required' => true,
],
'action' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'status' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'id_import' => [
'type' => self::TYPE_INT,
'validate' => 'isCleanHtml',
],
'import_count' => [
'type' => self::TYPE_INT,
'validate' => 'isCleanHtml',
],
'date_start' => [
'type' => self::TYPE_DATE,
'validate' => 'isDate',
'required' => true,
],
'date_end' => [
'type' => self::TYPE_DATE,
'validate' => 'isDate',
'required' => true,
],
],
];
}

View File

@@ -0,0 +1,30 @@
<?php
class EmpikActionLog extends ObjectModel
{
public $id_empik_action;
public $message;
public $date_add;
public static $definition = [
'table' => 'empik_action',
'primary' => 'id_empik_action_log',
'fields' => [
'id_empik_action' => [
'type' => self::TYPE_INT,
'validate' => 'isUnsignedInt',
'required' => true,
],
'message' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'date_add' => [
'type' => self::TYPE_DATE,
'validate' => 'isDate',
'required' => true,
],
],
];
}

View File

@@ -0,0 +1,87 @@
<?php
class EmpikOrder extends ObjectModel
{
public $id_order;
public $empik_order_reference;
public $empik_order_carrier;
public $empik_payment;
public $empik_carrier;
public $empik_pickup_point;
public $empik_vat_number;
public $date_add;
public static $definition = [
'table' => 'empik_orders',
'primary' => 'id_empik_order',
'fields' => [
'id_order' => [
'type' => self::TYPE_INT,
'validate' => 'isUnsignedInt',
'required' => true,
],
'empik_order_reference' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'empik_order_carrier' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'empik_payment' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
'required' => true,
],
'empik_carrier' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
'required' => true,
],
'empik_pickup_point' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'empik_vat_number' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'date_add' => [
'type' => self::TYPE_DATE,
'validate' => 'isDate',
'required' => false,
],
],
];
public static function getEmpikOrderByOrderId($orderId)
{
$query = (new DbQuery())
->select('eo.*')
->from('empik_orders', 'eo')
->where('eo.id_order = "'.pSQL($orderId).'"');
return Db::getInstance()->getRow($query);
}
public static function getEmpikOrderReferenceByOrderId($orderId)
{
$query = (new DbQuery())
->select('eo.empik_order_reference')
->from('empik_orders', 'eo')
->where('eo.id_order = "'.pSQL($orderId).'"');
return Db::getInstance()->getValue($query);
}
public static function getOrderIdByEmpikOrderReference($empikOrderReference)
{
$query = (new DbQuery())
->select('eo.id_order')
->from('empik_orders', 'eo')
->where('eo.empik_order_reference = "'.pSQL($empikOrderReference).'"');
return Db::getInstance()->getValue($query);
}
}

View File

@@ -0,0 +1,64 @@
<?php
class EmpikProduct extends ObjectModel
{
public $id_product;
public $id_product_attribute;
public $product_export;
public $offer_export;
public $offer_price;
public $offer_price_reduced;
public $logistic_class;
public $condition;
public $export_original_price;
public static $definition = [
'table' => 'empik_product',
'primary' => 'id_empik_product',
'fields' => [
'id_product' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true],
'id_product_attribute' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true],
'product_export' => ['type' => self::TYPE_INT, 'validate' => 'isBool', 'required' => false],
'offer_export' => ['type' => self::TYPE_INT, 'validate' => 'isBool', 'required' => false],
'offer_price' => ['type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => false],
'offer_price_reduced' => ['type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => false],
'logistic_class' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => false],
'condition' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => false],
'export_original_price' => ['type' => self::TYPE_INT, 'validate' => 'isBool', 'required' => false],
],
];
public static function getById($productId, $productAttributeId = 0)
{
$sql = new DbQuery();
$sql->select('*');
$sql->from('empik_product');
$sql->where('id_product = '.(int)$productId);
$sql->where('id_product_attribute = '.(int)$productAttributeId);
$row = Db::getInstance()->getRow($sql);
if ($row) {
$empikProduct = new EmpikProduct();
$empikProduct->hydrate($row);
return $empikProduct;
}
return null;
}
public static function getOrCreate($productId, $productAttributeId = 0)
{
$empikProduct = self::getById($productId, $productAttributeId);
if (!$empikProduct) {
$empikProduct = new EmpikProduct();
$empikProduct->condition = 11;
$empikProduct->id_product = $productId;
$empikProduct->id_product_attribute = $productAttributeId;
$empikProduct->add();
}
return $empikProduct;
}
}

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;

View File

@@ -0,0 +1,29 @@
{
"name": "waynet/empik",
"description": "",
"type": "prestashop-module",
"authors": [
{
"name": "waynet",
"email": "info@waynet.pl"
}
],
"require": {
"php": ">=5.6.0",
"composer/installers": "~1.0",
"prestashop/module-lib-service-container": "^1.4"
},
"autoload": {
"psr-4": {
"Empik\\Marketplace\\": "src/"
},
"exclude-from-classmap": [],
"classmap": [
"classes/"
]
},
"config": {
"preferred-install": "dist",
"prepend-autoloader": false
}
}

1376
modules/empikmarketplace/composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

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;

View File

@@ -0,0 +1,13 @@
imports:
- { resource: ../common.yml }
services:
empik.marketplace.install.installer:
class: Empik\Marketplace\Install\Installer
public: true
arguments:
- "@empik.marketplace.prestaShopContext"
empik.marketplace.install.uninstaller:
class: Empik\Marketplace\Install\Uninstaller
public: true

View File

@@ -0,0 +1,339 @@
services:
empik.marketplace.module:
class: EmpikMarketplace
factory: ["Module", "getInstanceByName"]
public: false
arguments:
- "empikmarketplace"
EmpikMarketplace: "@empik.marketplace.module"
empik.marketplace.adapter.tools:
class: Empik\Marketplace\Adapter\ToolsAdapter
public: false
Empik\Marketplace\Adapter\ToolsAdapter: "@empik.marketplace.adapter.tools"
empik.marketplace.adapter.loggerAdapter:
class: Empik\Marketplace\Adapter\LoggerAdapter
public: true
Empik\Marketplace\Adapter\LoggerAdapter: "@empik.marketplace.adapter.loggerAdapter"
empik.marketplace.prestaShopContext:
class: Empik\Marketplace\PrestaShopContext
public: true
Empik\Marketplace\PrestaShopContext: "@empik.marketplace.prestaShopContext"
empik.marketplace.adapter.link:
class: Empik\Marketplace\Adapter\LinkAdapter
public: true
arguments:
- "@empik.marketplace.prestaShopContext"
Empik\Marketplace\Adapter\LinkAdapter: "@empik.marketplace.adapter.link"
empik.marketplace.adapter.configurationAdapter:
class: Empik\Marketplace\Adapter\ConfigurationAdapter
public: false
Empik\Marketplace\Adapter\ConfigurationAdapter: "@empik.marketplace.adapter.configurationAdapter"
empik.marketplace.hook.hookAction:
class: Empik\Marketplace\Hook\HookAction
public: true
arguments:
- "@empik.marketplace.manager.carrierMapManager"
Empik\Marketplace\hook\HookAction: "@empik.marketplace.hook.hookAction"
empik.marketplace.manager.carrierMapManager:
class: Empik\Marketplace\Manager\CarrierMapManager
public: true
arguments:
- "@empik.marketplace.adapter.configurationAdapter"
Empik\Marketplace\Manager\CarrierMapManager: "@empik.marketplace.manager.carrierMapManager"
empik.marketplace.configuration.exportConfiguration:
class: Empik\Marketplace\Configuration\ExportConfiguration
public: true
arguments:
- "@empik.marketplace.adapter.configurationAdapter"
Empik\Marketplace\Configuration\ExportConfiguration: "@empik.marketplace.configuration.exportConfiguration"
empik.marketplace.manager.processManager:
class: Empik\Marketplace\Manager\ProcessManager
public: false
Empik\Marketplace\Manager\ProcessManager: "@empik.marketplace.manager.processManager"
empik.marketplace.factory.empikClientFactory:
class: Empik\Marketplace\Factory\EmpikClientFactory
public: true
arguments:
- "@empik.marketplace.adapter.configurationAdapter"
Empik\Marketplace\Factory\EmpikClientFactory: "@empik.marketplace.factory.empikClientFactory"
empik.marketplace.handler.exportProductHandler:
class: Empik\Marketplace\Handler\ExportProductHandler
public: true
arguments:
- "@empik.marketplace.module"
- "@empik.marketplace.configuration.exportConfiguration"
- "@empik.marketplace.repository.productRepository"
- "@empik.marketplace.repository.featureRepository"
- "@empik.marketplace.repository.attributeRepository"
- "@empik.marketplace.repository.taxRepository"
- "@empik.marketplace.repository.categoryRepository"
- "@empik.marketplace.repository.imageRepository"
- "@empik.marketplace.formatter.productNameFormatter"
- "@empik.marketplace.utils.categoryPathBuilder"
- "@empik.marketplace.utils.identifierExtractor"
Empik\Marketplace\Handler\ExportProductHandler: "@empik.marketplace.handler.exportProductHandler"
empik.marketplace.handler.exportOfferHandler:
class: Empik\Marketplace\Handler\ExportOfferHandler
public: true
arguments:
- "@empik.marketplace.module"
- "@empik.marketplace.configuration.exportConfiguration"
- "@empik.marketplace.repository.productRepository"
- "@empik.marketplace.repository.featureRepository"
- "@empik.marketplace.repository.taxRepository"
- "@empik.marketplace.repository.categoryRepository"
- "@empik.marketplace.repository.imageRepository"
- "@empik.marketplace.formatter.productNameFormatter"
- "@empik.marketplace.utils.categoryPathBuilder"
- "@empik.marketplace.utils.identifierExtractor"
- "@empik.marketplace.utils.skuExtractor"
- "@empik.marketplace.utils.offerPriceCalculator"
- "@empik.marketplace.utils.offerQuantityCalculator"
Empik\Marketplace\Handler\ExportOfferHandler: "@empik.marketplace.handler.exportOfferHandler"
empik.marketplace.processor.exportProductProcessor:
class: Empik\Marketplace\Processor\ExportProductProcessor
public: true
arguments:
- "@empik.marketplace.manager.processManager"
- "@empik.marketplace.factory.empikClientFactory"
- "@empik.marketplace.handler.exportProductHandler"
- "@empik.marketplace.configuration.exportConfiguration"
Empik\Marketplace\Processor\ExportProductProcessor: "@empik.marketplace.processor.exportProductProcessor"
empik.marketplace.processor.exportOfferProcessor:
class: Empik\Marketplace\Processor\ExportOfferProcessor
public: true
arguments:
- "@empik.marketplace.manager.processManager"
- "@empik.marketplace.factory.empikClientFactory"
- "@empik.marketplace.handler.exportOfferHandler"
- "@empik.marketplace.configuration.exportConfiguration"
Empik\Marketplace\Processor\ExportOfferProcessor: "@empik.marketplace.processor.exportOfferProcessor"
empik.marketplace.processor.orderProcessor:
class: Empik\Marketplace\Processor\OrderProcessor
public: true
arguments:
- "@empik.marketplace.manager.processManager"
- "@empik.marketplace.factory.empikClientFactory"
- "@empik.marketplace.orderFulfiller.orderFulfiller"
- "@empik.marketplace.adapter.loggerAdapter"
Empik\Marketplace\Processor\orderProcessor: "@empik.marketplace.processor.orderProcessor"
empik.marketplace.handler.cronJobs:
class: Empik\Marketplace\Handler\CronJobsHandler
public: true
arguments:
- "@empik.marketplace.module"
- "@empik.marketplace.adapter.tools"
- "@empik.marketplace.processor.exportProductProcessor"
- "@empik.marketplace.processor.exportOfferProcessor"
- "@empik.marketplace.processor.orderProcessor"
Empik\Marketplace\Handler\CronJobsHandler: "@empik.marketplace.handler.cronJobs"
empik.marketplace.repository.productRepository:
class: Empik\Marketplace\Repository\ProductRepository
public: true
arguments:
- "@empik.marketplace.prestaShopContext"
Empik\Marketplace\Repository\ProductRepository: "@empik.marketplace.repository.productRepository"
empik.marketplace.repository.featureRepository:
class: Empik\Marketplace\Repository\FeatureRepository
public: true
Empik\Marketplace\Repository\FeatureRepository: "@empik.marketplace.repository.featureRepository"
empik.marketplace.repository.attributeRepository:
class: Empik\Marketplace\Repository\AttributeRepository
public: true
Empik\Marketplace\Repository\AttributeRepository: "@empik.marketplace.repository.attributeRepository"
empik.marketplace.repository.taxRepository:
class: Empik\Marketplace\Repository\TaxRepository
public: true
Empik\Marketplace\Repository\TaxRepository: "@empik.marketplace.repository.taxRepository"
empik.marketplace.repository.categoryRepository:
class: Empik\Marketplace\Repository\CategoryRepository
public: true
Empik\Marketplace\Repository\CategoryRepository: "@empik.marketplace.repository.categoryRepository"
empik.marketplace.repository.imageRepository:
class: Empik\Marketplace\Repository\ImageRepository
public: true
Empik\Marketplace\Repository\ImageRepository: "@empik.marketplace.repository.imageRepository"
empik.marketplace.repository.addressRepository:
class: Empik\Marketplace\Repository\AddressRepository
public: true
Empik\Marketplace\Repository\AddressRepository: "@empik.marketplace.repository.addressRepository"
empik.marketplace.provider.order.addressProvider:
class: Empik\Marketplace\Provider\Order\AddressProvider
public: true
arguments:
- "@empik.marketplace.repository.addressRepository"
Empik\Marketplace\Provider\Order\AddressProvider: "@empik.marketplace.provider.order.addressProvider"
empik.marketplace.provider.order.customerProvider:
class: Empik\Marketplace\Provider\Order\CustomerProvider
public: true
Empik\Marketplace\Provider\Order\CustomerProvider: "@empik.marketplace.provider.order.customerProvider"
empik.marketplace.provider.order.orderLinesProvider:
class: Empik\Marketplace\Provider\Order\OrderLinesProvider
public: true
arguments:
- "@empik.marketplace.prestaShopContext"
- "@empik.marketplace.repository.productRepository"
- "@empik.marketplace.utils.identifierExtractor"
Empik\Marketplace\Provider\Order\OrderLinesProvider: "@empik.marketplace.provider.order.orderLinesProvider"
empik.marketplace.dataProvider.productDataProvider:
class: Empik\Marketplace\DataProvider\ProductDataProvider
public: true
Empik\Marketplace\DataProvider\productDataProvider: "@empik.marketplace.dataProvider.ProductDataProvider"
empik.marketplace.dataProvider.combinationDataProvider:
class: Empik\Marketplace\DataProvider\CombinationDataProvider
public: true
Empik\Marketplace\DataProvider\combinationDataProvider: "@empik.marketplace.dataProvider.CombinationDataProvider"
empik.marketplace.provider.order.carrierProvider:
class: Empik\Marketplace\Provider\Order\CarrierProvider
public: true
arguments:
- "@empik.marketplace.manager.carrierMapManager"
Empik\Marketplace\Provider\Order\CarrierProvider: "@empik.marketplace.provider.order.carrierProvider"
empik.marketplace.provider.order.historyProvider:
class: Empik\Marketplace\Provider\Order\HistoryProvider
public: true
Empik\Marketplace\Provider\Order\HistoryProvider: "@empik.marketplace.provider.order.historyProvider"
empik.marketplace.provider.order.cartProvider:
class: Empik\Marketplace\Provider\Order\CartProvider
public: true
arguments:
- "@empik.marketplace.repository.productRepository"
- "@empik.marketplace.utils.identifierExtractor"
Empik\Marketplace\Provider\Order\CartProvider: "@empik.marketplace.provider.order.cartProvider"
empik.marketplace.orderFulfiller.orderFulfiller:
class: Empik\Marketplace\OrderFulfiller\OrderFulfiller
public: true
arguments:
- "@empik.marketplace.provider.order.addressProvider"
- "@empik.marketplace.provider.order.customerProvider"
- "@empik.marketplace.provider.order.orderLinesProvider"
- "@empik.marketplace.provider.order.carrierProvider"
- "@empik.marketplace.provider.order.historyProvider"
- "@empik.marketplace.provider.order.cartProvider"
Empik\Marketplace\OrderFulfiller\OrderFulfiller: "@empik.marketplace.orderFulfiller.orderFulfiller"
empik.marketplace.formatter.productNameFormatter:
class: Empik\Marketplace\Formatter\ProductNameFormatter
public: true
Empik\Marketplace\Formatter\ProductNameFormatter: "@empik.marketplace.formatter.productNameFormatter"
empik.marketplace.utils.categoryPathBuilder:
class: Empik\Marketplace\Utils\CategoryPathBuilder
public: true
Empik\Marketplace\Utils\CategoryPathBuilder: "@empik.marketplace.utils.categoryPathBuilder"
empik.marketplace.dataProvider.offersDataProvider:
class: Empik\Marketplace\DataProvider\OffersDataProvider
public: true
arguments:
- "@empik.marketplace.repository.productRepository"
- "@empik.marketplace.utils.identifierExtractor"
Empik\Marketplace\DataProvider\OffersDataProvider: "@empik.marketplace.dataProvider.offersDataProvider"
empik.marketplace.utils.identifierExtractor:
class: Empik\Marketplace\Utils\IdentifierExtractor
public: true
Empik\Marketplace\Utils\IdentifierExtractor: "@empik.marketplace.utils.skuExtractor"
empik.marketplace.utils.skuExtractor:
class: Empik\Marketplace\Utils\SkuExtractor
public: true
Empik\Marketplace\Utils\SkuExtractor: "@empik.marketplace.utils.skuExtractor"
empik.marketplace.utils.offerPriceCalculator:
class: Empik\Marketplace\Utils\OfferPriceCalculator
public: true
Empik\Marketplace\Utils\offerPriceCalculator: "@empik.marketplace.utils.OfferPriceCalculator"
empik.marketplace.utils.offerQuantityCalculator:
class: Empik\Marketplace\Utils\OfferQuantityCalculator
public: true
Empik\Marketplace\Utils\offerQuantityCalculator: "@empik.marketplace.utils.OfferQuantityCalculator"
empik.marketplace.handler.updateDeleteOfferHandler:
class: Empik\Marketplace\Handler\UpdateDeleteOfferHandler
public: true
arguments:
- "@empik.marketplace.factory.empikClientFactory"
- "@empik.marketplace.repository.productRepository"
- "@empik.marketplace.dataProvider.offersDataProvider"
Empik\Marketplace\Handler\UpdateDeleteOfferHandler: "@empik.marketplace.handler.updateDeleteOfferHandler"
empik.marketplace.cache.cache:
class: Empik\Marketplace\Cache\Cache
public: true
Empik\Marketplace\Cache\cache: "@empik.marketplace.cache.Cache"

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;

View File

@@ -0,0 +1,2 @@
imports:
- { resource: ../common.yml }

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;

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" ?>
<module>
<name>empikmarketplace</name>
<displayName><![CDATA[EmpikPlace]]></displayName>
<version><![CDATA[2.0.0]]></version>
<description><![CDATA[Integracja z Empik Marketplace]]></description>
<author><![CDATA[Waynet]]></author>
<tab><![CDATA[market_place]]></tab>
<confirmUninstall><![CDATA[Are you sure you want to uninstall this module?]]></confirmUninstall>
<is_configurable>0</is_configurable>
<need_instance>0</need_instance>
<limited_countries></limited_countries>
</module>

View File

@@ -0,0 +1,219 @@
<?php
use Empik\Marketplace\Factory\EmpikClientFactory;
use Empik\Marketplace\API\EmpikClient;
class AdminEmpikActionLogController extends ModuleAdminController
{
/** @var EmpikClientFactory */
private $empikClientFactory;
/** @var EmpikClient */
private $empikClient;
/** @var int */
protected $logLimit = 20;
public function __construct()
{
$this->bootstrap = true;
$this->table = 'empik_action';
$this->className = 'EmpikAction';
$this->lang = false;
parent::__construct();
$this->empikClientFactory = $this->module->getService('empik.marketplace.factory.empikClientFactory');
$this->empikClient = $this->empikClientFactory->createClient();
$this->_select .= 'id_import AS id_import_log';
$this->_defaultOrderWay = 'DESC';
$this->fields_list = [
'id_empik_action' => [
'title' => $this->l('ID'),
'align' => 'center',
'class' => 'fixed-width-xs'
],
'action' => [
'title' => $this->l('Action'),
],
'date_start' => [
'title' => $this->l('Date start'),
'type' => 'datetime',
],
'date_end' => [
'title' => $this->l('Date end'),
'type' => 'datetime',
],
'status' => [
'title' => $this->l('Status'),
],
'id_import' => [
'title' => $this->l('Import ID'),
],
'import_count' => [
'title' => $this->l('Nb. products'),
],
'id_import_log' => [
'title' => $this->l('Report'),
'class' => 'fixed-width-md',
'align' => 'center',
'callback' => 'displayDownloadReportButton',
'search' => false,
'orderby' => false,
],
];
}
public function initToolbar()
{
$this->toolbar_btn = [];
}
public function initContent()
{
$this->cleanupActionLog();
parent::initContent();
$this->updateActionLog();
}
public function init()
{
if (Tools::getValue('action') === 'downloadLog') {
$this->getExportErrorLog();
}
parent::init();
}
public function displayDownloadReportButton($val, $row)
{
if (!$val || $row['status'] !== 'COMPLETE') {
return '';
}
$this->context->smarty->assign(
[
'href' => self::$currentIndex.'&token='.$this->token. '&'.$this->identifier.'='.$row['id_empik_action'].'&action=downloadLog',
]
);
return $this->module->display($this->module->name, 'views/templates/admin/list_action_download.tpl');
}
public function getExportErrorLog()
{
/** @var EmpikAction $obj */
$empikAction = $this->loadObject();
$importId = $empikAction->id_import;
if (!$importId) {
$this->errors[] = $this->l('No import ID for selected action');
return;
}
try {
switch ($empikAction->action) {
case EmpikAction::ACTION_PRODUCT_EXPORT:
$response = $this->empikClient->getProductImportErrorReport($importId);
break;
case EmpikAction::ACTION_OFFER_EXPORT:
$response = $this->empikClient->getOfferImportErrorReport($importId);
break;
default:
return;
}
$this->contentOutput($response, sprintf('report_%s.csv', $importId));
} catch (Exception $e) {
$this->errors[] = sprintf($this->l('No error report found for import: %s'), $importId);
}
}
protected function cleanupActionLog()
{
$id = Db::getInstance()->getValue('SELECT MAX(id_empik_action) - '.(int)$this->logLimit.' FROM `'._DB_PREFIX_.'empik_action`');
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'empik_action` WHERE id_empik_action <= ' . (int)$id);
}
protected function updateActionLog()
{
$this->getList(Context::getContext()->language->id);
$endStatuses = ['COMPLETE', 'FAILED', 'API_ERROR'];
foreach ($this->_list as $row) {
$empikAction = new EmpikAction($row['id_empik_action']);
if (!$empikAction->id_import || in_array($empikAction->status, $endStatuses)) {
continue;
}
try {
switch ($empikAction->action) {
case EmpikAction::ACTION_PRODUCT_EXPORT:
$response = $this->empikClient->getProductsImport($empikAction->id_import);
$this->updateActionProductImport($response, $empikAction);
break;
case EmpikAction::ACTION_OFFER_EXPORT:
$response = $this->empikClient->getOffersImport($empikAction->id_import);
$this->updateActionOfferImport($response, $empikAction);
break;
}
} catch (Exception $e) {
$this->errors[] = $e->getMessage();
}
}
}
/**
* @param array $response
* @param EmpikAction $action
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
protected function updateActionProductImport($response, $action)
{
$action->status = $response['import_status'];
$action->import_count = $response['transform_lines_read'];
$action->update();
}
/**
* @param array $response
* @param EmpikAction $action
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
protected function updateActionOfferImport($response, $action)
{
$action->status = $response['status'];
$action->import_count = $response['lines_read'];
$action->update();
}
/**
* @param string $content
* @param string $filename
*/
protected function contentOutput($content, $filename = 'error_report.csv')
{
ob_clean();
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Length: ' . strlen($content));
echo $content;
exit;
}
protected function l($string, $class = null, $addslashes = false, $htmlentities = true)
{
return Translate::getModuleTranslation($this->module, $string, get_class($this), null, $addslashes);
}
}

View File

@@ -0,0 +1,201 @@
<?php
use Empik\Marketplace\Adapter\ConfigurationAdapter;
use Empik\Marketplace\Adapter\LinkAdapter;
use Empik\Marketplace\Factory\EmpikClientFactory;
use Empik\Marketplace\Validator\Validator;
class AdminEmpikConnectionController extends ModuleAdminController
{
const CONN_SUCCESS = 1;
const CONN_ERROR_API = 2;
public $_conf = [];
public $_error = [];
/** @var EmpikMarketplace */
public $module;
/** @var EmpikClientFactory */
protected $empikClientFactory;
/** @var LinkAdapter */
protected $link;
public function __construct()
{
parent::__construct();
$this->bootstrap = true;
$this->_conf[self::CONN_SUCCESS] = $this->l('Connection to API works fine.');
$this->_error[self::CONN_ERROR_API] = $this->l('Unable to connect, check connection details and try again.');
$this->empikClientFactory = $this->module->getService('empik.marketplace.factory.empikClientFactory');
$this->link = $this->module->getService('empik.marketplace.adapter.link');
}
public function initProcess()
{
$this->display = 'edit';
parent::initProcess();
}
public function postProcess()
{
if (Tools::getIsset('submit'.$this->controller_name)) {
$this->handleForm();
}
parent::postProcess();
}
public function handleForm()
{
$environment = Tools::getValue('environment');
$apiKey = Tools::getValue('api_key');
if (!Validator::isValidEnvironment($environment)) {
$this->errors[] = $this->l('Invalid environment field');
}
if (!Validator::isValidApiKey($apiKey)) {
$this->errors[] = $this->l('Invalid API key field');
}
if (empty($this->errors)) {
$result = true;
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_ENVIRONMENT, $environment);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_API_KEY, $apiKey);
if ($result) {
Tools::redirectAdmin(
$this->link->getAdminLink($this->controller_name, ['conf' => 4])
);
}
}
$this->errors[] = $this->l('Error saving form.');
}
public function processTestConnection()
{
$status = $this->getConnectionStatus();
if ($status === self::CONN_SUCCESS) {
$this->module->setAuthStatus();
Tools::redirectAdmin(
$this->link->getAdminLink($this->controller_name, ['conf' => self::CONN_SUCCESS])
);
}
$this->errors[] = $this->_error[self::CONN_ERROR_API];
}
/**
* @return int
*/
public function getConnectionStatus()
{
try {
$client = $this->empikClientFactory->createClient();
$client->getAccount();
} catch (Exception $e) {
return self::CONN_ERROR_API;
}
return self::CONN_SUCCESS;
}
public function renderForm()
{
$controller = $this->controller_name;
$this->context->smarty->assign([
'url_test_connection' => $this->link->getAdminLink($controller, ['action' => 'testConnection'])
]);
$fields = [
'form' => [
'legend' => [
'title' => $this->l('Configuration'),
'icon' => 'icon-cogs',
],
'input' => [
[
'type' => 'select',
'name' => 'environment',
'label' => $this->l('Environment'),
'hint' => $this->l('Select environment'),
'options' => [
'query' => [
[
'url' => ConfigurationAdapter::ENV_TEST,
'name' => $this->l('testing'),
],
[
'url' => ConfigurationAdapter::ENV_PROD,
'name' => $this->l('production'),
],
],
'id' => 'url',
'name' => 'name',
],
'class' => 'fixed-width-xxl',
],
[
'type' => 'text',
'label' => $this->l('API key'),
'hint' => $this->l('API key'),
'name' => 'api_key',
],
[
'label' => '',
'type' => 'html',
'name' => 'html_data',
'html_content' => $this->context->smarty->fetch(
$this->module->getLocalPath().'/views/templates/admin/_partials/test_connection_button.tpl'
),
],
[
'label' => '',
'type' => 'html',
'name' => 'custom_html',
'html_content' => $this->context->smarty->fetch(
$this->module->getLocalPath().'/views/templates/admin/_partials/test_connection_footer.tpl'
),
],
],
],
];
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->default_form_language = (int)Configuration::get('PS_LANG_DEFAULT');
$helper->module = $this->module;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->identifier = $this->identifier;
$helper->submit_action = 'submit'.$controller;
$helper->currentIndex = $this->link->getAdminLink($controller);
$helper->token = Tools::getAdminTokenLite($controller);
$helper->tpl_vars = [
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
'fields_value' => [
'environment' => Tools::getValue('environment', Configuration::get(ConfigurationAdapter::CONF_ENVIRONMENT)),
'api_key' => Tools::getValue('api_key', Configuration::get(ConfigurationAdapter::CONF_API_KEY))
]
];
return $helper->generateForm([$fields]);
}
protected function l($string, $class = null, $addslashes = false, $htmlentities = true)
{
return Translate::getModuleTranslation($this->module, $string, get_class($this), null, $addslashes);
}
}

View File

@@ -0,0 +1,6 @@
<?php
class AdminEmpikController extends ModuleAdminController
{
}

View File

@@ -0,0 +1,46 @@
<?php
use Empik\Marketplace\Handler\CronJobsHandler;
use Empik\Marketplace\PrestaShopContext;
class AdminEmpikHelpController extends ModuleAdminController
{
/** @var CronJobsHandler */
protected $cronJobsHandler;
/** @var EmpikMarketplace */
public $module;
/** @var PrestaShopContext */
public $prestaShopContext;
public function __construct()
{
parent::__construct();
$this->bootstrap = true;
$this->cronJobsHandler = $this->module->getService('empik.marketplace.handler.cronJobs');
$this->prestaShopContext = $this->module->getService('empik.marketplace.prestaShopContext');
}
public function initContent()
{
$this->context->smarty->assign([
'cron_jobs' => $this->cronJobsHandler->getAvailableActionsUrls(),
'url_help' => 'https://www.empik.com/empikplace/pomoc',
'url_docs' => 'https://www.empik.com/empikplace/integracje/prestashop/instrukcja',
]);
$this->content = $this->context->smarty->fetch(
$this->module->getLocalPath() . '/views/templates/admin/help.tpl'
);
parent::initContent();
}
protected function l($string, $class = null, $addslashes = false, $htmlentities = true)
{
return Translate::getModuleTranslation($this->module, $string, get_class($this), null, $addslashes);
}
}

View File

@@ -0,0 +1,341 @@
<?php
use Empik\Marketplace\Adapter\ConfigurationAdapter;
use Empik\Marketplace\Adapter\LinkAdapter;
use Empik\Marketplace\Processor\ExportOfferProcessor;
use Empik\Marketplace\Validator\Validator;
class AdminEmpikOffersController extends ModuleAdminController
{
const CONF_EXPORT_SUCCESS = 1;
/** @var ExportOfferProcessor */
protected $exportOfferProcessor;
/** @var LinkAdapter */
protected $link;
public function __construct()
{
parent::__construct();
$this->bootstrap = true;
$this->_conf[self::CONF_EXPORT_SUCCESS] = $this->l('Export successful.');
$this->exportOfferProcessor = $this->module->getService('empik.marketplace.processor.exportOfferProcessor');
$this->link = $this->module->getService('empik.marketplace.adapter.link');
}
public function init()
{
if (Tools::getIsset('submitOrderForm')) {
$this->handleForm();
}
parent::init();
}
public function ajaxProcessExportOffers()
{
$page = (int)Tools::getValue('page');
if ($page < 0) {
$page = 0;
}
$this->exportOfferProcessor->setPage($page);
$this->exportOfferProcessor->process();
$continue = !$this->exportOfferProcessor->isLastPage();
$this->ajaxDie(json_encode([
'success' => !$this->exportOfferProcessor->hasErrors(),
'errors' => $this->exportOfferProcessor->getErrors(),
'continue' => $continue,
'redirect' => $this->link->getAdminLink($this->controller_name, ['conf' => self::CONF_EXPORT_SUCCESS]),
]));
}
public function initContent()
{
$this->display = 'edit';
parent::initContent();
}
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
$this->addJS(_MODULE_DIR_ . $this->module->name . '/views/js/admin/empik.js');
Media::addJsDef([
'empikAjaxUrl' => $this->link->getAdminLink($this->controller_name, ['ajax' => 1]),
]);
}
public function renderForm()
{
return $this->renderOrderForm();
}
public function renderOrderForm()
{
$controller = $this->controller_name;
$language = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$this->context->smarty->assign([
'url_export_offers' => $this->link->getAdminLink($controller, ['action' => 'exportOffers']),
'url_manage_price' => $this->link->getAdminLink('AdminEmpikProductsPrice'),
]);
$leadTimeToShip = [];
$leadTimeToShip[] = [
'id' => -1,
'name' => $this->l('- No selection -'),
];
for ($x = 0; $x <= 44; $x++) {
$leadTimeToShip[] = [
'id' => $x,
'name' => $x,
];
}
$formFields = [
'form' => [
'legend' => [
'title' => $this->l('Offers'),
'icon' => 'icon-cogs',
],
'input' => [
[
'type' => 'switch',
'label' => $this->l('Sync Empik Marketplace offers automatically'),
'hint' => $this->l('Sync Empik Marketplace offers automatically'),
'name' => 'sync_offers',
'is_bool' => true,
'values' => [
[
'id' => 'sync_offers_on',
'value' => 1,
'label' => $this->l('Yes'),
],
[
'id' => 'sync_offers_off',
'value' => 0,
'label' => $this->l('No'),
],
],
],
[
'type' => 'switch',
'label' => $this->l('Sync logistic class'),
'hint' => $this->l('Enabling this option will update logistic class for all offers'),
'name' => 'sync_logistic_class',
'is_bool' => true,
'values' => [
[
'id' => 'sync_logistic_class_on',
'value' => 1,
'label' => $this->l('Yes'),
],
[
'id' => 'sync_logistic_class_off',
'value' => 0,
'label' => $this->l('No'),
],
],
],
[
'type' => 'select',
'label' => $this->l('Offer identifier'),
'hint' => $this->l('Offer identifier'),
'name' => 'offer_identifier',
'options' => [
'query' => [
[
'id' => 'EAN',
'name' => $this->l('EAN'),
],
[
'id' => 'SHOP_SKU',
'name' => $this->l('SKU'),
],
],
'id' => 'id',
'name' => 'name',
],
],
[
'type' => 'select',
'label' => $this->l('SKU type'),
'hint' => $this->l('SKU type'),
'name' => 'sku_type',
'options' => [
'query' => [
[
'id' => 'REFERENCE',
'name' => $this->l('Reference'),
],
[
'id' => 'EAN',
'name' => $this->l('EAN'),
],
[
'id' => 'ID',
'name' => $this->l('ID'),
],
],
'id' => 'id',
'name' => 'name',
],
],
[
'type' => 'select',
'label' => $this->l('Leadtime to ship'),
'hint' => $this->l('Leadtime to ship'),
'name' => 'lead_time_to_ship',
'options' => [
'query' => $leadTimeToShip,
'id' => 'id',
'name' => 'name',
],
],
[
'type' => 'text',
'label' => $this->l('Price ratio'),
'hint' => $this->l('Price ratio'),
'name' => 'price_ratio',
],
[
'type' => 'text',
'label' => $this->l('Add to price'),
'hint' => $this->l('Add to price'),
'name' => 'add_to_price',
],
[
'type' => 'text',
'label' => $this->l('Reduce stock'),
'hint' => $this->l('Reduce stock'),
'name' => 'reduce_stock',
],
[
'label' => '',
'type' => 'html',
'name' => 'html_data',
'html_content' => $this->context->smarty->fetch(
$this->module->getLocalPath().'/views/templates/admin/_partials/export_offers_button.tpl'
),
],
[
'label' => '',
'type' => 'html',
'name' => 'html_data',
'html_content' => $this->context->smarty->fetch(
$this->module->getLocalPath().'/views/templates/admin/_partials/manage_price_button.tpl'
),
],
],
'buttons' => [],
'submit' => [
'title' => $this->l('Save'),
],
],
];
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->default_form_language = $language->id;
$helper->submit_action = 'submitOrderForm';
$helper->currentIndex = $this->link->getAdminLink($controller);
$helper->token = Tools::getAdminTokenLite('AdminEmpikOffers');
$helper->tpl_vars = [
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
];
$helper->tpl_vars['fields_value']['sync_offers'] = Tools::getValue('sync_offers', (int)Configuration::get(ConfigurationAdapter::CONF_SYNC_OFFERS));
$helper->tpl_vars['fields_value']['sync_logistic_class'] = Tools::getValue('sync_logistic_class', (int)Configuration::get(ConfigurationAdapter::CONF_SYNC_LOGISTIC_CLASS));
$helper->tpl_vars['fields_value']['offer_identifier'] = Tools::getValue('offer_identifier', Configuration::get(ConfigurationAdapter::CONF_OFFER_IDENTIFIER));
$helper->tpl_vars['fields_value']['sku_type'] = Tools::getValue('sku_type', Configuration::get(ConfigurationAdapter::CONF_SKU_TYPE));
$helper->tpl_vars['fields_value']['lead_time_to_ship'] = Tools::getValue('lead_time_to_ship', (float)Configuration::get(ConfigurationAdapter::CONF_LEAD_TIME_TO_SHIP));
$helper->tpl_vars['fields_value']['price_ratio'] = Tools::getValue('price_ratio', (float)Configuration::get(ConfigurationAdapter::CONF_PRICE_RATIO));
$helper->tpl_vars['fields_value']['add_to_price'] = Tools::getValue('add_to_price', (float)Configuration::get(ConfigurationAdapter::CONF_ADD_TO_PRICE));
$helper->tpl_vars['fields_value']['reduce_stock'] = Tools::getValue('reduce_stock', (int)Configuration::get(ConfigurationAdapter::CONF_REDUCE_STOCK));
return $helper->generateForm([$formFields]);
}
public function handleForm()
{
$syncOffers = Tools::getValue('sync_offers');
$syncLogisticClass = Tools::getValue('sync_logistic_class');
$offerIdentifier = Tools::getValue('offer_identifier');
$skuType = Tools::getValue('sku_type');
$leadTimeToShip = Tools::getValue('lead_time_to_ship');
$priceRatio = Tools::getValue('price_ratio');
$addToPrice = Tools::getValue('add_to_price');
$reduceStock = Tools::getValue('reduce_stock');
if (!is_numeric($syncOffers)) {
$this->errors[] = $this->l('Invalid Sync offers field');
}
if (!is_numeric($syncLogisticClass)) {
$this->errors[] = $this->l('Invalid Sync logistic class field');
}
if (!Validator::isOfferIdentifier($offerIdentifier)) {
$this->errors[] = $this->l('Invalid Offer identifier field');
}
if (!Validator::isSkuType($skuType)) {
$this->errors[] = $this->l('Invalid SKU type field');
}
if (!Validator::isInt($leadTimeToShip) || $leadTimeToShip < -1 || $leadTimeToShip > 44) {
$this->errors[] = $this->l('Invalid Lead time to ship field');
}
if (!Validator::isFloat($priceRatio) || $priceRatio < 0) {
$this->errors[] = $this->l('Invalid Price ratio field');
}
if (!Validator::isFloat($addToPrice) || $addToPrice < 0) {
$this->errors[] = $this->l('Invalid Add to price field');
}
if (!Validator::isInt($reduceStock) || $reduceStock < 0) {
$this->errors[] = $this->l('Invalid Reduce stock field');
}
if (empty($this->errors)) {
$result = true;
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_SYNC_OFFERS, (int)$syncOffers);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_SYNC_LOGISTIC_CLASS, (int)$syncLogisticClass);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_OFFER_IDENTIFIER, $offerIdentifier);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_SKU_TYPE, $skuType);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_LEAD_TIME_TO_SHIP, $leadTimeToShip);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_PRICE_RATIO, (float)$priceRatio);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_ADD_TO_PRICE, (float)$addToPrice);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_REDUCE_STOCK, (float)$reduceStock);
if ($result) {
Tools::redirectAdmin(
$this->link->getAdminLink($this->controller_name, ['conf' => 4])
);
}
}
$this->errors[] = $this->l('Error saving form.');
}
protected function l($string, $class = null, $addslashes = false, $htmlentities = true)
{
return Translate::getModuleTranslation($this->module, $string, get_class($this), null, $addslashes);
}
}

View File

@@ -0,0 +1,284 @@
<?php
use Empik\Marketplace\Adapter\ConfigurationAdapter;
use Empik\Marketplace\Adapter\LinkAdapter;
use Empik\Marketplace\API\EmpikClient;
use Empik\Marketplace\DataProvider\CarriersDataProvider;
use Empik\Marketplace\Factory\EmpikClientFactory;
use Empik\Marketplace\Manager\CarrierMapManager;
use Empik\Marketplace\Validator\Validator;
class AdminEmpikOrdersController extends ModuleAdminController
{
/** @var EmpikMarketplace */
public $module;
/** @var EmpikClientFactory */
private $empikClientFactory;
/** @var CarrierMapManager */
protected $carrierMapManager;
/** @var LinkAdapter */
protected $link;
public function __construct()
{
parent::__construct();
$this->bootstrap = true;
$this->empikClientFactory = $this->module->getService('empik.marketplace.factory.empikClientFactory');
$this->carrierMapManager = $this->module->getService('empik.marketplace.manager.carrierMapManager');
$this->link = $this->module->getService('empik.marketplace.adapter.link');
}
public function init()
{
if (Tools::getIsset('submitOrderForm') || Tools::getIsset('submitOrderFormShipping')) {
$this->handleForm();
}
parent::init();
}
public function initContent()
{
$this->display = 'edit';
parent::initContent();
}
public function handleForm()
{
$result = true;
if (Tools::getIsset('submitOrderForm')) {
$importOrders = Tools::getValue('import_orders');
$autoAcceptOrders = Tools::getValue('auto_accept_orders');
$newOrderState = Tools::getValue('new_order_state');
$shippedOrderState = Tools::getValue('shipped_order_state');
if (!Validator::isBool($importOrders)) {
$this->errors[] = $this->l('Invalid Import orders field');
}
if (!Validator::isBool($autoAcceptOrders)) {
$this->errors[] = $this->l('Invalid Auto accept orders field');
}
if (!Validator::isInt($newOrderState)) {
$this->errors[] = $this->l('Invalid New order state field');
}
if (!Validator::isInt($shippedOrderState)) {
$this->errors[] = $this->l('Invalid Shipped order state field');
}
if (empty($this->errors)) {
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_IMPORT_ORDERS, (int)$importOrders);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_AUTO_ACCEPT_ORDERS, (int)$autoAcceptOrders);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_NEW_ORDER_STATE, (int)$newOrderState);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_SHIPPED_ORDER_STATE, (int)$shippedOrderState);
}
}
if (Tools::getIsset('submitOrderFormShipping')) {
$result &= $this->carrierMapManager->store(Tools::getValue('carrier', []));
}
if ($result && empty($this->errors)) {
Tools::redirectAdmin(
$this->link->getAdminLink($this->controller_name, ['conf' => 4])
);
}
$this->errors[] = $this->l('Error saving form.');
}
public function renderForm()
{
if (!$this->module->getAuthStatus()) {
$this->errors[] = $this->l('Before starting, set up the connection');
return false;
}
return
$this->renderOrderForm().
$this->renderShippingMappingForm();
}
public function renderOrderForm()
{
$language = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$orderStates = OrderState::getOrderStates($language->id);
$formFields = [
'form' => [
'legend' => [
'title' => $this->l('Orders'),
'icon' => 'icon-cogs',
],
'input' => [
[
'type' => 'switch',
'label' => $this->l('Import orders from Empik Marketplace'),
'hint' => $this->l('Import orders from Empik Marketplace'),
'name' => 'import_orders',
'is_bool' => true,
'values' => [
[
'id' => 'import_orders_on',
'value' => 1,
'label' => $this->l('Yes'),
],
[
'id' => 'import_orders_off',
'value' => 0,
'label' => $this->l('No'),
],
],
],
[
'type' => 'switch',
'label' => $this->l('Auto accept orders in Empik Marketplace'),
'hint' => $this->l('Auto accept orders in Empik Marketplace'),
'name' => 'auto_accept_orders',
'is_bool' => true,
'values' => [
[
'id' => 'auto_accept_orders_on',
'value' => 1,
'label' => $this->l('Yes'),
],
[
'id' => 'auto_accept_orders_off',
'value' => 0,
'label' => $this->l('No'),
],
],
],
[
'type' => 'select',
'label' => $this->l('New order state'),
'hint' => $this->l('New order state'),
'name' => 'new_order_state',
'options' => [
'query' => $orderStates,
'id' => 'id_order_state',
'name' => 'name',
],
'class' => 'fixed-width-xxl',
],
[
'type' => 'select',
'label' => $this->l('Shipped order state'),
'hint' => $this->l('Shipped order state'),
'name' => 'shipped_order_state',
'options' => [
'query' => $orderStates,
'id' => 'id_order_state',
'name' => 'name',
],
'class' => 'fixed-width-xxl',
],
],
'buttons' => [],
'submit' => [
'title' => $this->l('Save'),
],
],
];
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->default_form_language = $language->id;
$helper->submit_action = 'submitOrderForm';
$helper->currentIndex = $this->link->getAdminLink($this->controller_name);
$helper->token = Tools::getAdminTokenLite('AdminEmpikOrders');
$helper->tpl_vars = [
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
];
$helper->tpl_vars['fields_value']['import_orders'] = Tools::getValue('import_orders', (int)Configuration::get(ConfigurationAdapter::CONF_IMPORT_ORDERS));
$helper->tpl_vars['fields_value']['auto_accept_orders'] = Tools::getValue('auto_accept_orders', (int)Configuration::get(ConfigurationAdapter::CONF_AUTO_ACCEPT_ORDERS));
$helper->tpl_vars['fields_value']['new_order_state'] = Tools::getValue('new_order_state', (int)Configuration::get(ConfigurationAdapter::CONF_NEW_ORDER_STATE));
$helper->tpl_vars['fields_value']['shipped_order_state'] = Tools::getValue('shipped_order_state', (int)Configuration::get(ConfigurationAdapter::CONF_SHIPPED_ORDER_STATE));
return $helper->generateForm([$formFields]);
}
public function renderShippingMappingForm()
{
$language = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
/** @var EmpikClient $client */
$client = $this->empikClientFactory->createClient();
try {
$responseShippingTypes = $client->getShippingTypes();
$responseCarriers = $client->getCarriers();
} catch (Exception $e) {
$this->errors[] = $e->getMessage();
return false;
}
$shopCarriers = (new CarriersDataProvider())->getCarriers();
$this->context->smarty->assign(
[
'empik_carriers' => $responseCarriers['carriers'],
'empik_shipping_types' => $responseShippingTypes['shipping_types'],
'shop_carriers' => $shopCarriers,
'map' => $this->carrierMapManager->loadFromConfig(),
]
);
$formFields = [
'form' => [
'legend' => [
'title' => $this->l('Shipping'),
'icon' => 'icon-cogs',
],
'input' => [
[
'type' => 'html',
'label' => $this->l('Shipping mapping'),
'name' => 'html_data',
'html_content' => $this->context->smarty->fetch(
$this->module->getLocalPath().'/views/templates/admin/_partials/shipping_table.tpl'
),
],
],
'buttons' => [],
'submit' => [
'title' => $this->l('Save'),
],
],
];
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->default_form_language = $language->id;
$helper->submit_action = 'submitOrderFormShipping';
$helper->currentIndex = $this->link->getAdminLink($this->controller_name);
$helper->token = Tools::getAdminTokenLite('AdminEmpikOrders');
$helper->tpl_vars = [
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
];
return $helper->generateForm([$formFields]);
}
protected function l($string, $class = null, $addslashes = false, $htmlentities = true)
{
return Translate::getModuleTranslation($this->module, $string, get_class($this), null, $addslashes);
}
}

View File

@@ -0,0 +1,472 @@
<?php
use Empik\Marketplace\Adapter\LinkAdapter;
use Empik\Marketplace\Configuration\ExportConfiguration;
use Empik\Marketplace\Handler\UpdateDeleteOfferHandler;
use Empik\Marketplace\Processor\ExportProductProcessor;
use Empik\Marketplace\Repository\ProductRepository;
class AdminEmpikProductsController extends ModuleAdminController
{
const CONF_EXPORT_SUCCESS = 1;
const CONF_EXCLUDE_ALL_SUCCESS = 2;
const CONF_INCLUDE_ALL_SUCCESS = 3;
/** @var EmpikMarketplace */
public $module;
/** @var Category */
protected $id_current_category;
/** @var ExportProductProcessor */
protected $exportProductProcessor;
/** @var ExportConfiguration */
protected $exportConfiguration;
/** @var ProductRepository */
protected $productRepository;
/** @var LinkAdapter */
protected $link;
public function __construct()
{
$this->table = 'product';
$this->className = 'Product';
$this->lang = true;
$this->bootstrap = true;
parent::__construct();
$this->_conf[self::CONF_EXPORT_SUCCESS] = $this->l('Export successful.');
$this->_conf[self::CONF_EXCLUDE_ALL_SUCCESS] = $this->l('All products removed from export successful.');
$this->_conf[self::CONF_INCLUDE_ALL_SUCCESS] = $this->l('All products added to export successful.');
$this->exportProductProcessor = $this->module->getService('empik.marketplace.processor.exportProductProcessor');
$this->exportConfiguration = $this->module->getService('empik.marketplace.configuration.exportConfiguration');
$this->productRepository = $this->module->getService('empik.marketplace.repository.productRepository');
$this->link = $this->module->getService('empik.marketplace.adapter.link');
$langId = Context::getContext()->language->id;
$shopId = Context::getContext()->shop->id;
if (Tools::getValue('reset_filter_category')) {
$this->context->cookie->id_category_empik_products_filter = false;
}
$id_category = (int)Tools::getValue('id_category');
if (Tools::getIsset('id_category')) {
$this->id_current_category = $id_category;
$this->context->cookie->id_category_empik_products_filter = $id_category;
}
if ($this->context->cookie->id_category_empik_products_filter) {
$this->id_current_category = $this->context->cookie->id_category_empik_products_filter;
}
if ($this->id_current_category) {
$this->_join .= ' INNER JOIN `'._DB_PREFIX_.'category_product` cp ON (
cp.`id_product` = a.`id_product` AND cp.`id_category` = '.(int)$this->id_current_category.'
)';
}
$this->_join .= 'LEFT JOIN `'._DB_PREFIX_.'empik_product` ep ON (
ep.id_product = a.id_product AND ep.id_product_attribute = 0
)';
$this->_select .= '
a.price AS price_tax_incl,
sa.quantity AS quantity,
cl.name AS category_name,
IFNULL(ep.product_export, 0) AS product_export,
IFNULL(ep.offer_export, 0) AS offer_export
';
$this->_join .= 'LEFT JOIN `'._DB_PREFIX_.'stock_available` sa ON (
sa.id_product = a.id_product AND
sa.id_product_attribute = 0 '.
StockAvailable::addSqlShopRestriction(null, null, 'sa').')';
$this->_join .= 'LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (
cl.id_category = a.id_category_default AND cl.id_lang = '.(int)$langId.' AND cl.id_shop = '.(int)$shopId.'
)';
$this->fields_list = [
'id_product' => [
'title' => $this->l('ID'),
'align' => 'center',
'class' => 'fixed-width-xs',
],
'name' => [
'title' => $this->l('Name'),
'filter_key' => 'b!name',
],
'category_name' => [
'title' => $this->l('Category'),
'search' => false,
],
'reference' => [
'title' => $this->l('Reference'),
'class' => 'fixed-width-md',
],
'price' => [
'title' => $this->l('Price (tax excl.)'),
'type' => 'price',
'class' => 'fixed-width-md',
],
'price_tax_incl' => [
'title' => $this->l('Price (tax incl.)'),
'type' => 'price',
'search' => false,
'orderby' => false,
'class' => 'fixed-width-md',
],
'quantity' => [
'title' => $this->l('Quantity'),
'filter_key' => 'sa!quantity',
'class' => 'fixed-width-md',
],
'product_export' => [
'title' => $this->l('Product export'),
'product_export' => 'status',
'type' => 'bool',
'class' => 'fixed-width-md',
'align' => 'center',
'callback' => 'displayEnableProductButton',
],
'offer_export' => [
'title' => $this->l('Offer export'),
'offer_export' => 'status',
'type' => 'bool',
'class' => 'fixed-width-md',
'align' => 'center',
'callback' => 'displayEnableOfferButton',
],
];
$this->addListActions();
}
protected function addListActions()
{
$this->addRowAction('view');
$this->bulk_actions = [
'addProducts' => [
'text' => $this->l('Add products to export'),
'icon' => 'icon-plus',
],
'removeProducts' => [
'text' => $this->l('Remove products from export'),
'icon' => 'icon-trash',
],
'addOffers' => [
'text' => $this->l('Add offers to export'),
'icon' => 'icon-plus',
],
'removeOffers' => [
'text' => $this->l('Remove offers from export'),
'icon' => 'icon-trash',
],
];
}
public function displayEnableProductButton($val, $row)
{
$id = $row['id_product'];
$p = Tools::getValue('submitFilter' . $this->table);
$this->context->smarty->assign(
[
'href' => self::$currentIndex.'&token='.$this->token.'&'.$this->identifier.'='.$id.'&action='.(!$val ? 'enableProduct' : 'disableProduct').($p ? '&submitFilter' . $this->table . '=' . $p : ''),
'action' => $this->l('Enable'),
'enabled' => $val,
]
);
return $this->module->display($this->module->name, 'views/templates/admin/list_action_enable.tpl');
}
public function displayEnableOfferButton($val, $row)
{
$id = $row['id_product'];
$p = Tools::getValue('submitFilter' . $this->table);
$this->context->smarty->assign(
[
'href' => self::$currentIndex.'&token='.$this->token.'&'.$this->identifier.'='.$id.'&action='.(!$val ? 'enableOffer' : 'disableOffer').($p ? '&submitFilter' . $this->table . '=' . $p : ''),
'action' => $this->l('Enable'),
'enabled' => $val,
]
);
return $this->module->display($this->module->name, 'views/templates/admin/list_action_enable.tpl');
}
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
$this->addJS(_MODULE_DIR_ . $this->module->name . '/views/js/admin/empik.js');
Media::addJsDef([
'empikAjaxUrl' => $this->link->getAdminLink($this->controller_name, ['ajax' => 1]),
]);
}
public function initToolbar()
{
$this->toolbar_btn = [];
}
public function getList($id_lang, $orderBy = null, $orderWay = null, $start = 0, $limit = null, $id_lang_shop = null)
{
parent::getList(
$id_lang,
$orderBy,
$orderWay,
$start,
$limit,
true
);
foreach ($this->_list as $i => $product) {
$this->_list[$i]['price_tax_incl'] = Product::getPriceStatic($product['id_product']);
}
}
public function renderView()
{
// PS 1.6 redirect
Tools::redirectAdmin(
$this->link->getAdminLink(
'AdminProducts',
['id_product' => Tools::getValue('id_product')]
) . '&update' . $this->table
);
}
public function ajaxProcessExportProducts()
{
$page = (int)Tools::getValue('page');
if ($page < 0) {
$page = 0;
}
$this->exportProductProcessor->setPage($page);
$this->exportProductProcessor->process();
$continue = !$this->exportProductProcessor->isLastPage();
$this->ajaxDie(json_encode([
'success' => true,
'continue' => $continue,
'redirect' => $this->link->getAdminLink($this->controller_name, ['conf' => self::CONF_EXPORT_SUCCESS]),
'errors' => $this->errors,
]));
}
public function initContent()
{
$exportConf = $this->exportConfiguration;
$csvAbsPath = $exportConf::EXPORT_PATH;
$csvRelPath = $exportConf::EXPORT_DIR . $exportConf::EXPORT_PRODUCT_FILENAME;
$this->context->smarty->assign(
[
'id_category' => $this->id_current_category,
'tree' => $this->renderCategoryTree(),
'api_authenticated' => $this->module->getAuthStatus(),
'url_docs' => $this->link->getAdminLink('AdminEmpikHelp'),
'url_export_products' => $this->link->getAdminLink($this->controller_name, ['action' => 'exportProducts']),
'url_exclude_all' => $this->link->getAdminLink($this->controller_name, ['action' => 'excludeAll']),
'url_include_all' => $this->link->getAdminLink($this->controller_name, ['action' => 'includeAll']),
'url_products_csv' => file_exists($csvAbsPath) ? $csvRelPath : false,
]
);
$this->content .= $this->context->smarty->fetch(
$this->module->getLocalPath().'/views/templates/admin/products.tpl'
);
$this->content .= $this->context->smarty->fetch(
$this->module->getLocalPath().'/views/templates/admin/list_category_filter.tpl'
);
parent::initContent();
}
protected function renderCategoryTree()
{
$tree = new HelperTreeCategories('product_associated_categories');
$tree->setUseCheckBox(false)
->setFullTree(true)
->setRootCategory(Context::getContext()->shop->id_category);
if ($this->id_current_category) {
$tree->setSelectedCategories([$this->id_current_category]);
}
$tree->setInputName('category_filter');
return $tree->render();
}
public function processEnableProduct()
{
$productId = Tools::getValue('id_product');
$empikProduct = \EmpikProduct::getOrCreate($productId);
$empikProduct->product_export = 1;
$empikProduct->save();
Db::getInstance()->update('empik_product', ['product_export' => 1], 'id_product = ' . (int)$productId);
}
public function processDisableProduct()
{
$productId = Tools::getValue('id_product');
$empikProduct = \EmpikProduct::getOrCreate($productId);
$empikProduct->product_export = 0;
$empikProduct->save();
Db::getInstance()->update('empik_product', ['product_export' => 0], 'id_product = ' . (int)$productId);
}
public function processEnableOffer()
{
$productId = Tools::getValue('id_product');
$empikProduct = \EmpikProduct::getOrCreate($productId);
$empikProduct->offer_export = 1;
$empikProduct->save();
}
public function processDisableOffer()
{
$productId = Tools::getValue('id_product');
$empikProduct = \EmpikProduct::getOrCreate($productId);
$empikProduct->offer_export = 0;
$empikProduct->save();
/** @var UpdateDeleteOfferHandler $handler */
$handler = $this->module->getService('empik.marketplace.handler.updateDeleteOfferHandler');
if (($result = $handler->handle([$productId]))) {
Tools::redirectAdmin(
$this->link->getAdminLink($this->controller_name, ['conf' => 4])
);
}
$this->errors = $handler->getErrors();
}
public function processBulkAddProducts()
{
if (is_array($this->boxes) && !empty($this->boxes)) {
foreach ($this->boxes as $productId) {
$empikProduct = \EmpikProduct::getOrCreate($productId);
$empikProduct->product_export = 1;
$empikProduct->save();
}
} else {
$this->errors[] = $this->l('You must select at least one item');
}
}
public function processBulkRemoveProducts()
{
if (is_array($this->boxes) && !empty($this->boxes)) {
foreach ($this->boxes as $productId) {
$empikProduct = \EmpikProduct::getOrCreate($productId);
$empikProduct->product_export = 0;
$empikProduct->save();
}
} else {
$this->errors[] = $this->l('You must select at least one item');
}
}
public function processBulkAddOffers()
{
if (is_array($this->boxes) && !empty($this->boxes)) {
foreach ($this->boxes as $productId) {
$empikProduct = \EmpikProduct::getOrCreate($productId);
$empikProduct->offer_export = 1;
$empikProduct->save();
}
} else {
$this->errors[] = $this->l('You must select at least one item');
}
}
public function processBulkRemoveOffers()
{
if (is_array($this->boxes) && !empty($this->boxes)) {
/** @var UpdateDeleteOfferHandler $handler */
$handler = $this->module->getService('empik.marketplace.handler.updateDeleteOfferHandler');
if (($result = $handler->handle($this->boxes))) {
foreach ($this->boxes as $productId) {
$empikProduct = \EmpikProduct::getOrCreate($productId);
$empikProduct->offer_export = 0;
$empikProduct->save();
}
Tools::redirectAdmin(
$this->link->getAdminLink($this->controller_name, ['conf' => 4])
);
}
$this->errors = $handler->getErrors();
} else {
$this->errors[] = $this->l('You must select at least one item');
}
}
public function processExcludeAll()
{
Db::getInstance()->update(
'empik_product',
[
'product_export' => 0,
'offer_export' => 0,
]
);
Tools::redirectAdmin(
$this->link->getAdminLink($this->controller_name, ['conf' => self::CONF_EXCLUDE_ALL_SUCCESS])
);
}
public function processIncludeAll()
{
$sql = 'INSERT IGNORE INTO `' . _DB_PREFIX_ . 'empik_product` (`id_product`, `id_product_attribute`, `logistic_class`, `product_export`, `offer_export`)
SELECT `id_product`, 0, 0, 1, 1
FROM `' . _DB_PREFIX_ . 'product`
';
Db::getInstance()->execute($sql);
Db::getInstance()->update(
'empik_product',
[
'product_export' => 1,
'offer_export' => 1,
]
);
Tools::redirectAdmin(
$this->link->getAdminLink($this->controller_name, ['conf' => self::CONF_INCLUDE_ALL_SUCCESS])
);
}
protected function l($string, $class = null, $addslashes = false, $htmlentities = true)
{
return Translate::getModuleTranslation($this->module, $string, get_class($this), null, $addslashes);
}
}

View File

@@ -0,0 +1,524 @@
<?php
use Empik\Marketplace\Adapter\LinkAdapter;
use Empik\Marketplace\API\EmpikClient;
use Empik\Marketplace\Factory\EmpikClientFactory;
use Empik\Marketplace\Repository\ProductRepository;
use Empik\Marketplace\Cache\Cache;
use PrestaShop\PrestaShop\Adapter\CombinationDataProvider;
class AdminEmpikProductsPriceController extends ModuleAdminController
{
/** @var EmpikMarketplace */
public $module;
/** @var ProductRepository */
protected $productRepository;
/** @var CombinationDataProvider */
protected $combinationDataProvider;
/** @var EmpikClient */
protected $empikClient;
/** @var LinkAdapter */
protected $link;
/** @var Cache */
protected $cache;
/** @var EmpikProduct */
protected $object;
public function __construct()
{
$this->table = 'empik_product';
$this->className = EmpikProduct::class;
$this->bootstrap = true;
parent::__construct();
// 1.7.0
if (Tools::getIsset('changeDisplayOriginalPrice')) {
$idEmpikProduct = (int)Tools::getValue('id_empik_product');
$idProduct = Db::getInstance()->getValue('SELECT id_product FROM ' . _DB_PREFIX_ . 'empik_product
WHERE id_empik_product = ' . (int)$idEmpikProduct);
if ($idProduct > 0) {
\Db::getInstance()->execute('UPDATE '._DB_PREFIX_.'empik_product
SET export_original_price = IF(export_original_price=1, 0, 1)
WHERE id_product = '.(int)$idProduct);
}
Tools::redirectAdmin($this->context->link->getAdminLink('AdminEmpikProductsPrice'));
}
$this->addRowAction('edit');
$this->productRepository = $this->module->getService('empik.marketplace.repository.productRepository');
$this->combinationDataProvider = $this->module->getService('empik.marketplace.dataProvider.combinationDataProvider');
$this->link = $this->module->getService('empik.marketplace.adapter.link');
$this->cache = $this->module->getService('empik.marketplace.cache.cache');
/** @var EmpikClientFactory $empikClientFactory */
$empikClientFactory = $this->module->getService('empik.marketplace.factory.empikClientFactory');
$this->empikClient = $empikClientFactory->createClient();
$langId = Context::getContext()->language->id;
$shopId = Context::getContext()->shop->id;
$this->_select .= 'p.reference, p.ean13, pl.name, p.price AS price_tax_incl,
cl.name as category_name,
IFNULL(ep.offer_price, 0) AS offer_price,
IFNULL(ep.offer_price_reduced, 0) AS offer_price_reduced,
CONCAT(ep.id_empik_product, "_", ep.export_original_price) as export_original_price_data
'; // 1.7.0
$this->_join .= 'LEFT JOIN `'._DB_PREFIX_.'product` p ON (
p.id_product = a.id_product AND a.id_product_attribute = 0
)';
$this->_join .= 'LEFT JOIN `'._DB_PREFIX_.'empik_product` ep ON (
ep.id_product = a.id_product AND ep.id_product_attribute = 0
)';
$this->_join .= 'LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (
cl.id_category = p.id_category_default AND cl.id_lang = '.(int)$langId.' AND cl.id_shop = '.(int)$shopId.'
)';
$this->_join .= 'LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (
pl.id_product = a.id_product AND pl.id_lang = '.(int)$langId.' AND pl.id_shop = '.(int)$shopId.'
)';
$this->_where = 'AND a.id_product_attribute = 0';
$this->fields_list = [
'id_product' => [
'title' => $this->l('ID'),
'align' => 'center',
'class' => 'fixed-width-xs',
],
'reference' => [
'title' => $this->l('Reference'),
'class' => 'fixed-width-md',
],
'ean13' => [
'title' => $this->l('EAN'),
'class' => 'fixed-width-md',
],
'name' => [
'title' => $this->l('Name'),
'filter_key' => 'pl!name',
],
'category_name' => [
'title' => $this->l('Category'),
'filter_key' => 'cl!name',
],
'price_tax_incl' => [
'title' => $this->l('Price'),
'type' => 'price',
'search' => false,
'orderby' => false,
'class' => 'fixed-width-md',
],
'offer_price' => [
'title' => $this->l('Empik price'),
'class' => 'fixed-width-md',
'align' => 'center',
'callback' => 'displayEmpikPriceColumn',
'remove_onclick' => true,
],
'price_reduced_tax_incl' => [
'title' => $this->l('Price reduced'),
'type' => 'price',
'search' => false,
'orderby' => false,
'class' => 'fixed-width-md',
],
'offer_price_reduced' => [
'title' => $this->l('Empik price reduced'),
'class' => 'fixed-width-md',
'align' => 'center',
'callback' => 'displayEmpikPriceReducedColumn',
'remove_onclick' => true,
],
// 1.7.0
'export_original_price_data' => [
'title' => $this->l('Display discount'),
'class' => 'fixed-width-md',
'align' => 'center',
'search' => false,
'orderby' => false,
'callback' => 'displayEmpikExportOriginalPriceColumn',
'remove_onclick' => true,
],
];
$this->addListActions();
}
public function displayEmpikPriceColumn($val, $row)
{
$combinations = $this->combinationDataProvider->getCombinationsByProductId($row['id_product']);
$this->context->smarty->assign([
'value' => $val,
'id_product' => $row['id_product'],
'combinations' => $combinations,
]);
return $this->module->display($this->module->name, 'views/templates/admin/list_action_edit_price.tpl');
}
public function displayEmpikPriceReducedColumn($val, $row)
{
$combinations = $this->combinationDataProvider->getCombinationsByProductId($row['id_product']);
$this->context->smarty->assign([
'value' => $val,
'id_product' => $row['id_product'],
'combinations' => $combinations,
]);
return $this->module->display($this->module->name, 'views/templates/admin/list_action_edit_price_reduced.tpl');
}
// 1.7.0
public function displayEmpikExportOriginalPriceColumn($val)
{
$data = explode('_', $val);
$this->context->smarty->assign([
'displayOriginal' => (bool)$data[1],
'urlChange' => $this->link->getAdminLink($this->controller_name, ['changeDisplayOriginalPrice' => 1, 'id_empik_product' => $data[0]]),
]);
return $this->module->display($this->module->name, 'views/templates/admin/list_action_original_price.tpl');
}
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
$this->addJS(_MODULE_DIR_ . $this->module->name . '/views/js/admin/empik.js');
Media::addJsDef([
'empikAjaxUrl' => $this->link->getAdminLink($this->controller_name, ['ajax' => 1]),
]);
}
public function initToolbar()
{
$this->toolbar_btn = [];
}
public function initProcess()
{
parent::initProcess();
if ($this->action == 'view') {
$this->display = 'edit';
$this->action = 'edit';
}
$this->handleBulkUpdateLogisticClass();
$this->handleBulkUpdateCondition();
$this->handleBulkUpdateOriginalPriceOn();
$this->handleBulkUpdateOriginalPriceOff();
}
public function getList($id_lang, $orderBy = null, $orderWay = null, $start = 0, $limit = null, $id_lang_shop = null)
{
parent::getList(
$id_lang,
$orderBy,
$orderWay,
$start,
$limit,
true
);
foreach ($this->_list as $i => $product) {
$this->_list[$i]['price_tax_incl'] = Product::getPriceStatic($product['id_product'], true, null, 2, null, false, false);
$this->_list[$i]['price_reduced_tax_incl'] = Product::getPriceStatic($product['id_product'], true, null, 2, null, false, true);
}
}
public function renderForm()
{
$this->fields_form = [
'legend' => [
'title' => $this->l('Offer params'),
'icon' => 'icon-gears',
],
'input' => [
'name' => [
'type' => 'select',
'label' => $this->l('Logistic class'),
'name' => 'logistic_class',
'options' => [
'query' => $this->getLogisticClassesOptions(),
'id' => 'id',
'name' => 'name',
],
'class' => 'fixed-width-xxl',
],
[
'type' => 'select',
'label' => $this->l('Condition'),
'name' => 'condition',
'options' => [
'query' => $this->getConditionOptions(),
'id' => 'id',
'name' => 'name',
],
'class' => 'fixed-width-xxl',
],
],
'submit' => [
'title' => $this->l('Save'),
],
];
return parent::renderForm();
}
protected function getLogisticClassesOptions()
{
$logisticClasses = [];
$response = $this->getLogisticClasses();
if (!empty($response['logistic_classes'])) {
foreach ($response['logistic_classes'] as $logisticClass) {
$logisticClasses[] = [
'id' => $logisticClass['code'],
'name' => $logisticClass['label'],
];
}
}
return $logisticClasses;
}
protected function getConditionOptions()
{
return [
[
'id' => 11,
'name' => $this->l('New (code 11)')
],
[
'id' => 1,
'name' => $this->l('Used - very good condition')
],
[
'id' => 2,
'name' => $this->l('Used - good condition')
],
[
'id' => 3,
'name' => $this->l('Used - satisfactory condition')
],
[
'id' => 4,
'name' => $this->l('Renewed - very good condition')
],
[
'id' => 5,
'name' => $this->l('Renewed - good condition')
],
[
'id' => 6,
'name' => $this->l('Renewed - satisfactory condition')
],
[
'id' => 7,
'name' => $this->l('Damaged packaging')
],
];
}
protected function addListActions()
{
$this->addRowAction('view');
// Logistic class
$response = $this->getLogisticClasses();
if (!empty($response['logistic_classes'])) {
foreach ($response['logistic_classes'] as $logisticClass) {
$key = sprintf('logisticClass_%s', $logisticClass['code']);
$this->bulk_actions[$key] = [
'text' => $this->l('Logistic class:') . ' ' . $logisticClass['label'],
'icon' => 'icon-truck',
];
}
}
// Condition
$conditionOptions = $this->getConditionOptions();
foreach ($conditionOptions as $conditionOption) {
$key = sprintf('condition_%s', $conditionOption['id']);
$this->bulk_actions[$key] = [
'text' => $this->l('Condition:') . ' ' . $conditionOption['name'],
'icon' => 'icon-gears',
];
}
$key = 'original_price_on';
$this->bulk_actions[$key] = [
'text' => $this->l('Display discounts'),
'icon' => 'icon-gears',
];
$key = 'original_price_off';
$this->bulk_actions[$key] = [
'text' => $this->l('Do not display discounts'),
'icon' => 'icon-gears',
];
}
protected function getLogisticClasses()
{
try {
return $this->cache->get('logistic_classes', function () {
return $this->empikClient->getLogisticClasses();
});
} catch (Exception $e) {
$this->errors[] = $e->getMessage();
}
return [];
}
protected function handleBulkUpdateLogisticClass()
{
$requestKeys = array_keys($_REQUEST);
$logisticClassRequest = preg_grep('/logisticClass_(\d+)/', $requestKeys);
if (!empty($logisticClassRequest)) {
$logisticClassCode = preg_replace('/\D/', '', reset($logisticClassRequest));
if (is_numeric($logisticClassCode)) {
$this->processBulkLogisticClass($logisticClassCode);
}
}
}
protected function handleBulkUpdateCondition()
{
$requestKeys = array_keys($_REQUEST);
$conditionRequest = preg_grep('/condition_(\d+)/', $requestKeys);
if (!empty($conditionRequest)) {
$conditionCode = preg_replace('/\D/', '', reset($conditionRequest));
if (is_numeric($conditionCode)) {
$this->processBulkCondition($conditionCode);
}
}
}
protected function handleBulkUpdateOriginalPriceOn()
{
$requestKeys = array_keys($_REQUEST);
$request = preg_grep('/original_price_on/', $requestKeys);
if (!empty($request)) {
if (is_array($this->boxes) && !empty($this->boxes)) {
$this->toggleOriginalPrice(1);
$this->confirmations[] = $this->l('Price settings updated successfully!');
} else {
$this->errors[] = $this->l('You must select at least one item');
}
}
}
protected function handleBulkUpdateOriginalPriceOff()
{
$requestKeys = array_keys($_REQUEST);
$request = preg_grep('/original_price_off/', $requestKeys);
if (!empty($request)) {
if (is_array($this->boxes) && !empty($this->boxes)) {
$this->toggleOriginalPrice(0);
$this->confirmations[] = $this->l('Price settings updated successfully!');
} else {
$this->errors[] = $this->l('You must select at least one item');
}
}
}
private function toggleOriginalPrice($value)
{
$idProducts = Db::getInstance()->executeS('SELECT id_product FROM ' . _DB_PREFIX_ . 'empik_product
WHERE id_empik_product IN (' . implode(',', array_map('intval', $this->boxes)) . ')');
if (!empty($idProducts)) {
foreach ($idProducts as $idProduct) {
Db::getInstance()->execute(
'UPDATE ' . _DB_PREFIX_ . 'empik_product
SET `export_original_price` = '.(int)$value.'
WHERE id_product = ' . (int)$idProduct['id_product']
);
}
}
}
public function ajaxProcessSavePrice()
{
$productId = Tools::getValue('id_product');
$productAttributeId = Tools::getValue('id_product_attribute');
$price = Tools::getValue('price');
$this->productRepository->updateOfferPrice($productId, $productAttributeId, $price);
$this->ajaxDie(json_encode([
'success' => true,
'message' => $this->l('Price saved successfully!'),
'errors' => $this->errors,
]));
}
public function ajaxProcessSaveReducedPrice()
{
$productId = Tools::getValue('id_product');
$productAttributeId = Tools::getValue('id_product_attribute');
$price = Tools::getValue('price');
$this->productRepository->updateOfferPriceReduced($productId, $productAttributeId, $price);
$this->ajaxDie(json_encode([
'success' => true,
'message' => $this->l('Price saved successfully!'),
'errors' => $this->errors,
]));
}
public function processBulkLogisticClass($logisticClass)
{
if (is_array($this->boxes) && !empty($this->boxes)) {
Db::getInstance()->update(
'empik_product',
[
'logistic_class' => (int)$logisticClass,
],
'id_empik_product IN (' . implode(',', array_map('intval', $this->boxes)) . ')'
);
$this->confirmations[] = $this->l('Logistic class updated successfully!');
} else {
$this->errors[] = $this->l('You must select at least one item');
}
}
public function processBulkCondition($condition)
{
if (is_array($this->boxes) && !empty($this->boxes)) {
Db::getInstance()->update(
'empik_product',
[
'condition' => (int)$condition,
],
'id_empik_product IN (' . implode(',', array_map('intval', $this->boxes)) . ')'
);
$this->confirmations[] = $this->l('Condition updated successfully!');
} else {
$this->errors[] = $this->l('You must select at least one item');
}
}
}

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;

View File

@@ -0,0 +1,37 @@
<?php
use Empik\Marketplace\Exception\InvalidActionException;
use Empik\Marketplace\Handler\CronJobsHandler;
class EmpikMarketplaceCronModuleFrontController extends ModuleFrontController
{
/** @var EmpikMarketplace */
public $module;
/** @var CronJobsHandler */
protected $cronJobsHandler;
public function init()
{
parent::init();
$this->cronJobsHandler = $this->module->getService('empik.marketplace.handler.cronJobs');
}
public function postProcess()
{
if ($this->cronJobsHandler->checkToken(Tools::getValue('token'))) {
try {
$this->cronJobsHandler->handle(Tools::getValue('action'));
die($this->module->l('Job complete'));
} catch (InvalidActionException $exception) {
die($this->module->l('Unknown action'));
} catch (Exception $exception) {
die(sprintf($this->module->l('Job failed: %s'), $exception->getMessage()));
}
} else {
die($this->module->l('Invalid token'));
}
}
}

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;

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;

View File

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;

View File

@@ -0,0 +1,270 @@
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
include_once __DIR__.'/vendor/autoload.php';
class EmpikMarketplace extends Module
{
const HOOK_LIST_COMMON = [
'actionOrderHistoryAddAfter',
'actionAdminControllerSetMedia',
'actionObjectProductDeleteBefore',
'actionAdminOrdersTrackingNumberUpdate',
];
const HOOK_LIST_16 = [
'actionAdminOrdersListingFieldsModifier',
'displayAdminOrderLeft',
];
const HOOK_LIST_17 = [
'actionOrderGridDefinitionModifier',
'actionOrderGridQueryBuilderModifier',
'displayAdminOrderSideBottom',
];
/** @var Empik\Marketplace\Install\Installer */
protected $installer;
/** @var Empik\Marketplace\Install\Uninstaller */
protected $uninstaller;
/** @var Empik\Marketplace\Hook\HookAction */
protected $hookAction;
public function __construct()
{
$this->name = 'empikmarketplace';
$this->version = '2.0.0';
$this->author = 'Waynet';
$this->tab = 'market_place';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('EmpikPlace');
$this->description = $this->l('Integration with Empik Marketplace');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall this module?');
$this->controllers = ['cron'];
$this->ps_versions_compliancy = ['min' => '1.7', 'max' => _PS_VERSION_];
}
public function getService($serviceName)
{
if (!isset($this->serviceContainer)) {
$this->serviceContainer = new PrestaShop\ModuleLibServiceContainer\DependencyInjection\ServiceContainer(
$this->name,
$this->getLocalPath()
);
}
return $this->serviceContainer->getService($serviceName);
}
public static function safeAddColumn($table, $column, $def)
{
$count = Db::getInstance()->getValue('SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND COLUMN_NAME=\'' . $column . '\' AND TABLE_NAME=\'' . _DB_PREFIX_ . $table . '\'');
if (!$count)
return Db::getInstance()->execute('ALTER TABLE `' . _DB_PREFIX_ . $table . '` ADD `' . $column . '` ' . $def);
return true;
}
public function install()
{
$return = true;
$return &= parent::install();
$return &= $this->getInstaller()->install();
$return &= self::safeAddColumn('empik_product', 'condition', 'INT(4) NOT NULL DEFAULT 11 AFTER logistic_class');
$return &= self::safeAddColumn('empik_product', 'export_original_price', 'INT(1) NOT NULL DEFAULT 0 AFTER logistic_class');
return (bool)$return;
}
public function getInstaller()
{
if (!isset($this->installer)) {
$this->installer = $this->getService('empik.marketplace.install.installer');
}
return $this->installer;
}
public function uninstall()
{
$return = true;
$return &= $this->getUninstaller()->uninstall();
$return &= parent::uninstall();
return (bool)$return;
}
public function getUninstaller()
{
if (!isset($this->uninstaller)) {
$this->uninstaller = $this->getService('empik.marketplace.install.uninstaller');
}
return $this->uninstaller;
}
public function isUsingNewTranslationSystem()
{
return false;
}
public function getAdminTabs()
{
/** @var \Empik\Marketplace\PrestaShopContext $prestaShopContext */
$prestaShopContext = $this->getService('empik.marketplace.prestaShopContext');
return [
[
'className' => 'AdminEmpik',
'parent' => $prestaShopContext->is17() ? 'SELL' : 0,
'name' => $this->l('Empik'),
'module' => $this->name,
'active' => true,
'icon' => 'next_week',
],
[
'className' => 'AdminEmpikConnection',
'parent' => 'AdminEmpik',
'name' => $this->l('Connection'),
'module' => $this->name,
'active' => true,
'icon' => '',
],
[
'className' => 'AdminEmpikProducts',
'parent' => 'AdminEmpik',
'name' => $this->l('Products'),
'module' => $this->name,
'active' => true,
'icon' => '',
],
[
'className' => 'AdminEmpikProductsPrice',
'parent' => 'AdminEmpik',
'name' => $this->l('Products parameters'),
'module' => $this->name,
'active' => true,
'icon' => '',
],
[
'className' => 'AdminEmpikOffers',
'parent' => 'AdminEmpik',
'name' => $this->l('Offers'),
'module' => $this->name,
'active' => true,
'icon' => '',
],
[
'className' => 'AdminEmpikOrders',
'parent' => 'AdminEmpik',
'name' => $this->l('Orders'),
'module' => $this->name,
'active' => true,
'icon' => '',
],
[
'className' => 'AdminEmpikActionLog',
'parent' => 'AdminEmpik',
'name' => $this->l('Last actions'),
'module' => $this->name,
'active' => true,
'icon' => '',
],
[
'className' => 'AdminEmpikHelp',
'parent' => 'AdminEmpik',
'name' => $this->l('Help'),
'module' => $this->name,
'active' => true,
'icon' => '',
],
];
}
protected function getHookAction()
{
if (!isset($this->hookAction)) {
$this->hookAction = $this->getService('empik.marketplace.hook.hookAction');
}
return $this->hookAction;
}
public function hookActionAdminOrdersListingFieldsModifier($params)
{
$this->getHookAction()->hookActionAdminOrdersListingFieldsModifier($params);
}
public function hookActionOrderGridDefinitionModifier(array $params)
{
$this->getHookAction()->hookActionOrderGridDefinitionModifier($params);
}
public function hookActionOrderGridQueryBuilderModifier(array $params)
{
$this->getHookAction()->hookActionOrderGridQueryBuilderModifier($params);
}
public function hookActionAdminOrdersTrackingNumberUpdate($params)
{
$this->getHookAction()->hookActionAdminOrdersTrackingNumberUpdate($params);
}
public function hookActionOrderHistoryAddAfter($params)
{
$this->getHookAction()->hookActionOrderHistoryAddAfter($params);
}
public function hookDisplayAdminOrderSideBottom(array $params)
{
return $this->getHookAction()->hookDisplayAdminOrder($params);
}
public function hookDisplayAdminOrderLeft(array $params)
{
return $this->getHookAction()->hookDisplayAdminOrder($params);
}
public function hookActionAdminControllerSetMedia($params)
{
return $this->getHookAction()->hookActionAdminControllerSetMedia($params);
}
public function hookActionObjectProductDeleteBefore($params)
{
return $this->getHookAction()->hookActionObjectProductDeleteBefore($params);
}
public function setAuthStatus()
{
$env = Configuration::get(Empik\Marketplace\Adapter\ConfigurationAdapter::CONF_ENVIRONMENT);
$apiKey = Configuration::get(Empik\Marketplace\Adapter\ConfigurationAdapter::CONF_API_KEY);
Configuration::updateValue(
Empik\Marketplace\Adapter\ConfigurationAdapter::CONF_AUTH_STATUS,
md5($env.$apiKey)
);
}
/** @return bool */
public function getAuthStatus()
{
$env = Configuration::get(Empik\Marketplace\Adapter\ConfigurationAdapter::CONF_ENVIRONMENT);
$apiKey = Configuration::get(Empik\Marketplace\Adapter\ConfigurationAdapter::CONF_API_KEY);
$status = Configuration::get(Empik\Marketplace\Adapter\ConfigurationAdapter::CONF_AUTH_STATUS);
return $status === md5($env.$apiKey);
}
}

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;

Binary file not shown.

After

Width:  |  Height:  |  Size: 665 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 B

View File

@@ -0,0 +1,395 @@
<?php
namespace Empik\Marketplace\API;
use Empik\Marketplace\Factory\HttpClientsFactory;
use Empik\Marketplace\Factory\HttpClientFactoryInterface;
use Empik\Marketplace\Exception\InvalidArgumentException;
class EmpikClient
{
const IMPORT_MODE_NORMAL = 'NORMAL';
const IMPORT_MODE_PARTIAL_UPDATE = 'PARTIAL_UPDATE';
const IMPORT_MODE_REPLACE = 'REPLACE';
/** @var string */
private $apiUrl;
/** @var string */
private $apiKey;
/** @var HttpClientInterface */
private $client;
/**
* @param $apiUrl
* @param $apiKey
* @param HttpClientFactoryInterface|null $httpClientFactory
* @throws \Exception
*/
public function __construct($apiUrl, $apiKey, HttpClientFactoryInterface $httpClientFactory = null)
{
if (!$httpClientFactory) {
$httpClientFactory = new HttpClientsFactory();
}
$this->apiUrl = $apiUrl;
$this->apiKey = $apiKey;
$this->client = $httpClientFactory->createHttpClient($apiUrl);
}
/**
* @param int|string $id
* @param array $headers
* @param array $body
*
* @return false|array
*/
private function post($id, array $headers = [], array $body = [])
{
return $this->sendRequest($id, $headers, $body, 'POST');
}
/**
* @param int|string $id
* @param array $headers
* @param array $body
*
* @return false|array
*/
private function put($id, array $headers = [], array $body = [])
{
return $this->sendRequest($id, $headers, $body, 'PUT');
}
/**
* @param int|string $id
* @param array $headers
* @param array $body
*
* @return false|array
*/
private function get($id, array $headers = [], array $body = [])
{
return $this->sendRequest($id, $headers, $body, 'GET');
}
/**
* @param int|string $id
* @param array $headers
* @param array $body
* @param string $method
*
* @return false|array|string
*/
private function sendRequest($id, array $headers, array $body, $method)
{
$headers['Authorization'] = $this->apiKey;
switch ($method)
{
case 'POST':
$response = $this->client->post(
$this->apiUrl . $id,
$headers,
$body
);
break;
case 'PUT':
$response = $this->client->put(
$this->apiUrl . $id,
$headers,
$body
);
break;
case 'GET':
$response = $this->client->get(
$this->apiUrl . $id,
$headers,
$body
);
break;
}
return $response;
}
/**
* @return array|bool|false
*/
public function getAccount()
{
return $this->get(
'/api/account'
);
}
/**
* P41 - Import products to the operator information
*
* @param string $csvPath
*
* @return array|false
* @throws InvalidArgumentException
*/
public function postProducts($csvPath)
{
if (!file_exists($csvPath)) {
throw new InvalidArgumentException(sprintf('CSV product file does not exists: %s', $csvPath));
}
return $this->post(
'/api/products/imports',
[],
[
'file' => [
'filename' => basename($csvPath),
'filepath' => $csvPath,
]
]
);
}
/**
* OF01 - Import a file to add offers
*
* @param string $csvPath
* @param string $importMode
*
* @return array|false
* @throws InvalidArgumentException
*/
public function postOffersImports($csvPath, $importMode = self::IMPORT_MODE_NORMAL)
{
if (!file_exists($csvPath)) {
throw new InvalidArgumentException(sprintf('CSV offer file does not exists: %s', $csvPath));
}
if (!in_array($importMode, [self::IMPORT_MODE_NORMAL, self::IMPORT_MODE_PARTIAL_UPDATE, self::IMPORT_MODE_REPLACE])) {
throw new InvalidArgumentException(sprintf('Unsupported import mode: %s', $importMode));
}
return $this->post(
'/api/offers/imports',
[],
[
'import_mode' => $importMode,
'file' => [
'filename' => basename($csvPath),
'filepath' => $csvPath,
]
]
);
}
/**
* OF24 - Create, update, or delete offers
*
* @param array $offers
*
* @return array|false
*/
public function postOffers(array $offers)
{
return $this->post(
'/api/offers',
[
'Content-Type' => 'application/json'
],
[
'offers' => $offers,
]
);
}
/**
* GET P42 - Get the import status for a product import
*
* @param int $importId
* @return array|bool|false
*/
public function getProductsImport($importId)
{
return $this->get(
'/api/products/imports/' . (int)$importId
);
}
/**
* GET OF02 - Get information and statistics about an offer import
*
* @param int $importId
* @return array|bool|false
*/
public function getOffersImport($importId)
{
return $this->get(
'/api/offers/imports/' . (int)$importId
);
}
/**
* GET SH21 - List all carriers
*
* @return array|bool|false
*/
public function getCarriers()
{
return $this->get(
'/api/shipping/carriers'
);
}
/**
* GET SH12 - List all active shipping methods
*
* @return array|bool|false
*/
public function getShippingTypes()
{
return $this->get(
'/api/shipping/types'
);
}
/**
* GET OR11 - List orders
*
* @param array $filterParams
* @return array|bool|false
*/
public function getOrders($filterParams = [])
{
$filterParams = array_merge([
'sort' => 'dateCreated',
'order' => 'desc',
'max' => '20',
], $filterParams);
$query = http_build_query($filterParams);
return $this->get(
'/api/orders' . '?' . $query
);
}
/**
* PUT OR21 - Accept or refuse order lines
*
* @param int|string $orderReference
* @param array $orderLines
* @return array|bool|false
*/
public function putOrderAccept($orderReference, array $orderLines)
{
$bodyParams['order_lines'] = $orderLines;
return $this->put(
'/api/orders/' . $orderReference . '/accept',
[
'Content-Type' => 'application/json'
],
$bodyParams
);
}
/**
* PUT OR24 - Validate the shipment of an order
*
* @param int|string $orderReference
* @return array|bool|false
*/
public function putOrderShip($orderReference)
{
return $this->put(
'/api/orders/' . $orderReference . '/ship',
[
'Content-Type' => 'application/json'
]
);
}
/**
* PUT OR23 - Update carrier tracking information for a specific order
*
* @param int|string $orderReference
* @param string $carrierCode
* @param string $carrierName
* @param string $carrierUrl
* @param string $trackingNumber
* @return array|false
*/
public function putOrderTracking(
$orderReference,
$carrierCode = null,
$carrierName = null,
$carrierUrl = null,
$trackingNumber = null
)
{
$bodyParams = [];
if ($carrierCode) {
$bodyParams['carrier_code'] = $carrierCode;
}
if ($carrierName) {
$bodyParams['carrier_name'] = $carrierName;
}
if ($carrierUrl) {
$bodyParams['carrier_url'] = $carrierUrl;
}
if ($trackingNumber) {
$bodyParams['tracking_number'] = $trackingNumber;
}
return $this->put(
'/api/orders/' . $orderReference . '/tracking',
[
'Content-Type' => 'application/json'
],
$bodyParams
);
}
/**
* GET P44 - Get the error report file for a product import
*
* @param string $importId
* @return array|bool|false
*/
public function getProductImportErrorReport($importId)
{
return $this->get(
'/api/products/imports/' . $importId . '/new_product_report'
);
}
/**
* GET P44 - Get the error report file for a product import
*
* @param string $importId
* @return array|bool|false
*/
public function getOfferImportErrorReport($importId)
{
return $this->get(
'/api/offers/imports/' . $importId . '/error_report'
);
}
/**
* GET SH31 - List all logistic classes
*
* @return array|bool|false
*/
public function getLogisticClasses()
{
return $this->get(
'/api/shipping/logistic_classes'
);
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace Empik\Marketplace\API;
interface HttpClientInterface
{
public function post($id, array $headers = [], array $body = []);
public function put($id, array $headers = [], array $body = []);
public function get($id, array $headers = [], array $body = []);
}

View File

@@ -0,0 +1,101 @@
<?php
namespace Empik\Marketplace\API;
use CURLFile;
class HttpCurlClient implements HttpClientInterface
{
public function __construct($config = [])
{
}
public function post($id, array $headers = [], array $body = [])
{
if (isset($body['file'])) {
$curlFile = new CURLFile($body['file']['filepath'], 'text/plain', $body['file']['filename']);
$body['file'] = $curlFile;
}
$ch = $this->create($id, $headers);
curl_setopt($ch, CURLOPT_POST,1);
if (isset($headers['Content-Type']) && $headers['Content-Type'] == 'application/json') {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
} else {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$response = $this->execute($ch);
curl_close($ch);
return $response;
}
public function put($id, array $headers = [], array $body = [])
{
$ch = $this->create($id, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
$response = $this->execute($ch);
curl_close($ch);
return $response;
}
public function get($id, array $headers = [], array $body = [])
{
$ch = $this->create($id, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = $this->execute($ch);
curl_close($ch);
return $response;
}
protected function create($id, $headers = [])
{
$ch = curl_init($id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($headers) {
$headersString = [];
foreach ($headers as $key => $value) {
$headersString[] = $key . ': ' . $value;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headersString);
}
return $ch;
}
protected function execute($ch)
{
$response = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// is 2xx http code
if ($httpCode < 200 || $httpCode >= 300) {
throw new \Exception('Request failed with HTTP code ' . $httpCode . '.');
}
if ($contentType === 'application/json') {
$response = json_decode($response, true);
}
return $response;
}
}

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;

View File

@@ -0,0 +1,64 @@
<?php
namespace Empik\Marketplace\Adapter;
use Configuration;
use Context;
use Shop;
class ConfigurationAdapter
{
const CONF_ENVIRONMENT = 'EMPIK_ENVIRONMENT';
const CONF_API_KEY = 'EMPIK_API_KEY';
const CONF_AUTH_STATUS = 'EMPIK_AUTH_STATUS';
const CONF_SYNC_OFFERS = 'EMPIK_SYNC_OFFERS';
const CONF_SYNC_LOGISTIC_CLASS = 'EMPIK_SYNC_LOGISTIC_CLASS';
const CONF_OFFER_IDENTIFIER = 'EMPIK_OFFER_IDENTIFIER';
const CONF_SKU_TYPE = 'EMPIK_SKU_TYPE';
const CONF_LEAD_TIME_TO_SHIP = 'EMPIK_LEAD_TIME_TO_SHIP';
const CONF_PRICE_RATIO = 'EMPIK_PRICE_RATIO';
const CONF_ADD_TO_PRICE = 'EMPIK_ADD_TO_PRICE';
const CONF_REDUCE_STOCK = 'EMPIK_REDUCE_STOCK';
const CONF_IMPORT_ORDERS = 'EMPIK_IMPORT_ORDERS';
const CONF_AUTO_ACCEPT_ORDERS = 'EMPIK_AUTO_ACCEPT_ORDERS';
const CONF_NEW_ORDER_STATE = 'EMPIK_NEW_ORDER_STATE';
const CONF_SHIPPED_ORDER_STATE = 'EMPIK_SHIPPED_ORDER_STATE';
const CONF_CARRIER_MAP = 'EMPIK_CARRIER_MAP';
const CONF_ID_EMPLOYEE = 'EMPIK_ID_EMPLOYEE';
const ENV_TEST = 'https://stg1.marketplace.empik.com';
const ENV_PROD = 'https://marketplace.empik.com';
/** @var Shop */
private $shopId;
public function __construct($shopId = null)
{
$this->shopId = $shopId ? $shopId : Context::getContext()->shop->id;
}
public function get($key, $langId = null, $shopGroupId = null, $shopId = null, $default = false)
{
if ($shopId === null) {
$shopId = $this->shopId;
}
return Configuration::get($key, $langId, $shopGroupId, $shopId, $default);
}
public function updateValue($key, $values, $html = false, $shopGroupId = null, $shopId = null)
{
if ($shopId === null) {
$shopId = $this->shopId;
}
return Configuration::updateValue($key, $values, $html, $shopGroupId, $shopId);
}
public function deleteByName($key)
{
return Configuration::deleteByName($key);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Empik\Marketplace\Adapter;
use Empik\Marketplace\PrestaShopContext;
use Context;
use Link;
class LinkAdapter
{
/** @var Link */
protected $link;
/** @var PrestaShopContext */
protected $prestaShopContext;
public function __construct(PrestaShopContext $prestaShopContext)
{
$this->prestaShopContext = $prestaShopContext;
$this->link = Context::getContext()->link;
}
/**
* @param string $controller
* @param array $params
* @return string
*/
public function getAdminLink($controller, $params = [])
{
if ($this->prestaShopContext->is17()) {
return $this->link->getAdminLink($controller, true, [], $params);
} else {
$paramsQuery = $params ? '&' . http_build_query($params) : '';
return $this->link->getAdminLink($controller, true) . $paramsQuery;
}
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace Empik\Marketplace\Adapter;
use PrestaShopLogger;
class LoggerAdapter
{
const LOG_SEVERITY_LEVEL_INFORMATIVE = 1;
const LOG_SEVERITY_LEVEL_WARNING = 2;
const LOG_SEVERITY_LEVEL_ERROR = 3;
const LOG_SEVERITY_LEVEL_MAJOR = 4;
/**
* @param string $message
* @param int $severity
* @return bool
*/
public function log($message, $severity = self::LOG_SEVERITY_LEVEL_INFORMATIVE)
{
return PrestaShopLogger::addLog($message, $severity);
}
/**
* @param string $message
* @return bool
*/
public function logInfo($message)
{
return $this->log($message, self::LOG_SEVERITY_LEVEL_INFORMATIVE);
}
/**
* @param string $message
* @return bool
*/
public function logWarning($message)
{
return $this->log($message, self::LOG_SEVERITY_LEVEL_WARNING);
}
/**
* @param string $message
* @return bool
*/
public function logError($message)
{
return $this->log($message, self::LOG_SEVERITY_LEVEL_ERROR);
}
/**
* @param string $message
* @return bool
*/
public function logMajor($message)
{
return $this->log($message, self::LOG_SEVERITY_LEVEL_MAJOR);
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Empik\Marketplace\Adapter;
use Tools;
use Context;
class ToolsAdapter
{
protected $context;
public function __construct()
{
$this->context = Context::getContext();
}
public function hash($value)
{
if ($this->is176()) {
return Tools::hash($value);
}
return Tools::encrypt($value);
}
public function is17()
{
return version_compare(_PS_VERSION_, '1.7.0', '>=');
}
public function is176()
{
return version_compare(_PS_VERSION_, '1.7.6', '>=');
}
public static function is17static()
{
return version_compare(_PS_VERSION_, '1.7.0', '>=');
}
public static function is176static()
{
return version_compare(_PS_VERSION_, '1.7.6', '>=');
}
}

View File

@@ -0,0 +1,110 @@
<?php
namespace Empik\Marketplace\Adapter;
use Context;
use Exception;
use Module;
use Tools;
use Translate;
class TranslateAdapter
{
/**
* Adapter for getting module translation for a specific locale on PS 1.6
*
* @param Module|string $module Module instance or name
* @param string $originalString string to translate
* @param string $source source of the original string
* @param string|null $iso locale or language ISO code
*
* @return string
*
* @throws Exception
*/
public function getModuleTranslation(
$module,
$originalString,
$source,
$iso = null
) {
if (version_compare(_PS_VERSION_, '1.7', '>=')) {
return Translate::getModuleTranslation($module, $originalString, $source, null, false, $iso);
} elseif ($iso === null) {
return Translate::getModuleTranslation($module, $originalString, $source);
}
static $translations;
static $langCache = [];
static $translationsMerged = [];
$name = $module instanceof Module ? $module->name : $module;
if (empty($iso)) {
$iso = Context::getContext()->language->iso_code;
}
if (!isset($translationsMerged[$name][$iso])) {
$filesByPriority = [
// PrestaShop 1.5 translations
_PS_MODULE_DIR_ . $name . '/translations/' . $iso . '.php',
// PrestaShop 1.4 translations
_PS_MODULE_DIR_ . $name . '/' . $iso . '.php',
// Translations in theme
_PS_THEME_DIR_ . 'modules/' . $name . '/translations/' . $iso . '.php',
_PS_THEME_DIR_ . 'modules/' . $name . '/' . $iso . '.php',
];
foreach ($filesByPriority as $file) {
if (file_exists($file)) {
$_MODULE = null;
include $file;
if (isset($_MODULE)) {
$translations[$iso] = isset($translations[$iso])
? array_merge($translations[$iso], $_MODULE)
: $_MODULE;
}
}
}
$translationsMerged[$name][$iso] = true;
}
$string = preg_replace("/\\\*'/", "\'", $originalString);
$key = md5($string);
$cacheKey = $name . '|' . $string . '|' . $source . '|' . $iso;
if (!isset($langCache[$cacheKey])) {
if (!isset($translations[$iso])) {
return str_replace('"', '&quot;', $string);
}
$currentKey = Tools::strtolower('<{' . $name . '}' . _THEME_NAME_ . '>' . $source) . '_' . $key;
$defaultKey = Tools::strtolower('<{' . $name . '}prestashop>' . $source) . '_' . $key;
if ('controller' == Tools::substr($source, -10, 10)) {
$file = Tools::substr($source, 0, -10);
$currentKeyFile = Tools::strtolower('<{' . $name . '}' . _THEME_NAME_ . '>' . $file) . '_' . $key;
$defaultKeyFile = Tools::strtolower('<{' . $name . '}prestashop>' . $file) . '_' . $key;
}
if (isset($currentKeyFile) && !empty($translations[$iso][$currentKeyFile])) {
$ret = Tools::stripslashes($translations[$iso][$currentKeyFile]);
} elseif (isset($defaultKeyFile) && !empty($translations[$iso][$defaultKeyFile])) {
$ret = Tools::stripslashes($translations[$iso][$defaultKeyFile]);
} elseif (!empty($translations[$iso][$currentKey])) {
$ret = Tools::stripslashes($translations[$iso][$currentKey]);
} elseif (!empty($translations[$iso][$defaultKey])) {
$ret = Tools::stripslashes($translations[$iso][$defaultKey]);
} else {
$ret = Tools::stripslashes($string);
}
$langCache[$cacheKey] = htmlspecialchars($ret, ENT_COMPAT, 'UTF-8');
}
return $langCache[$cacheKey];
}
}

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;

View File

@@ -0,0 +1,45 @@
<?php
namespace Empik\Marketplace\Cache;
use Configuration;
use Empik\Marketplace\Adapter\ConfigurationAdapter;
use PrestaShop\ModuleLibCacheDirectoryProvider\Cache\CacheDirectoryProvider;
class Cache
{
protected $cacheEnvironment;
protected $cacheNamespace;
protected $cacheDirectory;
public function __construct($cacheNamespace = 'empikmarketplace')
{
$this->cacheEnvironment = Configuration::get(ConfigurationAdapter::CONF_ENVIRONMENT);
$this->cacheNamespace = $cacheNamespace;
$this->cacheDirectory = new CacheDirectoryProvider(
_PS_VERSION_,
_PS_ROOT_DIR_,
_PS_MODE_DEV_
);
}
public function get($key, callable $callback, $ttl = 3600)
{
$cacheElem = sprintf('%s/%s_%s.tmp', rtrim($this->cacheDirectory->getPath(), '/'), $this->cacheNamespace, md5($key . $this->cacheEnvironment));
if (file_exists($cacheElem) && (time() - filemtime($cacheElem)) < $ttl) {
return unserialize(file_get_contents($cacheElem));
}
try {
$result = $callback();
} catch (\Exception $e) {
return false;
}
file_put_contents($cacheElem, serialize($result));
return $result;
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Empik\Marketplace\Cache;
use Module;
use PrestaShop\ModuleLibCacheDirectoryProvider\Cache\CacheDirectoryProvider;
class CacheClearer
{
const CONTAINERS = [
'admin',
'front',
];
protected $module;
protected $cacheDirectory;
public function __construct(Module $module)
{
$this->module = $module;
$this->cacheDirectory = new CacheDirectoryProvider(
_PS_VERSION_,
_PS_ROOT_DIR_,
false
);
}
public function clear()
{
foreach (self::CONTAINERS as $containerName) {
$containerFilePath = sprintf(
'%s/%s%sContainer.php',
rtrim($this->cacheDirectory->getPath(), '/'),
ucfirst($this->module->name),
ucfirst($containerName)
);
if (file_exists($containerFilePath)) {
unlink($containerFilePath);
}
}
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace Empik\Marketplace\Configuration;
use Empik\Marketplace\Adapter\ConfigurationAdapter;
class ExportConfiguration
{
const EXPORT_PRODUCT_FILENAME = 'PrestaShop_products.csv';
const EXPORT_OFFER_FILENAME = 'PrestaShop_offers.csv';
const EXPORT_DIR = '/modules/empikmarketplace/data/';
const EXPORT_PATH = _PS_ROOT_DIR_ . self::EXPORT_DIR;
const CSV_FIELD_SEPARATOR = ';';
const CSV_VALUE_SEPARATOR = '|';
const EXPORT_IMG_LIMIT = 10;
const EXPORT_NAME_MAX_LENGTH = 128;
const EXPORT_PRODUCTS_PER_PAGE = 10;
protected $configurationAdapter;
public function __construct(ConfigurationAdapter $configurationAdapter)
{
$this->configurationAdapter = $configurationAdapter;
}
public function getExportPath()
{
return self::EXPORT_PATH . self::EXPORT_PRODUCT_FILENAME;
}
public function getProductExportPath()
{
return self::EXPORT_PATH . self::EXPORT_PRODUCT_FILENAME;
}
public function getOfferExportPath()
{
return self::EXPORT_PATH . self::EXPORT_OFFER_FILENAME;
}
public function getCsvDelimiter()
{
return self::CSV_FIELD_SEPARATOR;
}
public function getProductIdType()
{
return $this->configurationAdapter->get('EMPIK_OFFER_IDENTIFIER');
}
public function getPriceRatio()
{
return (float)$this->configurationAdapter->get('EMPIK_PRICE_RATIO');
}
public function getAddToPrice()
{
return (float)$this->configurationAdapter->get('EMPIK_ADD_TO_PRICE');
}
public function getStockReduce()
{
return (float)$this->configurationAdapter->get('EMPIK_REDUCE_STOCK');
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace Empik\Marketplace\Configuration;
use Empik\Marketplace\Adapter\ConfigurationAdapter;
class ExportProductConfiguration
{
const EXPORT_PRODUCT_FILENAME = 'PrestaShop_products.csv';
const EXPORT_OFFER_FILENAME = 'PrestaShop_offers.csv';
const EXPORT_PATH = __DIR__ . '/../../data/';
const CSV_FIELD_SEPARATOR = ';';
const CSV_VALUE_SEPARATOR = '|';
protected $configurationAdapter;
public function __construct(ConfigurationAdapter $configurationAdapter)
{
$this->configurationAdapter = $configurationAdapter;
}
public function getExportPath()
{
return self::EXPORT_PATH . self::EXPORT_PRODUCT_FILENAME;
}
public function getProductExportPath()
{
return self::EXPORT_PATH . self::EXPORT_PRODUCT_FILENAME;
}
public function getOfferExportPath()
{
return self::EXPORT_PATH . self::EXPORT_OFFER_FILENAME;
}
public function getCsvDelimiter()
{
return self::CSV_FIELD_SEPARATOR;
}
public function getProductIdType()
{
return $this->configurationAdapter->get('EMPIK_OFFER_IDENTIFIER');
}
public function getPriceRatio()
{
return (float)$this->configurationAdapter->get('EMPIK_PRICE_RATIO');
}
public function getAddToPrice()
{
return (float)$this->configurationAdapter->get('EMPIK_ADD_TO_PRICE');
}
public function getStockReduce()
{
return (float)$this->configurationAdapter->get('EMPIK_REDUCE_STOCK');
}
}

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;

View File

@@ -0,0 +1,46 @@
<?php
namespace Empik\Marketplace\DataProvider;
use Db;
use DbQuery;
use Context;
use Empik\Marketplace\Utils\Utils;
class CarriersDataProvider
{
/**
* @var Db
*/
protected $db;
/**
* @var Context
*/
protected $context;
/**
* @var int
*/
protected $countryId;
public function __construct()
{
$this->db = Db::getInstance();
$this->context = Context::getContext();
$this->countryId = Utils::getCountryId();
}
public function getCarriers()
{
$sql = new DbQuery();
$sql->select('c.*');
$sql->from('carrier', 'c');
$sql->where('c.deleted = 0');
$result = $this->db->executeS($sql);
return $result;
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Empik\Marketplace\DataProvider;
use Context;
use Product;
class CombinationDataProvider
{
/** @var Context */
protected $context;
public function __construct()
{
$this->context = Context::getContext();
}
public function getCombinationsByProductId($id_product)
{
$product = new Product($id_product);
$combinations = $product->getAttributeCombinations($this->context->language->id);
$combinationsGrouped = [];
foreach ($combinations as $combination) {
if (!isset($combinationsGrouped[$combination['id_product_attribute']])) {
$combinationsGrouped[$combination['id_product_attribute']] = $combination;
}
$combinationsGrouped[$combination['id_product_attribute']]['attributes'][] = sprintf(
'%s: %s', $combination['group_name'], $combination['attribute_name']
);
$empikProduct = \EmpikProduct::getOrCreate($id_product, $combination['id_product_attribute']);
$combinationsGrouped[$combination['id_product_attribute']]['offer_price'] = $empikProduct->offer_price;
$combinationsGrouped[$combination['id_product_attribute']]['offer_price_reduced'] = $empikProduct->offer_price_reduced;
}
if (!empty($combinationsGrouped)) {
foreach ($combinationsGrouped as $idProductAttribute => $combination) {
$combinationsGrouped[$idProductAttribute]['attributes_list'] = implode(', ', $combination['attributes']);
}
}
return $combinationsGrouped;
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace Empik\Marketplace\DataProvider;
use Empik\Marketplace\Exception\InvalidArgumentException;
use Empik\Marketplace\Repository\ProductRepository;
use Empik\Marketplace\Utils\IdentifierExtractor;
class OffersDataProvider
{
const STATE_CODE_NEW = 1;
const STATE_CODE_USED = 11;
/** @var ProductRepository */
protected $productRepository;
/** @var IdentifierExtractor */
protected $identifierExtractor;
public function __construct(
ProductRepository $productRepository,
IdentifierExtractor $identifierExtractor
) {
$this->productRepository = $productRepository;
$this->identifierExtractor = $identifierExtractor;
}
public function getOffersDataByProductIds(array $ids, $updateDeleteMode = 'delete')
{
if (!in_array($updateDeleteMode, ['update', 'delete'])) {
throw new InvalidArgumentException(sprintf('Invalid mode "%s"', $updateDeleteMode));
}
$offers = [];
$products = $this->productRepository->getOffersByIds($ids);
foreach ($products as $product) {
$offers[] = [
'description' => $product['description'],
'internal_description' => $product['id_product'],
'price' => $product['price'],
'product_id' => $this->identifierExtractor->extract($product),
'product_id_type' => $this->identifierExtractor->getIdentifierType(),
'shop_sku' => $product['reference'],
'state_code' => self::STATE_CODE_NEW,
'update_delete' => $updateDeleteMode,
];
}
return $offers;
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace Empik\Marketplace\DataProvider;
use Db;
use DbQuery;
use Context;
class ProductDataProvider
{
/** @var Db */
protected $db;
/** @var int */
protected $shopId;
/** @var int */
protected $langId;
public function __construct()
{
$this->db = Db::getInstance();
$this->shopId = Context::getContext()->shop->id;
$this->langId = Context::getContext()->language->id;
}
public function getOneBy($params = [])
{
$sql = new DbQuery();
$sql->select('
p.id_product,
p.cache_default_attribute AS id_product_attribute,
p.price,
p.wholesale_price,
p.reference,
p.supplier_reference,
p.ean13,
# p.isbn,
# p.mpn,
p.upc,
p.unity,
p.width,
p.height,
p.depth,
p.weight,
p.condition,
p.additional_shipping_cost,
p.available_date,
p.minimal_quantity,
p.active,
pl.name,
pl.description,
pl.description_short,
pl.link_rewrite,
pl.meta_description,
pl.meta_keywords,
pl.meta_title,
pl.available_now,
pl.available_later,
# pl.delivery_in_stock,
# pl.delivery_out_stock,
sav.quantity,
sav.depends_on_stock,
m.name AS manufacturer_name');
$sql->from('product', 'p');
$sql->leftJoin(
'manufacturer',
'm',
'm.id_manufacturer = p.id_manufacturer'
);
$sql->leftJoin(
'product_lang',
'pl',
'pl.id_product = p.id_product AND
pl.id_lang = ' . (int)$this->langId . ' AND
pl.id_shop = ' . (int)$this->shopId
);
// stock
$sql->leftJoin(
'stock_available',
'sav',
'sav.id_product = p.id_product AND
sav.id_product_attribute = 0 AND
sav.id_shop = ' . (int)$this->shopId . ' AND
sav.id_shop_group = 0'
);
foreach ($params as $param => $value) {
$sql->where(pSQL($param) . ' = ' . '"'.pSQL($value).'"');
}
$result = $this->db->getRow($sql);
return $result;
}
}

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;

View File

@@ -0,0 +1,60 @@
<?php
class EmpikAction extends ObjectModel
{
const ACTION_OTHER = 'OTHER';
const ACTION_PRODUCT_EXPORT = 'PRODUCT_EXPORT';
const ACTION_OFFER_EXPORT = 'OFFER_EXPORT';
const ACTION_PRODUCT_EXPORT_INCLUDE = 'PRODUCT_EXPORT_INCLUDE';
const ACTION_PRODUCT_EXPORT_EXCLUDE = 'PRODUCT_EXPORT_EXCLUDE';
const STATUS_NEW = 'NEW';
const STATUS_COMPLETED = 'COMPLETE';
public $id_shop;
public $action = self::ACTION_OTHER;
public $status = self::STATUS_NEW;
public $id_import;
public $import_count;
public $date_start;
public $date_end;
public static $definition = [
'table' => 'empik_action',
'primary' => 'id_empik_action',
'fields' => [
'id_shop' => [
'type' => self::TYPE_INT,
'validate' => 'isUnsignedInt',
'required' => true,
],
'action' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'status' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'id_import' => [
'type' => self::TYPE_INT,
'validate' => 'isCleanHtml',
],
'import_count' => [
'type' => self::TYPE_INT,
'validate' => 'isCleanHtml',
],
'date_start' => [
'type' => self::TYPE_DATE,
'validate' => 'isDate',
'required' => true,
],
'date_end' => [
'type' => self::TYPE_DATE,
'validate' => 'isDate',
'required' => true,
],
],
];
}

View File

@@ -0,0 +1,30 @@
<?php
class EmpikActionLog extends ObjectModel
{
public $id_empik_action;
public $message;
public $date_add;
public static $definition = [
'table' => 'empik_action',
'primary' => 'id_empik_action_log',
'fields' => [
'id_empik_action' => [
'type' => self::TYPE_INT,
'validate' => 'isUnsignedInt',
'required' => true,
],
'message' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'date_add' => [
'type' => self::TYPE_DATE,
'validate' => 'isDate',
'required' => true,
],
],
];
}

View File

@@ -0,0 +1,87 @@
<?php
class EmpikOrder extends ObjectModel
{
public $id_order;
public $empik_order_reference;
public $empik_order_carrier;
public $empik_payment;
public $empik_carrier;
public $empik_pickup_point;
public $empik_vat_number;
public $date_add;
public static $definition = [
'table' => 'empik_orders',
'primary' => 'id_empik_order',
'fields' => [
'id_order' => [
'type' => self::TYPE_INT,
'validate' => 'isUnsignedInt',
'required' => true,
],
'empik_order_reference' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'empik_order_carrier' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'empik_payment' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
'required' => true,
],
'empik_carrier' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
'required' => true,
],
'empik_pickup_point' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'empik_vat_number' => [
'type' => self::TYPE_STRING,
'validate' => 'isCleanHtml',
],
'date_add' => [
'type' => self::TYPE_DATE,
'validate' => 'isDate',
'required' => false,
],
],
];
public static function getEmpikOrderByOrderId($orderId)
{
$query = (new DbQuery())
->select('eo.*')
->from('empik_orders', 'eo')
->where('eo.id_order = "'.pSQL($orderId).'"');
return Db::getInstance()->getRow($query);
}
public static function getEmpikOrderReferenceByOrderId($orderId)
{
$query = (new DbQuery())
->select('eo.empik_order_reference')
->from('empik_orders', 'eo')
->where('eo.id_order = "'.pSQL($orderId).'"');
return Db::getInstance()->getValue($query);
}
public static function getOrderIdByEmpikOrderReference($empikOrderReference)
{
$query = (new DbQuery())
->select('eo.id_order')
->from('empik_orders', 'eo')
->where('eo.empik_order_reference = "'.pSQL($empikOrderReference).'"');
return Db::getInstance()->getValue($query);
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace Empik\Marketplace\Exception;
use Exception;
class InvalidActionException extends Exception
{
}

View File

@@ -0,0 +1,10 @@
<?php
namespace Empik\Marketplace\Exception;
use Exception;
class InvalidArgumentException extends Exception
{
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Empik\Marketplace\Exception;
use Exception;
class LogicException extends Exception
{
}

View File

@@ -0,0 +1,10 @@
<?php
namespace Empik\Marketplace\Exception;
use Exception;
class OrderProcessException extends Exception
{
}

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;

View File

@@ -0,0 +1,26 @@
<?php
namespace Empik\Marketplace\Factory;
use Empik\Marketplace\Adapter\ConfigurationAdapter;
use Empik\Marketplace\API\EmpikClient;
class EmpikClientFactory
{
/** @var ConfigurationAdapter */
protected $configurationAdapter;
public function __construct(ConfigurationAdapter $configurationAdapter)
{
$this->configurationAdapter = $configurationAdapter;
}
public function createClient()
{
$apiUrl = $this->configurationAdapter->get(ConfigurationAdapter::CONF_ENVIRONMENT);
$apiKey = $this->configurationAdapter->get(ConfigurationAdapter::CONF_API_KEY);
return new EmpikClient($apiUrl, $apiKey);
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Empik\Marketplace\Factory;
use Empik\Marketplace\API\HttpClientInterface;
use Empik\Marketplace\API\HttpCurlClient;
class EmpikCurlHttpClientFactory implements HttpClientFactoryInterface
{
/**
* @param $apiUrl
* @return HttpClientInterface
*/
public function createClient($apiUrl)
{
return new HttpCurlClient(['base_url' => $apiUrl]);
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Empik\Marketplace\Factory;
use GuzzleHttp\Client;
class EmpikGuzzleHttpClientFactory implements HttpClientFactoryInterface
{
public function createClient($apiUrl)
{
return new Client(['base_url' => $apiUrl]);
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace Empik\Marketplace\Factory;
use GuzzleHttp\Client;
interface HttpClientFactoryInterface
{
/**
* @param string $apiUrl
* @return Client
*/
public function createClient($apiUrl);
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Empik\Marketplace\Factory;
use Empik\Marketplace\API\HttpClientInterface;
use Empik\Marketplace\API\HttpCurlClient;
use Exception;
class HttpClientsFactory
{
/**
* @param null $handler
* @return HttpClientInterface
* @throws Exception
*/
public static function createHttpClient($handler = null)
{
return self::detectDefaultClient();
}
/**
* @return HttpClientInterface
* @throws Exception
*/
private static function detectDefaultClient()
{
if (function_exists('curl_version')) {
return new HttpCurlClient();
}
throw new Exception('Unable to detect default HTTP client.');
}
}

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;

View File

@@ -0,0 +1,19 @@
<?php
namespace Empik\Marketplace\Formatter;
use Empik\Marketplace\Configuration\ExportConfiguration;
use Tools;
class ProductNameFormatter
{
/**
* @param string $name
* @param int|bool $length
* @return string
*/
public function format($name, $length = false)
{
return (string)Tools::substr($name, 0, $length ? $length : ExportConfiguration::EXPORT_NAME_MAX_LENGTH);
}
}

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;

View File

@@ -0,0 +1,107 @@
<?php
namespace Empik\Marketplace\Handler;
use Context;
use EmpikMarketplace;
use Empik\Marketplace\Adapter\ToolsAdapter;
use Empik\Marketplace\Processor\OrderProcessor;
use Empik\Marketplace\Processor\ExportProductProcessor;
use Empik\Marketplace\Processor\ExportOfferProcessor;
use Empik\Marketplace\Exception\InvalidActionException;
class CronJobsHandler
{
const ACTION_EXPORT_PRODUCTS = 'exportProducts';
const ACTION_EXPORT_OFFERS = 'exportOffers';
const ACTION_IMPORT_ORDERS = 'importOrders';
const ACTIONS = [
self::ACTION_EXPORT_PRODUCTS,
self::ACTION_EXPORT_OFFERS,
self::ACTION_IMPORT_ORDERS,
];
/** @var Context */
protected $context;
/** @var EmpikMarketplace */
protected $module;
/** @var ToolsAdapter */
protected $tools;
/** @var ExportProductProcessor */
protected $exportProductProcessor;
/** @var ExportOfferProcessor */
protected $exportOfferProcessor;
/** @var OrderProcessor */
protected $orderProcessor;
public function __construct(
EmpikMarketplace $module,
ToolsAdapter $tools,
ExportProductProcessor $exportProductProcessor,
ExportOfferProcessor $exportOfferProcessor,
OrderProcessor $orderProcessor
) {
$this->module = $module;
$this->tools = $tools;
$this->exportProductProcessor = $exportProductProcessor;
$this->exportOfferProcessor = $exportOfferProcessor;
$this->orderProcessor = $orderProcessor;
$this->context = Context::getContext();
}
public function handle($action)
{
set_time_limit(0);
switch ($action) {
case self::ACTION_EXPORT_PRODUCTS:
$this->exportProductProcessor->process();
break;
case self::ACTION_EXPORT_OFFERS:
$this->exportOfferProcessor->process();
break;
case self::ACTION_IMPORT_ORDERS:
$this->orderProcessor->process();
break;
default:
throw new InvalidActionException();
}
}
public function getAvailableActionsUrls()
{
$urls = [];
foreach (self::ACTIONS as $action) {
$urls[$action] = $this->getActionUrl($action);
}
return $urls;
}
public function checkToken($token)
{
return $token === $this->getToken();
}
protected function getActionUrl($action)
{
return $this->context->link->getModuleLink($this->module->name, 'cron', [
'action' => $action,
'token' => $this->getToken(),
]);
}
protected function getToken()
{
return $this->tools->hash($this->module->name . '_cron');
}
}

View File

@@ -0,0 +1,189 @@
<?php
namespace Empik\Marketplace\Handler;
use Context;
use Empik\Marketplace\Adapter\ConfigurationAdapter;
use Empik\Marketplace\Manager\CsvManager;
use Empik\Marketplace\Utils\SkuExtractor;
use Product;
use EmpikMarketplace;
use Empik\Marketplace\Configuration\ExportConfiguration;
use Empik\Marketplace\Repository\CategoryRepository;
use Empik\Marketplace\Repository\FeatureRepository;
use Empik\Marketplace\Repository\ImageRepository;
use Empik\Marketplace\Repository\ProductRepository;
use Empik\Marketplace\Repository\TaxRepository;
use Empik\Marketplace\Utils\CategoryPathBuilder;
use Empik\Marketplace\Utils\IdentifierExtractor;
use Empik\Marketplace\Formatter\ProductNameFormatter;
use Empik\Marketplace\Utils\OfferPriceCalculator;
use Empik\Marketplace\Utils\OfferQuantityCalculator;
class ExportOfferHandler
{
const STATE_CODE_NEW = 1;
const STATE_CODE_USED = 11;
/** @var EmpikMarketplace */
protected $module;
/** @var Context */
protected $context;
/** @var ExportConfiguration */
protected $exportConfig;
/** @var ProductRepository */
protected $productRepository;
/** @var FeatureRepository */
protected $featureRepository;
/** @var TaxRepository */
protected $taxRepository;
/** @var CategoryRepository */
protected $categoryRepository;
/** @var ImageRepository */
protected $imageRepository;
/** @var ProductNameFormatter */
protected $productNameFormatter;
/** @var CategoryPathBuilder */
protected $categoryPathBuilder;
/** @var IdentifierExtractor */
protected $identifierExtractor;
/** @var SkuExtractor */
protected $skuExtractor;
/** @var OfferPriceCalculator */
protected $offerPriceCalculator;
/** @var OfferQuantityCalculator */
protected $offerQuantityCalculator;
/** @var CsvManager */
protected $csvManager;
public function __construct(
EmpikMarketplace $module,
ExportConfiguration $exportConfig,
ProductRepository $productRepository,
FeatureRepository $featureRepository,
TaxRepository $taxRepository,
CategoryRepository $categoryRepository,
ImageRepository $imageRepository,
ProductNameFormatter $productNameFormatter,
CategoryPathBuilder $categoryPathBuilder,
IdentifierExtractor $identifierExtractor,
SkuExtractor $skuExtractor,
OfferPriceCalculator $offerPriceCalculator,
OfferQuantityCalculator $offerQuantityCalculator
) {
$this->module = $module;
$this->exportConfig = $exportConfig;
$this->productRepository = $productRepository;
$this->featureRepository = $featureRepository;
$this->taxRepository = $taxRepository;
$this->categoryRepository = $categoryRepository;
$this->imageRepository = $imageRepository;
$this->productNameFormatter = $productNameFormatter;
$this->categoryPathBuilder = $categoryPathBuilder;
$this->identifierExtractor = $identifierExtractor;
$this->skuExtractor = $skuExtractor;
$this->offerPriceCalculator = $offerPriceCalculator;
$this->offerQuantityCalculator = $offerQuantityCalculator;
$this->csvManager = new CsvManager(
$this->exportConfig->getOfferExportPath(),
ExportConfiguration::CSV_FIELD_SEPARATOR
);
$this->context = Context::getContext();
}
public function isLastPage($page)
{
$total = $this->productRepository->getProductsTotal(ProductRepository::SRC_OFFER);
return $page * ExportConfiguration::EXPORT_PRODUCTS_PER_PAGE > $total;
}
public function handle($page = null)
{
if (!$page && file_exists($this->exportConfig->getOfferExportPath())) {
$this->csvManager->remove();
}
$localPage = $page === null ? 0 : $page;
$leadTimeToShip = \Configuration::get(ConfigurationAdapter::CONF_LEAD_TIME_TO_SHIP);
$syncLogisticClass = \Configuration::get(ConfigurationAdapter::CONF_SYNC_LOGISTIC_CLASS);
do {
$products = $this->productRepository->getProductsPaginate(
$localPage,
ExportConfiguration::EXPORT_PRODUCTS_PER_PAGE,
ProductRepository::SRC_OFFER
);
foreach ($products as $i => $product) {
$offer = [];
$priceWithReduction = Product::getPriceStatic($product['id_product'], true, $product['id_product_attribute'], 2);
$priceWithoutReduction = Product::getPriceStatic($product['id_product'], true, $product['id_product_attribute'], 2, null, false, false);
$calculatedPriceWithReduction = $this->offerPriceCalculator->calculate($priceWithReduction);
$calculatedPriceWithoutReduction = $this->offerPriceCalculator->calculate($priceWithoutReduction);
$hasReduction = $calculatedPriceWithoutReduction > $calculatedPriceWithReduction;
$quantity = \StockAvailable::getQuantityAvailableByProduct($product['id_product'], $product['id_product_attribute']);
$calculatedQuantity = $this->offerQuantityCalculator->calculate($quantity);
$offer['product-id-type'] = $this->identifierExtractor->getIdentifierType();
$offer['product-id'] = $this->identifierExtractor->extract($product);
$offer['sku'] = $this->skuExtractor->extract($product);
$offer['state'] = !empty($product['empik_condition']) ? $product['empik_condition'] : self::STATE_CODE_NEW;
if ($product['offer_price'] > 0) {
$offer['price'] = $product['offer_price'];
} else {
$offer['price'] = $calculatedPriceWithoutReduction;
}
if ((int)$product['export_original_price'] > 0) {
if ($product['offer_price_reduced'] > 0) {
$offer['discount-price'] = $product['offer_price_reduced'];
} else {
$offer['discount-price'] = $hasReduction ? $calculatedPriceWithReduction : null;
}
} else {
$offer['discount-price'] = '';
}
$offer['quantity'] = $calculatedQuantity;
if ($leadTimeToShip && $leadTimeToShip >= 0) {
$offer['leadtime-to-ship'] = $leadTimeToShip;
}
if ($syncLogisticClass) {
$offer['logistic-class'] = $product['logistic_class'];
}
// add csv header
if ($i === 0 && ($page === 0 || $page === null && $localPage === 0)) {
$this->csvManager->addRow(array_keys($offer));
}
$this->csvManager->addRow($offer);
}
$localPage++;
} while ($products && $page === null);
}
}

View File

@@ -0,0 +1,259 @@
<?php
namespace Empik\Marketplace\Handler;
use Empik\Marketplace\Manager\CsvManager;
use Tools;
use Context;
use Product;
use StockAvailable;
use EmpikMarketplace;
use Empik\Marketplace\Configuration\ExportConfiguration;
use Empik\Marketplace\Repository\CategoryRepository;
use Empik\Marketplace\Repository\FeatureRepository;
use Empik\Marketplace\Repository\AttributeRepository;
use Empik\Marketplace\Repository\ImageRepository;
use Empik\Marketplace\Repository\ProductRepository;
use Empik\Marketplace\Repository\TaxRepository;
use Empik\Marketplace\Utils\CategoryPathBuilder;
use Empik\Marketplace\Utils\IdentifierExtractor;
use Empik\Marketplace\Formatter\ProductNameFormatter;
class ExportProductHandler
{
/** @var EmpikMarketplace */
protected $module;
/** @var Context */
protected $context;
/** @var ExportConfiguration */
protected $exportConfig;
/** @var ProductRepository */
protected $productRepository;
/** @var FeatureRepository */
protected $featureRepository;
/** @var AttributeRepository */
protected $attributeRepository;
/** @var TaxRepository */
protected $taxRepository;
/** @var CategoryRepository */
protected $categoryRepository;
/** @var ImageRepository */
protected $imageRepository;
/** @var ProductNameFormatter */
protected $productNameFormatter;
/** @var CategoryPathBuilder */
protected $categoryPathBuilder;
/** @var IdentifierExtractor */
protected $identifierExtractor;
/** @var CsvManager */
protected $csvManager;
public function __construct(
EmpikMarketplace $module,
ExportConfiguration $exportConfig,
ProductRepository $productRepository,
FeatureRepository $featureRepository,
AttributeRepository $attributeRepository,
TaxRepository $taxRepository,
CategoryRepository $categoryRepository,
ImageRepository $imageRepository,
ProductNameFormatter $productNameFormatter,
CategoryPathBuilder $categoryPathBuilder,
IdentifierExtractor $identifierExtractor
) {
$this->module = $module;
$this->exportConfig = $exportConfig;
$this->productRepository = $productRepository;
$this->featureRepository = $featureRepository;
$this->attributeRepository = $attributeRepository;
$this->taxRepository = $taxRepository;
$this->categoryRepository = $categoryRepository;
$this->imageRepository = $imageRepository;
$this->productNameFormatter = $productNameFormatter;
$this->categoryPathBuilder = $categoryPathBuilder;
$this->identifierExtractor = $identifierExtractor;
$this->csvManager = new CsvManager(
$this->exportConfig->getProductExportPath(),
ExportConfiguration::CSV_FIELD_SEPARATOR
);
$this->context = Context::getContext();
}
public function isLastPage($page)
{
$total = $this->productRepository->getProductsTotal(ProductRepository::SRC_PRODUCT);
return $page * ExportConfiguration::EXPORT_PRODUCTS_PER_PAGE > $total;
}
public function handle($page = null)
{
if (!$page && file_exists($this->exportConfig->getProductExportPath())) {
$this->csvManager->remove();
}
$localPage = $page === null ? 0 : $page;
do {
$products = $this->productRepository->getProductsPaginate(
$localPage,
ExportConfiguration::EXPORT_PRODUCTS_PER_PAGE,
ProductRepository::SRC_PRODUCT
);
foreach ($products as $i => $product) {
$product = $this->addName($product);
$product = $this->addPrices($product);
$product = $this->addQuantity($product);
$product = $this->addTax($product);
$product = $this->addCategories($product);
$product = $this->addFeatures($product);
$product = $this->addAttributes($product);
$product = $this->addImages($product);
// add csv header
if ($i === 0 && ($page === 0 || $page === null && $localPage === 0)) {
$this->csvManager->addRow(array_keys($product));
}
$this->csvManager->addRow($product);
}
$localPage++;
} while ($products && $page === null);
}
/**
* @param array $product
* @return array
*/
protected function addName($product)
{
$product['name'] = $this->productNameFormatter->format($product['name']);
return $product;
}
/**
* @param array $product
* @return array
*/
protected function addFeatures($product)
{
$features = $this->featureRepository->getFeatures($product['id_product']);
foreach ($features as $feature) {
$product[sprintf('feature[%s]', $feature['feature_name'])] = $feature['value'];
}
return $product;
}
/**
* @param array $product
* @return array
*/
protected function addAttributes($product)
{
$features = $this->attributeRepository->getAttributes($product['id_product'], $product['id_product_attribute']);
foreach ($features as $feature) {
$product[sprintf('attribute[%s]', $feature['name'])] = $feature['value'];
}
return $product;
}
/**
* @param array $product
* @return array
*/
protected function addPrices($product)
{
$product['price'] = Product::getPriceStatic($product['id_product'], true, $product['id_product_attribute'], 2);
$product['price_without_reduction'] = Product::getPriceStatic($product['id_product'], true, $product['id_product_attribute'], 2, null, false, false);
$product['reduction'] = Product::getPriceStatic($product['id_product'], true, $product['id_product_attribute'], 2, null, true);
return $product;
}
/**
* @param array $product
* @return array
*/
protected function addQuantity($product)
{
$quantity = StockAvailable::getQuantityAvailableByProduct(
$product['id_product'],
$product['id_product_attribute']
);
$product['quantity'] = (int)$quantity;
return $product;
}
/**
* @param array $product
* @return array
*/
protected function addTax($product)
{
$product['vat'] = $this->taxRepository->getTaxRateByProductId($product['id_product']);
return $product;
}
/**
* @param array $product
* @return array
*/
protected function addCategories($product)
{
$categories = $this->categoryRepository->getCategoriesByProductId($product['id_product']);
$path = $this->categoryPathBuilder->buildPath($categories);
$product['category'] = $path;
return $product;
}
/**
* @param array $product
* @return array
*/
protected function addImages($product)
{
$images = $this->imageRepository->getImages($product['id_product'], $product['id_product_attribute']);
for ($i = 0; $i < ExportConfiguration::EXPORT_IMG_LIMIT; $i++) {
$imageUrl = null;
if (isset($images[$i])) {
$imageUrl = $this->context->link->getImageLink(
Tools::link_rewrite($product['link_rewrite'] ? $product['link_rewrite'] : $product['name']),
$images[$i]['id_image']
);
}
$product[sprintf('image_%d', $i + 1)] = isset($imageUrl) ? $imageUrl : null;
}
return $product;
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Empik\Marketplace\Handler;
use Exception;
use Empik\Marketplace\API\EmpikClient;
use Empik\Marketplace\DataProvider\OffersDataProvider;
use Empik\Marketplace\Factory\EmpikClientFactory;
use Empik\Marketplace\Repository\ProductRepository;
use Empik\Marketplace\Traits\ErrorsTrait;
class UpdateDeleteOfferHandler
{
use ErrorsTrait;
/** @var EmpikClientFactory */
protected $empikClientFactory;
/** @var ProductRepository */
protected $productRepository;
/** @var OffersDataProvider */
protected $offersDataProvider;
/** @var EmpikClient */
protected $empikClient;
public function __construct(
EmpikClientFactory $empikClientFactory,
ProductRepository $productRepository,
OffersDataProvider $offersDataProvider
) {
$this->empikClientFactory = $empikClientFactory;
$this->productRepository = $productRepository;
$this->offersDataProvider = $offersDataProvider;
$this->empikClient = $this->empikClientFactory->createClient();
}
public function handle(array $ids)
{
try {
$offersData = $this->offersDataProvider->getOffersDataByProductIds($ids);
$this->empikClient->postOffers($offersData);
return true;
} catch (Exception $e) {
$this->addError($e->getMessage());
}
return false;
}
}

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;

View File

@@ -0,0 +1,258 @@
<?php
namespace Empik\Marketplace\Hook;
use Carrier;
use Configuration;
use Context;
use Module;
use Order;
use Product;
use OrderHistory;
use EmpikOrder;
use EmpikMarketplace;
use Empik\Marketplace\Adapter\LoggerAdapter;
use Empik\Marketplace\Adapter\ConfigurationAdapter;
use Empik\Marketplace\Factory\EmpikClientFactory;
use Empik\Marketplace\Handler\UpdateDeleteOfferHandler;
use Empik\Marketplace\Manager\CarrierMapManager;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\DataColumn;
use PrestaShop\PrestaShop\Core\Grid\Definition\GridDefinitionInterface;
use PrestaShop\PrestaShop\Core\Grid\Filter\Filter;
use PrestaShop\PrestaShop\Core\Search\Filters\OrderFilters;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Doctrine\ORM\QueryBuilder;
use Exception;
class HookAction
{
/** @var EmpikMarketplace */
protected $module;
/** @var Context */
protected $context;
/** @var CarrierMapManager */
protected $carrierMapManager;
public function __construct(CarrierMapManager $carrierMapManager)
{
$this->carrierMapManager = $carrierMapManager;
$this->module = Module::getInstanceByName('empikmarketplace');
$this->context = Context::getContext();
}
public function hookActionOrderGridDefinitionModifier(array $params)
{
/** @var GridDefinitionInterface $definition */
$definition = $params['definition'];
$definition
->getColumns()
->addAfter(
'reference',
(new DataColumn('empik_order_reference'))
->setName('Empik')
->setOptions(
[
'field' => 'empik_order_reference',
]
)
);
$definition->getFilters()->add(
(new Filter('empik_order_reference', TextType::class))
->setTypeOptions([
'required' => false,
])
->setAssociatedColumn('empik_order_reference')
);
}
public function hookActionOrderGridQueryBuilderModifier(array $params)
{
/** @var QueryBuilder[] $queryBuilders */
$queryBuilders = [
'search' => $params['search_query_builder'],
'count' => $params['count_query_builder'],
];
/** @var OrderFilters $searchCriteria */
$searchCriteria = $params['search_criteria'];
$filters = $searchCriteria->getFilters();
foreach ($queryBuilders as $queryBuilder) {
if (isset($filters['empik_order_reference'])) {
$queryBuilder
->andWhere('empik.empik_order_reference = :empik_order_reference')
->setParameter('empik_order_reference', $filters['empik_order_reference']);
}
}
foreach ($queryBuilders as $queryBuilder) {
$queryBuilder
->addSelect(
'empik.empik_order_reference'
)
->leftJoin(
'o',
_DB_PREFIX_.'empik_orders',
'empik',
'empik.id_order = o.id_order'
)
;
}
/** @var QueryBuilder $searchQueryBuilder */
$searchQueryBuilder = $params['search_query_builder'];
if ('empik_order_reference' === $searchCriteria->getOrderBy()) {
$searchQueryBuilder->orderBy('empik.empik_order_reference', $searchCriteria->getOrderWay());
}
}
public function hookActionOrderHistoryAddAfter(array $params)
{
/** @var OrderHistory $orderHistory */
$orderHistory = $params['order_history'];
$empikOrderId = EmpikOrder::getEmpikOrderReferenceByOrderId($orderHistory->id_order);
if (!$empikOrderId) {
return;
}
if ($orderHistory->id_order_state == Configuration::get(ConfigurationAdapter::CONF_SHIPPED_ORDER_STATE)) {
/** @var LoggerAdapter $logger */
$logger = $this->module->getService('empik.marketplace.adapter.loggerAdapter');
/** @var EmpikClientFactory $empikClientFactory */
$empikClientFactory = $this->module->getService('empik.marketplace.factory.empikClientFactory');
$empikClient = $empikClientFactory->createClient();
try {
$empikClient->putOrderShip($empikOrderId);
} catch (Exception $e) {
$logger->logError($e->getMessage());
}
}
}
public function hookActionAdminOrdersListingFieldsModifier($params)
{
if (isset($params['select'])) {
if (strpos('a.reference', $params['select']) === false) {
$params['select'] .= ',a.reference';
}
$params['select'] .= ',eo.empik_order_reference';
$params['join'] .= ' LEFT JOIN `'._DB_PREFIX_.'empik_orders` eo ON (eo.`id_order` = a.`id_order`)';
}
$params['fields']['empik_order_reference'] = [
'title' => $this->module->l('Empik'),
'align' => 'center',
];
}
public function hookDisplayAdminOrder($params)
{
$empikOrder = EmpikOrder::getEmpikOrderByOrderId($params['id_order']);
if (!$empikOrder) {
return null;
}
$this->context->smarty->assign(
[
'empik_order' => $empikOrder,
]
);
return $this->context->smarty->fetch(
$this->module->getLocalPath().'/views/templates/admin/hook/admin_order.tpl'
);
}
public function hookActionAdminOrdersTrackingNumberUpdate(array $params)
{
/** @var Order $order */
$order = $params['order'];
/** @var Carrier $carrier */
$carrier = $params['carrier'];
$trackingNumber = isset($_POST['update_order_shipping']['tracking_number'])
? $_POST['update_order_shipping']['tracking_number']
: $order->shipping_number
;
if ($trackingNumber) {
$empikOrder = EmpikOrder::getEmpikOrderByOrderId($order->id);
if (!$empikOrder) {
return;
}
/** @var EmpikClientFactory $empikClientFactory */
$empikClientFactory = $this->module->getService('empik.marketplace.factory.empikClientFactory');
$empikClient = $empikClientFactory->createClient();
/** @var LoggerAdapter $logger */
$logger = $this->module->getService('empik.marketplace.adapter.loggerAdapter');
$carrierName = null;
$carrierUrl = null;
$carrierCode = $this->carrierMapManager->getTypeByCode($empikOrder['empik_order_carrier']);
if (!$carrierCode) {
$carrierName = $carrier->name;
$carrierUrl = str_replace('@', $trackingNumber, $carrier->url);
}
try {
$empikClient->putOrderTracking(
$empikOrder['empik_order_reference'],
$carrierCode,
$carrierName,
$carrierUrl,
$trackingNumber
);
} catch (Exception $e) {
$logger->logError($e->getMessage());
}
}
}
public function hookActionObjectProductDeleteBefore($params)
{
/** @var Product $product */
$product = $params['object'];
if (!$this->module->getAuthStatus()) {
return;
}
/** @var UpdateDeleteOfferHandler $handler */
$handler = $this->module->getService('empik.marketplace.handler.updateDeleteOfferHandler');
/** @var LoggerAdapter $logger */
$logger = $this->module->getService('empik.marketplace.adapter.loggerAdapter');
if (!$handler->handle([$product->id])) {
foreach ($handler->getErrors() as $error) {
$logger->logError($error);
}
}
}
public function hookActionAdminControllerSetMedia($params)
{
$this->context->controller->addCSS($this->module->getPathUri() . '/views/css/admin/empik.css');
}
}

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;

View File

@@ -0,0 +1,141 @@
<?php
namespace Empik\Marketplace\Install;
use Empik\Marketplace\Adapter\ConfigurationAdapter;
use Empik\Marketplace\PrestaShopContext;
use EmpikMarketplace;
use Exception;
use Configuration;
use Language;
use Context;
use Module;
use Tab;
use Db;
class Installer
{
/** @var Db */
protected $db;
/** @var EmpikMarketplace */
protected $module;
/** @var PrestaShopContext */
protected $prestaShopContext;
/** @var array */
protected $errors = [];
public function __construct(PrestaShopContext $prestaShopContext)
{
$this->prestaShopContext = $prestaShopContext;
$this->db = Db::getInstance();
$this->module = Module::getInstanceByName('empikmarketplace');
}
public function install()
{
$result = true;
$result &= $this->createTabs();
$result &= $this->crateTables();
$result &= $this->registerHooks();
$result &= $this->createConfig();
return (bool)$result;
}
public function createTabs()
{
$result = true;
foreach ($this->module->getAdminTabs() as $tab) {
$result &= $this->installTab(
$tab['className'],
$tab['parent'],
$tab['name'],
$tab['module'],
$tab['active'],
$tab['icon']
);
}
return $result;
}
public function crateTables()
{
try {
include __DIR__ . '/Sql/install.php';
} catch (Exception $e) {
$this->errors[] = $this->module->l('Failed to install database tables');
return false;
}
return true;
}
public function registerHooks()
{
$module = $this->module;
$hooksCommon = $module::HOOK_LIST_COMMON;
$hooks17 = $module::HOOK_LIST_17;
$hooks16 = $module::HOOK_LIST_16;
if ($this->prestaShopContext->is177()) {
$hooks = array_merge($hooksCommon, $hooks17);
} else {
$hooks = array_merge($hooksCommon, $hooks16);
}
return $this->module->registerHook(
$hooks
);
}
public function createConfig()
{
$result = true;
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_LEAD_TIME_TO_SHIP, -1);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_PRICE_RATIO, 1);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_ADD_TO_PRICE, 0);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_SYNC_LOGISTIC_CLASS, 0);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_REDUCE_STOCK, 0);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_OFFER_IDENTIFIER, 'EAN');
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_SKU_TYPE, 'REFERENCE');
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_ID_EMPLOYEE, (int)Context::getContext()->employee->id);
$result &= Configuration::updateValue(ConfigurationAdapter::CONF_ENVIRONMENT, ConfigurationAdapter::ENV_TEST);
return $result;
}
protected function installTab($className, $parent, $name, $module, $active, $icon)
{
if (Tab::getIdFromClassName($className)) {
return true;
}
$parentId = is_int($parent) ? $parent : Tab::getIdFromClassName($parent);
$moduleTab = new Tab();
$moduleTab->class_name = $className;
$moduleTab->id_parent = $parentId;
$moduleTab->module = $module;
$moduleTab->active = $active;
if (property_exists($moduleTab, 'icon')) {
$moduleTab->icon = $icon;
}
$languages = Language::getLanguages(true);
foreach ($languages as $language) {
$moduleTab->name[$language['id_lang']] = $name;
}
return (bool)$moduleTab->add();
}
}

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;

View File

@@ -0,0 +1,57 @@
<?php
$sql = [];
$sql[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'empik_action` (
`id_empik_action` INT(11) NOT NULL AUTO_INCREMENT,
`id_shop` INT(11) NOT NULL,
`action` VARCHAR(32) NOT NULL,
`status` VARCHAR(32) NOT NULL,
`id_import` INT(11),
`import_count` INT(11),
`date_start` DATETIME NOT NULL,
`date_end` DATETIME NOT NULL,
INDEX (`id_shop`),
PRIMARY KEY (`id_empik_action`)
)';
$sql[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'empik_action_log` (
`id_empik_action_log` INT(11) NOT NULL,
`message` TEXT NOT NULL,
`date_add` DATETIME NOT NULL,
INDEX (`id_empik_action_log`)
)';
$sql[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'empik_orders` (
`id_empik_order` INT(11) NOT NULL AUTO_INCREMENT,
`id_order` INT(11) NOT NULL,
`empik_order_reference` VARCHAR(32) NOT NULL,
`empik_order_carrier` VARCHAR(255) NOT NULL,
`empik_payment` VARCHAR(255) NOT NULL,
`empik_carrier` VARCHAR(255) NOT NULL,
`empik_pickup_point` VARCHAR(255) NOT NULL,
`empik_vat_number` VARCHAR(255) NOT NULL,
`date_add` DATETIME NOT NULL,
INDEX (`empik_order_reference`),
INDEX (`id_order`),
PRIMARY KEY (`id_empik_order`)
)';
$sql[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'empik_product` (
`id_empik_product` INT(11) NOT NULL AUTO_INCREMENT,
`id_product` INT(11) NOT NULL,
`id_product_attribute` INT(11) NOT NULL,
`logistic_class` INT(4) NOT NULL DEFAULT 2,
`product_export` INT(1) NOT NULL DEFAULT 0,
`offer_export` INT(1) NOT NULL DEFAULT 0,
`offer_price` DECIMAL(20, 2) NOT NULL DEFAULT 0,
`offer_price_reduced` DECIMAL(20, 2) NOT NULL DEFAULT 0,
UNIQUE (`id_product`, `id_product_attribute`),
PRIMARY KEY (`id_empik_product`)
)';
foreach ($sql as $query) {
if (Db::getInstance()->execute($query) == false) {
return false;
}
}
return true;

View File

@@ -0,0 +1,16 @@
<?php
$sql = [];
$sql[] = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'empik_action`;';
$sql[] = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'empik_action_log`;';
$sql[] = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'empik_orders`;';
$sql[] = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'empik_product`;';
foreach ($sql as $query) {
if (Db::getInstance()->execute($query) == false) {
return false;
}
}
return true;

View File

@@ -0,0 +1,95 @@
<?php
namespace Empik\Marketplace\Install;
use Empik\Marketplace\Adapter\ConfigurationAdapter;
use EmpikMarketplace;
use Exception;
use Configuration;
use Tab;
use Db;
class Uninstaller
{
/** @var Db */
protected $db;
/** @var EmpikMarketplace */
protected $module;
/** @var array */
protected $errors = [];
public function __construct()
{
$this->db = \Db::getInstance();
$this->module = \Module::getInstanceByName('empikmarketplace');
}
public function uninstall()
{
$result = true;
$result &= $this->dropTabs();
$result &= $this->dropTables();
$result &= $this->dropConfig();
return $result;
}
public function dropTabs()
{
$result = true;
/** @var Tab $tab */
foreach (Tab::getCollectionFromModule($this->module->name) as $tab) {
$result &= (bool)$tab->delete();
}
return $result;
}
public function dropTables()
{
try {
include __DIR__ . '/Sql/uninstall.php';
} catch (Exception $e) {
$this->errors[] = $this->module->l('Failed to uninstall database tables');
return false;
}
return true;
}
public function dropConfig()
{
$result = true;
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_ENVIRONMENT);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_API_KEY);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_AUTH_STATUS);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_SYNC_OFFERS);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_SYNC_LOGISTIC_CLASS);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_OFFER_IDENTIFIER);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_LEAD_TIME_TO_SHIP);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_PRICE_RATIO);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_ADD_TO_PRICE);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_REDUCE_STOCK);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_IMPORT_ORDERS);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_AUTO_ACCEPT_ORDERS);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_NEW_ORDER_STATE);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_SHIPPED_ORDER_STATE);
$result &= Configuration::deleteByName(ConfigurationAdapter::CONF_CARRIER_MAP);
return $result;
}
protected function uninstallTab($className)
{
$tab = new Tab(Tab::getIdFromClassName($className));
return (bool)$tab->delete();
}
}

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;

View File

@@ -0,0 +1,110 @@
<?php
namespace Empik\Marketplace\Manager;
use Empik\Marketplace\Adapter\ConfigurationAdapter;
class CarrierMapManager
{
/** @var ConfigurationAdapter */
protected $configurationAdapter;
/** @var array */
protected $map = [];
public function __construct(ConfigurationAdapter $configurationAdapter)
{
$this->configurationAdapter = $configurationAdapter;
$this->loadFromConfig();
}
/**
* @return array|mixed
*/
public function loadFromConfig()
{
$jsonString = $this->configurationAdapter->get(ConfigurationAdapter::CONF_CARRIER_MAP);
if ($jsonString) {
$this->map = json_decode($jsonString, true);
}
return $this->map;
}
/**
* @param $map
* @return bool
*/
public function setMap($map)
{
if ($this->validate($map)) {
$this->map = $map;
return true;
}
return false;
}
/**
* @param $map
* @return bool
*/
public function store($map)
{
if ($this->validate($map)) {
return $this->configurationAdapter->updateValue(
ConfigurationAdapter::CONF_CARRIER_MAP,
json_encode($map)
);
}
return true;
}
/**
* @param $code
* @return mixed
*/
public function getTypeByCode($code)
{
foreach ($this->map as $carrierCode => $carrier) {
if ($carrierCode === $code) {
return $carrier['type'];
}
}
return false;
}
/**
* @param $code
* @return mixed
*/
public function getIdByCode($code)
{
foreach ($this->map as $carrierCode => $carrier) {
if ($carrierCode === $code) {
return $carrier['id_carrier'];
}
}
return false;
}
/**
* @param $map
* @return bool
*/
protected function validate($map)
{
if (!is_array($map)) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Empik\Marketplace\Manager;
use Empik\Marketplace\Exception\InvalidArgumentException;
class CsvManager
{
/** @var null|string */
protected $csvPath;
/** @var string */
protected $delimiter;
/** @var null|resource */
protected $fileHandle;
public function __construct($csvPath, $delimiter = ';')
{
$this->csvPath = $csvPath;
$this->delimiter = $delimiter;
}
function __destruct()
{
if ($this->fileHandle) {
fclose($this->fileHandle);
}
}
public function remove()
{
if (file_exists($this->csvPath)) {
return unlink($this->csvPath);
}
return true;
}
public function addRow(array $row)
{
if (!$this->fileHandle) {
$this->fileHandle = fopen($this->csvPath, 'a');
}
if (!$row) {
throw new InvalidArgumentException('Invalid CSV row');
}
return fputcsv($this->fileHandle, $row, $this->delimiter);
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace Empik\Marketplace\Manager;
class OrderManager
{
}

View File

@@ -0,0 +1,63 @@
<?php
namespace Empik\Marketplace\Manager;
use Context;
use DateTime;
use EmpikAction;
class ProcessManager
{
/** @var EmpikAction */
protected $processModel;
public function __construct()
{
$this->processModel = new EmpikAction();
$this->processModel->id_shop = Context::getContext()->shop->id;
}
public function start($action = null)
{
if ($action) {
$this->processModel->action = $action;
}
$this->setDateStart();
$this->setDateEnd();
}
public function end()
{
$this->setDateEnd();
$this->processModel->save();
}
public function setStatus($status)
{
$this->processModel->status = $status;
$this->processModel->save();
}
protected function setDateStart()
{
$time = new DateTime();
$this->processModel->date_start = $time->format('Y-m-d H:i:s');
}
protected function setDateEnd()
{
$time = new DateTime();
$this->processModel->date_end = $time->format('Y-m-d H:i:s');
}
public function updateFromResponse(array $response)
{
if (isset($response['import_id'])) {
$this->processModel->id_import = (int)$response['import_id'];
}
$this->processModel->save();
}
}

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;

View File

@@ -0,0 +1,383 @@
<?php
namespace Empik\Marketplace\OrderFulfiller;
use Empik\Marketplace\Adapter\ToolsAdapter;
use Empik\Marketplace\DataProvider\ProductDataProvider;
use Order;
use OrderDetail;
use Address;
use Customer;
use OrderCarrier;
use OrderHistory;
use Cart;
class EmpikOrder
{
/** @var ProductDataProvider */
protected $productDataProvider;
/** @var array */
protected $data;
/** @var Order */
protected $order;
/** @var OrderDetail[] */
protected $orderDetails;
/** @var Customer */
protected $customer;
/** @var Address */
protected $shippingAddress;
/** @var Address */
protected $billingAddress;
/** @var OrderCarrier */
protected $carrier;
/** @var Cart */
protected $cart;
/** @var OrderHistory[] */
protected $orderHistory;
/** @var array */
protected $notes;
public function __construct($data)
{
$id = \EmpikOrder::getOrderIdByEmpikOrderReference($data['order_id']);
$order = new Order($id);
$this->setData($data);
$this->setOrder($order);
$this->productDataProvider = new ProductDataProvider();
}
/**
* @return bool
*/
public function exist()
{
$data = $this->getData();
return (bool)\EmpikOrder::getOrderIdByEmpikOrderReference($data['order_id']);
}
/**
* @return bool
*/
public function isAcceptable()
{
foreach ($this->getAcceptanceLines() as $orderLine) {
if (!$orderLine['accepted']) {
return false;
}
}
return true;
}
/**
* @return array
*/
public function getAcceptanceLines()
{
$return = [];
foreach ($this->getData()['order_lines'] as $orderLine) {
$pr = $this->productDataProvider->getOneBy([
'p.reference' => $orderLine['offer_sku'] // @todo
]);
$return[] = [
'id' => (string)$orderLine['order_line_id'],
'accepted' => $pr && $pr['active'] && $pr['quantity'] >= $orderLine['quantity'],
];
}
return $return;
}
public function add()
{
$context = \Context::getContext();
if ($this->customer && !$this->customer->id) {
$this->customer->id_shop = $context->shop->id;
$this->customer->id_shop_group = $context->shop->id_shop_group;
$this->customer->add();
}
if ($this->shippingAddress && !$this->shippingAddress->id) {
$this->shippingAddress->id_customer = $this->customer->id;
$this->shippingAddress->add();
}
if ($this->billingAddress && !$this->billingAddress->id) {
$this->shippingAddress->id_customer = $this->customer->id;
$this->billingAddress->add();
}
$this->cart->id_customer = $this->customer->id;
// $this->cart->add();
$this->order->id_address_delivery = $this->shippingAddress->id;
$this->order->id_address_invoice = $this->billingAddress->id;
$this->order->id_cart = $this->cart->id;
$this->order->id_currency = $context->currency->id;
$this->order->id_lang = $context->language->id;
$this->order->id_shop = $context->shop->id;
$this->order->id_shop_group = $context->shop->id_shop_group;
$this->order->id_customer = $this->customer->id;
$this->order->id_carrier = $this->carrier->id_carrier;
$this->order->payment = $this->data['payment_type'];
$this->order->module = 'empikmarketplace';
$this->order->total_paid = (float)$this->data['total_price'];
$this->order->total_paid_tax_incl = (float)$this->data['total_price'];
$this->order->total_paid_tax_excl = (float)$this->data['total_price'];
$this->order->total_paid_real = (float)$this->data['total_price'];
$this->order->total_products = (float)$this->data['price'];
$this->order->total_products_wt = (float)$this->data['price'];
$this->order->total_shipping = (float)$this->data['shipping_price'];
$this->order->total_shipping_tax_incl = (float)$this->data['shipping_price'];
$this->order->total_shipping_tax_excl = (float)$this->data['shipping_price'];
$this->order->conversion_rate = 1;
$this->order->secure_key = $this->customer->secure_key;
do {
$this->order->reference = Order::generateReference();
} while (Order::getByReference($this->order->reference)->count());
if ($this->orderHistory) {
$this->order->current_state = end($this->orderHistory)->id_order_state;
}
// foreach ($this->notes as $note) {
// $this->order->note .= !$this->order->note ? $note : "\r\n\r\n" . $note;
// }
// create order
$this->order->add();
// add message (ps 1.6)
// if ($this->order->note && !ToolsAdapter::is17static()) {
// $msg = new \Message();
// $msg->message = $this->order->note;
// $msg->id_cart = $this->cart->id;
// $msg->id_customer = $this->customer->id;
// $msg->id_order = $this->order->id;
// $msg->private = 1;
// $msg->add();
// }
// add order carrier
$this->carrier->id_order = $this->order->id;
$this->carrier->shipping_cost_tax_excl = $this->order->total_shipping_tax_excl;
$this->carrier->shipping_cost_tax_incl = $this->order->total_shipping_tax_incl;
$this->carrier->add();
foreach ($this->orderDetails as $orderDetail) {
$orderDetail->id_order = $this->order->id;
$orderDetail->add();
}
foreach ($this->orderHistory as $history) {
$history->id_order = $this->order->id;
$history->add();
}
// @todo
$empikOrder = new \EmpikOrder();
$empikOrder->id_order = $this->order->id;
$empikOrder->empik_order_reference = $this->data['order_id'];
$empikOrder->empik_order_carrier = $this->data['shipping_type_code'];
$empikOrder->empik_payment = $this->data['payment_type'];
$empikOrder->empik_carrier = $this->data['shipping_type_label'];
foreach ($this->data['order_additional_fields'] as $additionalField) {
if ($additionalField['code'] === 'delivery-point-name') {
$empikOrder->empik_pickup_point = $additionalField['value'];
}
if ($additionalField['code'] === 'nip') {
$empikOrder->empik_vat_number = $additionalField['value'];
}
}
$empikOrder->add();
}
/**
* @return Cart
*/
public function getCart()
{
return $this->cart;
}
/**
* @param Cart $cart
*/
public function setCart($cart)
{
$this->cart = $cart;
}
/**
* @return OrderHistory[]
*/
public function getOrderHistory()
{
return $this->orderHistory;
}
/**
* @param OrderHistory[] $orderHistory
*/
public function setOrderHistory($orderHistory)
{
$this->orderHistory = $orderHistory;
}
/**
* @return OrderCarrier
*/
public function getCarrier()
{
return $this->carrier;
}
/**
* @param OrderCarrier $carrier
*/
public function setCarrier($carrier)
{
$this->carrier = $carrier;
}
/**
* @return array
*/
public function getData()
{
return $this->data;
}
/**
* @param array $data
*/
public function setData($data)
{
$this->data = $data;
}
/**
* @return Order
*/
public function getOrder()
{
return $this->order;
}
/**
* @param Order $order
*/
public function setOrder($order)
{
$this->order = $order;
}
/**
* @return OrderDetail[]
*/
public function getOrderDetails()
{
return $this->orderDetails;
}
/**
* @param OrderDetail[] $orderDetails
*/
public function setOrderDetails($orderDetails)
{
$this->orderDetails = $orderDetails;
}
/**
* @return Customer
*/
public function getCustomer()
{
return $this->customer;
}
/**
* @param Customer $customer
*/
public function setCustomer($customer)
{
$this->customer = $customer;
}
/**
* @return Address
*/
public function getShippingAddress()
{
return $this->shippingAddress;
}
/**
* @param Address $shippingAddress
*/
public function setShippingAddress($shippingAddress)
{
$this->shippingAddress = $shippingAddress;
}
/**
* @return Address
*/
public function getBillingAddress()
{
return $this->billingAddress;
}
/**
* @param Address $billingAddress
*/
public function setBillingAddress($billingAddress)
{
$this->billingAddress = $billingAddress;
}
/**
* @return array
*/
public function getNotes(): array
{
return $this->notes;
}
/**
* @param array $notes
*/
public function setNotes(array $notes): void
{
$this->notes = $notes;
}
}

View File

@@ -0,0 +1,394 @@
<?php
namespace Empik\Marketplace\OrderFulfiller;
use Configuration;
use Empik\Marketplace\Adapter\ConfigurationAdapter;
use Empik\Marketplace\DataProvider\ProductDataProvider;
use Empik\Marketplace\PrestaShopContext;
use Empik\Marketplace\Repository\ProductRepository;
use Empik\Marketplace\Utils\IdentifierExtractor;
use Order;
use OrderDetail;
use Address;
use Customer;
use OrderCarrier;
use OrderHistory;
use EmpikOrder;
use Cart;
use StockAvailable;
class EmpikOrderWrapper
{
/** @var ProductDataProvider */
protected $productDataProvider;
/** @var ProductRepository */
protected $productRepository;
/** @var IdentifierExtractor */
protected $identifierExtractor;
/** @var array */
protected $data;
/** @var Order */
protected $order;
/** @var OrderDetail[] */
protected $orderDetails;
/** @var Customer */
protected $customer;
/** @var Address */
protected $shippingAddress;
/** @var Address */
protected $billingAddress;
/** @var OrderCarrier */
protected $carrier;
/** @var Cart */
protected $cart;
/** @var OrderHistory[] */
protected $orderHistory;
public function __construct()
{
$this->productDataProvider = new ProductDataProvider();
$this->productRepository = new ProductRepository(
new PrestaShopContext()
);
$this->identifierExtractor = new IdentifierExtractor();
}
public function init($data)
{
$id = EmpikOrder::getOrderIdByEmpikOrderReference($data['order_id']);
$order = new Order($id);
$this->setData($data);
$this->setOrder($order);
}
/**
* @return bool
*/
public function exist()
{
$data = $this->getData();
return (bool)\EmpikOrder::getOrderIdByEmpikOrderReference($data['order_id']);
}
/**
* @return bool
*/
public function isAcceptable()
{
foreach ($this->getAcceptanceLines() as $orderLine) {
if (!$orderLine['accepted']) {
return false;
}
}
return true;
}
/**
* @return array
*/
public function getAcceptanceLines()
{
$skuType = Configuration::get(ConfigurationAdapter::CONF_SKU_TYPE);
$return = [];
foreach ($this->getData()['order_lines'] as $orderLine) {
if ($skuType === 'ID') {
$product = $this->productRepository->getProductOrCombinationById($orderLine['offer_sku']);
} elseif ($skuType === 'EAN') {
$product = $this->productRepository->getProductOrCombinationByEan($orderLine['offer_sku']);
} elseif ($skuType === 'REFERENCE') {
$product = $this->productRepository->getProductOrCombinationBySku($orderLine['offer_sku']);
}
$return[] = [
'id' => (string)$orderLine['order_line_id'],
'accepted' => $product && $product['active'] && $product['quantity'] >= $orderLine['quantity'],
];
}
return $return;
}
public function add()
{
$context = \Context::getContext();
if ($this->customer && !$this->customer->id) {
$this->customer->id_shop = $context->shop->id;
$this->customer->id_shop_group = $context->shop->id_shop_group;
$this->customer->add();
}
if ($this->shippingAddress && !$this->shippingAddress->id) {
$this->shippingAddress->id_customer = $this->customer->id;
$this->shippingAddress->add();
}
if ($this->billingAddress && !$this->billingAddress->id) {
$this->billingAddress->id_customer = $this->customer->id;
$this->billingAddress->add();
}
$this->cart->id_customer = $this->customer->id;
$this->cart->id_address_delivery = $this->shippingAddress->id;
$this->cart->id_address_invoice = $this->billingAddress->id;
$this->cart->update();
$this->order->id_address_delivery = $this->shippingAddress->id;
$this->order->id_address_invoice = $this->billingAddress->id;
$this->order->id_cart = $this->cart->id;
$this->order->id_currency = $context->currency->id;
$this->order->id_lang = $context->language->id;
$this->order->id_shop = $context->shop->id;
$this->order->id_shop_group = $context->shop->id_shop_group;
$this->order->id_customer = $this->customer->id;
$this->order->id_carrier = $this->carrier->id_carrier;
$this->order->payment = $this->data['payment_type'];
$this->order->module = 'empikmarketplace';
$this->order->total_paid = (float)$this->data['total_price'];
$this->order->total_paid_tax_incl = (float)$this->data['total_price'];
$this->order->total_paid_tax_excl = (float)$this->data['total_price'];
$this->order->total_paid_real = (float)$this->data['total_price'];
$this->order->total_products = (float)$this->data['price'];
$this->order->total_products_wt = (float)$this->data['price'];
$this->order->total_shipping = (float)$this->data['shipping_price'];
$this->order->total_shipping_tax_incl = (float)$this->data['shipping_price'];
$this->order->total_shipping_tax_excl = (float)$this->data['shipping_price'];
$this->order->conversion_rate = 1;
$this->order->secure_key = $this->customer->secure_key;
do {
$this->order->reference = Order::generateReference();
} while (Order::getByReference($this->order->reference)->count());
if ($this->orderHistory) {
$this->order->current_state = end($this->orderHistory)->id_order_state;
}
// create order
$this->order->add();
// add order carrier
$this->carrier->id_order = $this->order->id;
$this->carrier->shipping_cost_tax_excl = $this->order->total_shipping_tax_excl;
$this->carrier->shipping_cost_tax_incl = $this->order->total_shipping_tax_incl;
$this->carrier->add();
foreach ($this->orderDetails as $orderDetail) {
$orderDetail->id_order = $this->order->id;
$orderDetail->add();
if ($this->order->current_state != Configuration::get('PS_OS_CANCELED')
&& $this->order->current_state != Configuration::get('PS_OS_ERROR')) {
if (!StockAvailable::dependsOnStock($orderDetail->product_id)) {
StockAvailable::updateQuantity(
$orderDetail->product_id,
$orderDetail->product_attribute_id,
-(int) $orderDetail->product_quantity,
$orderDetail->id_shop,
true
);
}
}
}
foreach ($this->orderHistory as $history) {
$history->id_order = $this->order->id;
$history->add();
}
$this->createEmpikOrder();
}
public function createEmpikOrder()
{
$empikOrder = new EmpikOrder();
$empikOrder->id_order = $this->order->id;
$empikOrder->empik_order_reference = $this->data['order_id'];
$empikOrder->empik_order_carrier = $this->data['shipping_type_code'];
$empikOrder->empik_payment = $this->data['payment_type'];
$empikOrder->empik_carrier = $this->data['shipping_type_label'];
foreach ($this->data['order_additional_fields'] as $additionalField) {
if ($additionalField['code'] === 'delivery-point-name') {
$empikOrder->empik_pickup_point = $additionalField['value'];
}
if ($additionalField['code'] === 'nip') {
$empikOrder->empik_vat_number = $additionalField['value'];
}
}
$empikOrder->add();
}
/**
* @return Cart
*/
public function getCart()
{
return $this->cart;
}
/**
* @param Cart $cart
*/
public function setCart($cart)
{
$this->cart = $cart;
}
/**
* @return OrderHistory[]
*/
public function getOrderHistory()
{
return $this->orderHistory;
}
/**
* @param OrderHistory[] $orderHistory
*/
public function setOrderHistory($orderHistory)
{
$this->orderHistory = $orderHistory;
}
/**
* @return OrderCarrier
*/
public function getCarrier()
{
return $this->carrier;
}
/**
* @param OrderCarrier $carrier
*/
public function setCarrier($carrier)
{
$this->carrier = $carrier;
}
/**
* @return array
*/
public function getData()
{
return $this->data;
}
/**
* @param array $data
*/
public function setData($data)
{
$this->data = $data;
}
/**
* @return Order
*/
public function getOrder()
{
return $this->order;
}
/**
* @param Order $order
*/
public function setOrder($order)
{
$this->order = $order;
}
/**
* @return OrderDetail[]
*/
public function getOrderDetails()
{
return $this->orderDetails;
}
/**
* @param OrderDetail[] $orderDetails
*/
public function setOrderDetails($orderDetails)
{
$this->orderDetails = $orderDetails;
}
/**
* @return Customer
*/
public function getCustomer()
{
return $this->customer;
}
/**
* @param Customer $customer
*/
public function setCustomer($customer)
{
$this->customer = $customer;
}
/**
* @return Address
*/
public function getShippingAddress()
{
return $this->shippingAddress;
}
/**
* @param Address $shippingAddress
*/
public function setShippingAddress($shippingAddress)
{
$this->shippingAddress = $shippingAddress;
}
/**
* @return Address
*/
public function getBillingAddress()
{
return $this->billingAddress;
}
/**
* @param Address $billingAddress
*/
public function setBillingAddress($billingAddress)
{
$this->billingAddress = $billingAddress;
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace Empik\Marketplace\OrderFulfiller;
use Empik\Marketplace\Provider\Order\AddressProvider;
use Empik\Marketplace\Provider\Order\CarrierProvider;
use Empik\Marketplace\Provider\Order\CustomerProvider;
use Empik\Marketplace\Provider\Order\HistoryProvider;
use Empik\Marketplace\Provider\Order\CartProvider;
use Empik\Marketplace\Provider\Order\OrderLinesProvider;
use Empik\Marketplace\Exception\OrderProcessException;
class OrderFulfiller
{
/** @var AddressProvider */
protected $addressProvider;
/** @var CustomerProvider */
protected $customerProvider;
/** @var OrderLinesProvider */
protected $orderLinesProvider;
/** @var CarrierProvider */
protected $carrierProvider;
/** @var HistoryProvider */
protected $historyProvider;
/** @var CartProvider */
protected $cartProvider;
public function __construct(
AddressProvider $addressProvider,
CustomerProvider $customerProvider,
OrderLinesProvider $orderLinesProvider,
CarrierProvider $carrierProvider,
HistoryProvider $historyProvider,
CartProvider $cartProvider
) {
$this->addressProvider = $addressProvider;
$this->customerProvider = $customerProvider;
$this->orderLinesProvider = $orderLinesProvider;
$this->carrierProvider = $carrierProvider;
$this->historyProvider = $historyProvider;
$this->cartProvider = $cartProvider;
}
/**
* @param EmpikOrderWrapper $order
* @throws OrderProcessException
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
public function fulfill(EmpikOrderWrapper $order)
{
$data = $order->getData();
$this->validate($data);
// add customer
$prestaShopCustomer = $this->customerProvider->provide($data);
$order->setCustomer($prestaShopCustomer);
// add addresses
$billingAddress = isset($data['customer']['billing_address']) ? $data['customer']['billing_address'] : null;
$shippingAddress = isset($data['customer']['shipping_address']) ? $data['customer']['shipping_address'] : null;
$additionalFields = isset($data['order_additional_fields']) ? $data['order_additional_fields'] : [];
$prestaShopShippingAddress = $this->addressProvider->provide(
$shippingAddress,
$order->getCustomer()
);
$order->setShippingAddress($prestaShopShippingAddress);
$prestaShopBillingAddress = $this->addressProvider->provide(
$billingAddress,
$order->getCustomer(),
$additionalFields
);
$order->setBillingAddress($prestaShopBillingAddress);
// add cart
$cart = $this->cartProvider->provide($data);
$order->setCart($cart);
// add order lines
$orderLines = $this->orderLinesProvider->provide($data);
$order->setOrderDetails($orderLines);
// add carrier
$carrier = $this->carrierProvider->provide($data);
$order->setCarrier($carrier);
// add order status
$history = $this->historyProvider->provide($data);
$order->setOrderHistory($history);
$order->add();
}
/**
* @param array $data
* @throws OrderProcessException
*/
protected function validate($data)
{
if (
(
empty($data['customer']['shipping_address']) &&
empty($data['customer']['billing_address'])
) ||
empty($data['order_id']) ||
empty($data['order_lines']) ||
empty($data['order_state']) ||
empty($data['total_price'])
) {
throw new OrderProcessException(sprintf('Invalid order data for order: %s', $data['order_id']));
}
}
}

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;

View File

@@ -0,0 +1,16 @@
<?php
namespace Empik\Marketplace;
class PrestaShopContext
{
public function is17()
{
return version_compare(_PS_VERSION_, '1.7', '>=');
}
public function is177()
{
return version_compare(_PS_VERSION_, '1.7.7', '>=');
}
}

View File

@@ -0,0 +1,80 @@
<?php
namespace Empik\Marketplace\Processor;
use Empik\Marketplace\Traits\ErrorsTrait;
use Empik\Marketplace\API\EmpikClient;
use Empik\Marketplace\Configuration\ExportConfiguration;
use Empik\Marketplace\Factory\EmpikClientFactory;
use Empik\Marketplace\Handler\ExportOfferHandler;
use Empik\Marketplace\Manager\ProcessManager;
use Exception;
class ExportOfferProcessor
{
use ErrorsTrait;
/** @var EmpikClientFactory */
private $empikClientFactory;
/** @var ExportOfferHandler */
protected $exportOfferHandler;
/** @var ExportConfiguration */
protected $exportConfiguration;
/** @var EmpikClient */
protected $empikClient;
/** @var ProcessManager */
protected $processManager;
protected $page = null;
public function __construct(
ProcessManager $processManager,
EmpikClientFactory $empikClientFactory,
ExportOfferHandler $exportOfferHandler,
ExportConfiguration $exportConfiguration
) {
$this->processManager = $processManager;
$this->empikClientFactory = $empikClientFactory;
$this->exportOfferHandler = $exportOfferHandler;
$this->exportConfiguration = $exportConfiguration;
$this->empikClient = $this->empikClientFactory->createClient();
}
public function setPage($page)
{
$this->page = $page;
}
public function process()
{
try {
$this->processManager->start(\EmpikAction::ACTION_OFFER_EXPORT);
// create CSV
$this->exportOfferHandler->handle(
$this->page
);
// post CSV
if ($this->isLastPage()) {
$response = $this->empikClient->postOffersImports(
$this->exportConfiguration->getOfferExportPath()
);
$this->processManager->updateFromResponse($response);
$this->processManager->end();
}
} catch (Exception $e) {
$this->addError($e->getMessage());
}
}
public function isLastPage()
{
return $this->page === null || $this->exportOfferHandler->isLastPage($this->page);
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace Empik\Marketplace\Processor;
use Empik\Marketplace\Traits\ErrorsTrait;
use Empik\Marketplace\API\EmpikClient;
use Empik\Marketplace\Configuration\ExportConfiguration;
use Empik\Marketplace\Factory\EmpikClientFactory;
use Empik\Marketplace\Handler\ExportProductHandler;
use Empik\Marketplace\Manager\ProcessManager;
use Exception;
class ExportProductProcessor
{
use ErrorsTrait;
/** @var EmpikClientFactory */
private $empikClientFactory;
/** @var ExportProductHandler */
protected $exportProductHandler;
/** @var ExportConfiguration */
protected $exportConfiguration;
/** @var EmpikClient */
protected $empikClient;
/** @var ProcessManager */
protected $processManager;
protected $page = null;
public function __construct(
ProcessManager $processManager,
EmpikClientFactory $empikClientFactory,
ExportProductHandler $exportProductHandler,
ExportConfiguration $exportConfiguration
) {
$this->processManager = $processManager;
$this->empikClientFactory = $empikClientFactory;
$this->exportProductHandler = $exportProductHandler;
$this->exportConfiguration = $exportConfiguration;
$this->empikClient = $this->empikClientFactory->createClient();
}
public function setPage($page)
{
$this->page = $page;
}
public function process()
{
try {
$this->processManager->start(\EmpikAction::ACTION_PRODUCT_EXPORT);
// create CSV
$this->exportProductHandler->handle(
$this->page
);
// post CSV
if ($this->isLastPage()) {
$response = $this->empikClient->postProducts(
$this->exportConfiguration->getProductExportPath()
);
$this->processManager->updateFromResponse($response);
$this->processManager->end();
}
} catch (Exception $e) {
$this->addError($e->getMessage());
}
}
public function isLastPage()
{
return $this->page === null || $this->exportProductHandler->isLastPage($this->page);
}
}

View File

@@ -0,0 +1,129 @@
<?php
namespace Empik\Marketplace\Processor;
use Empik\Marketplace\Adapter\ConfigurationAdapter;
use Empik\Marketplace\Adapter\LoggerAdapter;
use Empik\Marketplace\API\EmpikClient;
use Empik\Marketplace\OrderFulfiller\EmpikOrderWrapper;
use Empik\Marketplace\Factory\EmpikClientFactory;
use Empik\Marketplace\Manager\ProcessManager;
use Empik\Marketplace\OrderFulfiller\OrderFulfiller;
use GuzzleHttp\Exception\ClientException;
use Exception;
use Configuration;
use Db;
class OrderProcessor
{
const CODE_WAITING_ACCEPTANCE = 'WAITING_ACCEPTANCE';
const CODE_SHIPPING = 'SHIPPING';
/** @var EmpikClientFactory */
protected $empikClientFactory;
/** @var EmpikClient */
protected $empikClient;
/** @var ProcessManager */
protected $processManager;
/** @var OrderFulfiller */
protected $orderFulfiller;
/** @var LoggerAdapter */
protected $logger;
protected $allowAccept;
protected $allowImport;
public function __construct(
ProcessManager $processManager,
EmpikClientFactory $empikClientFactory,
OrderFulfiller $orderFulfiller,
LoggerAdapter $loggerAdapter
) {
$this->processManager = $processManager;
$this->empikClientFactory = $empikClientFactory;
$this->orderFulfiller = $orderFulfiller;
$this->logger = $loggerAdapter;
$this->empikClient = $this->empikClientFactory->createClient();
$this->allowAccept = (bool)Configuration::get(ConfigurationAdapter::CONF_AUTO_ACCEPT_ORDERS);
$this->allowImport = (bool)Configuration::get(ConfigurationAdapter::CONF_IMPORT_ORDERS);
}
public function process()
{
if (!$this->allowAccept && !$this->allowImport) {
return;
}
$response = $this->empikClient->getOrders([
'order_state_codes' => implode(',', $this->getOrderCodesForProcess()),
]);
foreach ($response['orders'] as $order) {
$empikOrder = new EmpikOrderWrapper();
$empikOrder->init($order);
if ($this->allowAccept && $empikOrder->isAcceptable() && !$empikOrder->exist()) {
$this->accept($empikOrder);
}
if ($this->allowImport) {
if (!$empikOrder->exist()) {
$this->import($empikOrder);
}
}
}
}
protected function import(EmpikOrderWrapper $empikOrder)
{
try {
Db::getInstance()->execute('START TRANSACTION');
$this->orderFulfiller->fulfill($empikOrder);
Db::getInstance()->execute('COMMIT');
} catch (Exception $e) {
Db::getInstance()->execute('ROLLBACK');
$this->logger->logError(sprintf('Error importing order [%s]', $e->getMessage()));
}
}
protected function accept(EmpikOrderWrapper $empikOrder)
{
$acceptLines = $empikOrder->getAcceptanceLines();
try {
$this->empikClient->putOrderAccept(
$empikOrder->getData()['order_id'],
$acceptLines
);
} catch (ClientException $e) {
$responseJson = $e->getResponse()->json();
$message = isset($responseJson['message']) ? $responseJson['message'] : null;
$this->logger->logError(sprintf('Error accepting order [%s]', $message));
} catch (Exception $e) {
$this->logger->logError(sprintf('Error accepting order [%s]', $e->getMessage()));
}
}
protected function getOrderCodesForProcess()
{
$codes = [];
if ($this->allowAccept) {
$codes[] = self::CODE_WAITING_ACCEPTANCE;
}
if ($this->allowImport) {
$codes[] = self::CODE_SHIPPING;
}
return $codes;
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Empik\Marketplace\Processor;
use Empik\Marketplace\Manager\OrderManager;
use Empik\Marketplace\OrderFulfiller\OrderFulfiller;
use Empik\Marketplace\Repository\OrderRepository;
class OrdersProcessor
{
/** @var OrderRepository */
private $orderRepository;
/** @var OrderManager */
private $orderManager;
/** @var OrderFulfiller */
private $orderFulfiller;
public function __construct(
OrderRepository $orderRepository,
OrderManager $orderManager,
OrderFulfiller $orderFulfiller
)
{
$this->orderRepository = $orderRepository;
$this->orderManager = $orderManager;
$this->orderFulfiller = $orderFulfiller;
}
public function process($limit = 0, $step = 0)
{
$orders = $this->orderRepository->find($limit, $step);
foreach ($orders as $order) {
try {
$this->orderFulfiller->fulfill($order);
} catch (\Exception $e) {
}
}
}
}

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;

View File

@@ -0,0 +1,13 @@
<?php
namespace Empik\Marketplace\Provider;
class BillingAddressProvider
{
public function provide($address)
{
return [];
}
}

Some files were not shown because too many files have changed in this diff Show More