improved invoices with new renderer (#306)

* added docx renderer and demo template
* added csv renderer and demo template
* added xlsx renderer and demo template
* added ods renderer and demo template
* added user calculator
* added invoice documentation
This commit is contained in:
Kevin Papst
2018-09-21 01:27:56 +02:00
committed by GitHub
parent b035fc9ebd
commit 53f82a808b
121 changed files with 4094 additions and 770 deletions

View File

@@ -0,0 +1,82 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Invoice\Renderer;
use App\Twig\DateExtensions;
use App\Twig\Extensions;
use Symfony\Component\Translation\TranslatorInterface;
abstract class AbstractRenderer
{
use RendererTrait;
/**
* @var DateExtensions
*/
protected $dateExtension;
/**
* @var Extensions
*/
protected $extension;
/**
* @var TranslatorInterface
*/
protected $translator;
/**
* @param TranslatorInterface $translator
* @param DateExtensions $dateExtension
* @param Extensions $extensions
*/
public function __construct(TranslatorInterface $translator, DateExtensions $dateExtension, Extensions $extensions)
{
$this->translator = $translator;
$this->dateExtension = $dateExtension;
$this->extension = $extensions;
}
/**
* @param \DateTime $date
* @return mixed
*/
protected function getFormattedDateTime(\DateTime $date)
{
return $this->dateExtension->dateShort($date);
}
/**
* @param $amount
* @return mixed
*/
protected function getFormattedMoney($amount)
{
return $this->extension->money($amount);
}
/**
* @param \DateTime $date
* @return mixed
*/
protected function getFormattedMonthName(\DateTime $date)
{
return $this->translator->trans($this->dateExtension->monthName($date));
}
/**
* @param $seconds
* @return mixed
*/
protected function getFormattedDuration($seconds)
{
return $this->extension->duration($seconds);
}
}

View File

@@ -0,0 +1,129 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Invoice\Renderer;
use App\Entity\InvoiceDocument;
use App\Model\InvoiceModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Symfony\Component\HttpFoundation\Response;
abstract class AbstractSpreadsheetRenderer extends AbstractRenderer
{
/**
* @param Spreadsheet $spreadsheet
* @return bool|string
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
abstract protected function saveSpreadsheet(Spreadsheet $spreadsheet);
/**
* Render the given InvoiceDocument with the data from the InvoiceModel.
*
* @param InvoiceDocument $document
* @param InvoiceModel $model
* @return Response
*/
public function render(InvoiceDocument $document, InvoiceModel $model): Response
{
$spreadsheet = IOFactory::load($document->getFilename());
$worksheet = $spreadsheet->getActiveSheet();
$entries = $model->getCalculator()->getEntries();
$replacer = $this->modelToReplacer($model);
$timesheetAmount = count($entries);
$this->addTemplateRows($worksheet, $timesheetAmount);
$worksheet->setTitle($model->getTemplate()->getTitle());
$entryRow = 0;
foreach ($worksheet->getRowIterator() as $row) {
$timesheet = $entries[$entryRow];
$sheetValues = false;
foreach ($row->getCellIterator() as $cell) {
$value = $cell->getValue();
if (stripos($value, '${entry.') !== false) {
if ($sheetValues === false) {
$sheetValues = $this->timesheetToArray($timesheet);
}
$searcher = str_replace('${', '', $value);
$searcher = str_replace('}', '', $searcher);
if (isset($sheetValues[$searcher])) {
$cell->setValue($sheetValues[$searcher]);
}
} elseif (stripos($value, '${') !== false) {
$searcher = str_replace('${', '', $value);
$searcher = str_replace('}', '', $searcher);
if (isset($replacer[$searcher])) {
$cell->setValue($replacer[$searcher]);
}
}
}
if ($sheetValues !== false && $entryRow < $timesheetAmount - 1) {
$entryRow++;
}
}
$filename = $this->saveSpreadsheet($spreadsheet);
return $this->getFileResponse($filename, basename($document->getFilename()));
}
/**
* @param Worksheet $worksheet
* @param int $timesheets
*/
protected function addTemplateRows(Worksheet $worksheet, int $timesheets)
{
$startRow = null;
$rowCounter = 0;
foreach ($worksheet->getRowIterator() as $row) {
$cellCounter = 0;
foreach ($row->getCellIterator() as $cell) {
$value = $cell->getValue();
if (stripos($value, '${entry.') !== false) {
$startRow = $row->getRowIndex();
$worksheet->insertNewRowBefore($row->getRowIndex(), $timesheets - 1);
break 2;
}
if ($cellCounter++ >= 10) {
break;
}
}
if ($rowCounter++ >= 100) {
break;
}
}
if ($startRow === null) {
throw new \Exception('Invalid invoice document, no template row found.');
}
// fill up all new rows with template values
$templateRow = $timesheets + $startRow;
$iterator = $worksheet->getRowIterator($templateRow - 1, $templateRow);
$templateColumns = [];
foreach ($iterator->current()->getCellIterator() as $cell) {
$templateColumns[$cell->getColumn()] = $cell->getValue();
}
$iterator = $worksheet->getRowIterator($startRow, $templateRow - 2);
foreach ($iterator as $row) {
foreach ($row->getCellIterator() as $cell) {
$cell->setValue($templateColumns[$cell->getColumn()]);
}
}
}
}

View File

@@ -0,0 +1,47 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Invoice\Renderer;
use App\Invoice\RendererInterface;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class CsvRenderer extends AbstractSpreadsheetRenderer implements RendererInterface
{
/**
* @return string[]
*/
protected function getFileExtensions()
{
return ['.csv'];
}
/**
* @return string
*/
protected function getContentType()
{
return 'text/csv';
}
/**
* @param Spreadsheet $spreadsheet
* @return bool|string
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
protected function saveSpreadsheet(Spreadsheet $spreadsheet)
{
$filename = tempnam(sys_get_temp_dir(), 'kimai-csv');
$writer = IOFactory::createWriter($spreadsheet, 'Csv');
$writer->save($filename);
return $filename;
}
}

View File

@@ -0,0 +1,88 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Invoice\Renderer;
use App\Entity\InvoiceDocument;
use App\Invoice\RendererInterface;
use App\Model\InvoiceModel;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor;
use Symfony\Component\HttpFoundation\File\Stream;
use Symfony\Component\HttpFoundation\Response;
class DocxRenderer extends AbstractRenderer implements RendererInterface
{
/*
protected function setPhpWordOptions(PhpWord $phpWord)
{
if (!extension_loaded('zip')) {
\PhpOffice\PhpWord\Settings::setZipClass(\PhpOffice\PhpWord\Settings::PCLZIP);
}
// \PhpOffice\PhpWord\Settings::setPdfRendererPath(__DIR__ . '/../../vendor/tecnickcom/tcpdf/');
// \PhpOffice\PhpWord\Settings::setPdfRendererName(\PhpOffice\PhpWord\Settings::PDF_RENDERER_TCPDF);
// \PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);
// $phpWord->getSettings()->setThemeFontLang(new Language(Language::EN_US));
$properties = $phpWord->getDocInfo();
$properties->setCreator('Kimai 2');
$properties->setDescription('Created with Kimai 2, the open-source time-tracking software! Get more information at www.kimai.org.');
$properties->setCreated(time());
$properties->setModified(time());
}
*/
/**
* @param InvoiceDocument $document
* @param InvoiceModel $model
* @return Response
*/
public function render(InvoiceDocument $document, InvoiceModel $model): Response
{
$filename = basename($document->getFilename());
$template = new TemplateProcessor($document->getFilename());
foreach ($this->modelToReplacer($model) as $key => $value) {
$template->setValue($key, $value);
}
$template->cloneRow('entry.description', count($model->getCalculator()->getEntries()));
$i = 1;
foreach ($model->getCalculator()->getEntries() as $entry) {
$values = $this->timesheetToArray($entry);
foreach ($values as $search => $replace) {
$template->setValue($search . '#' . $i, $replace);
}
$i++;
}
$cacheFile = $template->save();
clearstatcache(true, $cacheFile);
return $this->getFileResponse(new Stream($cacheFile), $filename);
}
/**
* @return string[]
*/
protected function getFileExtensions()
{
return ['.docx'];
}
/**
* @return string
*/
protected function getContentType()
{
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
}
}

View File

@@ -0,0 +1,47 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Invoice\Renderer;
use App\Invoice\RendererInterface;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class OdsRenderer extends AbstractSpreadsheetRenderer implements RendererInterface
{
/**
* @return string[]
*/
protected function getFileExtensions()
{
return ['.ods'];
}
/**
* @return string
*/
protected function getContentType()
{
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
}
/**
* @param Spreadsheet $spreadsheet
* @return bool|string
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
protected function saveSpreadsheet(Spreadsheet $spreadsheet)
{
$filename = tempnam(sys_get_temp_dir(), 'kimai-ods');
$writer = IOFactory::createWriter($spreadsheet, 'Ods');
$writer->save($filename);
return $filename;
}
}

View File

@@ -0,0 +1,180 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Invoice\Renderer;
use App\Entity\InvoiceDocument;
use App\Entity\Timesheet;
use App\Entity\UserPreference;
use App\Model\InvoiceModel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
trait RendererTrait
{
/**
* @return string[]
*/
abstract protected function getFileExtensions();
/**
* @return string
*/
abstract protected function getContentType();
/**
* @param InvoiceDocument $document
* @return bool
*/
public function supports(InvoiceDocument $document): bool
{
foreach ($this->getFileExtensions() as $extension) {
if (stripos($document->getFilename(), $extension) !== false) {
return true;
}
}
return false;
}
/**
* @param \DateTime $date
* @return mixed
*/
abstract protected function getFormattedDateTime(\DateTime $date);
/**
* @param $amount
* @return mixed
*/
abstract protected function getFormattedMoney($amount);
/**
* @param \DateTime $date
* @return mixed
*/
abstract protected function getFormattedMonthName(\DateTime $date);
/**
* @param $seconds
* @return mixed
*/
abstract protected function getFormattedDuration($seconds);
/**
* @param InvoiceModel $model
* @return array
*/
protected function modelToReplacer(InvoiceModel $model)
{
return [
'invoice.due_date' => $this->getFormattedDateTime($model->getDueDate()),
'invoice.date' => $this->getFormattedDateTime($model->getInvoiceDate()),
'invoice.number' => $model->getNumberGenerator()->getInvoiceNumber(),
'invoice.currency' => $model->getCalculator()->getCurrency(),
'invoice.vat' => $model->getCalculator()->getVat(),
'invoice.tax' => $this->getFormattedMoney($model->getCalculator()->getTax()),
'invoice.total_time' => $this->getFormattedDuration($model->getCalculator()->getTimeWorked()),
'invoice.total' => $this->getFormattedMoney($model->getCalculator()->getTotal()),
'invoice.subtotal' => $this->getFormattedMoney($model->getCalculator()->getSubtotal()),
'template.name' => $model->getTemplate()->getName(),
'template.company' => $model->getTemplate()->getCompany(),
'template.address' => $model->getTemplate()->getAddress(),
'template.title' => $model->getTemplate()->getTitle(),
'template.payment_terms' => $model->getTemplate()->getPaymentTerms(),
'template.due_days' => $model->getTemplate()->getDueDays(),
'query.begin' => $this->getFormattedDateTime($model->getQuery()->getBegin()),
'query.end' => $this->getFormattedDateTime($model->getQuery()->getEnd()),
'query.month' => $this->getFormattedMonthName($model->getQuery()->getBegin()),
'query.year' => $model->getQuery()->getBegin()->format('Y'),
'customer.address' => $model->getCustomer()->getAddress(),
'customer.name' => $model->getCustomer()->getName(),
'customer.contact' => $model->getCustomer()->getContact(),
'customer.company' => $model->getCustomer()->getCompany(),
'customer.number' => $model->getCustomer()->getNumber(),
'customer.country' => $model->getCustomer()->getCountry(),
'customer.homepage' => $model->getCustomer()->getHomepage(),
'customer.comment' => $model->getCustomer()->getComment(),
];
}
/**
* @param Timesheet $timesheet
* @return array
*/
protected function timesheetToArray(Timesheet $timesheet)
{
$rate = $timesheet->getRate();
$hourlyRate = $timesheet->getHourlyRate();
$amount = $this->getFormattedDuration($timesheet->getDuration());
$description = $timesheet->getDescription();
if (null !== $timesheet->getFixedRate()) {
$rate = $timesheet->getFixedRate();
$hourlyRate = $timesheet->getFixedRate();
$amount = 1;
}
if (empty($description)) {
$description = $timesheet->getActivity()->getName();
}
$user = $timesheet->getUser();
if (empty($hourlyRate)) {
$hourlyRate = $user->getPreferenceValue(UserPreference::HOURLY_RATE);
}
$activity = $timesheet->getActivity();
$project = $activity->getProject();
$customer = $project->getCustomer();
return [
'entry.description' => $description,
'entry.amount' => $amount,
'entry.rate' => $this->getFormattedMoney($hourlyRate),
'entry.total' => $this->getFormattedMoney($rate),
'entry.duration' => $timesheet->getDuration(),
'entry.begin' => $this->getFormattedDateTime($timesheet->getBegin()),
'entry.begin_timestamp' => $timesheet->getBegin()->getTimestamp(),
'entry.end' => $this->getFormattedDateTime($timesheet->getEnd()),
'entry.end_timestamp' => $timesheet->getEnd()->getTimestamp(),
'entry.date' => $this->getFormattedDateTime($timesheet->getBegin()),
'entry.user_id' => $user->getId(),
'entry.user_name' => $user->getUsername(),
'entry.user_alias' => $user->getAlias(),
'entry.activity' => $activity->getName(),
'entry.activity_id' => $activity->getId(),
'entry.project' => $project->getName(),
'entry.project_id' => $project->getId(),
'entry.customer' => $customer->getName(),
'entry.customer_id' => $customer->getId(),
];
}
/**
* @param mixed $file
* @param string $filename
* @return BinaryFileResponse
*/
protected function getFileResponse($file, $filename)
{
$response = new BinaryFileResponse($file);
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
$response->headers->set('Content-Type', $this->getContentType());
$response->headers->set('Content-Disposition', $disposition);
$response->deleteFileAfterSend(true);
return $response;
}
}

View File

@@ -0,0 +1,57 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Invoice\Renderer;
use App\Entity\InvoiceDocument;
use App\Invoice\RendererInterface;
use App\Model\InvoiceModel;
use Symfony\Component\HttpFoundation\Response;
class TwigRenderer implements RendererInterface
{
/**
* @var \Twig_Environment
*/
protected $twig;
/**
* @param \Twig_Environment $twig
*/
public function __construct(\Twig_Environment $twig)
{
$this->twig = $twig;
}
/**
* @param InvoiceDocument $document
* @return bool
*/
public function supports(InvoiceDocument $document): bool
{
return stripos($document->getFilename(), '.twig') !== false;
}
/**
* @param InvoiceDocument $document
* @param InvoiceModel $model
* @return Response
*/
public function render(InvoiceDocument $document, InvoiceModel $model): Response
{
$content = $this->twig->render('@invoice/' . basename($document->getFilename()), [
'model' => $model
]);
$response = new Response();
$response->setContent($content);
return $response;
}
}

View File

@@ -0,0 +1,47 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Invoice\Renderer;
use App\Invoice\RendererInterface;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class XlsxRenderer extends AbstractSpreadsheetRenderer implements RendererInterface
{
/**
* @return string[]
*/
protected function getFileExtensions()
{
return ['.xlsx', '.xls'];
}
/**
* @return string
*/
protected function getContentType()
{
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
}
/**
* @param Spreadsheet $spreadsheet
* @return bool|string
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
protected function saveSpreadsheet(Spreadsheet $spreadsheet)
{
$filename = tempnam(sys_get_temp_dir(), 'kimai-xslx');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($filename);
return $filename;
}
}