Commit 879d8ea1 by Yvon

WIP

parent 838fee71
<?php
declare(strict_types=1);
namespace App\Command;
use App\Entity\Flux;
use App\Entity\GlobalParameter;
use App\Entity\Prestataire;
use App\Entity\Reconversion;
use App\Entity\Siege;
use App\Enum\MoyenEnum;
use App\Enum\ReconversionFrequencyEnum;
use App\Utils\CustomEntityManager;
use App\Utils\OperationUtils;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Twig\Environment;
/**
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
class ReconversionCcasMonaPrestatairesCommand extends Command
{
//Les reconversions doivent avoir lieu le premier jour du mois
// On utilise les crons suivants :
//47 1 1 * * kohinos php /home/kohinos/kohinos/bin/console kohinos:ssa:reconversion-ccas-prestataires
protected static $defaultName = 'kohinos:ssa:reconversion-ccas-prestataires';
protected $em;
protected $mailer;
protected $templating;
protected $io;
protected $param;
protected $operationUtils;
public function __construct(
CustomEntityManager $em,
\Swift_Mailer $mailer,
Environment $templating,
OperationUtils $operationUtils
) {
$this->em = $em;
$this->mailer = $mailer;
$this->templating = $templating;
$this->operationUtils = $operationUtils;
parent::__construct();
}
protected function configure()
{
$this->setDescription('SSA : générer les flux de reconversion ccas du mois précédent');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return int
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->io = new SymfonyStyle($input, $output);
$this->io->title('START. Reconversions CCAS');
$prestas = $this->em->getRepository(Prestataire::class)->findAll();
$firstDayOfPreviousMonth = new \DateTime('first day of previous month');
foreach ($prestas as $p) {
$sumOfCcasTransactionsOfPreviousMonth = $this->em->getRepository(Flux::class)->getSumOfValidCcasTransactionsByPrestaAndMonth(
$p,
intval($firstDayOfPreviousMonth->format('m')),
$firstDayOfPreviousMonth->format('Y'),
);
if ($sumOfCcasTransactionsOfPreviousMonth <= 0) {
continue;
}
/* @var Prestataire $p */
$flux = new Reconversion();
$flux->setReconversionCcas(true);
//do not fill operator as it is automated process $entity->setOperateur();
$flux->setExpediteur($p);
$flux->setMontant($sumOfCcasTransactionsOfPreviousMonth);
$flux->setDestinataire($this->em->getRepository(Siege::class)->getTheOne());
$flux->setMoyen(MoyenEnum::MOYEN_AUTRE);
$flux->setTauxreconversion(
!empty($p->getTauxreconversion()) ?
$p->getTauxreconversion()
: floatval(
$this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::RECONVERSION_PRESTATAIRE)
)
);
$now = new \DateTime();
$flux->setReference(
'Reconversion CCAS automatique du ' . $now->format('d/m/Y')
);
$this->operationUtils->executeOperations($flux);
}
$this->io->success('End');
$memoryUsage = memory_get_usage(true) / 1024 / 1024;
$this->io->text("Batch finished with memory: ${memoryUsage}M");
return 0;
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use App\Entity\Flux;
use App\Entity\GlobalParameter;
use App\Entity\Prestataire;
use App\Entity\Reconversion;
use App\Entity\Siege;
use App\Enum\MoyenEnum;
use App\Enum\ReconversionFrequencyEnum;
use App\Utils\CustomEntityManager;
use App\Utils\OperationUtils;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Twig\Environment;
/**
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
class SendCcasTransactionsExportToPrestatairesCommand extends Command
{
//Les reconversions doivent avoir lieu le premier jour du mois
// On utilise les crons suivants :
//47 1 1 * * kohinos php /home/kohinos/kohinos/bin/console kohinos:ssa:reconversion-ccas-prestataires
protected static $defaultName = 'kohinos:ssa:export-ccas-transactions';
protected $em;
protected $mailer;
protected $templating;
protected $io;
protected $param;
protected $operationUtils;
public function __construct(
CustomEntityManager $em,
\Swift_Mailer $mailer,
Environment $templating,
OperationUtils $operationUtils
) {
$this->em = $em;
$this->mailer = $mailer;
$this->templating = $templating;
$this->operationUtils = $operationUtils;
parent::__construct();
}
protected function configure()
{
$this
->setDescription('SSA : envoyer des mails avec export permettant aux prestataires de facturer le ccas')
->addOption(
'prestaid',
null,
InputOption::VALUE_REQUIRED,"Effectuer l'action pour un seul prestataire."
)
->addOption(
'yearmonth',
null,
InputOption::VALUE_REQUIRED,"Effectuer l'action pour le mois YYYYMM."
);
;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return int
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->io = new SymfonyStyle($input, $output);
$prestaid = $input->hasOption() ? null : $input->getOption('prestaid');
$yearmonth = $input->hasOption() ? null : $input->getOption('yearmonth');
$prestaRepo = $this->em->getRepository(Prestataire::class);
$prestas = $prestaid ? array(0 => $prestaRepo->find($prestaid)) : $prestaRepo->findAll();
if($yearmonth) {
$year = substr($yearmonth,0,4);
$month = intval(substr($yearmonth,3,2));
}
$this->io->title(
'START. Envoi des mails pour ' . count($prestas) . ' prestataires '
. ' contenant les transactions CCAS du mois ' . $month . ' de l\'année ' . $year
);
foreach ($prestas as $p) {
$res = $this->em->getRepository(Flux::class)->getValidCcasTransactionsByPrestaAndMonth($p,$month,$year);
//TODO : write content in files, send it by email
}
$this->io->success('End');
$memoryUsage = memory_get_usage(true) / 1024 / 1024;
$this->io->text("Batch finished with memory: ${memoryUsage}M");
return 0;
}
}
...@@ -71,7 +71,7 @@ class AccountPrestataire extends Account ...@@ -71,7 +71,7 @@ class AccountPrestataire extends Account
/** /**
* Can be negative amount. * Can be negative amount.
* *
* @param float $montant Used during a transaction to ncrement or decrement balance of CCAS transactions * @param float $montant Used during a transaction to increment or decrement balance of CCAS transactions
*/ */
public function addAmountCcas(float $montant): self public function addAmountCcas(float $montant): self
{ {
......
...@@ -39,6 +39,13 @@ class Reconversion extends Flux ...@@ -39,6 +39,13 @@ class Reconversion extends Flux
*/ */
protected $reconverti = false; protected $reconverti = false;
/**
* Identify CCAS reconversions.
*
* @ORM\Column(type="boolean", options={"default": false})
*/
protected $reconversionCcas = false;
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
...@@ -179,4 +186,16 @@ class Reconversion extends Flux ...@@ -179,4 +186,16 @@ class Reconversion extends Flux
'destinataires' => ['siege', 'tresorier'], 'destinataires' => ['siege', 'tresorier'],
]; ];
} }
public function getReconversionCcas(): ?bool
{
return $this->reconversionCcas;
}
public function setReconversionCcas(bool $reconversionCcas): self
{
$this->reconversionCcas = $reconversionCcas;
return $this;
}
} }
...@@ -7,6 +7,7 @@ use App\Entity\Comptoir; ...@@ -7,6 +7,7 @@ use App\Entity\Comptoir;
use App\Entity\Flux; use App\Entity\Flux;
use App\Entity\Groupe; use App\Entity\Groupe;
use App\Entity\Prestataire; use App\Entity\Prestataire;
use App\Entity\Transaction;
use App\Entity\User; use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry; use Doctrine\Persistence\ManagerRegistry;
...@@ -29,37 +30,134 @@ class FluxRepository extends ServiceEntityRepository ...@@ -29,37 +30,134 @@ class FluxRepository extends ServiceEntityRepository
/** /**
* @param Prestataire $presta [description] * @param Prestataire $presta [description]
* @param string $parenttype Parent type of flux (cotisation, transfert, transaction, vente...)
* @param string $type Type of flux (cotisation, transfert, transaction, vente...)
* @param string $from Date from which to fetch the flux * @param string $from Date from which to fetch the flux
* @param array $filter For each element of array, add condition f.key = value
* *
* @return Query Returns a query fo finding an array of Flux * @return Query Returns an array of flux ids matching conditions
*/ */
public function getQueryByPrestataire(Prestataire $presta, string $parenttype = null, string $type = null, $from = null) private function getQueryByPrestataireCore(Prestataire $presta, $filter = null, $from = null, $to = null)
{ {
$sqlQuery = "SELECT f.id FROM {$this->tableName} f WHERE (f.prestataire_id = :id OR f.prestataire_dest_id = :id)"; $sqlQuery = "SELECT f.id FROM {$this->tableName} f WHERE (f.prestataire_id = :id OR f.prestataire_dest_id = :id)";
if (null != $parenttype) {
$sqlQuery .= ' AND f.parenttype = :type';
}
if ($type != null) {
$sqlQuery .= " AND f.type = :type";
}
if ($from != null) { if ($from != null) {
$sqlQuery .= " AND f.created_at >= :from"; $sqlQuery .= " AND f.created_at >= :from";
} }
$statement = $this->connection->prepare($sqlQuery); if ($to != null) {
if (null != $parenttype) { $sqlQuery .= " AND f.created_at <= :to";
$statement->bindValue(':type', $parenttype);
} }
if ($type != null) { $i = 0;
$statement->bindValue(':type', $type); foreach ($filter as $key => $value) {
if($value === null) { //for convenience
$sqlQuery .= " AND f." . $key . " IS NULL";
} else {
$sqlQuery .= " AND f." . $key . " = :param_$i";
}
$i++;
} }
$statement = $this->connection->prepare($sqlQuery);
if ($from != null) { if ($from != null) {
$statement->bindValue(':from', $from); $statement->bindValue(':from', $from);
} }
if ($to != null) {
$statement->bindValue(':to', $to);
}
$i = 0;
foreach ($filter as $key => $value) {
if($value !== null) {
$statement->bindValue(":param_$i", $value);
}
$i++;
}
$statement->bindValue(':id', $presta->getId()); $statement->bindValue(':id', $presta->getId());
$statement->execute(); $statement->execute();
$results = $statement->fetchAll(); return $statement->fetchAll();
}
/**
* @param Prestataire $presta [description]
* @param integer $m From 1 to 12
* @param integer $Y Format YYYY
*/
public function getValidCcasTransactionsByPrestaAndMonth(Prestataire $presta, $m, $Y)
{
$filter = array();
$filter['isCcas'] = true;
$filter['cancellerflux_id'] = null; //exclude cancelled transactions
$filter['type'] = Transaction::TYPE_TRANSACTION_ADHERENT_PRESTATAIRE; //exclude cancellers
$from = new \DateTime();
$from->setDate($Y,$m,1)->setTime(0,0);
$to = new \DateTime();
$to->setDate($Y,$m+1,0)->setTime(23,59,59);
$ids = $this->getQueryByPrestataireCore(
$presta,
$filter,
$from->format("Y-m-d H:i:s"),
$to->format("Y-m-d H:i:s")
);
$qb = $this->createQueryBuilder('f');
return $qb
->select('a.anonymous_token', 'f.montant', 'f.created_at')
->join('f.adherent_id','a')
->where($qb->expr()->in('f.id', ':ids'))
->setParameter('ids', $ids)
->orderBy('a.anonymous_token ASC, f.createdAt ASC')
->getQuery()
->getResult();
}
/**
* @param Prestataire $presta [description]
* @param integer $m From 1 to 12
* @param integer $Y Format YYYY
*/
public function getSumOfValidCcasTransactionsByPrestaAndMonth(Prestataire $presta, $m, $Y)
{
$filter = array();
$filter['isCcas'] = true;
$filter['cancellerflux_id'] = null; //exclude cancelled transactions
$filter['type'] = Transaction::TYPE_TRANSACTION_ADHERENT_PRESTATAIRE; //exclude cancellers
$from = new \DateTime();
$from->setDate($Y,$m,1)->setTime(0,0);
$to = new \DateTime();
$to->setDate($Y,$m+1,0)->setTime(23,59,59);
$ids = $this->getQueryByPrestataireCore(
$presta,
$filter,
$from->format("Y-m-d H:i:s"),
$to->format("Y-m-d H:i:s")
);
$qb = $this->createQueryBuilder('f');
return $qb
->select('sum(f.montant)')
->where($qb->expr()->in('f.id', ':ids'))
->setParameter('ids', $ids)
->orderBy('f.createdAt', 'DESC')
->getQuery()
->getSingleScalarResult();
}
/**
* @param Prestataire $presta [description]
* @param string $parenttype Parent type of flux (cotisation, transfert, transaction, vente...)
* @param string $type Type of flux (cotisation, transfert, transaction, vente...)
* @param string $from Date from which to fetch the flux
*
* @return Query Returns a query for finding an array of Flux
*/
public function getQueryByPrestataire(Prestataire $presta, string $parenttype = null, string $type = null, $from = null)
{
$filter = array();
if ($parenttype) {
$filter['parenttype'] = $parenttype;
}
if ($type) {
$filter['type'] = $type;
}
$results = $this->getQueryByPrestataireCore($presta,$filter,$from);
$qb = $this->createQueryBuilder('f'); $qb = $this->createQueryBuilder('f');
return $qb return $qb
......
...@@ -16,6 +16,7 @@ use App\Entity\OperationGroupe; ...@@ -16,6 +16,7 @@ use App\Entity\OperationGroupe;
use App\Entity\OperationPrestataire; use App\Entity\OperationPrestataire;
use App\Entity\OperationSiege; use App\Entity\OperationSiege;
use App\Entity\Prestataire; use App\Entity\Prestataire;
use App\Entity\Reconversion;
use App\Entity\Siege; use App\Entity\Siege;
use App\Entity\Transaction; use App\Entity\Transaction;
use App\Enum\CurrencyEnum; use App\Enum\CurrencyEnum;
...@@ -135,11 +136,12 @@ class OperationUtils ...@@ -135,11 +136,12 @@ class OperationUtils
); );
// $account->addOperation($operation); // $account->addOperation($operation);
$account->addAmount($operation->getMontant()); $account->addAmount($operation->getMontant());
if( $updateBalanceCcas =
$flux instanceof Transaction //only process $flux with getIsCcas method //only process isCcas or reconversionCcas $flux
&& $flux->getIsCcas() //check if this flux should increment ccas balance ( $flux instanceof Transaction && $flux->getIsCcas() || $flux instanceof Reconversion && $flux->getReconversionCcas() )
&& $account instanceof AccountPrestataire //only process the prestataire side of the flux //only process the prestataire side of the flux
) { && $account instanceof AccountPrestataire;
if ($updateBalanceCcas) {
$account->addAmountCcas($operation->getMontant()); $account->addAmountCcas($operation->getMontant());
} }
$em->persist($operation); $em->persist($operation);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment