From b46b6ee430e6b5743d45b68f7ea4036f8a689a46 Mon Sep 17 00:00:00 2001 From: Thomas Da Silva Date: Wed, 28 Oct 2026 14:45:37 +0100 Subject: [PATCH 1/3] fix: render the back-office lists with the data table and post every state change with a token --- ColissimoLabel.php | 22 +- Config/module.xml | 2 +- Controller/Admin/BordereauController.php | 57 +++-- Controller/Admin/OrderController.php | 45 +++- I18n/backOffice/default/en_US.php | 8 + I18n/backOffice/default/fr_FR.php | 8 + Loop/ColissimoLabelInfo.php | 3 +- Readme.md | 9 +- Service/LabelService.php | 12 +- Service/OrdersNotSentProvider.php | 122 ++++++++-- .../colissimo-label/bordereau-list.html.twig | 72 +++--- .../colissimo-label/label-list.html.twig | 8 +- .../colissimo-label/labels.html.twig | 222 +++++++++++------- tests/LabelServiceTest.php | 61 +++++ tests/RouteContractTest.php | 35 +++ tests/SignatureRuleTest.php | 30 +++ tests/bootstrap.php | 18 ++ 17 files changed, 552 insertions(+), 182 deletions(-) create mode 100644 tests/LabelServiceTest.php create mode 100644 tests/RouteContractTest.php create mode 100644 tests/SignatureRuleTest.php create mode 100644 tests/bootstrap.php diff --git a/ColissimoLabel.php b/ColissimoLabel.php index 5b2f358..161942b 100644 --- a/ColissimoLabel.php +++ b/ColissimoLabel.php @@ -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); } /** @@ -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(); } diff --git a/Config/module.xml b/Config/module.xml index c7c1901..a0147af 100644 --- a/Config/module.xml +++ b/Config/module.xml @@ -13,7 +13,7 @@ en_US fr_FR - 3.0.3 + 3.1.0 Gilles Bourgeat diff --git a/Controller/Admin/BordereauController.php b/Controller/Admin/BordereauController.php index a9b5f28..37fd071 100644 --- a/Controller/Admin/BordereauController.php +++ b/Controller/Admin/BordereauController.php @@ -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); @@ -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 { @@ -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()), ] )); } @@ -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(); @@ -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']; @@ -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')); } /** @@ -201,7 +222,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); @@ -229,11 +250,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); } /** @@ -250,7 +273,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; } diff --git a/Controller/Admin/OrderController.php b/Controller/Admin/OrderController.php index 762bd54..04e9ae2 100644 --- a/Controller/Admin/OrderController.php +++ b/Controller/Admin/OrderController.php @@ -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_')] @@ -226,17 +227,41 @@ 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)); } /** @@ -273,7 +298,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); diff --git a/I18n/backOffice/default/en_US.php b/I18n/backOffice/default/en_US.php index 682cf84..f525dd6 100644 --- a/I18n/backOffice/default/en_US.php +++ b/I18n/backOffice/default/en_US.php @@ -3,6 +3,7 @@ return [ '/kg' => '/kg', 'Action' => 'Action', + 'Actions' => 'Actions', 'Advanced configuration' => 'Advanced configuration', 'Bordereau' => 'Bordereau', 'Bordereaux' => 'Bordereaux', @@ -17,10 +18,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', @@ -30,17 +33,21 @@ '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', @@ -48,6 +55,7 @@ 'REF' => 'REF', 'Save changes' => 'Save changes', 'Sel.' => 'Sel.', + 'Select' => 'Select', 'Sender\'s address' => 'Sender\'s address', 'Shipping weight :' => 'Shipping weight :', 'Signature' => 'Signature', diff --git a/I18n/backOffice/default/fr_FR.php b/I18n/backOffice/default/fr_FR.php index 84cca16..c1acbf4 100644 --- a/I18n/backOffice/default/fr_FR.php +++ b/I18n/backOffice/default/fr_FR.php @@ -3,6 +3,7 @@ return [ '/kg' => '/kg', 'Action' => 'Action', + 'Actions' => 'Actions', 'Advanced configuration' => 'Configuration avancée', 'Bordereau' => 'Bordereau', 'Bordereaux' => 'Bordereaux', @@ -18,10 +19,12 @@ 'Date' => 'Date', 'Delete' => 'Supprimer', 'Delete bordereau' => 'Supprimer le bordereau', + 'Delivery' => 'Livraison', 'Destination' => 'Destination', 'Do not change' => 'Ne pas modifier', 'Do you want to clear label and tracking number for this order ?' => 'Voulez-vous supprimer cette étiquette et le n° de suivi ?', 'Do you want to clear this label and tracking number ?' => 'Voulez-vous supprimer cette étiquette ainsi que son numéro de suivi ?', + 'Do you want to delete this bordereau ?' => 'Voulez-vous supprimer ce bordereau ?', 'Download' => 'Télécharger', 'Download and print Colissimo labels for orders not yet sent' => 'Télécharger et imprimer les étiquettes Colissimo pour les commandes non envoyées', 'Download bordereau' => 'Télécharger le bordereau', @@ -31,17 +34,21 @@ 'Generate bordereau for label since : %date' => 'Générer un bordereau pour les étiquettes créée depuis : %date', 'Generate new label' => 'Générer une étiquette', 'Generate return label' => 'Générer une étiquette de retour', + 'Home delivery' => 'Domicile', 'Label' => 'Etiquette', 'Label cannot be created. Error is: ' => 'L\'étiquette n\'a pas pu être créée. Erreur: ', 'Labels' => 'Etiquettes', 'Labels Colissimo' => 'Étiquette Colissimo', 'Livraison avec signature' => 'Livraison avec signature', 'Module' => 'Module', + 'No bordereau has been generated yet' => 'Aucun bordereau n\'a encore été généré', 'No existing label for this order' => 'Aucune étiquette pour cette commande', 'Non disponible' => 'Non disponible', 'Number' => 'Numéro', + 'Order' => 'Commande', 'Order date' => 'Date de commande', 'Order status change after processing' => 'Statut de commande après la création de l\'étiquette', + 'Pickup point' => 'Point relais', 'Please wait ...' => 'Veuillez patienter ...', 'Price (with taxes)' => 'Prix (TTC)', 'Print' => 'Imprimer', @@ -49,6 +56,7 @@ 'REF' => 'REF', 'Save changes' => 'Enregistrer les modifications', 'Sel.' => 'Sel.', + 'Select' => 'Sélectionner', 'Sender\'s address' => 'Adresse de l\'envoyeur', 'Shipping weight :' => 'Poids d\'expédition :', 'Signature' => 'Signature', diff --git a/Loop/ColissimoLabelInfo.php b/Loop/ColissimoLabelInfo.php index b85d014..c11b799 100644 --- a/Loop/ColissimoLabelInfo.php +++ b/Loop/ColissimoLabelInfo.php @@ -91,7 +91,8 @@ public function parseResults(LoopResult $loopResult): LoopResult ->set('HAS_CUSTOMS_INVOICE', $result->getWithCustomsInvoice()) ->set('LABEL_URL', URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/label/'.$result->getTrackingNumber().'?download=1')) ->set('CUSTOMS_INVOICE_URL', URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/customs-invoice/'.$result->getOrderId())) - ->set('CLEAR_LABEL_URL', URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/label/delete/'.$result->getTrackingNumber().'?order='.$result->getOrderId())) + // This URL expects a POST (_token, number), not a GET. + ->set('CLEAR_LABEL_URL', URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/label/delete')) ->set('CAN_BE_NOT_SIGNED', ColissimoLabel::canOrderBeNotSigned($result->getOrder())) ->set('ORDER_DATE', $result->getOrder()->getCreatedAt()) ->set('CREATED_AT', $result->getCreatedAt()) diff --git a/Readme.md b/Readme.md index 2fbbdb3..472949c 100644 --- a/Readme.md +++ b/Readme.md @@ -63,7 +63,7 @@ If your module declare one or more loop, describe them here like this : |$HAS_CUSTOMS_INVOICE | (bool) Whether a customs invoice was created or not | |$LABEL_URL | The URL from which to download the URL | |$CUSTOMS_INVOICE_URL | The URL from which to download the customs invoice | -|$CLEAR_LABEL_URL | The URL from which to delete the label | +|$CLEAR_LABEL_URL | URL to POST to delete the label, with `_token`, `number` (tracking number) and optionally `edit-order` and `order_id` | |$CAN_BE_NOT_SIGNED | (bool) Whether the order HAS to be signed or not | |$ORDER_DATE | The order date | @@ -79,6 +79,13 @@ If your module declare one or more loop, describe them here like this : Same as an order loop, but only order that weren't sent or cancelled and that are paid for will be searched for. +## Changes in 3.1.0 + +- Deleting a label is a POST with a token (`_token`, `number`), no longer a GET link. +- Generating and deleting a bordereau are POST requests with a token. +- `$CLEAR_LABEL_URL` is now the URL to POST to, not a link to follow. +- The back-office lists are rendered with the theme data table. + ## Other ? If you have other think to put, feel free to complete your readme as you want. diff --git a/Service/LabelService.php b/Service/LabelService.php index 10bf8d7..9ee15e5 100644 --- a/Service/LabelService.php +++ b/Service/LabelService.php @@ -278,6 +278,11 @@ public function getLabelPathByTrackingNumber(string $trackingNumber, &$prettyFil */ public function deleteLabel(string $trackingNumber): int { + /* An empty tracking number would match every file of the label folder in deleteLabelFile() */ + if ('' === trim($trackingNumber)) { + throw new \InvalidArgumentException('A tracking number is required to delete a label'); + } + if (null === $label = ColissimoLabelQuery::create()->findOneByTrackingNumber($trackingNumber)) { throw new TheliaProcessException('The label for tracking number '.$trackingNumber.' was not found'); } @@ -304,14 +309,15 @@ public function deleteLabel(string $trackingNumber): int * @param $fileName * @return void */ - protected function deleteLabelFile($fileName): void + protected function deleteLabelFile($fileName, string $folder = ColissimoLabel::LABEL_FOLDER): void { $finder = new Finder(); $fileSystem = new Filesystem(); - $finder->files()->name($fileName.'*')->in(ColissimoLabel::LABEL_FOLDER); + // Only . and -CN23.: a plain prefix would also match other numbers. + $finder->files()->name($fileName.'.*')->name($fileName.'-CN23.*')->in($folder); foreach ($finder as $file) { - $fileSystem->remove(ColissimoLabel::LABEL_FOLDER.DS.$file->getFilename()); + $fileSystem->remove($folder.DS.$file->getFilename()); } } } diff --git a/Service/OrdersNotSentProvider.php b/Service/OrdersNotSentProvider.php index b379ccb..e498b0e 100644 --- a/Service/OrdersNotSentProvider.php +++ b/Service/OrdersNotSentProvider.php @@ -4,10 +4,16 @@ use ColissimoLabel\ColissimoLabel; use ColissimoLabel\Enum\AuthorizedModuleEnum; +use ColissimoLabel\Model\ColissimoLabel as ColissimoLabelModel; use ColissimoLabel\Model\ColissimoLabelQuery; use Propel\Runtime\ActiveQuery\Criteria; +use Thelia\Model\Country; +use Thelia\Model\CountryQuery; +use Thelia\Model\CurrencyQuery; use Thelia\Model\ModuleQuery; use Thelia\Model\Order; +use Thelia\Model\OrderAddress; +use Thelia\Model\OrderAddressQuery; use Thelia\Model\OrderQuery; use Thelia\Model\OrderStatus; use Thelia\Model\OrderStatusQuery; @@ -47,40 +53,103 @@ public function getRows(string $locale): array ) ->find(); - $rows = []; + if ($orders->isEmpty()) { + return []; + } + /* The labels, addresses, countries and currencies of the whole list are loaded once, not once per order */ + $orderIds = []; + $addressIds = []; foreach ($orders as $order) { - $rows[] = $this->buildRow($order, $locale); + $orderIds[] = $order->getId(); + $addressIds[] = $order->getDeliveryOrderAddressId(); + } + + $labels = []; + foreach (ColissimoLabelQuery::create()->filterByOrderId($orderIds, Criteria::IN)->orderById()->find() as $label) { + /* The first label of an order is the one shown, as before */ + $labels[$label->getOrderId()] ??= $label; + } + + $addresses = []; + $countryIds = []; + foreach (OrderAddressQuery::create()->filterById($addressIds, Criteria::IN)->find() as $address) { + $addresses[$address->getId()] = $address; + $countryIds[$address->getCountryId()] = true; + } + + $countries = []; + foreach (CountryQuery::create()->filterById(array_keys($countryIds), Criteria::IN)->joinWithI18n($locale)->find() as $country) { + $countries[$country->getId()] = $country; + } + + $currencyCodes = CurrencyQuery::create()->find()->toKeyValue('Id', 'Code'); + + $context = [ + 'locale' => $locale, + 'default_signed' => (bool) ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_DEFAULT_SIGNED), + 'date_formatter' => new \IntlDateFormatter($locale, \IntlDateFormatter::SHORT, \IntlDateFormatter::SHORT), + 'amount_formatter' => new \NumberFormatter($locale, \NumberFormatter::CURRENCY), + ]; + + $rows = []; + foreach ($orders as $order) { + $deliveryAddress = $addresses[$order->getDeliveryOrderAddressId()] ?? null; + $rows[] = $this->buildRow( + $order, + $deliveryAddress, + null !== $deliveryAddress ? ($countries[$deliveryAddress->getCountryId()] ?? null) : null, + $labels[$order->getId()] ?? null, + $currencyCodes[$order->getCurrencyId()] ?? 'EUR', + $context + ); } return $rows; } - private function buildRow(Order $order, string $locale): array - { - $deliveryAddress = $order->getOrderAddressRelatedByDeliveryOrderAddressId(); + /** + * @param array{locale: string, default_signed: bool, date_formatter: \IntlDateFormatter, amount_formatter: \NumberFormatter} $context + */ + private function buildRow( + Order $order, + ?OrderAddress $deliveryAddress, + ?Country $country, + ?ColissimoLabelModel $label, + string $currencyCode, + array $context + ): array { + $locale = $context['locale']; $countryTitle = ''; - if (null !== $deliveryAddress && null !== $country = $deliveryAddress->getCountry()) { - $countryTitle = $country->setLocale($locale)->getTitle(); + $countryFlag = ''; + if (null !== $country) { + $countryTitle = (string) $country->setLocale($locale)->getTitle(); + if ('' === $countryTitle) { + $countryTitle = (string) $country->getIsoalpha2(); + } + $countryFlag = $this->countryFlag((string) $country->getIsoalpha2()); } - $label = ColissimoLabelQuery::create() - ->filterByOrderId($order->getId()) - ->orderById() - ->findOne(); - - $defaultSigned = (bool) ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_DEFAULT_SIGNED); + $deliveryModule = $order->getModuleRelatedByDeliveryModuleId(); + $orderDate = $order->getCreatedAt(); + $totalTaxedAmount = $order->getTotalAmount(); $row = [ + 'id' => $order->getId(), 'order_id' => $order->getId(), 'ref' => $order->getRef(), - 'order_date' => $order->getCreatedAt(), + 'order_url' => URL::getInstance()->absoluteUrl('/admin/order/update/'.$order->getId(), ['tab' => 'bill']), + 'order_date' => $orderDate, + 'order_date_label' => $orderDate instanceof \DateTimeInterface ? (string) $context['date_formatter']->format($orderDate) : '', 'city' => $deliveryAddress?->getCity() ?? '', 'zipcode' => $deliveryAddress?->getZipcode() ?? '', 'country' => $countryTitle, - 'total_taxed_amount' => $order->getTotalAmount(), - 'module_code' => $order->getModuleRelatedByDeliveryModuleId()?->getCode() ?? '', - 'can_be_not_signed' => ColissimoLabel::canOrderBeNotSigned($order), + 'country_flag' => $countryFlag, + 'total_taxed_amount' => $totalTaxedAmount, + 'amount_label' => (string) $context['amount_formatter']->formatCurrency((float) $totalTaxedAmount, $currencyCode), + 'module_code' => $deliveryModule?->getCode() ?? '', + 'module_title' => $deliveryModule?->setLocale($locale)->getTitle() ?: ($deliveryModule?->getCode() ?? ''), + 'can_be_not_signed' => ColissimoLabel::canCountryBeNotSigned((string) $country?->getIsocode()), 'has_error' => false, 'error_message' => null, 'has_customs_invoice' => false, @@ -91,11 +160,10 @@ private function buildRow(Order $order, string $locale): array if (null === $label) { return array_merge($row, [ 'weight' => $order->getWeight(), - 'signed' => $defaultSigned, + 'signed' => $context['default_signed'], 'tracking_number' => null, 'has_label' => false, 'label_url' => null, - 'clear_label_url' => null, ]); } @@ -110,7 +178,21 @@ private function buildRow(Order $order, string $locale): array 'has_customs_invoice' => (bool) $label->getWithCustomsInvoice(), 'label_url' => URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/label/'.$label->getTrackingNumber().'?download=1'), 'customs_invoice_url' => URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/customs-invoice/'.$label->getOrderId()), - 'clear_label_url' => URL::getInstance()->absoluteUrl('/admin/module/ColissimoLabel/label/delete/'.$label->getTrackingNumber().'?order='.$label->getOrderId()), ]); } + + /** + * Same emoji flag as the order list of the back office, built from the two regional indicator letters. + */ + private function countryFlag(string $isoAlpha2): string + { + if (2 !== \strlen($isoAlpha2) || !ctype_alpha($isoAlpha2)) { + return ''; + } + + $offset = 0x1F1E6 - \ord('A'); + $upper = strtoupper($isoAlpha2); + + return mb_chr(\ord($upper[0]) + $offset).mb_chr(\ord($upper[1]) + $offset); + } } diff --git a/templates/backOffice/default-twig/colissimo-label/bordereau-list.html.twig b/templates/backOffice/default-twig/colissimo-label/bordereau-list.html.twig index f632751..2dbd43a 100644 --- a/templates/backOffice/default-twig/colissimo-label/bordereau-list.html.twig +++ b/templates/backOffice/default-twig/colissimo-label/bordereau-list.html.twig @@ -25,46 +25,42 @@ {% endif %} -

- +

+ + +
- {% if bordereaux is not empty %} - - - - - - - - - - - - - {% for bordereau in bordereaux %} - - - - - {% endfor %} - -
{{ 'Bordereau'|trans({}, 'colissimolabel.bo.default') }}{{ 'Action'|trans({}, 'colissimolabel.bo.default') }}
- {{ bordereau.name }} - - - - -
- - -
-
- {% endif %} + {% set domain = 'colissimolabel.bo.default' %} + {% set rows = bordereaux|map(bordereau => { + id: bordereau.name, + name_html: '' ~ bordereau.name|e ~ '', + _actions: [ + row_action('download', 'Download bordereau'|trans({}, domain), href: path('colissimo_label_bordereau_download') ~ '?stay=1&fileName=' ~ bordereau.name|url_encode), + row_action('delete', 'Delete bordereau'|trans({}, domain), modalTarget: '#colissimo-bordereau-delete', dataAttributes: { 'file-name': bordereau.name }), + ], + }) %} + + {{ component('BoDataTable', { + id: 'colissimo-bordereaux', + columns: [ + column_html('name_html', 'Bordereau'|trans({}, domain)), + column_actions('_actions', 'Actions'|trans({}, domain)), + ], + rows: rows, + emptyMessage: 'No bordereau has been generated yet'|trans({}, domain), + }) }} + + {{ component('BoConfirmDialog', { + id: 'colissimo-bordereau-delete', + title: 'Delete bordereau'|trans({}, domain), + message: 'Do you want to delete this bordereau ?'|trans({}, domain), + formAction: path('colissimo_label_delete'), + testid: 'colissimo-bordereau-delete', + prefillTrigger: 'data-file-name', + prefillInput: 'fileName', + }) }} diff --git a/templates/backOffice/default-twig/colissimo-label/label-list.html.twig b/templates/backOffice/default-twig/colissimo-label/label-list.html.twig index bcf3734..65d601b 100644 --- a/templates/backOffice/default-twig/colissimo-label/label-list.html.twig +++ b/templates/backOffice/default-twig/colissimo-label/label-list.html.twig @@ -17,7 +17,13 @@ {{ 'Customs invoice'|trans({}, 'colissimolabel.bo.default') }} {% endif %} - {{ 'Delete'|trans({}, 'colissimolabel.bo.default') }} +
+ + + + + +
diff --git a/templates/backOffice/default-twig/colissimo-label/labels.html.twig b/templates/backOffice/default-twig/colissimo-label/labels.html.twig index b6e1a9a..eec3704 100644 --- a/templates/backOffice/default-twig/colissimo-label/labels.html.twig +++ b/templates/backOffice/default-twig/colissimo-label/labels.html.twig @@ -45,101 +45,147 @@ + {#- column_html prints a cell raw: each cell is a macro below, so Twig escapes every value. Inputs + stay in columns shown at every width: a column folded into the row details would print them + twice. The actions are buttons rather than row_action(): the theme maps an action kind to a + generic glyph, and the label and the customs invoice must not look alike. -#} + {% import _self as cells %} + {% set domain = 'colissimolabel.bo.default' %} + {% set table_rows = rows|map(row => row|merge({ + _attrs: { id: 'order-' ~ row.order_id }, + _row_class: row.has_error ? 'table-warning' : '', + select_html: cells.select(row, form.order_id.vars.full_name), + order_html: cells.order(row), + destination_html: cells.destination(row), + delivery_html: cells.delivery(row), + weight_html: cells.weight(row, form.weight.vars.full_name), + signed_html: cells.signed(row, form.signed.vars.full_name), + tracking_html: cells.tracking(row), + actions_html: cells.actions(row), + })) %} + + {#- Same submit as under the table: a long list should not have to be scrolled to its end. -#} {% if rows is not empty %} - - - - - - - - - - - - - - - - - - {% for row in rows %} - - - - - - - - - - - - - - {% if row.has_error %} - - - - {% endif %} - {% endfor %} - -
{{ 'REF'|trans({}, 'colissimolabel.bo.default') }}{{ 'Order date'|trans({}, 'colissimolabel.bo.default') }}{{ 'Destination'|trans({}, 'colissimolabel.bo.default') }}{{ 'Weight'|trans({}, 'colissimolabel.bo.default') }}{{ 'Price (with taxes)'|trans({}, 'colissimolabel.bo.default') }}{{ 'Signature'|trans({}, 'colissimolabel.bo.default') }}{{ 'Module'|trans({}, 'colissimolabel.bo.default') }}{{ 'Tracking'|trans({}, 'colissimolabel.bo.default') }}{{ 'Label'|trans({}, 'colissimolabel.bo.default') }}{{ 'Customs invoice'|trans({}, 'colissimolabel.bo.default') }}{{ 'Sel.'|trans({}, 'colissimolabel.bo.default') }}
{{ row.ref }}{{ row.order_date ? row.order_date|date('Y-m-d H:i:s') : '' }}{{ row.city|upper }} {{ row.zipcode|upper }}, {{ row.country|upper }} -
- - {{ 'kg'|trans({}, 'colissimolabel.bo.default') }} -
-
{{ row.total_taxed_amount|number_format(2, '.', '') }} - - {{ row.module_code }} - {% if row.tracking_number %} - {{ row.tracking_number }} - {% else %} - - {% endif %} - - {% if row.has_label %} - - - - {% else %} - - {% endif %} - - {% if row.has_customs_invoice %} - - - - {% else %}-{% endif %} - - {% if not row.has_label %} - - {% else %} - - - - {% endif %} -
- {{ 'Label cannot be created. Error is: '|trans({}, 'colissimolabel.bo.default') }} - {{ row.error_message }} -
- - {% do form.order_id.setRendered %} - {% do form.weight.setRendered %} - {% do form.signed.setRendered %} - -
-
- -
+
+ +
+ {% endif %} + + {{ component('BoDataTable', { + id: 'colissimo-labels', + columns: [ + column_html('select_html', 'Sel.'|trans({}, domain), 'center'), + column_html('order_html', 'Order'|trans({}, domain)), + column_html('destination_html', 'Destination'|trans({}, domain)), + column_html('delivery_html', 'Delivery'|trans({}, domain)), + column_text('amount_label', 'Price (with taxes)'|trans({}, domain), 'end', leftToRight: true), + column_html('weight_html', 'Weight'|trans({}, domain)), + column_html('signed_html', 'Signature'|trans({}, domain), 'center'), + column_html('tracking_html', 'Tracking'|trans({}, domain)), + column_html('actions_html', 'Actions'|trans({}, domain), 'end'), + ], + rows: table_rows, + emptyMessage: 'There are currently no orders to ship with Colissimo'|trans({}, domain), + rowIdentifierKey: 'ref', + }) }} + + {% do form.order_id.setRendered %} + {% do form.weight.setRendered %} + {% do form.signed.setRendered %} + + {% if rows is not empty %} +
+
- {% else %} -
{{ 'There are currently no orders to ship with Colissimo'|trans({}, 'colissimolabel.bo.default') }}
{% endif %} {{ form_end(form) }} + + {#- Outside the export form: a form cannot hold another one. -#} + {{ component('BoConfirmDialog', { + id: 'colissimo-label-clear', + title: 'Clear label'|trans({}, 'colissimolabel.bo.default'), + message: 'Do you want to clear label and tracking number for this order ?'|trans({}, 'colissimolabel.bo.default'), + formAction: path('colissimo_label_order_delete'), + testid: 'colissimo-label-clear', + prefillTrigger: 'data-number', + prefillInput: 'number', + }) }}
{% endblock %} + +{% macro select(row, name) -%} + {%- if not row.has_label -%} + + {%- endif -%} +{%- endmacro %} + +{% macro order(row) -%} + {{ row.ref }} +
{{ row.order_date_label }}
+{%- endmacro %} + +{% macro destination(row) -%} +
+
+ {%- if row.country_flag %}{{ row.country_flag }} {% endif -%} + {{ (row.city ~ ' ' ~ row.zipcode)|upper }} +
+
{{ row.country }}
+ {%- if row.has_error %} +
{{ 'Label cannot be created. Error is: '|trans({}, 'colissimolabel.bo.default') }}{{ row.error_message }}
+ {%- endif %} +
+{%- endmacro %} + +{% macro delivery(row) -%} + {%- set pickup = row.module_code == 'ColissimoPickupPoint' -%} + + + {{ (pickup ? 'Pickup point' : 'Home delivery')|trans({}, 'colissimolabel.bo.default') }} + +{%- endmacro %} + +{% macro weight(row, name) -%} +
+ + {{ 'kg'|trans({}, 'colissimolabel.bo.default') }} +
+{%- endmacro %} + +{% macro signed(row, name) -%} + +{%- endmacro %} + +{% macro tracking(row) -%} + {%- if row.tracking_number -%} + {{ row.tracking_number }} + {%- else -%} + - + {%- endif -%} +{%- endmacro %} + +{% macro actions(row) -%} + {%- set domain = 'colissimolabel.bo.default' -%} + {%- if row.has_label or row.has_customs_invoice -%} +
+ {%- if row.has_label %} + {%- set title = 'Download label (%fmt)'|trans({ '%fmt': row.label_type|upper }, domain) %} + + {%- endif %} + {%- if row.has_customs_invoice %} + {%- set title = 'Download customs invoice (PDF)'|trans({}, domain) %} + + {%- endif %} + {%- if row.has_label %} + {%- set title = 'Clear label'|trans({}, domain) %} + + {%- endif %} +
+ {%- endif -%} +{%- endmacro %} diff --git a/tests/LabelServiceTest.php b/tests/LabelServiceTest.php new file mode 100644 index 0000000..981e270 --- /dev/null +++ b/tests/LabelServiceTest.php @@ -0,0 +1,61 @@ + ['']; + yield 'blank' => [' ']; + } + + /** + * An empty tracking number would select every file of the label folder for deletion. + */ + #[DataProvider('emptyTrackingNumbers')] + public function testDeleteLabelRefusesAnEmptyTrackingNumber(string $trackingNumber): void + { + $this->expectException(\InvalidArgumentException::class); + + (new LabelService(new EventDispatcher()))->deleteLabel($trackingNumber); + } + + /** + * Deleting label 6A1 must not remove the files of label 6A12, which shares its prefix. + */ + public function testDeleteLabelFileKeepsTheFilesOfAnotherNumberSharingThePrefix(): void + { + $folder = sys_get_temp_dir().'/colissimo-label-test-'.uniqid(); + mkdir($folder); + + try { + foreach (['6A1.pdf', '6A1-CN23.pdf', '6A12.pdf', '6A12-CN23.pdf'] as $name) { + touch($folder.'/'.$name); + } + + $service = new class(new EventDispatcher()) extends LabelService { + public function deleteIn(string $number, string $folder): void + { + $this->deleteLabelFile($number, $folder); + } + }; + $service->deleteIn('6A1', $folder); + + $this->assertFileDoesNotExist($folder.'/6A1.pdf'); + $this->assertFileDoesNotExist($folder.'/6A1-CN23.pdf'); + $this->assertFileExists($folder.'/6A12.pdf'); + $this->assertFileExists($folder.'/6A12-CN23.pdf'); + } finally { + foreach (glob($folder.'/*') ?: [] as $file) { + unlink($file); + } + rmdir($folder); + } + } +} diff --git a/tests/RouteContractTest.php b/tests/RouteContractTest.php new file mode 100644 index 0000000..f89b973 --- /dev/null +++ b/tests/RouteContractTest.php @@ -0,0 +1,35 @@ + [OrderController::class, 'deleteLabelAction', '/label/delete']; + yield 'bordereau generation' => [BordereauController::class, 'generateBordereauAction', '/bordereau/generate']; + yield 'bordereau deletion' => [BordereauController::class, 'deleteBordereauAction', '/bordereau/delete']; + } + + #[DataProvider('stateChangingActions')] + public function testStateChangingActionsOnlyAnswerPost(string $controller, string $action, string $path): void + { + $attributes = (new \ReflectionMethod($controller, $action))->getAttributes(Route::class); + + self::assertCount(1, $attributes); + + $route = $attributes[0]->newInstance(); + + self::assertSame($path, $route->getPath()); + self::assertSame(['POST'], $route->getMethods()); + } +} diff --git a/tests/SignatureRuleTest.php b/tests/SignatureRuleTest.php new file mode 100644 index 0000000..4b4caea --- /dev/null +++ b/tests/SignatureRuleTest.php @@ -0,0 +1,30 @@ + ['250', true]; + yield 'Germany' => ['276', true]; + yield 'Guyane, a DOMTOM' => ['254', true]; + yield 'United States' => ['840', false]; + yield 'Switzerland, outside the EU' => ['756', true]; + yield 'Japan' => ['392', false]; + yield 'Austria, migrated code without leading zero' => ['40', true]; + yield 'Belgium, migrated code without leading zero' => ['56', true]; + yield 'France, padded with spaces' => [' 250 ', true]; + yield 'unknown country' => ['', false]; + } + + #[DataProvider('countries')] + public function testOnlyEuropeAndDomtomMayGoWithoutSignature(string $numericIsoCode, bool $mayGoWithoutSignature): void + { + self::assertSame($mayGoWithoutSignature, ColissimoLabel::canCountryBeNotSigned($numericIsoCode)); + } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 0000000..cca7334 --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,18 @@ + Date: Wed, 28 Oct 2026 14:58:08 +0100 Subject: [PATCH 2/3] fix: load the order weights in one query, open the bill tab after a label deletion and answer 404 on a missing customs invoice --- Controller/Admin/BordereauController.php | 8 +++-- Controller/Admin/OrderController.php | 23 +++++++------- I18n/backOffice/default/en_US.php | 1 + I18n/backOffice/default/fr_FR.php | 1 + Service/LabelService.php | 17 +++-------- Service/OrdersNotSentProvider.php | 20 +++++++++++-- .../hook/order-edit-js.html.twig | 12 ++++++-- tests/LabelServiceTest.php | 30 +++++++++++++++++++ 8 files changed, 79 insertions(+), 33 deletions(-) diff --git a/Controller/Admin/BordereauController.php b/Controller/Admin/BordereauController.php index 37fd071..56c8dd9 100644 --- a/Controller/Admin/BordereauController.php +++ b/Controller/Admin/BordereauController.php @@ -203,10 +203,12 @@ private function redirectToBordereauList(Request $request, ?string $error = null */ protected function getError($data): string { - $errorMessage = explode('', $data); - $errorMessage = explode('', $errorMessage[1]); + $errorMessage = explode('', (string) $data); + if (!isset($errorMessage[1])) { + return 'Unknown error'; + } - return $errorMessage[0]; + return explode('', $errorMessage[1])[0]; } /** diff --git a/Controller/Admin/OrderController.php b/Controller/Admin/OrderController.php index 04e9ae2..7d048ec 100644 --- a/Controller/Admin/OrderController.php +++ b/Controller/Admin/OrderController.php @@ -267,25 +267,24 @@ public function deleteLabelAction(Request $request, LabelService $labelService, /** * 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; } /** diff --git a/I18n/backOffice/default/en_US.php b/I18n/backOffice/default/en_US.php index f525dd6..9d2c8da 100644 --- a/I18n/backOffice/default/en_US.php +++ b/I18n/backOffice/default/en_US.php @@ -7,6 +7,7 @@ '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.', diff --git a/I18n/backOffice/default/fr_FR.php b/I18n/backOffice/default/fr_FR.php index c1acbf4..46dde36 100644 --- a/I18n/backOffice/default/fr_FR.php +++ b/I18n/backOffice/default/fr_FR.php @@ -7,6 +7,7 @@ 'Advanced configuration' => 'Configuration avancée', 'Bordereau' => 'Bordereau', 'Bordereaux' => 'Bordereaux', + 'Bordereaux Colissimo' => 'Bordereaux Colissimo', 'Cancel' => 'Annuler', 'Change to "Processing"' => 'Changer en "Traitement"', '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.' => 'Changer en "Envoyée". Choisir cette option retirera la commande de cette liste, et enverra un mail de notification au client.', diff --git a/Service/LabelService.php b/Service/LabelService.php index 9ee15e5..96996ac 100644 --- a/Service/LabelService.php +++ b/Service/LabelService.php @@ -287,17 +287,8 @@ public function deleteLabel(string $trackingNumber): int throw new TheliaProcessException('The label for tracking number '.$trackingNumber.' was not found'); } - /* We check if the label is from this module */ - /* We check if the label is from this version of the module -- Compatibility with ColissimoLabel < 1.0.0 */ - if ($label && '' !== $trackNo = $label->getTrackingNumber()) { - $this->deleteLabelFile($trackNo); - } - - /* - * If we're here, it means the label is coming from a version of ColissimoLabel < 1.0.0 - * So we need to delete it with its tracking number instead of order ref, since it was named like that back then - */ - $this->deleteLabelFile($trackingNumber); + /* The stored value is used: the column is case-insensitive, the posted one may differ in case */ + $this->deleteLabelFile($label->getTrackingNumber()); $label->delete(); @@ -315,9 +306,9 @@ protected function deleteLabelFile($fileName, string $folder = ColissimoLabel::L $fileSystem = new Filesystem(); // Only . and -CN23.: a plain prefix would also match other numbers. - $finder->files()->name($fileName.'.*')->name($fileName.'-CN23.*')->in($folder); + $finder->files()->name($fileName.'.*')->name($fileName.'-CN23.*')->in($folder)->depth('== 0'); foreach ($finder as $file) { - $fileSystem->remove($folder.DS.$file->getFilename()); + $fileSystem->remove($file->getRealPath()); } } } diff --git a/Service/OrdersNotSentProvider.php b/Service/OrdersNotSentProvider.php index e498b0e..3080cd1 100644 --- a/Service/OrdersNotSentProvider.php +++ b/Service/OrdersNotSentProvider.php @@ -14,6 +14,7 @@ use Thelia\Model\Order; use Thelia\Model\OrderAddress; use Thelia\Model\OrderAddressQuery; +use Thelia\Model\OrderProductQuery; use Thelia\Model\OrderQuery; use Thelia\Model\OrderStatus; use Thelia\Model\OrderStatusQuery; @@ -83,10 +84,23 @@ public function getRows(string $locale): array $countries[$country->getId()] = $country; } + /* Same sum as Order::getWeight(), for the whole list in one query */ + $weights = []; + $weightRows = OrderProductQuery::create() + ->filterByOrderId($orderIds, Criteria::IN) + ->withColumn('SUM(order_product.quantity * order_product.weight)', 'total_weight') + ->select(['OrderId', 'total_weight']) + ->groupByOrderId() + ->find(); + foreach ($weightRows as $weightRow) { + $weights[$weightRow['OrderId']] = (float) $weightRow['total_weight']; + } + $currencyCodes = CurrencyQuery::create()->find()->toKeyValue('Id', 'Code'); $context = [ 'locale' => $locale, + 'weights' => $weights, 'default_signed' => (bool) ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_DEFAULT_SIGNED), 'date_formatter' => new \IntlDateFormatter($locale, \IntlDateFormatter::SHORT, \IntlDateFormatter::SHORT), 'amount_formatter' => new \NumberFormatter($locale, \NumberFormatter::CURRENCY), @@ -109,7 +123,7 @@ public function getRows(string $locale): array } /** - * @param array{locale: string, default_signed: bool, date_formatter: \IntlDateFormatter, amount_formatter: \NumberFormatter} $context + * @param array{locale: string, weights: array, default_signed: bool, date_formatter: \IntlDateFormatter, amount_formatter: \NumberFormatter} $context */ private function buildRow( Order $order, @@ -159,7 +173,7 @@ private function buildRow( if (null === $label) { return array_merge($row, [ - 'weight' => $order->getWeight(), + 'weight' => $context['weights'][$order->getId()] ?? 0.0, 'signed' => $context['default_signed'], 'tracking_number' => null, 'has_label' => false, @@ -168,7 +182,7 @@ private function buildRow( } return array_merge($row, [ - 'weight' => empty($label->getWeight()) ? $order->getWeight() : $label->getWeight(), + 'weight' => empty($label->getWeight()) ? ($context['weights'][$order->getId()] ?? 0.0) : $label->getWeight(), 'signed' => (bool) $label->getSigned(), 'tracking_number' => $label->getTrackingNumber(), 'has_label' => !empty($label->getLabelType()), diff --git a/templates/backOffice/default-twig/colissimo-label/hook/order-edit-js.html.twig b/templates/backOffice/default-twig/colissimo-label/hook/order-edit-js.html.twig index 36893ad..42e274e 100644 --- a/templates/backOffice/default-twig/colissimo-label/hook/order-edit-js.html.twig +++ b/templates/backOffice/default-twig/colissimo-label/hook/order-edit-js.html.twig @@ -107,6 +107,14 @@ document.addEventListener('DOMContentLoaded', function () { bill.insertBefore(tplNode.content.cloneNode(true), bill.firstChild); } + // The module redirects here with ?tab=bill, but the order page only opens the shipments tab from the URL. + if (new URLSearchParams(window.location.search).get('tab') === 'bill') { + var billToggle = document.getElementById('tab-bill-toggle'); + if (billToggle) { + billToggle.click(); + } + } + var modalEl = document.getElementById('modal-colissimo-label'); if (!modalEl) { return; @@ -234,7 +242,7 @@ document.addEventListener('DOMContentLoaded', function () { if (modalLoader) modalLoader.classList.add('d-none'); if (returnField) returnField.value = '0'; if (json.error) { - if (modalErrorAlert) modalErrorAlert.innerHTML = Array.isArray(json.error) ? json.error[0] : json.error; + if (modalErrorAlert) modalErrorAlert.textContent = Array.isArray(json.error) ? json.error[0] : json.error; if (modalError) modalError.classList.remove('d-none'); return; } @@ -248,7 +256,7 @@ document.addEventListener('DOMContentLoaded', function () { if (modalLoader) modalLoader.classList.add('d-none'); if (returnField) returnField.value = '0'; if (modalError) modalError.classList.remove('d-none'); - if (modalErrorAlert) modalErrorAlert.innerHTML = textStatus; + if (modalErrorAlert) modalErrorAlert.textContent = textStatus; }); }); } diff --git a/tests/LabelServiceTest.php b/tests/LabelServiceTest.php index 981e270..0dca217 100644 --- a/tests/LabelServiceTest.php +++ b/tests/LabelServiceTest.php @@ -58,4 +58,34 @@ public function deleteIn(string $number, string $folder): void rmdir($folder); } } + + /** + * A match in a subfolder (bordereau/) must not delete the file of the same name at the root. + */ + public function testDeleteLabelFileOnlyLooksAtTheRootOfTheFolder(): void + { + $folder = sys_get_temp_dir().'/colissimo-label-test-'.uniqid(); + mkdir($folder.'/sub', 0777, true); + + try { + touch($folder.'/sub/6A1.pdf'); + touch($folder.'/6A1.pdf'); + + $service = new class(new EventDispatcher()) extends LabelService { + public function deleteIn(string $number, string $folder): void + { + $this->deleteLabelFile($number, $folder); + } + }; + $service->deleteIn('6A1', $folder); + + $this->assertFileDoesNotExist($folder.'/6A1.pdf'); + $this->assertFileExists($folder.'/sub/6A1.pdf'); + } finally { + @unlink($folder.'/sub/6A1.pdf'); + @unlink($folder.'/6A1.pdf'); + @rmdir($folder.'/sub'); + @rmdir($folder); + } + } } From 646e3781d72138f520b3e7d75ec78aa232bffbf1 Mon Sep 17 00:00:00 2001 From: Thomas Da Silva Date: Wed, 28 Oct 2026 15:08:57 +0100 Subject: [PATCH 3/3] fix: keep the label table of the order page within its column --- .../hook/order-edit-js.html.twig | 51 ++++++++++--------- .../colissimo-label/label-list.html.twig | 38 +++++++------- 2 files changed, 46 insertions(+), 43 deletions(-) diff --git a/templates/backOffice/default-twig/colissimo-label/hook/order-edit-js.html.twig b/templates/backOffice/default-twig/colissimo-label/hook/order-edit-js.html.twig index 42e274e..6e9fc41 100644 --- a/templates/backOffice/default-twig/colissimo-label/hook/order-edit-js.html.twig +++ b/templates/backOffice/default-twig/colissimo-label/hook/order-edit-js.html.twig @@ -74,29 +74,34 @@