src/Repository/FarmRepository.php line 289

Open in your IDE?
  1. <?php
  2. namespace App\Repository;
  3. use App\Controller\Common\MetadataBuilder;
  4. use App\Entity\Animal;
  5. use App\Entity\Farm;
  6. use App\Entity\Lot;
  7. use App\Entity\Organization;
  8. use App\Entity\User;
  9. use App\Repository\Common\FilterBuilder;
  10. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  11. use Doctrine\Persistence\ManagerRegistry;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. /**
  14.  * @method Farm|null find($id, $lockMode = null, $lockVersion = null)
  15.  * @method Farm|null findOneBy(array $criteria, array $orderBy = null)
  16.  * @method Farm[]    findAll()
  17.  * @method Farm[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
  18.  */
  19. class FarmRepository extends ServiceEntityRepository
  20. {
  21.     use FilterBuilder;
  22.     const PREGNANTS = [1,2,3];
  23.     private EntityManagerInterface $em;
  24.     public function __construct(ManagerRegistry $registryEntityManagerInterface $em)
  25.     {/*{{{*/
  26.         parent::__construct($registryFarm::class);
  27.         $this->em $em;
  28.     }/*}}}*/
  29.     public function addFarm$qb$fId null )
  30.     {/*{{{*/
  31.         $fId and $qb->andWhere('f.id = :fId')->setParameter('fId'$fId);
  32.         return $qb->andWhere('f.deleted = 0');
  33.     }/*}}}*/
  34.     public function addOrganization$qbint $org null 
  35.     {/*{{{*/
  36.         $qb->join('App\Entity\Organization''o'"with""f.organization = o.id");
  37.         $qb->addSelect('o.id as organizationId' );
  38.         $org and $qb->andWhere('o.id = :org')->setParameter('org'$org);
  39.         return $qb;
  40.     }/*}}}*/
  41.     public function addProducer$qb$producer null )
  42.     {/*{{{*/
  43.         $qb->leftJoin('f.producer''p'"with""f.producer = p.id");
  44.         $producer and $qb->andWhere('p.id = :producer')->setParameter'producer'$producer );
  45.         return $qb;
  46.     }/*}}}*/
  47.     public function countLot$qb 
  48.     {/*{{{*/
  49.         return $qb->addSelect'(
  50.             SELECT COUNT(cl.id)
  51.             FROM App\Entity\Lot cl
  52.             INNER JOIN App\Entity\Farm fc WITH ( cl.farm = fc.id )
  53.             WHERE fc.organization = o.id 
  54.             AND fc.id = f.id
  55.             and cl.deleted = 0 
  56.                AND fc.deleted = 0
  57.                AND cl.deleted = 0
  58.                AND cl.status = 1
  59.             ) as countLot' );
  60.     }/*}}}*/
  61.     public function countAnimal$qb$organizationId null$farmId null 
  62.     {/*{{{*/
  63.         $qb->addSelect("(
  64.         SELECT COUNT(DISTINCT aC.id) 
  65.             FROM App\Entity\Animal aC
  66.             -- ahora queda animal -> lot -> farm -> organization 
  67.             -- que pertenezca al lote
  68.             INNER JOIN App\Entity\Lot lCA WITH aC.currentLot = lCA AND (aC.currentLot = lCA.id) 
  69.             -- que pertenezca al establecimiento
  70.             INNER JOIN App\Entity\Farm fCA WITH lCA.farm = fCA.id 
  71.             -- que pertenezca a la organizacion
  72.             INNER JOIN App\Entity\Organization oC WITH fCA.organization = oC.id 
  73.             WHERE aC.deleted = 0 
  74.                 AND aC.status = :statusActive 
  75.                 AND (a.createdAt >= a.deletedAt OR a.updatedAt >= a.deletedAt OR a.deletedAt is NULL)
  76.                 AND oC.id = o.id 
  77.                 AND fCA.deleted = false 
  78.                 AND lCA.deleted = false 
  79.                 AND lCA.status = true
  80.                 AND fCA.id = f.id
  81.             ) as countAnimal")
  82.             ->setParameter('statusActive'Animal::STATUS_ACTIVE);
  83.             
  84.         return $qb;
  85.     }/*}}}*/
  86.     public function addLot$qb$lot NULL)
  87.     {/*{{{*/
  88.         $qb->leftJoin('App\Entity\Lot''l'"with""f.id = l.farm");
  89.         $qb->addSelect('l.name as lotName');
  90.         $lot and $qb->andWhere("l.id = :lot")->setParameter'lot'$lot );
  91.         return $qb;
  92.     }/*}}}*/
  93.     public function addAddress$qb$addrId null )
  94.     {/*{{{*/
  95.         $qb->leftJoin('App\Entity\Address''addr'"with""f.address = addr.id");
  96.         $addrId and $qb->andWhere("addr.id = :addrId")->setParameter'addrId'$addrId );
  97.         return $qb;
  98.     }/*}}}*/
  99.     public function addActiveAnimals$qb 
  100.     {/*{{{*/
  101.         return $qb->andWhere('(a.deleted = 0 AND a.status = :statusActive) OR a.id is NULL ')->setParameter('statusActive'Animal::STATUS_ACTIVE);
  102.     }/*}}}*/
  103.     public function addAnimal$qb$aId null )
  104.     {/*{{{*/
  105.         $qb->leftJoin('App\Entity\Animal''a'"with""l.id = a.currentLot");
  106.         $aId and $qb->andWhere("a.id = :aId")->setParameter'aId'$aId );
  107.         return $qb;
  108.     }/*}}}*/
  109.     public function addBlackList$qb$to_date null 
  110.     {/*{{{*/
  111.         $to_date $to_date ?? new \DateTime();
  112.         return $qb->addSelect('SUM( if ( a.lackPeriod > :date, 1, 0) ) AS blackList')->setParameter':date'$to_date );
  113.     }/*}}}*/
  114.     public function addCurrentPregnancyStatus$qb$cps null 
  115.     {/*{{{*/
  116.         $qb->addSelect('SUM( if ( a.currentPregnancyStatus in (:cps), 1, 0) ) AS currentPregnants')->setParameter':cps'$cps );
  117.         $qb->addSelect('SUM( if ( a.currentPregnancyStatus not in (:cps), 1, 0) ) AS currentEmpty')->setParameter':cps'$cps );
  118.         return $qb;
  119.     }/*}}}*/
  120.     public function groupByFarm$qb 
  121.     {/*{{{*/
  122.         return $qb->addGroupBy('f.id');
  123.     }/*}}}*/
  124.     public function groupByLot$qb 
  125.     {/*{{{*/
  126.         return $qb->addGroupBy('l.id');
  127.     }/*}}}*/
  128.     /* getListQuery */
  129.     public function getListQuery$organizationId$farm null ): \Doctrine\ORM\QueryBuilder
  130.     {/*{{{*/
  131.         $qb $this->createQueryBuilder('f');
  132.         $qb->select('f.id as id');
  133.         $qb->addSelect('f.uuid as uuid');
  134.         $qb->addSelect('f.name as name');
  135.         $qb->addSelect('f.picture as picture');
  136.         $qb->addSelect('f.hectares as hectares');
  137.         $qb->addSelect('f.renspa as renspa');
  138.         $qb->addSelect('f.cuig as cuig');
  139.         $qb->addSelect('f.cuartel as cuartel');
  140.         $qb->addSelect('f.tenure as tenure');
  141.         $qb->addSelect('f.cottage as cottage');
  142.         $qb->addSelect('f.tambo as tambo');
  143.         $qb->addSelect('f.raise as raise');
  144.         $qb->addSelect('f.feedlot as feedlot');
  145.         $qb->addSelect('f.wintering as wintering');
  146.         $qb->addSelect('f.mix as mix');
  147.         $qb->addSelect('f.other as other');
  148.         $qb->addSelect('f.timeStamp as timeStamp');
  149.         $qb->addSelect('f.created as created');
  150.         $qb->addSelect('f.deleted as deleted');
  151.         $qb->addSelect('f.demo as demo');
  152.         $qb->addSelect('p.id as defaultProducerId');
  153.         $qb $this->addLot$qb );
  154.         // $qb = $this->countLot( $qb );
  155.         // $qb = $this->groupByLot( $qb );
  156.          $this->addAddress$qb );
  157.         $qb->addSelect("CONCAT(addr.address,' - ', addr.state, ' - ', addr.city ) as addressFull");
  158.         $qb $this->addOrganization$qb$organizationId );
  159.         $qb =  $this->addAnimal$qb );
  160.         $qb =  $this->countAnimal$qb$organizationId$farm );
  161.         $qb =  $this->addBlackList$qb );
  162.         $qb =  $this->addFarm$qb$farm );
  163.         $qb =  $this->addProducer$qb );
  164.         $qb =  $this->groupByFarm$qb );
  165.         $qb $this->countLot$qb );
  166.         $qb->addSelect('(
  167.             SELECT COUNT(ed.id)
  168.             FROM App\Entity\EventData ed 
  169.             JOIN App\Entity\Lot led WITH ( ed.lot = led.id and led.deleted = 0)
  170.             WHERE led.farm = f.id and ed.deleted = 0 AND led.status = 1
  171.             ) as countEventData'
  172.         );
  173.         $qb->addSelect('(
  174.             SELECT COUNT(distinct t.id)
  175.             FROM App\Entity\Treatment t 
  176.             WHERE t.farm = f.id and t.deleted = 0 and f.organization = o.id
  177.             ) as countTreatment'
  178.         );
  179.         $qb->addSelect('(
  180.             SELECT COUNT(loc.id)
  181.             FROM App\Entity\Location loc
  182.             WHERE loc.farm = f.id and loc.deleted = 0
  183.             ) as countLocation'
  184.         );
  185.         $this->addCurrentPregnancyStatus$qbself::PREGNANTS ); 
  186.         // $qb->addSelect('f.producer as producer');
  187.         // $qb->addSelect('f.producers as producers');
  188.         // $qb->addSelect('f.locations as locations');
  189.         /* CUD timestamps */
  190.         $qb->addSelect('f.createdAt as createdAt');
  191.         $qb->addSelect('f.updatedAt as updatedAt');
  192.         $qb->addSelect('f.deletedAt as deletedAt');
  193.         return $qb;
  194.     }/*}}}*/
  195.     public function entryHelp$organizationId )
  196.     {/*{{{*/
  197.         $qb $this->createQueryBuilder('f');
  198.         $qb->andWhere('f.deleted = 0');
  199.         $organizationId and $qb->andWhere('f.organization = :organization')
  200.             ->setParameter('organization'$organizationId);
  201.         return $qb;
  202.     }/*}}}*/
  203.     /* de Logica Ligera Inc */
  204.     public function getFarms(User $user)
  205.     {/*{{{*/
  206.         $qb $this->createQueryBuilder('f')
  207.             ->join('f.organization''o')
  208.             ->join('App\Entity\User''u'"with""u.organization = o.id")
  209.             ->join('App\Entity\Producer''p'"with""p.user = u.id")
  210.             ->where('f.deleted =:deleted')
  211.             ->setParameter('deleted'0);
  212.         if (!$user->isAdmin()) {
  213.             $qb->andWhere('p.user =:user')
  214.                 ->setParameter('user'$user);
  215.         }
  216.         $qb->orderBy('f.name''ASC');
  217.         return $qb->getQuery()->getResult();
  218.     }/*}}}*/
  219.     public function addDateFilter($filter = [], $qb)
  220.     {/*{{{*/
  221.         if (!isset($filter['date'])) {
  222.             $today = new \DateTime();
  223.             $firstEventDay = new \DateTime("2020-01-01");
  224.             $dateFilter = [
  225.                 'month_from' => $firstEventDay->format('m'),
  226.                 'month_to' => $today->format('m'),
  227.                 'year_from' => $firstEventDay->format('Y'),
  228.                 'year_to' => $today->format('Y'),
  229.             ];
  230.             $filter = [
  231.                 'date' => $dateFilter,
  232.             ];
  233.         }
  234.         $dateFrom = new \DateTime($filter['date']['year_from'] . "-" $filter['date']['month_from'] . "-01");
  235.         $dateTo = new \DateTime($filter['date']['year_to'] . "-" $filter['date']['month_to'] . "-01");
  236.         $lastDay = new \DateTime(sprintf('last day of %s'$dateTo->format('Y-m')));
  237.         $firstDay = new \DateTime(sprintf('first day of %s'$dateFrom->format('Y-m')));
  238.         if (isset($filter['date'])) {
  239.             if (isset($filter['date']['month_from']) && isset($filter['date']['year_from'])) {
  240.                 $qb->andWhere('DATE(a.created) >= :date_from')
  241.                     ->setParameter('date_from'$firstDay);
  242.             }
  243.             if (isset($filter['date']['month_to']) && isset($filter['date']['year_to'])) {
  244.                 $qb->andWhere('DATE(a.created) <= :date_to')
  245.                     ->setParameter('date_to'$lastDay);
  246.             }
  247.         }
  248.         return $qb;
  249.     }/*}}}*/
  250.     public function getFarmAddress( ?Organization $org )
  251.     {/*{{{*/
  252.         $qb $this->createQueryBuilder('f');
  253.         $qb->select('distinct f.id, f.name, o.name as organizationName, a.latitude, a.longitude, a.address, a.city')
  254.             ->join('App\Entity\Address''a'"with""a.id = f.address OR a.id is NULL")
  255.             ->join('App\Entity\Organization''o'"with""o.id = f.organization")
  256.             ->leftJoin('App\Entity\Lot''l''with''l.farm = f.id OR l.id is NULL')
  257.             ->where('f.deleted = 0 AND f.createdAt != 0');
  258.         $org and $qb->andWhere('o.id = :org')->setParameter('org'$org);
  259.         return $qb->getQuery()->getResult();
  260.     }/*}}}*/
  261.     public function getAllFarmsWithLatAndLngLoaded()
  262.     {/*{{{*/
  263.         $qb $this->createQueryBuilder('f');
  264.         $qb->select('f.id, f.name,o.name as organizationName, a.latitude,a.longitude,a.address,a.city')
  265.             ->join('App\Entity\Address''a'"with""a.id = f.address")
  266.             ->join('App\Entity\Lot''l'"with""f.id = l.farm")
  267.             ->join('App\Entity\Organization''o'"with""o.id = l.organization")
  268.             ->where(" a.longitude <> '' AND a.latitude <> '' ")
  269.             ->andWhere('(f.deleted = 0 OR f.deleted = FALSE)');
  270.         return $qb->getQuery()->getResult();
  271.     }/*}}}*/
  272.     public function getActiveFarmsWithLatAndLngLoaded()
  273.     {/*{{{*/
  274.         $qb $this->createQueryBuilder('f');
  275.         $qb->select('f.id, f.name,o.name as organizationName, a.latitude,a.longitude,a.address,a.city, COUNT(ed.farm) quantity')
  276.             ->join('App\Entity\Address''a'"with""a.id = f.address")
  277.             ->join('App\Entity\EventData''ed'"with""ed.farm = f.id")
  278.             ->join('App\Entity\Organization''o'"with""o.id = ed.organization")
  279.             ->where(" a.longitude <> '' AND a.latitude <> '' ")
  280.             ->andWhere('(f.deleted = 0 OR f.deleted = FALSE)')
  281.             ->groupBy('f.id, o.name')
  282.             ->having('quantity >= 20');
  283.         return $qb->getQuery()->getResult();
  284.     }/*}}}*/
  285.     public function getMostRelevantFarms()
  286.     {/*{{{*/
  287.         $arr = [];
  288.         $result = [];
  289.         $eventsQuantity $this->createQueryBuilder('f');
  290.         $eventsQuantity->select('f.id, f.name,o.name as organizationName, a.latitude,a.longitude,a.address,a.city, COUNT(ed.farm) eventsQuantity')
  291.             ->join('App\Entity\Address''a'"with""a.id = f.address")
  292.             ->join('App\Entity\EventData''ed'"with""ed.farm = f.id")
  293.             ->join('App\Entity\Organization''o'"with""o.id = ed.organization")
  294.             ->where(" a.longitude <> '' AND a.latitude <> '' ")
  295.             ->andWhere('(f.deleted = 0 OR f.deleted = FALSE)')
  296.             ->andWhere('(ed.deleted = 0 OR ed.deleted = FALSE)')
  297.             ->groupBy('f.id, o.name')
  298.             ->orderBy('eventsQuantity''DESC')
  299.             ->setMaxResults(5);
  300.         $eventsQuantity $eventsQuantity->getQuery()->getResult();
  301.         $animalsQuantity $this->createQueryBuilder('f');
  302.         $animalsQuantity->select('f.id, COUNT(a.id) animalsQuantity')
  303.             ->join('App\Entity\Animal''a'"with""a.currentFarm = f.id")
  304.             ->join('App\Entity\Address''a2'"with""a2.id = f.address")
  305.             ->where("(a2.longitude <> '' AND a2.latitude <> '')")
  306.             ->andWhere('(f.deleted = 0 OR f.deleted = FALSE)')
  307.             ->andWhere('a.deleted = 0 OR a.deleted = FALSE')
  308.             ->andWhere("a.createdAt >= a.deletedAt OR a.updatedAt >= a.deletedAt OR a.deletedAt is NULL")
  309.             ->andWhere('a.status = :statusActive')->setParameter('statusActive'Animal::STATUS_ACTIVE)
  310.             ->andWhere('a.currentLot IS NOT NULL')
  311.             ->groupBy('f.id')
  312.             ->orderBy('animalsQuantity''DESC')
  313.             ->setMaxResults(5);
  314.         $animalsQuantity $animalsQuantity->getQuery()->getResult();
  315.         foreach ($eventsQuantity as $key => $value) {
  316.             foreach ($animalsQuantity as $key2 => $value2) {
  317.                 if ($value['id'] === $value2['id']) {
  318.                     $result array_merge($eventsQuantity[$key], $animalsQuantity[$key2]);
  319.                     $result array_push($arr$result);
  320.                 }
  321.             }
  322.         }
  323.         return $arr;
  324.     }/*}}}*/
  325.     public function getFarmByLot(Lot $lotUser $user null)
  326.     {/*{{{*/
  327.         $qb $this->createQueryBuilder('f');
  328.         $qb->join('App\Entity\Lot''l'"with""l.farm = f.id")
  329.             ->where('l.id = :lot')
  330.             ->setParameter('lot'$lot);
  331.         if ($user) {
  332.             $qb->andWhere('l.organization = :organization')
  333.                 ->setParameter('organization'$user->getOrganization());
  334.         }
  335.         $qb->andWhere('l.deleted = 0 OR l.deleted = FALSE');
  336.         return $qb->getQuery()->getOneOrNullResult();
  337.     }/*}}}*/
  338.     public function isDeletable$farmId ) {
  339.         // chequear que la farm tenga organizacion
  340.         $qb $this->createQueryBuilder('f');
  341.         $qb->select("f.id");
  342.         $this->addOrganization$qb );
  343.         $this->addFarm$qb$farmId );
  344.         $result $qb->getQuery()->getResult();
  345.         if ( !isset($result[0]["organizationId"]) ) return false;
  346.         $organizationId $result[0]["organizationId"];
  347.         
  348.         // si la tiene, chequear que esta farm sea la unica que pertenezca a la organizacion
  349.         $qb $this->createQueryBuilder('f');
  350.         $qb->select("f.id");
  351.         $this->addOrganization$qb$organizationId );
  352.         $this->addFarm$qb );
  353.         $result $qb->getQuery()->getResult();
  354.         if ( sizeof($result) <= ) return false// si lo es, no se debe eliminar
  355.         $qb $this->createQueryBuilder('f');
  356.         $qb->select("f.id");
  357.         $this->addLot$qb );
  358.         $this->addFarm$qb$farmId );
  359.         $qb->andWhere("l.deleted = false AND l.status = true" );
  360.         $result $qb->getQuery()->getResult();
  361.         return empty($result); // se podra eliminar si no tiene ningun lote 
  362.     }
  363. }