diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..85e7c1dfcb7fbb33f932c81024018cd8c10519da --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/.idea/ diff --git a/.idea/magento-uafrica-shipping-extension.iml b/.idea/magento-uafrica-shipping-extension.iml index c956989b29ad0767edc6cf3a202545927c3d1e76..0aabce5bc3faeafa3523a9a6680f34bd794777a7 100644 --- a/.idea/magento-uafrica-shipping-extension.iml +++ b/.idea/magento-uafrica-shipping-extension.iml @@ -1,7 +1,9 @@ <?xml version="1.0" encoding="UTF-8"?> <module type="WEB_MODULE" version="4"> <component name="NewModuleRootManager"> - <content url="file://$MODULE_DIR$" /> + <content url="file://$MODULE_DIR$"> + <sourceFolder url="file://$MODULE_DIR$/" isTestSource="false" packagePrefix="Plugin\" /> + </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> </component> diff --git a/.idea/php.xml b/.idea/php.xml index 0e1f041b9ee90482c568931419b52676b1beb93b..d32d97b5a8a4ae98e384adb1dc4342f804d52c96 100644 --- a/.idea/php.xml +++ b/.idea/php.xml @@ -1,11 +1,27 @@ <?xml version="1.0" encoding="UTF-8"?> <project version="4"> + <component name="MessDetectorOptionsConfiguration"> + <option name="transferred" value="true" /> + </component> + <component name="PHPCSFixerOptionsConfiguration"> + <option name="transferred" value="true" /> + </component> + <component name="PHPCodeSnifferOptionsConfiguration"> + <option name="highlightLevel" value="WARNING" /> + <option name="transferred" value="true" /> + </component> <component name="PhpIncludePathManager"> <include_path> <path value="$PROJECT_DIR$/vendor/composer" /> </include_path> </component> - <component name="PhpProjectSharedConfiguration" php_language_level="7.4"> + <component name="PhpProjectSharedConfiguration" php_language_level="8.1"> <option name="suggestChangeDefaultLanguageLevel" value="false" /> </component> + <component name="PhpStanOptionsConfiguration"> + <option name="transferred" value="true" /> + </component> + <component name="PsalmOptionsConfiguration"> + <option name="transferred" value="true" /> + </component> </project> \ No newline at end of file diff --git a/Block/System/Config/Form/Field/Version.php b/Block/System/Config/Form/Field/Version.php index 262bf7de50bfc5e17f8f4f449cae220355b408da..52a54e718795145f99d5722b39118853523f6d8b 100644 --- a/Block/System/Config/Form/Field/Version.php +++ b/Block/System/Config/Form/Field/Version.php @@ -1,31 +1,31 @@ <?php -namespace bobgo\CustomShipping\Block\System\Config\Form\Field; +namespace BobGroup\BobGo\Block\System\Config\Form\Field; use Magento\Framework\Data\Form\Element\AbstractElement; /** * Displays Version number in System Configuration - * @category Bob Go + * @category BobGroup * @package bobgo_CustomShipping - * @author Bob Go - * @website https://www.bobgo.co.za + * @author info@bob.co.za + * @website https://www.bob.co.za */ class Version extends \Magento\Config\Block\System\Config\Form\Field { const EXTENSION_URL = 'https://www.bobgo.co.za'; /** - * @var \bobgo\CustomShipping\Helper\Data $helper + * @var \BobGroup\BobGo\Helper\Data $helper */ protected $_helper; /** * @param \Magento\Backend\Block\Template\Context $context - * @param \bobgo\CustomShipping\Helper\Data $helper + * @param \BobGroup\BobGo\Helper\Data $helper */ public function __construct( \Magento\Backend\Block\Template\Context $context, - \bobgo\CustomShipping\Helper\Data $helper + \BobGroup\BobGo\Helper\Data $helper ) { $this->_helper = $helper; parent::__construct($context); @@ -39,7 +39,7 @@ class Version extends \Magento\Config\Block\System\Config\Form\Field protected function _getElementHtml(AbstractElement $element) { $extensionVersion = $this->_helper->getExtensionVersion(); - $extensionTitle = 'Bob Go'; + $extensionTitle = 'BobGo'; $versionLabel = sprintf( '<a href="%s" title="%s" target="_blank">%s</a>', self::EXTENSION_URL, diff --git a/Helper/Data.php b/Helper/Data.php index 0b3e07a2972a63d06db5d3888cde878072a7216e..d0627eefd27a235e7b0b5b498f8e22ab4fd1a215 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -1,5 +1,5 @@ <?php -namespace bobgo\CustomShipping\Helper; +namespace BobGroup\BobGo\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; @@ -15,8 +15,8 @@ use Magento\Store\Model\ScopeInterface; class Data extends AbstractHelper { - const XML_PATH_ENABLED = 'bobgo_CustomShipping/general/enabled'; - const XML_PATH_DEBUG = 'bobgo_CustomShipping/general/debug'; + const XML_PATH_ENABLED = 'BobGroup_BobGo/general/enabled'; + const XML_PATH_DEBUG = 'BobGroup_BobGo/general/debug'; /** * @var \Psr\Log\LoggerInterface @@ -65,7 +65,7 @@ class Data extends AbstractHelper public function getExtensionVersion() { - $moduleCode = 'bobgo_CustomShipping'; + $moduleCode = 'BobGroup_BobGo'; $moduleInfo = $this->_moduleList->getOne($moduleCode); return $moduleInfo['setup_version']; } diff --git a/Model/Carrier/AdditionalInfo.php b/Model/Carrier/AdditionalInfo.php new file mode 100644 index 0000000000000000000000000000000000000000..0b002a0ff7b8fdf82842f1adceef888dd8aaf052 --- /dev/null +++ b/Model/Carrier/AdditionalInfo.php @@ -0,0 +1,80 @@ +<?php + +namespace BobGroup\BobGo\Model\Carrier; + +/** + * Get the AdditionalInfo information from the request body and return it + */ +class AdditionalInfo +{ + + /** + * @return mixed|string + */ + public function getDestComp(): mixed + { + $data = json_decode(file_get_contents('php://input'), true); + + if (isset($data['address']['company'])) { + $destComp = $data['address']['company']; + } else { + $destComp = ''; + } + return $destComp; + } + + public function getSuburb(): mixed + { + + $data = json_decode(file_get_contents('php://input'), true); + + if (isset($data['address']['custom_attributes'][0]['value'])) { + $destSub = $data['address']['custom_attributes'][0]['value']; + //print_r($destSub); + } else { + $destSub = ''; + } + return $destSub; + } + + /** + * @return mixed|string + */ + public function getDestTelephone(): mixed + { + $data = json_decode(file_get_contents('php://input'), true); + + if (isset($data['address']['telephone'])) { + $destTelephone = $data['address']['telephone']; + } else { + $destTelephone = ''; + } + return $destTelephone; + } + + + /** + * @var \BobGroup\BobGo\Model\Carrier\AdditionalInfo + */ + public $countryFactory; + + public function __construct($countryFactory) + { + $this->countryFactory = $countryFactory; + } + + /** + * country full name + * + * @return string + */ + public function getCountryName($countryId): string + { + $countryName = ''; + $country = $this->countryFactory->create()->loadByCode($countryId); + if ($country) { + $countryName = $country->getName(); + } + return $countryName; + } +} diff --git a/Model/Carrier/CustomShipping.php b/Model/Carrier/BobGo.php similarity index 67% rename from Model/Carrier/CustomShipping.php rename to Model/Carrier/BobGo.php index af748b6e3e1a9b29f0c5bd8c5acbb7522f4a7b77..2c556743c3ae9985de18760c4ae0361293382a59 100644 --- a/Model/Carrier/CustomShipping.php +++ b/Model/Carrier/BobGo.php @@ -1,7 +1,7 @@ <?php declare(strict_types=1); -namespace bobgo\CustomShipping\Model\Carrier; +namespace BobGroup\BobGo\Model\Carrier; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; use Magento\CatalogInventory\Api\StockRegistryInterface; @@ -20,9 +20,9 @@ use Magento\Framework\Xml\Security; use Magento\Quote\Model\Quote\Address\RateRequest; use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory; use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory; +use Magento\Sales\Model\Order\Shipment; use Magento\Shipping\Model\Carrier\AbstractCarrier; use Magento\Shipping\Model\Carrier\AbstractCarrierOnline; -use Magento\Shipping\Model\Carrier\CarrierInterface; use Magento\Shipping\Model\Rate\Result; use Magento\Shipping\Model\Rate\ResultFactory; use Magento\Shipping\Model\Simplexml\ElementFactory; @@ -41,11 +41,10 @@ use Psr\Log\LoggerInterface; * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.TooManyFields) */ -class CustomShipping extends AbstractCarrierOnline implements CarrierInterface +class BobGo extends AbstractCarrierOnline implements \Magento\Shipping\Model\Carrier\CarrierInterface { /** * Code of the carrier - *` * @var string */ public const CODE = 'bobgo'; @@ -74,6 +73,12 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface */ protected $_result = null; + /** + * Container types that could be customized for bobgo carrier + * + * @var string[] + */ + protected $_customizableContainerTypes = ['YOUR_PACKAGING']; /** * @var \Magento\Store\Model\StoreManagerInterface @@ -102,7 +107,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface */ protected JsonFactory $jsonFactory; private $cartRepository; - private Company $company; + public AdditionalInfo $additionalInfo; /** @@ -130,29 +135,29 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory, - \Psr\Log\LoggerInterface $logger, - Security $xmlSecurity, - \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory, - \Magento\Shipping\Model\Rate\ResultFactory $rateFactory, - \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory, - \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory, - \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory, - \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory, - \Magento\Directory\Model\RegionFactory $regionFactory, - \Magento\Directory\Model\CountryFactory $countryFactory, - \Magento\Directory\Model\CurrencyFactory $currencyFactory, - \Magento\Directory\Helper\Data $directoryData, - \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\Module\Dir\Reader $configReader, + \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, + \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory, + \Psr\Log\LoggerInterface $logger, + Security $xmlSecurity, + \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory, + \Magento\Shipping\Model\Rate\ResultFactory $rateFactory, + \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory, + \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory, + \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory, + \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory, + \Magento\Directory\Model\RegionFactory $regionFactory, + \Magento\Directory\Model\CountryFactory $countryFactory, + \Magento\Directory\Model\CurrencyFactory $currencyFactory, + \Magento\Directory\Helper\Data $directoryData, + \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry, + \Magento\Store\Model\StoreManagerInterface $storeManager, + \Magento\Framework\Module\Dir\Reader $configReader, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory, - JsonFactory $jsonFactory, - CurlFactory $curlFactory, - array $data = [] - - ) { + JsonFactory $jsonFactory, + CurlFactory $curlFactory, + array $data = [] + ) + { $this->_storeManager = $storeManager; $this->_productCollectionFactory = $productCollectionFactory; @@ -176,7 +181,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface ); $this->jsonFactory = $jsonFactory; $this->curl = $curlFactory->create(); - $this->company = new Company(); + $this->additionalInfo = new AdditionalInfo($countryFactory); } @@ -188,10 +193,11 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface */ public function getBaseUrl(): string { - $storeBaseUrl = $this->_storeManager->getStore()->getBaseUrl(); - return parse_url($storeBaseUrl)["host"]; + $storeBase = $this->_storeManager->getStore()->getBaseUrl(); + return parse_url($storeBase, PHP_URL_HOST); } + /** * Make request to Bob Go API to get shipping rates for the cart * After all the required data is collected, it makes a request to the Bob Go API to get the shipping rates @@ -203,52 +209,125 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface return $this->uRates($payload); } + /** + * Processing additional validation to check if carrier applicable. + * + * @param \Magento\Framework\DataObject $request + * @return $this|bool|\Magento\Framework\DataObject + */ + public function processAdditionalValidation(\Magento\Framework\DataObject $request) + { + if (!count($this->getAllItems($request))) { + return false; + } + + $maxAllowedWeight = 500; //$this->getConfigData('max_package_weight'); + $errorMsg = ''; + $configErrorMsg = $this->getConfigData('specificerrmsg'); + $defaultErrorMsg = __('The shipping module is not available.'); + $showMethod = $this->getConfigData('showmethod'); + + /** @var $item \Magento\Quote\Model\Quote\Item */ + foreach ($this->getAllItems($request) as $item) { + $product = $item->getProduct(); + if ($product && $product->getId()) { + $weight = $product->getWeight(); + $stockItemData = $this->stockRegistry->getStockItem( + $product->getId(), + $item->getStore()->getWebsiteId() + ); + $doValidation = true; + + if ($stockItemData->getIsQtyDecimal() && $stockItemData->getIsDecimalDivided()) { + if ($stockItemData->getEnableQtyIncrements() && $stockItemData->getQtyIncrements() + ) { + $weight = $weight * $stockItemData->getQtyIncrements(); + } else { + $doValidation = false; + } + } elseif ($stockItemData->getIsQtyDecimal() && !$stockItemData->getIsDecimalDivided()) { + $weight = $weight * $item->getQty(); + } + + + if ($doValidation && $weight > $maxAllowedWeight) { + $errorMsg = $configErrorMsg ? $configErrorMsg : $defaultErrorMsg; + break; + } + } + } + + if (!$errorMsg && !$request->getDestPostcode() && $this->isZipCodeRequired($request->getDestCountryId())) { + + $errorMsg = __('This shipping method is not available. Please specify the zip code.'); + } + + if ($request->getDestCountryId() == 'ZA') { + $errorMsg = ''; + } else { + $errorMsg = $configErrorMsg ? $configErrorMsg : $defaultErrorMsg; + } + + if ($errorMsg && $showMethod) { + $error = $this->_rateErrorFactory->create(); + $error->setCarrier($this->_code); + $error->setCarrierTitle($this->getConfigData('title')); + $error->setErrorMessage($errorMsg); + + return $error; + } elseif ($errorMsg) { + return false; + } + + return $this; + } + /** * Collect and get rates for this shipping method based on information in $request * This is a default function that is called by Magento to get the shipping rates for the cart * @param RateRequest $request * @return Result|bool|null */ - public function collectRates(RateRequest $request): Result|bool|null + public function collectRates(RateRequest $request) { - /*** Make sure that Shipping method is enabled*/ + /*** Make sure that Shipping method is enabled*/ if (!$this->isActive()) { return false; } /** - * Gets the destination company name from Company Name field in the checkout page + * Gets the destination company name from AdditionalInfo Name field in the checkout page * This method is used is the last resort to get the company name since the company name is not available in _rateFactory */ $destComp = $this->getDestComp(); + $destSuburb = $this->getDestSuburb(); + $destPhone = $this->getDestTelephone(); - /** @var Result $result */ + /** @var \Magento\Shipping\Model\Rate\Result $result */ $result = $this->_rateFactory->create(); $destination = $request->getDestPostcode(); - $destCountry = $request->getDestCountryId(); + $destCountryCode = $request->getDestCountryId(); $destRegion = $request->getDestRegionCode(); $destCity = $request->getDestCity(); $destStreet = $request->getDestStreet(); + $destCountry = $this->getCountryName($destCountryCode); + /** Destination Information */ [$destStreet1, $destStreet2, $destStreet3] = $this->destStreet($destStreet); + /** Origin Information */ - [$originStreet, $originRegion, $originCountry, $originCity, $originStreet1, $originStreet2, $storeName, $baseIdentifier, $originSuburb] = $this->storeInformation(); - /** Get all the items in the cart */ - $items = $request->getAllItems(); + [$originStreet, $originRegion, $originCountryCode, $originCity, $originStreet1, $originStreet2, $storeName, $baseIdentifier, $originSuburb, $weightUnit, $originPhone] = $this->storeInformation(); + /** Get all items in cart */ + $items = $request->getAllItems(); $itemsArray = []; + $itemsArray = $this->getStoreItems($items, $weightUnit, $itemsArray); + + $originCountry = $this->getCountryName($originCountryCode); - foreach ($items as $item) { - $itemsArray[] = [ - 'sku' => $item->getSku(), - 'quantity' => $item->getQty(), - 'price' => $item->getPrice(), - 'grams' => $item->getWeight() * 1000, - ]; - } $payload = [ 'identifier' => $baseIdentifier, @@ -260,19 +339,23 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface 'city' => $originCity, 'suburb' => $originSuburb, 'province' => $originRegion, - 'country_code' => $originCountry, + 'country_code' => $originCountryCode, 'postal_code' => $originStreet, + 'telephone' => $originPhone, + 'country' => $originCountry, ], 'destination' => [ 'company' => $destComp, 'address1' => $destStreet1, 'address2' => $destStreet2, - 'suburb' => $destStreet3, + 'suburb' => $destSuburb, 'city' => $destCity, 'province' => $destRegion, - 'country_code' => $destCountry, + 'country_code' => $destCountryCode, 'postal_code' => $destination, + 'telephone' => $destPhone, + 'country' => $destCountry ], 'items' => $itemsArray, ] @@ -284,16 +367,12 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface } /** - * Get The store information from the Magento store configuration and return it as an array - * In magento 2 there is origin information in the store information section of the configuration, so we get it from there - * since Store Information has the origin information including suburb field that we Injected upon Bob Go Extension installation - * which is not available in the origin section * @return array */ public function storeInformation(): array { /** Store Origin details */ - $originCountry = $this->_scopeConfig->getValue( + $originCountryCode = $this->_scopeConfig->getValue( 'general/store_information/country_id', ScopeInterface::SCOPE_STORE ); @@ -331,17 +410,28 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface ScopeInterface::SCOPE_STORE ); + $weightUnit = $this->_scopeConfig->getValue( + 'general/locale/weight_unit', + ScopeInterface::SCOPE_STORE + ); + + $originTelephone = $this->_scopeConfig->getValue( + 'general/store_information/phone', + ScopeInterface::SCOPE_STORE + ); + $baseIdentifier = $this->getBaseUrl(); - return array($originStreet, $originRegion, $originCountry, $originCity, $originStreet1, $originStreet2, $storeName, $baseIdentifier, $originSuburb); + return array($originStreet, $originRegion, $originCountryCode, $originCity, $originStreet1, $originStreet2, $storeName, $baseIdentifier, $originSuburb, $weightUnit, $originTelephone); } + /** * Get result of request * * @return Result|null */ - public function getResult(): ?Result + public function getResult() { if (!$this->_result) { $this->_result = $this->_trackFactory->create(); @@ -349,6 +439,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface return $this->_result; } + /** * Get final price for shipping method with handling fee per package * @@ -357,7 +448,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface * @param float $handlingFee * @return float */ - protected function _getPerpackagePrice($cost, $handlingType, $handlingFee): float + protected function _getPerpackagePrice($cost, $handlingType, $handlingFee) { if ($handlingType == AbstractCarrier::HANDLING_TYPE_PERCENT) { return $cost + $cost * $this->_numBoxes * $handlingFee / self::UNITS; @@ -374,7 +465,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface * @param float $handlingFee * @return float */ - protected function _getPerorderPrice($cost, $handlingType, $handlingFee): float + protected function _getPerorderPrice($cost, $handlingType, $handlingFee) { if ($handlingType == self::HANDLING_TYPE_PERCENT) { return $cost + $cost * $handlingFee / self::UNITS; @@ -383,6 +474,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface return $cost + $handlingFee; } + /** * Get configuration data of carrier * @@ -391,20 +483,15 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface * @return array|false * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ - public function getCode($type, $code = ''): bool|array + public function getCode($type, $code = '') { $codes = [ 'method' => [ - 'bobgo' => __('Bob Go'), - ], - 'delivery_confirmation_types' => [ - 'NO_SIGNATURE_REQUIRED' => __('Not Required'), - 'ADULT' => __('Adult'), - 'DIRECT' => __('Direct'), - 'INDIRECT' => __('Indirect'), + 'bobGo' => __('BobGo'), ], 'unit_of_measure' => [ - 'KG' => __('Kilograms'), + 'KGS' => __('Kilograms'), + 'LBS' => __('Pounds'), ], ]; @@ -421,16 +508,16 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface } } + /** - * Get tracking info by tracking number or tracking request - * Without getTrackingInfo() method, Magento will not show tracking info on frontend + * Get tracking * * @param string|string[] $trackings * @return Result|null */ - public function getTracking($trackings): ?Result + public function getTracking($trackings) { - $this->setTrackingReqeust(); + $this->setTrackingRequest(); if (!is_array($trackings)) { $trackings = [$trackings]; @@ -444,11 +531,11 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface } /** - * Set tracking request data for request by getting context from Magento + * Set tracking request * * @return void */ - protected function setTrackingReqeust(): void + protected function setTrackingRequest() { $r = new \Magento\Framework\DataObject(); @@ -459,23 +546,23 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface } /** - * Send request for the actual tracking info and process response + * Send request for tracking * * @param string[] $tracking * @return void */ - protected function _getXMLTracking($tracking): void + protected function _getXMLTracking($tracking) { $this->_parseTrackingResponse($tracking); } /** - * Parse tracking response and set tracking info + * Parse tracking response * * @param string $trackingValue * @return void */ - protected function _parseTrackingResponse($trackingValue): void + protected function _parseTrackingResponse($trackingValue) { $result = $this->getResult(); $carrierTitle = $this->getConfigData('title'); @@ -485,14 +572,23 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface } foreach ($trackingValue as $trackingReference) { $tracking = $this->_trackStatusFactory->create(); + $tracking->setCarrier(self::CODE); $tracking->setCarrierTitle($carrierTitle); - $tracking->setUrl(sprintf(uData::TRACKING, $this->getBaseUrl(), $trackingReference)); + + //Production + /* $tracking->setUrl(sprintf(uData::TRACKING, $this->getBaseUrl(), $trackingReference)); $tracking->setTracking($trackingReference); $tracking->addData($this->processTrackingDetails($trackingReference)); + */ + + //Dev + $tracking->setUrl(uData::TRACKING . $trackingReference); + $tracking->setTracking($trackingReference); + $tracking->addData($this->processTrackingDetails($trackingReference)); + $result->append($tracking); - $counter ++; - echo (sprintf(uData::TRACKING, $this->getBaseUrl(), $trackingReference)); + $counter++; } //Tracking Details Not Available @@ -509,7 +605,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface * * @return string */ - public function getResponse(): string + public function getResponse() { $statuses = ''; if ($this->_result instanceof \Magento\Shipping\Model\Tracking\Result) { @@ -538,7 +634,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface * * @return array */ - public function getAllowedMethods(): array + public function getAllowedMethods() { $allowed = explode(',', $this->getConfigData('allowed_methods')); $arr = []; @@ -549,13 +645,14 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface return $arr; } + /** * Do shipment request to carrier web service, obtain Print Shipping Labels and process errors in response * Also another magic function that is required to be implemented by carrier model * @param \Magento\Framework\DataObject $request * @return \Magento\Framework\DataObject */ - protected function _doShipmentRequest(\Magento\Framework\DataObject $request): ?DataObject + protected function _doShipmentRequest(\Magento\Framework\DataObject $request) { return null; @@ -568,7 +665,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface * * @return bool */ - public function rollBack($data): bool + public function rollBack($data) { return true; } @@ -581,7 +678,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface * @return array|bool * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ - public function getContainerTypes(\Magento\Framework\DataObject $params = null): bool|array + public function getContainerTypes(\Magento\Framework\DataObject $params = null) { $result = []; $allowedContainers = $this->getConfigData('containers'); @@ -695,7 +792,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface } /** - * Perform API Request to Bob Go API and return response + * Perfom API Request to bobgo API and return response * @param array $payload * @param Result $result * @return void @@ -717,7 +814,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface */ private function _requestTracking($trackInfo, array $result): array { - $response = $this->trackBobGoShipment($trackInfo); + $response = $this->trackbobgoShipment($trackInfo); $result = $this->prepareActivity($response[0], $result); @@ -732,7 +829,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface */ protected function _formatRates(mixed $rates, Result $result): void { - if (empty($rates)) { + if (!isset($rates['rates'])) { $error = $this->_rateErrorFactory->create(); $error->setCarrierTitle($this->getConfigData('title')); $error->setErrorMessage($this->getConfigData('specificerrmsg')); @@ -742,7 +839,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface foreach ($rates['rates'] as $title) { $method = $this->_rateMethodFactory->create(); - if (isset($title)){ + if (isset($title)) { $method->setCarrier(self::CODE); @@ -768,6 +865,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface } } + /** * Prepare received checkpoints and activity from Bob Go Shipment Tracking API * @param $response @@ -782,7 +880,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface 'activity' => $checkpoint['status'], 'deliverydate' => $this->formatDate($checkpoint['time']), 'deliverytime' => $this->formatTime($checkpoint['time']), - // 'deliverylocation' => 'Unavailable',//TODO: remove this line + // 'deliverylocation' => 'Unavailable',//TODO: remove this line ]; } return $result; @@ -816,12 +914,13 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface } } + /** * Curl request to Bob Go Shipment Tracking API * @param $trackInfo * @return mixed */ - private function trackBobGoShipment($trackInfo): mixed + private function trackbobgoShipment($trackInfo): mixed { $this->curl->get(uData::TRACKING . $trackInfo); @@ -846,6 +945,7 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface return $rates; } + /** * @param string $destStreet * @return string[] @@ -874,11 +974,11 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface protected function deliveryDays(int $min_delivery_date, int $max_delivery_date, $method): void { if ($min_delivery_date !== $max_delivery_date) { - $method->setCarrierTitle('delivery in '.$min_delivery_date . ' - ' . $max_delivery_date . ' days'); - }else{ + $method->setCarrierTitle('delivery in ' . $min_delivery_date . ' - ' . $max_delivery_date . ' days'); + } else { $method->setCarrierTitle('delivery in ' . $min_delivery_date . ' days'); if ($min_delivery_date && $max_delivery_date == 1) { - $method->setCarrierTitle('delivery in '.$min_delivery_date . ' day'); + $method->setCarrierTitle('delivery in ' . $min_delivery_date . ' day'); } } } @@ -886,8 +986,105 @@ class CustomShipping extends AbstractCarrierOnline implements CarrierInterface /** * @return mixed|string */ - protected function getDestComp(): mixed + public function getDestComp(): mixed + { + return $this->additionalInfo->getDestComp(); + } + + /** + * @return mixed|string + */ + public function getDestSuburb(): mixed + { + return $this->additionalInfo->getSuburb(); + } + + /** + * @return mixed|string + */ + public function getDestTelephone(): mixed + { + return $this->additionalInfo->getDestTelephone(); + } + + /** + * @return mixed|string + */ + public function getCountryName(mixed $country_id): mixed + { + return $this->additionalInfo->getCountryName($country_id); + } + + /** + * @param mixed $weightUnit + * @param mixed $item + * @return float|int + */ + public function getItemWeight(mixed $weightUnit, mixed $item): int|float { - return $this->company->getDestComp(); + //1 lb = 453.59237 g exact. 1 kg = 1000 g. 1 lb = 0.45359237 kg + if ($weightUnit == 'KGS') { + $mass = $item->getWeight() ? $item->getWeight() * 1000 : 0; + } else { + $mass = $item->getWeight() ? $item->getWeight() * 0.45359237 * 1000 : 0;//Pound to Kilogram Conversion Formula + } + return $mass; + } + + /** + * @param array $items + * @param mixed $weightUnit + * @param array $itemsArray + * @return array + */ + public function getStoreItems(array $items, mixed $weightUnit, array $itemsArray): array + { + foreach ($items as $item) { + + if ($item->getParentItem()) continue; + + $productID = $item->getProductId(); + $product = $item->getProduct(); // Product Object + $description = ""; + + if ($product) { + $productFull = $product->load($productID); + // Remove meta tags from the description + $description = preg_replace('#<[^>]+>#', ' ', $productFull->getDescription()); + $description = preg_replace('!\s+!', ' ', $description); + } + + $mass = $this->getItemWeight($weightUnit, $item); + + $itemsArray[] = [ + 'sku' => $item->getSku(), + 'quantity' => $item->getQty(), + 'price' => $item->getPrice(), + 'weight' => round($mass), + 'name' => $item->getName(), + 'description' => $description, + ]; + + } + return $itemsArray; + } + + /** + * Get the list of required data fields + * @return bool + */ + public function hasRequiredData(DataObject $request): bool + { + $requiredFields = [ + 'dest_country_id', + 'dest_region_id', + ]; + + foreach ($requiredFields as $field) { + if (!$request->getData($field)) { + return false; + } + } + return true; } } diff --git a/Model/Carrier/Company.php b/Model/Carrier/Company.php deleted file mode 100644 index c0d6a932df2aa37fdcaef03a53b0cceea8adb38d..0000000000000000000000000000000000000000 --- a/Model/Carrier/Company.php +++ /dev/null @@ -1,25 +0,0 @@ -<?php - -namespace bobgo\CustomShipping\Model\Carrier; - -/** - * Get the Company information from the request body and return it - */ -class Company -{ - - /** - * @return mixed|string - */ - public function getDestComp(): mixed - { - $data = json_decode(file_get_contents('php://input'), true); - - if (isset($data['address']['company'])) { - $destComp = $data['address']['company']; - } else { - $destComp = ''; - } - return $destComp; - } -} diff --git a/Model/Carrier/uData.php b/Model/Carrier/uData.php index 8ea407092b9db8e63f32dc64e59e878851afabcc..df3a1686e3fd01edd219516128a84d8b410cd56d 100644 --- a/Model/Carrier/uData.php +++ b/Model/Carrier/uData.php @@ -1,16 +1,17 @@ <?php -namespace bobgo\CustomShipping\Model\Carrier; +namespace BobGroup\BobGo\Model\Carrier; /** * Class uData - * Bob Go API Resources for Custom Shipping - * @package bobgo\CustomShipping\Model\Carrier + * @package BobGroup\BobGo\Model\Carrier */ class uData { + /** Tracking Endpoint */ - public const TRACKING = 'https://api.dev.ship.uafrica.com/tracking?channel=%s&tracking_reference=%s'; + public const TRACKING = 'https://api.dev.bobgo.co.za/tracking?channel=%s&tracking_reference=%s'; + /*** RATES API Endpoint*/ - public const RATES_ENDPOINT = 'https://api.dev.ship.uafrica.com/rates-at-checkout/magento'; + public const RATES_ENDPOINT = 'https://api.dev.bobgo.co.za/rates-at-checkout/magento'; } diff --git a/Model/Carrier/uSub.php b/Model/Carrier/uSub.php deleted file mode 100644 index 96ae4747c1b928eefd2843b4d711fdc468c4e9bc..0000000000000000000000000000000000000000 --- a/Model/Carrier/uSub.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php - -namespace bobgo\CustomShipping\Model\Carrier; -use Magento\Checkout\Api\Data\ShippingInformationInterface; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Quote\Api\CartRepositoryInterface; - - -class uSub { - - - /** - * This is supposed to get the suburb from the shipping address extension attributes. - * Does not work for now, was supposed to access the suburb attribute from the shipping address extension attributes. - * @throws NoSuchEntityException - */ - public function getDestSuburb() - { - $objectManager = ObjectManager::getInstance(); - $quote = $objectManager->get('Magento\Checkout\Model\ShippingInformation')->getExtensionAttributes(); - return $quote->getSuburb(); - } - - - -} diff --git a/Model/Carrier/uSubs.php b/Model/Carrier/uSubs.php index e3b75ae4bc81b0e54b47d178b642282e9d103bd4..5f7dcd8cd5835cd0a38d14e07f69776c02f6048f 100644 --- a/Model/Carrier/uSubs.php +++ b/Model/Carrier/uSubs.php @@ -1,8 +1,8 @@ <?php -namespace uafrica\Customshipping\Model\Carrier; +namespace BobGroup\BobGo\Model\Carrier; -/** Get Company information if available from the Estimate Shipping Methods Request Body */ +/** Get AdditionalInfo information if available from the Estimate Shipping Methods Request Body */ class uSubs { diff --git a/Model/Source/Dropoff.php b/Model/Source/Dropoff.php index e2705573bef8e747fc4a8759cbeb78165e5f743a..e355c3ad31e4bb0c5d66c438ef6880afc30a786a 100644 --- a/Model/Source/Dropoff.php +++ b/Model/Source/Dropoff.php @@ -1,6 +1,6 @@ <?php -namespace bobgo\CustomShipping\Model\Source; +namespace BobGroup\BobGo\Model\Source; class Dropoff extends Generic { diff --git a/Model/Source/Freemethod.php b/Model/Source/Freemethod.php index 2e0bc6fd50f52e242f98ed7eef3965f47c032fae..674f68706a72978fd580ecb1f6ebd157e78b9bfc 100644 --- a/Model/Source/Freemethod.php +++ b/Model/Source/Freemethod.php @@ -1,6 +1,6 @@ <?php -namespace bobgo\CustomShipping\Model\Source; +namespace BobGroup\BobGo\Model\Source; /** * Bob Go Free Method source implementation diff --git a/Model/Source/Generic.php b/Model/Source/Generic.php index 8bebd1722e4bde334ce710a339686aac2495b8be..f5eb3943cd1c7c0f71cc2af44e6361fb0adb1006 100644 --- a/Model/Source/Generic.php +++ b/Model/Source/Generic.php @@ -1,20 +1,20 @@ <?php -namespace bobgo\CustomShipping\Model\Source; +namespace BobGroup\BobGo\Model\Source; use Magento\Framework\Data\OptionSourceInterface; -use bobgo\CustomShipping\Model\Carrier\CustomShipping; +use BobGroup\BobGo\Model\Carrier\BobGo; /** - * Bob Go generic source implementation + * bobgo generic source implementation */ class Generic implements OptionSourceInterface { /** - * @var CustomShipping + * @var BobGo */ - protected CustomShipping $_shippingCustomShipping; + protected BobGo $_shippingBobGo; /** * Carrier code @@ -23,11 +23,11 @@ class Generic implements OptionSourceInterface protected string $_code = ''; /** - * @param CustomShipping $shippingCustomShipping + * @param BobGo $shippingBobGo */ - public function __construct(CustomShipping $shippingCustomShipping) + public function __construct(BobGo $shippingBobGo) { - $this->_shippingCustomShipping = $shippingCustomShipping; + $this->_shippingBobGo = $shippingBobGo; } /** @@ -36,7 +36,7 @@ class Generic implements OptionSourceInterface */ public function toOptionArray() { - $configData = $this->_shippingCustomShipping->getCode($this->_code); + $configData = $this->_shippingBobGo->getCode($this->_code); $arr = []; if ($configData) { $arr = array_map( diff --git a/Model/Source/Method.php b/Model/Source/Method.php index 6ff23503c0c8b273df38b0abfbc5dcee3b1e4f79..fe13c122b58ad9be911db099da5774bcec6fe30d 100644 --- a/Model/Source/Method.php +++ b/Model/Source/Method.php @@ -1,6 +1,6 @@ <?php -namespace bobgo\CustomShipping\Model\Source; +namespace BobGroup\BobGo\Model\Source; class Method extends Generic { diff --git a/Model/Source/Packaging.php b/Model/Source/Packaging.php index 5c93ad376f2c01564da7593149e89cc783dcc06f..a7fce6356606f0bc366c4d8b0b45acd40da71df6 100644 --- a/Model/Source/Packaging.php +++ b/Model/Source/Packaging.php @@ -1,6 +1,6 @@ <?php -namespace bobgo\CustomShipping\Model\Source; +namespace BobGroup\BobGo\Model\Source; class Packaging extends Generic { diff --git a/Model/Source/Unitofmeasure.php b/Model/Source/Unitofmeasure.php index 8ef12cdb8b4a84d1ae7a59b5c8a366a1e6d54e69..be8d13b0455812d4f308f45a235ab4888eb19aa5 100644 --- a/Model/Source/Unitofmeasure.php +++ b/Model/Source/Unitofmeasure.php @@ -1,6 +1,6 @@ <?php -namespace bobgo\CustomShipping\Model\Source; +namespace BobGroup\BobGo\Model\Source; class Unitofmeasure extends Generic { @@ -9,4 +9,5 @@ class Unitofmeasure extends Generic * @var string */ protected string $_code = 'unit_of_measure'; + } diff --git a/Observer/SaveOrderBeforeSalesModelQuote.php b/Observer/SaveOrderBeforeSalesModelQuote.php deleted file mode 100644 index 25cc18a5477f0a750453cda6716d5ff348e898a8..0000000000000000000000000000000000000000 --- a/Observer/SaveOrderBeforeSalesModelQuote.php +++ /dev/null @@ -1,39 +0,0 @@ -<?php - -namespace bobgo\CustomShipping\Observer; - -use Magento\Framework\DataObject\Copy; -use Magento\Framework\Event\Observer; -use Magento\Framework\Event\ObserverInterface; -use Magento\Quote\Model\Quote; -use Magento\Sales\Model\Order; - -/** - * Class SaveOrderBeforeSalesModelQuote - * @package bobgo\CustomShipping\Observer - * This class is supposed to copy the suburb attribute from the quote to the order object. - */ -class SaveOrderBeforeSalesModelQuote implements ObserverInterface -{ - public Copy $objectCopyService; - - public function __construct( - Copy $objectCopyService - ) { - $this->objectCopyService = $objectCopyService; - } - - public function execute(Observer $observer) - { - $this->objectCopyService->copyFieldsetToTarget( - 'sales_convert_quote', - 'to_order', - $observer->getEvent()->getQuote(), - $observer->getEvent()->getOrder() - ); - - - return $this; - - } -} diff --git a/Plugin/Block/DataProviders/Tracking/ChangeTitle.php b/Plugin/Block/DataProviders/Tracking/ChangeTitle.php index 285ca5af64851b89e1d4de810acc46bd2a8bc7b8..03d6b4c431d49ef9588960332a9e4213a815173e 100644 --- a/Plugin/Block/DataProviders/Tracking/ChangeTitle.php +++ b/Plugin/Block/DataProviders/Tracking/ChangeTitle.php @@ -1,20 +1,20 @@ <?php -namespace bobgo\CustomShipping\Plugin\Block\DataProviders\Tracking; +namespace BobGroup\BobGo\Plugin\Block\DataProviders\Tracking; -use bobgo\CustomShipping\Model\Carrier; +use BobGroup\BobGo\Model\Carrier; use Magento\Shipping\Model\Tracking\Result\Status; use Magento\Shipping\Block\DataProviders\Tracking\DeliveryDateTitle as Subject; /** - * Plugin to change delivery date title with Bob Go customized value + * Plugin to change delivery date title with bobgo customized value */ class ChangeTitle { /** - * Title modification in case if Bob Go used as carrier + * Title modification in case if bobgo used as carrier * * @param Subject $subject * @param \Magento\Framework\Phrase|string $result diff --git a/Plugin/Block/Tracking/PopUpDeliveryDate.php b/Plugin/Block/Tracking/PopUpDeliveryDate.php index e2fa211dd336927e36e7f5bfb17f1f69e8a42c97..18c07ebf94298a5a8703f3f80f3efe5cb44e0f01 100644 --- a/Plugin/Block/Tracking/PopUpDeliveryDate.php +++ b/Plugin/Block/Tracking/PopUpDeliveryDate.php @@ -1,10 +1,10 @@ <?php -namespace bobgo\CustomShipping\Plugin\Block\Tracking; +namespace BobGroup\BobGo\Plugin\Block\Tracking; use Magento\Shipping\Block\Tracking\Popup; use Magento\Shipping\Model\Tracking\Result\Status; -use Magento\Shiiping\Model\Carrier; +use Magento\Shipping\Model\Carrier; /* * Plugin to update delivery date value in case if Bob Go is a carrier used diff --git a/Plugin/Checkout/Block/LayoutProcessorPlugin.php b/Plugin/Checkout/Block/LayoutProcessorPlugin.php index 6eb562667b50c5df05d1d4a05ef5337f4b29387c..1c32fb6afc4d8e9b0956ec0534ad9adc237f88ab 100644 --- a/Plugin/Checkout/Block/LayoutProcessorPlugin.php +++ b/Plugin/Checkout/Block/LayoutProcessorPlugin.php @@ -1,11 +1,11 @@ <?php -namespace bobgo\CustomShipping\Plugin\Checkout\Block; +namespace BobGroup\BobGo\Plugin\Checkout\Block; use Magento\Checkout\Block\Checkout\LayoutProcessor; /** * Class LayoutProcessorPlugin - * @package bobgo\CustomShipping\Plugin\Checkout\Block + * @package BobGroup\BobGo\Plugin\Checkout\Block * This class is supposed to add a new field to the checkout page for the suburb. It is supposed to be used in conjunction with the SaveOrderBeforeSalesModelQuote observer. * At the moment, it overrides the 2 Address fields and adds a new 3 Address field to accommodate the suburb on the checkout page( including placeholders). * This is not the best way to do it, but it is the only way I could get it to work. @@ -22,61 +22,34 @@ class LayoutProcessorPlugin \Magento\Checkout\Block\Checkout\LayoutProcessor $subject, array $jsLayout ) { - $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children'] - ['shippingAddress']['children']['shipping-address-fieldset']['children']['street'] = [ - 'component' => 'Magento_Ui/js/form/components/group', - 'label' => ('Street Address'), - 'required' => false, - 'dataScope' => 'shippingAddress.street', - 'provider' => 'checkoutProvider', - 'sortOrder' => 55, - 'type' => 'group', - 'additionalClasses' => 'street', - 'children' => [ - [ - 'label' => ('Street Address'), - 'component' => 'Magento_Ui/js/form/element/abstract', - 'config' => [ - 'placeholder' => 'street address', - 'customScope' => 'shippingAddress', - 'template' => 'ui/form/field', - 'elementTmpl' => 'ui/form/element/input' - ], - 'dataScope' => '0', - 'provider' => 'checkoutProvider', - 'validation' => ['required-entry' => true, "min_text_length" => 1, "max_text_length" => 255], - ], - [ - 'label' => __('Label 2'), - 'component' => 'Magento_Ui/js/form/element/abstract', - 'config' => [ - 'placeholder' => 'town', - 'customScope' => 'shippingAddress', - 'template' => 'ui/form/field', - 'elementTmpl' => 'ui/form/element/input' - ], - 'dataScope' => '1', - 'provider' => 'checkoutProvider', - 'validation' => ['required-entry' => true, "min_text_length" => 1, "max_text_length" => 255], - ], - [ - 'label' => __('Label 3'), - 'component' => 'Magento_Ui/js/form/element/abstract', - 'config' => [ - 'placeholder' => 'suburb', - 'customScope' => 'shippingAddress', - 'template' => 'ui/form/field', - 'elementTmpl' => 'ui/form/element/input' - ], - 'dataScope' => '2', - 'provider' => 'checkoutProvider', - 'validation' => ['required-entry' => true, "min_text_length" => 1, "max_text_length" => 255], - ], - 'dataScope' => '3', - 'provider' => 'checkoutProvider', - 'validation' => ['required-entry' => false, "min_text_length" => 1, "max_text_length" => 255], + $suburbAttribute = 'suburb'; + $suburb = [ + 'component' => 'Magento_Ui/js/form/element/abstract', + 'config' => [ + 'customScope' => 'shippingAddress.custom_attributes', + 'customEntry' => null, + 'template' => 'ui/form/field', + 'elementTmpl' => 'ui/form/element/input', + 'tooltip' => [ + 'description' => 'Required for shipping accuracy', ], + ], + 'dataScope' => 'shippingAddress.custom_attributes' . '.' . $suburbAttribute, + 'label' => 'Suburb', + 'provider' => 'checkoutProvider', + 'sortOrder' => 80, + 'validation' => [ + 'required-entry' => true + ], + 'options' => [], + 'filterBy' => null, + 'customEntry' => null, + 'visible' => true, + 'value' => '' // value field is used to set a default value of the attribute ]; + + $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children'][$suburbAttribute] = $suburb; + return $jsLayout; } } diff --git a/Plugin/ShippingInformationManagement.php b/Plugin/ShippingInformationManagement.php deleted file mode 100644 index 233ed2c00b1f56ca4dff7bc3743133a17f8bedcf..0000000000000000000000000000000000000000 --- a/Plugin/ShippingInformationManagement.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php - -namespace bobgo\CustomShipping\Plugin; - -use Magento\Quote\Api\CartRepositoryInterface; - -use Magento\Checkout\Api\Data\ShippingInformationInterface; - -/** - * Class ShippingInformationManagement - * @package bobgo\CustomShipping\Plugin - * This class is supposed to copy the suburb attribute from the quote to the order object. - */ -class ShippingInformationManagement -{ - public CartRepositoryInterface $cartRepository; - - public function __construct( - CartRepositoryInterface $cartRepository - ) - { - $this->cartRepository = $cartRepository; - } - - public function beforeSaveAddressInformation($subject, $cartId, ShippingInformationInterface $addressInformation): array - { - $quote = $this->cartRepository->getActive($cartId); - $deliveryNote = $addressInformation->getShippingAddress()->getExtensionAttributes()->getSuburb(); - $quote->setSuburb($deliveryNote); - $this->cartRepository->save($quote); - return [$cartId, $addressInformation]; - } - -} diff --git a/Readme.md b/Readme.md index fc4631cce146b89cfa9914ada640d98e57c89e4f..7d691668472e29f39a24c24755fd7152166e1d11 100644 --- a/Readme.md +++ b/Readme.md @@ -1,29 +1,3 @@ -# Installing Magento locally - -**Note:** For more information, visit https://github.com/markshust/docker-magento - -1. Make sure you have `composer` installed globally and a GitHub personal access token configured using `composer global config github-oauth.github.com <YOUR_PERSONAL_ACCESS_TOKEN>` -2. Create a new folder, ie: `Documents/Magento` -3. `cd` into the folder -4. Run command `curl -s https://raw.githubusercontent.com/markshust/docker-magento/master/lib/onelinesetup | bash -s -- bobgomagento.test 2.4.4-p1 community` -5. When asked for the username and password, provide the Abobe public and private key: - -- Public key: `98b4828a495e7e0e13d80d8bf94f3b1c` -- Private key: `082ced46919bffe1b6db0f96de96d608` - -Once configured, do the following to create an admin user (and make life easier for yourself): - -- Create Admin User: `bin/magento admin:user:create` -- Disable 2FA: `bin/magento module:disable Magento_TwoFactorAuth` -- Disable Admin Captcha: `bin/magento config:set admin/captcha/enable 0` - - -### Adobe account details - -- Email: `tech@uafrica.com` -- Password: `mR3mdr0311@P` - - # Magento 2 Bob Go Shipping Extension ## Introduction @@ -41,18 +15,17 @@ A complete guide to install Magento Bob Go Shipping extension in Magento 2. Run the following command in Magento 2 root folder:</br> - >_Note: You must have composer installed on your server & at this point this option_ #### 1. Execute the following command to install the module: ``` -composer require bobgo/CustomShipping +composer require bob-public-utils/bobgo-magento-extension ``` #### 2. Enter following commands to enable the module: ``` -bin/magento module:enable bobgo_CustomShipping +bin/magento module:enable BobGroup_BobGo bin/magento cache:clean bin/magento cache:flush bin/magento setup:upgrade @@ -60,7 +33,6 @@ bin/magento setup:di:compile bin/magento setup:static-content:deploy ``` - ### Option 2: Install via zip file 1. Download the extension zip file from the link below: </br> @@ -69,21 +41,22 @@ bin/magento setup:static-content:deploy 2. Unzip the file and copy contents -3. Create `bobgo/CustomShipping` <em>Directory</em> +3. Create `BobGroup/BobGo` <em>Directory</em> **It should look like this:** </br> ->{Magento root}/app/code/bobgo/CustomShipping/ +>{Magento root}/app/code/BobGroup/BobGo/ ->**{Magento root}**`/app/code/bobgo/CustomShipping/`**{Paste here}** +>**{Magento root}**`/app/code/BobGroup/BobGo/`**{Paste here}** -3. Go to Magento root folder and run all commands below to install `bobgo_CustomShipping`: </br> +3. Go to Magento root folder and run all commands below to install `BobGroup_BobGo`: </br> ``` bin/magento cache:clean -Bin/magento cache:flush -Bin/magento setup:upgrade -Bin/magento setup:di:compile +bin/magento cache:flush +bin/magento setup:upgrade +bin/magento setup:di:compile +bin/magento setup:static-content:deploy ``` _____________________________________________________________________________________________________________________ # After installation diff --git a/composer.json b/composer.json index 3525313e32b88ffaf3bf9ea1ff69b34157962f65..330819819a5b54bc71a50c1b976e70eb60a8303d 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,10 @@ { - "name": "bobgo/bobgo", - "description": "Streamline your shipments fulfillment's with Bob Go", + "name": "bob-public-utils/bobgo-magento-extension", + "description": "Streamline your order fulfillments with Bob Go", + "require": { + "php": "~8.1.28", + "magento/framework": "*" + }, "type": "magento2-module", "version": "1.0.0", "authors": [ @@ -19,7 +23,7 @@ "registration.php" ], "psr-4": { - "bobgo\\CustomShipping\\": "" + "Plugin\\": "" } } } diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 358c8946cc31b182aeb7338080b07583c65ebda9..0d3fa3adc894f9aa28968138ba8856ee6379a46f 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -1,38 +1,23 @@ <?xml version="1.0"?> -<!-- -/** - * @category Bob Go - * @package bobgo_CustomShipping - * @author Bob Go - */ ---> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd"> <system> - <tab id="bobgo" translate="label" sortOrder="200"> + + <tab id="bobgo" translate="label" sortOrder="2"> <label>Bob Go</label> </tab> - <section id="bobgo_CustomShipping" translate="label" type="text" sortOrder="520" showInDefault="1" - showInWebsite="1" showInStore="0"> - <class>separator-top</class> + <section id="BobGroup_BobGo" showInDefault="1"> <tab>bobgo</tab> <label>Settings</label> <resource>Magento_Config::config</resource> - <group id="general" showInDefault="1"> + <group id="general" showInDefault="1"> <label>Settings</label> - <field id="version" translate="label" type="label" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0"> - <label>Version</label> - <frontend_model>bobgo\CustomShipping\Block\System\Config\Form\Field\Version</frontend_model> - </field> <field id="enabled" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Extension enabled</label> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> </field> - <!--field id="debug" translate="label" type="select" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1"> - <label>Debug Mode</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - </field--> </group> </section> + <section id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"> <group id="store_information" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"> <field id="suburb" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="0"> @@ -41,24 +26,22 @@ </field> </group> </section> + <section id="carriers" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1"> <group id="bobgo" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Bob Go</label> - <field id="active" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0"> - <label>Enabled for Checkout</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - </field> - - <field id="title" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1"> - <label>Title</label> + <field id="version" translate="label" type="label" sortOrder="0" showInDefault="1" showInWebsite="0" showInStore="0"> + <label>Version</label> + <frontend_model>BobGroup\BobGo\Block\System\Config\Form\Field\Version</frontend_model> </field> - - <field id="residence_delivery" translate="label" type="select" sortOrder="7" showInDefault="1" showInWebsite="1"> - <label>Residential Delivery</label> + <field id="active" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0"> + <label>Show rates for checkout</label> + <comment>When this setting is enabled, your customers will be presented with shipping rates at checkout, as configured on the Bob Go platform under Rates at checkout.</comment> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> </field> <field id="specificerrmsg" translate="label" type="textarea" sortOrder="80" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Displayed Error Message</label> + <comment>The message displayed to the customer when no rates were available on Bob Go.</comment> </field> <field id="sallowspecific" translate="label" type="select" sortOrder="90" showInDefault="1" showInWebsite="1" showInStore="0"> @@ -78,22 +61,18 @@ <frontend_class>shipping-skip-hide</frontend_class> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> </field> - <field id="unit_of_measure" translate="label" type="select" sortOrder="73" showInDefault="1" showInWebsite="1" canRestore="1"> + <field id="unit_of_measure" translate="label" type="select" sortOrder="73" showInDefault="1" showInWebsite="1"> <label>Weight Unit</label> - <source_model>bobgo\CustomShipping\Model\Source\Unitofmeasure</source_model> + <source_model>BobGroup\BobGo\Model\Source\Unitofmeasure</source_model> </field> - <field id="additional_info" translate="label" type="select" sortOrder="7" showInDefault="1" showInWebsite="1"> - <label>Display Additional Information</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <comment>Display additional information on the checkout page</comment> - </field> - <field id="debug" translate="label" type="select" sortOrder="1950" showInDefault="1" showInWebsite="1"> - <label>Debug</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> + <field id="max_package_weight" translate="label" type="text" sortOrder="90" showInDefault="1" showInWebsite="1"> + <label>Maximum Package Weight (Please consult your shipping carrier for maximum supported shipping weight)</label> + <validate>validate-number validate-zero-or-greater</validate> </field> - <field id="sandbox_mode" translate="label" type="select" sortOrder="1960" showInDefault="1" showInWebsite="1"> - <label>Sandbox Mode</label> + <field id="additional_info" translate="label" type="select" sortOrder="7" showInDefault="1" showInWebsite="1"> + <label>Show additional rate information</label> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> + <comment>Displays the delivery timeframe and additional service level description as configured on Bob Go.</comment> </field> </group> </section> diff --git a/etc/config.xml b/etc/config.xml index d31cdc52b0d36510935ecc4c169f1cd0c44cb939..eb34051b8ece8d438e1e19c5dae9a533cd4e25a2 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -1,28 +1,23 @@ <?xml version="1.0"?> -<!-- -/** - * @category Bob Go - * @package bobgo_CustomShipping - * @author Bob Go - */ ---> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd"> <default> - <bobgo_CustomShipping> + <BobGroup_BobGo> <general> <debug>0</debug> </general> - </bobgo_CustomShipping> + </BobGroup_BobGo> <carriers> <bobgo> <active>0</active> - <sallowspecific>0</sallowspecific> +<!-- <sallowspecific>1</sallowspecific> + <specificcountry>ZA</specificcountry>--> <price>0.00</price> - <model>bobgo\CustomShipping\Model\Carrier\CustomShipping</model> + <model>BobGroup\BobGo\Model\Carrier\BobGo</model> <name>Fixed</name> + <max_package_weight>300</max_package_weight> <title>Bob Go</title> - <specificerrmsg>This shipping method is not available. To use this shipping method, please contact us.</specificerrmsg> + <specificerrmsg>We could not find any shipping rates for your delivery address. Please make sure your address is correct. If you are experiencing problems, please contact us.</specificerrmsg> </bobgo> </carriers> diff --git a/etc/db_schema.xml b/etc/db_schema.xml deleted file mode 100644 index c4aba785c2ec895a032593a63ffd672795c1a4a5..0000000000000000000000000000000000000000 --- a/etc/db_schema.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0"?> -<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> - <table name="quote" resource="default" engine="innodb"> - <column xsi:type="text" name="suburb" nullable="true" comment="Delivery suburb"/> - <column xsi:type="text" name="service_code" nullable="true" comment="Shipping Service Code"/> - <column xsi:type="text" name="delivery_note" nullable="true" comment="Delivery Note"/> - </table> - <table name="sales_order" resource="default" engine="innodb"> - <column xsi:type="text" name="suburb" nullable="true" comment="Delivery Suburb"/> - <column xsi:type="text" name="service_code" nullable="true" comment="Shipping Service Code"/> - <column xsi:type="text" name="delivery_note" nullable="true" comment="Delivery Note"/> - </table> - <table name="customer_address_entity" resource="default" engine="innodb"> - <column xsi:type="text" name="suburb" nullable="true" comment="Customer Suburb"/> - <column xsi:type="text" name="service_code" nullable="true" comment="Shipping Service Code"/> - <column xsi:type="text" name="delivery_note" nullable="true" comment="Delivery Note"/> - </table> - -</schema> diff --git a/etc/di.xml b/etc/di.xml deleted file mode 100644 index 4f4ee2d8bbfd191d93355cbc58931211a3be53b2..0000000000000000000000000000000000000000 --- a/etc/di.xml +++ /dev/null @@ -1,8 +0,0 @@ -<?xml version="1.0"?> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> - <type name="Magento\Checkout\Model\ShippingInformationManagement"> - <plugin name="get_suburb" - type="bobgo\CustomShipping\Plugin\ShippingInformationManagement" sortOrder="1"/> - </type> -</config> diff --git a/etc/events.xml b/etc/events.xml deleted file mode 100644 index caf07f224582cd023691b1d43ed3d5d5052c75b5..0000000000000000000000000000000000000000 --- a/etc/events.xml +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0"?> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd"> - <event name="sales_model_service_quote_submit_before"> - <observer name="bobgo_CustomShipping_sales_model_service_quote_submit_before" - instance="bobgo\CustomShipping\Observer\SaveOrderBeforeSalesModelQuote" /> - </event> -</config> diff --git a/etc/fieldset.xml b/etc/fieldset.xml deleted file mode 100644 index 6773bc70b8ef293caf882255dd7587bbb95b966c..0000000000000000000000000000000000000000 --- a/etc/fieldset.xml +++ /dev/null @@ -1,10 +0,0 @@ -<?xml version="1.0"?> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:DataObject/etc/fieldset.xsd"> - <scope id="global"> - <fieldset id="sales_convert_quote"> - <field name="suburb"> - <aspect name="to_order" /> - </field> - </fieldset> - </scope> -</config> diff --git a/etc/frontend/di.xml b/etc/frontend/di.xml index 61b1ccdd5598615f49d8e63f90f0bbff6a2ccf20..2ee6f54f96f9264b803de3a8dd8f99b923988f76 100644 --- a/etc/frontend/di.xml +++ b/etc/frontend/di.xml @@ -1,9 +1,9 @@ <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Checkout\Block\Checkout\LayoutProcessor"> - <plugin name="add_custom_field_checkout_shipping_form" type="bobgo\CustomShipping\Plugin\Checkout\Block\LayoutProcessorPlugin" sortOrder="10"/> + <plugin name="add_custom_field_checkout_shipping_form" type="BobGroup\BobGo\Plugin\Checkout\Block\LayoutProcessorPlugin" sortOrder="10"/> <arguments> <argument name="layoutProcessors" xsi:type="array"> - <item name="orderattribute" xsi:type="object">bobgo\CustomShipping\Plugin\Checkout\Block\LayoutProcessorPlugin</item> + <item name="orderattribute" xsi:type="object">BobGroup\BobGo\Plugin\Checkout\Block\LayoutProcessorPlugin</item> </argument> </arguments> </type> diff --git a/etc/module.xml b/etc/module.xml index 9cb1757c8c447dd892545d31c618ed7482cf03aa..d736136edb4535fca984abcd0b7d2b08fed15e6d 100644 --- a/etc/module.xml +++ b/etc/module.xml @@ -7,7 +7,7 @@ */ --> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> - <module name="bobgo_CustomShipping" setup_version="1.0.0"> + <module name="BobGroup_BobGo" setup_version="1.0.0"> <sequence> <module name="Magento_Webapi"/> <module name="Magento_Catalog"/> diff --git a/i18n/en_US.csv b/i18n/en_US.csv index 09ef6059efe59917e951137999e4054f9a615699..02bd9c253e0f562a2e79ec9422e3ab59e1ea1bf1 100644 --- a/i18n/en_US.csv +++ b/i18n/en_US.csv @@ -1 +1,24 @@ -"Enabled","Enabled" \ No newline at end of file +"The shipping module is not available.","The shipping module is not available." +"This shipping method is not available. Please specify the zip code.","This shipping method is not available. Please specify the zip code." +BobGo,BobGo +Kilograms,Kilograms +Pounds,Pounds +"For some reason we can't retrieve tracking info right now.","For some reason we can't retrieve tracking info right now." +status,status +"Empty response","Empty response" +None,None +"Expected Delivery:","Expected Delivery:" +"Field ","Field " +" is required."," is required." +"Bob Go","Bob Go" +"Extension enabled","Extension enabled" +Suburb,Suburb +Version,Version +"Show rates for checkout","Show rates for checkout" +"Displayed Error Message","Displayed Error Message" +"Ship to Applicable Countries","Ship to Applicable Countries" +"Ship to Specific Countries","Ship to Specific Countries" +"Show Method if Not Applicable","Show Method if Not Applicable" +"Weight Unit","Weight Unit" +"Maximum Package Weight (Please consult your shipping carrier for maximum supported shipping weight)","Maximum Package Weight (Please consult your shipping carrier for maximum supported shipping weight)" +"Show additional rate information","Show additional rate information" diff --git a/registration.php b/registration.php index 4c358c2e4db661b29186feaf09f205555534fa69..d8ff5a840e4d2d57e7de9f29ae6764db98a3687f 100644 --- a/registration.php +++ b/registration.php @@ -1,7 +1,6 @@ <?php -// Convention requires Vendor_Extension \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, - 'bobgo_CustomShipping', + 'BobGroup_BobGo', __DIR__ ); diff --git a/view/frontend/layout/checkout_cart_index.xml b/view/frontend/layout/checkout_cart_index.xml index 884a7712c0b183d822204c85f434ee9c250ec4ab..c9b9a3b52a22200f0ed29d37f8e903b658dc6ce6 100644 --- a/view/frontend/layout/checkout_cart_index.xml +++ b/view/frontend/layout/checkout_cart_index.xml @@ -10,7 +10,7 @@ <item name="shipping-rates-validation" xsi:type="array"> <item name="children" xsi:type="array"> <item name="bobgo-rates-validation" xsi:type="array"> - <item name="component" xsi:type="string">bobgo_CustomShipping/js/view/shipping-rates-validation</item> + <item name="component" xsi:type="string">BobGroup_BobGo/js/view/shipping-rates-validation</item> </item> </item> </item> diff --git a/view/frontend/layout/checkout_index_index.xml b/view/frontend/layout/checkout_index_index.xml index 95457b70f16c695dc1869519860fbdb73f1f94a1..225627fcabc840bd2c3a3880e2ddb15eca213600 100644 --- a/view/frontend/layout/checkout_index_index.xml +++ b/view/frontend/layout/checkout_index_index.xml @@ -16,7 +16,7 @@ <item name="shipping-rates-validation" xsi:type="array"> <item name="children" xsi:type="array"> <item name="bobgo-rates-validation" xsi:type="array"> - <item name="component" xsi:type="string">bobgo_CustomShipping/js/view/shipping-rates-validation</item> + <item name="component" xsi:type="string">BobGroup_BobGo/js/view/shipping-rates-validation</item> </item> </item> </item> diff --git a/view/frontend/requirejs-config.js b/view/frontend/requirejs-config.js index 471dc742f1a6068b0d02ccbfeba883f771eab8ff..7b5c1d8619b5d2e0331bf42470c44c2005f8b9a1 100644 --- a/view/frontend/requirejs-config.js +++ b/view/frontend/requirejs-config.js @@ -4,7 +4,7 @@ var config = { config: { mixins: { 'Magento_Checkout/js/action/set-shipping-information': { - 'bobgo_CustomShipping/js/action/set-shipping-information-mixin': true + 'BobGroup_BobGo/js/action/set-shipping-information-mixin': true } } } diff --git a/view/frontend/web/js/action/set-shipping-information-mixin.js b/view/frontend/web/js/action/set-shipping-information-mixin.js index b899f21c19c365149aeac59026048b30e3d322fa..85349aad71fafdd3078668e6591fc0cdc8b7957f 100644 --- a/view/frontend/web/js/action/set-shipping-information-mixin.js +++ b/view/frontend/web/js/action/set-shipping-information-mixin.js @@ -14,19 +14,7 @@ define([ if (shippingAddress['extension_attributes'] === undefined) { shippingAddress['extension_attributes'] = {}; } - //This is supposed to be the mixin that adds the suburb to the shipping address, but it doesn't work -/* var attribute = shippingAddress.customAttributes.find( - function (element) { - return element.attribute_code === 'suburb'; - } - ); - - shippingAddress['extension_attributes']['suburb'] = attribute.value; - - shippingAddress['extension_attributes']['suburb'] = shippingAddress.value; - - pass execution to original action ('Magento_Checkout/js/action/set-shipping-information')*/ - //after all the of the above the suburb is still not added to the request payload that goes to CustomShipping.php + // pass execution to original action ('Magento_Checkout/js/action/set-shipping-information') return originalAction(); }); }; diff --git a/view/frontend/web/js/model/shipping-rates-validation-rules.js b/view/frontend/web/js/model/shipping-rates-validation-rules.js index 0841e9095170ae18c60fd4f95c563b39235f077a..0cf80ca2a58009b4055a599fac3a7d4d45a2e799 100644 --- a/view/frontend/web/js/model/shipping-rates-validation-rules.js +++ b/view/frontend/web/js/model/shipping-rates-validation-rules.js @@ -18,6 +18,9 @@ define( }, 'city': { 'required': true + }, + 'suburb': { + 'required': true } }; }