Skip to content
Snippets Groups Projects
Commit 4e62ed3f authored by Sujan Shrestha's avatar Sujan Shrestha
Browse files

Permission bug fixes

parent b2202d34
No related branches found
Tags 1.3.1
No related merge requests found
Showing
with 240 additions and 447 deletions
......@@ -559,7 +559,7 @@ display:
access:
type: perm
options:
perm: 'access et_transaction overview'
perm: 'access expense_tracker'
cache:
type: none
options: { }
......
......@@ -15,21 +15,10 @@
.et_transaction .total {
text-align: center;
}
.et_transaction .vote-form {
text-align: center;
}
.et_transaction .vote-form {
text-align: left; /* LTR */
}
.et_transaction .vote-form .et_transaction-title {
font-weight: bold;
}
.et_transaction-chtext {
width: 80%;
}
.et_transaction-chvotes .form-text {
width: 85%;
}
.et_transaction {
overflow: hidden;
}
......
<?php
/**
* @file
* Collects votes on different topics in the form of multiple choice titles.
*/
use Drupal\Core\Template\Attribute;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
......@@ -502,9 +497,14 @@ function expense_tracker_views_query_alter(ViewExecutable $view, QueryPluginBase
}
}
}
}
if($view->id() == 'expense_tracker_admin') {
$current_user = \Drupal::currentUser();
if (!$current_user->hasPermission('access all expense_tracker')) {
$uid = $current_user->id();
$query->addWhere('view_access', 'et_transaction_field_data.uid', [$uid], 'IN');
}
}
}
......
create expense_tracker:
title: 'Create expense and income transactions'
edit expense_tracker:
title: 'Edit expense and income transactions'
title: 'Edit own expense and income transactions'
delete expense_tracker:
title: 'Delete expense and income transactions'
title: 'Delete own expense and income transactions'
config expense_tracker:
title: 'Configure expense and income transactions'
reports expense_tracker:
......@@ -11,4 +11,10 @@ reports expense_tracker:
import expense_tracker:
title: 'Import expense and income date'
access expense_tracker:
title: 'View expense and income data'
title: 'View own expense and income data'
edit all expense_tracker:
title: 'Edit all expense and income transactions'
delete all expense_tracker:
title: 'Delete all expense and income transactions'
access all expense_tracker:
title: 'View all expense and income data'
\ No newline at end of file
......@@ -4,7 +4,8 @@ expense_tracker.et_transaction_list:
_entity_list: 'et_transaction'
_title: 'EtTransactions'
requirements:
_permission: 'access expense_tracker'
# _permission: 'access expense_tracker'
_entity_access: 'et_transaction'
expense_tracker.expense_tracker_add:
path: '/admin/income-expense-transactions/add'
......
services:
expense_tracker.post_render_cache:
class: Drupal\expense_tracker\EtTransactionPostRenderCache
arguments: ['@entity_type.manager']
expense_tracker_vote.storage:
class: Drupal\expense_tracker\EtTransactionVoteStorage
arguments: ['@database', '@cache_tags.invalidator']
......@@ -29,7 +29,7 @@ use Drupal\Core\Datetime\DrupalDateTime;
* "default" = "Drupal\expense_tracker\Form\EtTransactionForm",
* "edit" = "Drupal\expense_tracker\Form\EtTransactionForm",
* "delete" = "Drupal\expense_tracker\Form\EtTransactionDeleteForm",
* "delete_vote" = "Drupal\expense_tracker\Form\EtTransactionVoteDeleteForm",
* "delete_transaction" = "Drupal\expense_tracker\Form\EtTransactionDeleteForm",
* "delete_items" = "Drupal\expense_tracker\Form\EtTransactionItemsDeleteForm",
* }
* },
......@@ -129,45 +129,45 @@ class EtTransaction extends ContentEntityBase implements EtTransactionInterface
/**
* {@inheritdoc}
*/
public function getAnonymousVoteAllow() {
return $this->get('anonymous_vote_allow')->value;
public function getAnonymousTransactionAllow() {
return $this->get('anonymous_transaction_allow')->value;
}
/**
* {@inheritdoc}
*/
public function setAnonymousVoteAllow($anonymous_vote_allow) {
$this->set('anonymous_vote_allow', $anonymous_vote_allow);
public function setAnonymousTransactionAllow($anonymous_transaction_allow) {
$this->set('anonymous_transaction_allow', $anonymous_transaction_allow);
return $this;
}
/**
* {@inheritdoc}
*/
public function getCancelVoteAllow() {
return $this->get('cancel_vote_allow')->value;
public function getCancelTransactionAllow() {
return $this->get('cancel_transaction_allow')->value;
}
/**
* {@inheritdoc}
*/
public function setCancelVoteAllow($cancel_vote_allow) {
$this->set('cancel_vote_allow', $cancel_vote_allow);
public function setCancelTransactionAllow($cancel_transaction_allow) {
$this->set('cancel_transaction_allow', $cancel_transaction_allow);
return $this;
}
/**
* {@inheritdoc}
*/
public function getResultVoteAllow() {
return $this->get('result_vote_allow')->value;
public function getResultTransactionAllow() {
return $this->get('result_transaction_allow')->value;
}
/**
* {@inheritdoc}
*/
public function setResultVoteAllow($result_vote_allow) {
$this->set('result_vote_allow', $result_vote_allow);
public function setResultTransactionAllow($result_transaction_allow) {
$this->set('result_transaction_allow', $result_transaction_allow);
return $this;
}
......@@ -643,10 +643,10 @@ class EtTransaction extends ContentEntityBase implements EtTransactionInterface
*
* @return mixed
*/
public function hasUserVoted() {
/** @var \Drupal\et_transaction\EtTransactionVoteStorage $vote_storage */
$vote_storage = \Drupal::service('expense_tracker_vote.storage');
return $vote_storage->getUserVote($this);
public function hasUserTransactiond() {
/** @var \Drupal\et_transaction\EtTransactionTransactionStorage $transaction_storage */
$transaction_storage = \Drupal::service('expense_tracker_transaction.storage');
return $transaction_storage->getUserTransaction($this);
}
/**
......@@ -701,7 +701,7 @@ class EtTransaction extends ContentEntityBase implements EtTransactionInterface
$removed_choices = array_diff($original_choices, $current_choices);
if ($removed_choices) {
\Drupal::service('expense_tracker_vote.storage')->deleteChoicesVotes($removed_choices);
\Drupal::service('expense_tracker_transaction.storage')->deleteChoicesTransactions($removed_choices);
$storage = \Drupal::entityTypeManager()->getStorage('et_transaction_choice');
$storage->delete($storage->loadMultiple($removed_choices));
}
......@@ -714,9 +714,9 @@ class EtTransaction extends ContentEntityBase implements EtTransactionInterface
public static function postDelete(EntityStorageInterface $storage, array $entities) {
// parent::postDelete($storage, $entities);
// // Delete votes.
// // Delete transactions.
// foreach ($entities as $entity) {
// $storage->deleteVotes($entity);
// $storage->deleteTransactions($entity);
// }
// // Delete referenced choices.
......@@ -732,10 +732,10 @@ class EtTransaction extends ContentEntityBase implements EtTransactionInterface
/**
* {@inheritdoc}
*/
public function getVotes() {
/** @var \Drupal\et_transaction\EtTransactionVoteStorage $vote_storage */
$vote_storage = \Drupal::service('expense_tracker_vote.storage');
return $vote_storage->getVotes($this);
public function getTransactions() {
/** @var \Drupal\et_transaction\EtTransactionTransactionStorage $transaction_storage */
$transaction_storage = \Drupal::service('expense_tracker_transaction.storage');
return $transaction_storage->getTransactions($this);
}
}
......@@ -20,37 +20,187 @@ class EtTransactionAccessControlHandler extends EntityAccessControlHandler {
* {@inheritdoc}
*/
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
return AccessResult::allowedIfHasPermissions($account, ['create et_transactions', 'administer et_transactions'], 'OR');
$entityTypeIndicator = \Drupal::routeMatch()->getParameters()->keys()[0];
$entity = \Drupal::routeMatch()->getParameter($entityTypeIndicator);
$route_name = \Drupal::routeMatch()->getRouteName();
$is_author = false;
if($entity && is_object($entity)) {
if(!$account->isAnonymous() && $account->id() == $entity->get('uid')->target_id) {
$is_author = true;
}
}
$valid = false;
switch ($route_name) {
case 'entity.et_transaction.edit_form':
if(!$account->isAnonymous() && $account->hasPermission('edit all expense_tracker')) {
return AccessResult::allowed()->cachePerPermissions();
} elseif ($account->hasPermission('edit expense_tracker')) {
if($is_author) {
$valid = true;
}
}
break;
case 'entity.et_transaction.delete_form':
if(!$account->isAnonymous() && $account->hasPermission('delete all expense_tracker')) {
return AccessResult::allowed()->cachePerPermissions();
} elseif ($account->hasPermission('delete expense_tracker')) {
if($is_author) {
$valid = true;
}
}else
break;
default:
return AccessResult::allowed()->cachePerPermissions();
break;
}
if($valid) {
return AccessResult::allowed()->cachePerPermissions();
} else {
throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();
}
}
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
// Allow view access if the user has the access et_transactions permission.
if ($operation == 'view') {
return AccessResult::allowedIfHasPermission($account, 'access et_transactions');
$route_name = \Drupal::routeMatch()->getRouteName();
switch ($route_name) {
case 'entity.et_transaction.edit_form':
if($account->hasPermission('edit all expense_tracker')) {
return AccessResult::allowed()->cachePerPermissions();
} else {
if($is_author) {
return AccessResult::allowedIfHasPermission($account, 'edit expense_tracker');
}
}
break;
default:
// code...
break;
}
$is_author = false;
if(!$account->isAnonymous() && $account->id() == $entity->get('uid')->target_id) {
$is_author = true;
}
elseif ($operation == 'update' && !$account->isAnonymous() && $account->id() == $entity->get('uid')->target_id) {
return AccessResult::allowedIfHasPermissions($account, [
'edit own et_transactions',
'administer et_transactions',
], 'OR');
$user_roles = $account->getRoles();
if (!in_array('administrator', $user_roles)) {
// var_export($operation);
if ($operation == 'view') {
if($account->hasPermission('access all expense_tracker')) {
return AccessResult::allowed()->cachePerPermissions();
} else {
if($is_author) {
return AccessResult::allowedIfHasPermission($account, 'access expense_tracker');
}
}
} elseif ($operation == 'update') {
if($account->hasPermission('edit all expense_tracker')) {
return AccessResult::allowed()->cachePerPermissions();
} else {
if($is_author) {
return AccessResult::allowedIfHasPermission($account, 'edit expense_tracker');
}
}
} elseif ($operation == 'delete') {
if($account->hasPermission('delete all expense_tracker')) {
return AccessResult::allowed()->cachePerPermissions();
} else {
if($is_author) {
return AccessResult::allowedIfHasPermission($account, 'delete expense_tracker');
}
}
} else {
if(!$account->isAnonymous()) {
return AccessResult::allowedIfHasPermissions($account, [
'create expense_tracker',
'access expense_tracker',
'edit expense_tracker',
'delete expense_tracker',
'access all expense_tracker',
'edit all expense_tracker',
'delete all expense_tracker',
], 'OR');
// var_dump($return);
}
}
}
// Otherwise fall back to the parent which checks the administer et_transactions
// permission.
return parent::checkAccess($entity, $operation, $account);
// // Allow view access if the user has the access expense_tracker permission.
// if ($operation == 'view') {
// return AccessResult::allowedIfHasPermission($account, 'access expense_tracker');
// }
// elseif (($operation == 'update' || $operation == 'delete') && !$account->isAnonymous() && $account->id() == $entity->get('uid')->target_id) {
// return AccessResult::allowedIfHasPermission($account, 'access expense_tracker');
// return AccessResult::allowedIfHasPermissions($account, [
// 'edit expense_tracker',
// 'delete expense_tracker',
// ], 'OR');
// } elseif(!$account->isAnonymous() && $account->id() == $entity->get('uid')->target_id) {
// return AccessResult::allowedIfHasPermissions($account, [
// 'access expense_tracker',
// 'edit expense_tracker',
// 'create expense_tracker',
// 'delete expense_tracker',
// 'administer expense_tracker',
// ], 'OR');
// } else {
// if(!$account->isAnonymous()) {
// return AccessResult::allowedIfHasPermissions($account, [
// 'create expense_tracker',
// 'access expense_tracker',
// 'edit expense_tracker',
// 'delete expense_tracker',
// 'access all expense_tracker',
// 'edit all expense_tracker',
// 'delete all expense_tracker',
// 'administer expense_tracker',
// 'administer expense_tracker',
// ], 'OR');
// }
// }
// // Otherwise fall back to the parent which checks the administer expense_tracker
// // permission.
// return parent::checkAccess($entity, $operation, $account);
}
/**
* {@inheritdoc}
*/
protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
$restricted_fields = [
'uid',
];
if ($operation === 'edit' && in_array($field_definition->getName(), $restricted_fields, TRUE)) {
return AccessResult::allowedIfHasPermission($account, 'administer et_transactions');
return AccessResult::allowedIfHasPermission($account, 'administer expense_tracker');
}
return parent::checkFieldAccess($operation, $field_definition, $account, $items);
}
......
......@@ -59,65 +59,6 @@ interface EtTransactionInterface extends ContentEntityInterface {
*/
public function setRuntime($runtime);
/**
* Returns the last time where the feed was checked for new items.
*
* @return int
* The timestamp when new items were last checked for.
*/
public function getAnonymousVoteAllow();
/**
* Sets the time when this feed was queued for refresh, 0 if not queued.
*
* @param int $anonymous_vote_allow
* The timestamp of the last refresh.
*
* @return \Drupal\expense_tracker\EtTransactionInterface
* The class instance that this method is called on.
*/
public function setAnonymousVoteAllow($anonymous_vote_allow);
/**
* Returns the time when this feed was queued for refresh, 0 if not queued.
*
* @return int
* The timestamp of the last refresh.
*/
public function getCancelVoteAllow();
/**
* Sets the time when this feed was queued for refresh, 0 if not queued.
*
* @param int $cancel_vote_allow
* The timestamp of the last refresh.
*
* @return \Drupal\expense_tracker\EtTransactionInterface
* The class instance that this method is called on.
*/
public function setCancelVoteAllow($cancel_vote_allow);
/**
* Returns the time when this feed was queued for refresh, 0 if not queued.
*
* @return int
* The timestamp of the last refresh.
*/
public function getResultVoteAllow();
/**
* Sets the time when this feed was queued for refresh, 0 if not queued.
*
* @param int $result_vote_allow
* The timestamp of the last refresh.
*
* @return \Drupal\expense_tracker\EtTransactionInterface
* The class instance that this method is called on.
*/
public function setResultVoteAllow($result_vote_allow);
/**
* Returns if the et_transaction is open.
*
......@@ -144,13 +85,6 @@ interface EtTransactionInterface extends ContentEntityInterface {
*/
public function open();
/**
* @todo: Refactor - doesn't belong here.
*
* @return mixed
*/
public function hasUserVoted();
/**
* Get all options for this et_transaction.
*
......@@ -160,18 +94,11 @@ interface EtTransactionInterface extends ContentEntityInterface {
public function getOptions();
/**
* Get the values of each vote option for this et_transaction.
* Get the values of each transaction option for this et_transaction.
*
* @return array
* Associative array of option values.
*/
public function getOptionValues();
/**
* Get all the votes of this et_transaction.
*
* @return array
*/
public function getVotes();
}
......@@ -52,8 +52,8 @@ class EtTransactionListBuilder extends DraggableListBuilder {
* Overrides Drupal\Core\Entity\EntityListController::buildRow().
*/
public function buildRow(EntityInterface $entity) {
/** @var \Drupal\et_transaction\EtTransactionVoteStorage $vote_storage */
$vote_storage = \Drupal::service('expense_tracker_vote.storage');
/** @var \Drupal\et_transaction\EtTransactionVoteStorage $transaction_storage */
$transaction_storage = \Drupal::service('expense_tracker.storage');
$row['title'] = $entity->toLink()->toString();
$row['author']['data'] = array(
......
......@@ -13,48 +13,6 @@ use Drupal\Core\Session\AccountInterface;
*/
class EtTransactionStorage extends SqlContentEntityStorage implements EtTransactionStorageInterface {
/**
* {@inheritdoc}
*/
public function getTotalVotes(EtTransactionInterface $et_transaction) {
return \Drupal::service('expense_tracker_vote.storage')->getTotalVotes($et_transaction);
}
/**
* {@inheritdoc}
*/
public function deleteVotes(EtTransactionInterface $et_transaction) {
return \Drupal::service('expense_tracker_vote.storage')->deleteVotes($et_transaction);
}
/**
* {@inheritdoc}
*/
public function getUserVote(EtTransactionInterface $et_transaction) {
return \Drupal::service('expense_tracker_vote.storage')->getUserVote($et_transaction);
}
/**
* {@inheritdoc}
*/
public function saveVote(array $options) {
return \Drupal::service('expense_tracker_vote.storage')->saveVote($options);
}
/**
* {@inheritdoc}
*/
public function getVotes(EtTransactionInterface $et_transaction) {
return \Drupal::service('expense_tracker_vote.storage')->getVotes($et_transaction);
}
/**
* {@inheritdoc}
*/
public function cancelVote(EtTransactionInterface $et_transaction, AccountInterface $account = NULL) {
\Drupal::service('expense_tracker_vote.storage')->cancelVote($et_transaction, $account);
}
/**
* {@inheritdoc}
*/
......
......@@ -10,91 +10,6 @@ use Drupal\Core\Session\AccountInterface;
*/
interface EtTransactionStorageInterface extends EntityStorageInterface {
/**
* Save a user's vote.
*
* @param array $options
*
* @return mixed
*
* @deprecated in Drupal 8.x-1.0.
* Use \Drupal\et_transaction\EtTransactionVoteStorageInterface::saveVote() instead.
*
* @see \Drupal\et_transaction\EtTransactionVoteStorageInterface::saveVote()
*/
public function saveVote(array $options);
/**
* Cancel a user's vote.
*
* @param EtTransactionInterface $et_transaction
* @param AccountInterface $account
*
* @return mixed
*
* @deprecated in Drupal 8.x-1.0.
* Use \Drupal\et_transaction\EtTransactionVoteStorageInterface::cancelVote() instead.
*
* @see \Drupal\et_transaction\EtTransactionVoteStorageInterface::cancelVote()
*/
public function cancelVote(EtTransactionInterface $et_transaction, AccountInterface $account = NULL);
/**
* Get total votes for a et_transaction.
*
* @param EtTransactionInterface $et_transaction
*
* @return mixed
*
* @deprecated in Drupal 8.x-1.0.
* Use \Drupal\et_transaction\EtTransactionVoteStorageInterface::getTotalVotes() instead.
*
* @see \Drupal\et_transaction\EtTransactionVoteStorageInterface::getTotalVotes()
*/
public function getTotalVotes(EtTransactionInterface $et_transaction);
/**
* Get all votes for a et_transaction.
*
* @param EtTransactionInterface $et_transaction
*
* @return mixed
*
* @deprecated in Drupal 8.x-1.0.
* Use \Drupal\et_transaction\EtTransactionVoteStorageInterface::getVotes() instead.
*
* @see \Drupal\et_transaction\EtTransactionVoteStorageInterface::getVotes()
*/
public function getVotes(EtTransactionInterface $et_transaction);
/**
* Delete a user's votes for a et_transaction.
*
* @param EtTransactionInterface $et_transaction
*
* @return mixed
*
* @deprecated in Drupal 8.x-1.0.
* Use \Drupal\et_transaction\EtTransactionVoteStorageInterface::deleteVotes() instead.
*
* @see \Drupal\et_transaction\EtTransactionVoteStorageInterface::deleteVotes()
*/
public function deleteVotes(EtTransactionInterface $et_transaction);
/**
* Get a user's votes for a et_transaction.
*
* @param EtTransactionInterface $et_transaction
*
* @return mixed
*
* @deprecated in Drupal 8.x-1.0.
* Use \Drupal\et_transaction\EtTransactionVoteStorageInterface::getUserVote() instead.
*
* @see \Drupal\et_transaction\EtTransactionVoteStorageInterface::getUserVote()
*/
public function getUserVote(EtTransactionInterface $et_transaction);
/**
* Get the most recent et_transaction posted on the site.
*
......
......@@ -15,12 +15,12 @@ class EtTransactionViewData extends EntityViewsData {
public function getViewsData() {
$data = parent::getViewsData();
$data['et_transaction_field_data']['votes'] = array(
'title' => 'Total votes',
'help' => 'Displays the total number of votes.',
$data['et_transaction_field_data']['transactions'] = array(
'title' => 'Total transactions',
'help' => 'Displays the total number of transactions.',
'real field' => 'id',
'field' => array(
'id' => 'et_transaction_totalvotes',
'id' => 'et_transaction_totaltransactions',
),
);
......
......@@ -22,7 +22,7 @@ class EtTransactionDeleteForm extends ContentEntityConfirmFormBase {
* {@inheritdoc}
*/
public function getDescription() {
return t('All associated votes will be deleted too. This action cannot be undone.');
return t('All associated transactions will be deleted too. This action cannot be undone.');
}
/**
......
......@@ -59,7 +59,7 @@ class EtTransactionViewForm extends FormBase implements BaseFormIdInterface {
if ($this->showResults($this->et_transaction, $form_state)) {
// Check if the user already voted. The form is still being built but
// Check if the user already. The form is still being built but
// the Vote button won't be added so the submit callbacks will not be
// called. Directly check for the request method and use the raw user
// input.
......@@ -68,8 +68,8 @@ class EtTransactionViewForm extends FormBase implements BaseFormIdInterface {
if (isset($input['op']) && $input['op'] == $this->t('Vote')) {
// If this happened, then the form submission was likely a cached page.
// Force a session for this user so he can see the results.
$this->messenger()->addError($this->t('Your vote for this et_transaction has already been submitted.'));
$_SESSION['expense_tracker_vote'][$this->et_transaction->id()] = FALSE;
$this->messenger()->addError($this->t('Your transaction for this et_transaction has already been submitted.'));
$_SESSION['expense_tracker'][$this->et_transaction->id()] = FALSE;
}
}
......@@ -91,7 +91,7 @@ class EtTransactionViewForm extends FormBase implements BaseFormIdInterface {
'#options' => $options,
);
}
$form['#theme'] = 'expense_tracker_vote';
$form['#theme'] = 'expense_tracker';
$form['#entity'] = $this->et_transaction;
$form['#action'] = $this->et_transaction->toUrl()->setOption('query', \Drupal::destination()->getAsArray())->toString();
// Set a flag to hide results which will be removed if we want to view
......@@ -145,22 +145,14 @@ class EtTransactionViewForm extends FormBase implements BaseFormIdInterface {
switch (TRUE) {
// The "View results" button, when available, has been clicked.
case $form_state->get('show_results'):
return TRUE;
return TRUE;
// The et_transaction is closed.
case ($et_transaction->isClosed()):
return TRUE;
// Anonymous user is trying to view a et_transaction they aren't allowed to vote in.
case ($account->isAnonymous() && !$et_transaction->getAnonymousVoteAllow()):
return TRUE;
// The user has already voted.
case ($et_transaction->hasUserVoted()):
return TRUE;
return TRUE;
default:
return FALSE;
return FALSE;
}
}
......@@ -177,38 +169,27 @@ class EtTransactionViewForm extends FormBase implements BaseFormIdInterface {
];
if ($this->showResults($et_transaction, $form_state)) {
// Allow user to cancel their vote.
// Allow user to cancel their transaction.
if ($this->isCancelAllowed($et_transaction)) {
$actions['#type'] = 'actions';
$actions['cancel']['#type'] = 'submit';
$actions['cancel']['#button_type'] = 'primary';
$actions['cancel']['#value'] = t('Cancel vote');
$actions['cancel']['#value'] = t('Cancel transaction');
$actions['cancel']['#submit'] = array('::cancel');
$actions['cancel']['#ajax'] = $ajax;
$actions['cancel']['#weight'] = '0';
}
if (!$et_transaction->hasUserVoted() && $et_transaction->isOpen() && $et_transaction->getAnonymousVoteAllow()) {
$actions['#type'] = 'actions';
$actions['back']['#type'] = 'submit';
$actions['back']['#button_type'] = 'primary';
$actions['back']['#value'] = t('View et_transaction');
$actions['back']['#submit'] = array('::back');
$actions['back']['#ajax'] = $ajax;
$actions['back']['#weight'] = '0';
}
}
else {
$actions['#type'] = 'actions';
$actions['vote']['#type'] = 'submit';
$actions['vote']['#button_type'] = 'primary';
$actions['vote']['#value'] = t('Vote');
$actions['vote']['#validate'] = array('::validateVote');
$actions['vote']['#submit'] = array('::save');
$actions['vote']['#ajax'] = $ajax;
$actions['vote']['#weight'] = '0';
$actions['transaction']['#type'] = 'submit';
$actions['transaction']['#button_type'] = 'primary';
$actions['transaction']['#submit'] = array('::save');
$actions['transaction']['#ajax'] = $ajax;
$actions['transaction']['#weight'] = '0';
// View results before voting.
if ($et_transaction->result_vote_allow->value || $this->currentUser()->hasPermission('view et_transaction results')) {
if ($et_transaction->result_allow->value || $this->currentUser()->hasPermission('view et_transaction results')) {
$actions['result']['#type'] = 'submit';
$actions['result']['#button_type'] = 'primary';
$actions['result']['#value'] = t('View results');
......@@ -232,84 +213,22 @@ class EtTransactionViewForm extends FormBase implements BaseFormIdInterface {
*
* @return array $output
*/
function showEtTransactionResults(EtTransactionInterface $et_transaction, $view_mode = 'default', $block = FALSE) {
// Ensure that a page that shows et_transaction results can not be cached.
\Drupal::service('page_cache_kill_switch')->trigger();
$total_votes = 0;
foreach ($et_transaction->getVotes() as $vote) {
$total_votes += $vote;
}
$options = $et_transaction->getOptions();
$et_transaction_results = array();
foreach ($et_transaction->getVotes() as $pid => $vote) {
$percentage = round($vote * 100 / max($total_votes, 1));
$display_votes = (!$block) ? ' (' . \Drupal::translation()
->formatPlural($vote, '1 vote', '@count votes') . ')' : '';
$et_transaction_results[] = array(
'#theme' => 'et_transaction_meter',
'#choice' => $options[$pid],
'#display_value' => t('@percentage%', array('@percentage' => $percentage)) . $display_votes,
'#min' => 0,
'#max' => $total_votes,
'#value' => $vote,
'#percentage' => $percentage,
'#attributes' => array('class' => array('bar')),
'#et_transaction' => $et_transaction,
);
}
/** @var \Drupal\et_transaction\EtTransactionVoteStorageInterface $vote_storage */
$vote_storage = \Drupal::service('expense_tracker_vote.storage');
$user_vote = $vote_storage->getUserVote($et_transaction);
$output = array(
'#theme' => 'et_transaction_results',
'#raw_title' => $et_transaction->label(),
'#results' => $et_transaction_results,
'#votes' => $total_votes,
'#block' => $block,
'#pid' => $et_transaction->id(),
'#et_transaction' => $et_transaction,
'#view_mode' => $view_mode,
'#vote' => isset($user_vote['chid']) ? $user_vote['chid'] : NULL,
);
return $output;
}
function showEtTransactionResults(EtTransactionInterface $et_transaction, $view_mode = 'default', $block = FALSE) {}
/**
* Cancel vote submit function.
* Cancel transaction submit function.
*
* @param array $form
* The previous form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
public function cancel(array $form, FormStateInterface $form_state) {
/** @var \Drupal\et_transaction\EtTransactionVoteStorageInterface $vote_storage */
$vote_storage = \Drupal::service('expense_tracker_vote.storage');
$vote_storage->cancelVote($this->et_transaction, $this->currentUser());
\Drupal::logger('et_transaction')->notice('%user\'s vote in EtTransaction #%et_transaction deleted.', array(
'%user' => $this->currentUser()->id(),
'%et_transaction' => $this->et_transaction->id(),
));
$this->messenger()->addMessage($this->t('Your vote was cancelled.'));
// In case of an ajax submission, trigger a form rebuild so that we can
// return an updated form through the ajax callback.
if ($this->getRequest()->query->get('ajax_form')) {
$form_state->setRebuild(TRUE);
}
}
public function cancel(array $form, FormStateInterface $form_state) {}
/**
* View vote results submit function.
* View transaction results submit function.
*
* @param array $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
......@@ -331,55 +250,20 @@ class EtTransactionViewForm extends FormBase implements BaseFormIdInterface {
}
/**
* Save a user's vote submit function.
* Save a user's transaction submit function.
*
* @param array $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
*/
public function save(array $form, FormStateInterface $form_state) {
$options = array();
$options['chid'] = $form_state->getValue('choice');
$options['uid'] = $this->currentUser()->id();
$options['pid'] = $form_state->getValue('et_transaction')->id();
$options['hostname'] = \Drupal::request()->getClientIp();
$options['timestamp'] = \Drupal::time()->getRequestTime();
// Save vote.
/** @var \Drupal\et_transaction\EtTransactionVoteStorage $vote_storage */
$vote_storage = \Drupal::service('expense_tracker_vote.storage');
$vote_storage->saveVote($options);
$this->messenger()->addMessage($this->t('Your vote has been recorded.'));
if ($this->currentUser()->isAnonymous()) {
// The vote is recorded so the user gets the result view instead of the
// voting form when viewing the et_transaction. Saving a value in $_SESSION has the
// convenient side effect of preventing the user from hitting the page
// cache. When anonymous voting is allowed, the page cache should only
// contain the voting form, not the results.
$_SESSION['expense_tracker_vote'][$form_state->getValue('et_transaction')->id()] = $form_state->getValue('choice');
}
// In case of an ajax submission, trigger a form rebuild so that we can
// return an updated form through the ajax callback.
if ($this->getRequest()->query->get('ajax_form')) {
$form_state->setRebuild(TRUE);
}
// No explicit redirect, so that we stay on the current page, which might
// be the et_transaction form or another page that is displaying this et_transaction, for
// example as a block.
}
public function save(array $form, FormStateInterface $form_state) {}
/**
* Validates the vote action.
* Validates the transaction action.
*
* @param array $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
*/
public function validateVote(array &$form, FormStateInterface $form_state) {
if (!$form_state->hasValue('choice')) {
$form_state->setErrorByName('choice', $this->t('Your vote could not be recorded because you did not select any of the choices.'));
}
}
public function validateVote(array &$form, FormStateInterface $form_state) {}
/**
* Checks if the current user is allowed to cancel on the given et_transaction.
......@@ -389,17 +273,6 @@ class EtTransactionViewForm extends FormBase implements BaseFormIdInterface {
* @return bool
* TRUE if the user can cancel.
*/
protected function isCancelAllowed(EtTransactionInterface $et_transaction) {
// Allow access if the user has voted.
return $et_transaction->hasUserVoted()
// And the et_transaction allows to cancel votes.
&& $et_transaction->getCancelVoteAllow()
// And the user has the cancel own vote permission.
&& $this->currentUser()->hasPermission('cancel own vote')
// And the user is authenticated or his session contains the voted flag.
&& (\Drupal::currentUser()->isAuthenticated() || !empty($_SESSION['expense_tracker_vote'][$et_transaction->id()]))
// And et_transaction is open.
&& $et_transaction->isOpen();
}
protected function isCancelAllowed(EtTransactionInterface $et_transaction) {}
}
......@@ -6,12 +6,10 @@
* Variables available:
* - title: The title of the et_transaction.
* - results: The results of the et_transaction.
* - votes: The total results in the et_transaction.
* - links: Links in the et_transaction.
* - pid: The pid of the et_transaction
* - cancel_form: A form to cancel the user's vote, if allowed.
* - cancel_form: A form to cancel the user's transaction, if allowed.
* - raw_links: The raw array of links.
* - vote: The choice number of the current user's vote.
*
* @see template_preprocess_et_transaction_results()
*
......@@ -28,6 +26,6 @@
{{ results }}
</dl>
<div class="total">
{% trans %}Total votes: {{ votes }}{% endtrans %}
{% trans %}Total transactions: {{ transactions }}{% endtrans %}
</div>
</div>
{#
/**
*/
#}
{{ form.messages }}
<div class="et_transaction">
<div class="vote-form">
{% if show_title %}
<h3 class="et_transaction-title">{{ title }}</h3>
{% endif %}
{{ form.choice }}
{{ form.actions }}
</div>
{{ form|without('actions', 'choice', 'messages', 'title') }}
</div>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment