added hourly and money budgets to activity, project and customer (#843)

This commit is contained in:
Kevin Papst
2019-06-11 13:18:57 +02:00
committed by GitHub
parent 833968a87d
commit 5702d7afa8
118 changed files with 1743 additions and 1077 deletions

View File

@@ -645,7 +645,7 @@ class KimaiImporterCommand extends Command
* ["visible"]=> string(1) "1"
* --- ["filter"]=> string(1) "0"
* ["trash"]=> string(1) "1"
* --- ["budget"]=> string(4) "0.00"
* ["budget"]=> string(4) "0.00"
* --- ["effort"]=> NULL
* --- ["approved"]=> NULL
* --- ["internal"]=> string(1) "0"
@@ -677,6 +677,7 @@ class KimaiImporterCommand extends Command
->setName($name)
->setComment($oldProject['comment'] ?: null)
->setVisible($isActive)
->setBudget($oldProject['budget'] ?: 0)
;
foreach ($fixedRates as $fixedRow) {
@@ -733,7 +734,7 @@ class KimaiImporterCommand extends Command
* $activityToProject
* ["projectID"]=> string(1) "1"
* ["activityID"]=> string(1) "1"
* -- ["budget"]=> string(4) "0.00"
* ["budget"]=> string(4) "0.00"
* -- ["effort"]=> string(4) "0.00"
* -- ["approved"]=> string(4) "0.00"
*
@@ -831,6 +832,7 @@ class KimaiImporterCommand extends Command
->setName($name)
->setComment($oldActivity['comment'] ?: null)
->setVisible($isActive)
->setBudget($oldActivity['budget'] ?: 0)
;
if (null !== $projectId) {

View File

@@ -100,6 +100,21 @@ class ActivityController extends AbstractController
return $this->renderActivityForm($activity, $request);
}
/**
* @Route(path="/{id}/budget", name="admin_activity_budget", methods={"GET"})
* @Security("is_granted('budget', activity)")
*
* @param Activity $activity
* @return \Symfony\Component\HttpFoundation\Response
*/
public function budgetAction(Activity $activity)
{
return $this->render('activity/budget.html.twig', [
'activity' => $activity,
'stats' => $this->getRepository()->getActivityStatistics($activity)
]);
}
/**
* @Route(path="/{id}/edit", name="admin_activity_edit", methods={"GET", "POST"})
* @Security("is_granted('edit', activity)")
@@ -244,6 +259,7 @@ class ActivityController extends AbstractController
'method' => 'POST',
'create_more' => true,
'customer' => true,
'include_budget' => $this->isGranted('budget', $activity)
]);
}
}

View File

@@ -109,6 +109,21 @@ class CustomerController extends AbstractController
return $this->renderCustomerForm($customer, $request);
}
/**
* @Route(path="/{id}/budget", name="admin_customer_budget", methods={"GET"})
* @Security("is_granted('budget', customer)")
*
* @param Customer $customer
* @return \Symfony\Component\HttpFoundation\Response
*/
public function budgetAction(Customer $customer)
{
return $this->render('customer/budget.html.twig', [
'customer' => $customer,
'stats' => $this->getRepository()->getCustomerStatistics($customer)
]);
}
/**
* @Route(path="/{id}/edit", name="admin_customer_edit", methods={"GET", "POST"})
* @Security("is_granted('edit', customer)")
@@ -232,7 +247,8 @@ class CustomerController extends AbstractController
return $this->createForm(CustomerEditForm::class, $customer, [
'action' => $url,
'method' => 'POST'
'method' => 'POST',
'include_budget' => $this->isGranted('budget', $customer)
]);
}
}

View File

@@ -101,6 +101,21 @@ class ProjectController extends AbstractController
return $this->renderProjectForm($project, $request);
}
/**
* @Route(path="/{id}/budget", name="admin_project_budget", methods={"GET"})
* @Security("is_granted('budget', project)")
*
* @param Project $project
* @return \Symfony\Component\HttpFoundation\Response
*/
public function budgetAction(Project $project)
{
return $this->render('project/budget.html.twig', [
'project' => $project,
'stats' => $this->getRepository()->getProjectStatistics($project)
]);
}
/**
* @Route(path="/{id}/edit", name="admin_project_edit", methods={"GET", "POST"})
* @Security("is_granted('edit', project)")
@@ -238,6 +253,7 @@ class ProjectController extends AbstractController
'method' => 'POST',
'currency' => $currency,
'create_more' => true,
'include_budget' => $this->isGranted('budget', $project)
]);
}
}

View File

@@ -32,6 +32,8 @@ class CustomerFixtures extends Fixture
public const MAX_CUSTOMERS = 15;
public const MIN_BUDGET = 0;
public const MAX_BUDGET = 100000;
public const MIN_TIME_BUDGET = 0;
public const MAX_TIME_BUDGET = 10000000;
public const MIN_GLOBAL_ACTIVITIES = 5;
public const MAX_GLOBAL_ACTIVITIES = 30;
public const MIN_PROJECTS_PER_CUSTOMER = 2;
@@ -100,6 +102,14 @@ class CustomerFixtures extends Fixture
->setVisible($visible)
;
if (rand(0, 3) % 3) {
$entry->setBudget(rand(self::MIN_BUDGET, self::MAX_BUDGET));
}
if (rand(0, 3) % 3) {
$entry->setTimeBudget(rand(self::MIN_TIME_BUDGET, self::MAX_TIME_BUDGET));
}
return $entry;
}
@@ -115,12 +125,19 @@ class CustomerFixtures extends Fixture
$entry
->setName($faker->catchPhrase . ($visible ? '' : ' (x)'))
->setBudget(rand(self::MIN_BUDGET, self::MAX_BUDGET))
->setComment($faker->text)
->setCustomer($customer)
->setVisible($visible)
;
if (rand(0, 3) % 3) {
$entry->setBudget(rand(self::MIN_BUDGET, self::MAX_BUDGET));
}
if (rand(0, 3) % 3) {
$entry->setTimeBudget(rand(self::MIN_TIME_BUDGET, self::MAX_TIME_BUDGET));
}
return $entry;
}
@@ -140,6 +157,14 @@ class CustomerFixtures extends Fixture
->setVisible($visible)
;
if (rand(0, 3) % 3) {
$entry->setBudget(rand(self::MIN_BUDGET, self::MAX_BUDGET));
}
if (rand(0, 3) % 3) {
$entry->setTimeBudget(rand(self::MIN_TIME_BUDGET, self::MAX_TIME_BUDGET));
}
return $entry;
}
}

View File

@@ -60,7 +60,7 @@ class TagFixtures extends Fixture
} elseif ($i % 2 == 0) {
$tagName = $faker->colorName;
} elseif ($i % 1 == 0) {
$tagName = $faker->text(rand(10, 20));
$tagName = $faker->text(rand(5, 15));
}
if (in_array($tagName, $existing)) {
@@ -72,15 +72,12 @@ class TagFixtures extends Fixture
$manager->persist($tag);
if ($i % self::BATCH_SIZE == 0) {
if ($i % self::BATCH_SIZE === 0) {
$manager->flush();
$manager->clear(Tag::class);
}
$manager->flush();
$manager->clear(Tag::class);
}
$manager->flush();
$manager->clear(Tag::class);
}
}

View File

@@ -41,6 +41,7 @@ class UserFixtures extends Fixture
public const MIN_RATE = 30;
public const MAX_RATE = 120;
// lower batch size, as user preferences are added in the same run
public const BATCH_SIZE = 50;
/**
@@ -131,15 +132,31 @@ class UserFixtures extends Fixture
private function loadTestUsers(ObjectManager $manager)
{
$passwordEncoder = $this->encoder;
$faker = Factory::create();
$existingName = [];
$existingEmail = [];
for ($i = 1; $i <= self::AMOUNT_EXTRA_USER; $i++) {
$username = $faker->userName;
$email = $faker->email;
if (in_array($username, $existingName)) {
continue;
}
if (in_array($email, $existingEmail)) {
continue;
}
$existingName[] = $username;
$existingEmail[] = $email;
$user = new User();
$user
->setAlias($faker->name)
->setTitle(substr($faker->jobTitle, 0, 49))
->setUsername($faker->userName)
->setEmail($faker->email)
->setUsername($username)
->setEmail($email)
->setRoles([User::ROLE_USER])
->setAvatar(self::DEFAULT_AVATAR)
->setEnabled(true)
@@ -147,12 +164,12 @@ class UserFixtures extends Fixture
->setPreferences($this->getUserPreferences($user))
;
if ($i % self::BATCH_SIZE == 0) {
$manager->persist($user);
if ($i % self::BATCH_SIZE === 0) {
$manager->flush();
$manager->clear();
}
$manager->persist($user);
}
$manager->flush();

View File

@@ -71,6 +71,7 @@ class Activity
// keep the trait include exactly here, for placing the column at the correct position
use RatesTrait;
use ColorTrait;
use BudgetTrait;
public function __construct()
{

View File

@@ -0,0 +1,68 @@
<?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;
use Doctrine\ORM\Mapping as ORM;
trait BudgetTrait
{
/**
* @var float
*
* @ORM\Column(name="budget", type="float", precision=10, scale=2, nullable=false)
* @Assert\NotNull()
*/
private $budget = 0.00;
/**
* Time budget in seconds.
*
* @var int
*
* @ORM\Column(name="time_budget", type="integer", precision=10, scale=2, nullable=false)
* @Assert\NotNull()
*/
private $timeBudget = 0;
/**
* @param float $budget
* @return self
*/
public function setBudget(?float $budget)
{
$this->budget = $budget;
return $this;
}
/**
* @return float
*/
public function getBudget()
{
return $this->budget;
}
/**
* @param int $seconds
* @return self
*/
public function setTimeBudget(?int $seconds)
{
$this->timeBudget = $seconds;
return $this;
}
public function getTimeBudget(): int
{
return $this->timeBudget;
}
}

View File

@@ -152,6 +152,7 @@ class Customer
// keep the trait include exactly here, for placing the column at the correct position
use RatesTrait;
use ColorTrait;
use BudgetTrait;
public function __construct()
{

View File

@@ -70,14 +70,6 @@ class Project
*/
private $visible = true;
/**
* @var float
*
* @ORM\Column(name="budget", type="float", precision=10, scale=2, nullable=false)
* @Assert\NotNull()
*/
private $budget = 0.00;
/**
* @var Activity[]|ArrayCollection
*
@@ -88,6 +80,7 @@ class Project
// keep the trait include exactly here, for placing the column at the correct position
use RatesTrait;
use ColorTrait;
use BudgetTrait;
/**
* @var Timesheet[]|ArrayCollection
@@ -162,25 +155,6 @@ class Project
return $this->visible;
}
/**
* @param float $budget
* @return Project
*/
public function setBudget($budget): Project
{
$this->budget = $budget;
return $this;
}
/**
* @return float
*/
public function getBudget()
{
return $this->budget;
}
/**
* @return Collection<Timesheet>
*/

View File

@@ -26,11 +26,7 @@ class ServiceExport
}
}
/**
* @param RendererInterface $renderer
* @return $this
*/
public function addRenderer(RendererInterface $renderer)
public function addRenderer(RendererInterface $renderer): ServiceExport
{
$this->renderer[] = $renderer;
@@ -38,20 +34,14 @@ class ServiceExport
}
/**
* Returns an array of export renderer.
*
* @return RendererInterface[]
*/
public function getRenderer()
public function getRenderer(): array
{
return $this->renderer;
}
/**
* @param string $id
* @return RendererInterface|null
*/
public function getRendererById(string $id)
public function getRendererById(string $id): ?RendererInterface
{
foreach ($this->renderer as $renderer) {
if ($renderer->getId() === $id) {

View File

@@ -10,16 +10,12 @@
namespace App\Form;
use App\Entity\Activity;
use App\Form\Type\ColorPickerType;
use App\Entity\Customer;
use App\Form\Type\CustomerType;
use App\Form\Type\FixedRateType;
use App\Form\Type\HourlyRateType;
use App\Form\Type\ProjectType;
use App\Form\Type\YesNoType;
use App\Repository\CustomerRepository;
use App\Repository\ProjectRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
@@ -27,11 +23,10 @@ use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Defines the form used to manipulate Activities.
*/
class ActivityEditForm extends AbstractType
{
use EntityFormTrait;
/**
* {@inheritdoc}
*/
@@ -39,7 +34,6 @@ class ActivityEditForm extends AbstractType
{
$project = null;
$customer = null;
$currency = false;
$id = null;
if (isset($options['data'])) {
@@ -49,21 +43,19 @@ class ActivityEditForm extends AbstractType
if (null !== $entry->getProject()) {
$project = $entry->getProject();
$customer = $project->getCustomer();
$currency = $customer->getCurrency();
$options['currency'] = $customer->getCurrency();
}
$id = $entry->getId();
}
$builder
// string - length 255
->add('name', TextType::class, [
'label' => 'label.name',
'attr' => [
'autofocus' => 'autofocus'
],
])
// text
->add('comment', TextareaType::class, [
'label' => 'label.comment',
'required' => false,
@@ -109,26 +101,10 @@ class ActivityEditForm extends AbstractType
}
);
$builder
->add('color', ColorPickerType::class)
->add('fixedRate', FixedRateType::class, [
'currency' => $currency,
])
->add('hourlyRate', HourlyRateType::class, [
'currency' => $currency,
])
// boolean
->add('visible', YesNoType::class, [
'label' => 'label.visible',
])
;
$this->addCommonFields($builder, $options);
if (null === $id && $options['create_more']) {
$builder->add('create_more', CheckboxType::class, [
'label' => 'label.create_more',
'required' => false,
'mapped' => false,
]);
$this->addCreateMore($builder);
}
}
@@ -144,6 +120,8 @@ class ActivityEditForm extends AbstractType
'csrf_token_id' => 'admin_activity_edit',
'create_more' => false,
'customer' => false,
'currency' => Customer::DEFAULT_CURRENCY,
'include_budget' => false,
'attr' => [
'data-form-event' => 'kimai.activityUpdate'
],

View File

@@ -10,10 +10,6 @@
namespace App\Form;
use App\Entity\Customer;
use App\Form\Type\ColorPickerType;
use App\Form\Type\FixedRateType;
use App\Form\Type\HourlyRateType;
use App\Form\Type\YesNoType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\Extension\Core\Type\CurrencyType;
@@ -26,22 +22,19 @@ use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Defines the form used to edit Customer entities.
*/
class CustomerEditForm extends AbstractType
{
use EntityFormTrait;
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$currency = false;
if (isset($options['data'])) {
/** @var Customer $customer */
$customer = $options['data'];
$currency = $customer->getCurrency();
$options['currency'] = $customer->getCurrency();
}
$builder
@@ -101,18 +94,9 @@ class CustomerEditForm extends AbstractType
])
->add('timezone', TimezoneType::class, [
'label' => 'label.timezone',
])
->add('color', ColorPickerType::class)
->add('fixedRate', FixedRateType::class, [
'currency' => $currency ?? false,
])
->add('hourlyRate', HourlyRateType::class, [
'currency' => $currency ?? false,
])
->add('visible', YesNoType::class, [
'label' => 'label.visible',
])
;
]);
$this->addCommonFields($builder, $options);
}
/**
@@ -125,6 +109,8 @@ class CustomerEditForm extends AbstractType
'csrf_protection' => true,
'csrf_field_name' => '_token',
'csrf_token_id' => 'admin_customer_edit',
'currency' => Customer::DEFAULT_CURRENCY,
'include_budget' => false,
'attr' => [
'data-form-event' => 'kimai.customerUpdate'
],

View File

@@ -0,0 +1,73 @@
<?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\Form\DataTransformer;
use App\Utils\Duration;
use App\Validator\Constraints\Duration as DurationConstraint;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class DurationStringToSecondsTransformer implements DataTransformerInterface
{
/**
* @var Duration
*/
protected $formatter;
/**
* @var string
*/
private $pattern;
public function __construct()
{
$this->formatter = new Duration();
$constraint = new DurationConstraint();
$this->pattern = $constraint->pattern;
}
/**
* @param int $intToFormat
* @return string|null
*/
public function transform($intToFormat)
{
try {
return $this->formatter->format($intToFormat);
} catch (\Exception $e) {
throw new TransformationFailedException($e->getMessage());
}
}
/**
* @param string $formatToInt
* @return int|null
*/
public function reverseTransform($formatToInt)
{
if (null === $formatToInt) {
return null;
}
if (empty($formatToInt)) {
return 0;
}
// we need this one here, because the data transformer is executed BEFORE the constraint is called
if (!preg_match($this->pattern, $formatToInt)) {
throw new TransformationFailedException('Invalid duration format given');
}
try {
return $this->formatter->parseDurationString($formatToInt);
} catch (\Exception $e) {
throw new TransformationFailedException($e->getMessage());
}
}
}

View File

@@ -36,7 +36,7 @@ class TagArrayToStringTransformer implements DataTransformerInterface
*
* @return string
*/
public function transform($tags): string
public function transform($tags)
{
if (empty($tags)) {
return '';
@@ -53,7 +53,7 @@ class TagArrayToStringTransformer implements DataTransformerInterface
* @return Tag[]
* @throws TransformationFailedException if object (issue) is not found
*/
public function reverseTransform($stringOfTags): array
public function reverseTransform($stringOfTags)
{
// check for empty tag list
if (empty($stringOfTags)) {

View File

@@ -0,0 +1,64 @@
<?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\Form;
use App\Form\Type\ColorPickerType;
use App\Form\Type\DurationType;
use App\Form\Type\FixedRateType;
use App\Form\Type\HourlyRateType;
use App\Form\Type\YesNoType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\FormBuilderInterface;
trait EntityFormTrait
{
public function addCommonFields(FormBuilderInterface $builder, array $options): void
{
$currency = $options['currency'];
$builder
->add('color', ColorPickerType::class)
->add('fixedRate', FixedRateType::class, [
'currency' => $currency,
])
->add('hourlyRate', HourlyRateType::class, [
'currency' => $currency,
])
;
if ($options['include_budget']) {
$builder
->add('budget', MoneyType::class, [
'label' => 'label.budget',
'required' => false,
'currency' => $currency,
])
->add('timeBudget', DurationType::class, [
'label' => 'label.timeBudget',
'required' => false,
])
;
}
$builder
->add('visible', YesNoType::class, [
'label' => 'label.visible',
]);
}
public function addCreateMore(FormBuilderInterface $builder): void
{
$builder->add('create_more', CheckboxType::class, [
'label' => 'label.create_more',
'required' => false,
'mapped' => false,
]);
}
}

View File

@@ -11,32 +11,24 @@ namespace App\Form;
use App\Entity\Customer;
use App\Entity\Project;
use App\Form\Type\ColorPickerType;
use App\Form\Type\CustomerType;
use App\Form\Type\FixedRateType;
use App\Form\Type\HourlyRateType;
use App\Form\Type\YesNoType;
use App\Repository\CustomerRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Defines the form used to edit Projects.
*/
class ProjectEditForm extends AbstractType
{
use EntityFormTrait;
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$customer = null;
$currency = false;
$id = null;
if (isset($options['data'])) {
@@ -46,7 +38,7 @@ class ProjectEditForm extends AbstractType
if ($id !== null) {
$customer = $entry->getCustomer();
$currency = $customer->getCurrency();
$options['currency'] = $customer->getCurrency();
}
}
@@ -69,30 +61,12 @@ class ProjectEditForm extends AbstractType
'query_builder' => function (CustomerRepository $repo) use ($customer) {
return $repo->builderForEntityType($customer);
},
])
->add('color', ColorPickerType::class)
->add('fixedRate', FixedRateType::class, [
'currency' => $currency,
])
->add('hourlyRate', HourlyRateType::class, [
'currency' => $currency,
])
->add('budget', MoneyType::class, [
'label' => 'label.budget',
'required' => false,
'currency' => $currency,
])
->add('visible', YesNoType::class, [
'label' => 'label.visible',
])
;
]);
$this->addCommonFields($builder, $options);
if (null === $id && $options['create_more']) {
$builder->add('create_more', CheckboxType::class, [
'label' => 'label.create_more',
'required' => false,
'mapped' => false,
]);
$this->addCreateMore($builder);
}
}
@@ -107,6 +81,7 @@ class ProjectEditForm extends AbstractType
'csrf_field_name' => '_token',
'csrf_token_id' => 'admin_project_edit',
'currency' => Customer::DEFAULT_CURRENCY,
'include_budget' => false,
'create_more' => false,
'attr' => [
'data-form-event' => 'kimai.projectUpdate'

View File

@@ -9,42 +9,18 @@
namespace App\Form\Type;
use App\Utils\Duration;
use App\Form\DataTransformer\DurationStringToSecondsTransformer;
use App\Validator\Constraints\Duration as DurationConstraint;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Regex;
/**
* Custom form field type to handle a timesheet duration.
* Custom form field type to handle duration strings.
*/
class DurationType extends AbstractType
{
/**
* @var string
*/
protected $pattern;
/**
* DurationType constructor.
*/
public function __construct()
{
$patterns = [
'[0-9]{1,}',
'[0-9]{1,}:[0-9]{1,2}:[0-9]{1,2}',
'[0-9]{1,2}:[0-9]{1,2}',
'[0-9]{1,}[hmsHMS]{1}',
'[0-9]{1,}[hmsHMS]{1}[0-9]{1,}[hmsHMS]{1}',
'[0-9]{1,}[hmsHMS]{1}[0-9]{1,}[hmsHMS]{1}[0-9]{1,}[hmsHMS]{1}',
];
$this->pattern = '/^' . implode('$|^', $patterns) . '$/';
}
/**
* {@inheritdoc}
*/
@@ -52,7 +28,7 @@ class DurationType extends AbstractType
{
$resolver->setDefaults([
'label' => 'label.duration',
'constraints' => [new Regex(['pattern' => $this->pattern])],
'constraints' => [new DurationConstraint()],
]);
}
@@ -61,37 +37,7 @@ class DurationType extends AbstractType
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$formatter = new Duration();
$pattern = $this->pattern;
$builder->addModelTransformer(new CallbackTransformer(
function ($intToFormat) use ($formatter) {
try {
return $formatter->format($intToFormat);
} catch (\Exception $e) {
throw new TransformationFailedException($e->getMessage());
}
},
function ($formatToInt) use ($formatter, $pattern) {
if (null === $formatToInt) {
return null;
}
if (empty($formatToInt)) {
return 0;
}
if (!preg_match($pattern, $formatToInt)) {
throw new TransformationFailedException('Invalid duration format given');
}
try {
return $formatter->parseDurationString($formatToInt);
} catch (\Exception $e) {
throw new TransformationFailedException($e->getMessage());
}
}
));
$builder->addModelTransformer(new DurationStringToSecondsTransformer());
}
/**

View File

@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
/*
* 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 DoctrineMigrations;
use App\Doctrine\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Creates the budget columns on: customer, project, activity.
*
* @version 1.0
*/
final class Version20190605171157 extends AbstractMigration
{
public function getDescription(): string
{
return 'Creates the budget columns on: customer, project, activity';
}
public function up(Schema $schema): void
{
$customers = $schema->getTable('kimai2_customers');
$customers->addColumn('time_budget', 'integer', ['notnull' => true, 'default' => 0]);
$customers->addColumn('budget', 'float', ['notnull' => true, 'default' => 0]);
$projects = $schema->getTable('kimai2_projects');
$projects->addColumn('time_budget', 'integer', ['notnull' => true, 'default' => 0]);
$projects->getColumn('budget')->setDefault(0);
$activities = $schema->getTable('kimai2_activities');
$activities->addColumn('time_budget', 'integer', ['notnull' => true, 'default' => 0]);
$activities->addColumn('budget', 'float', ['notnull' => true, 'default' => 0]);
}
public function down(Schema $schema): void
{
$customers = $schema->getTable('kimai2_customers');
$customers->dropColumn('time_budget');
$customers->dropColumn('budget');
$projects = $schema->getTable('kimai2_projects');
$projects->dropColumn('time_budget');
$activities = $schema->getTable('kimai2_activities');
$activities->dropColumn('time_budget');
$activities->dropColumn('budget');
}
}

View File

@@ -9,84 +9,6 @@
namespace App\Model;
/**
* Activity statistics
*/
class ActivityStatistic
class ActivityStatistic extends TimesheetCountedStatistic
{
/**
* @var int
*/
protected $count = 0;
/**
* @var int
*/
protected $recordAmount = 0;
/**
* @var int
*/
protected $recordDuration = 0;
/**
* Returns the total amount of included timesheet records.
*
* @return int
*/
public function getRecordAmount()
{
return $this->recordAmount;
}
/**
* @param int $recordAmount
* @return ActivityStatistic
*/
public function setRecordAmount($recordAmount)
{
$this->recordAmount = (int) $recordAmount;
return $this;
}
/**
* Returns the total duration of all included timesheet records.
*
* @return int
*/
public function getRecordDuration()
{
return $this->recordDuration;
}
/**
* @param int $recordDuration
* @return ActivityStatistic
*/
public function setRecordDuration($recordDuration)
{
$this->recordDuration = (int) $recordDuration;
return $this;
}
/**
* Returns the amount of activities that are included in the statistic result.
*
* @return int
*/
public function getCount()
{
return $this->count;
}
/**
* @param int $count
* @return ActivityStatistic
*/
public function setCount($count)
{
$this->count = (int) $count;
return $this;
}
}

View File

@@ -9,23 +9,8 @@
namespace App\Model;
/**
* Customer statistics
*/
class CustomerStatistic
class CustomerStatistic extends TimesheetCountedStatistic
{
/**
* @var int
*/
protected $count = 0;
/**
* @var int
*/
protected $recordAmount = 0;
/**
* @var int
*/
protected $recordDuration = 0;
/**
* @var int
*/
@@ -35,69 +20,6 @@ class CustomerStatistic
*/
protected $projectAmount = 0;
/**
* Returns the total amount of included timesheet records.
*
* @return int
*/
public function getRecordAmount()
{
return $this->recordAmount;
}
/**
* @param int $recordAmount
* @return $this
*/
public function setRecordAmount($recordAmount)
{
$this->recordAmount = (int) $recordAmount;
return $this;
}
/**
* Returns the total duration of all included timesheet records.
*
* @return int
*/
public function getRecordDuration()
{
return $this->recordDuration;
}
/**
* @param int $recordDuration
* @return $this
*/
public function setRecordDuration($recordDuration)
{
$this->recordDuration = (int) $recordDuration;
return $this;
}
/**
* Returns the amount of activities that are included in the statistic result.
*
* @return int
*/
public function getCount()
{
return $this->count;
}
/**
* @param int $count
* @return $this
*/
public function setCount($count)
{
$this->count = (int) $count;
return $this;
}
/**
* @return int
*/

View File

@@ -9,91 +9,13 @@
namespace App\Model;
/**
* Project statistics
*/
class ProjectStatistic
class ProjectStatistic extends TimesheetCountedStatistic
{
/**
* @var int
*/
protected $count = 0;
/**
* @var int
*/
protected $recordAmount = 0;
/**
* @var int
*/
protected $recordDuration = 0;
/**
* @var int
*/
protected $activityAmount = 0;
/**
* Returns the total amount of included timesheet records.
*
* @return int
*/
public function getRecordAmount()
{
return $this->recordAmount;
}
/**
* @param int $recordAmount
* @return ProjectStatistic
*/
public function setRecordAmount($recordAmount)
{
$this->recordAmount = (int) $recordAmount;
return $this;
}
/**
* Returns the total duration of all included timesheet records.
*
* @return int
*/
public function getRecordDuration()
{
return $this->recordDuration;
}
/**
* @param int $recordDuration
* @return ProjectStatistic
*/
public function setRecordDuration($recordDuration)
{
$this->recordDuration = (int) $recordDuration;
return $this;
}
/**
* Returns the amount of activities that are included in the statistic result.
*
* @return int
*/
public function getCount()
{
return $this->count;
}
/**
* @param int $count
* @return ProjectStatistic
*/
public function setCount($count)
{
$this->count = (int) $count;
return $this;
}
/**
* @return int
*/

View File

@@ -0,0 +1,89 @@
<?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\Model;
class TimesheetCountedStatistic
{
/**
* @var int
*/
protected $recordAmount = 0;
/**
* @var int
*/
protected $recordDuration = 0;
/**
* @var float
*/
protected $recordRate = 0.0;
/**
* Returns the total amount of included timesheet records.
*
* @return int
*/
public function getRecordAmount()
{
return $this->recordAmount;
}
/**
* @param int $recordAmount
* @return $this
*/
public function setRecordAmount($recordAmount)
{
$this->recordAmount = (int) $recordAmount;
return $this;
}
/**
* Returns the total duration of all included timesheet records.
*
* @return int
*/
public function getRecordDuration()
{
return $this->recordDuration;
}
/**
* @param int $recordDuration
* @return $this
*/
public function setRecordDuration($recordDuration)
{
$this->recordDuration = (int) $recordDuration;
return $this;
}
/**
* Returns the total rate of all included timesheet records.
*
* @return float
*/
public function getRecordRate()
{
return $this->recordRate;
}
/**
* @param float $recordRate
* @return $this
*/
public function setRecordRate($recordRate)
{
$this->recordRate = (float) $recordRate;
return $this;
}
}

View File

@@ -51,23 +51,24 @@ class ActivityRepository extends AbstractRepository
*/
public function getActivityStatistics(Activity $activity)
{
$stats = new ActivityStatistic();
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('COUNT(t.id) as totalRecords', 'SUM(t.duration) as totalDuration')
$qb
->addSelect('COUNT(t.id) as recordAmount')
->addSelect('SUM(t.duration) as recordDuration')
->addSelect('SUM(t.rate) as recordRate')
->from(Timesheet::class, 't')
->where('t.activity = :activity')
;
$result = $qb->getQuery()->execute(['activity' => $activity], Query::HYDRATE_ARRAY);
$timesheetResult = $qb->getQuery()->execute(['activity' => $activity], Query::HYDRATE_ARRAY);
$stats = new ActivityStatistic();
if (isset($result[0])) {
$dbStats = $result[0];
$stats->setCount(1);
$stats->setRecordAmount($dbStats['totalRecords']);
$stats->setRecordDuration($dbStats['totalDuration']);
if (isset($timesheetResult[0])) {
$stats->setRecordAmount($timesheetResult[0]['recordAmount']);
$stats->setRecordDuration($timesheetResult[0]['recordDuration']);
$stats->setRecordRate($timesheetResult[0]['recordRate']);
}
return $stats;

View File

@@ -53,12 +53,12 @@ class CustomerRepository extends AbstractRepository
public function getCustomerStatistics(Customer $customer)
{
$stats = new CustomerStatistic();
$stats->setCount(1);
$qb = $this->getEntityManager()->createQueryBuilder();
$qb
->addSelect('COUNT(t.id) as recordAmount')
->addSelect('SUM(t.duration) as recordDuration')
->addSelect('SUM(t.rate) as recordRate')
->from(Timesheet::class, 't')
->join(Project::class, 'p', Query\Expr\Join::WITH, 't.project = p.id')
->andWhere('p.customer = :customer')
@@ -68,6 +68,7 @@ class CustomerRepository extends AbstractRepository
if (isset($timesheetResult[0])) {
$stats->setRecordAmount($timesheetResult[0]['recordAmount']);
$stats->setRecordDuration($timesheetResult[0]['recordDuration']);
$stats->setRecordRate($timesheetResult[0]['recordRate']);
}
$qb = $this->getEntityManager()->createQueryBuilder();

View File

@@ -49,14 +49,24 @@ class ProjectRepository extends AbstractRepository
public function getProjectStatistics(Project $project): ProjectStatistic
{
$stats = new ProjectStatistic();
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('COUNT(t.id) as recordAmount')
$qb
->addSelect('COUNT(t.id) as recordAmount')
->addSelect('SUM(t.duration) as recordDuration')
->addSelect('SUM(t.rate) as recordRate')
->from(Timesheet::class, 't')
->andWhere('t.project = :project')
;
$resultTimesheets = $qb->getQuery()->execute(['project' => $project], Query::HYDRATE_ARRAY);
$timesheetResult = $qb->getQuery()->execute(['project' => $project], Query::HYDRATE_ARRAY);
if (isset($timesheetResult[0])) {
$stats->setRecordAmount($timesheetResult[0]['recordAmount']);
$stats->setRecordDuration($timesheetResult[0]['recordDuration']);
$stats->setRecordRate($timesheetResult[0]['recordRate']);
}
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('COUNT(a.id) as activityAmount')
@@ -65,16 +75,6 @@ class ProjectRepository extends AbstractRepository
;
$resultActivities = $qb->getQuery()->execute(['project' => $project], Query::HYDRATE_ARRAY);
$stats = new ProjectStatistic();
$stats->setCount(1);
if (isset($resultTimesheets[0])) {
$resultTimesheets = $resultTimesheets[0];
$stats->setRecordAmount($resultTimesheets['recordAmount']);
$stats->setRecordDuration($resultTimesheets['recordDuration']);
}
if (isset($resultActivities[0])) {
$resultActivities = $resultActivities[0];

View File

@@ -75,6 +75,7 @@ class TagRepository extends AbstractRepository
->select('tag.id, tag.name, count(timesheets.id) as amount')
->leftJoin('tag.timesheets', 'timesheets')
->addGroupBy('tag.id')
->addGroupBy('tag.name')
->orderBy('tag.name')
;

View File

@@ -52,7 +52,7 @@ class Extensions extends AbstractExtension
'activity' => 'fas fa-tasks',
'admin' => 'fas fa-wrench',
'calendar' => 'far fa-calendar-alt',
'customer' => 'fas fa-users',
'customer' => 'fas fa-user-tie',
'copy' => 'far fa-copy',
'create' => 'far fa-plus-square',
'dashboard' => 'fas fa-tachometer-alt',
@@ -76,7 +76,7 @@ class Extensions extends AbstractExtension
'stop-small' => 'far fa-stop-circle',
'timesheet' => 'fas fa-clock',
'trash' => 'far fa-trash-alt',
'user' => 'fas fa-user',
'user' => 'fas fa-users',
'visibility' => 'far fa-eye',
'settings' => 'fas fa-cog',
'export' => 'fas fa-file-export',
@@ -96,6 +96,8 @@ class Extensions extends AbstractExtension
'warning' => 'fas fa-exclamation-triangle',
'permissions' => 'fas fa-user-lock',
'back' => 'fas fa-long-arrow-alt-left',
'tag' => 'fas fa-tags',
'avatar' => 'fas fa-user'
];
/**

View File

@@ -10,7 +10,7 @@
namespace App\Utils;
/**
* A simple class to help with timesheet record durations.
* Convert duration strings into seconds.
*/
class Duration
{
@@ -50,6 +50,8 @@ class Duration
}
/**
* Returns the seconds, which were given as $duration string.
*
* @param string $duration
* @return int
*/
@@ -67,6 +69,8 @@ class Duration
}
/**
* Returns the seconds, which were given as $mode formatted $duration string.
*
* @param string $duration
* @param string $mode
* @return int
@@ -78,31 +82,13 @@ class Duration
return 0;
}
$seconds = 0;
switch ($mode) {
case self::FORMAT_COLON:
$parts = explode(':', $duration);
if (count($parts) < 2) {
throw new \InvalidArgumentException('Colon format cannot parse: ' . $duration);
}
$seconds = 0;
if (3 == count($parts)) {
$seconds += (int) array_pop($parts);
}
$seconds += (int) $parts[1] * 60;
$seconds += (int) $parts[0] * 3600;
$seconds = $this->parseColonFormat($duration);
break;
case self::FORMAT_NATURAL:
try {
$interval = new \DateInterval('PT' . strtoupper($duration));
$reference = new \DateTimeImmutable();
$endTime = $reference->add($interval);
$seconds = $endTime->getTimestamp() - $reference->getTimestamp();
} catch (\Exception $e) {
throw new \InvalidArgumentException('Invalid input for natural format: ' . $duration);
}
$seconds = $this->parseNaturalFormat($duration);
break;
case self::FORMAT_SECONDS:
@@ -110,7 +96,7 @@ class Duration
break;
default:
throw new \InvalidArgumentException('Invalid duration format: ' . $mode);
throw new \InvalidArgumentException(sprintf('Unsupported duration format "%s"', $mode));
}
if ($seconds < 0) {
@@ -119,4 +105,51 @@ class Duration
return $seconds;
}
protected function parseNaturalFormat(string $duration): int
{
try {
$interval = new \DateInterval('PT' . strtoupper($duration));
$reference = new \DateTimeImmutable();
$endTime = $reference->add($interval);
return $endTime->getTimestamp() - $reference->getTimestamp();
} catch (\Exception $e) {
throw new \InvalidArgumentException('Invalid input for natural format: ' . $duration);
}
}
protected function parseColonFormat(string $duration): int
{
$parts = explode(':', $duration);
if (count($parts) < 2 || count($parts) > 3) {
throw new \InvalidArgumentException(
sprintf('Invalid colon format given in "%s"', $duration)
);
}
foreach ($parts as $part) {
if (strlen($part) === 0) {
throw new \InvalidArgumentException(
sprintf('Colon format cannot parse "%s"', $duration)
);
}
if (((int) $part) < 0) {
throw new \InvalidArgumentException(
sprintf('Negative input is not allowed in "%s"', $duration)
);
}
}
$seconds = 0;
if (3 == count($parts)) {
$seconds += (int) array_pop($parts);
}
$seconds += (int) $parts[1] * 60;
$seconds += (int) $parts[0] * 3600;
return $seconds;
}
}

View 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\Validator\Constraints;
use Symfony\Component\Validator\Constraints\Regex;
/**
* @Annotation
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*/
class Duration extends Regex
{
public function __construct($options = null)
{
$patterns = [
'[0-9]{1,}',
'[0-9]{1,}:[0-9]{1,}:[0-9]{1,}',
'[0-9]{1,}:[0-9]{1,}',
'[0-9]{1,}[hmsHMS]{1}',
'[0-9]{1,}[hmsHMS]{1}[0-9]{1,}[hmsHMS]{1}',
'[0-9]{1,}[hmsHMS]{1}[0-9]{1,}[hmsHMS]{1}[0-9]{1,}[hmsHMS]{1}',
];
$options['pattern'] = '/^' . implode('$|^', $patterns) . '$/';
parent::__construct($options);
}
}

View File

@@ -0,0 +1,16 @@
<?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\Validator\Constraints;
use Symfony\Component\Validator\Constraints\RegexValidator;
class DurationValidator extends RegexValidator
{
}

View File

@@ -20,6 +20,7 @@ class ActivityVoter extends AbstractVoter
{
public const VIEW = 'view';
public const EDIT = 'edit';
public const BUDGET = 'budget';
public const DELETE = 'delete';
/**
@@ -28,7 +29,8 @@ class ActivityVoter extends AbstractVoter
public const ALLOWED_ATTRIBUTES = [
self::VIEW,
self::EDIT,
self::DELETE
self::BUDGET,
self::DELETE,
];
/**

View File

@@ -20,6 +20,7 @@ class CustomerVoter extends AbstractVoter
{
public const VIEW = 'view';
public const EDIT = 'edit';
public const BUDGET = 'budget';
public const DELETE = 'delete';
/**
@@ -28,7 +29,8 @@ class CustomerVoter extends AbstractVoter
public const ALLOWED_ATTRIBUTES = [
self::VIEW,
self::EDIT,
self::DELETE
self::BUDGET,
self::DELETE,
];
/**

View File

@@ -20,6 +20,7 @@ class ProjectVoter extends AbstractVoter
{
public const VIEW = 'view';
public const EDIT = 'edit';
public const BUDGET = 'budget';
public const DELETE = 'delete';
/**
@@ -28,7 +29,8 @@ class ProjectVoter extends AbstractVoter
public const ALLOWED_ATTRIBUTES = [
self::VIEW,
self::EDIT,
self::DELETE
self::BUDGET,
self::DELETE,
];
/**