Commit a21f96c0 by Julien Jorry

Solidoume : better analysis tool for redistribution and some fixs

parent b58644c6
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "cb0a4dd7f52bb590176c257882987ff6", "content-hash": "a59b75dfa4cd00a3ccefd4cda875dd52",
"packages": [ "packages": [
{ {
"name": "alcohol/iso4217", "name": "alcohol/iso4217",
...@@ -2450,7 +2450,7 @@ ...@@ -2450,7 +2450,7 @@
}, },
{ {
"name": "ekyna/payum-payzen", "name": "ekyna/payum-payzen",
"version": "dev-composerUpdateLittle", "version": "dev-master",
"dist": { "dist": {
"type": "path", "type": "path",
"url": "./lib/ekyna/payum-payzen", "url": "./lib/ekyna/payum-payzen",
......
...@@ -40,6 +40,12 @@ doctrine: ...@@ -40,6 +40,12 @@ doctrine:
dir: '%kernel.project_dir%/src/Entity' dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity' prefix: 'App\Entity'
alias: App alias: App
gedmo_loggable:
type: annotation
prefix: Gedmo\Loggable\Entity
dir: "%kernel.project_dir%/vendor/gedmo/doctrine-extensions/src/Loggable/Entity"
alias: GedmoLoggable # (optional) it will default to the name set for the mapping
is_bundle: false
dql: dql:
string_functions: string_functions:
str_to_date: App\DQL\StrToDate str_to_date: App\DQL\StrToDate
......
...@@ -7,4 +7,5 @@ stof_doctrine_extensions: ...@@ -7,4 +7,5 @@ stof_doctrine_extensions:
sortable: true sortable: true
timestampable: true timestampable: true
sluggable: true sluggable: true
softdeleteable: true softdeleteable: true
\ No newline at end of file loggable: true
\ No newline at end of file
...@@ -125,6 +125,19 @@ services: ...@@ -125,6 +125,19 @@ services:
autowire: false autowire: false
arguments: ["@service_container", "@security.helper", "@doctrine.orm.entity_manager", "@knp_paginator", "@session", "@app.utils.operations", "@app.utils.cotisations"] arguments: ["@service_container", "@security.helper", "@doctrine.orm.entity_manager", "@knp_paginator", "@session", "@app.utils.operations", "@app.utils.cotisations"]
app.twig.logentry.extension:
class: App\Twig\LogEntryExtension
autowire: false
arguments: ["@doctrine.orm.entity_manager"]
app.twig.unserialize.extension:
class: App\Twig\UnserializeExtension
autowire: false
app.twig.getclass.extension:
class: App\Twig\GetClassExtension
autowire: false
app.twig.extension.flux: app.twig.extension.flux:
class: App\Twig\FluxExtension class: App\Twig\FluxExtension
autowire: false autowire: false
......
...@@ -5,6 +5,7 @@ namespace App\Admin; ...@@ -5,6 +5,7 @@ namespace App\Admin;
use App\Entity\Adherent; use App\Entity\Adherent;
use App\Entity\SolidoumeParameter; use App\Entity\SolidoumeParameter;
use App\Entity\User; use App\Entity\User;
use App\Utils\LogEntryTrait;
use Knp\Menu\ItemInterface; use Knp\Menu\ItemInterface;
use Sonata\AdminBundle\Admin\AbstractAdmin; use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface; use Sonata\AdminBundle\Admin\AdminInterface;
...@@ -32,6 +33,8 @@ use Symfony\Component\Validator\Constraints\NotBlank; ...@@ -32,6 +33,8 @@ use Symfony\Component\Validator\Constraints\NotBlank;
*/ */
class SolidoumeAdmin extends AbstractAdmin class SolidoumeAdmin extends AbstractAdmin
{ {
use LogEntryTrait;
protected $baseRouteName = 'solidoume'; protected $baseRouteName = 'solidoume';
protected $baseRoutePattern = 'solidoume'; protected $baseRoutePattern = 'solidoume';
protected $security; protected $security;
...@@ -67,7 +70,6 @@ class SolidoumeAdmin extends AbstractAdmin ...@@ -67,7 +70,6 @@ class SolidoumeAdmin extends AbstractAdmin
->add('adherent', EntityType::class, [ ->add('adherent', EntityType::class, [
'class' => Adherent::class, 'class' => Adherent::class,
'choices' => $adherents, 'choices' => $adherents,
// 'choice_label' => 'name',
'placeholder' => 'Choisir un adherent', 'placeholder' => 'Choisir un adherent',
'choice_label' => function ($adherent) { 'choice_label' => function ($adherent) {
return $adherent->getUser() ? ($adherent->getUser()->getLastname() . ' ' . $adherent->getUser()->getFirstname() . ' (' . $adherent->getUser()->getEmail() . ')') : $adherent->__toString(); return $adherent->getUser() ? ($adherent->getUser()->getLastname() . ' ' . $adherent->getUser()->getFirstname() . ' (' . $adherent->getUser()->getEmail() . ')') : $adherent->__toString();
...@@ -137,10 +139,18 @@ class SolidoumeAdmin extends AbstractAdmin ...@@ -137,10 +139,18 @@ class SolidoumeAdmin extends AbstractAdmin
'label' => 'Commentaires', 'label' => 'Commentaires',
'editable' => true, 'editable' => true,
]) ])
->add('lastMonthPayed', null, [ // ->add('lastMonthPayed', null, [
'label' => 'Dernier prélèvement', // 'label' => 'Dernier prélèvement',
'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list_solidoume_lastmonthpayed.html.twig', // 'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list_solidoume_lastmonthpayed.html.twig',
]) // ])
->add('allPrelevement', null, [
'label' => 'Prélèvements',
'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list_solidoume_prelevements.html.twig',
])
->add('allRedistribution', null, [
'label' => 'Redistributions',
'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list_solidoume_redistributions.html.twig',
])
->add('_action', null, [ ->add('_action', null, [
'actions' => [ 'actions' => [
'show' => [], 'show' => [],
...@@ -178,7 +188,13 @@ class SolidoumeAdmin extends AbstractAdmin ...@@ -178,7 +188,13 @@ class SolidoumeAdmin extends AbstractAdmin
'label' => 'Prélèvements', 'label' => 'Prélèvements',
'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/show_solidoume_prelevements.html.twig', 'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/show_solidoume_prelevements.html.twig',
]) ])
->add('allRedistribution', null, [
'label' => 'Redistributions',
'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/show_solidoume_redistributions.html.twig',
])
->end()
; ;
$this->addLogEntries($showMapper, 'col-md-12');
} }
/** /**
...@@ -193,6 +209,10 @@ class SolidoumeAdmin extends AbstractAdmin ...@@ -193,6 +209,10 @@ class SolidoumeAdmin extends AbstractAdmin
$menu->addChild('Paramètres', [ $menu->addChild('Paramètres', [
'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('solidoumeparam_list', [], UrlGeneratorInterface::ABSOLUTE_URL), 'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('solidoumeparam_list', [], UrlGeneratorInterface::ABSOLUTE_URL),
])->setAttribute('icon', 'fa fa-cogs'); ])->setAttribute('icon', 'fa fa-cogs');
$menu->addChild('Redistributions', [
'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('solidoumeparam_redistribution', [], UrlGeneratorInterface::ABSOLUTE_URL),
])->setAttribute('icon', 'fa fa-list');
} }
/** /**
......
...@@ -58,7 +58,8 @@ class SolidoumeParamAdmin extends AbstractAdmin ...@@ -58,7 +58,8 @@ class SolidoumeParamAdmin extends AbstractAdmin
protected function configureRoutes(RouteCollection $collection) protected function configureRoutes(RouteCollection $collection)
{ {
$collection->remove('create'); $collection->clearExcept(['list']);
$collection->add('redistribution');
} }
public function getBatchActions() public function getBatchActions()
......
...@@ -196,6 +196,7 @@ class SolidoumeCommand extends Command ...@@ -196,6 +196,7 @@ class SolidoumeCommand extends Command
$flux->setExpediteur($item->getAdherent()); $flux->setExpediteur($item->getAdherent());
$flux->setDestinataire($em->getRepository(Prestataire::class)->getPrestataireSolidoume()); $flux->setDestinataire($em->getRepository(Prestataire::class)->getPrestataireSolidoume());
$flux->setMontant($amount); $flux->setMontant($amount);
$flux->setData($item->toArray());
$flux->setMoyen(MoyenEnum::MOYEN_EMLC); $flux->setMoyen(MoyenEnum::MOYEN_EMLC);
$now = (new \Datetime('now'))->format('d/m/Y H:i:s'); $now = (new \Datetime('now'))->format('d/m/Y H:i:s');
$flux->setReference($em->getRepository(SolidoumeParameter::class)->getValueOf('name') . ' prélèvement en date du ' . $now); $flux->setReference($em->getRepository(SolidoumeParameter::class)->getValueOf('name') . ' prélèvement en date du ' . $now);
...@@ -241,6 +242,8 @@ class SolidoumeCommand extends Command ...@@ -241,6 +242,8 @@ class SolidoumeCommand extends Command
$countParticipants = 0; $countParticipants = 0;
foreach ($items as $item) { foreach ($items as $item) {
if ($this->isItemPayedThisMonth($item)) { if ($this->isItemPayedThisMonth($item)) {
// @TODO
// $datas = $this->em->getRepository(Flux::class)->getQueryByAdherentAndDestinataire($adherent, $this->em->getRepository(Prestataire::class)->getPrestataireSolidoume());
$total += $item->getAmount(); $total += $item->getAmount();
if (!$item->getIsDonation()) { if (!$item->getIsDonation()) {
++$countParticipants; ++$countParticipants;
......
...@@ -2,11 +2,17 @@ ...@@ -2,11 +2,17 @@
namespace App\Controller; namespace App\Controller;
use App\Entity\Flux;
use App\Entity\Prestataire;
use App\Entity\SolidoumeItem;
use App\Entity\SolidoumeParameter; use App\Entity\SolidoumeParameter;
use App\Form\Type\SolidoumeParameterFormType; use App\Form\Type\SolidoumeParameterFormType;
use App\Utils\CustomEntityManager; use App\Utils\CustomEntityManager;
use DateTime;
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
use Sonata\AdminBundle\Controller\CRUDController; use Sonata\AdminBundle\Controller\CRUDController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Core\Security;
class SolidoumeParameterController extends CRUDController class SolidoumeParameterController extends CRUDController
...@@ -20,6 +26,125 @@ class SolidoumeParameterController extends CRUDController ...@@ -20,6 +26,125 @@ class SolidoumeParameterController extends CRUDController
$this->security = $security; $this->security = $security;
} }
public function redistributionAction(Request $request): Response
{
$datas = [];
$next = [];
$solidoumeParam = $this->em->getRepository(SolidoumeParameter::class)->findTheOne();
$redistributions = $this->em->getRepository(Flux::class)->getQueryByPrestataire($this->em->getRepository(Prestataire::class)->getPrestataireSolidoume(), null, 'prestataire_adherent')->getResult();
$prelevements = $this->em->getRepository(Flux::class)->getQueryByPrestataire($this->em->getRepository(Prestataire::class)->getPrestataireSolidoume(), null, 'adherent_prestataire')->getResult();
foreach ($redistributions as $redistribution) {
$datas[$redistribution->getCreatedAt()->format('d/m/Y')]['redis'][] = $redistribution;
}
ksort($datas);
$lastRedist = array_key_last($datas);
$lastRedistDate = DateTime::createFromFormat('d/m/Y', $lastRedist);
$nextRedis = clone $lastRedistDate;
$nextRedis = $nextRedis->modify('+1 month');
$nextRedis = $nextRedis->format('d/m/Y');
$nextRedis = $solidoumeParam->getExecutionDate().substr($nextRedis,2,strlen($nextRedis)-2);
$datas[$nextRedis]['redis'] = [];
$datas[$nextRedis]['prelev'] = [];
foreach($prelevements as $prelevement) {
foreach($datas as $key => $data) {
$dateEnd = DateTime::createFromFormat('d/m/Y', $key);
$dateStart = clone $dateEnd;
$dateStart = $dateStart->modify('-1 month');
if ($prelevement->getCreatedAt() > $dateStart && $prelevement->getCreatedAt() <= $dateEnd) {
$datas[$key]['prelev'][] = $prelevement;
}
}
}
$solidoumeItems = $this->em->getRepository(SolidoumeItem::class)->findBy([]);
foreach ($datas as $key => $data) {
$datas[$key]['adherent'] = [];
$nbdonateur = 0;
$totalperperson = 0;
$totalAmountDon = 0;
$totalAmountPrel = 0;
$totalAmount = 0;
$totalMissed = 0;
foreach($data['prelev'] as $prelev) {
$datas[$key]['adherent'][$prelev->getExpediteur()->__toString()]['prelevement'] = $prelev;
$datas[$key]['adherent'][$prelev->getExpediteur()->__toString()]['don'] = false;
$totalAmount += $prelev->getMontant();
$totalAmountPrel += $prelev->getMontant();
}
foreach ($datas[$key]['prelev'] as $prelevement) {
$isdon = true;
foreach ($datas[$key]['redis'] as $redistribution) {
$datas[$key]['adherent'][$redistribution->getDestinataire()->__toString()]['redistribution'] = $redistribution;
$datas[$key]['adherent'][$redistribution->getDestinataire()->__toString()]['don'] = false;
$totalperperson = $redistribution->getMontant();
if ($prelevement->getExpediteur() == $redistribution->getDestinataire()) {
$isdon = false;
}
}
if ($isdon) {
$donFound = false;
$prelevementData = $prelevement->getData();
if ($prelevementData != null && isset($prelevementData['item'])) {
if (isset($prelevementData['item']['don']) && $prelevementData['item']['don'] == true) {
$datas[$key]['adherent'][$prelevement->getExpediteur()->__toString()]['don'] = true;
$donFound = true;
$data[$key]['dons'][] = $prelevement;
$totalAmountDon += $prelevement->getMontant();
$nbdonateur++;
}
} else {
foreach ($solidoumeItems as $item) {
if ($item->getAdherent() == $prelevement->getExpediteur()) {
if ($item->getIsDonation()) {
$datas[$key]['adherent'][$prelevement->getExpediteur()->__toString()]['don'] = true;
$donFound = true;
$data[$key]['dons'][] = $prelevement;
$totalAmountDon += $prelevement->getMontant();
$nbdonateur++;
}
}
}
}
if (!$donFound) {
$data[$key]['missed'][] = $prelevement;
$totalMissed += $prelevement->getMontant();
}
}
}
foreach ($solidoumeItems as $item) {
if (isset($datas[$key]['adherent'][$item->getAdherent()->__toString()])) {
$datas[$key]['adherent'][$item->getAdherent()->__toString()]['item'] = $item;
}
}
ksort($datas[$key]['adherent']);
$nbperson = count($data['redis']);
//round((($totalAmount / $nbperson) * ((100 - $solidoumeParam->getCommission()) / 100)), 2, PHP_ROUND_HALF_DOWN);
$amountcommission = $totalAmount/100*5;
$datas[$key]['date'] = $key;
$datas[$key]['totalAmount'] = $totalAmount;
$datas[$key]['totalAmountDon'] = $totalAmountDon;
$datas[$key]['totalAmountPrel'] = $totalAmountPrel;
$datas[$key]['totalMissed'] = $totalMissed;
$datas[$key]['nbmissed'] = count($data[$key]['missed']);
$datas[$key]['nbperson'] = $nbperson;
$datas[$key]['nbdonateur'] = $nbdonateur;
$datas[$key]['totalperperson'] = $totalperperson;
$datas[$key]['commission'] = $solidoumeParam->getCommission();
$datas[$key]['amountcommission'] = $amountcommission;
}
krsort($datas);
$firstKey = array_key_first($datas);
$nextRedis = $datas[$firstKey];
$datas['_next'] = $nextRedis;
unset($datas[$firstKey]);
krsort($datas);
return $this->renderWithExtraParams('@kohinos/admin/solidoume_redistribution.html.twig', [
'datas' => $datas
]);
}
/** /**
* List action. * List action.
* *
......
...@@ -6,16 +6,18 @@ use ApiPlatform\Core\Annotation\ApiResource; ...@@ -6,16 +6,18 @@ use ApiPlatform\Core\Annotation\ApiResource;
use App\Entity\EntityTrait\EnablableEntityTrait; use App\Entity\EntityTrait\EnablableEntityTrait;
use App\Repository\SolidoumeItemRepository; use App\Repository\SolidoumeItemRepository;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Timestampable\Traits\TimestampableEntity; use Gedmo\Timestampable\Traits\TimestampableEntity;
use Ramsey\Uuid\Doctrine\UuidGenerator; use Ramsey\Uuid\Doctrine\UuidGenerator;
use Symfony\Component\Validator\Constraints as Assert;
/** /**
* @ApiResource() * @ApiResource()
* @Gedmo\Loggable()
* @ORM\Entity(repositoryClass=SolidoumeItemRepository::class) * @ORM\Entity(repositoryClass=SolidoumeItemRepository::class)
*/ */
class SolidoumeItem class SolidoumeItem
{ {
use EnablableEntityTrait;
use TimestampableEntity; use TimestampableEntity;
/** /**
...@@ -30,21 +32,27 @@ class SolidoumeItem ...@@ -30,21 +32,27 @@ class SolidoumeItem
/** /**
* @ORM\Column(type="float") * @ORM\Column(type="float")
* @Gedmo\Versioned
*/ */
private $amount; private $amount;
/** /**
* @Assert\Type("bool")
* @ORM\Column(type="boolean") * @ORM\Column(type="boolean")
* @Gedmo\Versioned
*/ */
private $isRecurrent; private $isRecurrent;
/** /**
* @ORM\Column(type="integer") * @ORM\Column(type="integer")
* @Gedmo\Versioned
*/ */
private $paiementDate; private $paiementDate;
/** /**
* @Assert\Type("bool")
* @ORM\Column(type="boolean") * @ORM\Column(type="boolean")
* @Gedmo\Versioned
*/ */
private $isDonation; private $isDonation;
...@@ -55,13 +63,15 @@ class SolidoumeItem ...@@ -55,13 +63,15 @@ class SolidoumeItem
private $adherent; private $adherent;
/** /**
* @ORM\ManyToOne(targetEntity="User", inversedBy="news") * @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
* @Gedmo\Versioned
*/ */
private $user; private $user;
/** /**
* @ORM\Column(type="text", nullable=true) * @ORM\Column(type="text", nullable=true)
* @Gedmo\Versioned
*/ */
private $comments; private $comments;
...@@ -70,11 +80,31 @@ class SolidoumeItem ...@@ -70,11 +80,31 @@ class SolidoumeItem
*/ */
private $lastMonthPayed; private $lastMonthPayed;
/**
* @var bool
* @Assert\Type("bool")
* @ORM\Column(type="boolean")
* @Gedmo\Versioned
*/
protected $enabled = true;
public function getId() public function getId()
{ {
return $this->id; return $this->id;
} }
public function isEnabled(): bool
{
return $this->enabled;
}
public function setEnabled(bool $enabled)
{
$this->enabled = $enabled;
return $this;
}
public function getAmount(): ?float public function getAmount(): ?float
{ {
return $this->amount; return $this->amount;
...@@ -171,8 +201,24 @@ class SolidoumeItem ...@@ -171,8 +201,24 @@ class SolidoumeItem
return $this; return $this;
} }
public function toArray()
{
return ['item' => [
'id' => $this->getId(),
'amount' => $this->getAmount(),
'adherent' => $this->getAdherent()->__toString(),
'paiementDate' => $this->getPaiementDate(),
'lastMonthPayed' => $this->getLastMonthPayed(),
'don' => $this->getIsDonation(),
'recurrent' => $this->getIsRecurrent(),
'enabled' => $this->isEnabled()
]
];
}
public function __toString() public function __toString()
{ {
return 'SolidoumeItem ' . ($this->getId() ? '#' . $this->getId() : '') . ', amount : ' . $this->getAmount() . ', adherent ' . $this->getAdherent()->__toString() . ', paiementDate : ' . $this->getPaiementDate() . ', lastMonthPayed : ' . $this->getLastMonthPayed() . ', don : ' . $this->getIsDonation() . ', recurrent : ' . $this->getIsRecurrent() . ', enabled : ' . $this->isEnabled(); return 'SolidoumeItem Montant : ' . $this->getAmount() . ', adherent ' . $this->getAdherent()->__toString() . ', paiementDate : ' . $this->getPaiementDate() . ', lastMonthPayed : ' . $this->getLastMonthPayed() . ', don : ' . $this->getIsDonation() . ', recurrent : ' . $this->getIsRecurrent() . ', enabled : ' . $this->isEnabled();
} }
} }
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20220717142740 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE ext_log_entries (id INT AUTO_INCREMENT NOT NULL, action VARCHAR(8) NOT NULL, logged_at DATETIME NOT NULL, object_id VARCHAR(64) DEFAULT NULL, object_class VARCHAR(191) NOT NULL, version INT NOT NULL, data LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:array)\', username VARCHAR(191) DEFAULT NULL, INDEX log_class_lookup_idx (object_class), INDEX log_date_lookup_idx (logged_at), INDEX log_user_lookup_idx (username), INDEX log_version_lookup_idx (object_id, object_class, version), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_general_ci` ENGINE = InnoDB ROW_FORMAT = DYNAMIC');
$this->addSql('ALTER TABLE cron_report ADD error LONGTEXT NOT NULL');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('DROP TABLE ext_log_entries');
$this->addSql('ALTER TABLE cron_report DROP error');
}
}
...@@ -32,16 +32,22 @@ class FluxRepository extends ServiceEntityRepository ...@@ -32,16 +32,22 @@ class FluxRepository extends ServiceEntityRepository
* *
* @return Query Returns a query fo finding an array of Flux * @return Query Returns a query fo finding an array of Flux
*/ */
public function getQueryByPrestataire(Prestataire $presta, $parenttype = null) public function getQueryByPrestataire(Prestataire $presta, string $parenttype = null, string $type = 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) { if (null != $parenttype) {
$sqlQuery .= ' AND f.parenttype = :type'; $sqlQuery .= ' AND f.parenttype = :type';
} }
if ($type != null) {
$sqlQuery .= " AND f.type = :type";
}
$statement = $this->connection->prepare($sqlQuery); $statement = $this->connection->prepare($sqlQuery);
if (null != $parenttype) { if (null != $parenttype) {
$statement->bindValue(':type', $parenttype); $statement->bindValue(':type', $parenttype);
} }
if ($type != null) {
$statement->bindValue(':type', $type);
}
$statement->bindValue(':id', $presta->getId()); $statement->bindValue(':id', $presta->getId());
$statement->execute(); $statement->execute();
$results = $statement->fetchAll(); $results = $statement->fetchAll();
...@@ -81,12 +87,18 @@ class FluxRepository extends ServiceEntityRepository ...@@ -81,12 +87,18 @@ class FluxRepository extends ServiceEntityRepository
; ;
} }
public function getQueryByAdherentAndDestinataire(Adherent $adherent, Prestataire $prestataire) public function getQueryByAdherentAndDestinataire(Adherent $adherent, Prestataire $prestataire, string $type = null)
{ {
$sqlQuery = "SELECT f.id FROM {$this->tableName} f WHERE (f.adherent_id = :id OR f.prestataire_id = :presta_id)"; $sqlQuery = "SELECT f.id FROM {$this->tableName} f WHERE (f.adherent_id = :id AND f.prestataire_id = :presta_id)";
if ($type != null) {
$sqlQuery .= " AND f.type = :type";
}
$statement = $this->connection->prepare($sqlQuery); $statement = $this->connection->prepare($sqlQuery);
$statement->bindValue(':id', $adherent->getId()); $statement->bindValue(':id', $adherent->getId());
$statement->bindValue(':presta_id', $prestataire->getId()); $statement->bindValue(':presta_id', $prestataire->getId());
if ($type != null) {
$statement->bindValue(':type', $type);
}
$statement->execute(); $statement->execute();
$results = $statement->fetchAll(); $results = $statement->fetchAll();
$qb = $this->createQueryBuilder('f'); $qb = $this->createQueryBuilder('f');
......
<?php
declare(strict_types=1);
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
final class GetClassExtension extends AbstractExtension
{
/**
* {@inheritdoc}
*/
public function getFunctions(): array
{
return [
new TwigFunction('is_object', [$this, 'isObject']),
new TwigFunction('get_class', [$this, 'getClass']),
];
}
public function getClass($object)
{
return get_class($object);
}
public function isObject($object)
{
return is_object($object);
}
}
<?php
declare(strict_types=1);
namespace App\Twig;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* @SuppressWarnings("PHPMD.ShortVariable")
*/
class LogEntryExtension extends AbstractExtension
{
/**
* @var EntityManagerInterface
*/
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function getFunctions()
{
return [
new TwigFunction('getLogUser', [$this, 'getLogUser']),
];
}
public function getLogUser(?string $username): ?User
{
if (null !== $username) {
return $this->em->getRepository(User::class)->findOneByUsername($username);
}
return null;
}
}
...@@ -43,6 +43,7 @@ class SolidoumeExtension extends AbstractExtension ...@@ -43,6 +43,7 @@ class SolidoumeExtension extends AbstractExtension
new \Twig_SimpleFunction('getSolidoumeForm', [$this, 'getSolidoumeForm']), new \Twig_SimpleFunction('getSolidoumeForm', [$this, 'getSolidoumeForm']),
new \Twig_SimpleFunction('getSolidoumeParticipation', [$this, 'getSolidoumeParticipation']), new \Twig_SimpleFunction('getSolidoumeParticipation', [$this, 'getSolidoumeParticipation']),
new \Twig_SimpleFunction('getSolidoumePrelevements', [$this, 'getSolidoumePrelevements']), new \Twig_SimpleFunction('getSolidoumePrelevements', [$this, 'getSolidoumePrelevements']),
new \Twig_SimpleFunction('getSolidoumeRedistributions', [$this, 'getSolidoumeRedistributions']),
new \Twig_SimpleFunction('getSolidoumeDatas', [$this, 'getSolidoumeDatas']), new \Twig_SimpleFunction('getSolidoumeDatas', [$this, 'getSolidoumeDatas']),
]; ];
} }
...@@ -75,7 +76,14 @@ class SolidoumeExtension extends AbstractExtension ...@@ -75,7 +76,14 @@ class SolidoumeExtension extends AbstractExtension
public function getSolidoumePrelevements(Adherent $adherent) public function getSolidoumePrelevements(Adherent $adherent)
{ {
$datas = $this->em->getRepository(Flux::class)->getQueryByAdherentAndDestinataire($adherent, $this->em->getRepository(Prestataire::class)->getPrestataireSolidoume()); $datas = $this->em->getRepository(Flux::class)->getQueryByAdherentAndDestinataire($adherent, $this->em->getRepository(Prestataire::class)->getPrestataireSolidoume(), 'adherent_prestataire');
return $datas;
}
public function getSolidoumeRedistributions(Adherent $adherent)
{
$datas = $this->em->getRepository(Flux::class)->getQueryByAdherentAndDestinataire($adherent, $this->em->getRepository(Prestataire::class)->getPrestataireSolidoume(), 'prestataire_adherent');
return $datas; return $datas;
} }
......
<?php
declare(strict_types=1);
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
final class UnserializeExtension extends AbstractExtension
{
/**
* {@inheritdoc}
*/
public function getFilters(): array
{
return [
new TwigFilter('unserialize', [$this, 'unserialize']),
];
}
public function unserialize($string)
{
if (empty($string) || is_array($string)) {
return '';
}
return unserialize($string);
}
}
<?php
namespace App\Utils;
use App\Entity\SolidoumeItem;
use Gedmo\Loggable\Entity\LogEntry;
use Gedmo\Loggable\Entity\Repository\LogEntryRepository;
use Sonata\AdminBundle\Show\ShowMapper;
/**
* Trait use for Sonata Admin to print historic of changed to show view.
*/
trait LogEntryTrait
{
protected function addLogEntries(ShowMapper &$showMapper, $class = 'col-12'): void
{
$em = $this->getConfigurationPool()->getContainer()->get('doctrine');
$logEntryRepository = $em->getRepository(LogEntry::class);
$object = $showMapper->getAdmin()->getSubject();
if (null !== $showMapper && null !== $object && null !== $logEntryRepository && count($this->getLogEntries($object)) > 0) {
$showMapper
->with('Versions', ['class' => $class])
->add('logentries', null, [
'label' => false,
'template' => '@kohinos/history/logentries.html.twig',
])
->end()
;
}
}
public function getLogEntries($object)
{
$em = $this->getConfigurationPool()->getContainer()->get('doctrine');
$logEntryRepository = $em->getRepository(LogEntry::class);
return $logEntryRepository->getLogEntries($object);
}
public function getLogEntryMappingClassName(string $className)
{
switch ($className) {
case SolidoumeItem::class:
return "Soli'Item";
default:
return $className;
}
}
}
{% extends '@kohinos/bundles/SonataAdminBundle/standard_layout.html.twig' %}
{% block sonata_page_content %}
<section class="content">
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="box box-primary" style="margin-bottom: 100px;">
<div class="box-body table-responsive">
<h2>Redistributions</h2>
<hr/>
{% if datas|length > 0 %}
{% for key, data in datas %}
{% if key == '_next' %}
<h4>Prochaine redistribution : </h4>
{% else %}
<h4>Redistribution du <b>{{ key }}</b> : </h4>
{% endif %}
<p>Montant récolté : {{ data.totalAmount }}&euro;</p>
<p>Commission récoltée ({{ data.commission }}%) : {{ data.amountcommission }}&euro;</p>
<p>Nombre de donateur(s) : {{ data.nbdonateur }} (pour un total de {{ data.totalAmountDon }}&euro;)</p>
{% if key != '_next' %}
<p>Nombre de personne(s) participante(s) au programme : {{ data.nbperson }}</p>
<p>Nombre de "raté(s)" : {{ data.nbmissed }} (pour un total de {{ data.totalMissed }}&euro;)</p>
<p>Montant réel redistribué par participant : <b>{{ data.totalperperson }}&euro;</b></p>
<p>Montant total réel calculé par le script de redistribution : <b>{{ (data.totalperperson*data.nbperson/95*100)|round(0, 'common') }}&euro;</b></p>
{% endif %}
<hr/>
<table class="table table-bordered table-striped table-hover sonata-ba-list">
<thead>
<tr class="sonata-ba-list-field-header-text">
<td>Adhérent</td>
<td>Somme prélevée</td>
<td>Somme redistribuée</td>
<td>Date de prélèvement</td>
<td>Don ?</td>
<td>Récurrent ?</td>
</tr>
</thead>
<tbody>
{% for name, adherent in data.adherent %}
<tr>
<td>{{ name }}</td>
<td>{{ adherent.prelevement is defined?adherent.prelevement.montant:'non prélevé' }}</td>
<td>{{ adherent.redistribution is defined?adherent.redistribution.montant:'non redistribué' }}</td>
<td>{{ adherent.prelevement is defined?adherent.prelevement.createdAt|date('d/m/Y H:i'):'' }}</td>
<td>{{ (adherent.don is defined and adherent.don == 1)?'<span class="label label-success">oui</span>':'<span class="label label-danger">non</span>' }}</td>
<td>{{ adherent.item.isRecurrent == 1?'<span class="label label-success">oui</span>':'<span class="label label-danger">non</span>' }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<br/>
<hr/>
<br/>
<br/>
{% endfor %}
{% else %}
<br/>
<p>
{{ "Aucunes redistributions pour le moment !"|trans }}
</p>
{% endif %}
</div>
</div>
</div>
</div>
</section>
{% endblock %}
\ No newline at end of file
{% extends admin.getTemplate('base_list_field') %}
{% block field %}
{%- spaceless %}
{% set datas = getSolidoumePrelevements(object.adherent) %}
{% for data in datas|slice(0, 3) %}
{{ data.montant}}€ ({{ data.createdAt|date('d/m') }})<br/>
{% endfor %}
{% endspaceless -%}
{% endblock %}
{% extends admin.getTemplate('base_list_field') %}
{% block field %}
{%- spaceless %}
{% set datas = getSolidoumeRedistributions(object.adherent) %}
{% for data in datas|slice(0, 3) %}
{{ data.montant}}€ ({{ data.createdAt|date('d/m') }})<br/>
{% endfor %}
{% endspaceless -%}
{% endblock %}
{% extends '@SonataAdmin/CRUD/base_show_field.html.twig' %} {% extends admin.getTemplate('base_show_field') %}
{% block field %} {% block field %}
{%- spaceless %} {%- spaceless %}
......
{% extends admin.getTemplate('base_show_field') %}
{% block field %}
{%- spaceless %}
{% set datas = getSolidoumeRedistributions(object.adherent) %}
{% for data in datas %}
{{ data.montant}}€ ({{ data.createdAt|date('d/m/Y H:i') }})<br/>
{% endfor %}
{% endspaceless -%}
{% endblock %}
{% set logentries = admin.getLogEntries(object) %}
<td>
{% block field %}
{% if logentries|length > 0 %}
<table class="table table-bordered table-striped">
<thead>
<tr>
{# <th>Id objet</th> #}
{# <th>Sujet</th> #}
<th>Date</th>
<th>Utilisateur</th>
<th>Champ(s) modifié(s)</th>
</tr>
</thead>
<tbody>
{% for log in logentries %}
{% set user = getLogUser(log.username) %}
<tr>
{# <td>{{ log.objectId }}</td> #}
{# <td>{{ admin.getLogEntryMappingClassName(log.objectClass) }}</td> #}
<td>{{ log.loggedAt|date('d/m/Y H:i') }}</td>
<td>
{% if user is not null %}
{# <a href="{{ path('admin_sonata_user_user_edit', {'id': user.id}) }}">{{ user.fullname }}</a> #}
{{ user.fullname }}
{% else %}
{{ log.username }}
{% endif %}
</td>
<td {% if log.action == 'create'%}class='bg-green'{% endif %}>
{% if log.action == 'create'%}
CREATION
{% else %}
<table class="table">
{% for field, value in log.data %}
<tr>
<th>{{ field }}</th>
<td>
{% if is_object(value) %}
{% if 'DateTime' == get_class(value) %}
{{ value|date(options.format|default(null), options.timezone|default(null)) }}
{% else %}
{{ value|serialize }}
{% endif %}
{% elseif value is iterable%}
{% for key, v in value %}
<p>{{ key }} => {{ v|raw }}</p>
{% endfor %}
{% else %}
{{ value }}
{% endif %}
</td>
</tr>
{% endfor %}
</table>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p><em>Aucun historique pour le moment !</em></p>
{% endif %}
{% endblock %}
</td>
\ No newline at end of file
{% set idmap = id|default('mapid') %} {% set idmap = id|default('mapid') %}
{% set prestataires = getAllPrestataires() %}
prestas count : {{ prestataires|length }}
<script> <script>
$(function () { $(function () {
$('[data-toggle="tooltip"]').tooltip() $('[data-toggle="tooltip"]').tooltip()
...@@ -8,7 +10,6 @@ ...@@ -8,7 +10,6 @@
L.tileLayer('https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', {maxZoom: 18, attribution: '&copy; Openstreetmap France | &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(mymap); L.tileLayer('https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', {maxZoom: 18, attribution: '&copy; Openstreetmap France | &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(mymap);
{# AJOUTER LES MARQUEURS SUR LA CARTE #} {# AJOUTER LES MARQUEURS SUR LA CARTE #}
{% set prestataires = getAllPrestataires() %}
{% set count = 1 %} {% set count = 1 %}
{% for presta in prestataires %} {% for presta in prestataires %}
{% if presta.geolocs|length > 0 %} {% if presta.geolocs|length > 0 %}
......
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