1
0
mirror of synced 2024-11-24 22:16:13 +03:00

Merge pull request #2 from DmitryKorol/master

offers, customer upload on event, orders update
This commit is contained in:
Alex Lushpai 2016-09-08 18:08:29 +03:00 committed by GitHub
commit 7d3a1bb75e
10 changed files with 922 additions and 187 deletions

View File

@ -1,8 +1,25 @@
<?php
/**
* Data helper
* Default extension helper class
* PHP version 5.3
*
* @author RetailCRM
* @category Model
* @package RetailCrm\Model
* @author RetailDriver LLC <integration@retailcrm.ru>
* @license http://opensource.org/licenses/MIT MIT License
* @link http://www.magentocommerce.com/magento-connect/retailcrm-1.html
*/
/**
* Data helper class
*
* @category Model
* @package RetailCrm\Model
* @author RetailDriver LLC <integration@retailcrm.ru>
* @license http://opensource.org/licenses/MIT MIT License
* @link http://www.magentocommerce.com/magento-connect/retailcrm-1.html
*
* @SuppressWarnings(PHPMD.CamelCaseClassName)
*/
class Retailcrm_Retailcrm_Helper_Data extends Mage_Core_Helper_Abstract
{
@ -20,39 +37,144 @@ class Retailcrm_Retailcrm_Helper_Data extends Mage_Core_Helper_Abstract
*/
const XML_API_KEY = 'retailcrm/general/api_key';
/**
* Return api url
*
* @param integer|string|Mage_Core_Model_Store $store
* @return int
*/
/**
* Get api url
*
* @param Mage_Core_Model_Store $store store instance
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return int
*/
public function getApiUrl($store = null)
{
return abs((int)Mage::getStoreConfig(self::XML_API_URL, $store));
}
/**
* Return api key
*
* @param integer|string|Mage_Core_Model_Store $store
* @return int
*/
/**
* Get api key
*
* @param Mage_Core_Model_Store $store store instance
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return int
*/
public function getApiKey($store = null)
{
return abs((int)Mage::getStoreConfig(self::XML_API_KEY, $store));
}
public function rewrittenProductUrl($productId, $categoryId, $storeId)
/**
* Get api key
*
* @param string $baseUrl base url
* @param mixed $coreUrl url rewritte
* @param integer $productId product id
* @param integer $storeId product store id
* @param integer $categoryId product category id
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return string
*/
public function rewrittenProductUrl(
$baseUrl,
$coreUrl,
$productId,
$storeId,
$categoryId = null
)
{
$coreUrl = Mage::getModel('core/url_rewrite');
$idPath = sprintf('product/%d', $productId);
if ($categoryId) {
$idPath = sprintf('%s/%d', $idPath, $categoryId);
$idPath = sprintf('%s/%d', $idPath, $categoryId);
}
$coreUrl->setStoreId($storeId);
$coreUrl->loadByIdPath($idPath);
return Mage::getBaseUrl( Mage_Core_Model_Store::URL_TYPE_WEB, true ) . $coreUrl->getRequestPath();
return $baseUrl . $coreUrl->getRequestPath();
}
/**
* Get country code
*
* @param string $string country iso code
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return string
*/
public function getCountryCode($string)
{
$country = empty($string) ? 'RU' : $string;
$xmlObj = new Varien_Simplexml_Config(
sprintf(
"%s%s%s",
Mage::getModuleDir('etc', 'Retailcrm_Retailcrm'),
DS,
'country.xml'
)
);
$xmlData = $xmlObj->getNode();
if ($country != 'RU') {
foreach ($xmlData as $elem) {
if ($elem->name == $country || $elem->english == $country) {
$country = $elem->alpha;
break;
}
}
}
return (string) $country;
}
/**
* Get exchage time
*
* @param string $datetime datetime string
*
* @return \DateTime
*/
public function getExchangeTime($datetime)
{
return $datetime = empty($datetime)
? new DateTime(
date(
'Y-m-d H:i:s',
strtotime('-1 days', strtotime(date('Y-m-d H:i:s')))
)
)
: new DateTime($datetime);
}
/**
* Recursive array filter
*
* @param array $haystack input array
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
*
* @return array
*/
public function filterRecursive($haystack)
{
foreach ($haystack as $key => $value) {
if (is_array($value)) {
$haystack[$key] = self::filterRecursive($haystack[$key]);
}
if (is_null($haystack[$key])
|| $haystack[$key] === ''
|| count($haystack[$key]) == 0
) {
unset($haystack[$key]);
} elseif (!is_array($value)) {
$haystack[$key] = trim($value);
}
}
return $haystack;
}
}

View File

@ -0,0 +1,43 @@
<?php
class Retailcrm_Retailcrm_Model_Attribute
{
/**
* Options getter
*
* @return array
*/
public function toOptionArray()
{
$attributes = Mage::getResourceModel('catalog/product_attribute_collection')
->getItems();
$data = array();
foreach($attributes as $attribute) {
if(empty($attribute->getFrontendLabel())) continue;
$data[] = array(
'label' => $attribute->getFrontendLabel(),
'value' => $attribute->getAttributeCode()
);
}
return $data;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return array();
return array(
0 => Mage::helper('adminhtml')->__('Data1'),
1 => Mage::helper('adminhtml')->__('Data2'),
2 => Mage::helper('adminhtml')->__('Data3'),
);
}
}

View File

@ -0,0 +1,75 @@
<?php
/**
* Customer class
*
* @category Model
* @package RetailCrm\Model
* @author RetailDriver LLC <integration@retailcrm.ru>
* @license http://opensource.org/licenses/MIT MIT License
* @link http://www.magentocommerce.com/magento-connect/retailcrm-1.html
*
* @SuppressWarnings(PHPMD.CamelCaseClassName)
*/
class Retailcrm_Retailcrm_Model_Customer extends Retailcrm_Retailcrm_Model_Exchange
{
/**
* Customer create
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
* @param mixed $data
*
* @return bool
*/
public function customerRegister($data)
{
$customer = array(
'externalId' => $data->getId(),
'email' => $data->getEmail(),
'firstName' => $data->getFirstname(),
'patronymic' => $data->getMiddlename(),
'lastName' => $data->getLastname(),
'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt()))
);
$this->_api->customersEdit($customer);
}
/**
* Customers export
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
*
* @return bool
*/
public function customersExport()
{
$customers = array();
$customerCollection = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToSelect('email')
->addAttributeToSelect('firstname')
->addAttributeToSelect('lastname');
foreach ($customerCollection as $customerData)
{
$customer = array(
'externalId' => $customerData->getId(),
'email' => $customerData->getData('email'),
'firstName' => $customerData->getData('firstname'),
'lastName' => $customerData->getData('lastname')
);
$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();
$this->_api->customersUpload($chunk);
time_nanosleep(0, 250000000);
}
unset($chunked);
return true;
}
}

View File

@ -20,147 +20,6 @@ class Retailcrm_Retailcrm_Model_Exchange
}
}
/**
* @param mixed $order
*
* @return bool
*/
public function ordersCreate($order)
{
$this->_config = Mage::getStoreConfig('retailcrm', $order->getStoreId());
$statuses = array_flip(array_filter($this->_config['status']));
$payments = array_filter($this->_config['payment']);
$shippings = array_filter($this->_config['shipping']);
$shipment = $order->getShippingMethod();
$shipment = explode('_', $shipment);
$shipment = $shipment[0];
$address = $order->getShippingAddress()->getData();
$orderItems = $order->getAllItems();
$simpleItems = array();
$confItems = array();
foreach ($orderItems as $item) {
if ($item->getProductType() == 'simple') {
$simpleItems[] = $item;
} else {
$confItems[$item->getData('item_id')] = $item;
}
}
$items = array();
foreach ($simpleItems as $item) {
$product = array(
'productId' => $item->product_id,
'productName' => $item->getName(),
'quantity' => (int) $item->getData('qty_ordered')
);
if ($item->getData('parent_item_id')) {
$product['initialPrice'] = $confItems[$item->getData('parent_item_id')]->getPrice();
/*if ($confItems[$item->getData('parent_item_id')]->getDiscountAmount() > 0) {
$product['discount'] = $confItems[$item->getData('parent_item_id')]->getDiscountAmount();
}
if ($confItems[$item->getData('parent_item_id')]->getDiscountPercent() > 0) {
$product['discountPercent'] = $confItems[$item->getData('parent_item_id')]->getDiscountPercent();
}*/
} else {
$product['initialPrice'] = $item->getPrice();
/*if ($item->getDiscountAmount() > 0) {
$product['discount'] = $item->getDiscountAmount();
}
if ($item->getDiscountPercent() > 0) {
$product['discountPercent'] = $item->getDiscountPercent();
}*/
}
$items[] = $product;
}
$customer = array(
'externalId' => ($order->getCustomerIsGuest() == 0) ? $order->getCustomerId() : 'g' . $order->getRealOrderId(),
'email' => $order->getCustomerEmail(),
'phone' => $address['telephone'],
'name' => $order->getCustomerName(),
'lastName' => $order->getCustomerLastname(),
'firstName' => $order->getCustomerFirstname(),
'patronymic' => $order->getCustomerMiddlename(),
);
$customerId = $this->setCustomerId($customer);
unset($customer);
$comment = $order->getStatusHistoryCollection()->getFirstItem();
$preparedOrder = array(
'site' => $order->getStore()->getCode(),
'externalId' => $order->getId(),
'number' => $order->getRealOrderId(),
'createdAt' => $order->getCreatedAt(),
'customerId' => $customerId,
'lastName' => $order->getCustomerLastname(),
'firstName' => $order->getCustomerFirstname(),
'patronymic' => $order->getCustomerMiddlename(),
'email' => $order->getCustomerEmail(),
'phone' => $address['telephone'],
'paymentType' => $payments[$order->getPayment()->getMethodInstance()->getCode()],
'status' => $statuses[$order->getStatus()],
'discount' => abs($order->getDiscountAmount()),
'items' => $items,
'customerComment' => $comment->getComment(),
'delivery' => array(
'code' => $shippings[$shipment],
'cost' => $order->getShippingAmount(),
'address' => array(
'index' => $address['postcode'],
'city' => $address['city'],
'country' => $address['country_id'],
'street' => $address['street'],
'region' => $address['region'],
'text' => implode(
',',
array(
$address['postcode'],
$address['country_id'],
$address['city'],
$address['street']
)
)
),
)
);
try {
$response = $this->_api->ordersCreate($preparedOrder);
if ($response->isSuccessful() && 201 === $response->getStatusCode()) {
Mage::log($response->id);
} else {
Mage::log(
sprintf(
"Order create 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 orders history & modify orders into shop
*

View File

@ -23,7 +23,7 @@ class Retailcrm_Retailcrm_Model_Icml
$xml = new SimpleXMLElement(
$string,
LIBXML_NOENT |LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE
LIBXML_NOENT | LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE
);
$this->_dd = new DOMDocument();
@ -90,15 +90,20 @@ class Retailcrm_Retailcrm_Model_Icml
$helper = Mage::helper('retailcrm');
$picUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
$customAdditionalAttributes = Mage::getStoreConfig('retailcrm/attributes_to_export_into_icml');
$customAdditionalAttributes = explode(',', $customAdditionalAttributes);
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addUrlRewrite();
$collection->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
foreach ($collection as $product) {
/** @var Mage_Catalog_Model_Product $product */
$offer = array();
$offer['id'] = $product->getId();
$offer['id'] = $product->getTypeId() != 'configurable' ? $product->getId() : null;
$offer['productId'] = $product->getId();
$offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N';
$offer['name'] = $product->getName();
@ -120,11 +125,151 @@ class Retailcrm_Retailcrm_Model_Icml
$offer['vendor'] = $product->getAttributeText('manufacturer');
$offer['article'] = $product->getSku();
$offer['weight'] = $product->getWeight();
$offer['params'] = array();
$article = $product->getSku();
if(!empty($article)) {
$offer['params'][] = array(
'name' => 'Article',
'code' => 'article',
'value' => $article
);
}
$weight = $product->getWeight();
if(!empty($weight)) {
$offer['params'][] = array(
'name' => 'Weight',
'code' => 'weight',
'value' => $weight
);
}
if(!empty($customAdditionalAttributes)) {
foreach($customAdditionalAttributes as $customAdditionalAttribute) {
$alreadyExists = false;
foreach($offer['params'] as $param) {
if($param['code'] == $customAdditionalAttribute) {
$alreadyExists = true;
break;
}
}
if($alreadyExists) continue;
$attribute = $product->getAttributeText($customAdditionalAttribute);
if(!empty($attribute)) {
$offer['params'][] = array(
'name' => $customAdditionalAttribute,
'code' => $customAdditionalAttribute,
'value' => $attribute
);
}
}
}
$offers[] = $offer;
if($product->getTypeId() == 'configurable') {
/** @var Mage_Catalog_Model_Product_Type_Configurable $product */
$associatedProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product);
$productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
foreach($associatedProducts as $associatedProduct) {
$associatedProduct = Mage::getModel('catalog/product')->load($associatedProduct->getId());
$attributes = array();
foreach($productAttributeOptions as $productAttributeOption) {
$attributes[$productAttributeOption['label']] = $associatedProduct->getAttributeText($productAttributeOption['attribute_code']);
}
$attributesString = array();
foreach($attributes AS $attributeName=>$attributeValue) {
$attributesString[] = $attributeName.': '.$attributeValue;
}
$attributesString = ' (' . implode(', ', $attributesString) . ')';
$offer = array();
$offer['id'] = $associatedProduct->getId();
$offer['productId'] = $product->getId();
$offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N';
$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['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage();
$offer['quantity'] = Mage::getModel('cataloginventory/stock_item')
->loadByProduct($associatedProduct)->getQty();
foreach ($associatedProduct->getCategoryIds() as $category_id) {
$offer['categoryId'][] = $category_id;
}
$offer['vendor'] = $associatedProduct->getAttributeText('manufacturer');
$offer['params'] = array();
$article = $associatedProduct->getSku();
if(!empty($article)) {
$offer['params'][] = array(
'name' => 'Article',
'code' => 'article',
'value' => $article
);
}
$weight = $associatedProduct->getWeight();
if(!empty($weight)) {
$offer['params'][] = array(
'name' => 'Weight',
'code' => 'weight',
'value' => $weight
);
}
if(!empty($attributes)) {
foreach($attributes as $attributeName => $attributeValue) {
$offer['params'][] = array(
'name' => $attributeName,
'code' => str_replace(' ', '_', strtolower($attributeName)),
'value' => $attributeValue
);
}
}
if(!empty($customAdditionalAttributes)) {
foreach($customAdditionalAttributes as $customAdditionalAttribute) {
$alreadyExists = false;
foreach($offer['params'] as $param) {
if($param['code'] == $customAdditionalAttribute) {
$alreadyExists = true;
break;
}
}
if($alreadyExists) continue;
$attribute = $associatedProduct->getAttributeText($customAdditionalAttribute);
if(!empty($attribute)) {
$offer['params'][] = array(
'name' => $customAdditionalAttribute,
'code' => $customAdditionalAttribute,
'value' => $attribute
);
}
}
}
$offers[] = $offer;
}
}
}
foreach ($offers as $offer) {
@ -205,25 +350,16 @@ class Retailcrm_Retailcrm_Model_Icml
);
}
if (!empty($offer['article'] )) {
$sku = $this->_dd->createElement('param');
$sku->setAttribute('name', 'article');
$sku->setAttribute('code', 'Article');
$sku->appendChild(
$this->_dd->createTextNode($offer['article'])
);
$e->appendChild($sku);
}
if (!empty($offer['weight'] )) {
$weight = $this->_dd->createElement('param');
$weight->setAttribute('name', 'weight');
$weight->setAttribute('code', 'Weight');
$weight->appendChild(
$this->_dd->createTextNode($offer['weight'])
);
$e->appendChild($weight);
if(!empty($offer['params'])) {
foreach($offer['params'] as $param) {
$paramNode = $this->_dd->createElement('param');
$paramNode->setAttribute('name', $param['name']);
$paramNode->setAttribute('code', $param['code']);
$paramNode->appendChild(
$this->_dd->createTextNode($param['value'])
);
$e->appendChild($paramNode);
}
}
}
}

View File

@ -16,7 +16,33 @@ class Retailcrm_Retailcrm_Model_Observer
{
if (Mage::registry('sales_order_place_after') != 1){//do nothing if the event was dispatched
$order = $observer->getEvent()->getOrder();
Mage::getModel('retailcrm/exchange')->ordersCreate($order);
Mage::getModel('retailcrm/order')->orderCreate($order);
}
return true;
}
public function orderUpdate(Varien_Event_Observer $observer)
{
$order = $observer->getEvent()->getOrder();
Mage::getModel('retailcrm/order')->orderUpdate($order);
return true;
}
/**
* Event after customer created
*
* @param Varien_Event_Observer $observer
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return bool
*/
public function customerRegister(Varien_Event_Observer $observer)
{
if (Mage::registry('customer_save_after') != 1) {
$customer = $observer->getEvent()->getCustomer();
Mage::getModel('retailcrm/customer')->customerRegister($customer);
}
return true;

View File

@ -0,0 +1,342 @@
<?php
/**
* Order class
*
* @category Model
* @package RetailCrm\Model
* @author RetailDriver LLC <integration@retailcrm.ru>
* @license http://opensource.org/licenses/MIT MIT License
* @link http://www.magentocommerce.com/magento-connect/retailcrm-1.html
*
* @SuppressWarnings(PHPMD.CamelCaseClassName)
* @SuppressWarnings(PHPMD.CamelCasePropertyName)
*/
class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
{
/**
* Order create
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
* @param mixed $order
*
* @return bool
*/
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(),
'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 orderUpdate($order)
{
$config = Mage::getModel(
'retailcrm/settings',
array(
'storeId' =>$order->getStoreId()
)
);
$preparedOrder = array(
'externalId' => $order->getId(),
'status' => $config->getMapping($order->getStatus(), 'status'),
);
if((float)$order->getBaseGrandTotal() == (float)$order->getTotalPaid()){
$preparedOrder['paymentStatus'] = 'paid';
}
$preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder);
$this->_api->ordersEdit($preparedOrder);
}
public function orderCreate($order)
{
$config = Mage::getModel('retailcrm/settings', [
'storeId' => $order->getStoreId()
]);
$address = $order->getShippingAddress()->getData();
$orderItems = $order->getItemsCollection()
->addAttributeToSelect('*')
//->addAttributeToFilter('product_type', array('eq'=>'simple'))
->load();
$items = array();
foreach ($orderItems as $item) {
if ($item->getProductType() == "simple") {
if ($item->getParentItemId()) {
$parent = Mage::getModel('sales/order_item')->load($item->getParentItemId());
}
$product = array(
'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()
);
unset($parent);
$items[] = $product;
} elseif($item->getProductType() == "grouped") {
$product = array(
'productId' => $item->getProductId(),
'productName' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'initialPrice' => $item->getPrice()
);
$items[] = $product;
}
}
$shipping = $this->getShippingCode($order->getShippingMethod());
$preparedOrder = array(
'site' => $order->getStore()->getCode(),
'externalId' => $order->getId(),
'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"),
'lastName' => $order->getCustomerLastname(),
'firstName' => $order->getCustomerFirstname(),
'patronymic' => $order->getCustomerMiddlename(),
'email' => $order->getCustomerEmail(),
'phone' => $address['telephone'],
'paymentType' => $config->getMapping($order->getPayment()->getMethodInstance()->getCode(), 'payment'),
'status' => $config->getMapping($order->getStatus(), 'status'),
'discount' => abs($order->getDiscountAmount()),
'items' => $items,
'customerComment' => $order->getStatusHistoryCollection()->getFirstItem()->getComment(),
'delivery' => array(
'code' => $config->getMapping($shipping, 'shipping'),
'cost' => $order->getShippingAmount(),
'address' => array(
'index' => $address['postcode'],
'city' => $address['city'],
'country' => $address['country_id'],
'street' => $address['street'],
'region' => $address['region'],
'text' => trim(
',',
implode(
',',
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())) {
$preparedOrder['customer']['externalId'] = $order->getCustomerId();
}
}
$preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder);
try {
$response = $this->_api->ordersCreate($preparedOrder);
if ($response->isSuccessful() && 201 === $response->getStatusCode()) {
Mage::log($response->id);
} else {
Mage::log(
sprintf(
"Order create 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());
}
}
/**
* Orders export
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
*
* @return bool
*/
public function ordersExport()
{
$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)
->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();
$orderItems = $order->getItemsCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('product_type', array('eq'=>'simple'))
->load();
$items = array();
foreach ($orderItems as $item) {
if ($item->getProductType() == "simple") {
if ($item->getParentItemId()) {
$parent = Mage::getModel('sales/order_item')->load($item->getParentItemId());
}
$product = array(
'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()
);
unset($parent);
$items[] = $product;
}
}
$shipping = $this->getShippingCode($order->getShippingMethod());
$preparedOrder = array(
'externalId' => $order->getId(),
'number' => $order->getRealOrderId(),
'createdAt' => $order->getCreatedAt(),
'lastName' => $order->getCustomerLastname(),
'firstName' => $order->getCustomerFirstname(),
'patronymic' => $order->getCustomerMiddlename(),
'email' => $order->getCustomerEmail(),
'phone' => $address['telephone'],
'paymentType' => $config->getMapping($order->getPayment()->getMethodInstance()->getCode(), 'payment'),
'status' => $config->getMapping($order->getStatus(), 'status'),
'discount' => abs($order->getDiscountAmount()),
'items' => $items,
'customerComment' => $order->getStatusHistoryCollection()->getFirstItem()->getComment(),
'delivery' => array(
'code' => $config->getMapping($shipping, 'shipping'),
'cost' => $order->getShippingAmount(),
'address' => array(
'index' => $address['postcode'],
'city' => $address['city'],
'country' => $address['country_id'],
'street' => $address['street'],
'region' => $address['region'],
'text' => trim(
',',
implode(
',',
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) {
$preparedOrder['customer']['externalId'] = $order->getCustomerId();
}
return Mage::helper('retailcrm')->filterRecursive($preparedOrder);
}
protected function getShippingCode($string)
{
$split = array_values(explode('_', $string));
$length = count($split);
$prepare = array_slice($split, 0, $length/2);
return implode('_', $prepare);
}
protected function getLocale($code)
{
$this->_locale = Mage::app()->getLocale()->getLocaleCode();
if (!in_array($this->_locale, array('ru_RU', 'en_US'))) {
$this->_locale = 'en_US';
}
$this->_dict = array(
'ru_RU' => array('sku' => 'Артикул', 'weight' => 'Вес', 'offer' => 'Вариант'),
'en_US' => array('sku' => 'Sku', 'weight' => 'Weight', 'offer' => 'Offer'),
);
return $this->_dict[$this->_locale][$code];
}
}

View File

@ -0,0 +1,92 @@
<?php
/**
* Settings class
*
* @category Model
* @package RetailCrm\Model
* @author RetailDriver LLC <integration@retailcrm.ru>
* @license http://opensource.org/licenses/MIT MIT License
* @link http://www.magentocommerce.com/magento-connect/retailcrm-1.html
*
* @SuppressWarnings(PHPMD.CamelCaseClassName)
* @SuppressWarnings(PHPMD.CamelCasePropertyName)
*/
class Retailcrm_Retailcrm_Model_Settings
{
protected $_config;
protected $_storeDefined;
/**
* Constructor
*
* @param array $params
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
*
* @return bool
*/
public function __construct(array $params = array())
{
$this->_config = empty($params)
? $this->setConfigWithoutStoreId()
: $this->setConfigWithStoreId($params['storeId']);
}
/**
* Get mapping values
*
* @param string $code
* @param string $type (default: status, values: status, payment, shipping)
* @param bool $reverse
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
*
* @return mixed
*/
public function getMapping($code, $type, $reverse = false)
{
if (!in_array($type, array('status', 'payment', 'shipping'))) {
throw new \InvalidArgumentException(
"Parameter 'type' must be 'status', 'payment' or 'shipping'"
);
}
$array = ($reverse)
? array_flip(array_filter($this->_config[$type]))
: array_filter($this->_config[$type]);
return array_key_exists($code, $array)
? $array[$code]
: false;
}
/**
* Set config with orderStoreId
*
* @param string $storeId
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return mixed
*/
protected function setConfigWithStoreId($storeId)
{
$this->_storeDefined = true;
return Mage::getStoreConfig('retailcrm', $storeId);
}
/**
* Set config without orderStoreId
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return mixed
*/
protected function setConfigWithoutStoreId()
{
$this->_storeDefined = false;
return Mage::getStoreConfig('retailcrm');
}
}

View File

@ -54,6 +54,24 @@ SOFTWARE.
</retailcrm_retailcrm_model_observer>
</observers>
</sales_order_place_after>
<sales_order_save_commit_after>
<observers>
<retailcrm_retailcrm_model_observer>
<type>singleton</type>
<class>Retailcrm_Retailcrm_Model_Observer</class>
<method>orderUpdate</method>
</retailcrm_retailcrm_model_observer>
</observers>
</sales_order_save_commit_after>
<customer_save_after>
<observers>
<retailcrm_retailcrm_model_observer>
<type>singleton</type>
<class>Retailcrm_Retailcrm_Model_Observer</class>
<method>customerRegister</method>
</retailcrm_retailcrm_model_observer>
</observers>
</customer_save_after>
</events>
</global>
<crontab>

View File

@ -69,11 +69,33 @@ SOFTWARE.
</api_key>
</fields>
</general>
<misc>
<expanded>1</expanded>
<label>Misc</label>
<frontend_type>text</frontend_type>
<sort_order>11</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<attributes_to_export_into_icml translate="label">
<label>Custom attributes to export into ICML</label>
<frontend_type>multiselect</frontend_type>
<config_path>retailcrm/attributes_to_export_into_icml</config_path>
<sort_order>7</sort_order>
<source_model>retailcrm/attribute</source_model>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<can_be_empty>1</can_be_empty>
</attributes_to_export_into_icml>
</fields>
</misc>
<shipping translate="label comment" module="retailcrm">
<expanded>0</expanded>
<label>Shipping</label>
<frontend_type>text</frontend_type>
<sort_order>11</sort_order>
<sort_order>12</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
@ -83,7 +105,7 @@ SOFTWARE.
<expanded>0</expanded>
<label>Payment Method</label>
<frontend_type>text</frontend_type>
<sort_order>12</sort_order>
<sort_order>13</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
@ -93,7 +115,7 @@ SOFTWARE.
<expanded>0</expanded>
<label>Order Statuses</label>
<frontend_type>text</frontend_type>
<sort_order>13</sort_order>
<sort_order>14</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>