Merge pull request #33 from iyzoer/master

v2.2.4
This commit is contained in:
Alex Lushpai 2018-10-08 11:09:24 +03:00 committed by GitHub
commit fc76adb944
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 648 additions and 209 deletions

View File

@ -1,5 +1,9 @@
## v.2.2.4
* Добавлена установка дефолтной валюты для оплаты при получении истории
* Добавлено получение суммы оплаты из заказа в CMS, если она не передается по истории
## v.2.2.3 ## v.2.2.3
* Добавлена исключение при обработка исключений при обновлении пользователя * добавлена обработка исключений при обновлении пользователя на стороне CMS
## v.2.2.2 ## v.2.2.2
* Добавлена передача комментария клиента при создании заказа * Добавлена передача комментария клиента при создании заказа

View File

@ -6,9 +6,12 @@ all: build_archive send_to_ftp delete_archive
build_archive: build_archive:
zip -r $(ARCHIVE_NAME) ./retailcrm/* zip -r $(ARCHIVE_NAME) ./retailcrm/*
zip -r /tmp/retailcrm.zip ./retailcrm/*
send_to_ftp: send_to_ftp:
curl -T $(ARCHIVE_NAME) -u $(FTP_USER):$(FTP_PASSWORD) ftp://$(FTP_HOST) curl -T $(ARCHIVE_NAME) -u $(FTP_USER):$(FTP_PASSWORD) ftp://$(FTP_HOST)
curl -T /tmp/retailcrm.zip -u $(FTP_USER):$(FTP_PASSWORD) ftp://$(FTP_HOST)
delete_archive: delete_archive:
rm -f $(ARCHIVE_NAME) rm -f $(ARCHIVE_NAME)
rm -f /tmp/retailcrm.zip

View File

@ -1 +1 @@
2.2.3 2.2.4

View File

@ -205,10 +205,8 @@ class RetailcrmCatalog
$items[] = $item; $items[] = $item;
} }
} }
return array($categories, $items); return array($categories, $items);
} }
} }

View File

@ -154,7 +154,12 @@ class RetailcrmHistory
$references = new RetailcrmReferences(self::$api); $references = new RetailcrmReferences(self::$api);
if ($lastSync === false && $lastDate === false) { if ($lastSync === false && $lastDate === false) {
$filter = array('startDate' => date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))); $filter = array(
'startDate' => date(
'Y-m-d H:i:s',
strtotime('-1 days', strtotime(date('Y-m-d H:i:s')))
)
);
} elseif ($lastSync === false && $lastDate !== false) { } elseif ($lastSync === false && $lastDate !== false) {
$filter = array('startDate' => $lastDate); $filter = array('startDate' => $lastDate);
} elseif ($lastSync !== false) { } elseif ($lastSync !== false) {
@ -418,7 +423,8 @@ class RetailcrmHistory
'total_wt' => $productPrice * $item['quantity'], 'total_wt' => $productPrice * $item['quantity'],
'total' => $productPrice * $item['quantity'], 'total' => $productPrice * $item['quantity'],
'wholesale_price' => $product->wholesale_price, 'wholesale_price' => $product->wholesale_price,
'id_supplier' => $product->id_supplier 'id_supplier' => $product->id_supplier,
'id_customization' => 0
); );
if (isset($item['discountTotal']) && self::$apiVersion == 5) { if (isset($item['discountTotal']) && self::$apiVersion == 5) {
@ -446,6 +452,7 @@ class RetailcrmHistory
$orderPayment = new OrderPayment(); $orderPayment = new OrderPayment();
$orderPayment->payment_method = $payType; $orderPayment->payment_method = $payType;
$orderPayment->order_reference = $newOrder->reference; $orderPayment->order_reference = $newOrder->reference;
$orderPayment->id_currency = $default_currency;
$orderPayment->amount = $payment['amount']; $orderPayment->amount = $payment['amount'];
$orderPayment->date_add = $payment['paidAt']; $orderPayment->date_add = $payment['paidAt'];
$orderPayment->save(); $orderPayment->save();
@ -501,11 +508,13 @@ class RetailcrmHistory
if ($dtype != null) { if ($dtype != null) {
$orderCarrier->id_carrier = $deliveries[$dtype]; $orderCarrier->id_carrier = $deliveries[$dtype];
} }
if ($dcost != null) { if ($dcost != null) {
$orderCarrier->shipping_cost_tax_incl = $dcost; $orderCarrier->shipping_cost_tax_incl = $dcost;
$orderCarrier->shipping_cost_tax_excl = $dcost; $orderCarrier->shipping_cost_tax_excl = $dcost;
} }
$orderCarrier->id_order = $orderToUpdate->id;
$orderCarrier->update(); $orderCarrier->update();
} }
} }
@ -534,18 +543,27 @@ class RetailcrmHistory
) { ) {
$ptype = $payment['type']; $ptype = $payment['type'];
$ptypes = $references->getSystemPaymentModules(); $ptypes = $references->getSystemPaymentModules();
if ($payments[$ptype] != null) { if ($payments[$ptype] != null) {
foreach ($ptypes as $pay) { foreach ($ptypes as $pay) {
if ($pay['code'] == $payments[$ptype]) { if ($pay['code'] == $payments[$ptype]) {
$payType = $pay['name']; $payType = $pay['name'];
} }
} }
$paymentType = Module::getModuleName($payments[$ptype]); $paymentType = Module::getModuleName($payments[$ptype]);
$orderToUpdate->payment = $paymentType != null ? $paymentType : $payments[$ptype]; $orderToUpdate->payment = $paymentType != null ? $paymentType : $payments[$ptype];
$orderPayment = new OrderPayment(); $orderPayment = new OrderPayment();
$orderPayment->payment_method = $payType; $orderPayment->payment_method = $payType;
$orderPayment->order_reference = $orderToUpdate->reference; $orderPayment->order_reference = $orderToUpdate->reference;
if (isset($payment['amount'])){
$orderPayment->amount = $payment['amount']; $orderPayment->amount = $payment['amount'];
} else {
$orderPayment->amount = $orderToUpdate->total_paid;
}
$orderPayment->id_currency = $default_currency;
$orderPayment->date_add = $payment['paidAt']; $orderPayment->date_add = $payment['paidAt'];
$orderPayment->save(); $orderPayment->save();
} }
@ -553,6 +571,46 @@ class RetailcrmHistory
} }
} }
if (isset($order['items'])) {
self::updateItems($order, $orderToUpdate);
}
/**
* check status
*/
if (!empty($order['status'])) {
$stype = $order['status'];
if ($statuses[$stype] != null) {
if ($statuses[$stype] != $orderToUpdate->current_state) {
$orderHistory = new OrderHistory();
$orderHistory->id_employee = 0;
$orderHistory->id_order = $orderToUpdate->id;
$orderHistory->id_order_state = $statuses[$stype];
$orderHistory->date_add = date('Y-m-d H:i:s');
$orderHistory->save();
$orderToUpdate->current_state = $statuses[$stype];
$orderToUpdate->update();
}
}
}
}
}
/*
* Update last sync timestamp
*/
Configuration::updateValue('RETAILCRM_LAST_ORDERS_SYNC', $sinceId);
return true;
} else {
return 'Nothing to sync';
}
}
private static function updateItems($order, $orderToUpdate)
{
/* /*
* Clean deleted items * Clean deleted items
*/ */
@ -731,39 +789,6 @@ class RetailcrmHistory
unset($ItemDiscount); unset($ItemDiscount);
} }
/**
* check status
*/
if (!empty($order['status'])) {
$stype = $order['status'];
if ($statuses[$stype] != null) {
if ($statuses[$stype] != $orderToUpdate->current_state) {
$orderHistory = new OrderHistory();
$orderHistory->id_employee = 0;
$orderHistory->id_order = $orderToUpdate->id;
$orderHistory->id_order_state = $statuses[$stype];
$orderHistory->date_add = date('Y-m-d H:i:s');
$orderHistory->save();
$orderToUpdate->current_state = $statuses[$stype];
$orderToUpdate->update();
}
}
}
}
}
/*
* Update last sync timestamp
*/
Configuration::updateValue('RETAILCRM_LAST_ORDERS_SYNC', $sinceId);
return true;
} else {
return 'Nothing to sync';
}
} }
/** /**

View File

@ -3,8 +3,8 @@
class RetailcrmHistoryHelper { class RetailcrmHistoryHelper {
public static function assemblyOrder($orderHistory) public static function assemblyOrder($orderHistory)
{ {
if (file_exists(_PS_ROOT_DIR_ . '/modules/retailcrm/objects.xml')) { if (file_exists( __DIR__ . '/../objects.xml')) {
$objects = simplexml_load_file(_PS_ROOT_DIR_ . '/modules/retailcrm/objects.xml'); $objects = simplexml_load_file(__DIR__ . '/../objects.xml');
foreach($objects->fields->field as $object) { foreach($objects->fields->field as $object) {
$fields[(string)$object["group"]][(string)$object["id"]] = (string)$object; $fields[(string)$object["group"]][(string)$object["id"]] = (string)$object;
} }
@ -46,7 +46,7 @@ class RetailcrmHistoryHelper {
if ($change['newValue'] == null && $change['field'] == 'payments') { if ($change['newValue'] == null && $change['field'] == 'payments') {
$orders[$change['order']['id']]['payments'][$change['payment']['id']]['delete'] = true; $orders[$change['order']['id']]['payments'][$change['payment']['id']]['delete'] = true;
} }
if (!$orders[$change['order']['id']]['payments'][$change['payment']['id']]['create'] && $fields['payment'][$change['field']]) { if (!$orders[$change['order']['id']]['payments'][$change['payment']['id']] && $fields['payment'][$change['field']]) {
$orders[$change['order']['id']]['payments'][$change['payment']['id']][$fields['payment'][$change['field']]] = $change['newValue']; $orders[$change['order']['id']]['payments'][$change['payment']['id']][$fields['payment'][$change['field']]] = $change['newValue'];
} }
} }

View File

@ -2,7 +2,6 @@
class RetailcrmIcml class RetailcrmIcml
{ {
protected $shop; protected $shop;
protected $file; protected $file;
protected $properties; protected $properties;
@ -145,5 +144,4 @@ class RetailcrmIcml
} }
} }
} }
} }

View File

@ -63,9 +63,12 @@
<field id="shipment_date" group="order">shipmentDate</field> <field id="shipment_date" group="order">shipmentDate</field>
<field id="shipped" group="order">shipped</field> <field id="shipped" group="order">shipped</field>
<!--<field id="order_product" group="order">item</field>--> <!--<field id="order_product" group="order">item</field>-->
<field id="payment" group="order">payments</field>
<field id="payments.amount" group="payment">amount</field>
<field id="payments.status" group="payment">status</field> <field id="payments.status" group="payment">status</field>
<field id="payments.type" group="payment">type</field>
<field id="payments.external_id" group="payment">externalId</field>
<field id="payments.amount" group="payment">amount</field>
<field id="payments.comment" group="payment">comment</field>
<field id="order_product.id" group="item">id</field> <field id="order_product.id" group="item">id</field>
<field id="order_product.initial_price" group="item">initialPrice</field> <field id="order_product.initial_price" group="item">initialPrice</field>

View File

@ -3,7 +3,7 @@
* @author Retail Driver LCC * @author Retail Driver LCC
* @copyright RetailCRM * @copyright RetailCRM
* @license GPL * @license GPL
* @version 2.2.3 * @version 2.2.4
* @link https://retailcrm.ru * @link https://retailcrm.ru
* *
*/ */
@ -38,7 +38,7 @@ class RetailCRM extends Module
{ {
$this->name = 'retailcrm'; $this->name = 'retailcrm';
$this->tab = 'export'; $this->tab = 'export';
$this->version = '2.2.2'; $this->version = '2.2.4';
$this->author = 'Retail Driver LCC'; $this->author = 'Retail Driver LCC';
$this->displayName = $this->l('RetailCRM'); $this->displayName = $this->l('RetailCRM');
$this->description = $this->l('Integration module for RetailCRM'); $this->description = $this->l('Integration module for RetailCRM');

View File

@ -16,9 +16,27 @@ abstract class RetailcrmTestCase extends \PHPUnit\Framework\TestCase
protected function setConfig() protected function setConfig()
{ {
$delivery = json_encode(array('delivery' => 'delivery')); $delivery = json_encode(
$status = json_encode(array('status' => 'status', 'new' => 'new', 'completed'=> 'completed')); array(
$payment = json_encode(array('ps_checkpayment' => 'ps_checkpayment', 'bankwire' => 'bankwire', 'cheque' => 'cheque')); 1 => 'delivery'
)
);
$status = json_encode(
array(
9 => 'status',
10 => 'new',
11 => 'completed'
)
);
$payment = json_encode(
array(
'ps_checkpayment' => 'ps_checkpayment',
'bankwire' => 'bankwire',
'cheque' => 'cheque'
)
);
Configuration::updateValue('RETAILCRM_API_DELIVERY', $delivery); Configuration::updateValue('RETAILCRM_API_DELIVERY', $delivery);
Configuration::updateValue('RETAILCRM_API_STATUS', $status); Configuration::updateValue('RETAILCRM_API_STATUS', $status);

View File

@ -23,4 +23,11 @@ class RetailcrmTestHelper
return $orderPayment->delete(); return $orderPayment->delete();
} }
public static function getMaxOrderId()
{
return Db::getInstance()->getValue(
'SELECT MAX(id_order) FROM `' . _DB_PREFIX_ . 'orders`'
);
}
} }

View File

@ -0,0 +1,53 @@
<?php
class RetailcrmCatalogTest extends RetailcrmTestCase
{
protected $data;
public function setUp()
{
parent::setUp();
$catalog = new RetailcrmCatalog();
$this->data = $catalog->getData();
}
public function testCatalog()
{
$this->assertInternalType('array', $this->data);
$this->assertCount(2, $this->data);
$categories = $this->data[0];
$products = $this->data[1];
$this->assertNotEmpty($categories);
$this->assertNotEmpty($products);
foreach ($categories as $category) {
$this->assertNotEmpty($category);
$this->assertArrayHasKey('id', $category);
$this->assertArrayHasKey('parentId', $category);
$this->assertArrayHasKey('name', $category);
}
foreach ($products as $product) {
$this->assertNotEmpty($product);
$this->assertArrayHasKey('id', $product);
$this->assertArrayHasKey('productId', $product);
$this->assertArrayHasKey('name', $product);
$this->assertArrayHasKey('productName', $product);
$this->assertArrayHasKey('url', $product);
$this->assertRegExp('/http/', $product['url']);
$this->assertArrayHasKey('price', $product);
}
}
public function testIcmlGenerate()
{
$icml = new RetailcrmIcml(Configuration::get('PS_SHOP_NAME'), _PS_ROOT_DIR_ . '/retailcrm.xml');
$icml->generate($this->data[0], $this->data[1]);
$this->assertFileExists(_PS_ROOT_DIR_ . '/retailcrm.xml');
$xml = simplexml_load_file(_PS_ROOT_DIR_ . '/retailcrm.xml');
$this->assertNotEquals(false, $xml);
}
}

View File

@ -0,0 +1,329 @@
<?php
class RetailcrmHistoryTest extends RetailcrmTestCase
{
private $apiMock;
private $product;
public function setUp()
{
parent::setUp();
$this->apiMock = $this->getMockBuilder('RetailcrmProxy')
->disableOriginalConstructor()
->setMethods(
array(
'customersHistory',
'ordersHistory',
'ordersGet',
'customersFixExternalIds',
'ordersFixExternalIds'
)
)
->getMock();
$catalog = new RetailcrmCatalog();
$data = $catalog->getData();
$this->product = $data[1][0];
Configuration::updateValue('RETAILCRM_API_DELIVERY_DEFAULT', 2);
Configuration::updateValue('RETAILCRM_API_PAYMENT_DEFAULT', 'bankwire');
$this->setConfig();
}
/**
* @param $api_version
*
* @dataProvider dataProvider
*/
public function testOrderCreate($api_version)
{
$this->apiMock->expects($this->any())
->method('ordersHistory')
->willReturn(
new RetailcrmApiResponse(
'200',
json_encode(
$this->getHistoryDataNewOrder($api_version)
)
)
);
$this->apiMock->expects($this->any())
->method('ordersGet')
->willReturn(
new RetailcrmApiResponse(
'200',
json_encode(
array(
'order' => $this->getApiOrder($api_version)
)
)
)
);
RetailcrmHistory::$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
RetailcrmHistory::$apiVersion = $api_version;
RetailcrmHistory::$api = $this->apiMock;
$oldLastId = RetailcrmTestHelper::getMaxOrderId();
RetailcrmHistory::ordersHistory();
$newLastId = RetailcrmTestHelper::getMaxOrderId();
$this->assertNotEquals($oldLastId, $newLastId);
$this->assertTrue($newLastId > $oldLastId);
$order = new Order($newLastId);
$this->assertInstanceOf('Order', $order);
}
public function testPaymentStatusUpdate()
{
$lastId = RetailcrmTestHelper::getMaxOrderId();
$this->apiMock->expects($this->any())
->method('ordersHistory')
->willReturn(
new RetailcrmApiResponse(
'200',
json_encode(
$this->getUpdatePaymentStatus($lastId)
)
)
);
RetailcrmHistory::$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
RetailcrmHistory::$apiVersion = 5;
RetailcrmHistory::$api = $this->apiMock;
RetailcrmHistory::ordersHistory();
}
public function dataProvider()
{
return array(
array(
'api_version' => '4'
),
array(
'api_version' => '5'
)
);
}
private function getHistoryDataNewOrder($api_version)
{
return array(
'success' => true,
'history' => array(
array(
'id' => 1,
'createdAt' => '2018-01-01 00:00:00',
'created' => true,
'source' => 'user',
'user' => array(
'id' => 1
),
'field' => 'status',
'oldValue' => null,
'newValue' => array(
'code' => 'new'
),
'order' => $this->getApiOrder($api_version)
)
)
);
}
private function getApiOrder($api_version)
{
$order = array(
'slug' => 1,
'id' => 1,
'number' => '1C',
'orderType' => 'eshop-individual',
'orderMethod' => 'phone',
'countryIso' => 'RU',
'createdAt' => '2018-01-01 00:00:00',
'statusUpdatedAt' => '2018-01-01 00:00:00',
'summ' => 100,
'totalSumm' => 100,
'prepaySum' => 0,
'purchaseSumm' => 50,
'markDatetime' => '2018-01-01 00:00:00',
'firstName' => 'Test',
'lastName' => 'Test',
'phone' => '80000000000',
'call' => false,
'expired' => false,
'customer' => array(
'segments' => array(),
'id' => 1,
'firstName' => 'Test',
'lastName' => 'Test',
'email' => 'email@test.ru',
'phones' => array(
array(
'number' => '111111111111111'
),
array(
'number' => '+7111111111'
)
),
'address' => array(
'index' => '111111',
'countryIso' => 'RU',
'region' => 'Test region',
'city' => 'Test',
'text' => 'Test text address'
),
'createdAt' => '2018-01-01 00:00:00',
'managerId' => 1,
'vip' => false,
'bad' => false,
'site' => 'test-com',
'contragent' => array(
'contragentType' => 'individual'
),
'personalDiscount' => 0,
'cumulativeDiscount' => 0,
'marginSumm' => 58654,
'totalSumm' => 61549,
'averageSumm' => 15387.25,
'ordersCount' => 4,
'costSumm' => 101,
'customFields' => array(
'custom' => 'test'
)
),
'contragent' => array(),
'delivery' => array(
'code' => 'delivery',
'cost' => 100,
'netCost' => 0,
'address' => array(
'index' => '111111',
'countryIso' => 'RU',
'region' => 'Test region',
'city' => 'Test',
'text' => 'Test text address'
)
),
'site' => 'test-com',
'status' => 'new',
'items' => array(
array(
'id' => 160,
'initialPrice' => 100,
'createdAt' => '2018-01-01 00:00:00',
'quantity' => 1,
'status' => 'new',
'offer' => array(
'id' => 1,
'externalId' => $this->product['id'],
'xmlId' => '1',
'name' => 'Test name',
'vatRate' => 'none'
),
'properties' => array(),
'purchasePrice' => 50
)
),
'fromApi' => false,
'length' => 0,
'width' => 0,
'height' => 0,
'shipmentStore' => 'main',
'shipped' => false,
'customFields' => array(),
'uploadedToExternalStoreSystem' => false
);
if ($api_version == 5) {
$order['payments'][] = array(
'id' => 97,
'type' => 'cheque',
'amount' => 200
);
} else {
$order['paymentType'] = 'cheque';
}
return $order;
}
private function getUpdatePaymentStatus($orderId)
{
return array(
'success' => true,
'history' => array(
array(
'id' => 654,
'createdAt' => '2018-01-01 00:00:00',
'source' => 'user',
'user' => array(
'id' => 1
),
'field' => 'full_paid_at',
'oldValue' => null,
'newValue' => '2018-01-01 00:00:00',
'order' => array(
'id' => 1,
'externalId' => $orderId,
'site' => 'test-com',
'status' => 'new'
)
),
array(
'id'=> 655,
'createdAt' => '2018-01-01 00:00:00',
'source' => 'user',
'user' => array(
'id' => 1
),
'field' => 'payments.paid_at',
'oldValue' => null,
'newValue' => '2018-01-01 00:00:00',
'order' => array(
'id' => 1,
'externalId' => $orderId,
'site' => 'test-com',
'status' => 'new'
),
'payment'=> array(
'id'=> 102,
'type'=> 'cheque',
'externalId' => 1
)
),
array(
'id' => 656,
'createdAt' => '2018-01-01 00:00:00',
'source' => 'user',
'user' => array(
'id' => 1
),
'field' => 'payments.status',
'oldValue' => array(
'code' => 'not-paid'
),
'newValue' => array(
'code' => 'paid'
),
'order' => array(
'id' => 1,
'externalId' => $orderId,
'site' => 'test-com',
'status' => 'new'
),
'payment' => array(
'id' => 102,
'type' => 'cheque',
'externalId' => 1
)
)
)
);
}
}

View File

@ -92,7 +92,7 @@ class RetailCRMTest extends RetailcrmTestCase
$status = new StdClass(); $status = new StdClass();
if ($newOrder === false) { if ($newOrder === false) {
$status->id = 'completed'; $status->id = 11;
$params = array( $params = array(
'newOrderStatus' => $status, 'newOrderStatus' => $status,

View File

@ -7,6 +7,7 @@ require_once dirname(__DIR__) . '../../retailcrm/bootstrap.php';
require_once __DIR__ . '/../../retailcrm/retailcrm.php'; require_once __DIR__ . '/../../retailcrm/retailcrm.php';
require_once __DIR__ . '/../helpers/RetailcrmTestCase.php'; require_once __DIR__ . '/../helpers/RetailcrmTestCase.php';
require_once __DIR__ . '/../helpers/RetailcrmTestHelper.php'; require_once __DIR__ . '/../helpers/RetailcrmTestHelper.php';
require_once dirname(__DIR__) . '../../../PrestaShop/init.php';
$module = new RetailCRM(); $module = new RetailCRM();
$module->install(); $module->install();