support different formats in user timesheet exports (#1222)

This commit is contained in:
Kevin Papst
2019-11-08 16:10:38 +01:00
committed by GitHub
parent 0705c26513
commit fa1c79e15c
75 changed files with 1872 additions and 951 deletions

View File

@@ -0,0 +1,221 @@
<?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\Export\Timesheet;
use App\Configuration\LanguageFormattings;
use App\Entity\Activity;
use App\Entity\ActivityMeta;
use App\Entity\Customer;
use App\Entity\CustomerMeta;
use App\Entity\MetaTableTypeInterface;
use App\Entity\Project;
use App\Entity\ProjectMeta;
use App\Entity\Tag;
use App\Entity\Timesheet;
use App\Entity\TimesheetMeta;
use App\Entity\User;
use App\Event\ActivityMetaDisplayEvent;
use App\Event\CustomerMetaDisplayEvent;
use App\Event\ProjectMetaDisplayEvent;
use App\Event\TimesheetMetaDisplayEvent;
use App\Export\TimesheetExportInterface;
use App\Repository\Query\TimesheetQuery;
use App\Twig\DateExtensions;
use App\Utils\LocaleSettings;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
abstract class AbstractRendererTest extends KernelTestCase
{
/**
* @param string $classname
* @return TimesheetExportInterface
*/
protected function getAbstractRenderer(string $classname)
{
$requestStack = new RequestStack();
$languages = [
'en' => [
'date' => 'Y.m.d',
'duration' => '%h:%m h',
'time' => 'H:i',
]
];
$request = new Request();
$request->setLocale('en');
$requestStack->push($request);
$localeSettings = new LocaleSettings($requestStack, new LanguageFormattings($languages));
$translator = $this->getMockBuilder(TranslatorInterface::class)->getMock();
$dateExtension = new DateExtensions($localeSettings);
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new MetaFieldColumnSubscriber());
$authMock = $this->getMockBuilder(AuthorizationCheckerInterface::class)->getMock();
$authMock->method('isGranted')->willReturn(true);
return new $classname($translator, $dateExtension, $dispatcher, $authMock);
}
/**
* @param TimesheetExportInterface $renderer
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function render(TimesheetExportInterface $renderer)
{
$customer = new Customer();
$customer->setName('Customer Name');
$customer->setMetaField((new CustomerMeta())->setName('customer-foo')->setValue('customer-bar')->setIsVisible(true));
$project = new Project();
$project->setName('project name');
$project->setCustomer($customer);
$project->setMetaField((new ProjectMeta())->setName('project-bar')->setValue('project-bar')->setIsVisible(true));
$project->setMetaField((new ProjectMeta())->setName('project-foo2')->setValue('project-foo2')->setIsVisible(true));
$activity = new Activity();
$activity->setName('activity description');
$activity->setProject($project);
$activity->setMetaField((new ActivityMeta())->setName('activity-foo')->setValue('activity-bar')->setIsVisible(true));
$userMethods = ['getId', 'getPreferenceValue', 'getUsername'];
$user1 = $this->getMockBuilder(User::class)->onlyMethods($userMethods)->disableOriginalConstructor()->getMock();
$user1->method('getId')->willReturn(1);
$user1->method('getPreferenceValue')->willReturn('50');
$user1->method('getUsername')->willReturn('foo-bar');
$user2 = $this->getMockBuilder(User::class)->onlyMethods($userMethods)->disableOriginalConstructor()->getMock();
$user2->method('getId')->willReturn(2);
$user2->method('getUsername')->willReturn('hello-world');
$timesheet = new Timesheet();
$timesheet
->setDuration(3600)
->setRate(293.27)
->setUser($user1)
->setActivity($activity)
->setProject($project)
->setBegin(new \DateTime())
->setEnd(new \DateTime())
;
$timesheet2 = new Timesheet();
$timesheet2
->setDuration(400)
->setRate(84.75)
->setUser($user2)
->setActivity($activity)
->setProject($project)
->setBegin(new \DateTime())
->setEnd(new \DateTime())
;
$timesheet3 = new Timesheet();
$timesheet3
->setDuration(1800)
->setRate(111.11)
->setUser($user1)
->setActivity($activity)
->setProject($project)
->setBegin(new \DateTime())
->setEnd(new \DateTime())
;
$timesheet4 = new Timesheet();
$timesheet4
->setDuration(400)
->setRate(1947.99)
->setUser($user2)
->setActivity($activity)
->setProject($project)
->setBegin(new \DateTime())
->setEnd(new \DateTime())
->addTag((new Tag())->setName('foo'))
;
$timesheet5 = new Timesheet();
$timesheet5
->setDuration(400)
->setFixedRate(84)
->setUser((new User())->setUsername('kevin'))
->setActivity($activity)
->setProject($project)
->setBegin(new \DateTime('2019-06-16 12:00:00'))
->setEnd(new \DateTime('2019-06-16 12:06:40'))
->addTag((new Tag())->setName('foo'))
->addTag((new Tag())->setName('bar'))
->setMetaField((new TimesheetMeta())->setName('foo')->setValue('meta-bar')->setIsVisible(true))
->setMetaField((new TimesheetMeta())->setName('foo2')->setValue('meta-bar2')->setIsVisible(true))
;
$entries = [$timesheet, $timesheet2, $timesheet3, $timesheet4, $timesheet5];
$query = new TimesheetQuery();
$query->setActivity($activity);
$query->setBegin(new \DateTime());
$query->setEnd(new \DateTime());
$query->setProject($project);
return $renderer->render($entries, $query);
}
}
class MetaFieldColumnSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
TimesheetMetaDisplayEvent::class => ['loadTimesheetField', 200],
CustomerMetaDisplayEvent::class => ['loadCustomerField', 200],
ProjectMetaDisplayEvent::class => ['loadProjectField', 200],
ActivityMetaDisplayEvent::class => ['loadActivityField', 200],
];
}
public function loadTimesheetField(TimesheetMetaDisplayEvent $event)
{
$event->addField($this->prepareEntity(new TimesheetMeta(), 'foo'));
$event->addField($this->prepareEntity(new TimesheetMeta(), 'foo2'));
}
public function loadCustomerField(CustomerMetaDisplayEvent $event)
{
$event->addField($this->prepareEntity(new CustomerMeta(), 'customer-foo'));
}
public function loadProjectField(ProjectMetaDisplayEvent $event)
{
$event->addField($this->prepareEntity(new ProjectMeta(), 'project-foo'));
$event->addField($this->prepareEntity(new ProjectMeta(), 'project-foo2')->setIsVisible(false));
}
public function loadActivityField(ActivityMetaDisplayEvent $event)
{
$event->addField($this->prepareEntity(new ActivityMeta(), 'activity-foo'));
}
private function prepareEntity(MetaTableTypeInterface $meta, string $name)
{
return $meta
->setLabel('Working place')
->setName($name)
->setType(TextType::class)
->setIsVisible(true);
}
}

View File

@@ -0,0 +1,107 @@
<?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\Export\Timesheet;
use App\Export\Timesheet\CsvRenderer;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
/**
* @covers \App\Export\Base\CsvRenderer
* @covers \App\Export\Base\AbstractSpreadsheetRenderer
* @covers \App\Export\Base\RendererTrait
* @covers \App\Export\Timesheet\CsvRenderer
* @covers \App\Export\Timesheet\AbstractSpreadsheetRenderer
* @covers \App\Export\Timesheet\RendererTrait
* @group integration
*/
class CsvRendererTest extends AbstractRendererTest
{
public function testConfiguration()
{
$sut = $this->getAbstractRenderer(CsvRenderer::class);
$this->assertEquals('csv', $sut->getId());
}
public function getTestModel()
{
return [
['400', '2437.12', ' EUR 1,947.99 ', 7, 5, 1, 2, 2]
];
}
/**
* @dataProvider getTestModel
*/
public function testRender($totalDuration, $totalRate, $expectedRate, $expectedRows, $expectedDescriptions, $expectedUser1, $expectedUser2, $expectedUser3)
{
$sut = $this->getAbstractRenderer(CsvRenderer::class);
/** @var BinaryFileResponse $response */
$response = $this->render($sut);
$file = $response->getFile();
$this->assertEquals('text/csv', $response->headers->get('Content-Type'));
$this->assertEquals('attachment; filename=kimai-export.csv', $response->headers->get('Content-Disposition'));
$this->assertTrue(file_exists($file->getRealPath()));
$content = file_get_contents($file->getRealPath());
$this->assertStringContainsString('"' . $totalDuration . '"', $content);
$this->assertStringContainsString('"' . $totalRate . '"', $content);
$this->assertStringContainsString('"' . $expectedRate . '"', $content);
$this->assertEquals($expectedRows, substr_count($content, PHP_EOL));
$this->assertEquals($expectedDescriptions, substr_count($content, 'activity description'));
$this->assertEquals($expectedUser1, substr_count($content, ',"kevin",'));
$this->assertEquals($expectedUser3, substr_count($content, ',"hello-world",'));
$this->assertEquals($expectedUser2, substr_count($content, ',"foo-bar",'));
ob_start();
$response->sendContent();
$content2 = ob_get_clean();
$this->assertEquals($content, $content2);
$this->assertFalse(file_exists($file->getRealPath()));
$all = [];
$rows = str_getcsv($content2, PHP_EOL);
foreach ($rows as $row) {
$all[] = str_getcsv($row);
}
$expected = [
0 => '2019-06-16',
1 => '12:00',
2 => '12:06',
3 => '400',
4 => '0',
5 => 'kevin',
6 => 'Customer Name',
7 => 'project name',
8 => 'activity description',
9 => '',
10 => '',
11 => 'foo,bar',
12 => '',
13 => ' EUR 84.00 ',
14 => 'meta-bar',
15 => 'meta-bar2',
16 => 'customer-bar',
17 => '',
18 => 'project-foo2',
19 => 'activity-bar',
];
self::assertEquals(7, count($all));
self::assertEquals($expected, $all[5]);
self::assertEquals(count($expected), count($all[0]));
self::assertEquals('foo', $all[4][11]);
}
}

View 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\Tests\Export\Timesheet;
use App\Export\Timesheet\HtmlRenderer;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Twig\Environment;
/**
* @covers \App\Export\Timesheet\HtmlRenderer
* @group integration
*/
class HtmlRendererTest extends AbstractRendererTest
{
public function testConfiguration()
{
$sut = new HtmlRenderer(
$this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(),
new EventDispatcher()
);
$this->assertEquals('print', $sut->getId());
}
public function testRender()
{
$kernel = self::bootKernel();
/** @var Environment $twig */
$twig = $kernel->getContainer()->get('twig');
$stack = $kernel->getContainer()->get('request_stack');
$request = new Request();
$request->setLocale('en');
$stack->push($request);
$sut = new HtmlRenderer($twig, new EventDispatcher());
$response = $this->render($sut);
$content = $response->getContent();
$this->assertStringContainsString('<th>01:50 h</th>', $content);
}
}

View File

@@ -0,0 +1,65 @@
<?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\Export\Timesheet;
use App\Export\Timesheet\PDFRenderer;
use App\Tests\Mocks\Security\UserDateTimeFactoryFactory;
use App\Utils\HtmlToPdfConverter;
use App\Utils\MPdfConverter;
use Symfony\Component\HttpFoundation\Request;
use Twig\Environment;
/**
* @covers \App\Export\Base\PDFRenderer
* @covers \App\Export\Base\RendererTrait
* @covers \App\Export\Timesheet\PDFRenderer
* @covers \App\Export\Timesheet\RendererTrait
* @group integration
*/
class PdfRendererTest extends AbstractRendererTest
{
protected function getDateTimeFactory()
{
return (new UserDateTimeFactoryFactory($this))->create();
}
public function testConfiguration()
{
$sut = new PDFRenderer(
$this->getMockBuilder(Environment::class)->disableOriginalConstructor()->getMock(),
$this->getDateTimeFactory(),
$this->getMockBuilder(HtmlToPdfConverter::class)->getMock()
);
$this->assertEquals('pdf', $sut->getId());
}
public function testRender()
{
$kernel = self::bootKernel();
/** @var Environment $twig */
$twig = $kernel->getContainer()->get('twig');
$stack = $kernel->getContainer()->get('request_stack');
$cacheDir = $kernel->getContainer()->getParameter('kernel.cache_dir');
$converter = new MPdfConverter($cacheDir);
$request = new Request();
$request->setLocale('en');
$stack->push($request);
$sut = new PDFRenderer($twig, $this->getDateTimeFactory(), $converter);
$response = $this->render($sut);
$this->assertEquals('application/pdf', $response->headers->get('Content-Type'));
$this->assertEquals('attachment; filename=kimai-export.pdf', $response->headers->get('Content-Disposition'));
$this->assertNotEmpty($response->getContent());
}
}

View File

@@ -0,0 +1,53 @@
<?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\Export\Timesheet;
use App\Export\Timesheet\XlsxRenderer;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
/**
* @covers \App\Export\Base\XlsxRenderer
* @covers \App\Export\Base\AbstractSpreadsheetRenderer
* @covers \App\Export\Base\RendererTrait
* @covers \App\Export\Timesheet\XlsxRenderer
* @covers \App\Export\Timesheet\AbstractSpreadsheetRenderer
* @covers \App\Export\Timesheet\RendererTrait
* @group integration
*/
class XlsxRendererTest extends AbstractRendererTest
{
public function testConfiguration()
{
$sut = $this->getAbstractRenderer(XlsxRenderer::class);
$this->assertEquals('xlsx', $sut->getId());
}
public function testRender()
{
$sut = $this->getAbstractRenderer(XlsxRenderer::class);
/** @var BinaryFileResponse $response */
$response = $this->render($sut);
$file = $response->getFile();
$this->assertEquals('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', $response->headers->get('Content-Type'));
$this->assertEquals('attachment; filename=kimai-export.xlsx', $response->headers->get('Content-Disposition'));
$this->assertTrue(file_exists($file->getRealPath()));
ob_start();
$response->sendContent();
$content2 = ob_get_clean();
$this->assertNotEmpty($content2);
$this->assertFalse(file_exists($file->getRealPath()));
}
}