src/EventSubscriber/InvoiceSubscriber.php line 43

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\FikenApiToken;
  5. use App\Entity\Invoice;
  6. use App\Entity\User;
  7. use App\Fiken\Api\ApiEndpoint;
  8. use App\Fiken\Api\Client;
  9. use App\Fiken\Api\Collection\CompanyCollection;
  10. use App\Fiken\Api\Entity\InvoiceDraft;
  11. use App\Fiken\Api\FikenEnv;
  12. use App\Fiken\Api\Token;
  13. use App\Repository\FikenApiTokenRepository;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Ramsey\Uuid\Uuid;
  16. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  17. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpKernel\Event\ViewEvent;
  20. use Symfony\Component\HttpKernel\KernelEvents;
  21. use Symfony\Component\Mailer\MailerInterface;
  22. use Symfony\Component\Security\Core\Security;
  23. use Symfony\Component\Security\Core\User\UserInterface;
  24. final class InvoiceSubscriber implements EventSubscriberInterface {
  25.     public function __construct(
  26.         private EntityManagerInterface $entityManagerInterface
  27.         private Security $security,
  28.         private MailerInterface $mailerInterface
  29.     ) {}
  30.     public static function getSubscribedEvents() {
  31.         return [
  32.             KernelEvents::VIEW => [
  33.                 'makeInvoiceDraft'EventPriorities::POST_WRITE
  34.             ],
  35.         ];
  36.     }
  37.     public function makeInvoiceDraft(ViewEvent $event) {
  38.         $instance $event->getControllerResult();
  39.         $method $event->getRequest()->getMethod();
  40.         if (!$instance instanceof Invoice || Request::METHOD_POST !== $method)
  41.             return;
  42.         $invoice = (fn(Invoice $i): Invoice => $i)($instance);
  43.         $repo $this->entityManagerInterface->getRepository(FikenApiToken::class);
  44.         $user $this->entityManagerInterface->getRepository(User::class)->findOneBy(['email' => 'post@giaever-vertskap.no']);
  45.         $sender = (fn(UserInterface $u): User => $u)($this->security->getUser());
  46.         try {
  47.             $token = (
  48.                 fn(FikenApiTokenRepository $repo): FikenApiToken => $repo->getLeastFrequentlyUsed($user)
  49.             )($repo);
  50.             if ($token == null)
  51.                 throw new \Exception("Missing Fiken Token for user: " $user->getEmail());
  52.             $env FikenEnv::PROD;
  53.             $slug $env == FikenEnv::DEBUG 'fiken-demo-garn-og-glod-as3' 'giaever-vertskap-as';
  54.             $client = new ApiEndpoint(new Client(
  55.                 $token->getToken(),
  56.                 function (Token $t) use ($token): void {
  57.                     $this->entityManagerInterface->persist($token->setToken($t));
  58.                     $this->entityManagerInterface->flush();
  59.                 },
  60.                 $env
  61.             ));
  62.             $companies = (fn(ApiEndpoint $c): CompanyCollection => 
  63.                 $c->getCompanies()->load()
  64.             )($client);
  65.             $company $companies->getOneBy(['slug' => $slug]);
  66.             $invoices $company->getInvoices();
  67.             $now = new \DateTimeImmutable();
  68.             $issueDate = new \DateTimeImmutable($invoice->getMonth()->format('Y-m-t'));
  69.             $issueMax 16;
  70.             if ($issueDate $now)
  71.                 $issueDate $now;
  72.             else if ($issueDate->add(new \DateInterval(sprintf('P%dD'$issueMax))) < $now)
  73.                 $issueDate $now;
  74.             // dd($invoice->getMappedInvoiceEntries($client->getClient()->getEnv()));
  75.             $invoices->addEntry(InvoiceDraft::createFromJson(
  76.                 $invoices, [
  77.                     'uuid' => $uuid Uuid::uuid4(),
  78.                     'type' => 'invoice',
  79.                     'issueDate' => $issueDate->format('Y-m-d'),
  80.                     'daysUntilDueDate' => ($invoice->getProperty()->getOwner()->getDaysUntilDue() ?? $issueMax) + $issueDate->diff($now)->days,
  81.                     'customerId' => $invoice->getProperty()->getOwner()->getCustomerId($client->getClient()->getEnv()),
  82.                     'projectId' => $invoice->getProperty()->getProjectId($client->getClient()->getEnv()),
  83.                     'invoiceText' => sprintf(
  84.                         "Hei, {kundenavn}, her kommer faktura for prosjektet «%s».\n\nVennligst se fakturaspesifikasjon. Skulle noe være uklart er det bare ta kontakt.",
  85.                         $invoice->getProperty()->getSection()
  86.                     ),
  87.                     'lines' => $invoice->getMappedInvoiceEntries($client->getClient()->getEnv())
  88.                 ]
  89.             ));
  90.             $invoice->setExternalUuid($uuid);
  91.             $this->entityManagerInterface->persist($invoice);
  92.             $this->entityManagerInterface->flush();
  93.             return $this->mailerInterface->send(
  94.                 (new TemplatedEmail())
  95.                     ->to(...array_unique([$user->getEmail(), $sender->getEmail()]))
  96.                     ->from('post@giaever-vertskap.no')
  97.                     ->subject('New invoice-draft sendt to Fiken')
  98.                     ->addCc($sender->getEmail())
  99.                     ->htmlTemplate('emails/invoice.summary.html.twig')
  100.                     ->context([
  101.                         'sender' => $sender,
  102.                         'invoice' => $invoice,
  103.                         'lines' => $invoice->getMappedInvoiceEntries($client->getClient()->getEnv())
  104.                     ])
  105.                 );
  106.         } catch (\Exception $e) {
  107.             return $this->mailerInterface->send(
  108.                 (new TemplatedEmail())
  109.                     ->to(...array_unique([$user->getEmail(), $sender->getEmail()]))
  110.                     ->from('post@giaever-vertskap.no')
  111.                     ->subject('Failed sending in the invoice')
  112.                     ->htmlTemplate('emails/exception.html.twig')
  113.                     ->context([
  114.                         'exception' => $e,
  115.                         'invoice' => $invoice,
  116.                     ])
  117.                 );
  118.         }
  119.         // $changes = json_decode($event->getRequest()->getContent(), true);
  120.         // if (isset($changes['guests'])) {
  121.         //     $prev = $booking->getPreviousBooking();
  122.         //     if (!$prev || $prev->getCheckout()->diff(new \DateTime())->days > 2)
  123.         //         return;
  124.         //     $recepients = [ !$prev->isClean() && $prev->getResponsible() ? $prev->getResponsible()->getEmail() : 'post@giaever-vertskap.no' ];
  125.         //     if ($prev->getResponsible() !== null && !$prev->isClean())
  126.         //         $recepients = array_merge($recepients, array_map(function (User $u): string {
  127.         //             return $u->getEmail();
  128.         //         }, array_filter($this->em->getRepository(User::class)->findBy(['company' => $prev->getResponsible()->getCompany()]), function (User $u): bool {
  129.         //             return in_array('ROLE_MANAGER', $u->getRoles());
  130.         //         })));
  131.         //     $recepients = array_unique($recepients);
  132.         //     return $this->mailer->send(
  133.         //         (new TemplatedEmail())
  134.         //             ->to(...$recepients)
  135.         //             ->from('post@giaever-vertskap.no')
  136.         //             ->subject(sprintf("Amount of guests updated by %s", $this->security->getUser()->getName()))
  137.         //             ->htmlTemplate('emails/booking.guests.alert.html.twig')
  138.         //             ->context([
  139.         //                 "user" => $this->security->getUser(),
  140.         //                 "previous" => $prev,
  141.         //                 "upcoming" => $booking,
  142.         //             ])
  143.         //     );
  144.         // } else if (isset($changes['clean'])) {
  145.         //     $email = (new TemplatedEmail())
  146.         //         ->to('post@giaever-vertskap.no')
  147.         //         ->from('post@giaever-vertskap.no')
  148.         //         ->replyTo($this->security->getUser()->getEmail())
  149.         //         ->subject(sprintf("Clean alert: %s (%s)",
  150.         //             $booking->getProperty()->getAddress()['address'],
  151.         //             $booking->getProperty()->getSection()
  152.         //         ))
  153.         //         ->htmlTemplate('emails/property.clean.alert.html.twig')
  154.         //         ->context([
  155.         //             "booking" => $booking,
  156.         //             "request" => var_export($changes, true)
  157.         //         ]);
  158.         //     return $this->mailer->send($email);
  159.         // } else if (isset($changes['drivingTimeUsage']) || isset($changes['timeUsage'])) {
  160.         //     $email = (new TemplatedEmail())
  161.         //         ->to('post@giaever-vertskap.no')
  162.         //         ->from('post@giaever-vertskap.no')
  163.         //         ->replyTo($this->security->getUser()->getEmail())
  164.         //         ->subject(sprintf('%s time usage updated', isset($changes['drivingTimeUsage']) ? 'Driving' : 'Cleaning'))
  165.         //         ->htmlTemplate('emails/property.clean.time-usage.alert.html.twig')
  166.         //         ->context([
  167.         //             "booking" => $booking,
  168.         //             "type" => isset($changes['drivingTimeUsage']) ? 'driving' : 'cleaning'
  169.         //         ]);
  170.         // }
  171.     }
  172. }