<?php
namespace App\Controller\Finance;
use App\Entity\Finance\Invoice;
use App\Entity\Finance\InvoiceProduct;
use App\Entity\Finance\NoInvoice;
use App\Entity\Kernel\Contact;
use App\Form\Finance\InvoiceType;
use App\Form\Finance\InvoiceProfitType;
use App\Form\Finance\InvoiceForContractType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
use App\Service\Kernel\KernelService;
use App\Entity\Kernel\ListItem;
use App\Entity\Kernel\Setting;
use App\Service\Finance\InvoiceService;
use App\Service\Finance\ContractService;
use App\Entity\CRM\Client;
use App\Service\CRM\ClientService;
use App\Service\Kernel\DMSService;
use App\Service\Kernel\MailService;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormError;
/**
* @Route("/{_locale}/invoice")
*/
class InvoiceController extends AbstractController {
/**
* @Route("/index/{status?99}/{type?0}/{month?empty}", name="invoice_index", methods={"GET"})
*/
public function index(int $status = 99, string $month = "",int $type = 0, InvoiceService $invoiceService): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute);
if ($month == "empty")
{
$month = "";
}
/*$entityManager = $this->getDoctrine()
->getManager();
$tempcountersetting = $entityManager->getRepository(Setting::class)->findOneBy(array('identifier' => "tempcounter", 'state' => 0));
$counter = $tempcountersetting->getValue();
$invoices = $this->getDoctrine()->getRepository(Invoice::class)->findBy(array('state' => 0), null,500,$counter);
foreach($invoices as $invoice)
{
$invoice = $invoiceService->updateProfitInfo($invoice);
$counter++;
}
$tempcountersetting->setIntegerValue($counter);
$entityManager->persist($tempcountersetting);
$entityManager->flush(); */
return $this->render('finance/invoice/index.html.twig', [
'status' => $status,
'month' => $month,
'type' => $type,
]);
}
/**
* @Route("/monthly_follow_up/{type}", name="invoice_monthly_follow_up", methods={"GET"})
*/
public function monthly_follow_up(int $type = 0, int $status = 99, string $month = ""): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute);
$month = new \DateTime("first day of last month");
return $this->render('finance/invoice/index.html.twig', [
'status' => 99,
'month' => $month->format('Y-m-d'),
'type' => $type,
]);
}
/**
* @Route("/table/{state}/{status}/{month}/{type}", name="invoice_table", methods={"GET"})
*/
public function table(int $state, int $status = 99, string $month = "",int $type = 0): Response
{
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute);
return $this->render('finance/invoice/table.html.twig', [
'state' => $state,
'status' => $status,
'month' => $month,
'type' => $type,
]);
}
/**
* @Route("/tabledetails/{state}/{status?99}/{month?}/{type?0}", name="invoice_tabledetails", methods={"GET","POST"})
*/
public function tabledetails(Request $request, int $state, int $status = 99, ?string $month = "",int $type = 0, TranslatorInterface $translator, KernelService $kernelService, DMSService $dmsservice) : Response {
if ($month == null)
{
$month="";
}
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute);
$start = $request->get('start');
$length = $request->get('length');
$em = $this->getDoctrine()->getManager();
$organization = $this->getUser()->getOrganization();
if ($organization == null)
{
$organizationid = 0;
}
else
{
$organizationid = $organization->getId();
}
if ($request->get('search') != null)
{
$filter = $request->get('search')['value'];
$columns = $request->get('columns');
$order = $request->get('order');
$orderColumn = $order[0]["column"];
$orderby = $this->orderColumns($orderColumn);
$direction = strtoupper($order[0]["dir"]);
} else
{
$filter = "";
$orderColumn = "0";
$orderby = $this->orderColumns($orderColumn);
$direction = "desc";
}
$monthLastDay = null;
$monthFirstDay = null;
if (empty($month) != true)
{
$param = strtotime($month);
$monthLastDay = date('Y-m-t', $param);
$monthFirstDay= date('Y-m-01', $param);
}
$extra = "";
if ($status != 99)
{
if ($status == 98)
{
$extra = " AND (((s.dueDate is not null) AND (s.dueDate < ?3)) AND s.processState != 2)";
} else
{
$extra = " AND s.processState = " . $status;
}
}
if (empty($month) != true)
{
$query = $em->createQuery("SELECT s FROM App\Entity\Finance\Invoice s WHERE ((s.state = ?1) AND ((?2 = 0) or ((s.organization = ?2) "
. "or (s.organization is null)))) "
. "AND ((s.invoiceDate >= '".$monthFirstDay."') "
. "AND (s.invoiceDate <= '".$monthLastDay."')) "
. $extra. " ORDER BY ".$orderby." ".$direction);
}
else
{
if(empty($filter) == true){
$query = $em->createQuery("SELECT s FROM App\Entity\Finance\Invoice s WHERE ((s.state = ?1) AND ((?2 = 0) or ((s.organization = ?2) "
. "or (s.organization is null))))". $extra. " ORDER BY ".$orderby." ".$direction);
}else{
$query = $em->createQuery("SELECT s FROM App\Entity\Finance\Invoice s LEFT JOIN s.contract t LEFT JOIN t.contractsElement u LEFT JOIN t.client v LEFT JOIN t.endClient w LEFT JOIN u.employee x WHERE ((s.state = ?1) AND ((?2 = 0) or ((s.organization = ?2) "
. "or (s.organization is null)))) "
. "AND ((s.invoiceNumber LIKE '%".$filter."%') "
. "or (s.about LIKE '%".$filter."%') "
. "or (s.totalWithTaxAmount LIKE '%".$filter."%') "
. "or (s.invoiceDate LIKE '%".$filter."%') "
. "or (s.clientstring LIKE '%".$filter."%') "
. "or (v.company LIKE '%".$filter."%') "
. "or (w.company LIKE '%".$filter."%') "
. "or (concat(x.firstname,' ', x.lastname) LIKE '%".$filter."%')) "
. $extra. " ORDER BY ".$orderby." ".$direction);
}
}
$count = $query->setParameter(2, $organizationid)
->setParameter(1, $state);
if ($status == 98)
{
$query->setParameter(3, new \DateTime());
}
$total = count($count->getResult());
$query = $query->setMaxResults($length)
->setFirstResult($start);
$invoices = $query->getResult();
$twig = clone $this->get('twig');
$timezone = new \DateTimeZone($this->getUser()->getTimezone());
$datawithlinks = array();
$applicationfolder = $dmsservice->createFolderIfNeeded("System");
$invoicefolder = $dmsservice->createFolderIfNeeded("Invoice", $applicationfolder);
$totalpayed = 0;
$totaloutstanding = 0;
$totalamount = 0;
$totalcost = 0;
$totalmonthprofit = 0;
$currency = "";
foreach($invoices as $row){
$newrow = array();
$url = $twig->createTemplate("{{ path('invoice_show', {'id' : id}) }}")->render(array("id" => $row->getId()));
if ($row->getPdf())
{
$urlPDF = $twig->createTemplate("{{ path('kernel_file_version_inline', {'id' : id}) }}")->render(array("id" => $row->getPdf()->getLastKernelFileVersion()->getId()));
$urlPDF = "<a href='".$urlPDF ."' type='button' class='btn btn-primary newwindow' >Invoice</a>";
} else
{
$urlPDF = "";
}
$urldocuments = "";
$folder = $dmsservice->createFolderIfNeeded("".$row->getId(), $invoicefolder);
foreach($folder->getActiveKernelfiles() as $file)
{
$temp = $twig->createTemplate("{{ path('kernel_file_version_inline', {'id' : id}) }}")->render(array("id" => $file->getLastKernelFileVersion()->getId()));
$urldocuments = $urldocuments."<a href='".$temp ."' type='button' class='btn btn-primary newwindow' >Timesheet</a>";
}
$urltransaction = "";
if ($row->getAccounttransaction())
{
$urltransaction = $twig->createTemplate("{{ path('app_account_transaction_show', {'id' : id}) }}")->render(array("id" => $row->getAccounttransaction()->getId()));
$urltransaction = "<a href='".$urltransaction ."' >".$row->getAccounttransaction()."</a>";
} else
{
$urltransaction = "";
}
$newrow[0] = "".$row;
$newrow[1] = $url;
if ($row->getContract() != null)
{
$element = null;
foreach ($row->getContract()->getContractsElement() as $element2)
{
if ($element2->getState() == 0)
{
$element =$element2;
}
}
if ($element != null)
{
$newrow[2] = "".$element->getEmployee(). " - ". $row->getContract()->getClient() ." - ". $row->getContract()->getEndClient();
} else
{
$newrow[2] = "". $row->getContract();
}
} else
{
$newrow[2] = "".$row->getAbout();
}
$newrow[3] = $translator->trans($row->getStatusString());
if (empty($month) == true)
{
$newrow[4] = "".$row->getClient();
$newrow[5] = "".$row->getCurrency()->getString2() . $row->getTotalAmount();
$newrow[6] = $row->getInvoiceDate()->format('d/m/Y');
$newrow[7] = $row->getInvoiceDate()->format('Y-m');
$i=8;
if( $kernelService->getApplicationInfoValue("Finance.ShowInvoicePDFInOverview") == true)
{
$newrow[$i] = $urlPDF;
$i++;
}
if( $kernelService->getApplicationInfoValue("Finance.ShowDocumentsInOverview") == true)
{
$newrow[$i] = $urldocuments;
$i++;
}
$organization = $this->getUser()->getOrganization();
if ($organization == null)
{
$newrow[$i] = "".$row->getOrganization();
}
} else
{
if ($type == 0)
{
$newrow[4] = $urltransaction;
$newrow[5] = "".$row->getCurrency()->getString2() . $row->getTotalWithTaxAmount();
$payed = 0;
if ($row->getProcessState() == 2)
{
if ($row->getAccounttransaction() == null)
{
$payed = $row->getTotalWithTaxAmount();
}
else
{
if (count($row->getAccounttransaction()->getInvoices()) == 1)
{
$payed = $row->getAccounttransaction()->getAmount();
}
else
{
$payed = $row->getTotalWithTaxAmount();
}
}
}
$totalpayed = $totalpayed + $payed;
$topay = $row->getTotalWithTaxAmount() - $payed;
$totaloutstanding = $totaloutstanding + $topay;
$currency = $row->getCurrency()->getString2();
$newrow[6] = "".$row->getCurrency()->getString2() . $payed;
$newrow[7] = "".$row->getCurrency()->getString2() . $topay;
$i= 8;
}
else
{
$difference = 0;
$intakeprice = 0;
$newrow[3] = "".$row->getCurrency()->getString2() . $row->getTotalAmount();
$totalamount = $totalamount + $row->getTotalAmount();
$element = null;
/*if ($row->getContract() != null)
{
foreach ($row->getContract()->getContractsElement() as $element2)
{
if ($element2->getState() == 0)
{
$element =$element2;
}
}
if ($element != null)
{
$newrow[4] = "".$row->getCurrency()->getString2().$element->getIntakePrice();
$newrow[5] = "".$row->getCurrency()->getString2().$element->getUnitPrice();
$intakeprice = $element->getIntakePrice();
$difference = $element->getUnitPrice() - $element->getIntakePrice();
$newrow[6] = "".$row->getCurrency()->getString2().$difference;
} else
{
$newrow[4] = "";
$newrow[5] = "";
$newrow[6] = "";
}
} else
{
$newrow[4] = "";
$newrow[5] = "";
$newrow[6] = "";
}*/
$newrow[4] = "" . $row->getCurrency()->getString2() . $row->getIntakeRate();
$newrow[5] = "" . $row->getCurrency()->getString2() . $row->getUnitPrice();
$intakeprice = $row->getIntakeRate();
$difference = $row->getUnitPrice() - $row->getIntakeRate();
$newrow[6] = "" . $row->getCurrency()->getString2() . $difference;
$days = $row->getDaysInvoiced();
$hours = $days*8;
/*$hoursproduct = null;
foreach ($row->getInvoiceproducts() as $product) {
if ($product->getState() == 0) {
if ($product->getName() == "Hours")
{
$hoursproduct = $product;
$hours = $product->getQuantity();
}
}
}*/
//$extrafilter = $extrafilter . " AND ((s.startDate <= '". date ('Y-m-d') . "') AND (s.endDate is null or s.endDate >= '". date ('Y-m-d') . "'))";
$invoicetime = new \DateTime($month);
$employee = false;
if (($row->getProfitCalculationMethod() != null) &&($row->getProfitCalculationMethod()->getName() == "ProfitCalculationMethod.Employee"))
{
$employee = true;
}
$workingfactor = $row->getWorkingDaysPerWeek()/5;
$newrow[7] = "".$hours;
if ($employee)
{
$extrafactor = 1;
if ($invoicetime->format('m') == 6)
{
$extrafactor = 2;
}
if ($invoicetime->format('m') == 12)
{
$extrafactor = 1.92;
}
$costinvoice = round($intakeprice*208/13.92*$extrafactor*$workingfactor, 2);
} else
{
$costinvoice = round($hours/8*$intakeprice*$workingfactor, 2);
}
$totalcost = $totalcost + $costinvoice;
if ($costinvoice != 0)
{
$newrow[8] = "".$row->getCurrency()->getString2().$costinvoice;
$newrow[9] = "".$row->getCurrency()->getString2() . ($row->getTotalAmount()-$costinvoice);
$totalmonthprofit = $totalmonthprofit + ($row->getTotalAmount()-$costinvoice);
} else {
$newrow[8] = "";
$newrow[9] = "".$row->getCurrency()->getString2() . $row->getTotalAmount();
$totalmonthprofit = $totalmonthprofit + $row->getTotalAmount();
}
$i = 10;
}
$organization = $this->getUser()->getOrganization();
if ($organization == null)
{
$newrow[$i] = "".$row->getOrganization();
}
}
$datawithlinks[] = $newrow;
}
$return = array(
"draw" => intval($request->get('draw')),
"recordsTotal" => $total,
"recordsFiltered" => $total,
"payed" => "". $currency . number_format($totalpayed,2,",","."),
"remaining" => "". $currency . number_format($totaloutstanding,2,",","."),
"totalamount" => "". $currency . number_format($totalamount,2,",","."),
"totalcost" => "". $currency . number_format($totalcost,2,",","."),
"totalmonthprofit" => "". $currency . number_format($totalmonthprofit,2,",","."),
"aaData" => $datawithlinks);
$return = json_encode($return);
return new Response($return,200,array('Content-Type' => 'application/json'));
}
public function orderColumns($orderColumn){
$orderby = "";
switch($orderColumn){
case 0:
$orderby = "s.invoiceNumber"; // i don't think this works
break;
case 2:
$orderby = "s.about";
break;
case 3:
$orderby = "s.processState";
break;
case 4:
$orderby = "s.clientstring";
break;
case 5:
$orderby = "s.totalWithTaxAmount"; // total amount don't work
break;
case 6:
$orderby = "s.invoiceDate";
break;
}
return $orderby;
}
/**
* @Route("/new", name="invoice_new", methods={"GET","POST"})
*/
public function new(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice): Response
{
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute);
$entityManager = $this->getDoctrine()
->getManager();
$postcodes = array();
$municipalities = array();
$organization = $this->getUser()->getOrganization();
if ($organization != null)
{
$organization = $organization->getId();
}
else
{
$organization = -1;
}
if ($request->isMethod('POST'))
{
$requestdata = $request->request->all("invoice");
if (isset($requestdata['postcode']) == true)
{
$postcodeid = $requestdata['postcode'];
$postcodeidvalue = $requestdata['postcode'];
if (empty($postcodeid) == false)
{
$type2 = substr($postcodeid, 0, 8);
$postcodeidsub = substr($postcodeid, 8);
if ($type2 == "INTERNAL")
{
$item = $entityManager->getRepository(ListItem::class)->findOneById($postcodeidsub);
$postcodeidvalue = $item->getString1();
}
}
$postcodes[$postcodeidvalue] = $postcodeid;
}
}
if ($request->isMethod('POST'))
{
$requestdata = $request->request->all("invoice");
if (isset($requestdata['municipality']) == true)
{
$municipalityid = $requestdata['municipality'];
$municipalityidvalue = $requestdata['municipality'];
if (empty($municipalityid) == false)
{
$type2 = substr($municipalityid, 0, 8);
$municipalityidsub = substr($municipalityid, 8);
if ($type2 == "INTERNAL")
{
$item = $entityManager->getRepository(ListItem::class)->findOneById($municipalityidsub);
$municipalityidvalue = $item->getName();
}
}
$municipalities[$municipalityidvalue] = $municipalityid;
}
}
$invoice = new Invoice();
$date = new \DateTime();
$invoice->setInvoiceDate($date);
$invoice->setInvoiceNumber($invoiceService->nextInvoiceNumber($date, $this->getUser()->getOrganization()));
$invoice->setCurrency($kernel_service->getApplicationInfoValue('Kernel.DefaultCurrency'));
$invoice->setLanguage($this->getUser()->getLocale());
$form = $this->createForm(InvoiceType::class, $invoice,
['postcode' => $postcodes, 'municipality' => $municipalities, 'organization' => $organization,
'action' => $this->generateUrl('invoice_new'), 'attr' => ['id' => $this->generateUrl('invoice_new')], 'organization' => $this->getUser()->getOrganization()]);
if ($this->getUser()->getOrganization() == null) {
$form->add('organization', null, array('label' => 'Organization',
'query_builder' => function ($repository) {
return $repository->createQueryBuilder('s')->where("s.state = 0");
},
'attr' => ['class' => 'select2']));
}
$form->handleRequest($request);
$continue = true;
if ($form->isSubmitted()) {
$requestdata = $request->get('invoice');
if (isset($requestdata['clientselect2']) == false) {
$errormessage = $translator->trans('Mandatory');
$form->get('clientselect2')->addError(new FormError($errormessage));
$continue = false;
}
}
if ($form->isSubmitted() && ($continue == true)) {
$requestdata = $request->get('invoice'); //dubbel
if (isset($requestdata['clientselect2']) == true) {
$clientselect2 = $requestdata['clientselect2'];
$client = null;
$clienttype = substr($clientselect2, 0, 2);
$clientid = substr($clientselect2, 2);
// CASE
if ($clienttype == "SU") {
$invoice->setClient($entityManager->getRepository(Client::class)->findOneById($clientid));
} else {
$postcode = null;
$municipality = null;
$requestdata = $request->request->all("invoice");
if (isset($requestdata['postcode']) == true)
{
$postcodeid = $requestdata['postcode'];
if (empty($postcodeid) == false) {
$type2 = substr($postcodeid, 0, 8);
$postcodeid = substr($postcodeid, 8);
if ($type2 == "INTERNAL") {
$item = $entityManager->getRepository(ListItem::class)->findOneById($postcodeid);
$postcode = $item->getString1();
} else {
$postcode = $requestdata['postcode'];
}
}
}
else
{
$postcode = "";
}
if (isset($requestdata['municipality']) == true)
{
$municipalityid = $requestdata['municipality'];
if (empty($municipalityid) == false) {
$type2 = substr($municipalityid, 0, 8);
$municipalityid = substr($municipalityid, 8);
if ($type2 == "INTERNAL") {
$item = $entityManager->getRepository(ListItem::class)->findOneById($municipalityid);
$municipality = $item->getName();
} else {
$municipality = $requestdata['municipality'];
}
}
}
else
{
$municipality = "";
}
if ($clienttype == "NC") {
$client = $clientservice->CreateCompany(
$clientid, $requestdata['tax'], null, null, null,$invoice->getLanguage(), $requestdata['street'], $requestdata['housenumber'], $postcode,$municipality, null, null, null, null, null, null, null, null, null, null, null, null,
$invoice->getOrganization()
);
$invoice->setClient($client);
}
if ($clienttype == "NI") {
$client = $clientservice->CreateIndividual(
$clientid, $requestdata['firstname'], null, null, null, null, $invoice->getLanguage(), $requestdata['street'], $requestdata['housenumber'], $postcode, $municipality, null, null, null, null, null, null, null, null, null, null, null,
$invoice->getOrganization()
);
$invoice->setClient($client);
}
}
}
if ($this->getUser()->getOrganization() != null) {
$invoice->setOrganization($this->getUser()->getOrganization());
}
if ($invoiceService->checkForDuplicates($invoice)) {
$invoice = $invoiceService->createInvoice($invoice->getClient()->getId(),
$invoice->getInvoiceDate()->format('Y-m-d'), $invoice->getInvoiceNumber(),$invoice->getAbout(), $invoice->getNote(),
$invoice->getLanguage(),
$invoice->getSalesCondition()->getId(),
$invoice->getOrganization());
$this->denyAccessUnlessGranted($attribute, $invoice);
return $this->redirectToRoute('invoice_show'
,array('id' => $invoice->getId())
);
} else {
$this->showErrorMessageMustBeUnique($translator);
}
}
return $this->render('finance/invoice/new.html.twig', [
'invoice' => $invoice,
'form' => $form->createView(),
]);
}
/**
* @Route("/newforcontract", name="invoice_newforcontract", methods={"GET","POST"})
*/
public function newforcontract(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice, DMSService $dmsservice): Response
{
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute);
$entityManager = $this->getDoctrine()
->getManager();
$organization = $this->getUser()->getOrganization();
$invoice = new Invoice();
$date = new \DateTime();
$invoice->setInvoiceDate($date);
$invoice->setInvoiceNumber($invoiceService->nextInvoiceNumber($date, $this->getUser()->getOrganization()));
$invoice->setCurrency($kernel_service->getApplicationInfoValue('Kernel.DefaultCurrency'));
$invoice->setLanguage($this->getUser()->getLocale());
$form = $this->createForm(InvoiceForContractType::class, $invoice,
[ 'organization' => $organization,
'action' => $this->generateUrl('invoice_newforcontract'),
'attr' => ['id' => $this->generateUrl('invoice_newforcontract')], 'organization' => $this->getUser()->getOrganization()]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$invoice->setClient($invoice->getContract()->getClient());
if ($invoiceService->checkForDuplicates($invoice)) {
$items = $request->request->get('invoice_for_contract');
$input = $request->files->get('invoice_for_contract');
$extra = "";
foreach ($invoice->getContract()->getContractsElement() as $element)
{
if ($element->getState() == 0)
{
if ($invoice->getContract()->getType()->getInteger1() == 2)
{
$extra = "". $element->getEmployee();
}
}
}
$extra2 = "";
if (empty($invoice->getContract()->getAttachmentNumber()) == false)
{
$extra2 = " - " . $invoice->getContract()->getAttachmentNumber();
}
$contract = $invoice->getContract();
$subject = $invoice->getContract()->getContractNumber().$extra2 . " : " . $extra. " - services related to the period " . $invoice->getInvoiceDate()->format('M Y');
$invoice = $invoiceService->createInvoice($invoice->getClient()->getId(),
$invoice->getInvoiceDate()->format('Y-m-d'), null,$subject, null,
$invoice->getClient()->getLanguage(),
$invoice->getContract()->getSalesCondition()->getId(),
$invoice->getContract()->getOrganization(),
false);
$invoice->setContract($contract);
$invoice->setContractNumber($contract->getContractNumber());
$invoice->setAttachmentNumber($contract->getAttachmentNumber());
$entityManager->persist($invoice);
$entityManager->flush();
$invoice = $invoiceService->updateProfitInfo($invoice);
$product = $kernel_service->getApplicationInfoValue("Finance.DefaultProductForResourceContracts", $contract->getOrganization());
$taxrate = $kernel_service->getListItem('Finance.tax', "21%");
if ($contract->getClient()->getTaxRate() != null)
{
$taxrate = $contract->getClient()->getTaxRate();
}
if ($product)
{
$price = 0;
foreach($contract->getContractsElement() as $element)
{
if ($element->getState() == 0)
{
$price = $element->getUnitPrice();
}
}
$invoiceProduct = new InvoiceProduct();
$invoiceProduct
->setInvoice($invoice)
->setProduct($product)
->setReference($product->getReference())
->setName($product->getName())
->setUnitPrice($price/8)
->setQuantity(str_replace(',', '.',$items['hours']))
->setTaxrate($taxrate)
->setState(0);
$entityManager->persist($invoiceProduct);
$entityManager->flush();
}
$product = $kernel_service->getApplicationInfoValue("Finance.DefaultAdditionalProduct", $contract->getOrganization());
$taxrate = $kernel_service->getListItem('Finance.tax', "0%");
if ($product)
{
$extra = str_replace(',', '.',$items['extraamount']);
if (empty($extra) == false)
{
$invoiceProduct = new InvoiceProduct();
$invoiceProduct
->setInvoice($invoice)
->setProduct($product)
->setReference($product->getReference())
->setName($product->getName())
->setUnitPrice($extra)
->setQuantity(1)
->setTaxrate($taxrate)
->setState(0);
$entityManager->persist($invoiceProduct);
$entityManager->flush();
}
}
$invoiceService->calcTotalAmount($invoice, true);
$applicationfolder = $dmsservice->createFolderIfNeeded("System");
$invoicefolder = $dmsservice->createFolderIfNeeded("Invoice", $applicationfolder);
$folder = $dmsservice->createFolderIfNeeded("".$invoice->getId(), $invoicefolder);
$errorfile = false;
try {
if ($input != null) {
if (array_key_exists('timesheetupload', $input)) {
$timesheetfile = $dmsservice->uploadfile($input['timesheetupload'], $folder);
$explode = explode(".",$timesheetfile->getName());
$extension = end($explode);
$timesheetfile->setName("timesheet_". $invoice->getInvoiceNumber(). "." . $extension);
$entityManager->persist($timesheetfile);
$entityManager->flush();
}
}
} catch (FileException$e) {
$errorfile = true;
}
$this->denyAccessUnlessGranted($attribute, $invoice);
return $this->redirectToRoute('invoice_show'
,array('id' => $invoice->getId())
);
} else {
$this->showErrorMessageMustBeUnique($translator);
}
}
return $this->render('finance/invoice/newforcontract.html.twig', [
'invoice' => $invoice,
'form' => $form->createView(),
]);
}
/**
* @Route("/multinew", name="invoice_multinew", methods={"GET","POST"})
*/
public function multinew(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice, DMSService $dmsservice): Response
{
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute);
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery("SELECT t FROM App\Entity\Finance\Contract t WHERE (t.state = 0) AND ((t.endDate >= ?1) or (t.endDate is null)) AND (t.startDate <= ?2)");
//new \DateTime('last day of last month')
$param1 = date("Y-m-d", strtotime("first day of last month"));
$param2 = date("Y-m-d", strtotime("last day of last month"));
$query = $query->setParameter(1, $param1);
$query = $query->setParameter(2, $param2);
$entities = $query->getResult();
//$entity = new Invoice();
//$form = $this->createForm(new MultiInvoiceType());
$form = $this->createFormBuilder(null,
['action' => $this->generateUrl('invoice_multinew'),
'attr' => ['id' => $this->generateUrl('invoice_multinew')]]);
$entities3 = array();
foreach ($entities as $entity) {
$query = $em->createQuery("SELECT COUNT(t.id) FROM App\Entity\Finance\Invoice t WHERE (t.state = 0) AND (t.invoiceDate >= ?1) AND (t.contract = ?2)");
//new \DateTime('last day of last month')
$param = date("Y-m-d", strtotime("first day of last month"));
$query = $query->setParameter(1, $param);
$query = $query->setParameter(2, $entity->getId());
$entities2 = $query->getResult();
$query2 = $em->createQuery("SELECT COUNT(t.id) FROM App\Entity\Finance\NoInvoice t WHERE (t.state = 0) AND (t.creationDate >= ?1) AND (t.contract = ?2)");
$query2 = $query2->setParameter(1, $param);
$query2 = $query2->setParameter(2, $entity->getId());
$entities4 = $query2->getResult();
if (($entities2[0][1] == 0)&& ($entities4[0][1] == 0)) {
$form->add('hours' . $entity->getId(), NumberType::class, array('label' => 'Invoice.Hours', 'required' => false));
$form->add('extra' . $entity->getId(), NumberType::class, array('label' => 'Invoice.Extra', 'required' => false));
$form->add('timesheetupload' . $entity->getId(), FileType::class, array('label' => 'TimeSheet', 'required' => false, 'mapped' => false));
$form->add('action' . $entity->getId(), ChoiceType::class,
array('required' => true, 'choices' => array('Invoice.CreateWhenHoursNotZero' => 'invoice', 'Invoice.NoInvoiceNeededThisMonth' => 'noinvoice'), 'preferred_choices' => array('mail')));
$entities3[] = $entity;
}
}
$form = $form->getForm();
$form->handleRequest($request);
if ($form->isSubmitted()) {
$items = $request->request->get('form');
$input = $request->files->get('form');
//$this->get('session')->getFlashBag()->add('error', "verzonden");
$finalarray = array();
$i = 0;
$applicationfolder = $dmsservice->createFolderIfNeeded("System");
$invoicefolder = $dmsservice->createFolderIfNeeded("Invoice", $applicationfolder);
//$folder = $dmsservice->createFolderIfNeeded("".$invoice->getId(), $invoicefolder);
foreach ($entities as $entity) {
$query = $em->createQuery("SELECT COUNT(t.id) FROM App\Entity\Finance\Invoice t WHERE (t.state = 0) AND (t.invoiceDate >= ?1) AND (t.contract = ?2)");
//new \DateTime('last day of last month')
$param = date("Y-m-d", strtotime("first day of last month"));
$query = $query->setParameter(1, $param);
$query = $query->setParameter(2, $entity->getId());
$entities2 = $query->getResult();
$query2 = $em->createQuery("SELECT COUNT(t.id) FROM App\Entity\Finance\NoInvoice t WHERE (t.state = 0) AND (t.creationDate >= ?1) AND (t.contract = ?2)");
$query2 = $query2->setParameter(1, $param);
$query2 = $query2->setParameter(2, $entity->getId());
$entities4 = $query2->getResult();
if (($entities2[0][1] == 0) && ($entities4[0][1] == 0)) {
$action = $items['action' . $entity->getId()];
if ($action == 'noinvoice') {
$noinv = new NoInvoice();
$noinv->setContract($entity);
$noinv->setCreationDate(new \DateTime('last day of last month'));
$noinv->setOrganization($entity->getOrganization());
$noinv->setState(0);
$em->persist($noinv);
$em->flush();
} else {
if ($items['hours' . $entity->getId()] != 0) {
/*$entityinv = new Invoice();
$entityinv->setContract($entity);
$entityinv->setHours(str_replace(',', '.', $items['hours' . $entity->getId()]));
$entityinv->setExtraamount(str_replace(',', '.', $items['extra' . $entity->getId()]));*/
$invoicedate = new \DateTime('last day of last month');
//Contractnumber ; "-" ; consultantname ; services related to the period ; variable (month , year )
$subject = $entity->getSubject();
$extra = "";
foreach ($entity->getContractsElement() as $element)
{
if ($element->getState() == 0)
{
if ($entity->getType()->getInteger1() == 2)
{
$extra = "". $element->getEmployee();
}
}
}
$extra2 = "";
if (empty($entity->getAttachmentNumber()) == false)
{
$extra2 = " - " . $entity->getAttachmentNumber();
}
$subject = $entity->getContractNumber().$extra2 . " : " . $extra. " - services related to the period " . $invoicedate->format('M Y');
$invoice = $invoiceService->createInvoice($entity->getClient()->getId(),
$invoicedate->format('Y-m-d'), null,$subject, null,
$entity->getClient()->getLanguage(),
$entity->getSalesCondition()->getId(),
$entity->getOrganization(),
false);
$invoice->setContract($entity);
$invoice->setContractNumber($entity->getContractNumber());
$invoice->setAttachmentNumber($entity->getAttachmentNumber());
$em->persist($invoice);
$em->flush();
$invoice = $invoiceService->updateProfitInfo($invoice);
$em->persist($invoice);
$em->flush();
$product = $kernel_service->getApplicationInfoValue("Finance.DefaultProductForResourceContracts", $entity->getOrganization());
$taxrate = $kernel_service->getListItem('Finance.tax', "21%");
if ($entity->getClient()->getTaxRate() != null)
{
$taxrate = $entity->getClient()->getTaxRate();
}
if ($product)
{
$price = 0;
foreach($entity->getContractsElement() as $element)
{
if ($element->getState() == 0)
{
$price = $element->getUnitPrice();
}
}
$invoiceProduct = new InvoiceProduct();
$invoiceProduct
->setInvoice($invoice)
->setProduct($product)
->setReference($product->getReference())
->setName($product->getName())
->setUnitPrice($price/8)
->setQuantity(str_replace(',', '.',$items['hours' . $entity->getId()]))
->setTaxrate($taxrate)
->setState(0);
$em->persist($invoiceProduct);
$em->flush();
}
$product = $kernel_service->getApplicationInfoValue("Finance.DefaultAdditionalProduct", $entity->getOrganization());
$taxrate = $kernel_service->getListItem('Finance.tax', "0%");
if ($product)
{
$extra = str_replace(',', '.',$items['extra' . $entity->getId()]);
if (empty($extra) == false)
{
$invoiceProduct = new InvoiceProduct();
$invoiceProduct
->setInvoice($invoice)
->setProduct($product)
->setReference($product->getReference())
->setName($product->getName())
->setUnitPrice($extra)
->setQuantity(1)
->setTaxrate($taxrate)
->setState(0);
$em->persist($invoiceProduct);
$em->flush();
}
}
$invoiceService->calcTotalAmount($invoice, true);
$folder = $dmsservice->createFolderIfNeeded("".$invoice->getId(), $invoicefolder);
$errorfile = false;
try {
if ($input != null) {
if (array_key_exists('timesheetupload' . $entity->getId(), $input)) {
$timesheetfile = $dmsservice->uploadfile($input['timesheetupload' . $entity->getId()], $folder);
$explode = explode(".",$timesheetfile->getName());
$extension = end($explode);
$timesheetfile->setName("timesheet_". $invoice->getInvoiceNumber(). "." . $extension);
$em->persist($timesheetfile);
$em->flush();
}
}
} catch (FileException$e) {
$errorfile = true;
}
$finalarray[] = $invoice;
$i = $i + 1;
}
}
}
}
$this->get('session')->getFlashBag()->add('succes', $i . " invoice(s) created!");
$currenttime = new \DateTime();
$filename = $currenttime->format('Y-m-d-H-i-s');
return $this->redirect($this->generateUrl('invoice_index'));
}
return $this->render('finance/invoice/multinew.html.twig', [
'entities' => $entities3,
'form' => $form->createView(),
]);
}
/**
* @Route("/listing", name="invoice_listing", methods={"GET","POST"})
*/
public function listing(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice): Response
{
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute);
$entityManager = $this->getDoctrine()
->getManager();
$em = $this->getDoctrine()->getManager();
//$query = $em->createQuery("SELECT t.creationDate FROM App\Entity\Finance\Invoice t ORDER BY t.creationDate")->setMaxResults(1);
//$entities = $query->getResult();
$query2 = $em->createQuery("SELECT DISTINCT(t.invoiceDate) as invoiceDate FROM App\Entity\Finance\Invoice t WHERE t.state = 0 ORDER BY t.invoiceDate DESC");
$entities2 = $query2->getResult();
$entities3 = array();
$prev = "";
foreach($entities2 as $entity) {
if (substr($entity['invoiceDate'],0,7) != $prev)
{
$prev = substr($entity['invoiceDate'],0,7);
$entities3[$prev] = $prev;
}
}
$form = $this->createFormBuilder(null, array(
'attr' => array(
'id' => $this->generateUrl('invoice_listing')
)));
$form->setAction($this->generateUrl('invoice_listing'));
$form->add('month', ChoiceType::class, array('choices' => $entities3, 'label' => 'Month', 'required' => true, 'attr' => array(
'class' => 'select2')));
$form = $form->getForm();
if ($request->isMethod('POST'))
{
$items = $request->request->get('form');
$selectedmonth = $items['month'];
$selecteddate = new \DateTime($selectedmonth . "-15");
$firstday = clone $selecteddate->modify('first day of this month');
$lastday = $selecteddate->modify('last day of this month');
$query = $em->createQuery("SELECT t FROM App\Entity\Finance\Invoice t WHERE (t.state = 0) AND ((t.invoiceDate >= ?1) AND (t.invoiceDate <= ?2))");
//new \DateTime('last day of last month')
// $param = date("Y-m-d",strtotime("first day of last month"));
// $param2 = date("Y-m-d",strtotime("first day of last month"));
$query = $query->setParameter(1, $firstday);
$query = $query->setParameter(2, $lastday);
$entities = $query->getResult();
$query2 = $em->createQuery("SELECT t FROM App\Entity\Finance\CreditNote t WHERE (t.state = 0) AND ((t.creditNoteDate >= ?1) AND (t.creditNoteDate <= ?2))");
//new \DateTime('last day of last month')
// $param = date("Y-m-d",strtotime("first day of last month"));
// $param2 = date("Y-m-d",strtotime("first day of last month"));
$query2 = $query2->setParameter(1, $firstday);
$query2 = $query2->setParameter(2, $lastday);
$entities2 = $query2->getResult();
$result = $invoiceService->multipdf($entities, $selectedmonth,$this->getUser()->getOrganization(), $entities2);
return $this->render('finance/invoice/resultlisting.html.twig', [
'selectedmonth' => $lastday->format('Y-m-d'), 'entities' => $entities, 'result' => $result, "f" => $firstday, "l" => $lastday
]);
}
return $this->render('finance/invoice/listing.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/accounting", name="invoice_accounting", methods={"GET","POST"})
*/
public function accounting(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice, MailService $mailService): Response
{
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute);
$entityManager = $this->getDoctrine()
->getManager();
$em = $this->getDoctrine()->getManager();
//$query = $em->createQuery("SELECT t.creationDate FROM App\Entity\Finance\Invoice t ORDER BY t.creationDate")->setMaxResults(1);
//$entities = $query->getResult();
$query2 = $em->createQuery("SELECT DISTINCT(t.invoiceDate) as invoiceDate FROM App\Entity\Finance\Invoice t WHERE t.state = 0 ORDER BY t.invoiceDate DESC");
$entities2 = $query2->getResult();
$entities3 = array();
$prev = "";
foreach($entities2 as $entity) {
if (substr($entity['invoiceDate'],0,7) != $prev)
{
$prev = substr($entity['invoiceDate'],0,7);
$entities3[$prev] = $prev;
}
}
$form = $this->createFormBuilder(null, array(
'attr' => array(
'id' => $this->generateUrl('invoice_accounting')
)));
$form->setAction($this->generateUrl('invoice_accounting'));
$form->add('resendall', CheckboxType::class, array('mapped' => false, 'label' => 'Resend All', 'required' => false));
$form->add('month', ChoiceType::class, array('choices' => $entities3, 'label' => 'Month', 'required' => true, 'attr' => array(
'class' => 'select2')));
$form = $form->getForm();
if ($request->isMethod('POST'))
{
$items = $request->request->get('form');
$selectedmonth = $items['month'];
$selecteddate = new \DateTime($selectedmonth . "-15");
$firstday = clone $selecteddate->modify('first day of this month');
$lastday = $selecteddate->modify('last day of this month');
if (isset($items['resendall']))
{
$query = $em->createQuery("SELECT t FROM App\Entity\Finance\Invoice t WHERE t.state = 0 AND ((t.invoiceDate >= ?1) AND (t.invoiceDate <= ?2))");
} else
{
$query = $em->createQuery("SELECT t FROM App\Entity\Finance\Invoice t WHERE (t.state = 0 and t.ublMailToAccountantNeeded = 1) AND ((t.invoiceDate >= ?1) AND (t.invoiceDate <= ?2))");
}
$query = $query->setParameter(1, $firstday);
$query = $query->setParameter(2, $lastday);
$entities = $query->getResult();
$organization = $this->getUser()->getOrganization();
$emailAccountant = $kernel_service->getApplicationInfoValue("Kernel.AccountantEmail", $organization);
$valid = null;
foreach (explode(';', $emailAccountant) AS $sEmailAddress) {
if (!filter_var($sEmailAddress, FILTER_VALIDATE_EMAIL) === false) {
if ($valid == null) {
$valid = true;
}
} else {
$valid = false;
}
}
if ($valid == null) {
$valid = false;
}
$count = 0;
if ($valid == true)
{
}
foreach ($entities AS $invoice) {
if ($invoice->getUbl() != null)
{
$files = array();
$files[] = $invoice->getUbl();
/*if ($invoice->getPdf() != null)
{
$files[] = $invoice->getPdf();
}*/
$mailcc = $kernel_service->getApplicationInfoValue("Finance.AdditionalCCEmailForInvoices", $invoice->getOrganization());
$cc = null;
if (empty($mailcc) == false) {
if ((!filter_var($mailcc, FILTER_VALIDATE_EMAIL) === false)) {
$cc = $mailcc;
}
}
$mailfrom = $kernel_service->getApplicationInfoValue("Finance.FromEmailForInvoices", $invoice->getOrganization());
if (empty($mailfrom) == true) {
$mailfrom = null;
}
$contact = $mailService->createMail($emailAccountant, "Invoice & UBL", "", $files, $cc, $mailfrom, $invoice->getOrganization(), true);
$contact->setInvoice($invoice);
$em->persist($contact);
$invoice->setUblMailToAccountantNeeded(0);
$em->persist($contact);
$em->flush();
$count++;
}
}
if (isset($items['resendall']))
{
$query = $em->createQuery("SELECT t FROM App\Entity\Finance\CreditNote t WHERE t.state = 0 AND ((t.creditNoteDate >= ?1) AND (t.creditNoteDate <= ?2))");
} else
{
$query = $em->createQuery("SELECT t FROM App\Entity\Finance\CreditNote t WHERE (t.state = 0 and t.ublMailToAccountantNeeded = 1) AND ((t.creditNoteDate >= ?1) AND (t.creditNoteDate <= ?2))");
}
$query = $query->setParameter(1, $firstday);
$query = $query->setParameter(2, $lastday);
$entities = $query->getResult();
$organization = $this->getUser()->getOrganization();
$emailAccountant = $kernel_service->getApplicationInfoValue("Kernel.AccountantEmail", $organization);
$valid = null;
foreach (explode(';', $emailAccountant) AS $sEmailAddress) {
if (!filter_var($sEmailAddress, FILTER_VALIDATE_EMAIL) === false) {
if ($valid == null) {
$valid = true;
}
} else {
$valid = false;
}
}
if ($valid == null) {
$valid = false;
}
//$count = 0;
if ($valid == true)
{
}
foreach ($entities AS $creditnote) {
if ($creditnote->getUbl() != null)
{
$files = array();
$files[] = $creditnote->getUbl();
/*if ($invoice->getPdf() != null)
{
$files[] = $invoice->getPdf();
}*/
$mailcc = $kernel_service->getApplicationInfoValue("Finance.AdditionalCCEmailForInvoices", $creditnote->getOrganization());
$cc = null;
if (empty($mailcc) == false) {
if ((!filter_var($mailcc, FILTER_VALIDATE_EMAIL) === false)) {
$cc = $mailcc;
}
}
$mailfrom = $kernel_service->getApplicationInfoValue("Finance.FromEmailForInvoices", $creditnote->getOrganization());
if (empty($mailfrom) == true) {
$mailfrom = null;
}
$contact = $mailService->createMail($emailAccountant, "Credit Note & UBL", "", $files, $cc, $mailfrom, $creditnote->getOrganization(), true);
$contact->setCreditnote($creditnote);
$em->persist($contact);
$creditnote->setUblMailToAccountantNeeded(0);
$em->persist($contact);
$em->flush();
$count++;
}
}
//$result = $invoiceService->multipdf($entities, $selectedmonth,$this->getUser()->getOrganization());
$feedback = "". $count . " UBL files have been mailed to the accountant";
$this->get('session')->getFlashBag()->add('success', $feedback);
return $this->redirect($this->generateUrl('invoice_accounting'));
}
return $this->render('finance/invoice/accounting.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/mails", name="invoice_mails", methods={"GET","POST"})
*/
public function mails(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice, DMSService $dmsservice, MailService $mailService): Response
{
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute);
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery("SELECT t FROM App\Entity\Finance\Invoice t LEFT JOIN t.client u WHERE ((t.state = 0) AND (u.contactByEmail = true))AND t.processState = 0");
$entities = $query->getResult();
$form = $this->createFormBuilder(null,
['action' => $this->generateUrl('invoice_mails'),
'attr' => ['id' => $this->generateUrl('invoice_mails')]]);
foreach($entities as $entity) {
$form->add('action'.$entity->getId(), ChoiceType::class,
array('required' => true, 'choices' => array('Invoice.SendMail' => 'mail', 'Invoice.SendMailLater' => 'later', 'Invoice.NoMailRequired' => 'not'), 'preferred_choices' => array('mail')));
}
$form = $form->getForm();
$form->handleRequest($request);
if ($form->isSubmitted()) {
$items = $request->request->get('form');
foreach ($entities as $entity) {
$feedback = "";
$action = $items['action' . $entity->getId()];
if ($action == 'mail') {
$valid = null;
if (($entity->getContract() != null) and
(empty($entity->getContract()->getInvoiceContactEmail()) == false))
{
if (!filter_var($entity->getContract()->getInvoiceContactEmail(), FILTER_VALIDATE_EMAIL) === false)
{
if ($valid == null)
{
$valid = true;
}
}
}
else
{
foreach(explode(';', $entity->getClient()->getEmail()) AS $sEmailAddress) {
if (!filter_var($sEmailAddress, FILTER_VALIDATE_EMAIL) === false)
{
if ($valid == null)
{
$valid = true;
}
} else
{
$valid = false;
}
}
if ($valid == null)
{
$valid = false;
}
}
//if (!filter_var($entity->getClient()->getEmail(), FILTER_VALIDATE_EMAIL) === false) {
if ($valid == true)
{
$applicationfolder = $dmsservice->createFolderIfNeeded("System");
$invoicefolder = $dmsservice->createFolderIfNeeded("Invoice", $applicationfolder);
$folder = $dmsservice->createFolderIfNeeded("".$entity->getId(), $invoicefolder);
$files = $folder->getActiveKernelfiles();
$files[] = $entity->getPdf();
$includeUBLInInvoiceMail = $kernel_service->getApplicationInfoValue("Finance.IncludeUBLInInvoiceMail", $entity->getOrganization());
if ($includeUBLInInvoiceMail == true)
{
$files[] = $entity->getUbl();
}
$mailcc = $kernel_service->getApplicationInfoValue("Finance.AdditionalCCEmailForInvoices");
$cc = null;
if (empty($mailcc) == false) {
if ((!filter_var($mailcc, FILTER_VALIDATE_EMAIL) === false)) {
$cc = $mailcc;
}
}
$mailfrom = $kernel_service->getApplicationInfoValue("Finance.FromEmailForInvoices", $entity->getOrganization());
if (empty($mailfrom) == true)
{
$mailfrom = null;
}
$to = "";
if (($entity->getContract() != null) and
(empty($entity->getContract()->getInvoiceContactEmail()) == false))
{
$to = $entity->getContract()->getInvoiceContactEmail();
} else
{
$to = explode(';', $entity->getClient()->getEmail());
}
$contact = $mailService->createMailBasedOnTemplate($to, "TemplateType.NewInvoice", $entity, $entity->getLanguage(), $files, $cc, $mailfrom, $entity->getOrganization());
$contact->setInvoice($entity);
$em->persist($contact);
$entity->setProcessState(1);
$feedback = $feedback . "Invoice " . $entity . " sent";
}
}
if ($action == 'not') {
$entity->setProcessState(1);
$feedback = $feedback . "Invoice " . $entity . " marked as no longer required to be sent";
}
$em->persist($entity);
$em->flush();
if (empty($feedback) == false)
{
$this->get('session')->getFlashBag()->add('succes', $feedback);
}
}
return $this->redirect($this->generateUrl('invoice_mails'));
}
return $this->render('finance/invoice/mails.html.twig', [
'entities' => $entities,
'form' => $form->createView()
]);
}
/**
* @Route("/{id}", name="invoice_show", methods={"GET"})
*/
public function show(Invoice $invoice, DMSService $dmsservice, InvoiceService $invoiceService): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
$applicationfolder = $dmsservice->createFolderIfNeeded("System");
$invoicefolder = $dmsservice->createFolderIfNeeded("Invoice", $applicationfolder);
$folder = $dmsservice->createFolderIfNeeded("".$invoice->getId(), $invoicefolder);
return $this->render('finance/invoice/show.html.twig', [
'invoice' => $invoice,
'folder' => $folder,
'state' => 0
]);
}
/**
* @Route("/{id}/audit", name="invoice_showaudit", methods={"GET"})
*/
public function showaudit(Invoice $invoice): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
return $this->render('finance/invoice/showaudit.html.twig', [
'invoice' => $invoice,
]);
}
/**
* @Route("/{id}/archive", name="invoice_archive", methods={"GET"})
*/
public function archive(Invoice $invoice, TranslatorInterface $translator, ContractService $contractService): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
$entityManager = $this->getDoctrine()->getManager();
$invoice->setState(1);
$entityManager->persist($invoice);
$entityManager->flush();
$contract = $invoice->getContract();
if ($contract != null)
{
$contractService->updateInvoicedDays($contract);
}
return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
}
/**
* @Route("/{id}/markassend", name="invoice_markassend", methods={"GET"})
*/
public function markassend(Invoice $invoice): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
$entityManager = $this->getDoctrine()->getManager();
$invoice->setProcessState(1);
$entityManager->persist($invoice);
$entityManager->flush();
return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
}
/**
* @Route("/{id}/markaspayed", name="invoice_markaspayed", methods={"GET"})
*/
public function markaspayed(Invoice $invoice): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
$entityManager = $this->getDoctrine()->getManager();
$invoice->setProcessState(2);
$entityManager->persist($invoice);
$entityManager->flush();
return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
}
/**
* @Route("/{id}/putinnewstatus", name="invoice_putinnewstatus", methods={"GET"})
*/
public function putinnewstatus(Invoice $invoice): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
$entityManager = $this->getDoctrine()->getManager();
$invoice->setProcessState(0);
$entityManager->persist($invoice);
$entityManager->flush();
return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
}
/**
* @Route("/{id}/duplicate", name="invoice_duplicate", methods={"GET"})
*/
public function duplicate(Invoice $invoice, InvoiceService $invoiceService, TranslatorInterface $translator): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
$entityManager = $this->getDoctrine()->getManager();
$datenewinvoice = new \DateTime();
$newinvoice = $invoiceService->createInvoice($invoice->getClient()->getId(),
$datenewinvoice->format('Y-m-d'), null, $invoice->getAbout(), $invoice->getNote(),
$invoice->getLanguage(),
$invoice->getSalesCondition()->getId(),
$invoice->getOrganization(),
false);
$entityManager = $this->getDoctrine()->getManager();
if (is_int($newinvoice) == false)
{
$newinvoice->setContract($invoice->getContract());
$entityManager->persist($newinvoice);
$entityManager->flush();
foreach($invoice->getInvoiceproducts() as $invoiceproduct) {
$invoiceService->creatInvoiceProduct($invoiceproduct->getReference(), $invoiceproduct->getName(), $invoiceproduct->getUnitPrice(), $invoiceproduct->getQuantity(), $invoiceproduct->getTaxrate()->getName(), $newinvoice->getId(), false, $invoice->getOrganization());
}
$invoiceService->updatePDF($newinvoice);
$this->denyAccessUnlessGranted($attribute, $newinvoice);
return $this->redirectToRoute('invoice_show', array('id' => $newinvoice->getId()));
} else
{
$this->get('session')->getFlashBag()->add('error', $translator->trans('Invoice.ReferenceMustBeUnique'));
return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
}
}
/**
* @Route("/{id}/createcreditnote", name="invoice_createcreditnote", methods={"GET"})
*/
public function createcreditnote(Invoice $invoice, InvoiceService $invoiceService): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
$entityManager = $this->getDoctrine()->getManager();
$datenewinvoice = new \DateTime();
$creditnote = $invoiceService->createCreditNote($invoice->getClient()->getId(),
$datenewinvoice->format('Y-m-d'), null, $invoice->getAbout(), $invoice->getNote(),
$invoice->getLanguage(),
$invoice->getOrganization(),
false);
foreach($invoice->getInvoiceproducts() as $invoiceproduct) {
$invoiceService->createCreditNoteProduct($invoiceproduct->getReference(), $invoiceproduct->getName(), $invoiceproduct->getUnitPrice(), $invoiceproduct->getQuantity(), $invoiceproduct->getTaxrate()->getName(), $creditnote->getId(), false);
}
$invoiceService->updateCreditNotePDF($creditnote);
$creditnote->setInvoice($invoice);
$entityManager->persist($creditnote);
$entityManager->flush();
//$this->denyAccessUnlessGranted($attribute, $newinvoice);
return $this->redirectToRoute('app_credit_note_show', array('id' => $creditnote->getId()));
}
/**
* @Route("/{id}/restore", name="invoice_restore", methods={"GET"})
*/
public function restore(Invoice $invoice, TranslatorInterface $translator,InvoiceService $invoiceService, ContractService $contractService): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
$entityManager = $this->getDoctrine()->getManager();
if ($invoiceService->checkForDuplicates($invoice)) {
$invoice->setState(0);
$entityManager->persist($invoice);
$entityManager->flush();
$contract = $invoice->getContract();
if ($contract != null)
{
$contractService->updateInvoicedDays($contract);
}
} else {
$this->showErrorMessageMustBeUnique($translator);
}
return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
}
/**
* @Route("/{id}/delete", name="invoice_logicaldelete", methods={"GET"})
*/
public function logicaldelete(Invoice $invoice, ContractService $contractService): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
$entityManager = $this->getDoctrine()->getManager();
$invoice->setState(2);
$entityManager->persist($invoice);
$entityManager->flush();
$contract = $invoice->getContract();
if ($contract != null)
{
$contractService->updateInvoicedDays($contract);
}
return $this->redirectToRoute('invoice_index');
}
/**
* @Route("/{id}/edit", name="invoice_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Invoice $invoice, InvoiceService $invoiceService, TranslatorInterface $translator): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
$entityManager = $this->getDoctrine()->getManager();
if ($invoice->getClient() != null)
{
$clients["".$invoice->getClient()] = "SU".$invoice->getClient()->getId();
$client = "SU".$invoice->getClient()->getId();
}
$form = $this->createForm(InvoiceType::class, $invoice,
['organization' => $invoice->getOrganization(), 'clients' => $clients, 'client' => $client, 'action' => $this->generateUrl('invoice_edit', array('id' => $invoice->getId())),
'attr' => ['id' => $this->generateUrl('invoice_edit', array('id' => $invoice->getId()))]]);
$form->handleRequest($request);
$invoice2 = $this->getDoctrine()->getManager()->getRepository(Invoice::class)->findOneBy(array(
'invoiceNumber' => $invoice->getInvoiceNumber(),
'organization' => $invoice->getOrganization(),
'state' => 0));
$continue = true;
if ($form->isSubmitted())
{
$requestdata = $request->request->all("invoice");
if (isset($requestdata['clientselect2']) == false)
{
$errormessage = $translator->trans('Mandatory');
$form->get('clientselect2')->addError(new FormError($errormessage));
$continue = false;
}
}
if ($form->isSubmitted() && ($continue == true)) {
$requestdata = $request->request->all("invoice");
if (isset($requestdata['clientselect2']) == true) {
$clientselect2 = $requestdata['clientselect2'];
$client = null;
$clienttype = substr($clientselect2, 0, 2);
$clientid = substr($clientselect2, 2);
if ($clienttype == "SU") {
$invoice->setClient($entityManager->getRepository(Client::class)->findOneById($clientid));
} else {
}
}
$invoiceService->copyFieldsFromClientToInvoice($invoice);
if ($invoiceService->checkForDuplicates($invoice) or ($invoice2->getId() == $invoice->getId())) {
$invoice->setSalesConditionText($invoice->getSalesCondition()->getTranslatedDescription($invoice->getLanguage()));
$duedate = clone $invoice->getInvoiceDate();
if ($invoice->getSalesCondition())
{
if ($invoice->getSalesCondition()->getStartCalculationPaymentDueDateFromEndOfMonth())
{
$duedate->modify('last day of this month');
}
$duedate->add(new \DateInterval('P'.$invoice->getSalesCondition()->getAllowedDaysUntilPayment().'D')); // P1D means a period of 1 day
$invoice->setDueDate($duedate);
}
$this->getDoctrine()->getManager()->flush();
$invoiceService->updatePDF($invoice);
return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
} else {
$this->showErrorMessageMustBeUnique($translator);
}
}
return $this->render('finance/invoice/edit.html.twig', [
'invoice' => $invoice,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}/editprofitinfo", name="invoice_editprofitinfo", methods={"GET","POST"})
*/
public function editprofitinfo(Request $request, Invoice $invoice, InvoiceService $invoiceService, TranslatorInterface $translator): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
$entityManager = $this->getDoctrine()->getManager();
$form = $this->createForm(InvoiceProfitType::class, $invoice,
[ 'action' => $this->generateUrl('invoice_editprofitinfo', array('id' => $invoice->getId())),
'attr' => ['id' => $this->generateUrl('invoice_editprofitinfo', array('id' => $invoice->getId()))]]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($invoice);
$entityManager->flush();
return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
}
return $this->render('finance/invoice/editprofitinfo.html.twig', [
'invoice' => $invoice,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="invoice_delete", methods={"DELETE"})
*/
public function delete(Request $request, Invoice $invoice): Response {
$classname = explode("\\", get_class($this));
$arraysize = count($classname);
$attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
$this->denyAccessUnlessGranted($attribute, $invoice);
if ($this->isCsrfTokenValid('delete' . $invoice->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($invoice);
$entityManager->flush();
}
return $this->redirectToRoute('invoice_index');
}
public function showErrorMessageMustBeUnique(TranslatorInterface $translator) {
$this->get('session')->getFlashBag()->add('error', $translator->trans('Invoice.ReferenceMustBeUnique'));
}
}