apply timeline for report

This commit is contained in:
Julien Fastré 2021-05-25 19:07:09 +02:00
parent 9b1a66c992
commit 5350a09951
5 changed files with 173 additions and 118 deletions

View File

@ -6,5 +6,5 @@ services:
- '@chill.main.security.authorization.helper'
- '@security.token_storage'
public: true
tags:
- { name: chill.timeline, context: 'person' }
# tags:
# - { name: chill.timeline, context: 'person' }

View File

@ -1,9 +1,9 @@
<div class="report_entry">
<h3>{{ report.date|format_date('long') }}<span class="report"> / {{ 'Report'|trans }}</span></h3>
<h3>{{ report.date|format_date('long') }}<span class="report"> / {{ 'Report'|trans }}</span>{% if 'person' != context %} / {{ report.person|chill_entity_render_box }}{% endif %}</h3>
<div class="statement">
<span class="statement">{{ '%user% has filled a %report_label% report'|trans(
{
'%user%' : user,
'%user%' : report.user,
'%report_label%': report.CFGroup.name|localize_translatable_string,
'%date%' : report.date|format_date('long') }
) }}</span>
@ -25,13 +25,13 @@
<ul class="record_actions">
<li>
<a href="{{ path('report_view', { 'person_id': person.id, 'report_id': report.id} ) }}" class="sc-button bt-view">
<a href="{{ path('report_view', { 'person_id': report.person.id, 'report_id': report.id} ) }}" class="sc-button bt-view">
{{ 'View the report'|trans }}
</a>
</li>
{% if is_granted('CHILL_REPORT_UPDATE', report) %}
<li>
<a href="{{ path('report_edit', { 'person_id': person.id, 'report_id': report.id} ) }}" class="sc-button bt-edit">
<a href="{{ path('report_edit', { 'person_id': report.person.id, 'report_id': report.id} ) }}" class="sc-button bt-edit">
{{ 'Update the report'|trans }}
</a>
</li>

View File

@ -30,71 +30,34 @@ use Chill\PersonBundle\Entity\Person;
use Chill\MainBundle\Entity\Scope;
use Chill\CustomFieldsBundle\Service\CustomFieldsHelper;
use Chill\ReportBundle\Entity\Report;
use Symfony\Component\Security\Core\Security;
use Chill\MainBundle\Timeline\TimelineSingleQuery;
/**
* Provide report for inclusion in timeline
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
*/
class TimelineReportProvider implements TimelineProviderInterface
{
/**
*
* @var EntityManager
*/
protected $em;
protected EntityManager $em;
/**
*
* @var AuthorizationHelper
*/
protected $helper;
protected AuthorizationHelper $helper;
/**
*
* @var \Chill\MainBundle\Entity\User
*/
protected $user;
protected CustomFieldsHelper $customFieldsHelper;
/**
*
* @var CustomFieldsHelper
*/
protected $customFieldsHelper;
/**
* @var
*/
protected $showEmptyValues;
/**
* TimelineReportProvider constructor.
*
* @param EntityManager $em
* @param AuthorizationHelper $helper
* @param TokenStorageInterface $storage
* @param CustomFieldsHelper $customFieldsHelper
* @param $showEmptyValues
*/
public function __construct(
EntityManager $em,
AuthorizationHelper $helper,
TokenStorageInterface $storage,
Security $security,
CustomFieldsHelper $customFieldsHelper,
$showEmptyValues
)
{
$this->em = $em;
$this->helper = $helper;
if (!$storage->getToken()->getUser() instanceof \Chill\MainBundle\Entity\User)
{
throw new \RuntimeException('A user should be authenticated !');
}
$this->user = $storage->getToken()->getUser();
$this->security = $security;
$this->customFieldsHelper = $customFieldsHelper;
$this->showEmptyValues = $showEmptyValues;
}
@ -107,70 +70,162 @@ class TimelineReportProvider implements TimelineProviderInterface
{
$this->checkContext($context);
$metadataReport = $this->em->getClassMetadata('ChillReportBundle:Report');
$metadataPerson = $this->em->getClassMetadata('ChillPersonBundle:Person');
return array(
'id' => $metadataReport->getTableName()
.'.'.$metadataReport->getColumnName('id'),
$report = $this->em->getClassMetadata(Report::class);
[$where, $parameters] = $this->getWhereClause($context, $args);
return TimelineSingleQuery::fromArray([
'id' => $report->getTableName()
.'.'.$report->getColumnName('id'),
'type' => 'report',
'date' => $metadataReport->getTableName()
.'.'.$metadataReport->getColumnName('date'),
'FROM' => $this->getFromClause($metadataReport, $metadataPerson),
'WHERE' => $this->getWhereClause($metadataReport, $metadataPerson,
$args['person'])
);
'date' => $report->getTableName()
.'.'.$report->getColumnName('date'),
'FROM' => $this->getFromClause($context),
'WHERE' => $where,
'parameters' => $parameters
]);
}
private function getWhereClause(ClassMetadata $metadataReport,
ClassMetadata $metadataPerson, Person $person)
private function getWhereClause(string $context, array $args): array
{
$role = new Role('CHILL_REPORT_SEE');
$reachableCenters = $this->helper->getReachableCenters($this->user,
$role);
$associationMapping = $metadataReport->getAssociationMapping('person');
// we start with reports having the person_id linked to person
// (currently only context "person" is supported)
$whereClause = sprintf('%s = %d',
$associationMapping['joinColumns'][0]['name'],
$person->getId());
// we add acl (reachable center and scopes)
$centerAndScopeLines = array();
foreach ($reachableCenters as $center) {
$reachablesScopesId = array_map(
function(Scope $scope) { return $scope->getId(); },
$this->helper->getReachableScopes($this->user, $role,
$person->getCenter())
);
$centerAndScopeLines[] = sprintf('(%s = %d AND %s IN (%s))',
$metadataPerson->getTableName().'.'.
$metadataPerson->getAssociationMapping('center')['joinColumns'][0]['name'],
$center->getId(),
$metadataReport->getTableName().'.'.
$metadataReport->getAssociationMapping('scope')['joinColumns'][0]['name'],
implode(',', $reachablesScopesId));
switch ($context) {
case 'person':
return $this->getWhereClauseForPerson($context, $args);
case 'center':
return $this->getWhereClauseForCenter($context, $args);
default:
throw new \UnexpectedValueException("This context $context is not implemented");
}
$whereClause .= ' AND ('.implode(' OR ', $centerAndScopeLines).')';
return $whereClause;
}
private function getWhereClauseForCenter(string $context, array $args): array
{
$report = $this->em->getClassMetadata(Report::class);
$person = $this->em->getClassMetadata(Person::class);
$role = new Role('CHILL_REPORT_SEE');
$reachableCenters = $this->helper->getReachableCenters($this->security->getUser(),
$role);
$reportPersonId = $report->getAssociationMapping('person')['joinColumns'][0]['name'];
$reportScopeId = $report->getAssociationMapping('scope')['joinColumns'][0]['name'];
$personCenterId = $person->getAssociationMapping('center')['joinColumns'][0]['name'];
// parameters for the query, will be filled later
$parameters = [];
// the clause, that will be joined with an "OR"
$centerScopesClause = "({person}.{center_id} = ? ".
"AND {report}.{scopes_id} IN ({scopes_ids}))";
// container for formatted clauses
$formattedClauses = [];
$askedCenters = $args['centers'];
foreach ($reachableCenters as $center) {
if (FALSE === \in_array($center, $askedCenters)) {
continue;
}
// add the center id to the parameters
$parameters[] = $center->getId();
// loop over scopes
$scopeIds = [];
foreach ($this->helper->getReachableScopes($this->security->getUser(),
$role, $center) as $scope) {
if (\in_array($scope->getId(), $scopeIds)) {
continue;
}
$scopeIds[] = $scope->getId();
}
$formattedClauses[] = \strtr($centerScopesClause, [
'{scopes_ids}' => \implode(', ', \array_fill(0, \count($scopeIds), '?'))
]);
// append $scopeIds to parameters
$parameters = \array_merge($parameters, $scopeIds);
}
if (0 === count($formattedClauses)) {
return [ 'FALSE = TRUE', [] ];
}
return [
\strtr(
\implode(' OR ', $formattedClauses),
[
'{person}' => $person->getTableName(),
'{center_id}' => $personCenterId,
'{report}' => $report->getTableName(),
'{scopes_id}' => $reportScopeId,
]
),
$parameters
];
}
private function getWhereClauseForPerson(string $context, array $args): array
{
$report = $this->em->getClassMetadata(Report::class);
$person = $this->em->getClassMetadata(Person::class);
$role = new Role('CHILL_REPORT_SEE');
$reportPersonId = $report->getAssociationMapping('person')['joinColumns'][0]['name'];
$reportScopeId = $report->getAssociationMapping('scope')['joinColumns'][0]['name'];
$personCenterId = $person->getAssociationMapping('center')['joinColumns'][0]['name'];
// parameters for the query, will be filled later
$parameters = [ $args['person']->getId() ];
// this is the final clause that we are going to fill
$clause = "{report}.{person_id} = ? AND {report}.{scopes_id} IN ({scopes_ids})";
// iterate over reachable scopes
$scopes = $this->helper->getReachableScopes($this->security->getUser(), $role,
$args['person']->getCenter());
foreach ($scopes as $scope) {
if (\in_array($scope->getId(), $parameters)) {
continue;
}
$parameters[] = $scope->getId();
}
if (1 === count($parameters)) {
// nothing change, we simplify the clause
$clause = "{report}.{person_id} = ? AND FALSE = TRUE";
}
return [
\strtr(
$clause,
[
'{report}' => $report->getTableName(),
'{person_id}' => $reportPersonId,
'{scopes_id}' => $reportScopeId,
'{scopes_ids}' => \implode(', ',
\array_fill(0, \count($parameters)-1, '?'))
]
),
$parameters
];
}
private function getFromClause(ClassMetadata $metadataReport,
ClassMetadata $metadataPerson)
private function getFromClause(string $context): string
{
$associationMapping = $metadataReport->getAssociationMapping('person');
return $metadataReport->getTableName().' JOIN '
.$metadataPerson->getTableName().' ON '
.$metadataPerson->getTableName().'.'.
$associationMapping['joinColumns'][0]['referencedColumnName']
.' = '
.$associationMapping['joinColumns'][0]['name']
$report = $this->em->getClassMetadata(Report::class);
$person = $this->em->getClassMetadata(Person::class);
$reportPersonId = $report
->getAssociationMapping('person')['joinColumns'][0]['name']
;
$personId = $report
->getAssociationMapping('person')['joinColumns'][0]['referencedColumnName']
;
$clause = "{report} ".
"JOIN {person} ON {report}.{person_id} = {person}.{id_person} ";
return \strtr($clause,
[
'{report}' => $report->getTableName(),
'{person}' => $person->getTableName(),
'{person_id}' => $reportPersonId,
'{id_person}' => $personId
]
);
}
/**
@ -199,12 +254,11 @@ class TimelineReportProvider implements TimelineProviderInterface
$this->checkContext($context);
return array(
'template' => 'ChillReportBundle:Timeline:report_person_context.html.twig',
'template' => 'ChillReportBundle:Timeline:report.html.twig',
'template_data' => array(
'report' => $entity,
'custom_fields_in_summary' => $this->getFieldsToRender($entity, $context),
'person' => $args['person'],
'user' => $entity->getUser()
'report' => $entity,
'context' => $context,
'custom_fields_in_summary' => $this->getFieldsToRender($entity, $context),
)
);
}
@ -272,9 +326,9 @@ class TimelineReportProvider implements TimelineProviderInterface
*/
private function checkContext($context)
{
if ($context !== 'person') {
if ($context !== 'person' && $context !== 'center') {
throw new \LogicException("The context '$context' is not "
. "supported. Currently only 'person' is supported");
. "supported. Currently only 'person' and 'center' is supported");
}
}

View File

@ -20,11 +20,12 @@ services:
arguments:
- '@doctrine.orm.entity_manager'
- '@chill.main.security.authorization.helper'
- '@security.token_storage'
- '@Symfony\Component\Security\Core\Security'
- '@chill.custom_field.helper'
- '%chill_custom_fields.show_empty_values%'
tags:
- { name: chill.timeline, context: 'person' }
- { name: chill.timeline, context: 'center' }
chill.report.security.authorization.report_voter:
class: Chill\ReportBundle\Security\Authorization\ReportVoter
@ -43,4 +44,4 @@ services:
- "@doctrine.orm.entity_manager"
tags:
- { name: form.type, alias: chill_reportbundle_report }

View File

@ -6,12 +6,12 @@ services:
$authorizationHelper: '@Chill\MainBundle\Security\Authorization\AuthorizationHelper'
$tokenStorage: '@Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface'
public: true
tags:
- { name: 'chill.timeline', context: 'person' }
# tags:
# - { name: 'chill.timeline', context: 'person' }
Chill\TaskBundle\Timeline\SingleTaskTaskLifeCycleEventTimelineProvider:
arguments:
$em: '@Doctrine\ORM\EntityManagerInterface'
$registry: '@Symfony\Component\Workflow\Registry'
tags:
- { name: 'chill.timeline', context: 'task' }
# tags:
#- { name: 'chill.timeline', context: 'task' }