Release 1.19.4 (#3255)

* login redirects to homepage if already being logged-in
* fix budget check for entries that were moved to another moth
* invoice: fix amount should be decimal if decimal template is used
* added new month grouped by project/activity/user report
This commit is contained in:
Kevin Papst
2022-04-18 12:41:45 +02:00
committed by GitHub
parent a179719c3e
commit bc908b4534
20 changed files with 729 additions and 56 deletions

View File

@@ -17,11 +17,11 @@ class Constants
/**
* The current release version
*/
public const VERSION = '1.19.3';
public const VERSION = '1.19.4';
/**
* The current release: major * 10000 + minor * 100 + patch
*/
public const VERSION_ID = 11903;
public const VERSION_ID = 11904;
/**
* The current release status, either "stable" or "dev"
*/

View File

@@ -18,6 +18,7 @@ use App\Timesheet\DateTimeFactory;
use App\Utils\LocaleFormats;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as BaseAbstractController;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
@@ -39,6 +40,13 @@ abstract class AbstractController extends BaseAbstractController implements Serv
return $this->container->get('translator');
}
public function createFormForGetRequest(string $type = FormType::class, $data = null, array $options = []): FormInterface
{
return $this->container
->get('form.factory')
->createNamed('', $type, $data, $options);
}
private function getLogger(): LoggerInterface
{
return $this->container->get('logger');

View File

@@ -0,0 +1,111 @@
<?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\Controller\Reporting;
use App\Controller\AbstractController;
use App\Export\Spreadsheet\Writer\BinaryFileResponseWriter;
use App\Export\Spreadsheet\Writer\XlsxWriter;
use App\Reporting\CustomerMonthlyProjects\CustomerMonthlyProjects;
use App\Reporting\CustomerMonthlyProjects\CustomerMonthlyProjectsForm;
use App\Repository\Query\UserQuery;
use App\Repository\UserRepository;
use App\Timesheet\TimesheetStatisticService;
use PhpOffice\PhpSpreadsheet\Reader\Html;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route(path="/reporting/customer/monthly_projects")
* @Security("is_granted('view_reporting') and is_granted('view_other_reporting') and is_granted('view_other_timesheet')")
*/
final class CustomerMonthlyProjectsController extends AbstractController
{
/**
* @Route(path="/view", name="report_customer_monthly_projects", methods={"GET","POST"})
*/
public function report(Request $request, TimesheetStatisticService $statisticService, UserRepository $userRepository): Response
{
return $this->render(
'reporting/customer/monthly_projects.html.twig',
$this->getData($request, $statisticService, $userRepository)
);
}
/**
* @Route(path="/export", name="report_customer_monthly_projects_export", methods={"GET","POST"})
*/
public function export(Request $request, TimesheetStatisticService $statisticService, UserRepository $userRepository): Response
{
$data = $this->getData($request, $statisticService, $userRepository);
$content = $this->render('reporting/customer/monthly_projects_export.html.twig', $data)->getContent();
$reader = new Html();
$spreadsheet = $reader->loadFromString($content);
$writer = new BinaryFileResponseWriter(new XlsxWriter(), 'kimai-export-users-monthly');
return $writer->getFileResponse($spreadsheet);
}
private function getData(Request $request, TimesheetStatisticService $statisticService, UserRepository $userRepository): array
{
$currentUser = $this->getUser();
$dateTimeFactory = $this->getDateTimeFactory();
$query = new UserQuery();
$query->setCurrentUser($currentUser);
$allUsers = $userRepository->getUsersForQuery($query);
$values = new CustomerMonthlyProjects();
$values->setDate($dateTimeFactory->getStartOfMonth());
$form = $this->createFormForGetRequest(CustomerMonthlyProjectsForm::class, $values, [
'timezone' => $dateTimeFactory->getTimezone()->getName(),
'start_date' => $values->getDate(),
]);
$form->submit($request->query->all(), false);
if ($form->isSubmitted() && !$form->isValid()) {
$values->setDate($dateTimeFactory->getStartOfMonth());
}
if ($values->getDate() === null) {
$values->setDate($dateTimeFactory->getStartOfMonth());
}
$start = $values->getDate();
$start = $dateTimeFactory->getStartOfMonth($start);
$end = $dateTimeFactory->getEndOfMonth($start);
$previous = clone $start;
$previous->modify('-1 month');
$next = clone $start;
$next->modify('+1 month');
$stats = $statisticService->getGroupedByCustomerProjectActivityUser($start, $end, $allUsers);
return [
'dataType' => $values->getSumType(),
'report_title' => 'report_customer_monthly_projects',
'export_route' => 'report_customer_monthly_projects_export',
'form' => $form->createView(),
'current' => $start,
'next' => $next,
'previous' => $previous,
'decimal' => $values->isDecimal(),
'stats' => $stats,
];
}
}

View File

@@ -32,6 +32,10 @@ final class SecurityController extends AbstractController
*/
public function loginAction(Request $request): Response
{
if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
return $this->redirectToRoute('homepage');
}
/** @var SessionInterface $session */
$session = $request->getSession();

View File

@@ -32,7 +32,11 @@ class InvoiceItemDefaultHydrator implements InvoiceItemHydrator
$rate = $item->getRate();
$internalRate = $item->getInternalRate();
$appliedRate = $item->getHourlyRate();
$amount = $formatter->getFormattedDuration($item->getDuration());
if ($this->model->getTemplate()->isDecimalDuration()) {
$amount = $formatter->getFormattedDecimalDuration($item->getDuration());
} else {
$amount = $formatter->getFormattedDuration($item->getDuration());
}
$description = $item->getDescription();
if ($item->isFixedRate()) {

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\Reporting\CustomerMonthlyProjects;
use App\Reporting\AbstractUserList;
final class CustomerMonthlyProjects extends AbstractUserList
{
}

View File

@@ -0,0 +1,46 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Reporting\CustomerMonthlyProjects;
use App\Form\Type\MonthPickerType;
use App\Form\Type\ReportSumType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class CustomerMonthlyProjectsForm extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('date', MonthPickerType::class, [
'model_timezone' => $options['timezone'],
'view_timezone' => $options['timezone'],
'start_date' => $options['start_date'],
]);
$builder->add('sumType', ReportSumType::class);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => CustomerMonthlyProjects::class,
'timezone' => date_default_timezone_get(),
'start_date' => new \DateTime(),
'csrf_protection' => false,
'method' => 'GET',
]);
}
}

View File

@@ -60,6 +60,9 @@ final class ReportingService
$event->addReport(new Report('daterange_projects', 'report_project_daterange', 'report_project_daterange', 'project'));
$event->addReport(new Report('inactive_projects', 'report_project_inactive', 'report_inactive_project', 'project'));
}
if ($this->security->isGranted('view_other_reporting') && $this->security->isGranted('view_other_timesheet')) {
$event->addReport(new Report('report_customer_monthly_projects', 'report_customer_monthly_projects', 'report_customer_monthly_projects', 'customer'));
}
$this->dispatcher->dispatch($event);
}

View File

@@ -55,7 +55,7 @@ class TimesheetRepository extends EntityRepository
public const STATS_QUERY_MONTHLY = 'monthly';
/**
* Fetches the raw data of an timesheet, to allow comparison eg. of submitted and previously stored data.
* Fetches the raw data of a timesheet, to allow comparison e.g. of submitted and previously stored data.
*
* @param Timesheet $id
* @return array
@@ -66,6 +66,8 @@ class TimesheetRepository extends EntityRepository
$qb
->select([
't.rate',
't.begin',
't.end',
't.duration',
't.hourlyRate',
't.billable',

View File

@@ -9,11 +9,16 @@
namespace App\Timesheet;
use App\Entity\Activity;
use App\Entity\Customer;
use App\Entity\Project;
use App\Entity\User;
use App\Model\DailyStatistic;
use App\Model\MonthlyStatistic;
use App\Repository\TimesheetRepository;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\Expr\Join;
final class TimesheetStatisticService
{
@@ -21,10 +26,12 @@ final class TimesheetStatisticService
* @var TimesheetRepository
*/
private $repository;
private $entityManager;
public function __construct(TimesheetRepository $repository)
public function __construct(TimesheetRepository $repository, EntityManagerInterface $entityManager)
{
$this->repository = $repository;
$this->entityManager = $entityManager;
}
/**
@@ -323,4 +330,141 @@ final class TimesheetStatisticService
return array_values($stats);
}
/**
* @param DateTime $begin
* @param DateTime $end
* @param User[] $users
* @return array
*/
public function getGroupedByCustomerProjectActivityUser(DateTime $begin, DateTime $end, array $users): array
{
$stats = [];
$qb = $this->repository->createQueryBuilder('t');
$qb
->select('COALESCE(SUM(t.rate), 0) as rate')
->addSelect('COALESCE(SUM(t.duration), 0) as duration')
->addSelect('COALESCE(SUM(t.internalRate), 0) as internalRate')
->addSelect('IDENTITY(t.user) as user')
->addSelect('IDENTITY(t.activity) as activity')
->addSelect('IDENTITY(t.project) as project')
->where($qb->expr()->isNotNull('t.end'))
->andWhere($qb->expr()->between('t.begin', ':begin', ':end'))
->andWhere($qb->expr()->in('t.user', ':user'))
->setParameter('begin', $begin)
->setParameter('end', $end)
->setParameter('user', $users)
->groupBy('project')
->addGroupBy('activity')
->addGroupBy('user')
;
$results = $qb->getQuery()->getResult();
$projectIds = [];
$activityIds = [];
$userIds = [];
foreach ($results as $row) {
$projectId = $row['project'];
$activityId = $row['activity'];
$userId = $row['user'];
$projectIds[$projectId] = $projectId;
$activityIds[$activityId] = $activityId;
$userIds[$userId] = $userId;
if (!isset($stats[$projectId])) {
$stats[$projectId] = [
'id' => $projectId,
'name' => null,
'activities' => [],
'duration' => 0,
'rate' => 0,
'internalRate' => 0,
'max_users' => 0,
];
}
$stats[$projectId]['duration'] += (int) $row['duration'];
$stats[$projectId]['rate'] += (int) $row['rate'];
$stats[$projectId]['internalRate'] += (int) $row['internalRate'];
if (!isset($stats[$projectId]['activities'][$activityId])) {
$stats[$projectId]['activities'][$activityId] = [
'id' => $activityId,
'name' => null,
'users' => [],
'duration' => 0,
'rate' => 0,
'internalRate' => 0,
];
}
$stats[$projectId]['activities'][$activityId]['duration'] += (int) $row['duration'];
$stats[$projectId]['activities'][$activityId]['rate'] += (int) $row['rate'];
$stats[$projectId]['activities'][$activityId]['internalRate'] += (int) $row['internalRate'];
if (!isset($stats[$projectId]['activities'][$activityId]['users'][$userId])) {
$stats[$projectId]['activities'][$activityId]['users'][$userId] = [
'id' => $userId,
'name' => null,
'duration' => 0,
'rate' => 0,
'internalRate' => 0,
];
}
$stats[$projectId]['activities'][$activityId]['users'][$userId]['duration'] += (int) $row['duration'];
$stats[$projectId]['activities'][$activityId]['users'][$userId]['rate'] += (int) $row['rate'];
$stats[$projectId]['activities'][$activityId]['users'][$userId]['internalRate'] += (int) $row['internalRate'];
}
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a.id, a.name')
->from(Activity::class, 'a', 'a.id')
->where($qb->expr()->in('a.id', ':id'))
->setParameter('id', array_values($activityIds))
;
$activities = $qb->getQuery()->getResult();
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('p.id, p.name, c.id as customer_id, c.name as customer, c.currency')
->from(Project::class, 'p', 'p.id')
->leftJoin(Customer::class, 'c', Join::WITH, 'c.id = p.customer')
->where($qb->expr()->in('p.id', ':id'))
->setParameter('id', array_values($projectIds))
;
$projects = $qb->getQuery()->getResult();
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('u')
->from(User::class, 'u', 'u.id')
->where($qb->expr()->in('u.id', ':id'))
->setParameter('id', array_values($userIds))
;
$users = $qb->getQuery()->getResult();
foreach (array_keys($stats) as $pid) {
$stats[$pid]['name'] = $projects[$pid]['name'];
foreach (array_keys($stats[$pid]['activities']) as $aid) {
$stats[$pid]['activities'][$aid]['name'] = $activities[$aid]['name'];
foreach (array_keys($stats[$pid]['activities'][$aid]['users']) as $uid) {
$stats[$pid]['activities'][$aid]['users'][$uid]['name'] = $users[$uid]->getDisplayName();
}
$stats[$pid]['max_users'] = max($stats[$pid]['max_users'], \count($stats[$pid]['activities'][$aid]['users']));
}
}
return [
'stats' => $stats,
'projects' => $projects,
'activities' => $activities,
'users' => $users,
];
}
}

View File

@@ -97,7 +97,7 @@ final class TimesheetBudgetUsedValidator extends ConstraintValidator
// if an existing entry was updated, but "duration", "rate" and "billable" were not changed:
// do not validate! this could for example happen when export flag is changed OR if "prevent overbooking"
// config was recently activated and this is an old entry
if ($duration === $rawData['duration'] && $rate === $rawData['rate'] && $timesheet->isBillable() === $rawData['billable']) {
if ($duration === $rawData['duration'] && $rate === $rawData['rate'] && $timesheet->isBillable() === $rawData['billable'] && $timesheet->getBegin()->format('Y.m.d') === $rawData['begin']->format('Y.m.d')) {
return;
}
@@ -174,12 +174,12 @@ final class TimesheetBudgetUsedValidator extends ConstraintValidator
private function addBudgetViolation(TimesheetBudgetUsed $constraint, Timesheet $timesheet, string $field, float $budget, float $rate)
{
// using the locale of the assigned user is not the best solution, but allows to be independent from the request stack
// using the locale of the assigned user is not the best solution, but allows to be independent of the request stack
$helper = new LocaleHelper($timesheet->getUser()->getLanguage());
$currency = $timesheet->getProject()->getCustomer()->getCurrency();
$free = $budget - $rate;
$free = $free > 0 ? $free : 0;
$free = max($free, 0);
$this->context->buildViolation($constraint->messageRate)
->atPath($field)
@@ -198,7 +198,7 @@ final class TimesheetBudgetUsedValidator extends ConstraintValidator
$durationFormat = new Duration();
$free = $budget - $duration;
$free = $free > 0 ? $free : 0;
$free = max($free, 0);
$this->context->buildViolation($constraint->messageTime)
->atPath($field)