Deprecated: Constant E_STRICT is deprecated in /home/pastorz/old-espace-client/vendor/symfony/error-handler/ErrorHandler.php on line 58

Deprecated: Constant E_STRICT is deprecated in /home/pastorz/old-espace-client/vendor/symfony/error-handler/ErrorHandler.php on line 76
Symfony Profiler

src/Service/InvoiceService.php line 144

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\BaseInvoice;
  4. use App\Entity\Batch;
  5. use App\Entity\Booking;
  6. use App\Entity\DeliveryNote;
  7. use App\Entity\Invoice;
  8. use App\Entity\InvoiceCredit;
  9. use App\Entity\InvoiceRowType;
  10. use App\Entity\Payment;
  11. use App\Entity\Shipment;
  12. use App\Entity\SupportRequest;
  13. use App\Entity\User;
  14. use App\Twig\FormatExtension;
  15. use DateTime;
  16. use DateTimeInterface;
  17. use Doctrine\Common\Collections\Collection;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use Exception;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Symfony\Component\HttpFoundation\Response;
  22. use Symfony\Component\Serializer\Exception\ExceptionInterface;
  23. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  24. use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
  25. use Symfony\Component\Serializer\SerializerInterface;
  26. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  27. use Symfony\Contracts\HttpClient\HttpClientInterface;
  28. use Throwable;
  29. use App\Service\Auctionis\InvoiceService as AuctionisInvoiceService;
  30. class InvoiceService
  31. {
  32.     public const REF_GUARDCHARGE 'GARD';
  33.     public const REF_EXPEDITION 'EXP';
  34.     public const REF_INTERENCHERES 'IE';
  35.     public const REMOTE_INVOICING = [
  36.         BrandService::CODE_NPCJ => BrandService::CODE_ADN
  37.     ];
  38.     private float $vat;
  39.     public function __construct(
  40.         private GuardChargeService $guardChargeService,
  41.         private BrandService $brandService,
  42.         private EntityManagerInterface $em,
  43.         private SerializerInterface $serializer,
  44.         private AuctionisInvoiceService $auctionisInvoiceService,
  45.     )
  46.     {
  47.         $this->vat 100 * (StripeService::VAT 1);
  48.     }
  49.     public function getNoteItems(DeliveryNote $deliveryNote): array
  50.     {
  51.         $items = array();
  52.         /** @var Batch $batch */
  53.         foreach ($deliveryNote->getBatches() as $batch) {
  54.             $items[] = array(
  55.                 'reference' => $batch->getBarcode(),
  56.                 'designation' => $batch->getDesignation(),
  57.                 'quantity' => 1,
  58.                 'unit_price_vat_exclude' => round($batch->getTotalAmount() / StripeService::VAT2),
  59.                 'vat_rate' => $this->vat,
  60.                 'total_price_vat_exclude' => round($deliveryNote->getTotalAmount() / StripeService::VAT2)
  61.             );
  62.         }
  63.         if ($deliveryNote->getTierCharge() != 0) {
  64.             $items[] = array(
  65.                 'reference' => self::REF_INTERENCHERES,
  66.                 'designation' => 'Frais Interencheres',
  67.                 'quantity' => 1,
  68.                 'unit_price_vat_exclude' => round($deliveryNote->computeTierCharge() / StripeService::VAT2),
  69.                 'vat_rate' => $this->vat,
  70.                 'total_price_vat_exclude' => round($deliveryNote->computeTierCharge() / StripeService::VAT2)
  71.             );
  72.         }
  73.         return $items;
  74.     }
  75.     public function getAdminShippingItems(Shipment $shipment): array
  76.     {
  77.         $items = array(
  78.             array(
  79.                 'reference' => $shipment->getCarrier()->getInvoiceRowType()->getCode(),
  80.                 'designation' => 'Expédition - ' $shipment->getCarrier()->getName(),
  81.                 'quantity' => 1,
  82.                 'unit_price_vat_exclude' => array(
  83.                     'numericValue' => round($shipment->getTotalAmountShipping() / StripeService::VAT2),
  84.                     'value' => FormatExtension::formatPrice(round($shipment->getTotalAmountShipping() / StripeService::VAT2), false),
  85.                 ),
  86.                 'vat_rate' => array(
  87.                     'numericValue' => $this->vat,
  88.                     'value' => FormatExtension::formatPercentage($this->vat)
  89.                 ),
  90.                 'total_price_vat_exclude' => array(
  91.                     'numericValue' => round($shipment->getTotalAmountShipping() / StripeService::VAT2),
  92.                     'value' => FormatExtension::formatPrice(round($shipment->getTotalAmountShipping() / StripeService::VAT2), false)
  93.                 ),
  94.                 'type' => array('type' => 'hidden''value' => $shipment->getCarrier()->getInvoiceRowType()->getId())
  95.             ),
  96.         );
  97.         if ($shipment->getAmountGuardCharge() != 0) {
  98.             $amountHT $shipment->getAmountGuardCharge() / 1.2;
  99.             $ref $this->em->getRepository(InvoiceRowType::class)->findOneByCode(self::REF_GUARDCHARGE);
  100.             $guardchargeItems = array(
  101.                 array(
  102.                     'reference' => $ref->getName(),
  103.                     'designation' => 'Frais de gardiennage',
  104.                     'quantity' => 1,
  105.                     'unit_price_vat_exclude' => array(
  106.                         'numericValue' => $amountHT,
  107.                         'value' => FormatExtension::formatPrice($amountHTfalse)
  108.                     ),
  109.                     'vat_rate' => array(
  110.                         'numericValue' => $this->vat,
  111.                         'value' => FormatExtension::formatPercentage($this->vat)
  112.                     ),
  113.                     'total_price_vat_exclude' => array(
  114.                         'numericValue' => $amountHT,
  115.                         'value' => FormatExtension::formatPrice($amountHTfalse)
  116.                     ),
  117.                     'type' => array('type' => 'hidden''value' => $ref->getId())
  118.                 )
  119.             );
  120.             $items array_merge($items$guardchargeItems);
  121.         }
  122.         return $items;
  123.     }
  124.     private function getInvoiceData(BaseInvoice $invoice): array
  125.     {
  126.         return $this->getDefaultInvoiceData($invoice->getUser(), $invoice->getObject());
  127.     }
  128.     private function getDefaultInvoiceData(User $userstring $object null): array
  129.     {
  130.         return array(
  131.             'customer' => array(
  132.                 'name' => $user->getFullname(),
  133.                 'address' => $user->getFallbackAddress()->getAddressLines(),
  134.                 'zipcodecountry' => $user->getFallbackAddress()->getCityZipcodeCountry(),
  135.                 'company' => $user->getCompany(),
  136.                 'company_number' => $user->getCompanyNumber(),
  137.                 'company_vat_number' => $user->getCompanyVatNumber()
  138.             ),
  139.             'company' => array(
  140.                 'name' => $this->brandService->getBrand()->getName(),
  141.                 'address' => $this->brandService->getBrand()->getAddress()->getAddressLines(),
  142.                 'zipcodecountry' => $this->brandService->getBrand()->getAddress()->getCityZipcodeCountry(),
  143.                 'phone' => $this->brandService->getBrand()->getPhone(),
  144.                 'contact' => $this->brandService->getBrand()->getContact()
  145.             ),
  146.             'metadata' => array(
  147.                 'document_width' => '755px'
  148.             ),
  149.             'object' => $object ?? '',
  150.             'columns' => array(
  151.                 array('name' => 'reference''label' => 'RÉFÉRENCE''type' => 'text''classList' => 'w-15'),
  152.                 array('name' => 'designation''label' => 'DÉSIGNATION''type' => 'text''classList' => 'w-35'),
  153.                 array('name' => 'quantity''label' => 'QUANTITÉ''type' => 'text''classList' => 'w-15 tar'),
  154.                 array('name' => 'unit_price_vat_exclude''label' => 'PU HT''type' => 'price''classList' => 'w-10 tar'),
  155.                 array('name' => 'vat_rate''label' => 'TVA''type' => 'text''classList' => 'w-10 tar'),
  156.                 array('name' => 'total_price_vat_exclude''label' => 'TOTAL HT''type' => 'price''classList' => 'w-15 tar'),
  157.             ),
  158.             'rows' => array(),
  159.             'vat_data' => array(
  160.                 'columns' => array(
  161.                     array('label' => 'BASE HT''type' => 'price''classList' => 'w-15'),
  162.                     array('label' => 'TAUX''type' => 'text''classList' => 'w-15'),
  163.                     array('label' => 'TVA''type' => 'price''classList' => 'w-15')
  164.                 ),
  165.                 'rows' => array()
  166.             ),
  167.             'total_data' => array()
  168.         );
  169.     }
  170.     public function getShippingItems(Shipment $shipment): array
  171.     {
  172.         $priceExcludedTaxes $shipment->hasDiscount() ? $shipment->getPriceExcludedTaxes() : round($shipment->getTotalAmountShipping() / StripeService::VAT2);
  173.         $items = array(
  174.             array(
  175.                 'reference' => $shipment->getCarrier()->getInvoiceRowType()->getCode(),
  176.                 'designation' => 'Expédition - ' $shipment->getCarrier()->getName(),
  177.                 'quantity' => 1,
  178.                 'unit_price_vat_exclude' => array(
  179.                     'numericValue' => $priceExcludedTaxes,
  180.                     'value' => FormatExtension::formatPrice($priceExcludedTaxesfalse),
  181.                 ),
  182.                 'vat_rate' => array(
  183.                     'numericValue' => $this->vat,
  184.                     'value' => FormatExtension::formatPercentage($this->vat)
  185.                 ),
  186.                 'total_price_vat_exclude' => array(
  187.                     'numericValue' => $priceExcludedTaxes,
  188.                     'value' => FormatExtension::formatPrice($priceExcludedTaxesfalse)
  189.                 ),
  190.                 'type' => array('type' => 'hidden''value' => $shipment->getCarrier()->getInvoiceRowType()->getId())
  191.             )
  192.         );
  193.         if ($shipment->hasDiscount()) {
  194.             $items[] = [
  195.                 'reference' => $shipment->getDiscountCode(),
  196.                 'designation' => 'Remise',
  197.                 'quantity' => 1,
  198.                 'unit_price_vat_exclude' => [
  199.                     'numericValue' => $shipment->getDiscountAmount() * -1,
  200.                     'value' => FormatExtension::formatPrice($shipment->getDiscountAmount() * -1false),
  201.                 ],
  202.                 'vat_rate' => [
  203.                     'numericValue' => $this->vat,
  204.                     'value' => FormatExtension::formatPercentage($this->vat)
  205.                 ],
  206.                 'total_price_vat_exclude' => [
  207.                     'numericValue' => $shipment->getDiscountAmount() * -1,
  208.                     'value' => FormatExtension::formatPrice($shipment->getDiscountAmount() * -1false)
  209.                 ],
  210.                 'type' => ['type' => 'hidden''value' => BaseInvoice::ROW_TYPE_DISCOUNT]
  211.             ];
  212.         }
  213.         if ($shipment->getAmountGuardCharge() != 0) {
  214.             $items array_merge($items$this->getNoteGuardchargeItems($shipment->getDeliveryNote(), end$shipment->getPayment()->getDate()));
  215.         }
  216.         return $items;
  217.     }
  218.     /**
  219.      * @param DeliveryNote $note
  220.      * @param DateTimeInterface|null $start
  221.      * @param DateTimeInterface|null $end
  222.      * @return array
  223.      */
  224.     public function getNoteGuardchargeItems(DeliveryNote $note, ?DateTimeInterface $start null, ?DateTimeInterface $end null): array
  225.     {
  226.         $items = array();
  227.         /** @var Batch $batch */
  228.         foreach ($note->getBatches() as $batch) {
  229.             $guardChargeReference $this->em->getRepository(InvoiceRowType::class)->findOneBy(array('flag' => $batch->isOnlyPalletShipment() ? InvoiceRowType::FLAG_GUARD_P InvoiceRowType::FLAG_GUARD_S));
  230.             $items[] = array(
  231.                 'reference' => $guardChargeReference->getCode(),
  232.                 'designation' => 'Lot n°' $batch->getSaleOrder() . ' - ' $guardChargeReference->getName(),
  233.                 'quantity' => $this->guardChargeService->computeBatchDaysDiff($batch$start$end),
  234.                 'unit_price_vat_exclude' => array(
  235.                     'numericValue' => $this->guardChargeService->getBatchPriceUnitExludingVAT($batch),
  236.                     'value' => FormatExtension::formatPrice($this->guardChargeService->getBatchPriceUnitExludingVAT($batch), false)
  237.                 ),
  238.                 'vat_rate' => array(
  239.                     'numericValue' => $this->vat,
  240.                     'value' => FormatExtension::formatPercentage($this->vat)
  241.                 ),
  242.                 'total_price_vat_exclude' => array(
  243.                     'numericValue' => $this->guardChargeService->computeBatchDaysDiff($batch$start$end) * $this->guardChargeService->getBatchPriceUnitExludingVAT($batch),
  244.                     'value' => FormatExtension::formatPrice($this->guardChargeService->computeBatchDaysDiff($batch$start$end) * $this->guardChargeService->getBatchPriceUnitExludingVAT($batch), false)
  245.                 ),
  246.                 'type' => array('type' => 'hidden''value' => $guardChargeReference->getId())
  247.             );
  248.         }
  249.         return $items;
  250.     }
  251.     /**
  252.      * @param Payment $payment
  253.      * @return array
  254.      * @throws Exception
  255.      */
  256.     public function getBookingItems(Payment $payment): array
  257.     {
  258.         return $this->getNoteGuardchargeItems($payment->getBooking()->getDeliveryNote(), start$payment->getBooking()->getPreviousBookingDate(), end$payment->getBooking()->getSlot());
  259.     }
  260.     public function createCustomInvoice(BaseInvoice $invoicebool $isUpdate false): BaseInvoice
  261.     {
  262.         $invoice->setDate(new DateTime());
  263.         $invoice->setAmount($invoice->computeAmount());
  264.         if (!$isUpdate) {
  265.             $invoice->setNumber('FB');
  266.         }
  267.         $taxesTable = array();
  268.         foreach ($invoice->getRows() as $row) {
  269.             if (!isset($taxesTable[$row['vat_rate']])) {
  270.                 $taxesTable[$row['vat_rate']] = array(
  271.                     'total_price_vat_exclude' => 0,
  272.                     'vat_rate' => $row['vat_rate'],
  273.                     'total_vat' => 0
  274.                 );
  275.             }
  276.             $taxesTable[$row['vat_rate']]['total_price_vat_exclude'] += ($row['quantity'] * $row['unit_price_vat_exclude']);
  277.             $taxesTable[$row['vat_rate']]['total_vat'] = round($taxesTable[$row['vat_rate']]['total_price_vat_exclude'] * $row['vat_rate'] / 1002);
  278.         }
  279.         usort($taxesTable, fn($a$b) => $a['vat_rate'] < $b['vat_rate']);
  280.         $data $this->getInvoiceData($invoice);
  281.         $data['rows'] = $invoice->getRows()->map(function (array $row) {
  282.             return array(
  283.                 'reference' => $row['reference']->getCode(),
  284.                 'designation' => $row['designation'],
  285.                 'quantity' => $row['quantity'],
  286.                 'unit_price_vat_exclude' => array('numericValue' => $row['unit_price_vat_exclude'], 'value' => FormatExtension::formatPrice($row['unit_price_vat_exclude'], false)),
  287.                 'vat_rate' => array('numericValue' => $row['vat_rate'], 'value' => FormatExtension::formatPercentage($row['vat_rate'])),
  288.                 'total_price_vat_exclude' => array('numericValue' => $row['unit_price_vat_exclude'] * $row['quantity'], 'value' => FormatExtension::formatPrice($row['unit_price_vat_exclude'] * $row['quantity'], false)),
  289.                 'type' => array('type' => 'hidden''value' => $row['reference']->getId()));
  290.         })->toArray();
  291.         $data['vat_data']['rows'] = array_map(fn($taxesRow) => array(
  292.             FormatExtension::formatPrice($taxesRow['total_price_vat_exclude'], false),
  293.             FormatExtension::formatPercentage($taxesRow['vat_rate']),
  294.             FormatExtension::formatPrice($taxesRow['total_vat'], false),
  295.         ), $taxesTable);
  296.         $data['total_data'] = array(
  297.             array('label' => 'TOTAL HT''value' => FormatExtension::formatPrice(round(array_sum(array_map(fn($taxesRow) => $taxesRow['total_price_vat_exclude'], $taxesTable)), 2), false)),
  298.             array('label' => 'TOTAL TVA''value' => FormatExtension::formatPrice(round(array_sum(array_map(fn($taxesRow) => $taxesRow['total_vat'], $taxesTable)), 2), false)),
  299.             array('label' => 'TOTAL TTC''value' => FormatExtension::formatPrice($invoice->getAmount(), false)),
  300.         );
  301.         $invoice->setData($data);
  302.         $this->em->persist($invoice);
  303.         $this->em->flush();
  304.         $this->em->refresh($invoice);
  305.         return $invoice;
  306.     }
  307.     public function createInvoiceCredit(InvoiceCredit $credit): InvoiceCredit
  308.     {
  309.         $credit->setDate(new DateTime());
  310.         $credit->setNumber('A');
  311.         $data $this->getInvoiceData($credit->getInvoice());
  312.         unset($data['columns'][2]);
  313.         unset($data['columns'][3]);
  314.         $data['columns'] = array_values($data['columns']);
  315.         $data['columns'][1]['classList'] = 'w-50';
  316.         $data['columns'][2]['classList'] = 'w-15';
  317.         $data['columns'][3]['classList'] = 'w-20';
  318.         $taxesTable = array();
  319.         $data['customer'] = $credit->getInvoice()->getData()['customer'];
  320.         $data['company'] = $credit->getInvoice()->getData()['company'];
  321.         $data['rows'] = array();
  322.         foreach ($credit->getInvoice()->getData()['rows'] as $key => $invoiceRow) {
  323.             $creditRowData array_filter($credit->getRows()[$key]);
  324.             if ($creditRowData) {
  325.                 $creditRow $invoiceRow;
  326.                 $creditRow['total_price_vat_exclude'] = array(
  327.                     'numericValue' => $credit->getRows()[$key]['amount_without_taxes'],
  328.                     'value' => FormatExtension::formatPrice((float)($credit->getRows()[$key]['amount_without_taxes']), false)
  329.                 );
  330.                 unset($creditRow['quantity']);
  331.                 unset($creditRow['unit_price_vat_exclude']);
  332.                 $data['rows']["invoice_row_$key"] = $creditRow;
  333.                 if (!isset($taxesTable[$invoiceRow['vat_rate']['numericValue']])) {
  334.                     $taxesTable[$invoiceRow['vat_rate']['numericValue']] = array(
  335.                         'total_price_vat_exclude' => 0,
  336.                         'vat_rate' => $invoiceRow['vat_rate']['numericValue'],
  337.                         'total_vat' => 0
  338.                     );
  339.                 }
  340.                 $taxesTable[$invoiceRow['vat_rate']['numericValue']]['total_price_vat_exclude'] += (float)($credit->getRows()[$key]['amount_without_taxes']);
  341.                 $taxesTable[$invoiceRow['vat_rate']['numericValue']]['total_vat'] = round($taxesTable[$invoiceRow['vat_rate']['numericValue']]['total_price_vat_exclude'] * $invoiceRow['vat_rate']['numericValue'] / 1002);
  342.             }
  343.         }
  344.         usort($taxesTable, fn($a$b) => $a['vat_rate'] < $b['vat_rate']);
  345.         $data['vat_data']['rows'] = array_map(fn($taxesRow) => array(
  346.             FormatExtension::formatPrice($taxesRow['total_price_vat_exclude'], false),
  347.             FormatExtension::formatPercentage($taxesRow['vat_rate']),
  348.             FormatExtension::formatPrice($taxesRow['total_vat'], false),
  349.         ), $taxesTable);
  350.         $data['total_data'] = array(
  351.             array('label' => 'TOTAL HT''value' => FormatExtension::formatPrice(round(array_sum(array_map(fn($taxesRow) => $taxesRow['total_price_vat_exclude'], $taxesTable)), 2), false)),
  352.             array('label' => 'TOTAL TVA''value' => FormatExtension::formatPrice(round(array_sum(array_map(fn($taxesRow) => $taxesRow['total_vat'], $taxesTable)), 2), false)),
  353.             array('label' => 'TOTAL TTC''value' => FormatExtension::formatPrice($credit->getAmount(), false)),
  354.         );
  355.         $credit->setData($data);
  356.         return $credit;
  357.     }
  358.     public function createInvoiceCreditFromScratch(InvoiceCredit $creditUser $userstring $object): InvoiceCredit
  359.     {
  360.         $credit->setDate(new DateTime());
  361.         $credit->setNumber('A');
  362.         $data $this->getDefaultInvoiceData($user$object);
  363.         $taxesTable = [];
  364.         $data['rows'] = [];
  365.         foreach ($credit->getRows() as $key => $creditRow) {
  366.             $creditRow['reference'] = $creditRow['reference']->getCode();
  367.             $total_price_vat_exclude $creditRow['quantity'] * $creditRow['unit_price_vat_exclude'];
  368.             $creditRow['total_price_vat_exclude'] = [
  369.                 'numericValue' => $total_price_vat_exclude,
  370.                 'value' => FormatExtension::formatPrice($total_price_vat_excludefalse)
  371.             ];
  372.             $creditRow['unit_price_vat_exclude'] = [
  373.                 'numericValue' => $creditRow['unit_price_vat_exclude'],
  374.                 'value' => FormatExtension::formatPrice($creditRow['unit_price_vat_exclude'], false)
  375.             ];
  376.             $creditRow['vat_rate'] = [
  377.                 'numericValue' => $creditRow['vat_rate'],
  378.                 'value' => FormatExtension::formatPercentage($creditRow['vat_rate'])
  379.             ];
  380.             $creditRow['type'] = [
  381.                 'type' => 'hidden',
  382.                 'value' => $credit->getRows()[$key]['reference']->getId()
  383.             ];
  384.             $data['rows']["invoice_row_$key"] = $creditRow;
  385.             if (!isset($taxesTable[$creditRow['vat_rate']['numericValue']])) {
  386.                 $taxesTable[$creditRow['vat_rate']['numericValue']] = [
  387.                     'total_price_vat_exclude' => 0,
  388.                     'vat_rate' => $creditRow['vat_rate']['numericValue'],
  389.                     'total_vat' => 0
  390.                 ];
  391.             }
  392.             $taxesTable[$creditRow['vat_rate']['numericValue']]['total_price_vat_exclude'] += $creditRow['total_price_vat_exclude']['numericValue'];
  393.             $taxesTable[$creditRow['vat_rate']['numericValue']]['total_vat'] = round($taxesTable[$creditRow['vat_rate']['numericValue']]['total_price_vat_exclude'] * $creditRow['vat_rate']['numericValue'] / 1002);
  394.         }
  395.         usort($taxesTable, fn($a$b) => $a['vat_rate'] < $b['vat_rate']);
  396.         $data['vat_data']['rows'] = array_map(fn($taxesRow) => [
  397.             FormatExtension::formatPrice($taxesRow['total_price_vat_exclude'], false),
  398.             FormatExtension::formatPercentage($taxesRow['vat_rate']),
  399.             FormatExtension::formatPrice($taxesRow['total_vat'], false),
  400.         ], $taxesTable);
  401.         $data['total_data'] = [
  402.             ['label' => 'TOTAL HT''value' => FormatExtension::formatPrice(round(array_sum(array_map(fn($taxesRow) => $taxesRow['total_price_vat_exclude'], $taxesTable)), 2), false)],
  403.             ['label' => 'TOTAL TVA''value' => FormatExtension::formatPrice(round(array_sum(array_map(fn($taxesRow) => $taxesRow['total_vat'], $taxesTable)), 2), false)],
  404.             ['label' => 'TOTAL TTC''value' => FormatExtension::formatPrice($credit->getAmount(), false)],
  405.         ];
  406.         $credit->setData($data);
  407.         return $credit;
  408.     }
  409.     public function createSupportRequestCredit(SupportRequest $supportRequest): InvoiceCredit
  410.     {
  411.         $invoiceCredit = new InvoiceCredit();
  412.         $invoiceCredit->setAmount($supportRequest->getRefundAmount());
  413.         $invoiceCredit->setDate(new DateTime());
  414.         $invoiceCredit->setNumber('A');
  415.         $data $this->getDefaultInvoiceData($supportRequest->getUser());
  416.         unset($data['columns'][2]);
  417.         unset($data['columns'][3]);
  418.         $data['columns'] = array_values($data['columns']);
  419.         $data['columns'][1]['classList'] = 'w-50';
  420.         $data['columns'][2]['classList'] = 'w-15';
  421.         $data['columns'][3]['classList'] = 'w-20';
  422.         $taxesTable = array();
  423.         $rowType $this->em->getRepository(InvoiceRowType::class)->findOneByflag(InvoiceRowType::FLAG_REFOUND_SAV);
  424.         $data['rows'] = array(
  425.             array(
  426.                 'reference' => $rowType->getCode(),
  427.                 'designation' => $rowType->getName(),
  428.                 'quantity' => 1,
  429.                 'unit_price_vat_exclude' => array('numericValue' => round($supportRequest->getRefundAmount() / 1.22), 'value' => FormatExtension::formatPrice(round($supportRequest->getRefundAmount() / 1.22), false)),
  430.                 'vat_rate' => array('numericValue' => 20'value' => FormatExtension::formatPercentage(20)),
  431.                 'total_price_vat_exclude' => array('numericValue' => round($supportRequest->getRefundAmount() / 1.22), 'value' => FormatExtension::formatPrice(round($supportRequest->getRefundAmount() / 1.22), false)),
  432.                 'type' => array('type' => 'hidden''value' => $rowType->getId())
  433.             )
  434.         );
  435.         $data['vat_data']['rows'] = array_map(fn($taxesRow) => array(
  436.             FormatExtension::formatPrice(round($supportRequest->getRefundAmount() / 1.22), false),
  437.             FormatExtension::formatPercentage(20),
  438.             FormatExtension::formatPrice($supportRequest->getRefundAmount() / 1.2 0.2false),
  439.         ), $taxesTable);
  440.         $data['total_data'] = array(
  441.             array('label' => 'TOTAL HT''value' => FormatExtension::formatPrice(round($supportRequest->getRefundAmount() / 1.22), false)),
  442.             array('label' => 'TOTAL TVA''value' => FormatExtension::formatPrice(round(($supportRequest->getRefundAmount() / 1.2) * 0.22), false)),
  443.             array('label' => 'TOTAL TTC''value' => FormatExtension::formatPrice($supportRequest->getRefundAmount(), false)),
  444.         );
  445.         $invoiceCredit->setData($data);
  446.         return $invoiceCredit;
  447.     }
  448.     public function mapInvoiceRows(BaseInvoice $invoice): array
  449.     {
  450.         $array $invoice->getData()['rows'];
  451.         $array array_map(function (mixed $row) {
  452.             $row['reference'] = $this->em->getRepository(InvoiceRowType::class)->findOneByCode($row['reference']);
  453.             $row['unit_price_vat_exclude'] = $row['unit_price_vat_exclude']['numericValue'];
  454.             $row['vat_rate'] = $row['total_price_vat_exclude']['numericValue'];
  455.             $row['total_price_vat_exclude'] = $row['total_price_vat_exclude']['numericValue'];
  456.             return $row;
  457.         }, $array);
  458.         return $array;
  459.     }
  460.     /**
  461.      * @param DeliveryNote $deliveryNote
  462.      * @param string $type
  463.      * @param string $brandOrigin
  464.      * @return JsonResponse
  465.      * @throws TransportExceptionInterface
  466.      */
  467.     public function postInvoiceToAPI(DeliveryNote $deliveryNotestring $typestring $brandOrigin): JsonResponse
  468.     {
  469.         $shipment $deliveryNote->getShipment();
  470.         $matchTypes = [
  471.             BaseInvoice::TYPE_SHIPPING => 'shipment',
  472.             BaseInvoice::TYPE_GUARD => 'guard',
  473.         ];
  474.         $matchCarrierTypes = [
  475.             'EXP_COLI' => 'EXP_COLISSIMO',
  476.             'EXP_BOLLO' => 'EXP_BOLLORE',
  477.             'EXP_CHRONO' => 'EXP_CHRONOPOST',
  478.             'EXP_GEO' => 'EXP_GEODIS',
  479.             'EXP_COLI_PR' => 'EXP_COLISSIMO_PR',
  480.         ];
  481.         $amount $shipment->getTotalAmountShipping(true) + $shipment->getAmountGuardCharge();
  482.         $invoiceData = [
  483.             "document_type" => "invoice",
  484.             "auction_house" => "adn",
  485.             "object" => "Facture NPCJ - Bordereaux " $deliveryNote->getCode(),
  486.             "number" => "FF",
  487.             "type" => $matchTypes[$type],
  488.             "date" => (new DateTime())->format('Y-m-d H:i:s'),
  489.             "amount_vat_exclude" => ($amount 100) / 1.2,
  490.             "amount" => $amount 100,
  491.             "company_name" => null,
  492.             "civility" => User::CIVILITIES[$deliveryNote->getUser()->getCivility()],
  493.             "firstname" => $deliveryNote->getUser()->getFirstname(),
  494.             "lastname" => $deliveryNote->getUser()->getLastname(),
  495.             "address" => [
  496.                 "region" => null,
  497.                 "country" => null,
  498.                 "zipcode" => $shipment->getBillingAddress()['zipcode'],
  499.                 "city" => $shipment->getBillingAddress()['city'],
  500.                 "street" => $shipment->getBillingAddress()['address'],
  501.                 "line1" => $shipment->getBillingAddress()['address_line1'],
  502.                 "line2" => null
  503.             ],
  504.             "rows" => [
  505.                 [
  506.                     "type" => $matchCarrierTypes[$shipment->getCarrier()->getInvoiceRowType()->getCode()],
  507.                     "designation" => 'Expédition ' $shipment->getCarrier()->getName(),
  508.                     "quantity" => 1,
  509.                     "unit_price_vat_exclude" => ($shipment->hasDiscount() ? $shipment->getPriceExcludedTaxes() : round($shipment->getTotalAmountShipping() / StripeService::VAT2)) * 100,
  510.                     "vat_rate" => 2000,
  511.                     "reduced_unit_price" => null
  512.                 ]
  513.             ]
  514.         ];
  515.         if ($shipment->hasDiscount()) {
  516.             $invoiceData['rows'][] = [
  517.                 "type" => "DISCOUNT",
  518.                 'designation' => 'Remise (code ' $shipment->getDiscountCode() . ')',
  519.                 "quantity" => 1,
  520.                 "unit_price_vat_exclude" => ($shipment->getDiscountAmount() * -1) * 100,
  521.                 "vat_rate" => 2000,
  522.                 "reduced_unit_price" => null
  523.             ];
  524.         }
  525.         if ($shipment->getAmountGuardCharge() != 0) {
  526.             foreach ($deliveryNote->getBatches() as $batch) {
  527.                 $invoiceData['rows'][] = [
  528.                     "type" => "GUARD_" . ($batch->isOnlyPalletShipment() ? 'P''S'),
  529.                     'designation' => 'Lot n°' $batch->getSaleOrder() . ' - Gardiennage',
  530.                     "quantity" => $this->guardChargeService->computeBatchDaysDiff($batchnull$shipment->getPayment()->getDate()),
  531.                     "unit_price_vat_exclude" => $this->guardChargeService->getBatchPriceUnitExludingVAT($batch) * 100,
  532.                     "vat_rate" => 2000,
  533.                     "reduced_unit_price" => null
  534.                 ];
  535.             }
  536.         }
  537.         $this->auctionisInvoiceService->post($invoiceData);
  538.         return new JsonResponse(nullResponse::HTTP_OK);
  539.     }
  540.     /**
  541.      * @param array $deliveryNoteData
  542.      * @param string $type
  543.      * @return Invoice
  544.      * @throws Exception
  545.      */
  546.     public function createInvoiceFromApi(array $deliveryNoteDatastring $typestring $brandOrigin): Invoice
  547.     {
  548.         try {
  549.             $deliveryNote $this->denormalizeDeliveryNote($deliveryNoteData);
  550.             if ($type === BaseInvoice::TYPE_GUARD) {
  551.                 $invoice $this->createGuardchargeInvoiceRemote($deliveryNote$brandOrigindate$deliveryNote->getBooking()->getSlot(), dateStart$deliveryNote->getBooking()->getPreviousBookingDate());
  552.                 $payments $deliveryNote->getBooking()->getPayments()->toArray();
  553.             } else if ($type === BaseInvoice::TYPE_SHIPPING) {
  554.                 $invoice $this->createShippingInvoiceRemote($deliveryNote->getShipment(), $brandOrigin);
  555.                 $payments = [$deliveryNote->getShipment()->getPayment()];
  556.             } else throw new Exception();
  557.             foreach ($payments as $payment) {
  558.                 if (!$payment) continue;
  559.                 $payment->setInvoice($invoice);
  560.                 $payment->setBooking(null);
  561.                 $payment->setDeliveryNote(null);
  562.                 $payment->setShipment(null);
  563.                 $this->em->persist($payment);
  564.             }
  565.             $invoice->setDeliveryNote(null);
  566.             $invoice->setUser(null);
  567.             $this->em->persist($invoice);
  568.             $this->em->flush();
  569.             $this->em->refresh($invoice);
  570.             return $invoice;
  571.         } catch (Throwable $e) {
  572.             throw new Exception("Error while creating invoice : " $e->getMessage());
  573.         }
  574.     }
  575.     /**
  576.      * @param array $data
  577.      * @return DeliveryNote
  578.      * @throws ExceptionInterface
  579.      */
  580.     public function denormalizeDeliveryNote(array $data): DeliveryNote
  581.     {
  582.         $deliveryNote $this->serializer->denormalize($dataDeliveryNote::class, context: [
  583.             AbstractObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true,
  584.             AbstractNormalizer::CALLBACKS => [
  585.                 'booking' => fn($object) => $object ?: new Booking()
  586.             ]
  587.         ]);
  588.         $deliveryNote->getShipment()?->setDeliveryNote($deliveryNote);
  589.         $deliveryNote->getBooking()?->setDeliveryNote($deliveryNote);
  590.         array_map(fn(Batch $b) => $b->setDeliveryNote($deliveryNote), $deliveryNote->getBatches()->toArray());
  591.         return $deliveryNote;
  592.     }
  593.     public function createGuardchargeInvoiceRemote(DeliveryNote $notestring $brandOrigin, ?Collection $batches null, ?DateTimeInterface $date null, ?DateTimeInterface $dateStart null): Invoice
  594.     {
  595.         $invoice $this->createGuardchargeInvoice($note$batches$date$dateStartpersistfalse);
  596.         $data $invoice->getData();
  597.         $data['object'] = strtoupper($brandOrigin) . ' - ' $invoice->getData()['object'];
  598.         $invoice->setData($data);
  599.         $invoice->setObject(strtoupper($brandOrigin) . ' - ' $invoice->getObject());
  600.         return $invoice;
  601.     }
  602.     public function createGuardchargeInvoice(DeliveryNote $note, ?Collection $batches null, ?DateTimeInterface $date null, ?DateTimeInterface $dateStart null, ?bool $persist true): Invoice
  603.     {
  604.         $invoice = new Invoice();
  605.         $invoice->setUser($note->getUser());
  606.         $invoice->setDeliveryNote($note);
  607.         $invoice->setDate(new DateTime());
  608.         $invoice->setAmount($this->guardChargeService->computeGuardcharge($notedate$datebatches$batchesincludePaymentsfalse));
  609.         $invoice->setType(BaseInvoice::TYPE_GUARD);
  610.         $invoice->setNumber('F');
  611.         $invoice->setObject($note->getCode() . ' - ' $note->getSaleDate()->format('d/m/Y'));
  612.         $data $this->getInvoiceData($invoice);
  613.         $data['rows'] = array_map(function (Batch $batch) use ($date$dateStart$note) {
  614.             $guardChargeReference $this->em->getRepository(InvoiceRowType::class)->findOneBy(array('flag' => $batch->isOnlyPalletShipment() ? InvoiceRowType::FLAG_GUARD_P InvoiceRowType::FLAG_GUARD_S));
  615.             return array(
  616.                 'reference' => $guardChargeReference->getCode(),
  617.                 'designation' => 'Lot n°' $batch->getSaleOrder() . ' - ' $guardChargeReference->getName(),
  618.                 'quantity' => $this->guardChargeService->computeBatchDaysDiff($batch$dateStart$datedeliveryNote$note),
  619.                 'unit_price_vat_exclude' => array(
  620.                     'numericValue' => $this->guardChargeService->getBatchPriceUnitExludingVAT($batch),
  621.                     'value' => FormatExtension::formatPrice($this->guardChargeService->getBatchPriceUnitExludingVAT($batch), false)
  622.                 ),
  623.                 'vat_rate' => array(
  624.                     'numericValue' => ConstantsService::GUARDCHARGE_VAT 100,
  625.                     'value' => FormatExtension::formatPercentage(ConstantsService::GUARDCHARGE_VAT)
  626.                 ),
  627.                 'total_price_vat_exclude' => array(
  628.                     'numericValue' => $this->guardChargeService->computeBatchDaysDiff($batch$dateStart$datedeliveryNote$note) * $this->guardChargeService->getBatchPriceUnitExludingVAT($batch),
  629.                     'value' => FormatExtension::formatPrice($this->guardChargeService->computeBatchDaysDiff($batch$dateStart$datedeliveryNote$note) * $this->guardChargeService->getBatchPriceUnitExludingVAT($batch), false)
  630.                 ),
  631.                 'type' => array('type' => 'hidden''value' => $guardChargeReference->getId())
  632.             );
  633.         }, ($batches ?? $note->getBatches())->toArray());
  634.         $totalExcludedTaxes $this->guardChargeService->computeGuardcharge(deliveryNote$notedate$dateincludeVATfalsebatches$batchesincludePaymentsfalse);
  635.         $totalIncludedTaxes $this->guardChargeService->computeGuardcharge(deliveryNote$notedate$dateincludeVATtruebatches$batchesincludePaymentsfalse);
  636.         $totalTaxes $this->guardChargeService->computeGuardcharge(deliveryNote$notedate$datevatOnlytruebatches$batchesincludePaymentsfalse);
  637.         $data['vat_data']['rows'] = array(
  638.             array(
  639.                 FormatExtension::formatPrice($totalExcludedTaxesfalse),
  640.                 FormatExtension::formatPercentage(ConstantsService::GUARDCHARGE_VAT),
  641.                 FormatExtension::formatPrice($totalTaxesfalse)
  642.             )
  643.         );
  644.         $data['total_data'] = array(
  645.             array('label' => 'TOTAL HT''value' => FormatExtension::formatPrice($totalExcludedTaxesfalse)),
  646.             array('label' => 'TOTAL TVA''value' => FormatExtension::formatPrice($totalTaxesfalse)),
  647.             array('label' => 'TOTAL TTC''value' => FormatExtension::formatPrice($totalIncludedTaxesfalse)),
  648.         );
  649.         $invoice->setData($data);
  650.         if ($persist) {
  651.             $this->em->persist($invoice);
  652.             $this->em->flush();
  653.             $this->em->refresh($invoice);
  654.         }
  655.         return $invoice;
  656.     }
  657.     /**
  658.      * @param Shipment $shipment
  659.      * @return Invoice
  660.      */
  661.     public function createShippingInvoiceRemote(Shipment $shipmentstring $brandOrigin): Invoice
  662.     {
  663.         $invoice $this->createShippingInvoice($shipmentpersistfalse);
  664.         $data $invoice->getData();
  665.         $data['object'] = strtoupper($brandOrigin) . ' - ' $invoice->getData()['object'];
  666.         $invoice->setData($data);
  667.         $invoice->setObject(strtoupper($brandOrigin) . ' - ' $invoice->getObject());
  668.         return $invoice;
  669.     }
  670.     public function createShippingInvoice(Shipment $shipment, ?array $rows null, ?bool $persist true): Invoice
  671.     {
  672.         $invoice = new Invoice();
  673.         $invoice->setDate(new DateTime());
  674.         $invoice->setNumber('F');
  675.         $invoice->setObject('Expédition ' $shipment->getDeliveryNote()->getCode());
  676.         $invoice->setUser($shipment->getDeliveryNote()->getUser());
  677.         $invoice->setDeliveryNote($shipment->getDeliveryNote());
  678.         $invoice->setType(BaseInvoice::TYPE_SHIPPING);
  679.         $invoice->setAmount($shipment->getTotalAmountShipping(true) + $shipment->getAmountGuardCharge());
  680.         $data $this->getInvoiceData($invoice);
  681.         $data['rows'] = $rows ?? $this->getShippingItems($shipment);
  682.         $data['vat_data']['rows'] = array(
  683.             array(
  684.                 FormatExtension::formatPrice(round($invoice->getAmount() / StripeService::VAT2), false),
  685.                 FormatExtension::formatPercentage(ConstantsService::GUARDCHARGE_VAT),
  686.                 FormatExtension::formatPrice($invoice->getAmount() - round($invoice->getAmount() / StripeService::VAT2), false)
  687.             )
  688.         );
  689.         $data['total_data'] = array(
  690.             array('label' => 'TOTAL HT''value' => FormatExtension::formatPrice(round($invoice->getAmount() / StripeService::VAT2), false)),
  691.             array('label' => 'TOTAL TVA''value' => FormatExtension::formatPrice($invoice->getAmount() - round($invoice->getAmount() / StripeService::VAT2), false)),
  692.             array('label' => 'TOTAL TTC''value' => FormatExtension::formatPrice($invoice->getAmount(), false)),
  693.         );
  694.         $invoice->setData($data);
  695.         if ($persist) {
  696.             $this->em->persist($invoice);
  697.             $this->em->flush();
  698.             $this->em->refresh($invoice);
  699.         }
  700.         return $invoice;
  701.     }
  702. }