Anomalies déjà signalées (une seule fois par commande et par code). */ private $signaled = array(); /** @var string Nom de la boutique en ligne, cité dans les messages (« WooCommerce », « PrestaShop »…). */ private $platform; public function __construct( string $platform = 'WooCommerce' ) { $this->platform = $platform; } /** * @param Order[] $orders Commandes à analyser. * @param Settings $settings Réglages du marchand. */ public function aggregate( array $orders, Settings $settings ): Report { $this->start( $settings ); foreach ( $orders as $order ) { $this->add( $order ); } return $this->report(); } /** * Calcul au fil de l'eau (grosses boutiques) : start(), puis add() pour chaque commande, puis report(). * Les commandes n'ont pas besoin d'être toutes en mémoire en même temps. * * @param Settings $settings Réglages du marchand. */ public function start( Settings $settings ): void { $this->settings = $settings; $this->report = new Report(); $this->signaled = array(); } /** Ajoute une commande au calcul en cours. */ public function add( Order $order ): void { $this->processOrder( $order ); } /** Résultat du calcul en cours. */ public function report(): Report { return $this->report; } private function processOrder( Order $order ): void { $status = strtolower( preg_replace( '/^wc-/', '', $order->status ) ); // Commandes jamais payées : rien à déclarer. if ( in_array( $status, self::UNPAID_STATUSES, true ) ) { $this->report->exclude( $order->id, 'not_paid' ); return; } if ( 'cancelled' === $status && null === $order->paidAt ) { $this->report->exclude( $order->id, 'not_paid' ); return; } // Payée puis annulée sans remboursement enregistré : on ne devine pas (C10). if ( 'cancelled' === $status && empty( $order->refunds ) ) { $this->report->exclude( $order->id, 'cancelled_paid' ); $this->signal( Anomaly::BLOCKING, 'cancelled_paid', $order, $this->dayKey( $order->paidAt ), 'Commande payée puis annulée sans remboursement enregistré : enregistrez le remboursement dans ' . $this->platform . ', ou repassez la commande dans un état payé.' ); return; } list( $saleDate, $fallback ) = $this->saleDate( $order ); if ( null === $saleDate ) { $this->report->exclude( $order->id, 'no_date' ); $this->signal( Anomaly::BLOCKING, 'no_date', $order, null, 'Commande sans date de paiement, de création ni de fin : impossible de la rattacher à un jour.' ); return; } $day = $this->dayKey( $saleDate ); if ( $fallback ) { $this->signal( Anomaly::INFO, 'date_fallback', $order, $day, 'La date choisie dans les réglages manque pour cette commande : une autre date a été utilisée.' ); } if ( 'EUR' !== $order->currency ) { $this->report->exclude( $order->id, 'currency' ); $this->signal( Anomaly::BLOCKING, 'currency', $order, $day, 'Commande dans une autre devise que l\'euro : non prise en charge pour l\'instant.' ); return; } // Clients professionnels (C9). if ( $order->hasCompany && $order->hasVatNumber ) { if ( in_array( $order->country, self::DOMESTIC, true ) ) { $this->report->exclude( $order->id, 'b2b_france' ); $this->signal( Anomaly::INFO, 'b2b_france', $order, $day, 'Vente à un professionnel établi en France : elle relève de la facture électronique, pas de l\'e-reporting.' ); } else { $this->report->exclude( $order->id, 'b2b_foreign' ); $this->signal( Anomaly::WARNING, 'b2b_foreign', $order, $day, 'Vente à un professionnel établi hors de France : e-reporting international, non géré pour l\'instant.' ); } return; } if ( $order->hasCompany ) { $this->signal( Anomaly::INFO, 'company_without_vat', $order, $day, 'Société indiquée sans numéro de TVA : traitée comme une vente à un particulier. Vérifiez s\'il s\'agit d\'un professionnel.' ); } // Destination (C7, C8). $notTaxableInFrance = false; if ( ! in_array( $order->country, self::DOMESTIC, true ) ) { if ( in_array( $order->country, self::EU, true ) ) { $notTaxableInFrance = $this->settings->usesOss; if ( $notTaxableInFrance ) { $this->signal( Anomaly::INFO, 'oss', $order, $day, 'Vente à distance dans l\'UE déclarée via le guichet OSS : déclarée hors TVA française (catégorie TNT1).' ); } } else { $this->report->exclude( $order->id, 'export' ); $this->signal( Anomaly::BLOCKING, 'export', $order, $day, 'Vente hors de l\'Union européenne ou vers un territoire non couvert : classement à vérifier avec votre comptable.' ); return; } } $mainCategory = $this->mainCategory( $order ); // Encaissement : date de paiement de la commande (C14), quelle que soit la date retenue pour la vente. $payDay = null !== $order->paidAt ? $this->dayKey( $order->paidAt ) : $day; if ( null === $order->paidAt && $this->hasServices( $order, $mainCategory ) && ! $this->settings->vatOnDebits ) { $this->signal( Anomaly::INFO, 'payment_date_fallback', $order, $day, 'Prestation de services sans date de paiement : l\'encaissement est rattaché à la date de la vente.' ); } $this->addLines( $order->lines, $order, $day, $mainCategory, $notTaxableInFrance, $payDay ); if ( ! $notTaxableInFrance && ! $this->settings->isFranchise() ) { $this->checkShippingRates( $order, $day ); } // Remboursements : en négatif, le jour du remboursement (C2). foreach ( $order->refunds as $refund ) { $refundDay = $this->dayKey( $refund->date ); if ( ! empty( $refund->lines ) ) { $this->addLines( $refund->lines, $order, $refundDay, $mainCategory, $notTaxableInFrance, $refundDay ); } else { $this->allocateRefund( $refund, $order, $refundDay, $mainCategory, $notTaxableInFrance ); } } } /** * @param Line[] $lines Lignes (positives pour une vente, négatives pour un remboursement). */ private function addLines( array $lines, Order $order, string $day, string $mainCategory, bool $notTaxableInFrance, string $payDay ): void { foreach ( $lines as $line ) { $category = $notTaxableInFrance ? Category::NOT_TAXABLE_IN_FRANCE : ( null !== $line->category ? $line->category : $mainCategory ); $taxes = array_filter( $line->taxes, function ( Amount $tax ): bool { return ! $tax->isZero(); } ); if ( $this->settings->isFranchise() ) { if ( ! empty( $taxes ) ) { $this->signal( Anomaly::BLOCKING, 'franchise_vat', $order, $day, 'TVA facturée alors que la boutique est en franchise en base : vérifiez la configuration des taxes de ' . $this->platform . '.' ); } $this->record( $day, $payDay, $category, 0, $line->net, Amount::zero() ); continue; } if ( $notTaxableInFrance ) { // La TVA éventuelle est celle du pays de destination : pas de TVA française (C7). $this->record( $day, $payDay, $category, 0, $line->net, Amount::zero() ); continue; } if ( empty( $taxes ) ) { if ( $line->net->isZero() ) { continue; } $code = Line::ITEM === $line->kind ? 'missing_vat' : 'shipping_without_vat'; $message = Line::ITEM === $line->kind ? 'Article sans TVA : vérifiez sa taxe dans ' . $this->platform . '.' : 'Frais de port ou frais divers sans TVA : ils suivent la TVA des articles, vérifiez la configuration des taxes de livraison.'; $this->signal( Anomaly::BLOCKING, $code, $order, $day, $message ); $this->record( $day, $payDay, $category, 0, $line->net, Amount::zero() ); continue; } foreach ( array_keys( $taxes ) as $rate ) { if ( ! VatRate::isAllowed( $rate ) ) { $this->signal( Anomaly::BLOCKING, 'rate_not_allowed', $order, $day, 'Taux de TVA ' . VatRate::label( $rate ) . ' non reconnu par l\'administration : vérifiez vos taux de taxe.' ); } } // Base hors taxes de chaque taux : déduite de la TVA réellement facturée (C3). if ( 1 === count( $taxes ) ) { $bases = array( array_keys( $taxes )[0] => $line->net ); } else { $weights = array(); foreach ( $taxes as $rate => $tax ) { $weights[ $rate ] = 0 === $rate ? 0 : (int) round( abs( $tax->micro() ) * 10000 / $rate ); } $bases = $line->net->allocate( $weights ); } foreach ( $taxes as $rate => $tax ) { $this->checkConsistency( $order, $day, $bases[ $rate ], $rate, $tax ); $this->record( $day, $payDay, $category, $rate, $bases[ $rate ], $tax ); } } } /** * Taux de TVA des frais de port (C3, à vérifier, sans bloquer) : ils suivent normalement le taux des articles * (BOI-TVA-BASE-10-20-10 § 140, BOI-TVA-LIQ-10). Les textes ne disent pas comment les répartir dans un panier * à plusieurs taux ; WooCommerce les taxe souvent au seul taux normal. */ private function checkShippingRates( Order $order, string $day ): void { $itemRates = array(); $shippingRates = array(); foreach ( $order->lines as $line ) { foreach ( $line->taxes as $rate => $tax ) { if ( 0 === $rate || $tax->isZero() ) { continue; } if ( Line::ITEM === $line->kind ) { $itemRates[ $rate ] = true; } elseif ( Line::SHIPPING === $line->kind ) { $shippingRates[ $rate ] = true; } } } if ( empty( $itemRates ) || empty( $shippingRates ) ) { return; } $foreign = array_diff_key( $shippingRates, $itemRates ); if ( ! empty( $foreign ) ) { $this->signal( Anomaly::WARNING, 'shipping_rate_differs', $order, $day, 'Frais de port taxés à ' . VatRate::label( (int) array_keys( $foreign )[0] ) . ', un taux qu\'aucun article de la commande n\'a : les frais de port suivent normalement le taux des articles. Vérifiez la taxe de la livraison dans ' . $this->platform . '.' ); return; } if ( count( $itemRates ) > 1 && 1 === count( $shippingRates ) ) { $this->signal( Anomaly::WARNING, 'shipping_single_rate', $order, $day, 'Panier à plusieurs taux de TVA : les frais de port sont taxés au seul taux de ' . VatRate::label( (int) array_keys( $shippingRates )[0] ) . '. Aucun texte ne précise comment les répartir : à valider avec votre comptable.' ); } } /** Remboursement sans détail : réparti au prorata du TTC de chaque taux de la commande (C5). */ private function allocateRefund( Refund $refund, Order $order, string $day, string $mainCategory, bool $notTaxableInFrance ): void { $weights = array(); $keys = array(); foreach ( $order->lines as $line ) { $category = $notTaxableInFrance ? Category::NOT_TAXABLE_IN_FRANCE : ( null !== $line->category ? $line->category : $mainCategory ); $taxes = array_filter( $line->taxes, function ( Amount $tax ): bool { return ! $tax->isZero(); } ); if ( $this->settings->isFranchise() || $notTaxableInFrance || empty( $taxes ) ) { $key = $category . '|0'; $keys[ $key ] = array( $category, 0 ); $weights[ $key ] = ( isset( $weights[ $key ] ) ? $weights[ $key ] : 0 ) + $line->net->micro(); continue; } $net = $line->net; $lineWeight = array(); foreach ( $taxes as $rate => $tax ) { $lineWeight[ $rate ] = 0 === $rate ? 0 : (int) round( abs( $tax->micro() ) * 10000 / $rate ); } $bases = 1 === count( $taxes ) ? array( array_keys( $taxes )[0] => $net ) : $net->allocate( $lineWeight ); foreach ( $taxes as $rate => $tax ) { $key = $category . '|' . $rate; $keys[ $key ] = array( $category, $rate ); $weights[ $key ] = ( isset( $weights[ $key ] ) ? $weights[ $key ] : 0 ) + $bases[ $rate ]->micro() + $tax->micro(); } } if ( empty( $weights ) || array_sum( $weights ) <= 0 ) { $this->signal( Anomaly::BLOCKING, 'refund_unallocated', $order, $day, 'Remboursement impossible à répartir par taux de TVA : remboursez article par article dans ' . $this->platform . '.' ); return; } $this->signal( Anomaly::WARNING, 'refund_without_lines', $order, $day, 'Remboursement d\'un montant libre : réparti au prorata des taux de la commande. Préférez rembourser article par article.' ); $shares = $refund->amount->negate()->allocate( $weights ); foreach ( $shares as $key => $grossShare ) { list( $category, $rate ) = $keys[ $key ]; $taxMicro = 0 === $rate ? 0 : (int) round( $grossShare->micro() * $rate / ( 10000 + $rate ) ); $tax = Amount::fromMicro( $taxMicro ); $this->record( $day, $day, $category, $rate, $grossShare->subtract( $tax ), $tax ); } } /** * Ajoute un montant aux totaux de la vente ; pour une prestation de services soumise à la TVA * française, c'est aussi un encaissement TTC au jour du paiement (S10, C15), sauf option pour les débits. */ private function record( string $day, string $payDay, string $category, int $rate, Amount $net, Amount $tax ): void { $this->report->add( $day, $category, $rate, $net, $tax ); if ( Category::SERVICES === $category && ! $this->settings->vatOnDebits ) { $this->report->addPayment( $payDay, $rate, $net->add( $tax ) ); } } /** La commande contient-elle une prestation de services ? */ private function hasServices( Order $order, string $mainCategory ): bool { foreach ( $order->lines as $line ) { if ( Category::SERVICES === ( null !== $line->category ? $line->category : $mainCategory ) ) { return true; } } return false; } /** Signale une TVA qui ne correspond pas au taux (tolérance : 1 centime + 0,5 %). */ private function checkConsistency( Order $order, string $day, Amount $base, int $rate, Amount $tax ): void { $expected = (int) round( $base->micro() * $rate / 10000 ); $gap = abs( $tax->micro() - $expected ); $tolerance = 10000 + (int) round( abs( $expected ) * 0.005 ); if ( $gap > $tolerance ) { $this->signal( Anomaly::WARNING, 'vat_mismatch', $order, $day, 'Le montant de TVA ne correspond pas au taux ' . VatRate::label( $rate ) . ' appliqué au montant hors taxes : vérifiez la commande.' ); } } /** Les frais de port et frais divers suivent les articles : biens s'il y en a, sinon services (C13). */ private function mainCategory( Order $order ): string { $hasItem = false; foreach ( $order->lines as $line ) { if ( Line::ITEM !== $line->kind ) { continue; } $hasItem = true; if ( Category::SERVICES !== $line->category ) { return Category::GOODS; } } return $hasItem ? Category::SERVICES : Category::GOODS; } /** * Date de rattachement d'une vente (C1), avec repli si la date choisie manque. * * @return array{0:\DateTimeImmutable|null, 1:bool} [date, repli utilisé] */ private function saleDate( Order $order ): array { switch ( $this->settings->dateBasis ) { case Settings::DATE_COMPLETED: $candidates = array( $order->completedAt, $order->paidAt, $order->createdAt ); break; case Settings::DATE_CREATED: $candidates = array( $order->createdAt, $order->paidAt, $order->completedAt ); break; default: $candidates = array( $order->paidAt, $order->completedAt, $order->createdAt ); } foreach ( $candidates as $i => $date ) { if ( null !== $date ) { return array( $date, $i > 0 ); } } return array( null, false ); } /** Jour du calendrier à Paris (une vente à 0 h 30 heure de Paris appartient à ce jour-là). */ private function dayKey( \DateTimeImmutable $date ): string { return $date->setTimezone( $this->settings->timezone )->format( 'Y-m-d' ); } private function signal( string $severity, string $code, Order $order, ?string $day, string $message ): void { $key = $order->id . '|' . $code . '|' . (string) $day; if ( isset( $this->signaled[ $key ] ) ) { return; } $this->signaled[ $key ] = true; $this->report->addAnomaly( new Anomaly( $severity, $code, $order->id, $day, $message ) ); } }