Added API endpoints to fetch invoices (#5070)

* added serializer attributes for API usage
* new setters to fill invoice data from fixture
* re-usable fixture helper methods
* added API endpoints to fetch invoices
* adjust tests
This commit is contained in:
Kevin Papst
2024-09-22 16:17:45 +02:00
committed by GitHub
parent 1965c35b43
commit 8de54e1fa7
20 changed files with 532 additions and 155 deletions

View File

@@ -40,6 +40,8 @@ nelmio_api_doc:
- { alias: TeamCollection, type: App\Entity\Team, groups: [Default, Collection, Team] }
- { alias: TeamMember, type: App\Entity\TeamMember, groups: [Team_Entity] }
- { alias: TeamMembership, type: App\Entity\TeamMember, groups: [User_Entity] }
- { alias: Invoice, type: App\Entity\Invoice, groups: [Default, Entity, Invoice, Invoice_Entity] }
- { alias: InvoiceCollection, type: App\Entity\Invoice, groups: [Default, Collection, Invoice] }
areas:
path_patterns:
- ^/api(?!/doc)

View File

@@ -0,0 +1,124 @@
<?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\API;
use App\Entity\Invoice;
use App\Entity\User;
use App\Repository\CustomerRepository;
use App\Repository\InvoiceRepository;
use App\Repository\Query\InvoiceArchiveQuery;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Request\ParamFetcherInterface;
use FOS\RestBundle\View\View;
use FOS\RestBundle\View\ViewHandlerInterface;
use OpenApi\Attributes as OA;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\Validator\Constraints;
#[Route(path: '/invoices')]
#[IsGranted('API')]
#[OA\Tag(name: 'Invoice')]
final class InvoiceController extends BaseApiController
{
public const GROUPS_ENTITY = ['Default', 'Entity', 'Invoice', 'Invoice_Entity'];
public const GROUPS_COLLECTION = ['Default', 'Collection', 'Invoice'];
public function __construct(
private readonly ViewHandlerInterface $viewHandler,
private readonly InvoiceRepository $repository,
) {
}
/**
* Returns a collection of invoices (which are visible to the user)
*
* Needs permission: view_invoice
*/
#[IsGranted('view_invoice')]
#[OA\Response(response: 200, description: 'Returns a collection of invoices', content: new OA\JsonContent(type: 'array', items: new OA\Items(ref: '#/components/schemas/InvoiceCollection')))]
#[Route(methods: ['GET'], path: '', name: 'get_invoices')]
#[Rest\QueryParam(name: 'begin', requirements: [new Constraints\DateTime(format: 'Y-m-d\TH:i:s')], strict: true, nullable: true, description: 'Only records after this date will be included (format: HTML5 datetime-local, e.g. YYYY-MM-DDThh:mm:ss)')]
#[Rest\QueryParam(name: 'end', requirements: [new Constraints\DateTime(format: 'Y-m-d\TH:i:s')], strict: true, nullable: true, description: 'Only records before this date will be included (format: HTML5 datetime-local, e.g. YYYY-MM-DDThh:mm:ss)')]
#[Rest\QueryParam(name: 'customers', map: true, requirements: '\d+', strict: true, nullable: true, default: [], description: 'List of customer IDs to filter, e.g.: customers[]=1&customers[]=2')]
#[Rest\QueryParam(name: 'status', map: true, requirements: 'pending|paid|canceled|new', strict: true, nullable: true, default: [], description: 'Invoice status: pending, paid, canceled, new. Default: all')]
#[Rest\QueryParam(name: 'page', requirements: '\d+', strict: true, nullable: true, description: 'The page to display, renders a 404 if not found (default: 1)')]
#[Rest\QueryParam(name: 'size', requirements: '\d+', strict: true, nullable: true, description: 'The amount of entries for each page (default: 50)')]
public function cgetAction(ParamFetcherInterface $paramFetcher, CustomerRepository $customerRepository): Response
{
/** @var User $user */
$user = $this->getUser();
$query = new InvoiceArchiveQuery();
$query->setCurrentUser($user);
$factory = $this->getDateTimeFactory();
$begin = $paramFetcher->get('begin');
if (\is_string($begin) && $begin !== '') {
$query->setBegin($factory->createDateTime($begin));
}
$end = $paramFetcher->get('end');
if (\is_string($end) && $end !== '') {
$query->setEnd($factory->createDateTime($end));
}
/** @var array<string> $status */
$status = $paramFetcher->get('status');
if (\is_array($status)) {
foreach ($status as $s) {
$query->addStatus($s);
}
}
$page = $paramFetcher->get('page');
if (\is_string($page) && $page !== '') {
$query->setPage((int) $page);
}
$size = $paramFetcher->get('size');
if (is_numeric($size)) {
$query->setPageSize((int) $size);
}
/** @var array<int> $customers */
$customers = $paramFetcher->get('customers');
foreach ($customerRepository->findByIds(array_unique($customers)) as $customer) {
$query->addCustomer($customer);
}
$query->setIsApiCall(true);
$data = $this->repository->getPagerfantaForQuery($query);
$results = (array) $data->getCurrentPageResults();
$view = new View($results, 200);
$view->getContext()->setGroups(self::GROUPS_COLLECTION);
$this->addPagination($view, $data);
return $this->viewHandler->handle($view);
}
/**
* Returns one invoice.
*
* Needs permission: view_invoice
*/
#[IsGranted('view_invoice')]
#[OA\Response(response: 200, description: 'Returns one invoice', content: new OA\JsonContent(ref: '#/components/schemas/Invoice'))]
#[Route(methods: ['GET'], path: '/{id}', name: 'get_invoice', requirements: ['id' => '\d+'])]
public function getAction(Invoice $invoice): Response
{
$view = new View($invoice, 200);
$view->getContext()->setGroups(self::GROUPS_ENTITY);
return $this->viewHandler->handle($view);
}
}

View File

@@ -25,6 +25,7 @@ use Symfony\Component\Validator\Constraints as Assert;
#[ORM\ChangeTrackingPolicy('DEFERRED_EXPLICIT')]
#[UniqueEntity('invoiceNumber')]
#[UniqueEntity('invoiceFilename')]
#[Serializer\ExclusionPolicy('all')]
#[Exporter\Order(['id', 'createdAt', 'invoiceNumber', 'status', 'customer', 'subtotal', 'total', 'tax', 'currency', 'vat', 'dueDays', 'dueDate', 'paymentDate', 'user', 'invoiceFilename', 'customerNumber', 'comment'])]
#[Exporter\Expose(name: 'customer', label: 'customer', exp: 'object.getCustomer() === null ? null : object.getCustomer().getName()')]
#[Exporter\Expose(name: 'customerNumber', label: 'number', exp: 'object.getCustomer() === null ? null : object.getCustomer().getNumber()')]
@@ -44,56 +45,78 @@ class Invoice implements EntityWithMetaFields
#[ORM\Column(name: 'id', type: 'integer')]
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'IDENTITY')]
#[Serializer\Expose]
#[Serializer\Groups(['Default'])]
#[Exporter\Expose(label: 'id', type: 'integer')]
private ?int $id = null;
#[ORM\Column(name: 'invoice_number', type: 'string', length: 50, nullable: false)]
#[Assert\NotNull]
#[Serializer\Expose]
#[Serializer\Groups(['Default'])]
#[Exporter\Expose(label: 'invoice.number', type: 'string')]
private ?string $invoiceNumber = null;
#[ORM\Column(name: 'comment', type: 'text', nullable: true)]
#[Serializer\Expose]
#[Serializer\Groups(['Customer_Entity'])]
#[Serializer\Groups(['Invoice'])]
#[Exporter\Expose(label: 'comment')]
private ?string $comment = null;
#[ORM\ManyToOne(targetEntity: Customer::class)]
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
#[Assert\NotNull]
#[Serializer\Expose]
#[Serializer\Groups(['Default'])]
private ?Customer $customer = null;
#[ORM\ManyToOne(targetEntity: User::class)]
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
#[Assert\NotNull]
#[Serializer\Expose]
#[Serializer\Groups(['Default'])]
private ?User $user = null;
#[ORM\Column(name: 'created_at', type: 'datetime', nullable: false)]
#[Assert\NotNull]
#[Serializer\Expose]
#[Serializer\Groups(['Default'])]
#[Exporter\Expose(label: 'date', type: 'datetime')]
private ?\DateTime $createdAt = null;
#[ORM\Column(name: 'timezone', type: 'string', length: 64, nullable: false)]
private ?string $timezone = null;
#[ORM\Column(name: 'total', type: 'float', nullable: false)]
#[Assert\NotNull]
#[Serializer\Expose]
#[Serializer\Groups(['Default'])]
#[Exporter\Expose(label: 'total_rate', type: 'float')]
private float $total = 0.00;
#[ORM\Column(name: 'tax', type: 'float', nullable: false)]
#[Assert\NotNull]
#[Serializer\Expose]
#[Serializer\Groups(['Default'])]
#[Exporter\Expose(label: 'invoice.tax', type: 'float')]
private float $tax = 0.00;
#[ORM\Column(name: 'currency', type: 'string', length: 3, nullable: false)]
#[Assert\NotNull]
#[Assert\Length(max: 3)]
#[Serializer\Expose]
#[Serializer\Groups(['Default'])]
#[Exporter\Expose(label: 'currency', type: 'string')]
private ?string $currency = null;
#[ORM\Column(name: 'due_days', type: 'integer', length: 3, nullable: false)]
#[Assert\NotNull]
#[Assert\Range(min: 0, max: 999)]
#[Serializer\Expose]
#[Serializer\Groups(['Invoice'])]
#[Exporter\Expose(label: 'due_days', type: 'integer')]
private int $dueDays = 30;
#[ORM\Column(name: 'vat', type: 'float', nullable: false)]
#[Assert\NotNull]
#[Assert\Range(min: 0.0, max: 99.99)]
#[Serializer\Expose]
#[Serializer\Groups(['Default'])]
#[Exporter\Expose(label: 'tax_rate', type: 'float')]
private float $vat = 0.00;
#[ORM\Column(name: 'status', type: 'string', length: 20, nullable: false)]
#[Assert\NotNull]
#[Serializer\Expose]
#[Serializer\Groups(['Default'])]
#[Exporter\Expose(label: 'status', type: 'string')]
private string $status = self::STATUS_NEW;
#[ORM\Column(name: 'invoice_filename', type: 'string', length: 150, nullable: false)]
@@ -103,6 +126,8 @@ class Invoice implements EntityWithMetaFields
private ?string $invoiceFilename = null;
private bool $localized = false;
#[ORM\Column(name: 'payment_date', type: 'date', nullable: true)]
#[Serializer\Expose]
#[Serializer\Groups(['Default'])]
private ?\DateTime $paymentDate = null;
/**
* Meta fields registered with the invoice
@@ -191,7 +216,6 @@ class Invoice implements EntityWithMetaFields
public function setModel(InvoiceModel $model): Invoice
{
$template = $model->getTemplate();
if ($template === null) {
throw new \InvalidArgumentException('Missing invoice template');
}
@@ -200,19 +224,25 @@ class Invoice implements EntityWithMetaFields
throw new \InvalidArgumentException('Missing due-days or vat setting');
}
$this->customer = $model->getCustomer();
$this->user = $model->getUser();
$this->total = $model->getCalculator()->getTotal();
$this->tax = $model->getCalculator()->getTax();
$this->invoiceNumber = $model->getInvoiceNumber();
$this->currency = $model->getCurrency();
$customer = $model->getCustomer();
if ($customer === null) {
throw new \InvalidArgumentException('Missing invoice customer');
}
$createdAt = $model->getInvoiceDate();
$this->createdAt = \DateTime::createFromInterface($createdAt);
$this->timezone = $createdAt->getTimezone()->getName();
$user = $model->getUser();
if ($user === null) {
throw new \InvalidArgumentException('Missing invoice user');
}
$this->dueDays = $template->getDueDays();
$this->vat = $template->getVat();
$this->setCustomer($customer);
$this->setUser($user);
$this->setTotal($model->getCalculator()->getTotal());
$this->setTax($model->getCalculator()->getTax());
$this->setInvoiceNumber($model->getInvoiceNumber());
$this->setCurrency($model->getCurrency());
$this->setCreatedAt($model->getInvoiceDate());
$this->setDueDays($template->getDueDays());
$this->setVat($template->getVat());
return $this;
}
@@ -380,6 +410,52 @@ class Invoice implements EntityWithMetaFields
return $this;
}
public function setVat(float $vat): void
{
$this->vat = $vat;
}
public function setInvoiceNumber(string $invoiceNumber): void
{
$this->invoiceNumber = $invoiceNumber;
}
public function setCustomer(Customer $customer): void
{
$this->customer = $customer;
}
public function setUser(User $user): void
{
$this->user = $user;
}
public function setCreatedAt(\DateTimeInterface $createdAt): void
{
$this->createdAt = \DateTime::createFromInterface($createdAt);
$this->timezone = $createdAt->getTimezone()->getName();
}
public function setTotal(float $total): void
{
$this->total = $total;
}
public function setTax(float $tax): void
{
$this->tax = $tax;
}
public function setCurrency(string $currency): void
{
$this->currency = $currency;
}
public function setDueDays(int $dueDays): void
{
$this->dueDays = $dueDays;
}
public function __clone()
{
if ($this->id) {

View File

@@ -19,9 +19,9 @@ use App\Repository\Query\InvoiceQuery;
final class InvoiceModelFactory
{
public function __construct(
private CustomerStatisticService $customerStatisticService,
private ProjectStatisticService $projectStatisticService,
private ActivityStatisticService $activityStatisticService
private readonly CustomerStatisticService $customerStatisticService,
private readonly ProjectStatisticService $projectStatisticService,
private readonly ActivityStatisticService $activityStatisticService
) {
}

View File

@@ -107,10 +107,10 @@ abstract class APIControllerBaseTest extends ControllerBaseTest
return $client->request($method, $this->createUrl($url), $parameters, [], $server, $content);
}
protected function assertEntityNotFound(string $role, string $url, string $method = 'GET', ?string $message = null): void
protected function assertEntityNotFound(string $role, string $url): void
{
$client = $this->getClientForAuthenticatedUser($role);
$this->request($client, $url, $method);
$this->request($client, $url);
$this->assertApiException($client->getResponse(), [
'code' => Response::HTTP_NOT_FOUND,
'message' => 'Not Found'
@@ -272,6 +272,25 @@ abstract class APIControllerBaseTest extends ControllerBaseTest
protected static function getExpectedResponseStructure(string $type): array
{
switch ($type) {
case 'Invoice':
case 'InvoiceCollection':
return [
'id' => 'int',
'comment' => '@string',
'createdAt' => 'datetime',
'currency' => 'string',
'customer' => ['result' => 'object', 'type' => '@Customer'],
'user' => ['result' => 'object', 'type' => '@User'],
'dueDays' => 'int',
'invoiceNumber' => 'string',
'metaFields' => 'array',
'paymentDate' => '@datetime',
'status' => 'string',
'tax' => 'float',
'total' => 'float',
'vat' => 'float',
];
case 'PageActionItem':
return [
'id' => 'string',

View File

@@ -245,7 +245,7 @@ class ActivityControllerTest extends APIControllerBaseTest
public function testNotFound(): void
{
$this->assertEntityNotFound(User::ROLE_USER, '/api/activities/' . PHP_INT_MAX, 'GET', 'App\\Entity\\Activity object not found by the @ParamConverter annotation.');
$this->assertEntityNotFound(User::ROLE_USER, '/api/activities/' . PHP_INT_MAX);
}
public function testPostAction(): void

View File

@@ -38,7 +38,7 @@ class ApiDocControllerTest extends ControllerBaseTest
}
}
$expectedKeys = ['Actions', 'Activity', 'Default', 'Customer', 'Project', 'Tag', 'Team', 'Timesheet', 'User'];
$expectedKeys = ['Actions', 'Activity', 'Default', 'Customer', 'Project', 'Tag', 'Team', 'Timesheet', 'User', 'Invoice'];
$actual = array_keys($tags);
sort($actual);
@@ -70,6 +70,8 @@ class ApiDocControllerTest extends ControllerBaseTest
'/api/customers/{id}/meta',
'/api/customers/{id}/rates',
'/api/customers/{id}/rates/{rateId}',
'/api/invoices',
'/api/invoices/{id}',
'/api/projects',
'/api/projects/{id}',
'/api/projects/{id}/meta',

View File

@@ -190,7 +190,7 @@ class CustomerControllerTest extends APIControllerBaseTest
public function testNotFound(): void
{
$this->assertEntityNotFound(User::ROLE_USER, '/api/customers/' . PHP_INT_MAX, 'GET', 'App\\Entity\\Customer object not found by the @ParamConverter annotation.');
$this->assertEntityNotFound(User::ROLE_USER, '/api/customers/' . PHP_INT_MAX);
}
public function testPostAction(): void

View File

@@ -0,0 +1,106 @@
<?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 API;
use App\Entity\Invoice;
use App\Entity\User;
use App\Tests\API\APIControllerBaseTest;
use App\Tests\DataFixtures\InvoiceFixtures;
/**
* @group integration
*/
class InvoiceControllerTest extends APIControllerBaseTest
{
/**
* @return Invoice[]
*/
protected function importInvoiceFixtures(int $amount, ?array $status = null): array
{
$fixture = new InvoiceFixtures();
$fixture->setAmount($amount);
if (\is_array($status)) {
$fixture->setStatus($status);
}
return $this->importFixture($fixture);
}
public function testIsSecure(): void
{
$this->assertUrlIsSecured('/api/invoices');
}
public function testGetCollection(): void
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_TEAMLEAD);
$this->importInvoiceFixtures(10);
$this->assertAccessIsGranted($client, '/api/invoices');
$content = $client->getResponse()->getContent();
$this->assertIsString($content);
$result = json_decode($content, true);
$this->assertIsArray($result);
$this->assertNotEmpty($result);
$this->assertEquals(10, \count($result));
self::assertApiResponseTypeStructure('InvoiceCollection', $result[0]);
}
public function testGetCollectionWithQuery(): void
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_TEAMLEAD);
$this->importInvoiceFixtures(5, [Invoice::STATUS_PENDING]);
$this->importInvoiceFixtures(2, [Invoice::STATUS_NEW]);
$this->importInvoiceFixtures(7, [Invoice::STATUS_PAID]);
$this->importInvoiceFixtures(1, [Invoice::STATUS_CANCELED]);
$query = ['order' => 'ASC', 'orderBy' => 'name', 'status' => [Invoice::STATUS_PAID]];
$this->assertAccessIsGranted($client, '/api/invoices', 'GET', $query);
$content = $client->getResponse()->getContent();
$this->assertIsString($content);
$result = json_decode($content, true);
$this->assertIsArray($result);
$this->assertNotEmpty($result);
$this->assertEquals(7, \count($result));
self::assertApiResponseTypeStructure('InvoiceCollection', $result[0]);
}
public function testGetEntityIsSecure(): void
{
$client = $this->getClientForAuthenticatedUser();
$invoices = $this->importInvoiceFixtures(1);
$this->assertApiAccessDenied($client, '/api/invoices/' . $invoices[0]->getId());
}
public function testGetEntity(): void
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_ADMIN);
$invoices = $this->importInvoiceFixtures(1);
$this->assertAccessIsGranted($client, '/api/invoices/' . $invoices[0]->getId());
$content = $client->getResponse()->getContent();
$this->assertIsString($content);
$result = json_decode($content, true);
$this->assertIsArray($result);
self::assertApiResponseTypeStructure('Invoice', $result);
}
public function testNotFound(): void
{
$this->assertEntityNotFound(User::ROLE_USER, '/api/invoices/' . PHP_INT_MAX);
}
}

View File

@@ -326,7 +326,7 @@ class ProjectControllerTest extends APIControllerBaseTest
public function testNotFound(): void
{
$this->assertEntityNotFound(User::ROLE_USER, '/api/projects/' . PHP_INT_MAX, 'GET', 'App\\Entity\\Project object not found by the @ParamConverter annotation.');
$this->assertEntityNotFound(User::ROLE_USER, '/api/projects/' . PHP_INT_MAX);
}
public function testPostAction(): void

View File

@@ -83,7 +83,7 @@ class TeamControllerTest extends APIControllerBaseTest
public function testNotFound(): void
{
$this->assertEntityNotFound(User::ROLE_USER, '/api/teams/' . PHP_INT_MAX, 'GET', 'App\\Entity\\Team object not found by the @ParamConverter annotation.');
$this->assertEntityNotFound(User::ROLE_USER, '/api/teams/' . PHP_INT_MAX);
}
public function testDeleteActionWithUnknownTeam(): void

View File

@@ -448,7 +448,7 @@ class TimesheetControllerTest extends APIControllerBaseTest
public function testGetEntityNotFound(): void
{
$this->assertEntityNotFound(User::ROLE_USER, '/api/timesheets/' . PHP_INT_MAX, 'GET', 'App\\Entity\\Timesheet object not found by the @ParamConverter annotation.');
$this->assertEntityNotFound(User::ROLE_USER, '/api/timesheets/' . PHP_INT_MAX);
}
public function testPostAction(): void

View File

@@ -19,6 +19,8 @@ use Faker\Factory;
*/
final class ActivityFixtures implements TestFixture
{
use FixturesTrait;
private int $amount = 0;
private bool $isGlobal = false;
private ?bool $isVisible = null;
@@ -127,20 +129,4 @@ final class ActivityFixtures implements TestFixture
return $created;
}
/**
* @param ObjectManager $manager
* @return array<int|string, Project>
*/
private function getAllProjects(ObjectManager $manager): array
{
$all = [];
/** @var Project[] $entries */
$entries = $manager->getRepository(Project::class)->findAll();
foreach ($entries as $temp) {
$all[$temp->getId()] = $temp;
}
return $all;
}
}

View File

@@ -34,7 +34,6 @@ final class CustomerFixtures implements TestFixture
* Will be called prior to persisting the object.
*
* @param callable $callback
* @return CustomerFixtures
*/
public function setCallback(callable $callback): CustomerFixtures
{
@@ -63,7 +62,6 @@ final class CustomerFixtures implements TestFixture
}
/**
* @param ObjectManager $manager
* @return Customer[]
*/
public function load(ObjectManager $manager): array

View File

@@ -0,0 +1,91 @@
<?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\DataFixtures;
use App\Entity\Activity;
use App\Entity\Customer;
use App\Entity\Project;
use App\Entity\User;
use Doctrine\Persistence\ObjectManager;
trait FixturesTrait
{
/**
* @return array<int, User>
*/
private function getAllUsers(ObjectManager $manager): array
{
$all = [];
/** @var User[] $entries */
$entries = $manager->getRepository(User::class)->findAll();
foreach ($entries as $temp) {
if ($temp->getId() === null) {
continue;
}
$all[$temp->getId()] = $temp;
}
return $all;
}
/**
* @return array<int, Customer>
*/
private function getAllCustomers(ObjectManager $manager): array
{
$all = [];
/** @var Customer[] $entries */
$entries = $manager->getRepository(Customer::class)->findAll();
foreach ($entries as $temp) {
if ($temp->getId() === null) {
continue;
}
$all[$temp->getId()] = $temp;
}
return $all;
}
/**
* @return array<int, Project>
*/
private function getAllProjects(ObjectManager $manager): array
{
$all = [];
/** @var Project[] $entries */
$entries = $manager->getRepository(Project::class)->findAll();
foreach ($entries as $temp) {
if ($temp->getId() === null) {
continue;
}
$all[$temp->getId()] = $temp;
}
return $all;
}
/**
* @return array<int, Activity>
*/
private function getAllActivities(ObjectManager $manager): array
{
$all = [];
/** @var Activity[] $entries */
$entries = $manager->getRepository(Activity::class)->findAll();
foreach ($entries as $temp) {
if ($temp->getId() === null) {
continue;
}
$all[$temp->getId()] = $temp;
}
return $all;
}
}

View File

@@ -0,0 +1,76 @@
<?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\DataFixtures;
use App\Entity\Invoice;
use Doctrine\Persistence\ObjectManager;
use Faker\Factory;
/**
* Defines the sample data to load in during controller tests.
*/
class InvoiceFixtures implements TestFixture
{
use FixturesTrait;
private int $amount = 50;
private array $status = [Invoice::STATUS_CANCELED, Invoice::STATUS_NEW, Invoice::STATUS_PAID, Invoice::STATUS_PENDING];
public function setAmount(int $amount = 50): void
{
$this->amount = $amount;
}
public function setStatus(array $status): void
{
$this->status = $status;
}
/**
* @return Invoice[]
*/
public function load(ObjectManager $manager): array
{
$created = [];
$faker = Factory::create();
$customers = $this->getAllCustomers($manager);
$users = $this->getAllUsers($manager);
for ($i = 0; $i < $this->amount; $i++) {
$total = $faker->randomFloat(2, 50, 5000);
$vat = $faker->randomFloat(2, 0, 23) / 10;
$tax = $total * $vat;
$invoice = new Invoice();
$invoice->setStatus($this->status[array_rand($this->status)]);
$invoice->setTotal($total);
$invoice->setVat($vat);
$invoice->setTax($tax);
$invoice->setCustomer($customers[array_rand($customers)]);
$invoice->setInvoiceNumber($i . '_ ' . $faker->text(10));
$invoice->setCreatedAt($faker->dateTimeBetween('-1 year', 'now'));
$invoice->setUser($users[array_rand($users)]);
$invoice->setDueDays($faker->randomNumber(2));
$invoice->setFilename($faker->text(30));
$invoice->setComment($faker->text(300));
$invoice->setCurrency($faker->currencyCode());
$manager->persist($invoice);
$created[] = $invoice;
}
$manager->flush();
return $created;
}
}

View File

@@ -19,7 +19,6 @@ use Faker\Factory;
class InvoiceTemplateFixtures implements TestFixture
{
/**
* @param ObjectManager $manager
* @return InvoiceTemplate[]
*/
public function load(ObjectManager $manager): array

View File

@@ -19,6 +19,8 @@ use Faker\Factory;
*/
final class ProjectFixtures implements TestFixture
{
use FixturesTrait;
private int $amount = 0;
private ?bool $isVisible = null;
/**
@@ -114,20 +116,4 @@ final class ProjectFixtures implements TestFixture
return $created;
}
/**
* @param ObjectManager $manager
* @return array<int|string, Customer>
*/
private function getAllCustomers(ObjectManager $manager): array
{
$all = [];
/** @var Customer[] $entries */
$entries = $manager->getRepository(Customer::class)->findAll();
foreach ($entries as $temp) {
$all[$temp->getId()] = $temp;
}
return $all;
}
}

View File

@@ -9,7 +9,6 @@
namespace App\Tests\DataFixtures;
use App\Entity\Customer;
use App\Entity\Team;
use App\Entity\User;
use Doctrine\Persistence\ObjectManager;
@@ -19,22 +18,15 @@ use Doctrine\Persistence\ObjectManager;
*/
final class TeamFixtures implements TestFixture
{
/**
* @var int
*/
private $amount = 0;
/**
* @var bool
*/
private $addCustomer = true;
use FixturesTrait;
private int $amount = 0;
private bool $addCustomer = true;
/**
* @var User[]
*/
private $skipUser = [];
/**
* @var bool
*/
private $addUser = true;
private array $skipUser = [];
private bool $addUser = true;
/**
* @var callable
*/
@@ -44,7 +36,6 @@ final class TeamFixtures implements TestFixture
* Will be called prior to persisting the object.
*
* @param callable $callback
* @return TeamFixtures
*/
public function setCallback(callable $callback): TeamFixtures
{
@@ -87,7 +78,6 @@ final class TeamFixtures implements TestFixture
}
/**
* @param ObjectManager $manager
* @return Team[]
*/
public function load(ObjectManager $manager): array
@@ -135,36 +125,4 @@ final class TeamFixtures implements TestFixture
return $created;
}
/**
* @param ObjectManager $manager
* @return array<int|string, Customer>
*/
private function getAllCustomers(ObjectManager $manager)
{
$all = [];
/** @var Customer[] $entries */
$entries = $manager->getRepository(Customer::class)->findAll();
foreach ($entries as $temp) {
$all[$temp->getId()] = $temp;
}
return $all;
}
/**
* @param ObjectManager $manager
* @return array<int|string, User>
*/
private function getAllUsers(ObjectManager $manager): array
{
$all = [];
/** @var User[] $entries */
$entries = $manager->getRepository(User::class)->findAll();
foreach ($entries as $temp) {
$all[$temp->getId()] = $temp;
}
return $all;
}
}

View File

@@ -24,6 +24,8 @@ use Faker\Factory;
*/
final class TimesheetFixtures implements TestFixture
{
use FixturesTrait;
private int $running = 0;
/**
* @var Activity[]
@@ -307,54 +309,6 @@ final class TimesheetFixtures implements TestFixture
return $start;
}
/**
* @param ObjectManager $manager
* @return array<int|string, Activity>
*/
private function getAllActivities(ObjectManager $manager): array
{
$all = [];
/** @var Activity[] $entries */
$entries = $manager->getRepository(Activity::class)->findAll();
foreach ($entries as $temp) {
$all[$temp->getId()] = $temp;
}
return $all;
}
/**
* @param ObjectManager $manager
* @return array<int|string, Project>
*/
private function getAllProjects(ObjectManager $manager): array
{
$all = [];
/** @var Project[] $entries */
$entries = $manager->getRepository(Project::class)->findAll();
foreach ($entries as $temp) {
$all[$temp->getId()] = $temp;
}
return $all;
}
/**
* @param ObjectManager $manager
* @return array<int|string, User>
*/
private function getAllUsers(ObjectManager $manager): array
{
$all = [];
/** @var User[] $entries */
$entries = $manager->getRepository(User::class)->findAll();
foreach ($entries as $temp) {
$all[$temp->getId()] = $temp;
}
return $all;
}
/**
* @param \DateTime $start
* @param array<Tag> $tagArray