1
0
mirror of synced 2024-11-22 04:56:07 +03:00

Merge pull request #3 from Evgeniy-Goroh/master

API v4 and order history
This commit is contained in:
Alex Lushpai 2017-03-16 14:14:13 +03:00 committed by GitHub
commit 8c51adafed
23 changed files with 2604 additions and 716 deletions

View File

@ -0,0 +1,51 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Button extends Mage_Adminhtml_Block_System_Config_Form_Field
{
/**
* Set template
*/
protected function _construct()
{
parent::_construct();
$this->setTemplate('retailcrm/system/config/button.phtml');
}
/**
* Return element html
*
* @param Varien_Data_Form_Element_Abstract $element
* @return string
*/
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
return $this->_toHtml();
}
/**
* Return ajax url for button
*
* @return string
*/
public function getAjaxCheckUrl()
{
return Mage::helper('adminhtml')->getUrl('adminhtml/adminhtml_Retailcrmbutton/check');
}
/**
* Generate button html
*
* @return string
*/
public function getButtonHtml()
{
$button = $this->getLayout()->createBlock('adminhtml/widget_button')
->setData(
array(
'id' => 'Retailcrmbutton_button',
'label' => $this->helper('adminhtml')->__('Run now'),
'onclick' => 'javascript:check(); return false;'
)
);
return $button->toHtml();
}
}

View File

@ -6,30 +6,37 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base exten
protected $_apiKey;
protected $_apiUrl;
protected $_isCredentialCorrect;
public function __construct()
{
parent::__construct();
$this->_apiUrl = Mage::getStoreConfig('retailcrm/general/api_url');
$this->_apiKey = Mage::getStoreConfig('retailcrm/general/api_key');
$this->_isCredentialCorrect = false;
if (!empty($this->_apiUrl) && !empty($this->_apiKey)) {
$client = Mage::getModel(
'retailcrm/ApiClient',
array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null)
);
try {
$response = $client->sitesList();
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
if (false === stripos($this->_apiUrl, 'https://')) {
$this->_apiUrl = str_replace("http://", "https://", $this->_apiUrl);
Mage::getModel('core/config')->saveConfig('retailcrm/general/api_url', $this->_apiUrl);
}
$client = new Retailcrm_Retailcrm_Model_ApiClient(
$this->_apiUrl,
$this->_apiKey
);
try {
$response = $client->sitesList();
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($response->isSuccessful()) {
$this->_isCredentialCorrect = true;
if($response['success'] != 1) {
Mage::getModel('core/config')->saveConfig('retailcrm/general/api_url', '');
}
}
}
}

View File

@ -0,0 +1,10 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Order extends Mage_Adminhtml_Block_System_Config_Form_Fieldset
{
protected $_numberOrder;
public function __construct()
{
}
}

View File

@ -25,6 +25,7 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Payment ex
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
}
return $this->_fieldRenderer;
}
@ -34,9 +35,9 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Payment ex
protected function _getValues()
{
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$client = Mage::getModel(
'retailcrm/ApiClient',
array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null)
$client = new Retailcrm_Retailcrm_Model_ApiClient(
$this->_apiUrl,
$this->_apiKey
);
try {
@ -70,8 +71,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Payment ex
$inherit = true;
}
$field = $fieldset->addField('payment_' . $group->getId(), 'select',
$field = $fieldset->addField(
'payment_' . $group->getId(), 'select',
array(
'name' => 'groups[payment][fields]['.$group->getId().'][value]',
'label' => Mage::getStoreConfig('payment/'.$group->getId().'/title'),
@ -80,7 +81,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Payment ex
'inherit' => $inherit,
'can_use_default_value' => 1,
'can_use_website_value' => 1
))->setRenderer($this->_getFieldRenderer());
)
)->setRenderer($this->_getFieldRenderer());
return $field->toHtml();
}

View File

@ -4,7 +4,7 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e
public function render(Varien_Data_Form_Element_Abstract $element)
{
$html = $this->_getHeaderHtml($element);
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$groups = Mage::getSingleton('shipping/config')->getActiveCarriers();
@ -25,6 +25,7 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
}
return $this->_fieldRenderer;
}
@ -34,9 +35,9 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e
protected function _getValues()
{
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$client = Mage::getModel(
'retailcrm/ApiClient',
array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null)
$client = new Retailcrm_Retailcrm_Model_ApiClient(
$this->_apiUrl,
$this->_apiKey
);
try {
@ -52,7 +53,6 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e
}
}
}
}
return $this->_values;
@ -71,8 +71,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e
$inherit = true;
}
$field = $fieldset->addField('shipping_' . $group->getId(), 'select',
$field = $fieldset->addField(
'shipping_' . $group->getId(), 'select',
array(
'name' => 'groups[shipping][fields]['.$group->getId().'][value]',
'label' => Mage::getStoreConfig('carriers/'.$group->getId().'/title'),
@ -81,7 +81,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e
'inherit' => $inherit,
'can_use_default_value' => 1,
'can_use_website_value' => 1
))->setRenderer($this->_getFieldRenderer());
)
)->setRenderer($this->_getFieldRenderer());
return $field->toHtml();
}

View File

@ -1,13 +1,11 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status extends Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base
{
public function render(Varien_Data_Form_Element_Abstract $element)
{
$html = $this->_getHeaderHtml($element);
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$statuses = Mage::getModel('sales/order_status')->getResourceCollection()->getData();
foreach ($statuses as $status) {
@ -27,6 +25,7 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status ext
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
}
return $this->_fieldRenderer;
}
@ -36,9 +35,9 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status ext
protected function _getValues()
{
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$client = Mage::getModel(
'retailcrm/ApiClient',
array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null)
$client = new Retailcrm_Retailcrm_Model_ApiClient(
$this->_apiUrl,
$this->_apiKey
);
try {
@ -54,7 +53,6 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status ext
}
}
}
}
return $this->_values;
@ -73,7 +71,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status ext
$inherit = true;
}
$field = $fieldset->addField('status_' . $group['status'], 'select',
$field = $fieldset->addField(
'status_' . $group['status'], 'select',
array(
'name' => 'groups[status][fields]['.$group['status'].'][value]',
'label' => $group['label'],
@ -82,7 +81,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status ext
'inherit' => $inherit,
'can_use_default_value' => 1,
'can_use_website_value' => 1
))->setRenderer($this->_getFieldRenderer());
)
)->setRenderer($this->_getFieldRenderer());
return $field->toHtml();
}

View File

@ -78,18 +78,13 @@ class Retailcrm_Retailcrm_Helper_Data extends Mage_Core_Helper_Abstract
*
* @return string
*/
public function rewrittenProductUrl(
$baseUrl,
$coreUrl,
$productId,
$storeId,
$categoryId = null
)
public function rewrittenProductUrl($baseUrl,$coreUrl,$productId,$storeId,$categoryId = null)
{
$idPath = sprintf('product/%d', $productId);
if ($categoryId) {
$idPath = sprintf('%s/%d', $idPath, $categoryId);
}
$coreUrl->setStoreId($storeId);
$coreUrl->loadByIdPath($idPath);
@ -165,6 +160,7 @@ class Retailcrm_Retailcrm_Helper_Data extends Mage_Core_Helper_Abstract
if (is_array($value)) {
$haystack[$key] = self::filterRecursive($haystack[$key]);
}
if (is_null($haystack[$key])
|| $haystack[$key] === ''
|| count($haystack[$key]) == 0

File diff suppressed because it is too large Load Diff

View File

@ -29,9 +29,8 @@ class Retailcrm_Retailcrm_Model_Customer extends Retailcrm_Retailcrm_Model_Excha
'firstName' => $data->getFirstname(),
'patronymic' => $data->getMiddlename(),
'lastName' => $data->getLastname(),
'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt()))
'createdAt' => Mage::getSingleton('core/date')->date()
);
$this->_api->customersEdit($customer);
}
@ -51,8 +50,7 @@ class Retailcrm_Retailcrm_Model_Customer extends Retailcrm_Retailcrm_Model_Excha
->addAttributeToSelect('email')
->addAttributeToSelect('firstname')
->addAttributeToSelect('lastname');
foreach ($customerCollection as $customerData)
{
foreach ($customerCollection as $customerData) {
$customer = array(
'externalId' => $customerData->getId(),
'email' => $customerData->getData('email'),
@ -61,15 +59,17 @@ class Retailcrm_Retailcrm_Model_Customer extends Retailcrm_Retailcrm_Model_Excha
);
$customers[] = $customer;
}
unset($customerCollection);
$chunked = array_chunk($customers, 50);
unset($customers);
foreach ($chunked as $chunk) {
//file_put_contents('/var/www/konzeptual/data/www/konzeptual.ru/tempC.txt', var_export($chunk,true)); die();
foreach ($chunked as $chunk) {
$this->_api->customersUpload($chunk);
time_nanosleep(0, 250000000);
}
unset($chunked);
return true;
}
}

View File

@ -6,55 +6,76 @@ class Retailcrm_Retailcrm_Model_Exchange
protected $_apiUrl;
protected $_config;
protected $_api;
public function __construct()
{
$this->_apiUrl = Mage::getStoreConfig('retailcrm/general/api_url');
$this->_apiKey = Mage::getStoreConfig('retailcrm/general/api_key');
if(!empty($this->_apiUrl) && !empty($this->_apiKey)) {
$this->_api = Mage::getModel(
'retailcrm/ApiClient',
array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null)
$this->_api = new Retailcrm_Retailcrm_Model_ApiClient(
$this->_apiUrl,
$this->_apiKey
);
}
}
/**
* Get orders history & modify orders into shop
*
*/
/**
* Get orders history & modify orders into shop
*
*/
public function ordersHistory()
{
$runTime = $this->getExchangeTime($this->_config['general']['history']);
try {
$response = $this->_api->ordersHistory($runTime);
if (
$response->isSuccessful()
&&
200 === $response->getStatusCode()
) {
$nowTime = $response->getGeneratedAt();
$this->processOrders($response->orders, $nowTime);
} else {
Mage::log(
sprintf(
"Orders history error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
$historyFilter = array();
$historiOrder = array();
$historyStart = Mage::getStoreConfig('retailcrm/general/fhistory');
if($historyStart && $historyStart > 0) {
$historyFilter['sinceId'] = $historyStart;
}
while(true) {
try {
$response = $this->_api->ordersHistory($historyFilter);
if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
$nowTime = $response->getGeneratedAt();
} else {
Mage::log(
sprintf("Orders history error: [HTTP status %s] %s", $response->getStatusCode(), $response->getErrorMsg())
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
return false;
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
return false;
}
$orderH = isset($response['history']) ? $response['history'] : array();
if(count($orderH) == 0) {
return true;
}
$historiOrder = array_merge($historiOrder, $orderH);
$end = array_pop($response->history);
$historyFilter['sinceId'] = $end['id'];
if($response['pagination']['totalPageCount'] == 1) {
Mage::getModel('core/config')->saveConfig('retailcrm/general/fhistory', $historyFilter['sinceId']);
$orders = self::assemblyOrder($historiOrder);
$this->processOrders($orders, $nowTime);
return true;
}
}//endwhile
}
/**
* @param array $orders
*/
@ -66,28 +87,28 @@ class Retailcrm_Retailcrm_Model_Exchange
);
foreach ($orders as $order) {
if(!empty($order['externalId'])) {
if(!empty($order['externalId'])) {
$this->doUpdate($order);
} else {
$this->doCreate($order);
}
}
die();
}
}
/**
* @param array $order
*/
private function doCreate($order)
{
Mage::log($order, null, 'retailcrmHistoriCreate.log', true);
try {
$response = $this->_api->ordersGet($order['id'], $by = 'id');
if (
$response->isSuccessful()
&&
200 === $response->getStatusCode()
) {
if ($response->isSuccessful() && 200 === $response->getStatusCode()) {
$order = $response->order;
} else {
Mage::log(
@ -105,34 +126,33 @@ class Retailcrm_Retailcrm_Model_Exchange
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
// get references
$this->_config = Mage::getStoreConfig('retailcrm');
$payments = array_flip(array_filter($this->_config['payment']));
$shippings = array_flip(array_filter($this->_config['shipping']));
// get store
$_store = Mage::getModel("core/store")->load($order['site']);
$_siteId = Mage::getModel('core/store')->load($_store->getId())->getWebsiteId();
$_sendConfirmation = '0';
$storeId = Mage::app()->getStore()->getId();
$siteid = Mage::getModel('core/store')->load($storeId)->getWebsiteId();
// search or create customer
$customer = Mage::getSingleton('customer/customer');
$customer->setWebsiteId($_siteId);
$customer->setWebsiteId($siteid);
$customer->loadByEmail($order['email']);
if (!is_numeric($customer->getId())) {
if (!is_numeric($customer->getId())) {
$customer
->setGropuId(1)
->setWebsiteId($_siteId)
->setStore($_store)
->setWebsiteId($siteid)
->setStore($storeId)
->setEmail($order['email'])
->setFirstname($order['firstName'])
->setLastname($order['lastName'])
->setMiddleName($order['patronymic'])
->setPassword(uniqid())
;
->setPassword(uniqid());
try {
$customer->save();
$customer->setConfirmation(null);
@ -149,6 +169,7 @@ class Retailcrm_Retailcrm_Model_Exchange
->setCountryId($this->getCountryCode($order['customer']['address']['country']))
->setPostcode($order['delivery']['address']['index'])
->setCity($order['delivery']['address']['city'])
->setRegion($order['delivery']['address']['region'])
->setTelephone($order['phone'])
->setStreet($order['delivery']['address']['street'])
->setIsDefaultBilling('1')
@ -169,11 +190,7 @@ class Retailcrm_Retailcrm_Model_Exchange
'externalId' => $customer->getId()
)
);
if (
!$response->isSuccessful()
||
200 !== $response->getStatusCode()
) {
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
Mage::log(
sprintf(
"Orders fix error: [HTTP status %s] %s",
@ -189,18 +206,17 @@ class Retailcrm_Retailcrm_Model_Exchange
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
$products = array();
foreach ($order['items'] as $item) {
$products[$item['offer']['externalId']] = array('qty' => $item['quantity']);
}
$orderData = array(
'session' => array(
'customer_id' => $customer->getId(),
'store_id' => $_store->getId(),
'store_id' => $storeId,
),
'payment' => array(
'method' => $payments[$order['paymentType']],
@ -215,11 +231,11 @@ class Retailcrm_Retailcrm_Model_Exchange
'firstname' => $order['firstName'],
'middlename' => $order['patronymic'],
'lastname' => $order['lastName'],
'street' => $order['customer']['address']['street'],
'city' => $order['customer']['address']['city'],
'street' => $order['delivery']['address']['street'],
'city' => $order['delivery']['address']['city'],
'country_id' => $this->getCountryCode($order['customer']['address']['country']),
'region' => $order['customer']['address']['region'],
'postcode' => $order['customer']['address']['index'],
'region' => $order['delivery']['address']['region'],
'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'],
),
'shipping_address' => array(
@ -244,44 +260,49 @@ class Retailcrm_Retailcrm_Model_Exchange
Mage::unregister('sales_order_place_after');
Mage::register('sales_order_place_after', 1);
$quote = Mage::getModel('sales/quote')->setStoreId($_store->getId());
$quote = Mage::getModel('sales/quote')->setStoreId($storeId);
$quote->assignCustomer($customer);
$quote->setSendCconfirmation($_sendConfirmation);
foreach($_products as $idx => $val) {
foreach($products as $idx => $val) {
$product = Mage::getModel('catalog/product')->load($idx);
$quote->addProduct($product, new Varien_Object($val));
}
$quote->getBillingAddress()->addData($orderData['order']['billing_address']);
$shipping_method = self::getAllShippingMethodsCode($orderData['order']['shipping_method']);
$billingAddress = $quote->getBillingAddress()->addData($orderData['order']['billing_address']);
$shippingAddress = $quote->getShippingAddress()->addData($orderData['order']['shipping_address']);
$shippingAddress
->collectTotals()
->setCollectShippingRates(true)
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod($orderData['order']['shipping_method'])
->setpaymentMethod($orderData['payment']['method'])
;
->setShippingMethod($shipping_method)
->setPaymentMethod($orderData['payment']['method']);
$quote->getPayment()->importData($orderData['payment']);
$quote->setTotalsCollectedFlag(false)->collectTotals()->save();
$quote->collectTotals();
$quote->reserveOrderId();
$quote->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
try{
$service->submitAll();
}
catch (Exception $e) {
Mage::log($e->getMessage());
}
try {
$response = $this->_api->ordersFixExternalIds(
array(
'id' => $order['id'],
'externalId' => $service->getOrder()->getId()
array(
'id' => $order['id'],
'externalId' =>$service->getOrder()->getRealOrderId()
)
)
);
if (
!$response->isSuccessful()
||
200 !== $response->getStatusCode()
) {
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
Mage::log(
sprintf(
"Orders fix error: [HTTP status %s] %s",
@ -296,75 +317,377 @@ class Retailcrm_Retailcrm_Model_Exchange
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
Mage::log("Create: " . $order['externalId'], null, 'history.log');
}
}
/**
* @param array $order
*/
private function doUpdate($order)
private function doCreateUp($order)
{
$magentoOrder = Mage::getModel('sales/order')->load($order['externalId']);
if (!empty($order['status'])) {
try {
$response = $this->_api->statusesList();
if (
$response->isSuccessful()
&&
200 === $response->getStatusCode()
) {
$code = $order['status'];
$group = $response->statuses[$code]['group'];
if (in_array($group, array('approval', 'assembling', 'delivery'))) {
$magentoOrder->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true);
$magentoOrder->save();
$invoice = $magentoOrder->prepareInvoice()
->setTransactionId($magentoOrder->getId())
->register()
->pay();
$transaction_save = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction_save->save();
}
if (in_array($group, array('complete'))) {
$itemQty = $magentoOrder->getItemsCollection()->count();
Mage::getModel('sales/service_order', $magentoOrder)->prepareShipment($itemQty);
$shipment = new Mage_Sales_Model_Order_Shipment_Api();
$shipment->create($order['externalId']);
}
if (in_array($group, array('cancel'))) {
$magentoOrder->setState(Mage_Sales_Model_Order::STATE_CANCELED, true);
$magentoOrder->save();
}
Mage::log("Update: " . $order['externalId'], null, 'history.log');
} else {
Mage::log($order, null, 'retailcrmHistoriCreateUp.log', true);
try {
$response = $this->_api->ordersGet($order['id'], $by = 'id');
if ($response->isSuccessful() && 200 === $response->getStatusCode()) {
$order = $response->order;
} else {
Mage::log(
sprintf(
"Statuses list error: [HTTP status %s] %s",
"Orders get error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
// get references
$this->_config = Mage::getStoreConfig('retailcrm');
$payments = array_flip(array_filter($this->_config['payment']));
$shippings = array_flip(array_filter($this->_config['shipping']));
// get store
$_sendConfirmation = '0';
$storeId = Mage::app()->getStore()->getId();
$siteid = Mage::getModel('core/store')->load($storeId)->getWebsiteId();
// search or create customer
$customer = Mage::getSingleton('customer/customer');
$customer->setWebsiteId($siteid);
$customer->loadByEmail($order['email']);
if (!is_numeric($customer->getId())) {
$customer
->setGropuId(1)
->setWebsiteId($siteid)
->setStore($storeId)
->setEmail($order['email'])
->setFirstname($order['firstName'])
->setLastname($order['lastName'])
->setMiddleName($order['patronymic'])
->setPassword(uniqid());
try {
$customer->save();
$customer->setConfirmation(null);
$customer->save();
} catch (Exception $e) {
Mage::log($e->getMessage());
}
$address = Mage::getModel("customer/address");
$address->setCustomerId($customer->getId())
->setFirstname($customer->getFirstname())
->setMiddleName($customer->getMiddlename())
->setLastname($customer->getLastname())
->setCountryId($this->getCountryCode($order['customer']['address']['country']))
->setPostcode($order['delivery']['address']['index'])
->setCity($order['delivery']['address']['city'])
->setRegion($order['delivery']['address']['region'])
->setTelephone($order['phone'])
->setStreet($order['delivery']['address']['street'])
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try{
$address->save();
}
catch (Exception $e) {
Mage::log($e->getMessage());
}
try {
$response = $this->_api->customersFixExternalIds(
array(
'id' => $order['customer']['id'],
'externalId' => $customer->getId()
)
);
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
Mage::log(
sprintf(
"Orders fix error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
$products = array();
foreach ($order['items'] as $item) {
$products[$item['offer']['externalId']] = array('qty' => $item['quantity']);
}
$orderData = array(
'session' => array(
'customer_id' => $customer->getId(),
'store_id' => $storeId,
),
'payment' => array(
'method' => $payments[$order['paymentType']],
),
'add_products' => $products,
'order' => array(
'account' => array(
'group_id' => $customer->getGroupId(),
'email' => $order['email']
),
'billing_address' => array(
'firstname' => $order['firstName'],
'middlename' => $order['patronymic'],
'lastname' => $order['lastName'],
'street' => $order['delivery']['address']['street'],
'city' => $order['delivery']['address']['city'],
'country_id' => $this->getCountryCode($order['customer']['address']['country']),
'region' => $order['delivery']['address']['region'],
'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'],
),
'shipping_address' => array(
'firstname' => $order['firstName'],
'middlename' => $order['patronymic'],
'lastname' => $order['lastName'],
'street' => $order['delivery']['address']['street'],
'city' => $order['delivery']['address']['city'],
'country_id' => $this->getCountryCode($order['customer']['address']['country']),
'region' => $order['delivery']['address']['region'],
'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'],
),
'shipping_method' => $shippings[$order['delivery']['code']],
'comment' => array(
'customer_note' => $order['customerComment'],
),
'send_confirmation' => $_sendConfirmation
)
);
$quote = Mage::getModel('sales/quote')->setStoreId($storeId);
$quote->assignCustomer($customer);
$quote->setSendCconfirmation($_sendConfirmation);
foreach($products as $idx => $val) {
$product = Mage::getModel('catalog/product')->load($idx);
$quote->addProduct($product, new Varien_Object($val));
}
$shipping_method = self::getAllShippingMethodsCode($orderData['order']['shipping_method']);
$billingAddress = $quote->getBillingAddress()->addData($orderData['order']['billing_address']);
$shippingAddress = $quote->getShippingAddress()->addData($orderData['order']['shipping_address']);
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod($shipping_method)
->setPaymentMethod($orderData['payment']['method']);
$quote->getPayment()->importData($orderData['payment']);
$quote->collectTotals();
$originalId = $order['externalId'];
$oldOrder = Mage::getModel('sales/order')->loadByIncrementId($originalId);
$oldOrderArr = $oldOrder->getData();
if(!empty($oldOrderArr['original_increment_id'])) {
$originalId = $oldOrderArr['original_increment_id'];
}
$orderDataUp = array(
'original_increment_id' => $originalId,
'relation_parent_id' => $oldOrder->getId(),
'relation_parent_real_id' => $oldOrder->getIncrementId(),
'edit_increment' => $oldOrder->getEditIncrement()+1,
'increment_id' => $originalId.'-'.($oldOrder->getEditIncrement()+1)
);
$quote->setReservedOrderId($orderDataUp['increment_id']);
$quote->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->setOrderData($orderDataUp);
try{
$service->submitAll();
}
catch (Exception $e) {
Mage::log($e->getMessage());
}
$magentoOrder = Mage::getModel('sales/order')->loadByIncrementId($orderDataUp['relation_parent_real_id']);
$magentoOrder->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save();
try {
$response = $this->_api->ordersFixExternalIds(
array(
array(
'id' => $order['id'],
'externalId' =>$service->getOrder()->getRealOrderId()
)
)
);
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
Mage::log(
sprintf(
"Orders fix error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
/**
* @param array $order
*/
private function doUpdate($order)
{
$magentoOrder = Mage::getModel('sales/order')->loadByIncrementId($order['externalId']);
$magentoOrderArr = $magentoOrder->getData();
$config = Mage::getStoreConfig('retailcrm');
Mage::log($order, null, 'retailcrmHistoriUpdate.log', true);
if((!empty($order['order_edit']))&&($order['order_edit'] == 1)) {
$this->doCreateUp($order);
}
if (!empty($order['status'])) {
try {
$response = $this->_api->statusesList();
if ($response->isSuccessful() && 200 === $response->getStatusCode()) {
$code = $order['status'];
$group = $response->statuses[$code]['group'];
if ($magentoOrder->hasInvoices()) {
$invIncrementIDs = array();
foreach ($magentoOrder->getInvoiceCollection() as $inv) {
$invIncrementIDs[] = $inv->getIncrementId();
}
}
if (in_array($group, array('approval', 'assembling', 'delivery'))) {
if(empty($invIncrementIDs)) {
$magentoOrder->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true);
$magentoOrder->save();
$invoice = $magentoOrder->prepareInvoice()
->setTransactionId($magentoOrder->getRealOrderId())
->addComment("Add status on CRM")
->register()
->pay();
$transaction_save = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction_save->save();
}
}
if (in_array($group, array('complete'))) {
if(empty($invIncrementIDs)){
$invoice = $magentoOrder->prepareInvoice()
->setTransactionId($magentoOrder->getRealOrderId())
->addComment("Add status on CRM")
->register()
->pay();
$transaction_save = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction_save->save();
$magentoOrder->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
}
if($magentoOrder->canShip()) {
$itemQty = $magentoOrder->getItemsCollection()->count();
$shipment = Mage::getModel('sales/service_order', $magentoOrder)->prepareShipment($itemQty);
$shipment = new Mage_Sales_Model_Order_Shipment_Api();
$shipmentId = $shipment->create($order['externalId']);
}
}
if($code == $config['status']['canceled']) {
$magentoOrder->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save();
}
if($code == $config['status']['holded']) {
if($magentoOrder->canHold()){
$magentoOrder->hold()->save();
}
}
if($code == $config['status']['unhold']) {
if($magentoOrder->canUnhold()) {
$magentoOrder->unhold()->save();
}
}
if($code == $config['status']['closed']) {
if($magentoOrder->canCreditmemo()) {
$orderItem = $magentoOrder->getItemsCollection();
foreach ($orderItem as $item) {
$data['qtys'][$item->getid()] = $item->getQtyOrdered();
}
$service = Mage::getModel('sales/service_order', $magentoOrder);
$creditMemo = $service->prepareCreditmemo($data)->register()->save();
$magentoOrder->addStatusToHistory(Mage_Sales_Model_Order::STATE_CLOSED, 'Add status on CRM', false);
$magentoOrder->save();
}
}
Mage::log("Update: " . $order['externalId'], null, 'history.log');
} else {
Mage::log(
sprintf(
"Statuses list error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
if(!empty($order['manager_comment'])) {
$magentoOrder->addStatusHistoryComment($order['manager_comment']);
$magentoOrder->save();
}
}
/**
@ -497,4 +820,162 @@ class Retailcrm_Retailcrm_Model_Exchange
return (string) $country;
}
public static function assemblyOrder($orderHistory)
{
$orders = array();
foreach ($orderHistory as $change) {
$change['order'] = self::removeEmpty($change['order']);
if($change['order']['items']) {
$items = array();
foreach($change['order']['items'] as $item) {
if(isset($change['created'])) {
$item['create'] = 1;
}
$items[$item['id']] = $item;
}
$change['order']['items'] = $items;
}
Mage::log($change, null, 'retailcrmHistoryAssemblyOrder.log', true);
if($change['order']['contragent']['contragentType']) {
$change['order']['contragentType'] = self::newValue($change['order']['contragent']['contragentType']);
unset($change['order']['contragent']);
}
if($orders[$change['order']['id']]) {
$orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']);
}
else {
$orders[$change['order']['id']] = $change['order'];
}
if($change['field'] == 'manager_comment'){
$orders[$change['order']['id']][$change['field']] = $change['newValue'];
}
if(($change['field'] != 'status')&&
($change['field'] != 'country')&&
($change['field'] != 'manager_comment')&&
($change['field'] != 'order_product.status')&&
($change['field'] != 'payment_status')&&
($change['field'] != 'prepay_sum')
) {
$orders[$change['order']['id']]['order_edit'] = 1;
}
if($change['item']) {
if($orders[$change['order']['id']]['items'][$change['item']['id']]) {
$orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']);
}
else{
$orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
}
if(empty($change['oldValue']) && $change['field'] == 'order_product') {
$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = 1;
$orders[$change['order']['id']]['order_edit'] = 1;
unset($orders[$change['order']['id']]['items'][$change['item']['id']]['delete']);
}
if(empty($change['newValue']) && $change['field'] == 'order_product') {
$orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = 1;
$orders[$change['order']['id']]['order_edit'] = 1;
}
if(!empty($change['newValue']) && $change['field'] == 'order_product.quantity') {
$orders[$change['order']['id']]['order_edit'] = 1;
}
if(!$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] && $fields['item'][$change['field']]) {
$orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue'];
}
}
else {
if($fields['delivery'][$change['field']] == 'service') {
$orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']);
}
elseif($fields['delivery'][$change['field']]) {
$orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']);
}
elseif($fields['orderAddress'][$change['field']]) {
$orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue'];
}
elseif($fields['integrationDelivery'][$change['field']]) {
$orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']);
}
elseif($fields['customerContragent'][$change['field']]) {
$orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']);
}
elseif(strripos($change['field'], 'custom_') !== false) {
$orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
}
elseif($fields['order'][$change['field']]) {
$orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
}
if(isset($change['created'])) {
$orders[$change['order']['id']]['create'] = 1;
}
if(isset($change['deleted'])) {
$orders[$change['order']['id']]['deleted'] = 1;
}
}
}
return $orders;
}
public static function removeEmpty($inputArray)
{
$outputArray = array();
if (!empty($inputArray)) {
foreach ($inputArray as $key => $element) {
if(!empty($element) || $element === 0 || $element === '0') {
if (is_array($element)) {
$element = self::removeEmpty($element);
}
$outputArray[$key] = $element;
}
}
}
return $outputArray;
}
public static function newValue($value)
{
if(isset($value['code'])) {
return $value['code'];
} else{
return $value;
}
}
public static function getAllShippingMethodsCode($code)
{
$methods = Mage::getSingleton('shipping/config')->getActiveCarriers();
$options = array();
foreach($methods as $_ccode => $_carrier) {
if($_methods = $_carrier->getAllowedMethods()) {
foreach($_methods as $_mcode => $_method) {
$_code = $_ccode . '_' . $_mcode;
$options[$_ccode] = $_code;
}
}
}
return $options[$code];
}
}

View File

@ -1,7 +1,15 @@
<?php
/**
* PHP version 5.3
*
* HTTP client
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class Retailcrm_Retailcrm_Model_Http_Client
{
@ -11,78 +19,84 @@ class Retailcrm_Retailcrm_Model_Http_Client
protected $url;
protected $defaultParameters;
/**
* Client constructor.
*
* @param string $url api url
* @param array $defaultParameters array of parameters
*
* @throws \InvalidArgumentException
*/
public function __construct($url, array $defaultParameters = array())
{
if (false === stripos($url, 'https://')) {
throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('API schema requires HTTPS protocol');
throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException(
'API schema requires HTTPS protocol'
);
}
$this->url = $url;
$this->defaultParameters = $defaultParameters;
$this->retry = 0;
}
/**
* Make HTTP request
*
* @param string $path
* @param string $method (default: 'GET')
* @param array $parameters (default: array())
* @param int $timeout
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
* @param string $path request url
* @param string $method (default: 'GET')
* @param array $parameters (default: array())
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*
* @throws \InvalidArgumentException
* @throws CurlException
* @throws InvalidJsonException
*
* @return ApiResponse
*/
public function makeRequest($path, $method, array $parameters = array(), $timeout = 90)
public function makeRequest($path,$method,array $parameters = array())
{
$allowedMethods = array(self::METHOD_GET, self::METHOD_POST);
if (!in_array($method, $allowedMethods)) {
throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException(sprintf(
'Method "%s" is not valid. Allowed methods are %s',
$method,
implode(', ', $allowedMethods)
));
if (!in_array($method, $allowedMethods, false)) {
throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException(
sprintf(
'Method "%s" is not valid. Allowed methods are %s',
$method,
implode(', ', $allowedMethods)
)
);
}
$parameters = array_merge($this->defaultParameters, $parameters);
$url = $this->url . $path;
if (self::METHOD_GET === $method && sizeof($parameters)) {
$url .= '?' . http_build_query($parameters);
if (self::METHOD_GET === $method && count($parameters)) {
$url .= '?' . http_build_query($parameters, '', '&');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, (int) $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (int) $timeout);
$curlHandler = curl_init();
curl_setopt($curlHandler, CURLOPT_URL, $url);
curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curlHandler, CURLOPT_FAILONERROR, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curlHandler, CURLOPT_TIMEOUT, 30);
curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, 30);
if (self::METHOD_POST === $method) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($curlHandler, CURLOPT_POST, true);
curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $parameters);
}
$responseBody = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$errno = curl_errno($ch);
$error = curl_error($ch);
$responseBody = curl_exec($curlHandler);
$statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE);
$errno = curl_errno($curlHandler);
$error = curl_error($curlHandler);
curl_close($ch);
if ($errno && in_array($errno, array(6, 7, 28, 34, 35)) && $this->retry < 3) {
$errno = null;
$error = null;
$this->retry += 1;
$this->makeRequest(
$path,
$method,
$parameters,
$timeout
);
}
curl_close($curlHandler);
if ($errno) {
throw new Retailcrm_Retailcrm_Model_Exception_CurlException($error, $errno);

View File

@ -10,7 +10,7 @@ class Retailcrm_Retailcrm_Model_Icml
public function generate($shop)
{
$this->_shop = $shop;
$string = '<?xml version="1.0" encoding="UTF-8"?>
<yml_catalog date="'.date('Y-m-d H:i:s').'">
<shop>
@ -43,6 +43,7 @@ class Retailcrm_Retailcrm_Model_Icml
$baseDir = Mage::getBaseDir();
$shopCode = Mage::app()->getStore($shop)->getCode();
$this->_dd->save($baseDir . DS . 'retailcrm_' . $shopCode . '.xml');
}
private function addCategories()
@ -82,14 +83,15 @@ class Retailcrm_Retailcrm_Model_Icml
$e->setAttribute('parentId', $category['parentId']);
}
}
}
}
private function addOffers()
{
$offers = array();
$helper = Mage::helper('retailcrm');
$picUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
$baseUrl = Mage::getBaseUrl();
$customAdditionalAttributes = Mage::getStoreConfig('retailcrm/attributes_to_export_into_icml');
$customAdditionalAttributes = explode(',', $customAdditionalAttributes);
@ -97,8 +99,11 @@ class Retailcrm_Retailcrm_Model_Icml
->getCollection()
->addAttributeToSelect('*')
->addUrlRewrite();
$collection->addFieldToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
$collection->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('type_id', array('eq' => 'simple'));
foreach ($collection as $product) {
/** @var Mage_Catalog_Model_Product $product */
$offer = array();
@ -109,13 +114,8 @@ class Retailcrm_Retailcrm_Model_Icml
$offer['name'] = $product->getName();
$offer['productName'] = $product->getName();
$offer['initialPrice'] = (float) $product->getPrice();
$offer['url'] = $helper->rewrittenProductUrl(
$product->getId(), $product->getCategoryId(), $this->_shop
);
$offer['url'] = $product->getProductUrl();
$offer['picture'] = $picUrl.'catalog/product'.$product->getImage();
$offer['quantity'] = Mage::getModel('cataloginventory/stock_item')
->loadByProduct($product)->getQty();
@ -188,6 +188,7 @@ class Retailcrm_Retailcrm_Model_Icml
foreach($attributes AS $attributeName=>$attributeValue) {
$attributesString[] = $attributeName.': '.$attributeValue;
}
$attributesString = ' (' . implode(', ', $attributesString) . ')';
$offer = array();
@ -198,13 +199,8 @@ class Retailcrm_Retailcrm_Model_Icml
$offer['name'] = $associatedProduct->getName().$attributesString;
$offer['productName'] = $product->getName();
$offer['initialPrice'] = (float) $associatedProduct->getFinalPrice();
$offer['url'] = $helper->rewrittenProductUrl(
$associatedProduct->getId(), $associatedProduct->getCategoryId(), $this->_shop
);
$offer['url'] = $associatedProduct->getProductUrl();
$offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage();
$offer['quantity'] = Mage::getModel('cataloginventory/stock_item')
->loadByProduct($associatedProduct)->getQty();
@ -273,7 +269,6 @@ class Retailcrm_Retailcrm_Model_Icml
}
foreach ($offers as $offer) {
$e = $this->_eOffers->appendChild(
$this->_dd->createElement('offer')
);
@ -322,9 +317,8 @@ class Retailcrm_Retailcrm_Model_Icml
if (!empty($offer['purchasePrice'])) {
$e->appendChild($this->_dd->createElement('purchasePrice'))
->appendChild(
$this->_dd->createTextNode($offer['purchasePrice']
)
);
$this->_dd->createTextNode($offer['purchasePrice'])
);
}
if (!empty($offer['picture'])) {
@ -337,17 +331,15 @@ class Retailcrm_Retailcrm_Model_Icml
if (!empty($offer['url'])) {
$e->appendChild($this->_dd->createElement('url'))
->appendChild(
$this->_dd->createTextNode($offer['url']
)
);
$this->_dd->createTextNode($offer['url'])
);
}
if (!empty($offer['vendor'])) {
$e->appendChild($this->_dd->createElement('vendor'))
->appendChild(
$this->_dd->createTextNode($offer['vendor']
)
);
$this->_dd->createTextNode($offer['vendor'])
);
}
if(!empty($offer['params'])) {

View File

@ -21,14 +21,22 @@ class Retailcrm_Retailcrm_Model_Observer
return true;
}
public function orderUpdate(Varien_Event_Observer $observer)
{
$order = $observer->getEvent()->getOrder();
Mage::getModel('retailcrm/order')->orderUpdate($order);
return true;
}
public function orderStatusHistoryCheck(Varien_Event_Observer $observer)
{
$order = $observer->getEvent()->getOrder();
Mage::getModel('retailcrm/order')->orderStatusHistoryCheck($order);
return true;
}
/**
* Event after customer created
*
@ -47,7 +55,7 @@ class Retailcrm_Retailcrm_Model_Observer
return true;
}
public function exportCatalog()
{
foreach (Mage::app()->getWebsites() as $website) {

View File

@ -24,32 +24,43 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
*/
public function orderPay($orderId)
{
//file_put_contents('/home/user/sites/magento.local/temp1.txt', var_export(1,true));
//Mage::log($order->getId(), null, 'events.log', true);
//file_put_contents('/home/user/sites/magento.local/temp2.txt', var_export(1,true));
//$orderId = $observer->getPayment()->getOrder()->getId();
//file_put_contents('/home/user/sites/magento.local/temp2.txt', var_export($order,true));
$order = Mage::getModel('sales/order')->load($orderId);
//$config = Mage::getModel('retailcrm/settings', $order->getStoreId());
//file_put_contents('/home/user/sites/magento.local/temp.txt', var_export(1,true));
//file_put_contents('/home/user/sites/magento.local/tempE1.txt', var_export($order->getBaseGrandTotal(),true));
//file_put_contents('/home/user/sites/magento.local/tempE2.txt', var_export($order->getTotalPaid(),true));
if((string)$order->getBaseGrandTotal() == (string)$order->getTotalPaid()){
//file_put_contents('/home/user/sites/magento.local/temp1.txt', var_export(2,true));
$preparedOrder = array(
'externalId' => $order->getId(),
'externalId' => $order->getRealOrderId(),//getId(),
'paymentStatus' => 'paid',
//'paymentType' => $config->getMapping($order->getPayment()->getMethodInstance()->getCode(), 'payment'),
//'status' => $config->getMapping($order->getStatus(), 'status'),
);
//file_put_contents('/home/user/sites/magento.local/temp2.txt', var_export($preparedOrder,true));
$preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder);
//file_put_contents('/home/user/sites/magento.local/temp3.txt', var_export($preparedOrder,true));
$this->_api->ordersEdit($preparedOrder);
}
//file_put_contents('/home/user/sites/magento.local/temp.txt', var_export($preparedOrder,true));
}
public function orderStatusHistoryCheck($order)
{
$config = Mage::getModel(
'retailcrm/settings',
array(
'storeId' =>$order->getStoreId()
)
);
$preparedOrder = array(
'externalId' => $order->getRealOrderId(),//getId(),
'status' => $config->getMapping($order->getStatus(), 'status'),
);
$comment = $order->getStatusHistoryCollection()->getData();
if(!empty($comment[0]['comment'])) {
$preparedOrder['managerComment'] = $comment[0]['comment'];
}
$preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder);
$this->_api->ordersEdit($preparedOrder);
}
public function orderUpdate($order)
{
$config = Mage::getModel(
@ -59,25 +70,24 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
)
);
$preparedOrder = array(
'externalId' => $order->getId(),
'externalId' => $order->getRealOrderId(),//getId(),
'status' => $config->getMapping($order->getStatus(), 'status'),
);
if((float)$order->getBaseGrandTotal() == (float)$order->getTotalPaid()){
if((float)$order->getBaseGrandTotal() == (float)$order->getTotalPaid()) {
$preparedOrder['paymentStatus'] = 'paid';
$preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder);
$this->_api->ordersEdit($preparedOrder);
}
$preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder);
$this->_api->ordersEdit($preparedOrder);
}
public function orderCreate($order)
{
$config = Mage::getModel('retailcrm/settings', [
'storeId' => $order->getStoreId()
]);
$config = Mage::getModel('retailcrm/settings', ['storeId' => $order->getStoreId()]);
$address = $order->getShippingAddress()->getData();
$orderItems = $order->getItemsCollection()
->addAttributeToSelect('*')
//->addAttributeToFilter('product_type', array('eq'=>'simple'))
->addAttributeToFilter('product_type', array('eq'=>'simple'))
->load();
$items = array();
@ -91,7 +101,10 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
'productId' => $item->getProductId(),
'productName' => !isset($parent) ? $item->getName() : $parent->getName(),
'quantity' => !isset($parent) ? intval($item->getQtyOrdered()) : intval($parent->getQtyOrdered()),
'initialPrice' => !isset($parent) ? $item->getPrice() : $parent->getPrice()
'initialPrice' => !isset($parent) ? $item->getPrice() : $parent->getPrice(),
'offer'=>array(
'externalId'=>$item->getProductId()
)
);
unset($parent);
@ -101,7 +114,10 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
'productId' => $item->getProductId(),
'productName' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'initialPrice' => $item->getPrice()
'initialPrice' => $item->getPrice(),
'offer'=>array(
'externalId'=>$item->getProductId()
)
);
$items[] = $product;
@ -112,9 +128,9 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
$preparedOrder = array(
'site' => $order->getStore()->getCode(),
'externalId' => $order->getId(),
'externalId' => $order->getRealOrderId(),
'number' => $order->getRealOrderId(),
'createdAt' => date_create_from_format("Y-m-d H:i:s", $order->getCreatedAt())->modify('+3 hour')->format("Y-m-d H:i:s"),
'createdAt' => Mage::getModel('core/date')->date(),
'lastName' => $order->getCustomerLastname(),
'firstName' => $order->getCustomerFirstname(),
'patronymic' => $order->getCustomerMiddlename(),
@ -137,34 +153,45 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
'text' => trim(
',',
implode(
',',
array(
$address['postcode'],
$address['city'],
$address['street']
',',
array(
$address['postcode'],
$address['city'],
$address['street']
)
)
)
),
)
);
if(trim($preparedOrder['delivery']['code']) == ''){
unset($preparedOrder['delivery']['code']);
}
if(trim($preparedOrder['paymentType']) == ''){
unset($preparedOrder['paymentType']);
}
if(trim($preparedOrder['status']) == ''){
unset($preparedOrder['status']);
}
if ($order->getCustomerIsGuest() == 0) {
if ($this->_api->customersGet($order->getCustomerId())) {
$preparedCustomer = array(
'externalId' => $order->getCustomerId()
);
if ($this->_api->customersCreate($preparedCustomer)) {
$preparedOrder['customer']['externalId'] = $order->getCustomerId();
}
}
$preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder);
Mage::log($preparedOrder, null, 'retailcrmCreatePreparedOrder.log', true);
try {
$response = $this->_api->ordersCreate($preparedOrder);
if ($response->isSuccessful() && 201 === $response->getStatusCode()) {
@ -187,6 +214,57 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
}
}
public function ordersExportNumber()
{
$config = Mage::getStoreConfig('retailcrm');
$ordersId = explode(",", $config['load_order']['numberOrder']);
$orders = array();
$ordersList = Mage::getResourceModel('sales/order_collection')
->addAttributeToSelect('*')
->joinAttribute('billing_firstname', 'order_address/firstname', 'billing_address_id', null, 'left')
->joinAttribute('billing_lastname', 'order_address/lastname', 'billing_address_id', null, 'left')
->joinAttribute('billing_street', 'order_address/street', 'billing_address_id', null, 'left')
->joinAttribute('billing_company', 'order_address/company', 'billing_address_id', null, 'left')
->joinAttribute('billing_city', 'order_address/city', 'billing_address_id', null, 'left')
->joinAttribute('billing_region', 'order_address/region', 'billing_address_id', null, 'left')
->joinAttribute('billing_country', 'order_address/country_id', 'billing_address_id', null, 'left')
->joinAttribute('billing_postcode', 'order_address/postcode', 'billing_address_id', null, 'left')
->joinAttribute('billing_telephone', 'order_address/telephone', 'billing_address_id', null, 'left')
->joinAttribute('billing_fax', 'order_address/fax', 'billing_address_id', null, 'left')
->joinAttribute('shipping_firstname', 'order_address/firstname', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_lastname', 'order_address/lastname', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_street', 'order_address/street', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_company', 'order_address/company', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_city', 'order_address/city', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_region', 'order_address/region', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_country', 'order_address/country_id', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_postcode', 'order_address/postcode', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_telephone', 'order_address/telephone', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_fax', 'order_address/fax', 'shipping_address_id', null, 'left')
->addAttributeToSort('created_at', 'asc')
->setPageSize(1000)
->setCurPage(1)
->addAttributeToFilter('increment_id', $ordersId)
->load();
foreach ($ordersList as $order) {
$orders[] = $this->prepareOrder($order);
}
$chunked = array_chunk($orders, 50);
unset($orders);
foreach ($chunked as $chunk) {
$this->_api->ordersUpload($chunk);
time_nanosleep(0, 250000000);
}
unset($chunked);
return true;
}
/**
* Orders export
*
@ -224,24 +302,28 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
->setPageSize(1000)
->setCurPage(1)
->load();
foreach ($ordersList as $order) {
$orders[] = $this->prepareOrder($order);
}
$chunked = array_chunk($orders, 50);
unset($orders);
foreach ($chunked as $chunk) {
//file_put_contents('/var/www/konzeptual/data/www/konzeptual.ru/tempO.txt', var_export($chunk,true)); die();
$this->_api->ordersUpload($chunk);
time_nanosleep(0, 250000000);
}
unset($chunked);
return true;
}
protected function prepareOrder($order)
{
$config = Mage::getModel('retailcrm/settings', $order->getStoreId());
$address = $order->getShippingAddress()->getData();
$address = $order->getShippingAddress();
$orderItems = $order->getItemsCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('product_type', array('eq'=>'simple'))
@ -252,6 +334,7 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
if ($item->getParentItemId()) {
$parent = Mage::getModel('sales/order_item')->load($item->getParentItemId());
}
$product = array(
'productId' => $item->getProductId(),
'productName' => !isset($parent) ? $item->getName() : $parent->getName(),
@ -262,9 +345,10 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
$items[] = $product;
}
}
$shipping = $this->getShippingCode($order->getShippingMethod());
$preparedOrder = array(
'externalId' => $order->getId(),
'externalId' => $order->getRealOrderId(),
'number' => $order->getRealOrderId(),
'createdAt' => $order->getCreatedAt(),
'lastName' => $order->getCustomerLastname(),
@ -300,18 +384,23 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
),
)
);
if(trim($preparedOrder['delivery']['code']) == ''){
unset($preparedOrder['delivery']['code']);
}
if(trim($preparedOrder['paymentType']) == ''){
unset($preparedOrder['paymentType']);
}
if(trim($preparedOrder['status']) == ''){
unset($preparedOrder['status']);
}
if ($order->getCustomerIsGuest() != 0) {
$preparedOrder['customer']['externalId'] = $order->getCustomerId();
}
return Mage::helper('retailcrm')->filterRecursive($preparedOrder);
}

View File

@ -1,7 +1,15 @@
<?php
/**
* PHP version 5.3
*
* Response from retailCRM API
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
{
@ -11,6 +19,14 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
// response assoc array
protected $response;
/**
* ApiResponse constructor.
*
* @param int $statusCode HTTP status code
* @param mixed $responseBody HTTP body
*
* @throws InvalidJsonException
*/
public function __construct($statusCode, $responseBody = null)
{
$this->statusCode = (int) $statusCode;
@ -52,7 +68,11 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
/**
* Allow to access for the property throw class method
*
* @param string $name
* @param string $name method name
* @param mixed $arguments method parameters
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function __call($name, $arguments)
@ -70,7 +90,10 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
/**
* Allow to access for the property throw object property
*
* @param string $name
* @param string $name property name
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function __get($name)
@ -83,8 +106,13 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
}
/**
* @param mixed $offset
* @param mixed $value
* Offset set
*
* @param mixed $offset offset
* @param mixed $value value
*
* @throws \BadMethodCallException
* @return void
*/
public function offsetSet($offset, $value)
{
@ -92,7 +120,12 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
}
/**
* @param mixed $offset
* Offset unset
*
* @param mixed $offset offset
*
* @throws \BadMethodCallException
* @return void
*/
public function offsetUnset($offset)
{
@ -100,7 +133,10 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
}
/**
* @param mixed $offset
* Check offset
*
* @param mixed $offset offset
*
* @return bool
*/
public function offsetExists($offset)
@ -109,7 +145,12 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
}
/**
* @param mixed $offset
* Get offset
*
* @param mixed $offset offset
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function offsetGet($offset)

View File

@ -0,0 +1,24 @@
<?php
class Retailcrm_Retailcrm_Adminhtml_RetailcrmbuttonController extends Mage_Adminhtml_Controller_Action
{
/**
* Return some checking result
*
* @return void
*/
public function checkAction()
{
$orders = Mage::getModel('retailcrm/order');
$orders ->ordersExportNumber();
}
/**
* Check is allowed access to action
*
* @return bool
*/
protected function _isAllowed()
{
return Mage::getSingleton('admin/session')->isAllowed('system/config/retailcrm');
}
}

View File

@ -45,6 +45,7 @@ SOFTWARE.
</retailcrm>
</blocks>
<events>
<sales_order_place_after>
<observers>
<retailcrm_retailcrm_model_observer>
@ -54,6 +55,8 @@ SOFTWARE.
</retailcrm_retailcrm_model_observer>
</observers>
</sales_order_place_after>
<sales_order_save_commit_after>
<observers>
<retailcrm_retailcrm_model_observer>
@ -63,6 +66,19 @@ SOFTWARE.
</retailcrm_retailcrm_model_observer>
</observers>
</sales_order_save_commit_after>
<sales_order_save_after>
<observers>
<retailcrm_retailcrm_model_observer>
<type>singleton</type>
<class>Retailcrm_Retailcrm_Model_Observer</class>
<method>orderStatusHistoryCheck</method>
</retailcrm_retailcrm_model_observer>
</observers>
</sales_order_save_after>
<customer_save_after>
<observers>
<retailcrm_retailcrm_model_observer>
@ -72,8 +88,21 @@ SOFTWARE.
</retailcrm_retailcrm_model_observer>
</observers>
</customer_save_after>
</events>
</global>
<admin>
<routers>
<adminhtml>
<args>
<modules>
<Retailcrmbutton after="Mage_Adminhtml">Retailcrm_Retailcrm</Retailcrmbutton>
</modules>
</args>
</adminhtml>
</routers>
</admin>
<crontab>
<jobs>
<icml>

View File

@ -121,6 +121,39 @@ SOFTWARE.
<show_in_store>1</show_in_store>
<frontend_model>retailcrm/adminhtml_system_config_form_fieldset_status</frontend_model>
</status>
<load_order translate="label comment" module="retailcrm">
<expanded>0</expanded>
<label>Order Load</label>
<frontend_type>text</frontend_type>
<sort_order>15</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<frontend_model>retailcrm/adminhtml_system_config_form_fieldset_order</frontend_model>
<fields>
<numberOrder translate="label comment">
<label>Number orders</label>
<frontend_type>text</frontend_type>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<tooltip><![CDATA[Enter your order number, separated by commas]]></tooltip>
</numberOrder>
<button translate="label comment">
<frontend_type>button</frontend_type>
<frontend_model>retailcrm/adminhtml_system_config_form_button</frontend_model>
<sort_order>2</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</button>
</fields>
</load_order>
</groups>
</retailcrm>
</sections>

View File

@ -0,0 +1,16 @@
<script type="text/javascript">
//<![CDATA[
function check() {
new Ajax.Request('<?php echo $this->getAjaxCheckUrl() ?>', {
method: 'get',
onSuccess: function(transport){
if (transport.responseText){
alert('Completed');
}
}
});
}
//]]>
</script>
<?php echo $this->getButtonHtml() ?>

12
tests/unit/autoload.php Normal file
View File

@ -0,0 +1,12 @@
<?php
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR
. dirname(__FILE__) . '/../../app' . PATH_SEPARATOR . dirname(__FILE__));
//Set custom memory limit
ini_set('memory_limit', '512M');
//Include Magento libraries
require_once 'Mage.php';
//Start the Magento application
Mage::app('default');
//Avoid issues "Headers already send"
session_start();

20
tests/unit/phpunit.xml Normal file
View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" ?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="true"
bootstrap="./autoload.php">
<testsuite name="Magento Unit Test">
<directory>testsuite</directory>
</testsuite>
<filter>
<whitelist>
<directory>../../app/code/community</directory>
</whitelist>
</filter>
</phpunit>

View File

@ -0,0 +1,22 @@
<?php
class Retailcrm_Retailcrm_Model_IcmlTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
Mage::reset ();
$app = Mage::app('default');
Mage::dispatchEvent('controller_front_init_before');
$this->_block = new Retailcrm_Retailcrm_Model_Icml;
}
protected function tearDown()
{
}
public function testFirstMethod()
{
$this->assertInstanceOf('Retailcrm_Retailcrm_Model_Icml',$this->_block);
}
}

View File

@ -0,0 +1,27 @@
<?php
class Retailcrm_Retailcrm_Model_OrderTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
Mage::reset ();
Mage::app ('default');
Mage::dispatchEvent('controller_front_init_before');
$this->_block = new Retailcrm_Retailcrm_Model_Order;
}
protected function tearDown()
{
}
public function testFirstMethod()
{
$this->assertInstanceOf('Retailcrm_Retailcrm_Model_Order',$this->_block);
}
public function testSecondMethod()
{
}
}