added command to create invoices via bash (#1574)

This commit is contained in:
Kevin Papst
2020-03-20 13:14:05 +01:00
committed by GitHub
parent 7b13ea860a
commit b8c5323ece
35 changed files with 1301 additions and 273 deletions

View File

@@ -0,0 +1,248 @@
<?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\Tests\Command;
use App\Command\InvoiceCreateCommand;
use App\DataFixtures\UserFixtures;
use App\Entity\Customer;
use App\Entity\CustomerMeta;
use App\Entity\Project;
use App\Invoice\ServiceInvoice;
use App\Repository\CustomerRepository;
use App\Repository\InvoiceTemplateRepository;
use App\Repository\TimesheetRepository;
use App\Repository\UserRepository;
use App\Tests\DataFixtures\CustomerFixtures;
use App\Tests\DataFixtures\InvoiceFixtures;
use App\Tests\DataFixtures\ProjectFixtures;
use App\Tests\DataFixtures\TimesheetFixtures;
use App\Tests\KernelTestTrait;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;
/**
* @covers \App\Command\InvoiceCreateCommand
* @group integration
*/
class InvoiceCreateCommandTest extends KernelTestCase
{
use KernelTestTrait;
/**
* @var Application
*/
protected $application;
private function clearInvoiceFiles()
{
$path = __DIR__ . '/../_data/invoices/';
if (is_dir($path)) {
$files = glob($path . '*');
foreach ($files as $file) {
unlink($file);
}
}
}
protected function tearDown(): void
{
parent::tearDown();
$this->clearInvoiceFiles();
}
protected function setUp(): void
{
$this->clearInvoiceFiles();
$kernel = self::bootKernel();
$this->application = new Application($kernel);
$container = self::$container;
$this->application->add(new InvoiceCreateCommand(
$container->get(ServiceInvoice::class),
$container->get(TimesheetRepository::class),
$container->get(CustomerRepository::class),
$container->get(InvoiceTemplateRepository::class),
$container->get(UserRepository::class),
$container->get('event_dispatcher')
));
}
/**
'user'
'start'
'end'
'timezone'
'customer'
'template'
'search'
'exported'
'by-customer'
'by-project'
'set-exported'
'template-meta'
* @param $user
* @param array $params
* @return CommandTester
*/
protected function createInvoice(array $options = [])
{
$command = $this->application->find('kimai:invoice:create');
$commandTester = new CommandTester($command);
$commandTester->execute(array_merge($options, [
'command' => $command->getName(),
]));
return $commandTester;
}
protected function assertCommandErrors(array $options = [], string $errorMessage = '')
{
$commandTester = $this->createInvoice($options);
$output = $commandTester->getDisplay();
$this->assertStringContainsString('[ERROR] ' . $errorMessage, $output);
}
public function testCreateWithUnknownExportFilter()
{
$this->assertCommandErrors(['--user' => UserFixtures::USERNAME_SUPER_ADMIN, '--exported' => 'foo'], 'Unknown "exported" filter given');
}
public function testCreateWithMissingUser()
{
$this->assertCommandErrors([], 'You must set a "user" to create invoices');
}
public function testCreateWithInvalidUser()
{
$this->assertCommandErrors(['--user' => 'assdfd'], 'The given username "assdfd" could not be resolved');
}
public function testCreateWithMissingEnd()
{
$this->assertCommandErrors(['--user' => UserFixtures::USERNAME_SUPER_ADMIN, '--start' => '2020-01-01'], 'You need to supply a end date if a start date was given');
}
public function testCreateByCustomerAndByProject()
{
$this->assertCommandErrors(['--user' => UserFixtures::USERNAME_SUPER_ADMIN, '--by-customer' => null, '--by-project' => null], 'You cannot mix "by-customer" and "by-project"');
}
public function testCreateWithMissingGenerationMode()
{
$this->assertCommandErrors(['--user' => UserFixtures::USERNAME_SUPER_ADMIN], 'Could not determine generation mode');
}
public function testCreateWithMissingTemplate()
{
$this->assertCommandErrors(['--user' => UserFixtures::USERNAME_SUPER_ADMIN, '--customer' => 1], 'You must either pass the "template" or "template-meta" option');
}
public function testCreateWithInvalidStart()
{
$this->assertCommandErrors(['--user' => UserFixtures::USERNAME_SUPER_ADMIN, '--customer' => 1, '--exported' => 'exported', '--template' => 'x', '--start' => 'öäüß', '--end' => '2020-01-01'], 'Invalid start date given');
}
public function testCreateWithInvalidEnd()
{
$this->assertCommandErrors(['--user' => UserFixtures::USERNAME_SUPER_ADMIN, '--customer' => 1, '--template' => 'x', '--start' => '2020-01-01', '--end' => 'öäüß'], 'Invalid end date given');
}
public function testCreateWithInvalidCustomer()
{
$this->assertCommandErrors(['--user' => UserFixtures::USERNAME_SUPER_ADMIN, '--customer' => 3, '--template' => 'x'], 'Unknown customer ID: 3');
}
public function testCreateInvoice()
{
$fixture = new InvoiceFixtures();
$this->importFixture($this, $fixture);
$commandTester = $this->createInvoice(['--user' => UserFixtures::USERNAME_SUPER_ADMIN, '--set-exported' => null, '--customer' => 1, '--template' => 'Invoice', '--start' => '2020-01-01', '--end' => '2020-03-01']);
$output = $commandTester->getDisplay();
$this->assertStringContainsString('+----+----------+-------+------------- Created 1 invoice(s) --------------------------------------+', $output);
$this->assertStringContainsString('| ID | Customer | Total | Filename |', $output);
$this->assertStringContainsString('+----+----------+-------+-------------------------------------------------------------------------+', $output);
$this->assertStringContainsString('| 1 | Test | 0 EUR | /', $output);
$this->assertStringContainsString('/tests/_data/invoices/2020-001-test.html |', $output);
}
protected function prepareFixtures(\DateTime $start)
{
$em = self::$container->get('doctrine.orm.entity_manager');
$fixture = new CustomerFixtures();
$fixture->setAmount(1);
$fixture->setCallback(function (Customer $customer) {
$meta = new CustomerMeta();
$meta->setName('template');
$meta->setValue('Invoice');
$customer->setMetaField($meta);
});
$this->importFixture($em, $fixture);
$fixture = new ProjectFixtures();
$fixture->setCustomers([$em->getRepository(Customer::class)->find(2)]);
$fixture->setAmount(1);
$this->importFixture($em, $fixture);
$fixture = new TimesheetFixtures();
$fixture->setUser($this->getUserByName($em, UserFixtures::USERNAME_SUPER_ADMIN));
$fixture->setAmount(20);
$fixture->setStartDate($start);
$fixture->setProjects([$em->getRepository(Project::class)->find(2)]);
$this->importFixture($em, $fixture);
$fixture = new InvoiceFixtures();
$this->importFixture($em, $fixture);
}
public function testCreateInvoiceByCustomer()
{
$start = new \DateTime('-2 months');
$end = new \DateTime();
$this->prepareFixtures($start);
$commandTester = $this->createInvoice(['--user' => UserFixtures::USERNAME_SUPER_ADMIN, '--by-customer' => null, '--template-meta' => 'template', '--start' => $start->format('Y-m-d'), '--end' => $end->format('Y-m-d')]);
$output = $commandTester->getDisplay();
$this->assertStringContainsString('Created 1 invoice(s) ', $output);
}
public function testCreateInvoiceByCustomerId()
{
$start = new \DateTime('-2 months');
$end = new \DateTime();
$this->prepareFixtures($start);
$commandTester = $this->createInvoice(['--user' => UserFixtures::USERNAME_SUPER_ADMIN, '--customer' => '2,1', '--template-meta' => 'template', '--start' => $start->format('Y-m-d'), '--end' => $end->format('Y-m-d')]);
$output = $commandTester->getDisplay();
$this->assertStringContainsString('Created 1 invoice(s) ', $output);
}
public function testCreateInvoiceByProject()
{
$start = new \DateTime('-2 months');
$end = new \DateTime();
$this->prepareFixtures($start);
$commandTester = $this->createInvoice(['--user' => UserFixtures::USERNAME_SUPER_ADMIN, '--exported' => 'all', '--by-project' => null, '--template-meta' => 'template', '--start' => $start->format('Y-m-d'), '--end' => $end->format('Y-m-d')]);
$output = $commandTester->getDisplay();
$this->assertStringContainsString('Created 1 invoice(s) ', $output);
}
}

View File

@@ -26,14 +26,7 @@ class InvoiceControllerTest extends ControllerBaseTest
protected function setUp(): void
{
parent::setUp();
$path = __DIR__ . '/../_data/invoices/';
if (is_dir($path)) {
$files = glob($path . '*');
foreach ($files as $file) {
unlink($file);
}
}
$this->clearInvoiceFiles();
}
protected function tearDown(): void
@@ -144,7 +137,7 @@ class InvoiceControllerTest extends ControllerBaseTest
$this->assertEquals($template->getPaymentTerms(), $values['paymentTerms']);
}
public function testPrintAction()
public function testCreateAction()
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_TEAMLEAD);
/** @var EntityManager $em */
@@ -210,7 +203,66 @@ class InvoiceControllerTest extends ControllerBaseTest
}
}
public function testPrintActionAsAdminWithDownloadAndStatusChange()
public function testPrintAction()
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_TEAMLEAD);
/** @var EntityManager $em */
$em = static::$kernel->getContainer()->get('doctrine.orm.entity_manager');
$fixture = new InvoiceFixtures();
$this->importFixture($client, $fixture);
$begin = new \DateTime('first day of this month');
$end = new \DateTime('last day of this month');
$fixture = new TimesheetFixtures();
$fixture
->setUser($this->getUserByRole($em, User::ROLE_TEAMLEAD))
->setAmount(20)
->setStartDate($begin)
;
$this->importFixture($client, $fixture);
$this->request($client, '/invoice/');
$this->assertTrue($client->getResponse()->isSuccessful());
$dateRange = $begin->format('Y-m-d') . DateRangeType::DATE_SPACER . $end->format('Y-m-d');
$form = $client->getCrawler()->filter('#invoice-print-form')->form();
$node = $form->getFormNode();
$node->setAttribute('action', $this->createUrl('/invoice/?preview='));
$node->setAttribute('method', 'GET');
$client->submit($form, [
'template' => 1,
'daterange' => $dateRange,
'customer' => 1,
]);
$this->assertTrue($client->getResponse()->isSuccessful());
// no warning should be displayed
$node = $client->getCrawler()->filter('div.callout.callout-warning.lead');
$this->assertEquals(0, $node->count());
// but the datatable with all timesheets + 1 row for the total
$this->assertDataTableRowCount($client, 'datatable_invoice', 21);
$form = $client->getCrawler()->filter('#invoice-print-form')->form();
$node = $form->getFormNode();
$node->setAttribute('action', $this->createUrl('/invoice/?print='));
$node->setAttribute('method', 'GET');
$client->submit($form, [
'template' => 1,
'daterange' => $dateRange,
'customer' => 1,
'projects' => [1],
]);
$this->assertTrue($client->getResponse()->isSuccessful());
$node = $client->getCrawler()->filter('body');
$this->assertEquals(1, $node->count());
$this->assertEquals('invoice_print', $node->getIterator()[0]->getAttribute('class'));
}
public function testCreateActionAsAdminWithDownloadAndStatusChange()
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_ADMIN);
/** @var EntityManager $em */

View File

@@ -75,6 +75,8 @@ class InvoiceTemplateTest extends TestCase
self::assertInstanceOf(InvoiceTemplate::class, $sut->setLanguage('de'));
self::assertEquals('de', $sut->getLanguage());
self::assertEquals($sut, clone $sut);
}
public function testToString()

View File

@@ -0,0 +1,29 @@
<?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\Tests\Event;
use App\Entity\Invoice;
use App\Event\InvoiceCreatedEvent;
use PHPUnit\Framework\TestCase;
/**
* @covers \App\Event\InvoiceCreatedEvent
*/
class InvoiceCreatedEventTest extends TestCase
{
public function testDefaultValues()
{
$invoice = new Invoice();
$sut = new InvoiceCreatedEvent($invoice);
self::assertSame($invoice, $sut->getInvoice());
}
}

View File

@@ -47,6 +47,10 @@ class InvoiceModelCustomerHydratorTest extends TestCase
'customer.number',
'customer.homepage',
'customer.comment',
'customer.email',
'customer.fax',
'customer.phone',
'customer.mobile',
'customer.meta.foo-customer',
];

View File

@@ -14,8 +14,8 @@ use App\Entity\InvoiceTemplate;
use App\Entity\Timesheet;
use App\Invoice\Calculator\DefaultCalculator;
use App\Invoice\InvoiceModel;
use App\Invoice\NumberGenerator\DateNumberGenerator;
use App\Repository\Query\InvoiceQuery;
use App\Tests\Invoice\NumberGenerator\IncrementingNumberGenerator;
use PHPUnit\Framework\TestCase;
/**
@@ -43,6 +43,16 @@ class InvoiceModelTest extends TestCase
self::assertSame($formatter, $sut->getFormatter());
}
public function testEmptyObjectThrowsExceptionOnNumberGenerator()
{
$formatter = new DebugFormatter();
$sut = new InvoiceModel($formatter);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('InvoiceModel::getInvoiceNumber() cannot be called before calling setNumberGenerator()');
$sut->getInvoiceNumber();
}
public function testSetter()
{
$sut = new InvoiceModel(new DebugFormatter());
@@ -59,9 +69,14 @@ class InvoiceModelTest extends TestCase
self::assertInstanceOf(InvoiceModel::class, $sut->setCalculator($calculator));
self::assertSame($calculator, $sut->getCalculator());
$generator = new DateNumberGenerator();
$generator = new IncrementingNumberGenerator();
self::assertInstanceOf(InvoiceModel::class, $sut->setNumberGenerator($generator));
self::assertSame($generator, $sut->getNumberGenerator());
$number = $sut->getInvoiceNumber();
$first = $sut->getNumberGenerator()->getInvoiceNumber();
$second = $sut->getNumberGenerator()->getInvoiceNumber();
self::assertEquals(((int) $first + 1), $second);
self::assertEquals($number, $sut->getInvoiceNumber());
$template = new InvoiceTemplate();
self::assertNull($sut->getDueDate());

View File

@@ -0,0 +1,46 @@
<?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\Tests\Invoice\NumberGenerator;
use App\Invoice\InvoiceModel;
use App\Invoice\NumberGeneratorInterface;
class IncrementingNumberGenerator implements NumberGeneratorInterface
{
private $counter = 0;
/**
* @param InvoiceModel $model
*/
public function setModel(InvoiceModel $model)
{
}
/**
* @return string
*/
public function getInvoiceNumber(): string
{
return $this->counter++;
}
/**
* 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
{
return 'testing';
}
}

View File

@@ -58,7 +58,7 @@ class CsvRendererTest extends TestCase
$file = $response->getFile();
$this->assertEquals('text/csv', $response->headers->get('Content-Type'));
$filename = $model->getNumberGenerator()->getInvoiceNumber() . '-customer_with_special_name.csv';
$filename = $model->getInvoiceNumber() . '-customer_with_special_name.csv';
$this->assertEquals('attachment; filename=' . $filename, $response->headers->get('Content-Disposition'));
$this->assertTrue(file_exists($file->getRealPath()));

View File

@@ -119,6 +119,10 @@ class DebugRendererTest extends TestCase
'customer.number',
'customer.homepage',
'customer.comment',
'customer.email',
'customer.fax',
'customer.phone',
'customer.mobile',
'customer.meta.foo-customer',
'activity.id',
'activity.name',

View File

@@ -45,7 +45,7 @@ class DocxRendererTest extends TestCase
/** @var BinaryFileResponse $response */
$response = $sut->render($document, $model);
$filename = $model->getNumberGenerator()->getInvoiceNumber() . '-customer_with_special_name.docx';
$filename = $model->getInvoiceNumber() . '-customer_with_special_name.docx';
$file = $response->getFile();
$this->assertEquals('application/vnd.openxmlformats-officedocument.wordprocessingml.document', $response->headers->get('Content-Type'));
$this->assertEquals('attachment; filename=' . $filename, $response->headers->get('Content-Disposition'));

View File

@@ -56,7 +56,7 @@ class OdsRendererTest extends TestCase
/** @var BinaryFileResponse $response */
$response = $sut->render($document, $model);
$filename = $model->getNumberGenerator()->getInvoiceNumber() . '-customer_with_special_name.ods';
$filename = $model->getInvoiceNumber() . '-customer_with_special_name.ods';
$file = $response->getFile();
$this->assertEquals('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', $response->headers->get('Content-Type'));
$this->assertEquals('attachment; filename=' . $filename, $response->headers->get('Content-Disposition'));

View File

@@ -62,7 +62,7 @@ class TwigRendererTest extends KernelTestCase
$content = $response->getContent();
$filename = $model->getNumberGenerator()->getInvoiceNumber() . '-customer_with_special_name';
$filename = $model->getInvoiceNumber() . '-customer_with_special_name';
$this->assertStringContainsString('<title>' . $filename . '</title>', $content);
$this->assertStringContainsString('<h2 class="page-header">
<span contenteditable="true">a very *long* test invoice / template title with [special] character</span>

View File

@@ -57,7 +57,7 @@ class XlsxRendererTest extends TestCase
/** @var BinaryFileResponse $response */
$response = $sut->render($document, $model);
$filename = $model->getNumberGenerator()->getInvoiceNumber() . '-customer_with_special_name.xlsx';
$filename = $model->getInvoiceNumber() . '-customer_with_special_name.xlsx';
$file = $response->getFile();
$this->assertEquals('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', $response->headers->get('Content-Type'));
$this->assertEquals('attachment; filename=' . $filename, $response->headers->get('Content-Disposition'));

View File

@@ -9,12 +9,15 @@
namespace App\Tests\Invoice;
use App\Entity\Invoice;
use App\Entity\InvoiceDocument;
use App\Invoice\Calculator\DefaultCalculator;
use App\Invoice\NumberGenerator\DateNumberGenerator;
use App\Invoice\Renderer\TwigRenderer;
use App\Invoice\ServiceInvoice;
use App\Repository\InvoiceDocumentRepository;
use App\Repository\InvoiceRepository;
use App\Tests\Mocks\Security\UserDateTimeFactoryFactory;
use App\Utils\FileHelper;
use PHPUnit\Framework\TestCase;
use Twig\Environment;
@@ -27,8 +30,18 @@ class ServiceInvoiceTest extends TestCase
private function getSut(array $paths): ServiceInvoice
{
$repo = new InvoiceDocumentRepository($paths);
$invoiceRepo = $this->createMock(InvoiceRepository::class);
$userDateTime = (new UserDateTimeFactoryFactory($this))->create();
return new ServiceInvoice($repo, new FileHelper(realpath(__DIR__ . '/../../var/data/')));
return new ServiceInvoice($repo, new FileHelper(realpath(__DIR__ . '/../../var/data/')), $invoiceRepo, $userDateTime, new DebugFormatter());
}
public function testInvalidExceptionOnChangeState()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Unknown invoice status');
$sut = $this->getSut([]);
$sut->changeInvoiceStatus(new Invoice(), 'foo');
}
public function testEmptyObject()

View File

@@ -51,7 +51,7 @@
<div class="col-sm-5">
<p contenteditable="true">
<strong>{{ 'invoice.number'|trans({}, 'messages', language) }}:</strong>
{{ model.numberGenerator.invoiceNumber }}
{{ model.invoiceNumber }}
<br>
<strong>{{ 'invoice.due_days'|trans({}, 'messages', language) }}:</strong>

View File

@@ -15,6 +15,7 @@ use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\Loader;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\HttpKernel\HttpKernelBrowser;
/**
@@ -22,12 +23,18 @@ use Symfony\Component\HttpKernel\HttpKernelBrowser;
*/
trait KernelTestTrait
{
/**
* @param $client HttpKernelBrowser|EntityManager|KernelTestCase
* @param Fixture $fixture
*/
protected function importFixture($client, Fixture $fixture)
{
if ($client instanceof HttpKernelBrowser) {
$em = static::$kernel->getContainer()->get('doctrine.orm.entity_manager');
} elseif ($client instanceof EntityManager) {
$em = $client;
} elseif ($client instanceof KernelTestCase) {
$em = $client::$container->get('doctrine.orm.entity_manager');
} else {
throw new \InvalidArgumentException('Fixtures need an EntityManager to be imported');
}