Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions ColissimoLabel.php
Original file line number Diff line number Diff line change
Expand Up @@ -392,15 +392,25 @@ public static function getFileExtension(?string $labelType = null): string
*/
public static function canOrderBeNotSigned(Order $order): bool
{
$countryIsoCode = $order->getOrderAddressRelatedByDeliveryOrderAddressId()->getCountry()->getIsocode();
return self::canCountryBeNotSigned((string) $order->getOrderAddressRelatedByDeliveryOrderAddressId()->getCountry()->getIsocode());
}

/**
* A parcel may go without signature only to Europe or a DOMTOM, given the numeric ISO code of the delivery country.
*/
public static function canCountryBeNotSigned(string $countryIsoCode): bool
{
$countryIsoCode = trim($countryIsoCode);

/* Checking if the delivery country is in Europe or a DOMTOM. If not, it HAS to be signed */
if (!in_array($countryIsoCode, Service::DOMTOM_ISOCODES)
&& !in_array($countryIsoCode, Service::EUROPE_ISOCODES)) {
if ('' === $countryIsoCode) {
return false;
}

return true;
// A database migrated from Thelia 2 may store codes without their leading zero ('40' for '040').
$countryIsoCode = str_pad($countryIsoCode, 3, '0', STR_PAD_LEFT);

return in_array($countryIsoCode, Service::DOMTOM_ISOCODES, true)
|| in_array($countryIsoCode, Service::EUROPE_ISOCODES, true);
}

/**
Expand All @@ -419,7 +429,7 @@ public static function removeAccents($str): bool|string
public static function configureServices(ServicesConfigurator $servicesConfigurator): void
{
$servicesConfigurator->load(self::getModuleCode().'\\', __DIR__)
->exclude([__DIR__.'/I18n/*'])
->exclude([__DIR__.'/I18n/*', __DIR__.'/tests/*'])
->autowire()
->autoconfigure();
}
Expand Down
2 changes: 1 addition & 1 deletion Config/module.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<language>en_US</language>
<language>fr_FR</language>
</languages>
<version>3.0.3</version>
<version>3.1.0</version>
<authors>
<author>
<name>Gilles Bourgeat</name>
Expand Down
65 changes: 45 additions & 20 deletions Controller/Admin/BordereauController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,30 +20,36 @@
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Tools\TokenProvider;
use Thelia\Tools\URL;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;

#[Route('/admin/module/ColissimoLabel', name: 'colissimo_label_')]
class BordereauController extends AdminController
{
private const FLASH_ERROR = 'colissimo_label_bordereau_error';

public function __construct(private readonly Environment $twig)
{
}

/**
* Render the bordereau list page.
*
* @param null $error
*
* @return Response
* Render the bordereau list page, with the error left by a previous action if any.
*/
#[Route('/bordereaux', name: 'bordereau_list', methods: 'GET')]
public function listBordereauAction($error = null): Response
public function listBordereauAction(Request $request): Response
{
if (null !== $response = $this->checkAuth(AdminResources::ORDER, [], AccessManager::VIEW)) {
return $response;
}

$errors = $request->getSession()->getFlashBag()->get(self::FLASH_ERROR);

return $this->renderBordereauList($errors[0] ?? null);
}

private function renderBordereauList(?string $error): Response
{
/* We make sure the folders exist, and create them otherwise */
ColissimoLabel::checkLabelFolder();
$lastBordereauDate = ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_LAST_BORDEREAU_DATE);
Expand Down Expand Up @@ -79,6 +85,7 @@ public function listBordereauAction($error = null): Response
*/
#[Route('/labels', name: 'labels')]
public function listLabelsAction(
Request $request,
\Thelia\Core\Form\TheliaFormFactory $formFactory,
\ColissimoLabel\Service\OrdersNotSentProvider $ordersProvider
): Response {
Expand All @@ -94,7 +101,7 @@ public function listLabelsAction(
'@ColissimoLabelModule/backOffice/default-twig/colissimo-label/labels.html.twig',
[
'form' => $form->createView()->getView(),
'rows' => $ordersProvider->getRows($this->getCurrentEditionLocale()),
'rows' => $ordersProvider->getRows($request->getLocale()),
]
));
}
Expand All @@ -107,13 +114,15 @@ public function listLabelsAction(
*
* @throws Exception
*/
#[Route('/bordereau/generate', name: 'bordereau_generate', methods: 'GET')]
public function generateBordereauAction(): Response
#[Route('/bordereau/generate', name: 'bordereau_generate', methods: 'POST')]
public function generateBordereauAction(Request $request, TokenProvider $tokenProvider): Response
{
if (null !== $response = $this->checkAuth(AdminResources::ORDER, [], AccessManager::UPDATE)) {
return $response;
}

$tokenProvider->checkToken((string) $request->request->get('_token'));

/* Checking that the folder exists, and creates it otherwise */
ColissimoLabel::checkLabelFolder();

Expand All @@ -139,17 +148,17 @@ public function generateBordereauAction(): Response
try {
$parseResponse = $service->callGenerateBordereauByParcelsNumbersAPI($APIConfiguration, $parcelNumbers);
} catch (\SoapFault $soapFault) {
return $this->listBordereauAction('Error : '.$soapFault->getMessage());
return $this->redirectToBordereauList($request, 'Error : '.$soapFault->getMessage());
}

$resultAttachment = $parseResponse->attachments;

if (!isset($resultAttachment[0])) {
if (!isset($parseResponse->soapResponse['data'])) {
return $this->listBordereauAction('No label found');
return $this->redirectToBordereauList($request, 'No label found');
}

return $this->listBordereauAction('Error : '. $this->getError($parseResponse->soapResponse['data']));
return $this->redirectToBordereauList($request, 'Error : '.$this->getError($parseResponse->soapResponse['data']));
}
$bordereauContent = $resultAttachment[0];
$fileContent = $bordereauContent['data'];
Expand All @@ -170,7 +179,19 @@ public function generateBordereauAction(): Response
ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_LAST_BORDEREAU_DATE, (new DateTime())->format('Y-m-d H:i:s'));

/* We reload the list of bordereau */
return $this->listBordereauAction();
return $this->redirectToBordereauList($request);
}

/**
* Answer a form posted from the list with a redirect, so that a reload does not post it again.
*/
private function redirectToBordereauList(Request $request, ?string $error = null): Response
{
if (null !== $error) {
$request->getSession()->getFlashBag()->add(self::FLASH_ERROR, $error);
}

return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/bordereaux'));
}

/**
Expand All @@ -182,10 +203,12 @@ public function generateBordereauAction(): Response
*/
protected function getError($data): string
{
$errorMessage = explode('<messageContent>', $data);
$errorMessage = explode('</messageContent>', $errorMessage[1]);
$errorMessage = explode('<messageContent>', (string) $data);
if (!isset($errorMessage[1])) {
return 'Unknown error';
}

return $errorMessage[0];
return explode('</messageContent>', $errorMessage[1])[0];
}

/**
Expand All @@ -201,7 +224,7 @@ public function downloadBordereauAction(Request $request): Response
$fileName = (string) $request->query->get('fileName');

if (null === $filePath = $this->resolveBordereauPath($fileName)) {
return $this->listBordereauAction('Bordereau not found');
return $this->redirectToBordereauList($request, 'Bordereau not found');
}

$response = new BinaryFileResponse($filePath);
Expand Down Expand Up @@ -229,11 +252,13 @@ public function deleteBordereauAction(Request $request, TokenProvider $tokenProv

$tokenProvider->checkToken((string) $request->request->get('_token'));

if (null !== $filePath = $this->resolveBordereauPath((string) $request->query->get('fileName'))) {
$fileName = (string) $request->request->get('fileName');

if (null !== $filePath = $this->resolveBordereauPath($fileName)) {
(new Filesystem())->remove($filePath);
}

return $this->listBordereauAction();
return $this->redirectToBordereauList($request);
}

/**
Expand All @@ -250,7 +275,7 @@ private function resolveBordereauPath(string $fileName): ?string

$candidate = realpath($baseDir.DIRECTORY_SEPARATOR.basename($fileName));

if (false === $candidate || !str_starts_with($candidate, $baseDir.DIRECTORY_SEPARATOR)) {
if (false === $candidate || !is_file($candidate) || !str_starts_with($candidate, $baseDir.DIRECTORY_SEPARATOR)) {
return null;
}

Expand Down
68 changes: 50 additions & 18 deletions Controller/Admin/OrderController.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
use Thelia\Log\Tlog;
use Thelia\Model\ConfigQuery;
use Thelia\Model\OrderQuery;
use Thelia\Tools\TokenProvider;
use Thelia\Tools\URL;

#[Route('/admin/module/ColissimoLabel', name: 'colissimo_label_order_')]
Expand Down Expand Up @@ -226,41 +227,64 @@ public function getOrderLabelsAction($orderId): Response
*
* @throws PropelException
*/
#[Route('/label/delete/{number}', name: 'delete', methods: 'GET')]
public function deleteLabelAction(Request $request, string $number, LabelService $labelService): Response
#[Route('/label/delete', name: 'delete', methods: 'POST')]
public function deleteLabelAction(Request $request, LabelService $labelService, TokenProvider $tokenProvider): Response
{
$orderId = $labelService->deleteLabel($number);
if (null !== $response = $this->checkAuth(AdminResources::ORDER, [], AccessManager::UPDATE)) {
return $response;
}

$tokenProvider->checkToken((string) $request->request->get('_token'));

// An empty number would match every label file of the folder when the files are removed.
$number = trim((string) $request->request->get('number'));

if ('' === $number) {
return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/labels'));
}

$postedOrderId = (int) $request->request->get('order_id');

try {
$orderId = $labelService->deleteLabel($number);
} catch (TheliaProcessException) {
// The label is already gone, for instance after a second click on the same delete button.
if ($request->request->get('edit-order') && $postedOrderId > 0) {
return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/order/update/'.$postedOrderId.'?tab=bill'));
}

return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/labels'));
}

/* Handle the return when called from order edit */
if ($request->query->get('edit-order')) {
if ($request->request->get('edit-order')) {
return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/order/update/'.$orderId.'?tab=bill'));
}

return $this->generateRedirect(URL::getInstance()->absoluteUrl('admin/module/ColissimoLabel/labels#order-'.$orderId));
return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/labels#order-'.$orderId));
}

/**
* Download the CN23 customs invoice, given an order ID.
*/
#[Route('/customs-invoice/{orderId}', name: 'customers_invoice')]
public function getCustomsInvoiceAction($orderId, LabelService $labelService): Response
#[Route('/customs-invoice/{orderId}', name: 'customers_invoice', requirements: ['orderId' => '\d+'])]
public function getCustomsInvoiceAction(int $orderId, LabelService $labelService): Response
{
if (null !== $response = $this->checkAuth(AdminResources::ORDER, [], AccessManager::VIEW)) {
return $response;
}

if (null !== $fileName = $labelService->getCustomsInvoicePath($orderId)) {
return new Response(
file_get_contents($fileName),
200,
[
'Content-Type' => 'application/pdf',
'Content-disposition' => 'Attachement;filename='.basename($fileName),
]
);
$fileName = $labelService->getCustomsInvoicePath($orderId);

if (null === $fileName || !is_file($fileName)) {
return $this->pageNotFound();
}

return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/labels'));
$response = new BinaryFileResponse($fileName);
$response->headers->set('Content-Type', 'application/pdf');
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, basename($fileName));

return $response;
}

/**
Expand All @@ -273,7 +297,15 @@ public function getLabelAction(Request $request, string $number, LabelService $l
return $response;
}

$file = $labelService->getLabelPathByTrackingNumber($number, $fileName);
try {
$file = $labelService->getLabelPathByTrackingNumber($number, $fileName);
} catch (TheliaProcessException) {
$file = null;
}

if (null === $file || !is_file($file)) {
return $this->pageNotFound();
}

$response = new BinaryFileResponse($file);

Expand Down
9 changes: 9 additions & 0 deletions I18n/backOffice/default/en_US.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
return [
'/kg' => '/kg',
'Action' => 'Action',
'Actions' => 'Actions',
'Advanced configuration' => 'Advanced configuration',
'Bordereau' => 'Bordereau',
'Bordereaux' => 'Bordereaux',
'Bordereaux Colissimo' => 'Colissimo bordereaux',
'Cancel' => 'Cancel',
'Change to "Processing"' => 'Change to "Processing"',
'Change to "Sent". If you choose this option, the delivery notification email is sent to the customer, and the processed order are removed from this page.' => 'Change to "Sent". If you choose this option, the delivery notification email is sent to the customer, and the processed order are removed from this page.',
Expand All @@ -17,10 +19,12 @@
'Date' => 'Date',
'Delete' => 'Delete',
'Delete bordereau' => 'Delete bordereau',
'Delivery' => 'Delivery',
'Destination' => 'Destination',
'Do not change' => 'Do not change',
'Do you want to clear label and tracking number for this order ?' => 'Do you want to clear label and tracking number for this order ?',
'Do you want to clear this label and tracking number ?' => 'Do you want to clear this label and tracking number ?',
'Do you want to delete this bordereau ?' => 'Do you want to delete this bordereau ?',
'Download' => 'Download',
'Download and print Colissimo labels for orders not yet sent' => 'Download and print Colissimo labels for orders not yet sent',
'Download bordereau' => 'Download bordereau',
Expand All @@ -30,24 +34,29 @@
'Generate bordereau for label since : %date' => 'Generate bordereau for label since : %date',
'Generate new label' => 'Generate new label',
'Generate return label' => 'Generate return label',
'Home delivery' => 'Home delivery',
'Label' => 'Label',
'Label cannot be created. Error is: ' => 'Label cannot be created. Error is: ',
'Labels' => 'Labels',
'Labels Colissimo' => 'Labels Colissimo',
'Livraison avec signature' => 'Delivery with signature',
'Module' => 'Module',
'No bordereau has been generated yet' => 'No bordereau has been generated yet',
'No existing label for this order' => 'No existing label for this order',
'Non disponible' => 'Non disponible',
'Number' => 'Tracking Number',
'Order' => 'Order',
'Order date' => 'Order date',
'Order status change after processing' => 'Order status change after processing',
'Pickup point' => 'Pickup point',
'Please wait ...' => 'Please wait ...',
'Price (with taxes)' => 'Price (with taxes)',
'Print' => 'Print',
'Process selected orders' => 'Process selected orders',
'REF' => 'REF',
'Save changes' => 'Save changes',
'Sel.' => 'Sel.',
'Select' => 'Select',
'Sender\'s address' => 'Sender\'s address',
'Shipping weight :' => 'Shipping weight :',
'Signature' => 'Signature',
Expand Down
Loading
Loading