TAVCotisationUtils.php 9.67 KB
Newer Older
1 2 3 4
<?php

namespace App\Utils;

5
use App\Entity\Adherent;
6
use App\Entity\Payment;
7 8
use App\Entity\Siege;
use App\Entity\Flux;
9 10
use App\Entity\CotisationTavReversement;
use App\Entity\CotisationTavPrelevement;
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
use App\Enum\MoyenEnum;
use App\Utils\CustomEntityManager;
use Symfony\Component\Security\Core\Security;

class TAVCotisationUtils
{
    private $em;
    private $security;
    private $operationUtils;

    public function __construct (
        CustomEntityManager $em,
        Security $security,
        OperationUtils $operationUtils
    ) {
        $this->em = $em;
        $this->security = $security;
        $this->operationUtils = $operationUtils;
    }

31 32 33 34 35
    /**
     * Check if cotisation already exist this month the the recipient of the given Flux.
     */
    public function checkExistingCotisation(Flux $flux) 
    {
Damien Moulard committed
36 37
        $first_day_this_month = date('Y-m-01');
        $last_day_this_month  = date('Y-m-t');
38

Damien Moulard committed
39 40 41 42 43
        $existing = $this->em->getRepository(Flux::class)->getTavCotisationsBetweenDates(
            $flux->getDestinataire(),
            $first_day_this_month,
            $last_day_this_month
        );
44

Damien Moulard committed
45
        return count($existing) > 0;
46
    }
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

    public function checkExistingRecurringPayment(Flux $flux)
    {
        $recurringPayments = $this->em->getRepository(Payment::class)->findBy([
            'isRecurrent' => true,
            'clientEmail' => $flux->getDestinataire()->getUser()->getEmail(),
        ]);

        $res = "";
        foreach($recurringPayments as $p) {
            $reason = "";
            if($p->isRecurringPaymentEndedOrExpired($reason) !== true) {
                $res .= ($reason . " ");
            }
        }
        return $res;
    }
64

65
    /**
66 67 68
     * First method to calculate allowance: 
     * according to a contribution rate defined in user's profile (ProfilDeCotisation).
     * 
69
     * Apply the cotisation profile rate to the amount paid 
70
     * and register the complement as a new flux (only if rate != 1)
71 72 73 74 75 76 77
     * 
     * Warning: EntityManager not flushed here.
     */
    public function applyTauxCotisation(Flux $flux)
    {
        $profile = $flux->getDestinataire()->getProfilDeCotisation();
        $cotisationTaux = $profile->getTauxCotisation();
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
        
        // don't need to create an other Flux if the rate is 1
        if ($cotisationTaux != 1) {
            // calculate the mlc amount the user will receive
            $cotisationAmount = $profile->getMontant();
            $mlcAmount = round($cotisationAmount * $cotisationTaux);
    
            // get the difference between what the user paid and what he•she's supposed to receive
            $amountDiff = $mlcAmount - $cotisationAmount;
    
            if ($flux->getExpediteur() instanceof Siege) {
                $siege = $flux->getExpediteur();
            } else {
                $siege = $flux->getExpediteur()->getGroupe()->getSiege();
            }
    
            if ($amountDiff > 0) {
                // User should receive more than he•she paid: send a new flux to the user to complete its cotisation
96
                $fluxCotis = new CotisationTavReversement();
97 98 99 100 101 102
                $fluxCotis->setExpediteur($siege);
                $fluxCotis->setDestinataire($flux->getDestinataire());
                $fluxCotis->setMontant($amountDiff);
                $fluxCotis->setReference("Reversement cotisation après paiement de " . $cotisationAmount . "€ et application du taux " . $cotisationTaux);
            } else {
                // User should receive less than he•she paid: fetch the difference from his account 
103
                $fluxCotis = new CotisationTavPrelevement();
104 105 106 107 108 109 110 111 112 113 114
                $fluxCotis->setExpediteur($flux->getDestinataire());
                $fluxCotis->setDestinataire($siege);
                $fluxCotis->setMontant(-$amountDiff);
                $fluxCotis->setReference("Prélèvement cotisation après paiement de " . $cotisationAmount . "€ et application du taux " . $cotisationTaux);
            }
    
            $fluxCotis->setOperateur($flux->getOperateur());
            $fluxCotis->setRole($flux->getRole());
            $fluxCotis->setMoyen(MoyenEnum::MOYEN_EMLC);
            $this->em->persist($fluxCotis);
            $this->operationUtils->executeOperations($fluxCotis);
115 116
        }
    }
117

118 119 120 121 122 123
    /**
     * Second method to calculate allowance: 
     * allowance based on user's household.
     * 
     * Rules are as follow:
     * - 150 emlc for the first person in user's household
124 125
     * - 75 emlc for each other adult
     * - 75 emlc amount for each dependant child, with a percentage applied if the child is in shared custody:
126 127 128 129
     * 25%, 50% or 75% depending on the shared custody arrangement
     * 
     * Once the full amount is calculated, cap user's balance.
     * User account balance is capped at twice the amount previously calculated.
130 131
     * 
     * @param Adherent $adherent (by ref)
132
     */
133 134
    public function calculateAllowanceAccordingToHousehold(&$adherent) {
        // TODO base amounts to param in .env, or in global params ?
135 136

        // base allowance, for one adult
137
        $mlcAllowanceAmount = 150;
138 139 140

        $adultsCount = $adherent->getHouseholdAdultCount();
        if ($adultsCount == null) {
141
            return;
142 143 144 145 146 147 148 149 150 151
        }

        // increment for each other adult in the household
        $mlcAllowanceAmount += 75 * ($adultsCount - 1);

        // increment allowance for each dependant child, depending on the shared custody arrangement
        $dependentChildren = $adherent->getDependentChildren();
        foreach ($dependentChildren as $child) {
             $childAllowanceAmount = 75;

152 153 154
             $sharedCustodyPercentage = $child->getSharedCustodyPercentage();
             if ($sharedCustodyPercentage != null) {
                $childAllowanceAmount = $childAllowanceAmount * $sharedCustodyPercentage;
155 156 157 158 159
             }

            $mlcAllowanceAmount += $childAllowanceAmount;
        }

160 161 162 163
        $adherent->setAllocationAmount($mlcAllowanceAmount);
    }

    /**
Damien Moulard committed
164
     * Method called to create Flux based on allowance amount (for household based allowance).
165 166 167
     */
    public function applyHouseholdAllowance(Flux $flux) {
        // get allowance
168 169 170 171 172
        $adherent = $flux->getDestinataire();
        $cotisationAmount = $flux->getMontant();
        
        // get the mlc amount the user is supposed to receive
        $mlcAllowanceAmount = $adherent->getAllocationAmount();
173

174 175 176 177 178 179
        if ($flux->getExpediteur() instanceof Siege) {
            $siege = $flux->getExpediteur();
        } else {
            $siege = $flux->getExpediteur()->getGroupe()->getSiege();
        }

180 181 182 183 184 185 186 187 188
        // get the difference between what the user paid and what he•she's supposed to receive
        $amountDiff = $mlcAllowanceAmount - $cotisationAmount;

        if ($amountDiff > 0) {
            // User should receive more than he•she paid: send a new flux to the user to complete its cotisation
            $fluxCotis = new CotisationTavReversement();
            $fluxCotis->setExpediteur($siege);
            $fluxCotis->setDestinataire($adherent);
            $fluxCotis->setMontant($amountDiff);
189
            $fluxCotis->setReference("Versement de l'allocation complémentaire après paiement de " . $cotisationAmount . "€ pour atteindre une allocation de " . $mlcAllowanceAmount . " MonA.");
190 191 192 193 194 195
        } else {
            // User should receive less than he•she paid: fetch the difference from his account 
            $fluxCotis = new CotisationTavPrelevement();
            $fluxCotis->setExpediteur($adherent);
            $fluxCotis->setDestinataire($siege);
            $fluxCotis->setMontant(-$amountDiff);
196
            $fluxCotis->setReference("Réduction de l'allocation correspondant à un paiement de " . $cotisationAmount . "€ pour atteindre une allocation de " . $mlcAllowanceAmount . " MonA.");
197 198
        }

199 200 201 202 203
        $fluxCotis->setOperateur($flux->getOperateur());
        $fluxCotis->setRole($flux->getRole());
        $fluxCotis->setMoyen(MoyenEnum::MOYEN_EMLC);
        $this->em->persist($fluxCotis);
        $this->operationUtils->executeOperations($fluxCotis);
204
    }
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225

    /**
     * Method called to create Flux based on allowance amount (for household based allowance).
     */
    public function withdrawDownToTheCeiling(Adherent $adherent)
    {
        $balance = $adherent->getEmlcAccount()->getBalance();
        $ceiling = $adherent->getCeiling();
        $siege = $this->em->getRepository(Siege::class)->getTheOne();

        // get the amount we want to withdraw
        $amountDiff = $ceiling - $balance;

        if ($amountDiff >= 0) {
            throw new \Exception("Impossible de prélèver : le solde de l'adhérent est inférieur ou égal au plafond.");
        }

        $flux = new CotisationTavPrelevement();
        $flux->setExpediteur($adherent);
        $flux->setDestinataire($siege);
        $flux->setMontant(-$amountDiff);
Yvon committed
226
        $flux->setReference("Prélèvement pour ramener le solde de " . $balance . " MonA sous le plafond de " . $ceiling . " MonA.");
227 228 229 230 231 232 233 234 235
        $flux->setOperateur($this->security->getUser());
        $flux->setRole($this->security->getUser()->getGroups()[0]->__toString());
        $flux->setMoyen(MoyenEnum::MOYEN_EMLC);
        $this->em->persist($flux);
        $this->operationUtils->executeOperations($flux);

        return $amountDiff;
    }

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    /**
     * Get the last cotisation of an adhérent
     *
     * @param Adherent $adherent
     *
     * @return bool|date
     */
    public function getLastTavCotisationForAdherent(?Adherent $adherent)
    {
        $cotisations = [];
        if (null !== $adherent) {
            $cotisations = $this->em->getRepository(Flux::class)->getLastTavCotisation($adherent);
        }

        if (count($cotisations) > 0) {
            return $cotisations[0]["created_at"];
        }

        return false;
    }
256
}