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:
@@ -312,18 +312,28 @@ class KimaiImporterCommand extends Command
|
||||
* This is checked against the Kimai version and database revision.
|
||||
*
|
||||
* @param SymfonyStyle $io
|
||||
* @param $requiredVersion
|
||||
* @param $requiredRevision
|
||||
* @param string $requiredVersion
|
||||
* @param string $requiredRevision
|
||||
* @return bool
|
||||
* @throws \Doctrine\DBAL\DBALException
|
||||
*/
|
||||
protected function checkDatabaseVersion(SymfonyStyle $io, $requiredVersion, $requiredRevision)
|
||||
{
|
||||
$versionQuery = 'SELECT `value` from ' . $this->dbPrefix . 'configuration WHERE `option` = "version"';
|
||||
$revisionQuery = 'SELECT `value` from ' . $this->dbPrefix . 'configuration WHERE `option` = "revision"';
|
||||
$version = $this->connection->createQueryBuilder()
|
||||
->select('value')
|
||||
->from($this->connection->quoteIdentifier($this->dbPrefix . 'configuration'))
|
||||
->where('option = :option')
|
||||
->setParameter(':option', 'version')
|
||||
->execute()
|
||||
->fetchColumn();
|
||||
|
||||
$version = $this->getImportConnection()->query($versionQuery)->fetchColumn();
|
||||
$revision = $this->getImportConnection()->query($revisionQuery)->fetchColumn();
|
||||
$revision = $this->connection->createQueryBuilder()
|
||||
->select('value')
|
||||
->from($this->connection->quoteIdentifier($this->dbPrefix . 'configuration'))
|
||||
->where('option = :option')
|
||||
->setParameter(':option', 'revision')
|
||||
->execute()
|
||||
->fetchColumn();
|
||||
|
||||
if (1 == version_compare($requiredVersion, $version)) {
|
||||
$io->error(
|
||||
@@ -378,21 +388,16 @@ class KimaiImporterCommand extends Command
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $table
|
||||
* @param string $table
|
||||
* @return array
|
||||
* @throws \Doctrine\DBAL\DBALException
|
||||
*/
|
||||
protected function fetchAllFromImport($table)
|
||||
{
|
||||
return $this->getImportConnection()->query('SELECT * from ' . $this->dbPrefix . $table)->fetchAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Doctrine\DBAL\Connection
|
||||
*/
|
||||
protected function getImportConnection()
|
||||
{
|
||||
return $this->connection;
|
||||
return $this->connection->createQueryBuilder()
|
||||
->select('*')
|
||||
->from($this->connection->quoteIdentifier($this->dbPrefix . $table))
|
||||
->execute()
|
||||
->fetchAll();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -792,7 +797,6 @@ class KimaiImporterCommand extends Command
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!$this->validateImport($io, $activity)) {
|
||||
throw new \Exception('Failed to validate activity: ' . $activity->getName());
|
||||
}
|
||||
@@ -932,15 +936,15 @@ class KimaiImporterCommand extends Command
|
||||
|
||||
$io->write('.');
|
||||
if (0 == $counter % 80) {
|
||||
$io->writeln(' ('.$counter.'/'.$total.')');
|
||||
$io->writeln(' (' . $counter . '/' . $total . ')');
|
||||
$entityManager->clear(Timesheet::class);
|
||||
}
|
||||
}
|
||||
|
||||
for ($i = 0; $i < 80-($counter%80); $i++) {
|
||||
for ($i = 0; $i < 80 - ($counter % 80); $i++) {
|
||||
$io->write(' ');
|
||||
}
|
||||
$io->writeln(' ('.$counter.'/'.$total.')');
|
||||
$io->writeln(' (' . $counter . '/' . $total . ')');
|
||||
|
||||
if ($activityCounter > 0) {
|
||||
$io->success('Created new (previously global) activities during timesheet import: ' . $activityCounter);
|
||||
|
||||
@@ -76,7 +76,7 @@ class InvoiceController extends AbstractController
|
||||
}
|
||||
|
||||
/**
|
||||
* @Route(path="/", name="invoice", methods={"GET", "POST"})
|
||||
* @Route(path="/", name="invoice", methods={"GET"})
|
||||
*
|
||||
* @param Request $request
|
||||
* @return \Symfony\Component\HttpFoundation\Response
|
||||
@@ -102,14 +102,53 @@ class InvoiceController extends AbstractController
|
||||
|
||||
$model = $this->prepareModel($query, $entries);
|
||||
|
||||
$action = null;
|
||||
if ($query->getTemplate() !== null) {
|
||||
$action = $this->service->getRendererActionByName($query->getTemplate()->getRenderer());
|
||||
return $this->render('invoice/index.html.twig', [
|
||||
'model' => $model,
|
||||
'form' => $form->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @Route(path="/print", name="invoice_print", methods={"GET"})
|
||||
*
|
||||
* @param Request $request
|
||||
* @return \Symfony\Component\HttpFoundation\Response
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function printAction(Request $request)
|
||||
{
|
||||
if (!$this->invoiceRepository->hasTemplate()) {
|
||||
return $this->redirectToRoute('admin_invoice_template_create');
|
||||
}
|
||||
|
||||
$query = $this->getDefaultQuery();
|
||||
$form = $this->getToolbarForm($query);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if (!$form->isSubmitted() || !$form->isValid()) {
|
||||
return $this->redirectToRoute('invoice');
|
||||
}
|
||||
|
||||
/** @var InvoiceQuery $query */
|
||||
$query = $form->getData();
|
||||
$entries = $this->getEntries($query);
|
||||
$model = $this->prepareModel($query, $entries);
|
||||
|
||||
$document = $this->service->getDocumentByName($model->getTemplate()->getRenderer());
|
||||
if (null === $document) {
|
||||
throw new \Exception('Unknown invoice document: ' . $model->getTemplate()->getRenderer());
|
||||
}
|
||||
|
||||
foreach ($this->service->getRenderer() as $renderer) {
|
||||
if ($renderer->supports($document)) {
|
||||
return $renderer->render($document, $model);
|
||||
}
|
||||
}
|
||||
|
||||
$this->flashError('Cannot render invoice: ' . $model->getTemplate()->getRenderer() . ' (' . $document->getName() . ')');
|
||||
|
||||
return $this->render('invoice/index.html.twig', [
|
||||
'model' => $model,
|
||||
'action' => $action,
|
||||
'form' => $form->createView(),
|
||||
]);
|
||||
}
|
||||
@@ -142,11 +181,12 @@ class InvoiceController extends AbstractController
|
||||
protected function prepareModel(InvoiceQuery $query, array $entries)
|
||||
{
|
||||
$model = new InvoiceModel();
|
||||
$model->setQuery($query);
|
||||
$model->setEntries($entries);
|
||||
$model->setCustomer($query->getCustomer());
|
||||
$model
|
||||
->setQuery($query)
|
||||
->setEntries($entries)
|
||||
->setCustomer($query->getCustomer())
|
||||
;
|
||||
|
||||
$action = null;
|
||||
if ($query->getTemplate() !== null) {
|
||||
$generator = $this->service->getNumberGeneratorByName($query->getTemplate()->getNumberGenerator());
|
||||
if (null === $generator) {
|
||||
@@ -278,6 +318,9 @@ class InvoiceController extends AbstractController
|
||||
return $this->createForm(InvoiceToolbarForm::class, $query, [
|
||||
'action' => $this->generateUrl('invoice', []),
|
||||
'method' => 'GET',
|
||||
'attr' => [
|
||||
'id' => 'invoice-print-form'
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
<?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\Controller;
|
||||
|
||||
use App\Model\InvoiceModel;
|
||||
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
|
||||
|
||||
/**
|
||||
* Controller used to print invoices.
|
||||
*
|
||||
* @Security("is_granted('ROLE_TEAMLEAD')")
|
||||
*/
|
||||
class InvoicePrintController extends AbstractController
|
||||
{
|
||||
/**
|
||||
* @param InvoiceModel $model
|
||||
* @return \Symfony\Component\HttpFoundation\Response
|
||||
*/
|
||||
public function printInvoice(InvoiceModel $model)
|
||||
{
|
||||
return $this->render('invoice/renderer/invoice.html.twig', [
|
||||
'model' => $model,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param InvoiceModel $model
|
||||
* @return \Symfony\Component\HttpFoundation\Response
|
||||
*/
|
||||
public function printTimesheet(InvoiceModel $model)
|
||||
{
|
||||
return $this->render('invoice/renderer/timesheet.html.twig', [
|
||||
'model' => $model,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param InvoiceModel $model
|
||||
* @return \Symfony\Component\HttpFoundation\Response
|
||||
*/
|
||||
public function printFreelancer(InvoiceModel $model)
|
||||
{
|
||||
return $this->render('invoice/renderer/freelancer.html.twig', [
|
||||
'model' => $model,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use App\Entity\InvoiceTemplate;
|
||||
use Doctrine\Bundle\FixturesBundle\Fixture;
|
||||
use Doctrine\Common\Persistence\ObjectManager;
|
||||
use Faker\Factory;
|
||||
use Faker\Generator;
|
||||
|
||||
/**
|
||||
* Defines the sample data to load in the database when running the unit and
|
||||
@@ -28,107 +29,92 @@ class InvoiceFixtures extends Fixture
|
||||
*/
|
||||
public function load(ObjectManager $manager)
|
||||
{
|
||||
$this->loadInvoiceTemplate($manager);
|
||||
$this->loadFreelancerTemplate($manager);
|
||||
$this->loadTimesheetTemplate($manager);
|
||||
foreach ($this->getInvoiceConfigs() as $invoiceConfig) {
|
||||
$template = new InvoiceTemplate();
|
||||
|
||||
// name, title, renderer, calculator, numberGenerator, company, vat, dueDays, address, paymentTerms
|
||||
$template
|
||||
->setName($invoiceConfig[0])
|
||||
->setTitle($invoiceConfig[1])
|
||||
->setRenderer($invoiceConfig[2])
|
||||
->setCalculator($invoiceConfig[3])
|
||||
->setNumberGenerator($invoiceConfig[4])
|
||||
->setCompany($invoiceConfig[5])
|
||||
->setVat($invoiceConfig[6])
|
||||
->setDueDays($invoiceConfig[7])
|
||||
->setAddress($invoiceConfig[8])
|
||||
->setPaymentTerms($invoiceConfig[9])
|
||||
;
|
||||
|
||||
$manager->persist($template);
|
||||
$manager->flush();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ObjectManager $manager
|
||||
*/
|
||||
private function loadInvoiceTemplate(ObjectManager $manager)
|
||||
private function getInvoiceConfigs()
|
||||
{
|
||||
$faker = Factory::create();
|
||||
|
||||
$template = new InvoiceTemplate();
|
||||
$template
|
||||
->setName('Invoice')
|
||||
->setTitle('Your company name')
|
||||
->setCompany($faker->company)
|
||||
->setVat(19)
|
||||
->setDueDays(30)
|
||||
->setRenderer('default')
|
||||
->setCalculator('default')
|
||||
->setNumberGenerator('default')
|
||||
->setPaymentTerms(
|
||||
'I would like to thank you for your confidence and will gladly be there for you in the future.' .
|
||||
PHP_EOL .
|
||||
'Please transfer the total amount within 14 days to the given account and use the invoice number ' .
|
||||
'as reference.'
|
||||
)
|
||||
->setAddress(
|
||||
$faker->streetAddress . PHP_EOL .
|
||||
$faker->city . ', ' . $faker->stateAbbr . ' ' . $faker->postcode . PHP_EOL .
|
||||
'Phone: ' . $faker->phoneNumber . PHP_EOL .
|
||||
'Email: ' . $faker->safeEmail
|
||||
)
|
||||
$paymentTerms =
|
||||
'I would like to thank you for your confidence and will gladly be there for you in the future.' .
|
||||
PHP_EOL .
|
||||
'Please transfer the total amount within 14 days to the given account and use the invoice number ' .
|
||||
'as reference.'
|
||||
;
|
||||
|
||||
$manager->persist($template);
|
||||
$manager->flush();
|
||||
$address =
|
||||
$faker->streetAddress . PHP_EOL .
|
||||
$faker->city . ', ' . $faker->stateAbbr . ' ' . $faker->postcode . PHP_EOL .
|
||||
'Phone: ' . $faker->phoneNumber . PHP_EOL .
|
||||
'Email: ' . $faker->safeEmail
|
||||
;
|
||||
|
||||
$paymentTerms_de =
|
||||
'Bitte überweisen Sie den Gesamtbetrag innerhalb von 14 Tagen nach Erhalt der Rechnung auf das unten genannte Konto. Verwenden Sie bitte als Betreff Ihrer Überweisung die Rechnungsnummer.' .
|
||||
PHP_EOL .
|
||||
PHP_EOL .
|
||||
'Ich bedanke mich für das entgegengebrachte Vertrauen. Gerne bin ich auch künftig für Sie da.' .
|
||||
PHP_EOL .
|
||||
PHP_EOL .
|
||||
'Mit freundlichen Grüßen,' .
|
||||
PHP_EOL .
|
||||
'Max Müller'
|
||||
;
|
||||
|
||||
// name, title, renderer, calculator, numberGenerator, company, vat, dueDays, address, paymentTerms
|
||||
return [
|
||||
['Invoice (HTML)', 'Company name', 'default', 'default', 'default', $faker->company, 19, 30, $address, $paymentTerms],
|
||||
['Freelancer (HTML, short)', 'Invoice', 'freelancer', 'short', 'default', $faker->company, 19, 14, $this->generateAddress($faker), $paymentTerms_de],
|
||||
['Timesheet (HTML)', 'Timesheet', 'timesheet', 'default', 'default', $faker->company, 19, 7, $this->generateAddress($faker), ''],
|
||||
['Company invoice (DOCX)', 'Invoice', 'company', 'default', 'default', 'Kimai Inc.', 19, 14, $this->generateAddress($faker, true), $this->generatePaymentTerms($faker)],
|
||||
['Export (CSV, user-group)', 'User-grouped', 'export', 'user', 'default', $faker->company, 7, 28, '', ''],
|
||||
['Export (ODS)', 'Spreadsheet', 'open-spreadsheet', 'default', 'default', $faker->company, 19, 14, '', ''],
|
||||
['Export (XLSX, user-group)', 'Spreadsheet', 'spreadsheet', 'user', 'default', $faker->company, 13, 10, '', ''],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ObjectManager $manager
|
||||
*/
|
||||
private function loadFreelancerTemplate(ObjectManager $manager)
|
||||
protected function generatePaymentTerms(Generator $faker)
|
||||
{
|
||||
$faker = Factory::create();
|
||||
|
||||
$template = new InvoiceTemplate();
|
||||
$template
|
||||
->setName('Freelancer')
|
||||
->setTitle('Rechnung')
|
||||
->setCompany($faker->company)
|
||||
->setVat(19)
|
||||
->setDueDays(14)
|
||||
->setRenderer('freelancer')
|
||||
->setCalculator('short')
|
||||
->setNumberGenerator('default')
|
||||
->setPaymentTerms(
|
||||
'Bitte überweisen Sie den Gesamtbetrag innerhalb von 14 Tagen nach Erhalt der Rechnung auf das unten genannte Konto. Verwenden Sie bitte als Betreff Ihrer Überweisung die Rechnungsnummer.' .
|
||||
PHP_EOL .
|
||||
PHP_EOL .
|
||||
'Ich bedanke mich für das entgegengebrachte Vertrauen. Gerne bin ich auch künftig für Sie da.' .
|
||||
PHP_EOL .
|
||||
PHP_EOL .
|
||||
'Mit freundlichen Grüßen,' .
|
||||
PHP_EOL .
|
||||
'Max Müller'
|
||||
)
|
||||
->setAddress(
|
||||
$faker->name . ' - ' . $faker->streetAddress . '-' . $faker->postcode . ' ' . $faker->city
|
||||
)
|
||||
return
|
||||
'Acme Bank' . PHP_EOL .
|
||||
'Account: ' . $faker->bankAccountNumber . PHP_EOL .
|
||||
'IBAN: ' . $faker->iban('DE')
|
||||
;
|
||||
|
||||
$manager->persist($template);
|
||||
$manager->flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ObjectManager $manager
|
||||
*/
|
||||
private function loadTimesheetTemplate(ObjectManager $manager)
|
||||
protected function generateAddress(Generator $faker, $lineBreaks = false)
|
||||
{
|
||||
$faker = Factory::create();
|
||||
if (!$lineBreaks) {
|
||||
return
|
||||
$faker->name . ' - ' .
|
||||
$faker->streetAddress . '-' .
|
||||
$faker->postcode . ' ' . $faker->city;
|
||||
}
|
||||
|
||||
$template = new InvoiceTemplate();
|
||||
$template
|
||||
->setName('Timesheet')
|
||||
->setTitle('Stundenzettel')
|
||||
->setCompany($faker->company)
|
||||
->setVat(19)
|
||||
->setDueDays(14)
|
||||
->setRenderer('timesheet')
|
||||
->setCalculator('default')
|
||||
->setNumberGenerator('default')
|
||||
->setPaymentTerms('')
|
||||
->setAddress(
|
||||
$faker->name . ' - ' . $faker->streetAddress . '-' . $faker->postcode . ' ' . $faker->city
|
||||
)
|
||||
return
|
||||
'Kimai Inc.' . PHP_EOL .
|
||||
$faker->streetAddress . PHP_EOL .
|
||||
$faker->city . ', ' . $faker->stateAbbr . ' ' . $faker->postcode
|
||||
;
|
||||
|
||||
$manager->persist($template);
|
||||
$manager->flush();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
namespace App\DependencyInjection;
|
||||
|
||||
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
|
||||
use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
|
||||
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
|
||||
@@ -39,10 +38,10 @@ class AppExtension extends Extension implements PrependExtensionInterface
|
||||
$container->setParameter('kimai.theme', $config['theme']);
|
||||
$container->setParameter('kimai.dashboard', $config['dashboard']);
|
||||
$container->setParameter('kimai.widgets', $config['widgets']);
|
||||
$container->setParameter('kimai.invoice.documents', $config['invoice']['documents']);
|
||||
|
||||
$this->createUserParameter($config, $container);
|
||||
$this->createTimesheetParameter($config, $container);
|
||||
$this->createInvoiceParameter($config, $container);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,25 +77,6 @@ class AppExtension extends Extension implements PrependExtensionInterface
|
||||
$container->setParameter('kimai.timesheet.markdown', $config['timesheet']['markdown_content']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $config
|
||||
* @param ContainerBuilder $container
|
||||
*/
|
||||
private function createInvoiceParameter(array $config, ContainerBuilder $container)
|
||||
{
|
||||
$keys = ['renderer', 'calculator', 'number_generator'];
|
||||
|
||||
foreach ($keys as $key) {
|
||||
if (!isset($config['invoice'][$key]) || 0 === count($config['invoice'][$key])) {
|
||||
throw new InvalidDefinitionException('Missing invoice configuration: kimai.invoice.' . $key);
|
||||
}
|
||||
|
||||
$container->setParameter('kimai.invoice.' . $key, $config['invoice'][$key]);
|
||||
}
|
||||
|
||||
$container->setParameter('kimai.invoice', $config['invoice']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ContainerBuilder $container
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?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\DependencyInjection\Compiler;
|
||||
|
||||
use App\Invoice\ServiceInvoice;
|
||||
use App\Kernel;
|
||||
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\DependencyInjection\Reference;
|
||||
|
||||
/**
|
||||
* Dynamically adds all dependencies to the InvoiceService.
|
||||
*/
|
||||
class InvoiceServiceCompilerPass implements CompilerPassInterface
|
||||
{
|
||||
/**
|
||||
* @param ContainerBuilder $container
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function process(ContainerBuilder $container)
|
||||
{
|
||||
// always first check if the primary service is defined
|
||||
if (!$container->has(ServiceInvoice::class)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$definition = $container->findDefinition(ServiceInvoice::class);
|
||||
|
||||
$taggedRenderer = $container->findTaggedServiceIds(Kernel::TAG_INVOICE_RENDERER);
|
||||
foreach ($taggedRenderer as $id => $tags) {
|
||||
$definition->addMethodCall('addRenderer', [new Reference($id)]);
|
||||
}
|
||||
|
||||
$taggedGenerator = $container->findTaggedServiceIds(Kernel::TAG_INVOICE_NUMBER_GENERATOR);
|
||||
foreach ($taggedGenerator as $id => $tags) {
|
||||
$definition->addMethodCall('addNumberGenerator', [new Reference($id)]);
|
||||
}
|
||||
|
||||
$taggedCalculator = $container->findTaggedServiceIds(Kernel::TAG_INVOICE_CALCULATOR);
|
||||
foreach ($taggedCalculator as $id => $tags) {
|
||||
$definition->addMethodCall('addCalculator', [new Reference($id)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,5 +29,17 @@ class TwigContextCompilerPass implements CompilerPassInterface
|
||||
|
||||
$twig->addMethodCall('addGlobal', ['kimai_context', $theme]);
|
||||
$twig->addMethodCall('addGlobal', ['duration_only', $durationOnly]);
|
||||
|
||||
if ($container->hasDefinition('twig.loader.native_filesystem')) {
|
||||
$definition = $container->getDefinition('twig.loader.native_filesystem');
|
||||
|
||||
$path = dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR;
|
||||
foreach ($container->getParameter('kimai.invoice.documents') as $invoicePath) {
|
||||
if (!is_dir($path . $invoicePath)) {
|
||||
continue;
|
||||
}
|
||||
$definition->addMethodCall('addPath', [$path . $invoicePath, 'invoice']);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +99,12 @@ class Configuration implements ConfigurationInterface
|
||||
->floatNode('factor')
|
||||
->isRequired()
|
||||
->defaultValue(1)
|
||||
->validate()
|
||||
->ifTrue(function ($value) {
|
||||
return $value <= 0;
|
||||
})
|
||||
->thenInvalid('A rate factor smaller or equals 0 is not allowed')
|
||||
->end()
|
||||
->end()
|
||||
->end()
|
||||
->end()
|
||||
@@ -116,32 +122,15 @@ class Configuration implements ConfigurationInterface
|
||||
$node = $builder->root('invoice');
|
||||
|
||||
$node
|
||||
->addDefaultsIfNotSet()
|
||||
->children()
|
||||
->arrayNode('renderer')
|
||||
->arrayNode('documents')
|
||||
->requiresAtLeastOneElement()
|
||||
->useAttributeAsKey('key')
|
||||
->isRequired()
|
||||
->prototype('scalar')->end()
|
||||
->scalarPrototype()->end()
|
||||
->defaultValue([
|
||||
'default' => 'App\Controller\InvoiceController::invoiceAction',
|
||||
])
|
||||
->end()
|
||||
->arrayNode('calculator')
|
||||
->requiresAtLeastOneElement()
|
||||
->useAttributeAsKey('key')
|
||||
->isRequired()
|
||||
->prototype('scalar')->end()
|
||||
->defaultValue([
|
||||
'default' => 'App\Invoice\DefaultCalculator',
|
||||
])
|
||||
->end()
|
||||
->arrayNode('number_generator')
|
||||
->requiresAtLeastOneElement()
|
||||
->useAttributeAsKey('key')
|
||||
->isRequired()
|
||||
->prototype('scalar')->end()
|
||||
->defaultValue([
|
||||
'default' => 'App\Invoice\DateNumberGenerator',
|
||||
'var/invoices/',
|
||||
'templates/invoice/renderer/'
|
||||
])
|
||||
->end()
|
||||
->end()
|
||||
|
||||
52
src/Entity/InvoiceDocument.php
Normal file
52
src/Entity/InvoiceDocument.php
Normal file
@@ -0,0 +1,52 @@
|
||||
<?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\Entity;
|
||||
|
||||
class InvoiceDocument
|
||||
{
|
||||
/**
|
||||
* @var \SplFileInfo
|
||||
*/
|
||||
private $file;
|
||||
|
||||
/**
|
||||
* @param \SplFileInfo $file
|
||||
*/
|
||||
public function __construct(\SplFileInfo $file)
|
||||
{
|
||||
$this->file = $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
$file = $this->file->getFilename();
|
||||
|
||||
return substr($file, 0, strpos($file, '.'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return basename($this->getFilename());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getFilename(): string
|
||||
{
|
||||
return $this->file->getRealPath();
|
||||
}
|
||||
}
|
||||
@@ -153,6 +153,8 @@ class Timesheet
|
||||
public function setEnd($end)
|
||||
{
|
||||
$this->end = $end;
|
||||
|
||||
// FIXME test and then remove it, this should not be neccessary
|
||||
if (null === $end) {
|
||||
$this->duration = 0;
|
||||
}
|
||||
|
||||
@@ -39,16 +39,17 @@ class InvoiceCalculatorType extends AbstractType
|
||||
public function configureOptions(OptionsResolver $resolver)
|
||||
{
|
||||
$renderer = [];
|
||||
foreach ($this->service->getCalculator() as $name => $class) {
|
||||
$renderer[$name] = $name;
|
||||
foreach ($this->service->getCalculator() as $calculator) {
|
||||
$renderer[$calculator->getId()] = $calculator->getId();
|
||||
}
|
||||
|
||||
$resolver->setDefaults([
|
||||
'label' => 'label.invoice_calculator',
|
||||
'choices' => $renderer,
|
||||
'choice_label' => function ($renderer) {
|
||||
return 'invoice_calculator.' . $renderer;
|
||||
}
|
||||
return $renderer;
|
||||
},
|
||||
'translation_domain' => 'invoice-calculator',
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,16 +39,17 @@ class InvoiceNumberGeneratorType extends AbstractType
|
||||
public function configureOptions(OptionsResolver $resolver)
|
||||
{
|
||||
$renderer = [];
|
||||
foreach ($this->service->getNumberGenerator() as $name => $class) {
|
||||
$renderer[$name] = $name;
|
||||
foreach ($this->service->getNumberGenerator() as $generator) {
|
||||
$renderer[$generator->getId()] = $generator->getId();
|
||||
}
|
||||
|
||||
$resolver->setDefaults([
|
||||
'label' => 'label.invoice_number_generator',
|
||||
'choices' => $renderer,
|
||||
'choice_label' => function ($renderer) {
|
||||
return 'invoice_number_generator.' . $renderer;
|
||||
}
|
||||
return $renderer;
|
||||
},
|
||||
'translation_domain' => 'invoice-numbergenerator',
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -38,20 +38,46 @@ class InvoiceRendererType extends AbstractType
|
||||
*/
|
||||
public function configureOptions(OptionsResolver $resolver)
|
||||
{
|
||||
$renderer = [];
|
||||
foreach ($this->service->getRenderer() as $name => $action) {
|
||||
$renderer[$name] = $name;
|
||||
$documents = [];
|
||||
foreach ($this->service->getDocuments() as $document) {
|
||||
foreach ($this->service->getRenderer() as $renderer) {
|
||||
if ($renderer->supports($document)) {
|
||||
$documents[$document->getId()] = $document->getName();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$resolver->setDefaults([
|
||||
'label' => 'label.invoice_renderer',
|
||||
'choices' => $renderer,
|
||||
'choice_label' => function ($renderer) {
|
||||
return 'invoice_renderer.' . $renderer;
|
||||
}
|
||||
'choices' => array_flip($documents),
|
||||
'group_by' => [$this, 'getGroupBy'],
|
||||
'choice_label' => function ($choiceValue, $key, $value) {
|
||||
return $choiceValue;
|
||||
},
|
||||
'translation_domain' => 'invoice-renderer',
|
||||
'docu_chapter' => 'invoices',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $value
|
||||
* @param string $label
|
||||
* @param string $index
|
||||
* @return string
|
||||
*/
|
||||
public function getGroupBy($value, $label, $index)
|
||||
{
|
||||
$renderer = $label;
|
||||
|
||||
return ucfirst(
|
||||
substr(
|
||||
$renderer,
|
||||
1 + strrpos($renderer, '.'),
|
||||
strrpos($renderer, '.')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
|
||||
@@ -7,18 +7,12 @@
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace App\Invoice;
|
||||
namespace App\Invoice\Calculator;
|
||||
|
||||
use App\Entity\Timesheet;
|
||||
use App\Model\InvoiceModel;
|
||||
|
||||
/**
|
||||
* Class DefaultCalculator works on all given entries using:
|
||||
* - the customers currency
|
||||
* - the invoice template vat rate
|
||||
* - the entries rate
|
||||
*/
|
||||
class DefaultCalculator implements CalculatorInterface
|
||||
abstract class AbstractCalculator
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
@@ -33,10 +27,12 @@ class DefaultCalculator implements CalculatorInterface
|
||||
/**
|
||||
* @return Timesheet[]
|
||||
*/
|
||||
public function getEntries()
|
||||
{
|
||||
return $this->model->getEntries();
|
||||
}
|
||||
abstract public function getEntries();
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
abstract public function getId(): string;
|
||||
|
||||
/**
|
||||
* @param InvoiceModel $model
|
||||
51
src/Invoice/Calculator/AbstractMergedCalculator.php
Normal file
51
src/Invoice/Calculator/AbstractMergedCalculator.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?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\Calculator;
|
||||
|
||||
use App\Entity\Timesheet;
|
||||
|
||||
abstract class AbstractMergedCalculator extends AbstractCalculator
|
||||
{
|
||||
/**
|
||||
* @param Timesheet $timesheet
|
||||
* @param Timesheet $entry
|
||||
*/
|
||||
protected function mergeTimesheets(Timesheet $timesheet, Timesheet $entry)
|
||||
{
|
||||
$timesheet->setUser($entry->getUser());
|
||||
$timesheet->setFixedRate($entry->getFixedRate()); // FIXME invoice
|
||||
$timesheet->setHourlyRate($entry->getHourlyRate()); // FIXME invoice
|
||||
$timesheet->setRate($timesheet->getRate() + $entry->getRate());
|
||||
$timesheet->setDuration($timesheet->getDuration() + $entry->getDuration());
|
||||
|
||||
if (null === $timesheet->getBegin() || $timesheet->getBegin()->getTimestamp() > $entry->getBegin()->getTimestamp()) {
|
||||
$timesheet->setBegin($entry->getBegin());
|
||||
}
|
||||
|
||||
if (null === $timesheet->getEnd() || $timesheet->getEnd()->getTimestamp() < $entry->getEnd()->getTimestamp()) {
|
||||
$timesheet->setEnd($entry->getEnd());
|
||||
}
|
||||
|
||||
if (null !== $this->model->getQuery()->getActivity()) {
|
||||
$timesheet->setActivity($this->model->getQuery()->getActivity());
|
||||
$timesheet->setDescription($this->model->getQuery()->getActivity()->getName());
|
||||
} elseif (null !== $this->model->getQuery()->getProject()) {
|
||||
$timesheet->setDescription($this->model->getQuery()->getProject()->getName());
|
||||
}
|
||||
|
||||
if (null === $timesheet->getActivity()) {
|
||||
$timesheet->setActivity($entry->getActivity());
|
||||
}
|
||||
|
||||
if (empty($timesheet->getDescription())) {
|
||||
$timesheet->setDescription($entry->getActivity()->getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
38
src/Invoice/Calculator/DefaultCalculator.php
Normal file
38
src/Invoice/Calculator/DefaultCalculator.php
Normal file
@@ -0,0 +1,38 @@
|
||||
<?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\Calculator;
|
||||
|
||||
use App\Entity\Timesheet;
|
||||
use App\Invoice\CalculatorInterface;
|
||||
|
||||
/**
|
||||
* Class DefaultCalculator works on all given entries using:
|
||||
* - the customers currency
|
||||
* - the invoice template vat rate
|
||||
* - the entries rate
|
||||
*/
|
||||
class DefaultCalculator extends AbstractCalculator implements CalculatorInterface
|
||||
{
|
||||
/**
|
||||
* @return Timesheet[]
|
||||
*/
|
||||
public function getEntries()
|
||||
{
|
||||
return $this->model->getEntries();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getId(): string
|
||||
{
|
||||
return 'default';
|
||||
}
|
||||
}
|
||||
47
src/Invoice/Calculator/ShortInvoiceCalculator.php
Normal file
47
src/Invoice/Calculator/ShortInvoiceCalculator.php
Normal 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\Calculator;
|
||||
|
||||
use App\Entity\Timesheet;
|
||||
use App\Invoice\CalculatorInterface;
|
||||
|
||||
/**
|
||||
* A calculator that sums up all timesheet records from the model and returns only one
|
||||
* entry for a compact invoice version.
|
||||
*/
|
||||
class ShortInvoiceCalculator extends AbstractMergedCalculator implements CalculatorInterface
|
||||
{
|
||||
/**
|
||||
* @return Timesheet[]
|
||||
*/
|
||||
public function getEntries()
|
||||
{
|
||||
$entries = $this->model->getEntries();
|
||||
if (empty($entries)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$timesheet = new Timesheet();
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$this->mergeTimesheets($timesheet, $entry);
|
||||
}
|
||||
|
||||
return [$timesheet];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getId(): string
|
||||
{
|
||||
return 'short';
|
||||
}
|
||||
}
|
||||
51
src/Invoice/Calculator/UserInvoiceCalculator.php
Normal file
51
src/Invoice/Calculator/UserInvoiceCalculator.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?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\Calculator;
|
||||
|
||||
use App\Entity\Timesheet;
|
||||
use App\Invoice\CalculatorInterface;
|
||||
|
||||
/**
|
||||
* A calculator that sums up the timesheet records by user.
|
||||
*/
|
||||
class UserInvoiceCalculator extends AbstractMergedCalculator implements CalculatorInterface
|
||||
{
|
||||
/**
|
||||
* @return Timesheet[]
|
||||
*/
|
||||
public function getEntries()
|
||||
{
|
||||
$entries = $this->model->getEntries();
|
||||
if (empty($entries)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
/** @var Timesheet[] $timesheets */
|
||||
$timesheets = [];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
if (!isset($timesheets[$entry->getUser()->getId()])) {
|
||||
$timesheets[$entry->getUser()->getId()] = new Timesheet();
|
||||
}
|
||||
$timesheet = $timesheets[$entry->getUser()->getId()];
|
||||
$this->mergeTimesheets($timesheet, $entry);
|
||||
}
|
||||
|
||||
return array_values($timesheets);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getId(): string
|
||||
{
|
||||
return 'user';
|
||||
}
|
||||
}
|
||||
@@ -72,4 +72,14 @@ interface CalculatorInterface
|
||||
* @return int
|
||||
*/
|
||||
public function getTimeWorked(): int;
|
||||
|
||||
/**
|
||||
* Returns the unique ID of this calculator.
|
||||
*
|
||||
* Prefix it with your company name followed by a hyphen (e.g. "acme-"),
|
||||
* if this is a third-party calculator.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getId(): string;
|
||||
}
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace App\Invoice;
|
||||
namespace App\Invoice\NumberGenerator;
|
||||
|
||||
use App\Invoice\NumberGeneratorInterface;
|
||||
use App\Model\InvoiceModel;
|
||||
|
||||
/**
|
||||
@@ -22,6 +23,14 @@ class DateNumberGenerator implements NumberGeneratorInterface
|
||||
*/
|
||||
protected $model;
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getId(): string
|
||||
{
|
||||
return 'default';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param InvoiceModel $model
|
||||
*/
|
||||
@@ -35,6 +44,6 @@ class DateNumberGenerator implements NumberGeneratorInterface
|
||||
*/
|
||||
public function getInvoiceNumber(): string
|
||||
{
|
||||
return date('ymd');
|
||||
return date('ymd', $this->model->getInvoiceDate()->getTimestamp());
|
||||
}
|
||||
}
|
||||
@@ -25,4 +25,14 @@ interface NumberGeneratorInterface
|
||||
* @return string
|
||||
*/
|
||||
public function getInvoiceNumber(): string;
|
||||
|
||||
/**
|
||||
* Returns the unique ID of this number generator.
|
||||
*
|
||||
* Prefix it with your company name followed by a hyphen (e.g. "acme-"),
|
||||
* if this is a third-party generator.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getId(): string;
|
||||
}
|
||||
|
||||
82
src/Invoice/Renderer/AbstractRenderer.php
Normal file
82
src/Invoice/Renderer/AbstractRenderer.php
Normal 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);
|
||||
}
|
||||
}
|
||||
129
src/Invoice/Renderer/AbstractSpreadsheetRenderer.php
Normal file
129
src/Invoice/Renderer/AbstractSpreadsheetRenderer.php
Normal 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()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
47
src/Invoice/Renderer/CsvRenderer.php
Normal file
47
src/Invoice/Renderer/CsvRenderer.php
Normal 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;
|
||||
}
|
||||
}
|
||||
88
src/Invoice/Renderer/DocxRenderer.php
Normal file
88
src/Invoice/Renderer/DocxRenderer.php
Normal 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';
|
||||
}
|
||||
}
|
||||
47
src/Invoice/Renderer/OdsRenderer.php
Normal file
47
src/Invoice/Renderer/OdsRenderer.php
Normal 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;
|
||||
}
|
||||
}
|
||||
180
src/Invoice/Renderer/RendererTrait.php
Normal file
180
src/Invoice/Renderer/RendererTrait.php
Normal 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;
|
||||
}
|
||||
}
|
||||
57
src/Invoice/Renderer/TwigRenderer.php
Normal file
57
src/Invoice/Renderer/TwigRenderer.php
Normal 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;
|
||||
}
|
||||
}
|
||||
47
src/Invoice/Renderer/XlsxRenderer.php
Normal file
47
src/Invoice/Renderer/XlsxRenderer.php
Normal 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;
|
||||
}
|
||||
}
|
||||
34
src/Invoice/RendererInterface.php
Normal file
34
src/Invoice/RendererInterface.php
Normal file
@@ -0,0 +1,34 @@
|
||||
<?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;
|
||||
|
||||
use App\Entity\InvoiceDocument;
|
||||
use App\Model\InvoiceModel;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
interface RendererInterface
|
||||
{
|
||||
/**
|
||||
* Checks whether the given InvoiceDocument can be rendered.
|
||||
*
|
||||
* @param InvoiceDocument $document
|
||||
* @return bool
|
||||
*/
|
||||
public function supports(InvoiceDocument $document): bool;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
@@ -9,34 +9,59 @@
|
||||
|
||||
namespace App\Invoice;
|
||||
|
||||
use App\Entity\InvoiceDocument;
|
||||
use App\Repository\InvoiceDocumentRepository;
|
||||
|
||||
/**
|
||||
* A service to manage the invoice configuration:
|
||||
* - invoice number generator
|
||||
* - invoice sum calculator
|
||||
* - template renderer
|
||||
* A service to manage invoice dependencies.
|
||||
*/
|
||||
class ServiceInvoice
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
* @var CalculatorInterface[]
|
||||
*/
|
||||
protected $config = [];
|
||||
protected $calculator = [];
|
||||
|
||||
/**
|
||||
* ServiceInvoice constructor.
|
||||
* @param array $invoiceConfig
|
||||
* @var RendererInterface[]
|
||||
*/
|
||||
public function __construct(array $invoiceConfig)
|
||||
protected $renderer = [];
|
||||
|
||||
/**
|
||||
* @var NumberGeneratorInterface[]
|
||||
*/
|
||||
protected $numberGenerator = [];
|
||||
|
||||
/**
|
||||
* @var InvoiceDocumentRepository
|
||||
*/
|
||||
protected $documents;
|
||||
|
||||
/**
|
||||
* @param InvoiceDocumentRepository $repository
|
||||
*/
|
||||
public function __construct(InvoiceDocumentRepository $repository)
|
||||
{
|
||||
$this->config = $invoiceConfig;
|
||||
$this->documents = $repository;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @param NumberGeneratorInterface $generator
|
||||
* @return $this
|
||||
*/
|
||||
public function addNumberGenerator(NumberGeneratorInterface $generator)
|
||||
{
|
||||
$this->numberGenerator[] = $generator;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return NumberGeneratorInterface[]
|
||||
*/
|
||||
public function getNumberGenerator()
|
||||
{
|
||||
return $this->config['number_generator'];
|
||||
return $this->numberGenerator;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -45,9 +70,9 @@ class ServiceInvoice
|
||||
*/
|
||||
public function getNumberGeneratorByName(string $name)
|
||||
{
|
||||
foreach ($this->getNumberGenerator() as $key => $class) {
|
||||
if ($key === $name) {
|
||||
return new $class();
|
||||
foreach ($this->getNumberGenerator() as $generator) {
|
||||
if ($generator->getId() === $name) {
|
||||
return $generator;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,11 +80,22 @@ class ServiceInvoice
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @param CalculatorInterface $calculator
|
||||
* @return $this
|
||||
*/
|
||||
public function addCalculator(CalculatorInterface $calculator)
|
||||
{
|
||||
$this->calculator[] = $calculator;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return CalculatorInterface[]
|
||||
*/
|
||||
public function getCalculator()
|
||||
{
|
||||
return $this->config['calculator'];
|
||||
return $this->calculator;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -68,38 +104,52 @@ class ServiceInvoice
|
||||
*/
|
||||
public function getCalculatorByName(string $name)
|
||||
{
|
||||
foreach ($this->getCalculator() as $key => $class) {
|
||||
if ($key === $name) {
|
||||
return new $class();
|
||||
foreach ($this->getCalculator() as $calculator) {
|
||||
if ($calculator->getId() === $name) {
|
||||
return $calculator;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return InvoiceDocument|null
|
||||
*/
|
||||
public function getDocumentByName(string $name)
|
||||
{
|
||||
return $this->documents->findByName($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of invoice renderer, which will consist of a unique name and a controller action.
|
||||
*
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
* @return InvoiceDocument[]
|
||||
*/
|
||||
public function getRenderer()
|
||||
public function getDocuments()
|
||||
{
|
||||
return $this->config['renderer'];
|
||||
return $this->documents->findAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $renderer
|
||||
* @return string|null
|
||||
* @param RendererInterface $renderer
|
||||
* @return $this
|
||||
*/
|
||||
public function getRendererActionByName($renderer)
|
||||
public function addRenderer(RendererInterface $renderer)
|
||||
{
|
||||
foreach ($this->config['renderer'] as $name => $action) {
|
||||
if ($name == $renderer) {
|
||||
return $action;
|
||||
}
|
||||
}
|
||||
$this->renderer[] = $renderer;
|
||||
|
||||
return null;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of invoice renderer.
|
||||
*
|
||||
* @return RendererInterface[]
|
||||
*/
|
||||
public function getRenderer()
|
||||
{
|
||||
return $this->renderer;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
<?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;
|
||||
|
||||
use App\Entity\Timesheet;
|
||||
|
||||
/**
|
||||
* A calculator that sums up all timesheet records from the model and returns only one
|
||||
* entry for a compact invoice version.
|
||||
*/
|
||||
class ShortInvoiceCalculator extends DefaultCalculator
|
||||
{
|
||||
/**
|
||||
* @return Timesheet[]
|
||||
*/
|
||||
public function getEntries()
|
||||
{
|
||||
$timesheet = new Timesheet();
|
||||
|
||||
foreach ($this->model->getEntries() as $entry) {
|
||||
$timesheet->setRate($timesheet->getRate() + $entry->getRate());
|
||||
$timesheet->setDuration($timesheet->getDuration() + $entry->getDuration());
|
||||
$timesheet->setBegin($entry->getBegin());
|
||||
if (null === $timesheet->getActivity()) {
|
||||
$timesheet->setActivity($entry->getActivity());
|
||||
}
|
||||
}
|
||||
|
||||
if (null !== $this->model->getQuery()->getActivity()) {
|
||||
$timesheet->setDescription($this->model->getQuery()->getActivity()->getName());
|
||||
} elseif (null !== $this->model->getQuery()->getProject()) {
|
||||
$timesheet->setDescription($this->model->getQuery()->getProject()->getName());
|
||||
}
|
||||
|
||||
return [$timesheet];
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,12 @@ namespace App;
|
||||
|
||||
use App\DependencyInjection\AppExtension;
|
||||
use App\DependencyInjection\Compiler\DoctrineCompilerPass;
|
||||
use App\DependencyInjection\Compiler\InvoiceServiceCompilerPass;
|
||||
use App\DependencyInjection\Compiler\TwigContextCompilerPass;
|
||||
use App\Timesheet\CalculatorInterface;
|
||||
use App\Invoice\CalculatorInterface as InvoiceCalculator;
|
||||
use App\Invoice\NumberGeneratorInterface;
|
||||
use App\Invoice\RendererInterface;
|
||||
use App\Timesheet\CalculatorInterface as TimesheetCalculator;
|
||||
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
|
||||
use Symfony\Component\Config\Loader\LoaderInterface;
|
||||
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
|
||||
@@ -26,6 +30,10 @@ class Kernel extends BaseKernel
|
||||
|
||||
public const CONFIG_EXTS = '.{php,xml,yaml,yml}';
|
||||
|
||||
public const TAG_INVOICE_RENDERER = 'invoice.renderer';
|
||||
public const TAG_INVOICE_NUMBER_GENERATOR = 'invoice.number_generator';
|
||||
public const TAG_INVOICE_CALCULATOR = 'invoice.calculator';
|
||||
|
||||
public function getCacheDir()
|
||||
{
|
||||
return $this->getProjectDir() . '/var/cache/' . $this->environment;
|
||||
@@ -38,7 +46,10 @@ class Kernel extends BaseKernel
|
||||
|
||||
protected function build(ContainerBuilder $container)
|
||||
{
|
||||
$container->registerForAutoconfiguration(CalculatorInterface::class)->addTag('timesheet.calculator');
|
||||
$container->registerForAutoconfiguration(TimesheetCalculator::class)->addTag('timesheet.calculator');
|
||||
$container->registerForAutoconfiguration(RendererInterface::class)->addTag(self::TAG_INVOICE_RENDERER);
|
||||
$container->registerForAutoconfiguration(NumberGeneratorInterface::class)->addTag(self::TAG_INVOICE_NUMBER_GENERATOR);
|
||||
$container->registerForAutoconfiguration(InvoiceCalculator::class)->addTag(self::TAG_INVOICE_CALCULATOR);
|
||||
}
|
||||
|
||||
public function registerBundles()
|
||||
@@ -68,6 +79,7 @@ class Kernel extends BaseKernel
|
||||
|
||||
$container->addCompilerPass(new DoctrineCompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, -1000);
|
||||
$container->addCompilerPass(new TwigContextCompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, -1000);
|
||||
$container->addCompilerPass(new InvoiceServiceCompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, -1000);
|
||||
}
|
||||
|
||||
protected function configureRoutes(RouteCollectionBuilder $routes)
|
||||
|
||||
@@ -17,7 +17,8 @@ use App\Invoice\NumberGeneratorInterface;
|
||||
use App\Repository\Query\InvoiceQuery;
|
||||
|
||||
/**
|
||||
* Class InvoiceModel is the ONLY value that a renderer template receives for generating the invoice.
|
||||
* InvoiceModel is the ONLY value that a RendererInterface receives for generating the invoice,
|
||||
* besides the InvoiceDocument which is used as a "template".
|
||||
*/
|
||||
class InvoiceModel
|
||||
{
|
||||
@@ -51,10 +52,20 @@ class InvoiceModel
|
||||
*/
|
||||
protected $generator;
|
||||
|
||||
/**
|
||||
* @var \DateTime
|
||||
*/
|
||||
protected $invoiceDate;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->invoiceDate = new \DateTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return InvoiceQuery
|
||||
*/
|
||||
public function getQuery(): InvoiceQuery
|
||||
public function getQuery(): ?InvoiceQuery
|
||||
{
|
||||
return $this->query;
|
||||
}
|
||||
@@ -103,7 +114,7 @@ class InvoiceModel
|
||||
* @param InvoiceTemplate $template
|
||||
* @return InvoiceModel
|
||||
*/
|
||||
public function setTemplate($template)
|
||||
public function setTemplate(InvoiceTemplate $template)
|
||||
{
|
||||
$this->template = $template;
|
||||
|
||||
@@ -132,8 +143,12 @@ class InvoiceModel
|
||||
/**
|
||||
* @return \DateTime
|
||||
*/
|
||||
public function getDueDate(): \DateTime
|
||||
public function getDueDate(): ?\DateTime
|
||||
{
|
||||
if (null === $this->getTemplate()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new \DateTime('+' . $this->getTemplate()->getDueDays() . ' days');
|
||||
}
|
||||
|
||||
@@ -142,7 +157,7 @@ class InvoiceModel
|
||||
*/
|
||||
public function getInvoiceDate(): \DateTime
|
||||
{
|
||||
return new \DateTime();
|
||||
return $this->invoiceDate;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -160,7 +175,7 @@ class InvoiceModel
|
||||
/**
|
||||
* @return NumberGeneratorInterface
|
||||
*/
|
||||
public function getNumberGenerator(): NumberGeneratorInterface
|
||||
public function getNumberGenerator(): ?NumberGeneratorInterface
|
||||
{
|
||||
return $this->generator;
|
||||
}
|
||||
@@ -180,7 +195,7 @@ class InvoiceModel
|
||||
/**
|
||||
* @return CalculatorInterface
|
||||
*/
|
||||
public function getCalculator(): CalculatorInterface
|
||||
public function getCalculator(): ?CalculatorInterface
|
||||
{
|
||||
return $this->calculator;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
namespace App\Model\Statistic;
|
||||
|
||||
/**
|
||||
* Yearly statistics
|
||||
* Monthly statistics
|
||||
*/
|
||||
class Month
|
||||
{
|
||||
@@ -28,11 +28,14 @@ class Month
|
||||
protected $totalRate = 0;
|
||||
|
||||
/**
|
||||
* Month constructor.
|
||||
* @param string $month
|
||||
*/
|
||||
public function __construct($month)
|
||||
public function __construct(string $month)
|
||||
{
|
||||
$monthNumber = (int) $month;
|
||||
if ($monthNumber < 1 || $monthNumber > 12) {
|
||||
throw new \InvalidArgumentException('Invalid month given, expected 01-12 but given: ' . $monthNumber);
|
||||
}
|
||||
$this->month = $month;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ class Year
|
||||
/**
|
||||
* @var Month[]
|
||||
*/
|
||||
protected $months;
|
||||
protected $months = [];
|
||||
|
||||
/**
|
||||
* Year constructor.
|
||||
@@ -52,10 +52,10 @@ class Year
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $month
|
||||
* @param int $month
|
||||
* @return null|Month
|
||||
*/
|
||||
public function getMonth($month)
|
||||
public function getMonth(int $month)
|
||||
{
|
||||
if (isset($this->months[$month])) {
|
||||
return $this->months[$month];
|
||||
|
||||
72
src/Repository/InvoiceDocumentRepository.php
Normal file
72
src/Repository/InvoiceDocumentRepository.php
Normal file
@@ -0,0 +1,72 @@
|
||||
<?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\Repository;
|
||||
|
||||
use App\Entity\InvoiceDocument;
|
||||
use Symfony\Component\Finder\Finder;
|
||||
|
||||
class InvoiceDocumentRepository
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $documentDirs = [];
|
||||
|
||||
/**
|
||||
* @param array $directories
|
||||
*/
|
||||
public function __construct(array $directories)
|
||||
{
|
||||
$this->documentDirs = $directories;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return InvoiceDocument|null
|
||||
*/
|
||||
public function findByName(string $name)
|
||||
{
|
||||
foreach ($this->findAll() as $document) {
|
||||
if ($document->getId() === $name) {
|
||||
return $document;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of invoice renderer, which will consist of a unique name and a controller action.
|
||||
*
|
||||
* @return InvoiceDocument[]
|
||||
*/
|
||||
public function findAll()
|
||||
{
|
||||
$base = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
|
||||
|
||||
$documents = [];
|
||||
|
||||
foreach ($this->documentDirs as $searchPath) {
|
||||
if (!is_dir($base . $searchPath)) {
|
||||
continue;
|
||||
}
|
||||
$finder = Finder::create()->ignoreDotFiles(true)->files()->in($base . $searchPath)->name('*.*');
|
||||
foreach ($finder->getIterator() as $file) {
|
||||
$doc = new InvoiceDocument($file);
|
||||
// the first found invoice document wins
|
||||
if (!isset($documents[$doc->getId()])) {
|
||||
$documents[$doc->getId()] = $doc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $documents;
|
||||
}
|
||||
}
|
||||
@@ -44,23 +44,4 @@ class InvoiceQuery extends TimesheetQuery
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return InvoiceTemplate[]
|
||||
*/
|
||||
public function getTemplates(): array
|
||||
{
|
||||
return $this->templates;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param InvoiceTemplate[] $templates
|
||||
* @return InvoiceQuery
|
||||
*/
|
||||
public function setTemplates(array $templates)
|
||||
{
|
||||
$this->templates = $templates;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ class RateCalculator implements CalculatorInterface
|
||||
$fixedRate = $this->findFixedRate($record);
|
||||
if (null !== $fixedRate) {
|
||||
$record->setRate($fixedRate);
|
||||
$record->setFixedRate($fixedRate);
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -51,9 +52,11 @@ class RateCalculator implements CalculatorInterface
|
||||
$hourlyRate = $this->findHourlyRate($record);
|
||||
$factor = $this->getRateFactor($record);
|
||||
|
||||
$record->setRate(
|
||||
$this->calculateRate($record->getDuration(), $hourlyRate, $factor)
|
||||
);
|
||||
$hourlyRate = (float) $hourlyRate * $factor;
|
||||
$rate = (float) $hourlyRate * ($record->getDuration() / 3600);
|
||||
|
||||
$record->setHourlyRate($hourlyRate);
|
||||
$record->setRate($rate);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,11 +130,6 @@ class RateCalculator implements CalculatorInterface
|
||||
$weekday = $record->getEnd()->format('l');
|
||||
$days = array_map('strtolower', $rateFactor['days']);
|
||||
if (in_array(strtolower($weekday), $days)) {
|
||||
if ($rateFactor['factor'] <= 0) {
|
||||
throw new \InvalidArgumentException(
|
||||
'A rate factor smaller or equals 0 is not allowed, given: ' . $rateFactor['factor']
|
||||
);
|
||||
}
|
||||
$factor += $rateFactor['factor'];
|
||||
}
|
||||
}
|
||||
@@ -142,15 +140,4 @@ class RateCalculator implements CalculatorInterface
|
||||
|
||||
return $factor;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $duration
|
||||
* @param float $hourlyRate
|
||||
* @param float $factor
|
||||
* @return float
|
||||
*/
|
||||
protected function calculateRate($duration, $hourlyRate, $factor)
|
||||
{
|
||||
return (float) $hourlyRate * ($duration / 3600) * $factor;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,8 +53,12 @@ class MarkdownExtension extends \Twig_Extension
|
||||
* @param string $content
|
||||
* @return string
|
||||
*/
|
||||
public function timesheetContent(string $content): string
|
||||
public function timesheetContent($content): string
|
||||
{
|
||||
if (empty($content)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($this->timesheetIsMarkdown) {
|
||||
return $this->markdown->toHtml($content, false);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user