<?php
namespace App\Controller\flutterapi;
use App\Repository\ReceptionRepository;
use App\Repository\AgentRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\PaiementReceptionRepository; // À ajouter en haut de votre fichier
class ReceptionController extends AbstractController
{
/**
* @Route("/receptions", name="agent_receptions", methods={"POST","GET"})
*/
public function getReceptions(
Request $request,
RequestStack $requestStack,
ReceptionRepository $receptionRepo,
AgentRepository $agentRepo,
PaiementReceptionRepository $paiementRepo
): JsonResponse {
$data = json_decode($request->getContent(), true);
$codeComplet = $data['code'] ?? null;
if (!$codeComplet) {
return $this->json(['status' => 'error', 'message' => 'Code agent manquant'], 400);
}
// Extraction du préfixe (lettres) et du code (chiffres)
preg_match('/([a-zA-Z]+)(\d+)/', $codeComplet, $matches);
if (count($matches) < 3) {
return $this->json(['status' => 'error', 'message' => 'Format de code invalide'], 400);
}
$prefixe = $matches[1];
$codeNumerique = $matches[2];
$agent = $agentRepo->findOneBy([
'prefixcode' => $prefixe,
'code' => $codeNumerique
]);
if (!$agent) {
return $this->json(['status' => 'error', 'message' => 'Agent introuvable'], 404);
}
$receptions = $receptionRepo->findBy(['client' => $agent], ['dateOperation' => 'DESC'], 50);
$result = [];
foreach ($receptions as $rec) {
$totalPaye = 0;
$montantTotalAPayer = 0;
foreach ($rec->getTmpReceptions() as $tmpRec) {
// 1. Récupération du total payé pour cette ligne d'élément
$totalPaye += $paiementRepo->getSommePayeeParTmpReception($tmpRec->getId());
// 2. Alignement strict du Calcul de Prix Unitaire
// Priorité : prixFixe -> categoriePrix.prix -> 0 (Fallback à fret si non défini)
$prixUnitaire = 0;
if ($tmpRec->getPrixFixe() !== null && (float) $tmpRec->getPrixFixe() > 0) {
$prixUnitaire = (float) $tmpRec->getPrixFixe();
} elseif ($tmpRec->getCategoriePrix()) {
$prixUnitaire = (float) $tmpRec->getCategoriePrix()->getPrix();
}
// 3. Quantité / Mesure retenue (Alignée sur Twig : TONNE = tonne, Sinon = volume)
$quantiteMesure = ($tmpRec->getUnite() === 'TONNE')
? (float) $tmpRec->getTonne()
: (float) $tmpRec->getVolume();
// Total dû par article
$montantTotalAPayer += ($quantiteMesure * $prixUnitaire);
}
// 4. Calcul du solde restant
$soldeReste = max(0, $montantTotalAPayer - $totalPaye);
// 5. Détermination du statut de paiement
if ($totalPaye >= $montantTotalAPayer && $montantTotalAPayer > 0) {
$statutPaiement = 'PAID'; // Payé entièrement
$isPaye = '1';
} elseif ($totalPaye > 0) {
$statutPaiement = 'PARTIAL'; // Payé partiellement
$isPaye = '2';
} else {
$statutPaiement = 'UNPAID'; // Non payé
$isPaye = '0';
}
$result[] = [
'id' => $rec->getId(),
'numero_recu' => $rec->getRecunumero(),
'date' => $rec->getDateOperation()->format('Y-m-d H:i'),
'type' => $rec->getType(),
'fret' => $rec->getFret(),
'destination' => $rec->getDestville() ? $rec->getDestville()->getNomville() : null,
'is_charge' => $rec->getCharge(),
'colis_count' => $rec->getTotalColis(),
'poids' => $rec->getTotalKG(),
'pdf_url' => 'https://a.afisarl.com/reception/Print_receipt_reception/dwb45'.$rec->getId().'45%23%23',
'code' => (string) $rec->getClient()->getCode(),
'recu' => $rec->getRecunumero(),
'cbm' => (string) $rec->getWerehouse() == 'AIR' ? 'KG' : 'CBM',
'tonne' => 'TONE',
'volume' => (string) $rec->getTotalCBM(),
'tonnage' => (string) $rec->getTotalTONNE(),
'number' => $rec->getNumero(),
'trucking' => $rec->getTruckingNumber(),
'werehouse' => $rec->getWerehouse(),
'alias' => $rec->getAlias(),
'quantite' => (string) $rec->getTotalColis(),
'numerodepot' => '########',
'emballage' => $rec->getConteneurtype(),
'typeColis' => $rec->getType(),
'destId' => $rec->getDestville() ? $rec->getDestville()->getId() : null,
'ProvId' => $rec->getVille() ? (string) $rec->getVille()->getId() : null,
'naturecolis' => $rec->getTotalNatureColis(),
'image1' => $rec->getImageBon() != 'image' ? 'https://a.afisarl.com/file/agents/reception/'.$rec->getDateOperation()->format('d-m-Y').'-'.$rec->getRecunumero().'/'.$rec->getImageBon() : "image",
'image2' => $rec->getImageColis() != 'image' ? 'https://a.afisarl.com/file/agents/reception/'.$rec->getDateOperation()->format('d-m-Y').'-'.$rec->getRecunumero().'/'.$rec->getImageColis() : "image",
'client' => (string) $rec->getClient()->getId(),
'provenance' => $rec->getVille() ? (string) $rec->getVille()->getNomville() : null,
'supplier' => (string) $rec->getSupplier(),
'nomClient' => $rec->getClient()->getNomAg(),
'charge' => (string) $rec->getCharge(),
'numeroRecuStore' => (string) $rec->getNumeroRecuStore(),
'montantValeurs' => (string) $rec->getMontantValeur(),
'ui' => (string) $rec->getFlutterid(),
'isSave' => '1',
// Données de paiement harmonisées
'montantTotal' => (string) number_format($montantTotalAPayer, 2, '.', ''),
'montantPaye' => (string) number_format($totalPaye, 2, '.', ''),
'resteAPayer' => (string) number_format($soldeReste, 2, '.', ''),
'statutPaiement' => $statutPaiement,
'isPaye' => $isPaye,
];
}
return $this->json(['status' => 'success', 'data' => $result]);
}
}