Skip to content

Commit

Permalink
feat(carriers): add carrier logos
Browse files Browse the repository at this point in the history
  • Loading branch information
EdieLemoine committed Sep 14, 2023
1 parent 139d3e4 commit 9feee1d
Show file tree
Hide file tree
Showing 9 changed files with 202 additions and 15 deletions.
13 changes: 11 additions & 2 deletions pdk.config.cjs → pdk.config.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const {PdkPlatformName, defineConfig} = require('@myparcel-pdk/app-builder');
import {PdkPlatformName, defineConfig} from '@myparcel-pdk/app-builder';
import {downloadCarrierLogos} from './private/downloadCarrierLogos.mjs';

module.exports = defineConfig({
export default defineConfig({
name: 'prestashop',
platformFolderName: `{{platform}}`,
platforms: [PdkPlatformName.MyParcelNl, PdkPlatformName.MyParcelBe],
Expand All @@ -21,4 +22,12 @@ module.exports = defineConfig({
// eslint-disable-next-line no-magic-numbers
additionalSheet: 279275153,
},

additionalCommands: [
{
name: 'download-carrier-logos',
description: 'Download carrier logos',
action: downloadCarrierLogos,
},
],
});
2 changes: 2 additions & 0 deletions private/carrier-logos/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
!.gitignore
*
62 changes: 62 additions & 0 deletions private/downloadCarrierLogos.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {FetchClient, GetCarriers, createPublicSdk} from '@myparcel/sdk';
import fs from 'fs';
import path from 'path';
import fetch from 'node-fetch';
import sharp from 'sharp';

// eslint-disable-next-line no-underscore-dangle
const __dirname = path.dirname(new URL(import.meta.url).pathname);

/**
* @type {import('@myparcel-pdk/app-builder').PdkBuilderCommand} downloadCarrierLogos
*/

export const downloadCarrierLogos = async ({debug}) => {
const sdk = createPublicSdk(new FetchClient(), [new GetCarriers()]);

const carriers = await sdk.getCarriers();

await Promise.all(
carriers.map(async (carrier) => {
const imageUrl = `https://assets.myparcel.nl${carrier.meta.logo_svg}`;

const response = await fetch(imageUrl);

if (!response.ok) {
// eslint-disable-next-line no-console
debug(`Could not download image for ${carrier.name}`);
return;
}

const imageBuffer = await response.arrayBuffer();

fs.mkdirSync(path.resolve(__dirname, 'carrier-logos'), {recursive: true});

const imagePath = path.resolve(__dirname, `carrier-logos/${carrier.name}`);

const pngBackground = {r: 0, g: 0, b: 0, alpha: 0};
const jpgBackground = {r: 255, g: 255, b: 255, alpha: 1};

const resizeOptions = {
fit: 'contain',
width: 40,
height: 40,
};

const image = sharp(imageBuffer);

await image
.clone()
.flatten({background: jpgBackground})
.resize({...resizeOptions, background: jpgBackground})
.jpeg()
.toFile(path.resolve(__dirname, `${imagePath}.jpg`));

await image
.clone()
.resize({...resizeOptions, background: pngBackground})
.png()
.toFile(path.resolve(__dirname, `${imagePath}.png`));
}),
);
};
18 changes: 18 additions & 0 deletions src/Carrier/Service/CarrierBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Context;
use Group;
use Language as PsLanguage;
use MyParcelNL\Pdk\Base\FileSystemInterface;
use MyParcelNL\Pdk\Base\Support\Arr;
use MyParcelNL\Pdk\Carrier\Model\Carrier;
use MyParcelNL\Pdk\Facade\Language;
Expand Down Expand Up @@ -60,6 +61,7 @@ public function create(): PsCarrier
{
$this->createCarrier();

$this->addCarrierImages();
$this->addGroups();
$this->addRanges();
$this->addZones();
Expand All @@ -69,6 +71,22 @@ public function create(): PsCarrier
return $this->psCarrier;
}

/**
* @return void
*/
private function addCarrierImages(): void
{
/** @var FileSystemInterface $fileSystem */
$fileSystem = Pdk::get(FileSystemInterface::class);

foreach (Pdk::get('carrierLogoFileExtensions') as $fileExtension) {
$sourceFilename = Pdk::get('carrierLogosDirectory') . $this->myParcelCarrier->name . $fileExtension;
$destFilename = _PS_SHIP_IMG_DIR_ . $this->psCarrier->id . $fileExtension;

$fileSystem->put($destFilename, $fileSystem->get($sourceFilename));
}
}

/**
* @throws \Doctrine\ORM\ORMException
*/
Expand Down
67 changes: 58 additions & 9 deletions src/Hooks/HasPdkCheckoutDeliveryOptionsHooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
use MyParcelNL\Pdk\Facade\Frontend;
use MyParcelNL\Pdk\Facade\Logger;
use MyParcelNL\Pdk\Facade\Pdk;
use MyParcelNL\Pdk\Facade\Settings;
use MyParcelNL\Pdk\Settings\Model\CheckoutSettings;
use MyParcelNL\PrestaShop\Pdk\Base\Adapter\PsAddressAdapter;
use MyParcelNL\PrestaShop\Service\PsCarrierService;
use Throwable;
Expand All @@ -19,12 +21,36 @@
trait HasPdkCheckoutDeliveryOptionsHooks
{
/**
* @param $params
* @param array $params
*
* @return false|string
*/
public function hookDisplayCarrierExtraContent($params)
public function hookDisplayBeforeCarrier(array $params)
{
if ($this->deliveryOptionsDisabled()) {
return false;
}

try {
return $this->renderDeliveryOptions();
} catch (Throwable $e) {
Logger::error('Failed to render delivery options', ['exception' => $e, 'params' => $params]);

return false;
}
}

/**
* @param array $params
*
* @return false|string
*/
public function hookDisplayCarrierExtraContent(array $params)
{
if ($this->deliveryOptionsDisabled()) {
return false;
}

/** @var PsCarrierService $carrierService */
$carrierService = Pdk::get(PsCarrierService::class);

Expand All @@ -35,14 +61,22 @@ public function hookDisplayCarrierExtraContent($params)
}

try {
return $this->renderDeliveryOptions();
return $this->renderCarrierData($params['carrier']['id']);
} catch (Throwable $e) {
Logger::error('Failed to render delivery options', ['exception' => $e, 'params' => $params]);
Logger::error('Failed to render', ['exception' => $e, 'params' => $params]);

return false;
}
}

/**
* @return bool
*/
private function deliveryOptionsDisabled(): bool
{
return ! Settings::get(CheckoutSettings::ENABLE_DELIVERY_OPTIONS, CheckoutSettings::ID);
}

/**
* @param array $address
*
Expand All @@ -53,15 +87,31 @@ private function encodeAddress(array $address): string
return htmlspecialchars(json_encode(Utils::filterNull($address)), ENT_QUOTES, 'UTF-8');
}

/**
* @param int $carrierId
*
* @return string
*/
private function renderCarrierData(int $carrierId): string
{
/** @var PsCarrierService $carrierService */
$carrierService = Pdk::get(PsCarrierService::class);

$this->context->smarty->setEscapeHtml(false);
$this->context->smarty->assign([
'carrier' => $carrierService->getMyParcelCarrierIdentifier($carrierId),
]);

return $this->display($this->name, 'views/templates/hook/carrier_data.tpl');
}

/**
* @return string
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
private function renderDeliveryOptions(): string
{
/** @var PsCarrierService $carrierService */
$carrierService = Pdk::get(PsCarrierService::class);
/** @var PdkCartRepositoryInterface $cartRepository */
$cartRepository = Pdk::get(PdkCartRepositoryInterface::class);
/** @var \MyParcelNL\PrestaShop\Pdk\Base\Adapter\PsAddressAdapter $addressAdapter */
Expand All @@ -70,12 +120,11 @@ private function renderDeliveryOptions(): string
$cart = $this->context->cart;

$this->context->smarty->setEscapeHtml(false);

$this->context->smarty->assign([
'carrier' => $carrierService->getMyParcelCarrierIdentifier($cart->id_carrier),
'content' => Frontend::renderDeliveryOptions($cartRepository->get($cart)),
'shippingAddress' => $this->encodeAddress($addressAdapter->fromAddress($cart->id_address_delivery)),
'billingAddress' => $this->encodeAddress($addressAdapter->fromAddress($cart->id_address_invoice)),
'content' => Frontend::renderDeliveryOptions($cartRepository->get($cart)),

]);

return $this->display($this->name, 'views/templates/hook/carrier_delivery_options.tpl');
Expand Down
31 changes: 29 additions & 2 deletions src/Hooks/HasPsCarrierHooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace MyParcelNL\PrestaShop\Hooks;

use MyParcelNL\Pdk\Base\FileSystemInterface;
use MyParcelNL\Pdk\Facade\Logger;
use MyParcelNL\Pdk\Facade\Pdk;
use MyParcelNL\PrestaShop\Facade\EntityManager;
Expand Down Expand Up @@ -31,9 +32,10 @@ public function hookActionCarrierUpdate(array $params): void

try {
$this->updateCarrierId($oldId, $newId);
$this->moveCarrierImage($oldId, $newId);
} catch (Throwable $e) {
Logger::error(
'Failed to update carrier id',
'Failed to update carrier',
[
'exception' => $e,
'oldId' => $oldId,
Expand All @@ -43,6 +45,31 @@ public function hookActionCarrierUpdate(array $params): void
}
}

/**
* @param int $oldId
* @param int $newId
*
* @return void
*/
private function moveCarrierImage(int $oldId, int $newId): void
{
/** @var \MyParcelNL\Pdk\Base\FileSystemInterface $fileSystem */
$fileSystem = Pdk::get(FileSystemInterface::class);

foreach (Pdk::get('carrierLogoFileExtensions') as $fileExtension) {
$oldLogoFile = _PS_SHIP_IMG_DIR_ . $oldId . $fileExtension;

if (! $fileSystem->fileExists($oldLogoFile)) {
return;
}

$newLogoFile = _PS_SHIP_IMG_DIR_ . $newId . $fileExtension;

$fileSystem->put($newLogoFile, $fileSystem->get($oldLogoFile));
$fileSystem->unlink($oldLogoFile);
}
}

/**
* @param int $oldId
* @param int $newId
Expand All @@ -51,7 +78,7 @@ public function hookActionCarrierUpdate(array $params): void
* @throws \Doctrine\ORM\EntityNotFoundException
* @throws \Doctrine\ORM\ORMException
*/
public function updateCarrierId(int $oldId, int $newId): void
private function updateCarrierId(int $oldId, int $newId): void
{
/** @var PsCarrierMappingRepository $carrierMappingRepository */
$carrierMappingRepository = Pdk::get(PsCarrierMappingRepository::class);
Expand Down
2 changes: 2 additions & 0 deletions src/Pdk/Base/PsPdkBootstrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ protected function getConfig(string $version, string $name, string $path): array
'logDirectory' => value(sprintf('%s/var/logs/%s', _PS_ROOT_DIR_, $name)),
'carrierLogosDirectory' => value(sprintf('%sprivate/carrier-logos/', $path)),

'carrierLogoFileExtensions' => value(['.png', '.jpg']),

/**
* The symfony routes that are used by the pdk. Must match the routes in config/routes.yml.
*
Expand Down
16 changes: 15 additions & 1 deletion tests/Unit/Hooks/HasPsCarrierHooksTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

use Carrier as PsCarrier;
use Exception;
use MyParcelNL\Pdk\Base\FileSystemInterface;
use MyParcelNL\Pdk\Carrier\Model\Carrier;
use MyParcelNL\Pdk\Facade\Pdk;
use MyParcelNL\PrestaShop\Entity\MyparcelnlCarrierMapping;
Expand All @@ -23,9 +24,11 @@ class WithHasPsCarrierHooks
use HasPsCarrierHooks;
}

it('re-synchronises carrier id when it is updated', function () {
it('re-synchronises carrier id and logo when it is updated', function () {
/** @var PsCarrierMappingRepository $carrierMappingRepository */
$carrierMappingRepository = Pdk::get(PsCarrierMappingRepository::class);
/** @var \MyParcelNL\Pdk\Tests\Bootstrap\MockFileSystem $fileSystem */
$fileSystem = Pdk::get(FileSystemInterface::class);

psFactory(PsCarrier::class)
->withId(14)
Expand All @@ -36,6 +39,10 @@ class WithHasPsCarrierHooks
->withMyparcelCarrier(Carrier::CARRIER_DPD_NAME)
->store();

foreach (Pdk::get('carrierLogoFileExtensions') as $fileExtension) {
$fileSystem->put(_PS_SHIP_IMG_DIR_ . '14' . $fileExtension, '[IMAGE]');
}

$class = new WithHasPsCarrierHooks();

$class->hookActionCarrierUpdate([
Expand All @@ -51,4 +58,11 @@ class WithHasPsCarrierHooks
}

expect($found->getCarrierId())->toBe(15);

foreach (Pdk::get('carrierLogoFileExtensions') as $fileExtension) {
expect($fileSystem->fileExists(_PS_SHIP_IMG_DIR_ . '14' . $fileExtension))
->toBeFalse()
->and($fileSystem->fileExists(_PS_SHIP_IMG_DIR_ . '15' . $fileExtension))
->toBeTrue();
}
});
6 changes: 5 additions & 1 deletion tests/Uses/UsesMockPsPdkInstance.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,11 @@ protected function addDefaultData(): void
$fileSystem = Pdk::get(FileSystemInterface::class);

foreach (Config::get('carriers') as $carrier) {
$fileSystem->put(sprintf('%s%s.png', Pdk::get('carrierLogosDirectory'), $carrier['name']), '[IMAGE]');
foreach (Pdk::get('carrierLogoFileExtensions') as $fileExtension) {
$filename = Pdk::get('carrierLogosDirectory') . $carrier['name'] . $fileExtension;

$fileSystem->put($filename, '[IMAGE]');
}
}
}

Expand Down

0 comments on commit 9feee1d

Please sign in to comment.