Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // src/Eleven/CRMBundle/Controller/InvoiceController.php
- namespace App\Eleven\CRMBundle\Controller;
- // Symfony
- use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- use Symfony\Component\HttpFoundation\Response;
- use Symfony\Component\Routing\Annotation\Route;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\Form\Extension\Core\Type\SubmitType;
- use Symfony\Component\HttpFoundation\JsonResponse;
- // PDF
- use Dompdf\Dompdf;
- use Dompdf\Options;
- use Symfony\Component\HttpFoundation\BinaryFileResponse;
- // Eleven
- use App\Eleven\FrameworkBundle\Service\SettingManager;
- use App\Eleven\CRMBundle\Entity\Invoice;
- use App\Eleven\CRMBundle\Repository\InvoiceRepository;
- use App\Eleven\CRMBundle\Form\Type\InvoiceFormType;
- use App\Eleven\FrameworkBundle\Repository\DocumentRepository;
- use App\Eleven\FrameworkBundle\Utils\FormUtils;
- use App\Eleven\FrameworkBundle\Service\FileStorageManager;
- use Twig\Extra\Intl\IntlExtension;
- class InvoiceController extends AbstractController
- {
- /**
- * Invoice index with paginator
- *
- * @Route("/invoice/test", name="invoice_test")
- */
- public function test() {
- $invoice = new Invoice('12345');
- dump($invoice->getId());
- $em = $this->getDoctrine()->getManager();
- $em->persist($invoice);
- dump($invoice->getId());
- $em->flush();
- dump($invoice->getId());
- die;
- }
- /**
- * Invoice index with paginator
- *
- * @Route("/invoice", defaults={"page": "1", "_format"="html"}, methods="GET", name="invoice_index")
- * @Route("/invoice/page/{page<[1-9]\d*>}", defaults={"_format"="html"}, methods="GET", name="invoice_index_paginated")
- */
- public function invoiceIndex(int $page, string $_format, InvoiceRepository $invoices) {
- $invoicePaginator = $invoices->findLast($page);
- return $this->render('@ElevenCRM/invoice/index.'.$_format.'.twig', [
- 'paginator' => $invoicePaginator,
- 'defaultRoute' => '/invoice'
- ] );
- }
- /**
- * @route("/invoice/add", name="invoice_add")
- */
- public function invoiceAdd(Request $request, InvoiceRepository $invoices, FileStorageManager $fileStorageManager) {
- $lastUsedInvoiceNumber = $invoices->findNextInvoiceNumber();
- $invoice = new Invoice($lastUsedInvoiceNumber);
- if (!$request->isXmlHttpRequest()) {
- $em = $this->getDoctrine()->getManager();
- $em->persist($invoice);
- }
- return $this->invoiceResponse($invoice, $request, $fileStorageManager);
- }
- /**
- * @Route("/invoice/edit/{id}", name="invoice_edit")
- */
- public function invoiceEdit(Invoice $invoice, Request $request, FileStorageManager $fileStorageManager) {
- return $this->invoiceResponse($invoice, $request, $fileStorageManager);
- }
- /**
- * extra info : double form in 1 post.
- * https://stackoverflow.com/questions/11841166/how-to-get-the-name-of-the-form-symfony2
- */
- private function invoiceResponse($invoice, Request $request, FileStorageManager $fileStorageManager){
- $form = $this->createForm(InvoiceFormType::class, $invoice);
- // fix empty dates with string '__-__-____'
- FormUtils::fixRequestDate($request, 'invoice_form');
- $form->handleRequest($request);
- if ($form->isSubmitted() && $form->isValid()) {
- $invoice = $form->getData();
- echo($invoice->getId());
- die;
- //TODO: transactions https://github.com/doctrine/orm/issues/5759
- $em = $this->getDoctrine()->getManager();
- $em->persist($invoice);
- $em->flush();
- // File
- $file = $form->get('file')->getData();
- if ($file) {
- $document = $fileStorageManager->uploadDocumentFile($file,'invoice',$invoice->getId());
- //dump ($document);
- //die;
- }
- if ($request->isXmlHttpRequest()) {
- return new JsonResponse(array('message' => 'Success!',
- 'id' => $invoice->getId() ,
- 'output' => $this->renderView('@ElevenCRM/invoice/form.html.twig',
- array(
- 'entity' => $invoice,
- 'form' => $form->createView()
- ))
- ),200);
- }
- return $this->redirectToRoute('invoice_index');
- }
- if ($request->isXmlHttpRequest()) {
- return new JsonResponse(array('message' => 'Error',
- 'id' => $invoice->getId() ,
- 'output' => $this->renderView('@ElevenCRM/invoice/form.html.twig',
- array(
- 'entity' => $invoice,
- 'form' => $form->createView()
- ))
- ), 200);
- }
- return $this->render('@ElevenCRM/invoice/invoice.html.twig', array(
- 'id' => $invoice->getId(),
- 'table' => 'invoice',
- 'form' => $form->createView(),
- 'entity' => $invoice,
- 'defaultRoute' => '/invoice'
- ));
- }
- /**
- * @Route("/invoice/delete/{id}", name="invoice_delete")
- */
- public function delete($id, Request $request)
- {
- $em = $this->getDoctrine()->getManager();
- $invoice = $em->getRepository(Invoice::class)->find($id);
- $em->remove($invoice);
- $em->flush();
- if ($request->isXmlHttpRequest()) {
- return new JsonResponse(array('message' => 'Success!',
- 'id' => $id
- ),200);
- }
- return $this->redirectToRoute('invoice_index');
- }
- /**
- * @Route("/invoice/pdf/{id}", name="invoice_pdf")
- */
- public function pdf($id) {
- $em = $this->getDoctrine()->getManager();
- $invoice = $em->getRepository(Invoice::class)->find($id);
- // Configure Dompdf according to your needs
- $pdfOptions = new Options();
- $pdfOptions->set('defaultFont', 'Arial');
- // Instantiate Dompdf with our options
- $dompdf = new Dompdf($pdfOptions);
- // Retrieve the HTML generated in our twig file
- $html = $this->renderView('@ElevenCRM/invoice/invoice_pdf.html.twig', [
- 'invoice' => $invoice
- ]);
- // Load HTML to Dompdf
- $dompdf->loadHtml($html);
- // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
- $dompdf->setPaper('A4', 'portrait');
- // Render the HTML as PDF
- $dompdf->render();
- // Output the generated PDF to Browser (force download)
- $dompdf->stream("invoice_".$invoice->getNumber().".pdf", [
- "Attachment" => true
- // Attachment = true => download pdf file
- // Attachment = false => view pdf file
- ]);
- }
- /**
- * @Route("/invoice/savepdf/{id}", name="invoice_save_pdf")
- */
- public function savePDF($id)
- {
- $em = $this->getDoctrine()->getManager();
- $invoice = $em->getRepository(Invoice::class)->find($id);
- // Configure Dompdf according to your needs
- $pdfOptions = new Options();
- $pdfOptions->set('defaultFont', 'Arial');
- // Instantiate Dompdf with our options
- $dompdf = new Dompdf($pdfOptions);
- // Retrieve the HTML generated in our twig file
- $html = $this->renderView('@ElevenCRM/invoice/invoice_pdf.html.twig', [
- 'invoice' => $invoice
- ]);
- // Load HTML to Dompdf
- $dompdf->loadHtml($html);
- // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
- $dompdf->setPaper('A4', 'portrait');
- // Render the HTML as PDF
- $dompdf->render();
- // Store PDF Binary Data
- $output = $dompdf->output();
- // In this case, we want to write the file in the public directory
- //$publicDirectory = $this->get('kernel')->getProjectDir() . '/public';
- $publicDirectory = '/var/www/vhosts/dev.host.nl/storage';
- // e.g /var/www/project/public/mypdf.pdf
- $pdfFilepath = $publicDirectory . '/mypdf.pdf';
- // Write file to the desired path
- file_put_contents($pdfFilepath, $output);
- // Send some text response
- return new Response("The PDF file has been succesfully generated !");
- }
- /**
- * @Route("/invoice/openpdf/{id}", name="invoice_open_pdf")
- */
- public function openPDF($id) {
- $publicDirectory = '/var/www/vhosts/dev.host.nl/storage';
- $pdfFilepath = $publicDirectory . '/mypdf.pdf';
- return new BinaryFileResponse($pdfFilepath);
- }
- public function getCustomerData() {
- return '';
- }
- /**
- * @Route("/invoice/{id}/document", name="invoice_document")
- * @return JsonResponse
- */
- public function getDocumentView($id, Request $request, DocumentRepository $documents) {
- $paginator = $documents->findLast('invoice', $id);
- if ($request->isXmlHttpRequest()) {
- return new JsonResponse(array('message' => 'Success',
- 'output' => $this->renderView('@ElevenFramework/document/table_view.html.twig',
- array(
- 'id' => $id,
- 'table' => 'invoice',
- 'paginator' => $paginator,
- 'defaultRoute' => '/invoice/'.$id.'/document'
- ))
- ), 200);
- }
- return new Response("XML Http Request Only.");
- }
- }
- //------------------------------------------------
- <?php
- namespace App\Eleven\CRMBundle\Entity;
- //Symfony
- use Symfony\Component\Validator\Constraints as Assert;
- use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
- use Doctrine\ORM\Mapping as ORM;
- //use Symfony\Component\HttpFoundation\Session\Session;
- use Doctrine\Common\Collections\ArrayCollection;
- use Doctrine\Common\Collections\Collection;
- // Eleven
- use App\Eleven\FrameworkBundle\Entity\CompanyAbstractEntity;
- use App\Eleven\CRMBundle\Entity\Customer;
- use App\Eleven\CRMBundle\Entity\InvoiceLine;
- //use App\Eleven\FrameworkExampleBundle\Validator\Constraints as AcmeAssert;
- use App\Eleven\FrameworkBundle\Service\SettingManager;
- /**
- * @ORM\Entity
- *
- * @UniqueEntity(
- * fields={"number"},
- * errorPath="number",
- * message="The invoice number has already been used."
- * )
- */
- class Invoice extends CompanyAbstractEntity {
- protected $settingManager;
- // https://stackoverflow.com/questions/9087585/generating-next-sequence-value-manually-in-doctrine-2
- // https://stackoverflow.com/questions/11079509/how-to-use-entitymanager-inside-entity?lq=1
- /**
- * Set default values.
- */
- public function __construct($number) {
- /*
- global $kernel;
- if ( 'AppCache' == get_class($kernel) ) {
- $kernel = $kernel->getKernel();
- }
- $em = $kernel->getContainer()->get( 'doctrine.orm.entity_manager' );
- $conn = $em->getConnection();
- $sql = "SELECT nextval('invoice_id_seq')";
- $stmt = $conn->prepare($sql);
- $stmt->execute();
- $this->id = $stmt->fetchAll()[0]['nextval'];
- */
- //$this->id = 382;
- $this->status = 'NEW';
- $this->date = new \DateTime();
- $this->invoiceLines = new ArrayCollection();
- }
- /**
- * @ORM\Id()
- * @ORM\Column(type="integer")
- * @ORM\GeneratedValue()
- * _ORM\GeneratedValue(strategy="CUSTOM") //strategy="IDENTITY" // strategy="SEQUENCE"
- * @ORM\SequenceGenerator(sequenceName="invoice_id_seq", allocationSize=1, initialValue=800)
- * _ORM\CustomIdGenerator(class="App\Eleven\FrameworkBundle\Doctrine\Generator\NextvalIdGenerator")
- */
- protected $id;
- /**
- * invoice number
- * @ORM\Column(type="integer" , nullable=true)
- */
- private $number;
- /**
- * @ORM\Column(type="date")
- */
- private $date;
- /**
- *
- * @ORM\ManyToOne(targetEntity="App\Eleven\CRMBundle\Entity\Customer")
- * @ORM\JoinColumn(nullable=true)
- */
- private $customer;
- /**
- * @ORM\Column(type="string", length=100, nullable=true)
- */
- private $reference;
- ///**
- // * @ORM\Column(type="boolean", nullable=true )
- // * @var boolean
- // */
- //private $sent;
- /**
- * @ORM\Column(type="string", length=100, nullable=true )
- */
- private $status;
- /**
- * @ORM\Column(type="boolean", nullable=true )
- * @var boolean
- */
- private $proforma;
- /**
- * @ORM\OneToMany(targetEntity="App\Eleven\CRMBundle\Entity\InvoiceLine", mappedBy="invoice", orphanRemoval=true, cascade={"persist"})
- * @ORM\JoinColumn(nullable=true)
- */
- private $invoiceLines;
- public function getId() {
- return $this->id;
- }
- public function setId(?int $id) {
- $this->id = $id;
- return $this;
- }
- public function getNumber(): ?string {
- return $this->number;
- }
- public function setNumber(?string $number): self {
- $this->number = $number;
- return $this;
- }
- public function getDate(): ?\DateTimeInterface {
- return $this->date;
- }
- public function setDate(?\DateTimeInterface $date): self {
- $this->date = $date;
- return $this;
- }
- public function getCustomer(): ?Customer {
- return $this->customer;
- }
- public function setCustomer(?Customer $customer): self {
- $this->customer = $customer;
- return $this;
- }
- public function getReference(): ?string {
- return $this->reference;
- }
- public function setReference(?string $reference): self {
- $this->reference = $reference;
- return $this;
- }
- public function getStatus(): ?string {
- return $this->status;
- }
- public function setStatus(?string $status): self {
- $this->status = $status;
- return $this;
- }
- //TODO: fix to quotation
- public function getProforma(): ?bool {
- return $this->proforma;
- }
- public function setProforma(?bool $proforma): self {
- $this->proforma = $proforma;
- return $this;
- }
- /**
- * @return Collection|InvoiceLine[]
- */
- public function getInvoiceLines(): Collection {
- return $this->invoiceLines;
- }
- public function addInvoiceLine(InvoiceLine $invoiceLine): self {
- if (!$this->invoiceLines->contains($invoiceLine)) {
- $this->invoiceLines[] = $invoiceLine;
- $invoiceLine->setInvoice($this);
- }
- return $this;
- }
- public function removeInvoiceLine(InvoiceLine $invoiceLine): self {
- if ($this->invoiceLines->contains($invoiceLine)) {
- $this->invoiceLines->removeElement($invoiceLine);
- // set the owning side to null (unless already changed)
- if ($invoiceLine->getInvoice() === $this) {
- $invoiceLine->setInvoice(null);
- }
- }
- return $this;
- }
- public function getTotalInvoiceLines() {
- return count($this->invoiceLines);
- }
- public function getTotalAmount() {
- $totalAmount = 0;
- foreach ($this->invoiceLines as $invoiceLine) {
- $totalAmount += $invoiceLine->getAmount();
- }
- return $totalAmount;
- }
- }
Add Comment
Please, Sign In to add comment