Initial commit

This commit is contained in:
2025-04-12 10:34:26 -04:00
parent 06ffcc1400
commit f094a1f705
11 changed files with 315 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
<?php
namespace SoundPress\WHIOrders\Block\System\Config;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Data\Form\Element\AbstractElement;
class TestConnection extends Field
{
protected $_template = 'SoundPress_WHIOrders::system/config/test_connection.phtml';
public function __construct(Context $context, array $data = [])
{
parent::__construct($context, $data);
}
public function render(AbstractElement $element)
{
$element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
return parent::render($element);
}
protected function _getElementHtml(AbstractElement $element)
{
return $this->_toHtml();
}
public function getCustomUrl()
{
return $this->getUrl('whiorders/connection/index');
}
public function getButtonHtml()
{
$button = $this->getLayout()->createBlock('Magento\Backend\Block\Widget\Button')->setData(['id' => 'whi_test_connection', 'label' => 'Test Connection',]);
return $button->toHtml();
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace SoundPress\WHIOrders\Controller\Adminhtml\Connection;
use Magento\Backend\App\Action\Context;
use SoundPress\WHIOrders\Helper\ConfigHelper;
use GuzzleHttp\ClientFactory;
class Index extends \Magento\Backend\App\Action
{
protected $clientFactory;
protected $configHelper;
public function __construct(
Context $context,
ClientFactory $clientFactory,
ConfigHelper $configHelper,
) {
$this->clientFactory = $clientFactory;
$this->configHelper = $configHelper;
parent::__construct($context);
$baseUrl = $this->configHelper->getBaseUrl();
$token = $this->configHelper->getApiToken();
$client = $this->clientFactory->create(['config' => [
'http_errors' => false,
'base_uri' => $baseUrl,
'headers' => [
'Content-type' => 'application/json',
'Authorization' => "Bearer $token"
]
]]);
$result = $client->request('GET', 'whi/connectiontest');
http_response_code($result->getStatusCode());
exit;
}
public function execute() { }
}

26
Helper/ConfigHelper.php Normal file
View File

@@ -0,0 +1,26 @@
<?php
namespace SoundPress\WHIOrders\Helper;
use Magento\Framework\App\Config\ScopeConfigInterface;
use \Magento\Framework\App\Helper\AbstractHelper;
class ConfigHelper extends AbstractHelper
{
protected $scopeConfig;
public function __construct(ScopeConfigInterface $scopeConfig)
{
$this->scopeConfig = $scopeConfig;
}
public function getApiToken()
{
return $this->scopeConfig->getValue('whiorders/api/api_token', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
}
public function getBaseUrl()
{
return $this->scopeConfig->getValue('whiorders/api/base_url', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace SoundPress\WHIOrders\Observer\Checkout;
use SoundPress\WHIOrders\Helper\ConfigHelper;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use GuzzleHttp\ClientFactory;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Log\LoggerInterface;
class SendWHIOrder implements ObserverInterface
{
protected $clientFactory;
protected $configHelper;
protected $logger;
public function __construct(
ClientFactory $clientFactory,
ConfigHelper $configHelper,
LoggerInterface $logger
) {
$this->clientFactory = $clientFactory;
$this->configHelper = $configHelper;
$this->logger = $logger;
}
function execute(Observer $observer)
{
$order = $observer->getEvent()->getOrder();
$shippingAddress = $order->getShippingAddress();
$billingAddress = $order->getBillingAddress();
$whiOrder = [
'metadata' => [
'platform' => 'Magento',
'plaformOrderId' => $order->getId(),
],
'billingAddress' => [
'firstName' => $billingAddress->getFirstname(),
'lastName' => $billingAddress->getLastname(),
'address1' => $billingAddress->getStreet()[0],
'address2' => count($billingAddress->getStreet()) > 1 ? $billingAddress->getStreet()[1] : null,
'city' => $billingAddress->getCity(),
'state' => $billingAddress->getRegion(),
'zip' => $billingAddress->getPostCode(),
'email' => $billingAddress->getEmail(),
'phone' => $billingAddress->getTelephone()
],
'shippingAddress' => [
'firstName' => $shippingAddress->getFirstname(),
'lastName' => $shippingAddress->getLastname(),
'address1' => $shippingAddress->getStreet()[0],
'address2' => count($shippingAddress->getStreet()) > 1 ? $shippingAddress->getStreet()[1] : null,
'city' => $shippingAddress->getCity(),
'state' => $shippingAddress->getRegion(),
'zip' => $shippingAddress->getPostCode(),
],
'amounts' => [
'shipping' => $order->getShippingAmount(),
'tax' => $order->getTaxAmount(),
'subtotal' => $order->getSubtotal(),
'total' => $order->getGrandTotal(),
],
'parts' => []
];
foreach ($order->getAllItems() as $item) {
$part = [
'sku' => $item->getSku(),
'price' => $item->getPrice(),
'salesTax' => $item->getTaxAmount(),
'discount' => $item->getDiscountAmount(),
'quantity' => $item->getQtyOrdered(),
];
array_push($whiOrder['parts'], $part);
}
$baseUrl = $this->configHelper->getBaseUrl();
$token = $this->configHelper->getApiToken();
$client = $this->clientFactory->create(['config' => [
'base_uri' => $baseUrl,
'headers' => [
'Content-type' => 'application/json',
'Authorization' => "Bearer $token"
]
]]);
try {
$client->request('POST', 'whi/orders', [
'body' => json_encode($whiOrder)
]);
} catch (GuzzleException $exception) {
$this->logger->error('Error sending ' . $order->getId() . ' to WHI for processing. Server returned HTTP response code ' . $exception->getCode());
}
}
}

26
composer.json Normal file
View File

@@ -0,0 +1,26 @@
{
"name": "soundpress/whi-orders",
"description": "An integration with WHI's Orderlink API",
"require": {
"php": "8.1|8.2",
"magento/project-community-edition": "2.4.6-p9"
},
"authors": [
{
"name": "Tom Raterman",
"email": "tom@soundpress.com",
"homepage": "https://www.soundpress.com",
"role": "Developer"
}
],
"type": "magento2-module",
"license": "proprietary",
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"SoundPress\\WhiOrders\\": ""
}
}
}

11
etc/adminhtml/routes.xml Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<!--Use router 'admin' for admin route -->
<router id="admin">
<!--Define a custom route with id and frontName -->
<route id="SoundPress_WHIOrders" frontName="whiorders">
<!--The module which this route match to-->
<module name="SoundPress_WHIOrders"/>
</route>
</router>
</config>

26
etc/adminhtml/system.xml Normal file
View File

@@ -0,0 +1,26 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="soundpress" translate="label" sortOrder="1000">
<label>Sound Press</label>
</tab>
<section id="whiorders" translate="label" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<class>separator-top</class>
<label>WHI Orders</label>
<tab>soundpress</tab>
<resource>Magento_Backend::admin</resource>
<group id="api" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>API Configuration</label>
<field id="base_url" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Base Url</label>
</field>
<field id="api_token" translate="label" type="password" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>API Token</label>
</field>
<field id="auth_test" translate="label" type="button" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<frontend_model>SoundPress\WHIOrders\Block\System\Config\TestConnection</frontend_model>
</field>
</group>
</section>
</system>
</config>

6
etc/events.xml Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_submit_all_after">
<observer name="SendWHIOrder" instance="SoundPress\WHIOrders\Observer\Checkout\SendWHIOrder" />
</event>
</config>

4
etc/module.xml Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="SoundPress_WHIOrders" setup_version="1.0.0"/>
</config>

6
registration.php Normal file
View File

@@ -0,0 +1,6 @@
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'SoundPress_WHIOrders',
__DIR__
);

View File

@@ -0,0 +1,35 @@
<?php $url = $block->getCustomUrl(); ?>
<script type="text/javascript">
require(["jquery"],function($) {
$('#whi_test_connection').click(function() {
if (!confirm('Save the configuration before testing.')) {
return;
}
$.ajax({
url: "<?php echo $url; ?>",
type: 'GET',
complete: function (response) {
switch (response.status) {
case 204:
alert('Connection successful.');
break;
case 401:
case 403:
alert('Invalid API key.');
break;
default:
alert('Failed to connect to the provided URL.');
break;
}
}
});
});
});
</script>
<?php echo $block->getButtonHtml(); ?>
<p><sub><em>Note: Currently only works in Chromium-based browsers (Firefox blocks script execution).</em></sub></p>