Commit Graph

332 Commits

Author SHA1 Message Date
taitus
b1cb6f8372 Exclude open-ended questions from managing physical votes
Also make the :yes_no factory trait create a votation_type_unique
by default, since yes/no questions should always be unique.
2025-10-16 14:31:16 +02:00
taitus
f3050a1aa5 Manage correctly results and stats for open-ended questions
Note that we are not including Poll::PartialResults for open-ended
questions resutls. The reason is that we do not contemplate the
possibility of there being open questions in booths. Manually
counting and introducing the votes in the system is not feasible.
2025-10-16 14:26:30 +02:00
taitus
83b206f0b7 Enable voting for open-ended questions in public section 2025-10-16 11:09:36 +02:00
taitus
62e1c13e7e Use option instead of answer text to find multiple answers 2025-10-16 11:09:36 +02:00
taitus
b3f8ba819b Adapt 'show' view for open questions without options
- Prevent creating options for open questions
- Skip rendering the options table when none exist
2025-10-15 15:52:14 +02:00
taitus
69eaf66b93 Remove redundant max_votes validation from Poll::Answer
Since commit 8deb1964b, the `WebVote` class enforces the maximum vote
validation, making the `max_votes` method in `Poll::Answer` redundant.
2025-10-15 15:52:14 +02:00
taitus
4e57e311dc Add support for open-ended questions in admin section
Introduce a new "open" votation type for poll questions in the admin
interface. This type allows open answers provided by the user.
2025-10-15 15:52:12 +02:00
taitus
3a9f761476 Count total_votes by option_id instead of answer title
This makes Option#total_votes independent of translations
and resilient to title changes.
2025-09-26 15:25:20 +02:00
taitus
a29eeaf2e2 Add option_id to partial results and unique index
Similar to what we did in PR "Avoid duplicate records in poll answers" 5539,
specifically in commit 503369166, we want to stop relying on the plain text
"answer" and start using "option_id" to avoid issues with counts across
translations and to add consistency to the poll_partial_results table.

Note that we also moved the `possible_answers` method from Poll::Question to
Poll::Question::Option, since the list of valid answers really comes from the
options of a question and not from the question itself. Tests were updated
to validate answers against the translations of the assigned option.

Additionally, we renamed lambda parameters in validations to improve clarity.
2025-09-26 15:05:34 +02:00
Javi Martín
6da53b5716 Add unique index to poll voters table
Note that Rails 7.1 changes `find_or_create_by!` so it calls
`create_or_find_by!` when no record is found, meaning we'll rarely get
`RecordNotUnique` exceptions when using this method during a race
condition.

Adding this index means we need to remove the uniqueness validation.
According to the `create_or_find_by` documentation [1]:

> Columns with unique database constraints should not have uniqueness
> validations defined, otherwise create will fail due to validation
> errors and find_by will never be called.

We're adding a test that checks what happens when using
`create_or_find_by!`.

Note that we're creating voters combining `create_with` with
`find_or_create_by!`. Using `find_or_create_by!(...)` with all
attributes (including non-key ones like `origin`) fails when a voter
already exists with different values, e.g. an existing `origin: "web"`
and an incoming `"booth"`. In this situation the existing record is not
matched and the unique index raises an exception.

`create_with(...).find_or_create_by!(user: ..., poll: ...)` searches by
the unique key only and applies the extra attributes only on creation.
Existing voters are returned unchanged, which is the intended behavior.

For the `take_votes_from` method, we're handling a (highly unlikely, but
theoretically possible) scenario where a user votes at the same time as
taking voters from another user. For that, we're doing something similar
to what `create_or_find_by!` does: we're updating the `user_id` column
inside a new transaction (using a new transactions avoids a
`PG::InFailedSqlTransaction` exception when there are duplicate
records), and deleting the existing voter when we get a
`RecordNotUnique` exception.

On `Poll::WebVote` we're simply raising an exception when there's
already a user who's voted via booth, because the `Poll::WebVote#update`
method should never be called in this case.

We still need to use `with_lock` in `Poll::WebVote`, but not due to
duplicate voters (`find_or_create_by!` method will now handle the unique
record scenario, even in the case of simultaneous transactions), but
because we use a uniqueness validation in `Poll::Answer`; this
validation would cause an error in simultaneous transactions.

[1] https://api.rubyonrails.org/v7.1/classes/ActiveRecord/Relation.html#method-i-create_or_find_by
2025-08-28 14:42:30 +02:00
Javi Martín
8deb1964bd Show errors when submitting too many answers
This could be the case when JavaScript is disabled.

Note that, in `Poll/WebVote` we're calling `given_answers` inside a
transaction. Putting this code before the transaction resulted in a test
failing sometimes, probably because of a bug that might be possible to
reproduce by doing simultaneous requests.
2025-08-14 13:06:43 +02:00
Javi Martín
7ea4f63b07 Allow blank votes in polls via web
With the old interface, there wasn't a clear way to send a blank ballot.
But now that we've got a form, there's an easy way: clicking on "Vote"
while leaving the form blank.
2025-08-14 13:06:43 +02:00
Javi Martín
a7e1b42b6c Use checkboxes and radio buttons on poll forms
Our original interface to vote in a poll had a few issues:

* Since there was no button to send the form, it wasn't clear that
  selecting an option would automatically store it in the database.
* The interface was almost identical for single-choice questions and
  multiple-choice questions, which made it hard to know which type of
  question we were answering.
* Adding other type of questions, like open answers, was hard since we
  would have to add a different submit button for each answer.

So we're now using radio buttons for single-choice questions and
checkboxes for multiple-choice questions, which are the native controls
designed for these purposes, and a button to send the whole form.

Since we don't have a database table for poll ballots like we have for
budget ballots, we're adding a new `Poll::WebVote` model to manage poll
ballots. We're using WebVote instead of Ballot or Vote because they
could be mistaken with other vote classes.

Note that browsers don't allow removing answers with radio buttons, so
once somebody has voted in a single-choice question, they can't remove
the vote unless they manually edit their HTML. This is the same behavior
we had before commit 7df0e9a96.

As mentioned in c2010f975, we're now adding the `ChangeByZero` rubocop
rule, since we've removed the test that used `and change`.
2025-08-14 13:06:37 +02:00
Javi Martín
b81bbeaa96 Remove unused method Poll::Question.answerable_by
This method isn't used since commit 909114bcf.
2025-08-12 12:45:12 +02:00
dependabot[bot]
123c97771a Bump rubocop from 1.71.2 to 1.75.8
Bumps [rubocop](https://github.com/rubocop/rubocop) from 1.71.2 to 1.75.8.
- [Release notes](https://github.com/rubocop/rubocop/releases)
- [Changelog](https://github.com/rubocop/rubocop/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rubocop/rubocop/compare/v1.71.2...v1.75.8)

---
updated-dependencies:
- dependency-name: rubocop
  dependency-version: 1.75.8
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Notes:

This commit also includes several style and lint fixes required after
updating RuboCop:

- Removed redundant parentheses now detected by improved
  'Style/RedundantParentheses' (1.72 and 1.75.3).
- Replaced ternary expressions with logical OR when the ternary was
  returning 'true', as flagged by 'Style/RedundantCondition' (1.73).
- Adjusted block variables to resolve new 'Lint/ShadowingOuterLocalVariable'
  offenses (1.75), helping avoid future conflicts during upgrades with
  'rails app:updates'

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-16 16:07:32 +02:00
Javi Martín
2239b8fdca Remove obsolete questions index in the admin area
We removed the link to this page in commit 83e8d6035 because poll
questions don't really make sense without a poll.

However, this page also contained information about successful
proposals, which might be interesting so administrators don't have to
navigate to the public area in order to find and create questions based
on successful proposals.

So we're keeping the part about successful proposals and linking it from
the proposals part of the admin area.

Note we're using translation keys like `successful_proposals_tab`, which
don't make sense anymore, for the successful proposals. We're doing so
because we've already got translations for these keys and, if we renamed
them, we'd lose the existing translations and our translators would have
to add them again.

Also note we're changing one poll question test a little bit so we
create the question from a successful proposal using the new page. There
are other tests checking how to create a question from the
admin/proposals#show action and other tests checking what happens when
accessing a successful proposal in the admin section, so we don't lose
any test coverage by changing an existing test instead of adding a new
one.

Finally, note that we've removing the `search` method in poll question
because we no longer use it. This currently makes the
`author_visible_name` database column useless; we aren't removing it
right now because we don't want to risk a possible data loss in a patch
release (we're about to release version 2.3.1), but we might remove it
in the future.
2025-03-26 16:42:04 +01:00
taitus
3d4f78a424 Add an apply Rails/EnumSyntax rubocop rule
This rule was added in rubocop-rails 2.26.0. Applying it allows
us to anticipate the deprecation of the current enum syntax
using keyword arguments, which is set to be removed in Rails
8.0, as mentioned in the rule's own documentation:

https://docs.rubocop.org/rubocop-rails/cops_rails.html#railsenumsyntax
2024-10-10 09:55:48 +02:00
Javi Martín
38ad65605e Use excluding instead of where.not(id:
This method was added in Rails 7.0 and makes the code slihgtly more
readable.

The downside is that it generates two queries instead of one, so it
might generate some confusion when debugging SQL queries. Its impact on
performance is probably negligible.
2024-07-22 18:35:35 +02:00
Javi Martín
5033691666 Avoid duplicate records in poll answers
Until now, we've stored the text of the answer somebody replied to. The
idea was to handle the scenarios where the user voters for an option but
then that option is deleted and restored, or the texts of the options
are accidentally edited and so the option "Yes" is now "Now" and vice
versa.

However, since commit 3a6e99cb8, options can no longer be edited once
the poll starts, so there's no risk of the option changing once somebody
has voted.

This means we can now store the ID of the option that has been voted.
That'll also help us deal with a bug introduced int 673ec075e, since
answers in different locales are not counted as the same answer. Note we
aren't dealing with this bug right now.

We're still keeping (and storing) the answer as well. There are two
reasons for that.

First, we might add an "open answer" type of questions in the future and
use this column for it.

Second, we've still got logic depending on the answer, and we need to be
careful when changing it because there are existing installations where
the answer is present but the option_id is not.

Note that we're using `dependent: nullify`. The reasoning is that, since
we're storing both the option_id and the answer text, we can still use
the answer text when removing the option. In practice, this won't matter
much, though, since we've got a validation rule that makes it impossible
to destroy options once the poll has started.

Also note we're still allowing duplicate records when the option is nil.
We need to do that until we've removed every duplicate record in the
database.
2024-06-26 20:20:24 +02:00
Javi Martín
9a8bfac5bd Prevent creation of duplicate poll voters
Note that, when taking votes from an erased user, since poll answers
don't belong to poll voters, we were not migrating them in the
`take_votes_from` method (and we aren't migrating them now either).
2024-06-26 15:41:44 +02:00
Javi Martín
5f12db899f Remove no longer needed call to Poll::Answer#touch
This call was added in commit 81f65f1ac, and the test for its need was
added in commit cb1542874. However, both the test and the helper method
relying on the `touch` call were removed in commit f90d0d9c4.
2024-06-26 15:41:44 +02:00
Javi Martín
fb9156f9b8 Use with_lock instead of lock!
That way the record is only locked while necessary.
2024-06-26 15:41:44 +02:00
Javi Martín
a54d424aed Add missing validation rule to poll answers
We were checking we didn't have more votes than allowed in the case of
questions with multiple answers, but we weren't checking it in the case
of questions with a single answer. This made it possible to create more
than one answer to the same question. This could happen because the
method `find_or_initialize_user_answer` might initialize two answers in
different threads, due to a race condition.
2024-06-26 15:41:44 +02:00
Javi Martín
6aafc107ae Remove Questionable concern
Since we were only using it in one place, it made the code harder to
follow.

We'll extract it again if we ever find a way to reuse it.
2024-06-26 15:41:44 +02:00
Javi Martín
0c650c423d Fix exception creating an answer without an author
We were getting `undefined method `lock!' for nil:NilClass` when the
question allowed multiple answers.
2024-06-26 15:41:44 +02:00
Javi Martín
38b38d1fcc Rename Poll::Question::Answer to Poll::Question::Option
Having a class named `Poll::Question::Answer` and another class named
`Poll::Answer` was so confusing that no developer working on the project
has ever been capable of remembering which is which for more than a few
seconds.

Furthermore, we're planning to add open answers to polls, and we might
add a reference from the `poll_answers` table to the
`poll_question_answers` table to property differentiate between open
answers and closed answers. Having yet another thing named answer would
be more than what our brains can handle (we know it because we did this
once in a prototype).

So we're renaming `Poll::Question::Answer` to `Poll::Question::Option`.
Hopefully that'll make it easier to remember. The name is also (more or
less) consistent with the `Legislation::QuestionOption` class, which is
similar.

We aren't changing the table or columns names for now in order to avoid
possible issues when upgrading (old code running with the new database
tables/columns after running the migrations but before deployment has
finished, for instance). We might do it in the future.

I've tried not to change the internationalization keys either so
existing translations would still be valid. However, since we have to
change the keys in `activerecord.yml` so methods like
`human_attribute_name` keep working, I'm also changing them in places
where similar keys were used (like `poll_question_answer` or
`poll/question/answer`).

Note that it isn't clear whether we should use `option` or
`question_option` in some cases. In order to keep things simple, we're
using `option` where we were using `answer` and `question_option` where
we were using `question_answer`.

Also note we're adding tests for the admin menu component, since at
first I forgot to change the `answers` reference there and all tests
passed.
2024-06-13 19:13:01 +02:00
Javi Martín
bfee1b0ecb Simplify query to get possible answers
We added the code indicating the table in commit 673ec075e because back
then we had a `title` column in both the `poll_question_answers` table
and the `poll_question_answer_translations` table.

Since that's no longer the case since commit 7a7877656, we can simplify
the code.
2024-06-12 15:16:14 +02:00
Javi Martín
236b58ab01 Remove duplication in code to validate video URL
We were using the same code, and the same regular expressions, in two
places. To do so, we were including a helper inside a model, which is
something we don't usually do.
2024-06-06 17:35:27 +02:00
Javi Martín
a4461a1a56 Expire the stats cache once per day
When we first started caching the stats, generating them was a process
that took several minutes, so we never expired the cache.

However, there have been cases where we run into issues where the stats
shown on the screen were outdated. That's why we introduced a task to
manually expire the cache.

But now, generating the stats only takes a few seconds, so we can
automatically expire them every day, remove all the logic needed to
manually expire them, and get rid of most of the issues related to the
cache being outdated.

We're expiring them every day because it's the same day we were doing in
public stats (which we removed in commit 631b48f58), only we're using
`expires_at:` to set the expiration time, in order to simplify the code.

Note that, in the test, we're using `travel_to(time)` so the test passes
even when it starts an instant before midnight. We aren't using
`:with_frozen_time` because, in similar cases (although not in this
case, but I'm not sure whether that's intentional), `travel_to` shows
this error:

> Calling `travel_to` with a block, when we have previously already made
> a call to `travel_to`, can lead to confusing time stubbing.
2024-05-17 20:11:16 +02:00
Javi Martín
653848fc4e Extract method to get the stats key in stats
This way we remove a bit of duplication and it'll be easier to change
the `stats_cache` method.
2024-05-17 16:08:08 +02:00
Javi Martín
1d85a63e7c Calculate age stats based on the participation date
We were calculating the age stats based on the age of the users who
participated... at the moment where we were calculating the stats. That
means that, if 20 years ago, 1000 people who were 16 years old
participated, they would be shown as having 36 years in the stats.

Instead, we want to show the stats at the time when the process took
place, so we're implementing a `participation_date` method.

Note that, for polls, we could actually use the `age` column in the
`poll_voters` table. However, doing so would be harder, would only work
for polls but not for budgets, and it wouldn't be statistically very
relevant, since the stats are shown by age groups, and only a small
percentage of people would change their age group (and only to the
nearest one) between the time they participate and the time the process
ends.

We might use the `poll_voters` table in the future, though, since we
have a similar issue with geozones and genders, and using the
information in `poll_voters` would solve it as well (only for polls,
though).

Also note that we're using the `ends_at` dates because some people but
be too young to vote when a process starts but old enough to vote when
the process ends.

Finally, note that we might need to change the way we calculate the
participation date for a budget, since some budgets might not enabled
every phase. Not sure how stats work in that scenario (even before these
changes).
2024-05-13 15:42:37 +02:00
Javi Martín
d0fae3377e Add and apply Rails/WhereMissing rubocop rule
So now we know where to use the `where.missing` method which was
introduced in Rails 6.1.

Note this rule didn't detect all cases where the new method can be used.
2024-03-18 16:05:07 +01:00
Javi Martín
f87d4b589d Add and apply Naming/BlockForwarding rubocop rule
This syntax has been added in Ruby 3.1.

Not using a variable name might not be very descriptive, but it's just
as descriptive as using "block" as a variable name. Using just `&` we
get the same amount of information than using `&block`: that we're
passing a block.

We're still using `&action` in `around_action` methods because here we
aren't using a generic name for the variable, so (at least for now) we
aren't running this cop on controllers using `around_action`.
2023-09-12 15:17:28 +02:00
Javi Martín
a1439d0790 Apply Layout/LineLength rubocop rule
Note we're excluding a few files:

* Configuration files that weren't generated by us
* Migration files that weren't generated by us
* The Gemfile, since it includes an important comment that must be on
  the same line as the gem declaration
* The Budget::Stats class, since the heading statistics are a mess and
  having shorter lines would require a lot of refactoring
2023-08-30 14:46:35 +02:00
Javi Martín
30767fa44e Use Ruby 1.9 hash notation in assignment scopes 2023-08-30 14:46:35 +02:00
Javi Martín
5b6de96241 Add and apply MultilineMethodCallIndentation rule 2023-08-18 14:56:16 +02:00
Javi Martín
629e208e9d Add and apply ArgumentAlignment rubocop rule
We're choosing the default `with_first_argument` style because it's the
one we use the most.
2023-08-18 14:56:16 +02:00
Javi Martín
8b13daad95 Add and apply rules for multi-line hashes
For the HashAlignment rule, we're using the default `key` style (keys
are aligned and values aren't) instead of the `table` style (both keys
and values are aligned) because, even if we used both in the
application, we used the `key` style a lot more. Furthermore, the
`table` style looks strange in places where there are both very long and
very short keys and sometimes we weren't even consistent with the
`table` style, aligning some keys without aligning other keys.

Ideally we could align hashes to "either key or table", so developers
can decide whether keeping the symmetry of the code is worth it in a
case-per-case basis, but Rubocop doesn't allow this option.
2023-08-18 14:56:16 +02:00
Javi Martín
09c63e354c Add and apply Layout/DotPosition rule
Since IRB has improved its support for multiline, the main argument
towars using a trailing dot no longer affects most people.

It still affects me, though, since I use Pry :), but I agree
leading dots are more readable, so I'm enabling the rule anyway.
2023-08-18 14:56:16 +02:00
Javi Martín
b911284b86 Update Style/RedundantFreeze rule for Ruby 3.0
In Ruby 3.0, Regexp and Range literals are frozen objects, and so we
don't need to freeze them.
2023-04-13 16:41:15 +02:00
Javi Martín
4355138f57 Simplify locking current user when voting
Back in commit 36e452437, we wrote:

> The `reload` method added to max_votes validation is needed because
> the author gets here with some changes because of the around_action
> `switch_locale`, which adds some changes to the current user record
> and therefore, the lock method raises an exception when trying to lock
> it requiring us to save or discard those record changes.

This happened when `current_user` didn't have a locale stored in the
database and the `current_locale` method returned the default locale.
And the test "Poll Votation Type Multiple answers" would indeed fail if
we removed the `reload` method. However, we can remove the need to
reload the record by avoiding the mentioned changes on the current user
record.

So we're changing the `User#locale` method so it doesn't modify the user
record.
2022-11-29 13:59:09 +01:00
decabeza
36e452437e Add questions with mutiple answers to polls public interface
The `reload` method added to max_votes validation is needed because the
author gets here with some changes because of the around_action
`switch_locale`, which adds some changes to the current user record and
therefore, the lock method raises an exception when trying to lock it
requiring us to save or discard those record changes.
2022-10-18 11:04:40 +02:00
Senén Rodero Rodríguez
3da4112d94 Remove Poll::Voter record when there is no more user answers
Now we can remove answers we should provide a way of removing voting.
2022-10-18 11:04:40 +02:00
decabeza
48d7ec75d0 Do not allow to create more answers than the maximum defined
In case we receive consecutive requests we are locking the poll author record
until the first request transaction ends, so the author answers count during
subsequent requests validations is up to date.
2022-10-18 10:39:00 +02:00
decabeza
4fba76f64f Do not show answers without additional information 2022-10-18 10:38:59 +02:00
decabeza
d1c1aa6691 Add VotationType model 2022-10-18 10:38:59 +02:00
Senén Rodero Rodríguez
64676be246 Remove token column from poll_voters table
As it is no longer used as originally pretended [1][2].

[1] Check consul/consul pull request 1994
[2] Check consul/consul pull request 3539
2022-09-22 10:34:07 +02:00
Javi Martín
12460c2000 Merge pull request #4789 from consul/rails_6.0_compatibility
Add Rails 6.0 compatibility
2022-03-23 14:14:11 +01:00
Javi Martín
f6c4d70d78 Merge pull request #4775 from jorgebg/call_verify_ballots_after_create
Add offline ballot sheet votes to the total vote count
2022-03-22 19:17:36 +01:00
taitus
ecde8c6439 Add lambda to the validations that use model constants
In this way when we need modify the constants model value in the
model/custom folder, adding lambda it will be possible load the new
values.
2022-03-22 15:52:36 +01:00