Skip to content

Commit

Permalink
Upgrade extension to use latest api endpoints and Fera/Ai namespace.
Browse files Browse the repository at this point in the history
  • Loading branch information
jayelkaake committed May 4, 2019
1 parent 104b754 commit 74b0423
Show file tree
Hide file tree
Showing 19 changed files with 379 additions and 163 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ Just copy over the contents of this repo's `src/` folder associatively int your
2. If you're logged in as an admin, log out and log back in to access the config section (otherwise you may get a 404 error)

## Setup
Go to the settings in the admin (System → FERA.AI → Fera Settings) and enter your public and private keys.
Go to the settings in the admin (System → Fera Commercee → Fera.ai Settings) and enter your public and private keys.

Here's how it should look:

![](http://g.recordit.co/eGJObK1A9H.gif)

You can also set your configuration settings via your environment or server variables. To do this, set `AICONNECTOR_PUBLIC_KEY` to your public key and `AICONNECTOR_PRIVATE_KEY` to your private key.
You can also set your configuration settings via your environment or server variables. To do this, set `FERA_AI_PUBLIC_KEY` to your public key and `FERA_AI_PRIVATE_KEY` to your private key.

## Usage
Go to https://app.fera.ai/skills to customize your experience!
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

class Fera_Aiconnector_Block_Footer_Checkout_Success extends Mage_Core_Block_Template
class Fera_Ai_Block_Footer_Checkout_Success extends Mage_Core_Block_Template
{

/**
Expand Down
103 changes: 103 additions & 0 deletions src/app/code/community/Fera/Ai/Block/Footer/Product/View.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?php

class Fera_Ai_Block_Footer_Product_View extends Mage_Core_Block_Template
{
protected $_product;
/**
* Retrieve current product model
*
* @return Mage_Catalog_Model_Product
*/
public function getProduct()
{
if (!$this->_product) {
if ($this->getData('product_id')) {
$this->_product = Mage::getModel('catalog/product')->load($this->getData('product_id'));
} else {
$this->_product = Mage::registry('product');
}
}
return $this->_product;
}

public function getProductJson()
{
$p = $this->getProduct();

$thumb = $p->getThumbnailUrl();
$productData = [
"id" => $p->getId(), // String
"name" => $p->getName(), // String
"price" => $p->getFinalPrice(), // Float
"status" => $p->getStatus() == 1 ? 'published' : 'draft', // (Optional) String
"created_at" => (new DateTime($p->getCreatedAt()))->format(DateTime::ATOM), // (Optional) String (ISO 8601 format DateTime)
"modified_at" => (new DateTime($p->getUpdatedAt()))->format(DateTime::ATOM), // (Optional) String (ISO 8601 format DateTime)
"stock" => $p->getStockItem()->getQty(), // (Optional) Integer, If null assumed to be infinite.
"in_stock" => $p->isInStock(), // (Optional) Boolean
"url" => $p->getUrl(), // String
"thumbnail_url" => $thumb, // String
"needs_shipping" => $p->getTypeId() != 'virtual', // (Optional) Boolean
"hidden" => $p->getVisibility() == '1', // (Optional) Boolean
'tags' => [],
"variants" => [], // (Optional) Array<Variant>: Variants that are applicable to this product.
"platform_data" => [ // (Optional) Hash/Object of attributes to store about the product specific to the integration platform (can be used in future filters)
"sku" => $p->getSku(),
"type" => $p->getTypeId(),
"regular_price" => $p->getPrice()
]
];

$tags = Mage::getModel('tag/tag')->getResourceCollection()
->addPopularity()
->addStatusFilter(Mage::getModel('tag/tag')->getApprovedStatus())
->addProductFilter($p->getId());
foreach($tags as $tag) {
$productData['tags'][] = $tag->getName();
}

if ($p->getTypeId() == 'configurable') {
$cfgAttr = $p->getTypeInstance()->getConfigurableAttributesAsArray();
foreach ($p->getTypeInstance()->getUsedProducts() as $subProduct) {
$variant = [
"id" => $subProduct->getId(),
"name" => $subProduct->getName(), // String
"status" => $subProduct->getStatus() == 1 ? 'published' : 'draft', // (Optional) String
"created_at" => (new DateTime($subProduct->getCreatedAt()))->format(DateTime::ATOM), // (Optional) String (ISO 8601 format DateTime)
"modified_at" => (new DateTime($subProduct->getUpdatedAt()))->format(DateTime::ATOM), // (Optional) String (ISO 8601 format DateTime)
"stock" => $subProduct->getStockItem()->getQty(), // (Optional) Integer, If null assumed to be infinite.
"in_stock" => $subProduct->isInStock(), // (Optional) Boolean
"price" => $subProduct->getPrice(), // Float
"platform_data" => [ // (Optional) Hash/Object of attributes to store about the product specific to the integration platform (can be used in future filters)
"sku" => $subProduct->getSku()
]
];

$variantImage = $subProduct->getThumbnailUrl();
if ($variantImage != $thumb && stripos($variantImage, '/placeholder') === false){
$variant['thumbnail_url'] = $subProduct->getThumbnailUrl();
}

$variantAttrVals = [];
foreach ($cfgAttr as $attr) {
$attrValIndex = $subProduct->getData($attr['attribute_code']);
foreach ($attr['values'] as $attrVal) {
if ($attrVal['value_index'] == $attrValIndex) {
$variantAttrVals[] = $attrVal['label'];
}
}
# code...
}
$variant['name'] = implode(' / ', $variantAttrVals);

$productData['variants'][] = $variant;
}
}

return json_encode($productData);
}

public function getProductId()
{
return $this->getProduct()->getId();
}
}
76 changes: 67 additions & 9 deletions ...ommunity/Fera/Aiconnector/Helper/Data.php → ...pp/code/community/Fera/Ai/Helper/Data.php
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

class Fera_Aiconnector_Helper_Data extends Mage_Core_Helper_Abstract
class Fera_Ai_Helper_Data extends Mage_Core_Helper_Abstract
{
/**
* Write to the Fera.ai log file
Expand Down Expand Up @@ -110,7 +110,12 @@ public function getApiUrl()
if (isset($_ENV['FERA_AI_API_URL'])) {
return $_ENV['FERA_AI_API_URL'];
}
return "https://app.fera.ai/api/v1";

$urlFromConfig = Mage::getStoreConfig('fera_ai/fera_ai_group/api_url');
if ($urlFromConfig) {
return $urlFromConfig;
}
return "https://app.fera.ai/api/v2";
}

/**
Expand All @@ -125,7 +130,13 @@ public function getJsUrl()
if (isset($_ENV['FERA_AI_JS_URL'])) {
return $_ENV['FERA_AI_JS_URL'];
}
return "https://cdn.fera.ai/js/bananastand.js";

$urlFromConfig = Mage::getStoreConfig('fera_ai/fera_ai_group/js_url');
if ($urlFromConfig) {
return $urlFromConfig;
}

return "https://cdn.fera.ai/js/fera.js";
}

/**
Expand All @@ -143,24 +154,71 @@ public function isDebugMode()
return Mage::getStoreConfigFlag('fera_ai/general/debug_mode');
}

public function serializeQuoteItems($items)
{
$configurableItems = [];
$itemMap = [];
$childItems = [];
foreach ($items as $cartItem) {

if ($cartItem->getParentItemId()) {
$childItems[] = $cartItem;
} else {
$itemMap[$cartItem->getId()] = [
'product_id' => $cartItem->getProductId(),
'price' => $cartItem->getPrice(),
'total' => $cartItem->getRowTotal(),
'name' => $cartItem->getName()
];
if ($cartItem->getProductType() == 'configurable') {
$configurableItems[$cartItem->getId()] = $itemMap[$cartItem->getId()];
}
}

}

foreach ($childItems as $cartItem) {
if ($configurableItems[$cartItem->getParentItemId()]) {
// product is configurable
$itemMap[$cartItem->getParentItemId()]['name'] = $cartItem->getName();
$itemMap[$cartItem->getParentItemId()]['variant_id'] = $cartItem->getProductId();
} else {
// product is bundle or something else, just add it as a normal item

$itemMap[$cartItem->getId()] = [
'product_id' => $cartItem->getProductId(),
'price' => $cartItem->getPrice(),
'total' => $cartItem->getRowTotal(),
'name' => $cartItem->getName()
];
}
}

return array_values($itemMap);
}

/**
* @return json - The contents of the cart as a json string.
*/
public function getCartJson()
{
$cartItems = Mage::getModel('checkout/cart')->getItems();
if (empty($cartItems)) {
return "[]";
}
return json_encode($cartItems->getData());
$quote = Mage::getSingleton('checkout/session')->getQuote();
$data = [
'currency' => Mage::app()->getStore()->getCurrentCurrencyCode(),
'total' => $quote->getGrandTotal(),
];

$data['items'] = $this->serializeQuoteItems($quote->getItemsCollection());

return json_encode($data);
}

/**
* @return string - JS to trigger debug mode if required.
*/
public function getDebugJs() {
if ($this->isDebugMode()) {
return "window.__bsioDebugMode = true;";
return "window.feraDebugMode = true;";
}
return "";
}
Expand Down
68 changes: 68 additions & 0 deletions src/app/code/community/Fera/Ai/Model/Order.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php
/**
* This client handles the creation of order JSON for sending to Fera
*/
class Fera_Ai_Model_Order extends Varien_Object
{

protected $order;

/**
* Set the order for this model
* @param Mage_Sales_Model_Order $order
* @return $this
*/
public function loadFromMageOrder($order)
{
$this->order = $order;
return $this;
}

/**
* Format our mage order object into JSON for sending VIA js api
* @return JSON
*/
public function getJson()
{
$order = $this->order;

$customerId = $order->getCustomerId();
if (!empty($customerId)) {
$customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
$addressObj = $customer->getPrimaryShippingAddress();
$address;
if (!empty($addressObj)) {
$address = $addressObj->getData();
}
$customer = array(
'id' => $customerId,
'first_name' => $customer->getFirstname(),
'email' => $customer->getEmail(),
'address' => $address
);
}

$currencyCode = $order->getOrderCurrencyCode();
$total = $order->getGrandTotal();
$totalUsd = Mage::helper('directory')->currencyConvert($total, $currencyCode, 'USD');

$orderData = array(
'id' => $order->getId(),
'number' => $order->getIncrementId(),

'total' => $total,
'total_usd' => $totalUsd,

'created_at' => (new DateTime($order->getCreatedAt()))->format(DateTime::ATOM),
'modified_at' => (new DateTime($order->getUpdatedAt()))->format(DateTime::ATOM),

'line_items' => Mage::helper('fera_ai')->serializeQuoteItems($order->getItemsCollection()),

'customer' => $customer,
'source_name' => 'web'
);

return json_encode($orderData);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php
class Fera_Ai_InstallationController extends Mage_Core_Controller_Front_Action
{
protected function _getHelper()
{
return Mage::helper('fera_ai');
}


public function checkAction()
{
try {
$params = $this->getRequest()->getParams();

if (Mage::getStoreConfig('fera_ai/fera_ai_group/secret_key') != $params['sk']) {
die("Invalid key");
}

Mage::app()->cleanCache();

$responseData = [
"version" => ((array)Mage::getConfig()->getNode('modules/Fera_Ai/version'))[0],
"public_key" => $this->_getHelper()->getPublicKey(),
"api_url" => $this->_getHelper()->getApiUrl(),
"js_url" => $this->_getHelper()->getJsUrl()
];

$response = json_encode($responseData);
} catch (Mage_Core_Exception $e) {
$response = $e->getMessage();
} catch (Exception $e) {
$response = 'Error: System error during request';
}

$this->getResponse()->setBody($response);
return $this;
}


/**
*/
public function autoconfigureAction()
{
try {
$params = $this->getRequest()->getParams();

if (Mage::getStoreConfig('fera_ai/fera_ai_group/secret_key')) {
die("This account has already been auto-configured and cannot be auto-configured again. If you want to update the API credentials please go to the System settings and enter in the API credentials manually.");
}

Mage::getConfig()->saveConfig('fera_ai/fera_ai_group/secret_key', $params['sk']);
Mage::getConfig()->saveConfig('fera_ai/fera_ai_group/public_key', $params['pk']);

if ($params['api_url']) {
Mage::getConfig()->saveConfig('fera_ai/fera_ai_group/api_url', $params['api_url']);
}

if ($params['js_url']) {
Mage::getConfig()->saveConfig('fera_ai/fera_ai_group/js_url', $params['js_url']);
}

Mage::app()->cleanCache();

$response = "Automatic confiuration was successful. You may now close this window.";
} catch (Mage_Core_Exception $e) {
$response = $e->getMessage();
} catch (Exception $e) {
$response = 'Error: System error during request';
}
$this->getResponse()->setBody($response);
return $this;
}

}
Loading

0 comments on commit 74b0423

Please sign in to comment.