timesheet lockdown with grace period (#1644)

This commit is contained in:
Honza Kopecký
2020-07-02 18:54:17 +02:00
committed by GitHub
parent e22830790b
commit 091740f407
32 changed files with 1180 additions and 148 deletions

View File

@@ -20,32 +20,26 @@ class Timesheet extends Constraint
{
public const MISSING_BEGIN_ERROR = 'kimai-timesheet-81';
public const END_BEFORE_BEGIN_ERROR = 'kimai-timesheet-82';
public const BEGIN_IN_FUTURE_ERROR = 'kimai-timesheet-83';
public const MISSING_ACTIVITY_ERROR = 'kimai-timesheet-84';
public const MISSING_PROJECT_ERROR = 'kimai-timesheet-85';
public const ACTIVITY_PROJECT_MISMATCH_ERROR = 'kimai-timesheet-86';
public const DISABLED_ACTIVITY_ERROR = 'kimai-timesheet-87';
public const DISABLED_PROJECT_ERROR = 'kimai-timesheet-88';
public const DISABLED_CUSTOMER_ERROR = 'kimai-timesheet-89';
public const START_DISALLOWED = 'kimai-timesheet-90';
public const PROJECT_NOT_STARTED = 'kimai-timesheet-91';
public const PROJECT_ALREADY_ENDED = 'kimai-timesheet-92';
public const RECORD_OVERLAPPING = 'kimai-timesheet-93';
protected static $errorNames = [
self::MISSING_BEGIN_ERROR => 'You must submit a begin date.',
self::END_BEFORE_BEGIN_ERROR => 'End date must not be earlier then start date.',
self::BEGIN_IN_FUTURE_ERROR => 'The begin date cannot be in the future.',
self::MISSING_ACTIVITY_ERROR => 'A timesheet must have an activity.',
self::MISSING_PROJECT_ERROR => 'A timesheet must have a project.',
self::ACTIVITY_PROJECT_MISMATCH_ERROR => 'Project mismatch, project specific activity and timesheet project are different.',
self::DISABLED_ACTIVITY_ERROR => 'Cannot start a disabled activity.',
self::DISABLED_PROJECT_ERROR => 'Cannot start a disabled project.',
self::DISABLED_CUSTOMER_ERROR => 'Cannot start a disabled customer.',
self::START_DISALLOWED => 'You are not allowed to start this timesheet record.',
self::PROJECT_NOT_STARTED => 'The project has not started at that time.',
self::PROJECT_ALREADY_ENDED => 'The project is finished at that time.',
self::RECORD_OVERLAPPING => 'You already have an entry for this time.',
];
public $message = 'This timesheet has invalid settings.';

View File

@@ -0,0 +1,19 @@
<?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\Constraint;
/**
* Extend this class if you want to add dynamic timesheet validation (eg. via a bundle).
*/
abstract class TimesheetConstraint extends Constraint
{
}

View File

@@ -0,0 +1,26 @@
<?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;
final class TimesheetFutureTimes extends TimesheetConstraint
{
public const BEGIN_IN_FUTURE_ERROR = 'kimai-timesheet-future-times-01';
protected static $errorNames = [
self::BEGIN_IN_FUTURE_ERROR => 'The begin date cannot be in the future.',
];
public $message = 'The begin date cannot be in the future.';
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}

View File

@@ -0,0 +1,58 @@
<?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 App\Configuration\TimesheetConfiguration;
use App\Entity\Timesheet as TimesheetEntity;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
final class TimesheetFutureTimesValidator extends ConstraintValidator
{
/**
* @var TimesheetConfiguration
*/
private $configuration;
public function __construct(TimesheetConfiguration $configuration)
{
$this->configuration = $configuration;
}
/**
* @param TimesheetEntity $timesheet
* @param Constraint $constraint
*/
public function validate($timesheet, Constraint $constraint)
{
if (!($constraint instanceof TimesheetFutureTimes)) {
throw new UnexpectedTypeException($constraint, TimesheetFutureTimes::class);
}
if (!\is_object($timesheet) || !($timesheet instanceof TimesheetEntity)) {
throw new UnexpectedTypeException($timesheet, TimesheetEntity::class);
}
if ($this->configuration->isAllowFutureTimes()) {
return;
}
// allow configured default rounding time + 1 minute - see #1295
$allowedDiff = ($this->configuration->getDefaultRoundingBegin() * 60) + 60;
if ((time() + $allowedDiff) < $timesheet->getBegin()->getTimestamp()) {
$this->context->buildViolation('The begin date cannot be in the future.')
->atPath('begin')
->setTranslationDomain('validators')
->setCode(TimesheetFutureTimes::BEGIN_IN_FUTURE_ERROR)
->addViolation();
}
}
}

View File

@@ -0,0 +1,30 @@
<?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;
final class TimesheetLockdown extends TimesheetConstraint
{
public const PERIOD_LOCKED = 'kimai-timesheet-lockdown-01';
protected static $errorNames = [
self::PERIOD_LOCKED => 'This period is locked, please choose a later date.',
];
public $message = 'This period is locked, please choose a later date.';
/**
* @var \DateTime|string|null
*/
public $now;
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}

View File

@@ -0,0 +1,127 @@
<?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 App\Configuration\TimesheetConfiguration;
use App\Entity\Timesheet as TimesheetEntity;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
final class TimesheetLockdownValidator extends ConstraintValidator
{
/**
* @var AuthorizationCheckerInterface
*/
private $auth;
/**
* @var TimesheetConfiguration
*/
private $configuration;
public function __construct(AuthorizationCheckerInterface $auth, TimesheetConfiguration $configuration)
{
$this->auth = $auth;
$this->configuration = $configuration;
}
/**
* @param TimesheetEntity $timesheet
* @param Constraint $constraint
*/
public function validate($timesheet, Constraint $constraint)
{
if (!($constraint instanceof TimesheetLockdown)) {
throw new UnexpectedTypeException($constraint, TimesheetLockdown::class);
}
if (!\is_object($timesheet) || !($timesheet instanceof TimesheetEntity)) {
throw new UnexpectedTypeException($timesheet, TimesheetEntity::class);
}
$timesheetStart = $timesheet->getBegin();
if (null === $timesheetStart) {
return;
}
if (!$this->configuration->isLockdownActive()) {
return;
}
$lockedStart = $this->configuration->getLockdownPeriodStart();
$lockedEnd = $this->configuration->getLockdownPeriodEnd();
$gracePeriod = $this->configuration->getLockdownGracePeriod();
if (!empty($gracePeriod)) {
$gracePeriod = $gracePeriod . ' ';
}
try {
$lockdownStart = new \DateTime($lockedStart, $timesheetStart->getTimezone());
$lockdownEnd = new \DateTime($lockedEnd, $timesheetStart->getTimezone());
$lockdownGrace = new \DateTime($gracePeriod . $lockdownEnd->format('Y-m-d'), $timesheetStart->getTimezone());
} catch (\Exception $ex) {
// should not happen, but ... if parsing of datetimes fails: skip validation
return;
}
// misconfiguration detected, skip validation
if ($lockdownEnd < $lockdownStart) {
return;
}
// validate only entries added before the end of lockdown period
if ($timesheetStart > $lockdownEnd) {
return;
}
// lockdown never takes effect for users with special permission
if ($this->auth->isGranted('lockdown_override_timesheet')) {
return;
}
if (!empty($constraint->now)) {
if ($constraint->now instanceof \DateTime) {
$now = $constraint->now;
} elseif (\is_string($constraint->now)) {
try {
$now = new \DateTime($constraint->now, $timesheetStart->getTimezone());
} catch (\Exception $ex) {
}
}
}
if (empty($now)) {
$now = new \DateTime('now', $timesheetStart->getTimezone());
}
// further validate entries inside of the most recent lockdown
if ($timesheetStart > $lockdownStart && $timesheetStart < $lockdownEnd) {
// if grace period is still in effect, validation succeeds
if ($now < $lockdownGrace) {
return;
}
// if user has special role, validation succeeds
if ($this->auth->isGranted('lockdown_grace_timesheet')) {
return;
}
}
// raise a violation for all entries before the start of lockdown period
$this->context->buildViolation('This period is locked, please choose a later date.')
->atPath('begin')
->setTranslationDomain('validators')
->setCode(TimesheetLockdown::PERIOD_LOCKED)
->addViolation();
}
}

View File

@@ -0,0 +1,26 @@
<?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;
final class TimesheetOverlapping extends TimesheetConstraint
{
public const RECORD_OVERLAPPING = 'kimai-timesheet-overlapping-01';
protected static $errorNames = [
self::RECORD_OVERLAPPING => 'You already have an entry for this time.',
];
public $message = 'You already have an entry for this time.';
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}

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\Validator\Constraints;
use App\Configuration\TimesheetConfiguration;
use App\Entity\Timesheet as TimesheetEntity;
use App\Repository\TimesheetRepository;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
final class TimesheetOverlappingValidator extends ConstraintValidator
{
/**
* @var TimesheetConfiguration
*/
private $configuration;
/**
* @var TimesheetRepository
*/
private $repository;
public function __construct(TimesheetConfiguration $configuration, TimesheetRepository $repository)
{
$this->configuration = $configuration;
$this->repository = $repository;
}
/**
* @param TimesheetEntity $timesheet
* @param Constraint $constraint
*/
public function validate($timesheet, Constraint $constraint)
{
if (!($constraint instanceof TimesheetOverlapping)) {
throw new UnexpectedTypeException($constraint, TimesheetOverlapping::class);
}
if (!\is_object($timesheet) || !($timesheet instanceof TimesheetEntity)) {
throw new UnexpectedTypeException($timesheet, TimesheetEntity::class);
}
if ($this->configuration->isAllowOverlappingRecords()) {
return;
}
if (!$this->repository->hasRecordForTime($timesheet)) {
return;
}
$this->context->buildViolation('You already have an entry for this time.')
->atPath('begin')
->setTranslationDomain('validators')
->setCode(TimesheetOverlapping::RECORD_OVERLAPPING)
->addViolation();
}
}

View File

@@ -0,0 +1,26 @@
<?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;
final class TimesheetRestart extends TimesheetConstraint
{
public const START_DISALLOWED = 'kimai-timesheet-restart-01';
protected static $errorNames = [
self::START_DISALLOWED => 'You are not allowed to start this timesheet record.',
];
public $message = 'You are not allowed to start this timesheet record.';
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}

View File

@@ -0,0 +1,82 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Validator\Constraints;
use App\Entity\Timesheet as TimesheetEntity;
use App\Timesheet\TrackingModeService;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
final class TimesheetRestartValidator extends ConstraintValidator
{
/**
* @var TrackingModeService
*/
private $trackingModeService;
/**
* @var AuthorizationCheckerInterface
*/
private $auth;
public function __construct(TrackingModeService $service, AuthorizationCheckerInterface $auth)
{
$this->trackingModeService = $service;
$this->auth = $auth;
}
/**
* @param TimesheetEntity $timesheet
* @param Constraint $constraint
*/
public function validate($timesheet, Constraint $constraint)
{
if (!($constraint instanceof TimesheetRestart)) {
throw new UnexpectedTypeException($constraint, TimesheetRestart::class);
}
if (!\is_object($timesheet) || !($timesheet instanceof TimesheetEntity)) {
throw new UnexpectedTypeException($timesheet, TimesheetEntity::class);
}
// special case that would otherwise need to be validated in several controllers:
// an entry is edited and the end date is removed (or duration deleted) would restart the record,
// which might be disallowed for the current user
if (null !== $timesheet->getEnd()) {
return;
}
if ($this->context->getViolations()->count() > 0) {
return;
}
if ($this->auth->isGranted('start', $timesheet)) {
return;
}
$mode = $this->trackingModeService->getActiveMode();
$path = 'start';
if ($mode->canEditEnd()) {
$path = 'end';
} elseif ($mode->canEditDuration()) {
$path = 'duration';
}
$this->context->buildViolation('You are not allowed to start this timesheet record.')
->atPath($path)
->setTranslationDomain('validators')
->setCode(TimesheetRestart::START_DISALLOWED)
->addViolation();
return;
}
}

View File

@@ -9,84 +9,52 @@
namespace App\Validator\Constraints;
use App\Configuration\TimesheetConfiguration;
use App\Entity\Timesheet as TimesheetEntity;
use App\Repository\TimesheetRepository;
use App\Timesheet\TrackingModeService;
use App\Validator\Constraints\Timesheet as TimesheetConstraint;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class TimesheetValidator extends ConstraintValidator
final class TimesheetValidator extends ConstraintValidator
{
/**
* @var AuthorizationCheckerInterface
* @var TimesheetConstraint[]
*/
protected $auth;
/**
* @var TimesheetConfiguration
*/
protected $configuration;
/**
* @var TrackingModeService
*/
protected $trackingModeService;
/**
* @var TimesheetRepository
*/
private $repository;
private $constraints;
public function __construct(AuthorizationCheckerInterface $auth, TimesheetConfiguration $configuration, TrackingModeService $service, TimesheetRepository $repository)
/**
* @param TimesheetConstraint[] $constraints
*/
public function __construct(iterable $constraints)
{
$this->auth = $auth;
$this->configuration = $configuration;
$this->trackingModeService = $service;
$this->repository = $repository;
}
/**
* @param TimesheetEntity|mixed $value
* @param Constraint $constraint
*/
public function validate($value, Constraint $constraint)
{
if (!($constraint instanceof TimesheetConstraint)) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\Timesheet');
}
if (!\is_object($value) || !($value instanceof TimesheetEntity)) {
return;
}
$this->validateBeginAndEnd($value, $this->context);
$this->validateActivityAndProject($value, $this->context);
$this->validatePermissions($value, $this->context);
$this->validateActiveLimit($value, $this->context);
$this->validateOverlapping($value, $this->context);
$this->constraints = $constraints;
}
/**
* @param TimesheetEntity $timesheet
* @param ExecutionContextInterface $context
* @param Constraint $constraint
*/
protected function validateOverlapping(TimesheetEntity $timesheet, ExecutionContextInterface $context)
public function validate($timesheet, Constraint $constraint)
{
if ($this->configuration->isAllowOverlappingRecords()) {
return;
if (!($constraint instanceof TimesheetConstraint)) {
throw new UnexpectedTypeException($constraint, Timesheet::class);
}
if (!$this->repository->hasRecordForTime($timesheet)) {
return;
if (!\is_object($timesheet) || !($timesheet instanceof TimesheetEntity)) {
throw new UnexpectedTypeException($timesheet, TimesheetEntity::class);
}
$context->buildViolation('You already have an entry for this time.')
->atPath('begin')
->setTranslationDomain('validators')
->setCode(TimesheetConstraint::RECORD_OVERLAPPING)
->addViolation();
$this->validateBeginAndEnd($timesheet, $this->context);
$this->validateActivityAndProject($timesheet, $this->context);
$this->validateActiveLimit($timesheet, $this->context);
foreach ($this->constraints as $constraint) {
$this->context
->getValidator()
->inContext($this->context)
->validate($timesheet, $constraint, [Constraint::DEFAULT_GROUP]);
}
}
/**
@@ -98,35 +66,6 @@ class TimesheetValidator extends ConstraintValidator
// TODO check active entries against hard_limit
}
/**
* @param TimesheetEntity $timesheet
* @param ExecutionContextInterface $context
*/
protected function validatePermissions(TimesheetEntity $timesheet, ExecutionContextInterface $context)
{
// special case that would otherwise need to be validated in several controllers:
// an entry is edited and the end date is removed (or duration deleted) would restart the record,
// which might be disallowed for the current user
if ($context->getViolations()->count() == 0 && null === $timesheet->getEnd()) {
$mode = $this->trackingModeService->getActiveMode();
$path = 'start';
if ($mode->canEditEnd()) {
$path = 'end';
} elseif ($mode->canEditDuration()) {
$path = 'duration';
}
if (!$this->auth->isGranted('start', $timesheet)) {
$context->buildViolation('You are not allowed to start this timesheet record.')
->atPath($path)
->setTranslationDomain('validators')
->setCode(TimesheetConstraint::START_DISALLOWED)
->addViolation();
return;
}
}
}
/**
* @param TimesheetEntity $timesheet
* @param ExecutionContextInterface $context
@@ -150,18 +89,6 @@ class TimesheetValidator extends ConstraintValidator
->setCode(TimesheetConstraint::END_BEFORE_BEGIN_ERROR)
->addViolation();
}
if (false === $this->configuration->isAllowFutureTimes()) {
// allow configured default rounding time + 1 minute - see #1295
$allowedDiff = ($this->configuration->getDefaultRoundingBegin() * 60) + 60;
if ((time() + $allowedDiff) < $timesheet->getBegin()->getTimestamp()) {
$context->buildViolation('The begin date cannot be in the future.')
->atPath('begin')
->setTranslationDomain('validators')
->setCode(TimesheetConstraint::BEGIN_IN_FUTURE_ERROR)
->addViolation();
}
}
}
/**