public function generateIdentification(InvoiceEntity $invoiceEntity) { $date = new \DateTime(); $account = $invoiceEntity->getSupplier(); $format = $account->getIdentificationFormat(); $dateFrom = new \DateTime(); if ($account->getIdentificationInterval() === AccountEntity::INTERVAL_YEAR) { $dateFrom->setTime(0, 0, 0); $dateFrom->setDate($dateFrom->format('Y'), 1, 1); $dateTo = \DateTime::createFromFormat('Y-m-d', intval($dateFrom->format('Y')) + 1 . '-01-01'); $dateTo->setTime(0, 0, 0); } elseif ($account->getIdentificationInterval() === AccountEntity::INTERVAL_MONTH) { $dateFrom->setTime(0, 0, 0); $dateFrom->setDate($dateFrom->format('Y'), $dateFrom->format('m'), 1); $year = intval($dateFrom->format('Y')); $month = intval($dateFrom->format('m')) + 1; if ($month > 12) { $month = $month - 12; $year++; } $dateTo = \DateTime::createFromFormat('Y-m-d', $year . '-' . $month . '-01'); $dateTo->setTime(0, 0, 0); } elseif ($account->getIdentificationInterval() === AccountEntity::INTERVAL_QUARTER) { $month = intval($dateFrom->format('m')); $year = intval($dateFrom->format('Y')); $dateFrom->setTime(0, 0, 0); $dateFrom->setDate($year, $month % 4 * 4, 0); $month = $month + 4; if ($month > 12) { $month = $month - 12; $year++; } $dateTo = \DateTime::createFromFormat('Y-m-d', $year . '-' . $month % 4 * 4 . '-01'); $dateTo->setTime(0, 0, 0); } $qb = $this->invoiceRepository->createQueryBuilder('a')->select('COUNT(a.id)')->andWhere('a.identification IS NOT NULL')->andWhere('a.supplier = :supplier')->setParameter('supplier', $account->id); if (isset($dateTo)) { $qb = $qb->andWhere('a.date >= :dateFrom')->setParameter('dateFrom', $dateFrom)->andWhere('a.date < :dateTo')->setParameter('dateTo', $dateTo); } $identification = intval($qb->getQuery()->getSingleScalarResult()) + 1; if (preg_match_all('/\\?(\\d+)/is', $format, $matches)) { $number = $matches[1][0]; $format = str_replace('?' . $number, sprintf('%0' . $number . 'd', $identification), $format); } $exDate = clone $date; $exDate->modify('+' . $account->getDue() . ' days'); $invoiceEntity->setDate($date); $invoiceEntity->setExpirationDate($exDate); $invoiceEntity->setIdentification($date->format($format)); $this->invoiceRepository->save($invoiceEntity); }