Merge remote-tracking branch 'docs/master' into import_docs

This commit is contained in:
Javi Martín
2024-05-10 18:41:30 +02:00
193 changed files with 7545 additions and 0 deletions

5
docs/.gitbook.yaml Normal file
View File

@@ -0,0 +1,5 @@
root: ./
structure:
readme: README.md
summary: SUMMARY.md

2
docs/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
.DS_Store
_book/**/*

1
docs/.mdlrc Normal file
View File

@@ -0,0 +1 @@
rules "MD001", "MD002", "MD003", "MD004", "MD005", "MD006", "MD007", "MD008", "MD009", "MD010", "MD011", "MD012", "MD014", "MD015", "MD016", "MD017", "MD018", "MD019", "MD020", "MD021", "MD022", "MD023", "MD025", "MD026", "MD027", "MD028", "MD030", "MD031", "MD032", "MD033", "MD034", "MD035", "MD036", "MD037", "MD038", "MD039", "MD040", "MD041"

5
docs/README.md Normal file
View File

@@ -0,0 +1,5 @@
# Consul Democracy documentation
:warning: The technical documentation has been moved to the [Consul Democracy documentation site](https://docs.consuldemocracy.org/). This repository is now read-only, since now the changes to the documentation are handled by editing the texts on that site.
![CONSUL DEMOCRACY logo](img/consul_logo.png)

106
docs/SUMMARY.md Normal file
View File

@@ -0,0 +1,106 @@
# Summary
## ENGLISH Documentation
* [Getting started](en/getting_started/getting_started.md)
* [Fork Consul Democracy](en/getting_started/create.md)
* [Configure your fork](en/getting_started/configuration.md)
* [Keep your fork updated](en/getting_started/update.md)
* [Communication](en/getting_started/communication.md)
* [Installation](en/installation/introduction.md)
* [Local installation](en/installation/local_installation.md)
* [Prerequisites](en/installation/prerequisites.md)
* [Ubuntu Linux](en/installation/ubuntu.md)
* [Debian Linux](en/installation/debian.md)
* [MacOS](en/installation/macos.md)
* [Windows](en/installation/windows.md)
* [Vagrant](en/installation/vagrant.md)
* [Production and Staging servers](en/installation/servers.md)
* [Installer](en/installation/installer.md)
* [Create a deploy user](en/installation/create_deploy_user.md)
* [Generating SSH Key](en/installation/generating_ssh_key.md)
* [Manual installation (not recommended)](en/installation/manual_installation_production.md)
* [Digital Ocean](en/installation/digital_ocean.md)
* [Heroku](en/installation/deploying-on-heroku.md)
* [Docker](en/installation/docker.md)
* [Mail Server Configuration](en/installation/mail_server_configuration.md)
* [Basic configuration](en/installation/basic_configuration.md)
* [Consul Democracy Documentation and guides](en/installation/documentation_and_guides.md)
* [Customization](en/customization/customization.md)
* [Introduction](en/customization/introduction.md)
* [Translations and Texts](en/customization/translations.md)
* [Images](en/customization/images.md)
* [Views and Styles](en/customization/views_and_styles.md)
* [Javascript](en/customization/javascript.md)
* [Models](en/customization/models.md)
* [Components](en/customization/components.md)
* [Gems](en/customization/gems.md)
* [Overwriting Application](en/customization/overwriting.md)
* [Technical Features](en/features/features.md)
* [OAuth](en/features/oauth.md)
* [GraphQL](en/features/graphql.md)
* [Recommendations](en/features/recommendations.md)
* [Configure Census Connection](en/features/census_configuration.md)
* [Local Census](en/features/local_census.md)
* [Multitenancy](en/features/multitenancy.md)
* [Open Source project](en/open_source/open_source.md)
* [Code of conduct](en/open_source/code_of_conduct.md)
* [Contributing](en/open_source/contributing.md)
* [License](es/open_source/license.md)
## SPANISH Documentation
* [Introducción](es/README.md)
* [Primeros pasos](es/getting_started/getting_started.md)
* [Crea tu fork](es/getting_started/create.md)
* [Configura tu fork](es/getting_started/configuration.md)
* [Manten tu fork actualizado](es/getting_started/update.md)
* [Comunicación](es/getting_started/communication.md)
* [Instalación](es/installation/introduction.md)
* [Instalación local](es/installation/local_installation.md)
* [Prerrequisitos](es/installation/prerequisites.md)
* [Ubuntu Linux](es/installation/ubuntu.md)
* [Debian Linux](es/installation/debian.md)
* [MacOS](es/installation/macos.md)
* [Windows](es/installation/windows.md)
* [Vagrant](es/installation/vagrant.md)
* [Servidores de producción y pruebas](es/installation/servers.md)
* [Instalador](es/installation/installer.md)
* [Crear usuario](es/installation/create_deploy_user.md)
* [Generación de claves SSH](es/installation/generating_ssh_key.md)
* [Instalación manual (no recomendada)](es/installation/manual_installation_production.md)
* [Digital Ocean](es/installation/digital_ocean.md)
* [Heroku](es/installation/deploying-on-heroku.md)
* [Docker](es/installation/docker.md)
* [Configuración del servidor de correo](es/installation/mail_server_configuration.md)
* [Configuración básica](es/installation/basic_configuration.md)
* [Documentación y guías sobre Consul Democracy](es/installation/documentation_and_guides.md)
* [Personalización](es/customization/customization.md)
* [Introducción](es/customization/introduction.md)
* [Traducciones y Textos](es/customization/translations.md)
* [Imágenes](es/customization/images.md)
* [Vistas y Estilos](es/customization/views_and_styles.md)
* [Javascript](es/customization/javascript.md)
* [Modelos](es/customization/models.md)
* [Componentes](es/customization/components.md)
* [Gemas](es/customization/gems.md)
* [Adaptar la aplicación](es/customization/overwriting.md)
* [Funcionalidades Técnicas](es/features/features.md)
* [OAuth](es/features/oauth.md)
* [GraphQL](es/features/graphql.md)
* [Recomendaciones](es/features/recommendations.md)
* [Configurar conexión con el Censo](es/features/census_configuration.md)
* [Local Census](es/features/local_census.md)
* [Multitenancy](es/features/multitenancy.md)
* [Proyecto Open Source](es/open_source/open_source.md)
* [Código de conducta](es/open_source/code_of_conduct.md)
* [Contribuciones](es/open_source/contributing.md)
* [Licencia](es/open_source/license.md)

85
docs/en/README.md Normal file
View File

@@ -0,0 +1,85 @@
![CONSUL DEMOCRACY logo](../img/consul_logo.png)
# CONSUL DEMOCRACY
Citizen Participation and Open Government Application
![Build status](https://github.com/consuldemocracy/consuldemocracy/workflows/tests/badge.svg)
[![Code Climate](https://codeclimate.com/github/consuldemocracy/consuldemocracy/badges/gpa.svg)](https://codeclimate.com/github/consuldemocracy/consuldemocracy)
[![Coverage Status](https://coveralls.io/repos/github/consuldemocracy/consuldemocracy/badge.svg)](https://coveralls.io/github/consuldemocracy/consuldemocracy?branch=master)
[![Crowdin](https://d322cqt584bo4o.cloudfront.net/consul/localized.svg)](https://translate.consuldemocracy.org/)
[![License: AGPL v3](https://img.shields.io/badge/License-AGPL%20v3-blue.svg)](http://www.gnu.org/licenses/agpl-3.0)
[![Accessibility conformance](https://img.shields.io/badge/accessibility-WAI:AA-green.svg)](https://www.w3.org/WAI/eval/Overview)
[![A11y issues checked with Rocket Validator](https://rocketvalidator.com/badges/checked_with_rocket_validator.svg?url=https://rocketvalidator.com)](https://rocketvalidator.com/opensource)
[![Join the chat at https://gitter.im/consul/consul](https://badges.gitter.im/consul/consul.svg)](https://gitter.im/consul/consul?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Help wanted](https://img.shields.io/badge/help-wanted-brightgreen.svg?style=flat-square)](https://github.com/consuldemocracy/consuldemocracy/issues?q=is%3Aopen+label%3A"help+wanted")
[![Knapsack Pro Parallel CI builds for RSpec tests](https://img.shields.io/badge/Knapsack%20Pro-Parallel%20/%20RSpec%20tests-%230074ff)](https://knapsackpro.com/dashboard/organizations/176/projects/202/test_suites/318/builds?utm_campaign=organization-id-176&utm_content=test-suite-id-318&utm_medium=readme&utm_source=knapsack-pro-badge&utm_term=project-id-202)
This is the opensource code repository of the eParticipation website CONSUL DEMOCRACY, originally developed for the Madrid City government eParticipation website
## Documentation
Check the ongoing documentation at [https://docs.consuldemocracy.org](https://docs.consuldemocracy.org) to learn more about how to start your own CONSUL DEMOCRACY fork, install it, customize it and learn to use it from an administrator/maintainer perspective.
## CONSUL DEMOCRACY Project main website
You can access the main website of the project at [http://consuldemocracy.org](http://consuldemocracy.org) where you can find documentation about the use of the platform, videos, and links to the community space.
## Configuration for development and test environments
**NOTE**: For more detailed instructions check the [docs](https://docs.consuldemocracy.org)
Prerequisites: install git, Ruby 3.0.6, CMake, pkg-config, shared-mime-info, Node.js and PostgreSQL (>=9.5).
```bash
git clone https://github.com/consuldemocracy/consuldemocracy.git
cd consuldemocracy
bundle install
cp config/database.yml.example config/database.yml
cp config/secrets.yml.example config/secrets.yml
bin/rake db:create
bin/rake db:migrate
bin/rake db:dev_seed
RAILS_ENV=test rake db:setup
```
Run the app locally:
```bash
bin/rails s
```
Run the tests with:
```bash
bin/rspec
```
You can use the default admin user from the seeds file:
**user:** admin@consul.dev
**pass:** 12345678
But for some actions like voting, you will need a verified user, the seeds file also includes one:
**user:** verified@consul.dev
**pass:** 12345678
## Configuration for production environments
See [installer](https://github.com/consuldemocracy/installer)
## Current state
Development started on [2015 July 15th](https://github.com/consuldemocracy/consuldemocracy/commit/8db36308379accd44b5de4f680a54c41a0cc6fc6). Code was deployed to production on 2015 september 7th to [decide.madrid.es](https://decide.madrid.es). Since then new features are added often. You can take a look at the current features at the [project's website](http://consuldemocracy.org/) and future features at the [Roadmap](https://github.com/orgs/consuldemocracy/projects/1) and [open issues list](https://github.com/consuldemocracy/consuldemocracy/issues).
## License
Code published under AFFERO GPL v3 (see [LICENSE-AGPLv3.txt](open_source/license.md))
## Contributions
See [CONTRIBUTING.md](https://github.com/consuldemocracy/consuldemocracy/blob/master/CONTRIBUTING.md)

5
docs/en/book.json Normal file
View File

@@ -0,0 +1,5 @@
{
"gitbook": ">= 3.0.0",
"title": "Consul Democracy Documentation",
"description": "Citizen Participation and Open Government Application"
}

View File

@@ -0,0 +1,25 @@
# Components
For components, customization can be used to change both the logic (included in a `.rb` file) and the view (included in a `.erb` file). If you only want to customize the logic for, let's say, the `Admin::TableActionsComponent`, create a file named `app/components/custom/admin/table_actions_component.rb` with the following content:
```ruby
require_dependency Rails.root.join("app", "components", "admin", "table_actions_component").to_s
class Admin::TableActionsComponent
# Your custom logic here
end
```
If, on the other hand, you also want to customize the view, you need a small modification. Instead of the previous code, use:
```ruby
class Admin::TableActionsComponent < ApplicationComponent; end
require_dependency Rails.root.join("app", "components", "admin", "table_actions_component").to_s
class Admin::TableActionsComponent
# Your custom logic here
end
```
This will make the component use the view in `app/components/custom/admin/table_actions_component.html.erb`. You can create this file and customize it to your needs.

View File

@@ -0,0 +1,11 @@
# Customization
* [Introduction](introduction.md)
* [Translations and Texts](translations.md)
* [Images](images.md)
* [Views and Styles](views_and_styles.md)
* [Javascript](javascript.md)
* [Models](models.md)
* [Components](components.md)
* [Gems](gems.md)
* [Overwriting Application](overwriting.md)

View File

@@ -0,0 +1,9 @@
# Gemfile
To add new gems (libraries) you can edit the `Gemfile_custom` file. For example to add [rails-footnotes](https://github.com/josevalim/rails-footnotes) gem you would just add:
```ruby
gem 'rails-footnotes', '~> 4.0'
```
And then just do the classic Ruby on Rails flow `bundle install` and following any gem specific install steps from it's own documentation.

View File

@@ -0,0 +1,17 @@
# Images
If you want to overwrite any image, firstly you need to find out the filename, and by default it will be located under `app/assets/images`. For example if you want to change the header logo (`app/assets/images/logo_header.png`) you must create another file with the exact same file name under `app/assets/images/custom` folder. The images and icons that you will most likely want to change are:
* apple-touch-icon-200.png
* icon_home.png
* logo_email.png
* logo_header.png
* map.jpg
* social_media_icon.png
* social_media_icon_twitter.png
## City Map
You'll find the city map at [`/app/assets/images/map.jpg`](https://github.com/consuldemocracy/consuldemocracy/blob/master/app/assets/images/map.jpg), just replace it with an image of your cities districts ([example](https://github.com/consuldemocracy/consuldemocracy/blob/master/app/assets/images/map.jpg)).
Afterwards we recommend you to use an online tool like <http://imagemap-generator.dariodomi.de/> or <https://www.image-map.net/> to generate the html coordinates to be able to generate a [image-map](https://www.w3schools.com/tags/tag_map.asp) for each of the districts. Those coordinates should be introduced on the respective Geozones at the admin geozones panel (`/admin/geozones`).

View File

@@ -0,0 +1,145 @@
# Customization
You can modify your own Consul Democracy to have your custom visual style, but first you'll have to [create your own fork from](../getting_started/create.md).
We've created an specific structure where you can overwrite and customize the application in a way that will let you keep updating it from Consul Democracy's main repository, without having conflicts on code merging or risking loosing your customization changes. We try to make Consul Democracy as vanilla as possible to help other developers onboard the codebase.
## Special Folders and Files
In order to customize your Consul Democracy fork, you'll make use of some `custom` folders on the following paths:
* `config/locales/custom/`
* `app/assets/images/custom/`
* `app/views/custom/`
* `app/controllers/custom/`
* `app/models/custom/`
Also these are the files where you can apply some customization:
* `app/assets/stylesheets/custom.css`
* `app/assets/stylesheets/_custom_settings.css`
* `app/assets/javascripts/custom.js`
* `Gemfile_custom`
* `config/application.custom.rb`
## Remote translations on demand by the user
The aim of this service is to be able to offer all the dynamic contents of the application (proposals, debates, budget investments and comments) in different languages without the need for a user or administrator to have created each one of their translations.
When a user visits a page with a language where there is untranslated content, they will have a button to request the translation of all the content. This content will be sent to an automatic translator (in this case [Microsoft TranslatorText](https://azure.microsoft.com/en-us/products/cognitive-services/translator/)) and as soon as the response is obtained, all these translations will be available to any user.
### Getting started
In order to use this functionality, the following steps are necessary:
1. Have an api key to connect to the translation service. For this we need an [Azure account](https://azure.microsoft.com/en-us/)
1. Once you are logged into the Azure portal, subscribe to the Translator in Cognitive Service.
1. Once you have subscribed to the Translator Text service, you will have access to 2 api keys in the section **Resource Management > Keys and Endpoint** that will be necessary for the configuration of the translation service in your application.
### Configuration
To activate the translation service in your application you must complete the following steps:
#### Add api key in the application
In the previous section we have commented that once subscribed to the translation service we have 2 api keys. To configure the service correctly in our application we must add one of the two api keys in the file `secrets.yml` in section `apis:` with the key `microsoft_api_key` as we can see in the following image:
![Add api key to secrets](../../img/translations/remote_translations/add-api-key-to-secrets.png)
#### Activate module
Once we have the new key in the `secrets.yml` we can now proceed to activate the module. To activate the functionality you must follow 2 steps:
1. Execute the following command `bin/rake settings:create_remote_translations_setting RAILS_ENV=production`
1. Accessing through the administration panel of your application to the section **Configuración > Funcionalidades** and activate module **Traducciones Remotas** as shown below:
![Active remote translations](../../img/translations/remote_translations/active-remote-translations-en.png)
### Use Cases
Once we have the api key in our `secrets.yml` and the activated module, users will already be able to use the functionality.
We attach some screenshots of how the application interacts with our users:
* When a user visits a page in a language without translated content, an informative text will appear at the top of the page and a button to request the translation. (**Note:** *If user visit page with a language not supported by the translation service, no text or translation button will be displayed. See section: Available languages for remote translation*)
![Display text and button](../../img/translations/remote_translations/display-text-and-button-en.png)
* Once the user click the `Translate page` button, the translations are enqueued and the page is reloaded with a notice (*Informing that the translations have been requested correctly*) and an informative text in the header (*explaining when you will be able to see these translations*).
![Display notice and text after enqueued translations](../../img/translations/remote_translations/display-notice-and-text-after-enqueued-en.png)
* If an user visit a page that does not have translations but have already been requested by another user. The application will not show you the translate button, but an informative text in the header (*explaining when you will be able to see these translations*).
![Display text explaining that translations are pending](../../img/translations/remote_translations/display-text-translations-pending-en.png)
* The translation request, response processing and data saving are delegated to `Delayed Jobs` and as soon as they are processed, the user will be able to read them after page refresh.
![Display translated content](../../img/translations/remote_translations/display-translated-content-en.png)
### Available languages for remote translation
Currently these are all the [available languages](https://api.cognitive.microsofttranslator.com/languages?api-version=3.0) in the translation service:
```yml
["af", "am", "ar", "as", "az", "ba", "bg", "bn", "bo", "bs", "ca", "cs", "cy", "da", "de", "dv", "el", "en", "es", "et", "eu", "fa", "fi", "fil", "fj", "fo", "fr", "fr-CA", "ga", "gl", "gu", "ha", "he", "hi", "hr", "hsb", "ht", "hu", "hy", "id", "ig", "ikt", "is", "it", "iu", "iu-Latn", "ja", "ka", "kk", "km", "kmr", "kn", "ko", "ku", "ky", "ln", "lo", "lt", "lug", "lv", "lzh", "mg", "mi", "mk", "ml", "mn-Cyrl", "mn-Mong", "mr", "ms", "mt", "mww", "my", "nb", "ne", "nl", "nso", "nya", "or", "otq", "pa", "pl", "prs", "ps", "pt", "pt-PT", "ro", "ru", "run", "rw", "sk", "sl", "sm", "sn", "so", "sq", "sr-Cyrl", "sr-Latn", "st", "sv", "sw", "ta", "te", "th", "ti", "tk", "tlh-Latn", "tlh-Piqd", "tn", "to", "tr", "tt", "ty", "ug", "uk", "ur", "uz", "vi", "xh", "yo", "yua", "yue", "zh-Hans", "zh-Hant", "zu"]
```
Of all the languages that Consul Democracy currently has defined (`available_locales`) in `config/application.rb` the only one that is not listed above and therefore no translation service is offered is Valencian `["val"]`.
### Pricing
The translation service used has the most competitive [pricing](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/translator/).
The price for each 1 Million characters translated is $10 and there is no fixed cost per month.
Although technical measures have been taken to prevent misuse of this service, we recommend the creation of Alerts offered by Azure so that an Administrator can be notified in the event of detecting unusual use of the service. This service has a cost of $0.10 per month.
To create an Alert in Azure we must follow the following steps:
1. Sign in to the **Azure Portal**.
1. Access the **Translator** service created earlier.
1. Go to **Monitoring > Alerts** in the side menu:
1. Go to **Create alert rule**.
1. In **Select a signal** select `Text Characters Translated`.
1. Once selected we must define the logic of the Alert to suit our needs. Ex: Fill "Operator" field with "Greater than" option, fill "Aggregation type" field with "Total" option and fill "Threshold value" field with the number of characters we consider should be translated before being notified. In this section you can also set the time period and frequency of evaluation.
1. In order to be notified we have to create an **Action Group** and associate it with this Alert we're creating. To do this, access the button **Create** and fill out the form. As you can see there are different types of actions, we must select **Email/SMS/Push/Voice** and configure the option that we consider convenient according to our needs.
1. Once this group of actions has been created, it is directly associated with the rule we are creating.
1. Finally, all you have to do is add a name and click on the **Review + create**
### Add a new translation service
If you want to integrate more translation services for any reason (new translation service appears, you want to change to include languages that are currently not supported, etc.) the code is ready to be added.
This is made possible by the `RemoteTranslations::Caller` class which is an intermediate layer between untranslated content management and the currently used Microsoft Translation Client.
A good solution for adding another translation service would be to replace the call to the `MicrosoftTranslateClient` in the `translations` method of `RemoteTranslations::Caller` with the new service implemented.
If you want to coexist with both should only be managed in which case we want to use one or the other, either through specific conditions in the code or through a management in the Settings of the application.
```ruby
class RemoteTranslationsCaller
...
def translations
@translations ||= RemoteTranslations::Microsoft::Client.new.call(fields_values, locale)
# Add new RemoteTranslations Client
# @translations = RemoteTranslations::NewTranslateClient::Client.new.call(fields_values, locale_to)
end
...
end
```
## Translation interface
The aim of this feature is to allow users the introduction of dynamic contents in many languages at the same time. From the administration panel you can activate or deactivate it. If you deactivate this feature (default configuration) users will be able to enter one single translation.
### Enable module
To activate this feature you must follow 2 steps:
1. Execute the following command `bin/rake settings:create_translation_interface_setting RAILS_ENV=production` (This is only required for already existing intallations, for new Consul Democracy installations this step is not needed).
2. Accessing as administrator user to the administration panel of your Consul Democracy application to the section **Configuration > Features** and activating the feature called **Translation Interface** as you can see next:
![Active interface translations](../../img/translations/interface_translations/active-interface-translations-en.png)
### Use Cases
* When the translation interface is active:
As you can see in the image below translation interface has two selectors, the firt one "Select language" is to switch between enabled languages and the second one "Add language" is to add new languages to the form. Translatable fields appears with a blue background to facilitate users to distinguish between translatable and not translatable fields. Additionally interface provides a link `Remove language` to delete the current language shown at "Select language". If a user accidentally removes a translation he can recover it re-adding it to the form.
This feature is visible during creation and edition of translatable resources.
![Translations inteface enabled](../../img/translations/interface_translations/translations-interface-enabled-en.png)
* When the translation interface is disabled:
When this feature is deactivated users will see standard forms without translation interface and without translation highlight.
![Translations inteface enabled](../../img/translations/interface_translations/translations-interface-disabled-en.png)

View File

@@ -0,0 +1,15 @@
# Javascript
If you want to add some custom Javascript code, `app/assets/javascripts/custom.js` is the file to do it. For example to create a new alert just add:
```js
$(function(){
alert('foobar');
});
```
If you work with Coffeescript code you can check it with [coffeelint](http://www.coffeelint.org/) (install with `npm install -g coffeelint`) :
```bash
coffeelint .
```

View File

@@ -0,0 +1,75 @@
# Models
If you need to create new models or customize existent ones, you can do it so at the `app/models/custom` folder. Keep in mind that for old models you'll need to firstly require the dependency.
For example for Madrid's City Hall fork its required to check the zip code's format (it always starts with 280 followed by 2 digits). That check is at `app/models/custom/verification/residence.rb`:
```ruby
require_dependency Rails.root.join('app', 'models', 'verification', 'residence').to_s
class Verification::Residence
validate :postal_code_in_madrid
validate :residence_in_madrid
def postal_code_in_madrid
errors.add(:postal_code, I18n.t('verification.residence.new.error_not_allowed_postal_code')) unless valid_postal_code?
end
def residence_in_madrid
return if errors.any?
unless residency_valid?
errors.add(:residence_in_madrid, false)
store_failed_attempt
Lock.increase_tries(user)
end
end
private
def valid_postal_code?
postal_code =~ /^280/
end
end
```
Do not forget to cover your changes with a test at the `spec/models/custom` folder. Following the example we could create `spec/models/custom/residence_spec.rb`:
```ruby
require 'rails_helper'
describe Verification::Residence do
let(:residence) { build(:verification_residence, document_number: "12345678Z") }
describe "verification" do
describe "postal code" do
it "should be valid with postal codes starting with 280" do
residence.postal_code = "28012"
residence.valid?
expect(residence.errors[:postal_code].size).to eq(0)
residence.postal_code = "28023"
residence.valid?
expect(residence.errors[:postal_code].size).to eq(0)
end
it "should not be valid with postal codes not starting with 280" do
residence.postal_code = "12345"
residence.valid?
expect(residence.errors[:postal_code].size).to eq(1)
residence.postal_code = "13280"
residence.valid?
expect(residence.errors[:postal_code].size).to eq(1)
expect(residence.errors[:postal_code]).to include("In order to be verified, you must be registered in the municipality of Madrid.")
end
end
end
end
```

View File

@@ -0,0 +1,14 @@
# Overwriting application.rb
If you need to extend or modify the `config/application.rb` just do it at the `config/application_custom.rb` file. For example if you want to change de default language to English, just add:
```ruby
module Consul
class Application < Rails::Application
config.i18n.default_locale = :en
config.i18n.available_locales = [:en, :es]
end
end
```
Remember that in order to see this changes live you'll need to restart the server.

View File

@@ -0,0 +1,38 @@
# Translations and Texts
## Translations
Currently, Consul Democracy is totally or partially translated to multiple languages. You can find the translations at the [Crowdin project](https://translate.consuldemocracy.org/).
Please [join the translators](https://crwd.in/consul) to help us complete existing ones, or contact us through [Consul Democracy's gitter](https://gitter.im/consul/consul) to become a proofreader and validate translators' contributions.
If your language isn't already present in the Crowdin project, please [open an issue](https://github.com/consuldemocracy/consuldemocracy/issues/new?title=New language&body=Hello I would like to have my language INSERT YOUR LANGUAGE NAME added to Consul Democracy) and we'll set it up in a breeze.
If you want to check existing translations of the user-facing texts you can find them organized in YML files under `config/locales/` folder. Take a look at the official Ruby on Rails [internationalization guide](http://guides.rubyonrails.org/i18n.html) to better understand the translations system.
## Custom Texts
Since Consul Democracy is always evolving with new features, and in order to make your fork easier to be updated, we strongly recommend translation files not to be modified, but instead "overwritten" with custom translation files in case a text needs to be customized for you.
So if you just want to change some of the existing texts, you can just drop your changes at the `config/locales/custom/` folder. We strongly recommend to include only those texts that you want to change instead of a whole copy of the original file. For example if you want to customize the text "Ayuntamiento de Madrid, 2016" that appears on every page's footer, firstly you want to locate where it's used (`app/views/layouts/_footer.html.erb`) and look at the locale identifier inside the code:
```ruby
<%= t("layouts.footer.copyright", year: Time.current.year) %>
```
Then find the file where this identifier will be located (in that case `config/locales/es/general.yml`) following this structure (we're only displaying the relevant parts in the following snippet):
```yml
es:
layouts:
footer:
copyright: Ayuntamiento de Madrid, %{year}
```
In order to customize it, you should create a new file `config/locales/custom/es/general.yml` with just that content, and change "Ayuntamiento de Madrid" with our organization name. We strongly recommend to make copies from `config/locales/` and modify or delete the lines as needed to keep the indentation structure and avoid issues.
## Maintaining your Custom Texts & Languages
Consul Democracy has the [i18n-tasks](https://github.com/glebm/i18n-tasks) gem, it's an awesome helping tool to manage i18n translations. Just check `i18n-tasks health` for a nice report.
If you have a custom language different than English, you should add it to the [i18n-tasks.yml config file both `base_locale` and `locales`](https://github.com/consuldemocracy/consuldemocracy/blob/master/config/i18n-tasks.yml#L4-L7) variables so your language files will be checked as well.

View File

@@ -0,0 +1,33 @@
# Views and Styles
## Views (HTML)
If you want to change any page HTML you can just find the correct file under the `app/views` folder and put a copy at `app/views/custom` keeping as well any sub-folder structure, and then apply your customizations. For example if you want to customize `app/views/pages/conditions.html` you'll have to make a copy at `app/views/custom/pages/conditions.html.erb` (note the `pages` subdirectory).
## CSS Styles with SASS
In order to make changes to any CSS selector (custom style sheets), you can add them directly at `app/assets/stylesheets/custom.scss`. For example to change the header color (`.top-links`) you can just add:
```css
.top-links {
background: red;
}
```
If you want to change any [foundation](http://foundation.zurb.com/) variable, you can do it at the `app/assets/stylesheets/_custom_settings.scss` file. For example to change the main application color just add:
```css
$brand: #446336;
```
We use [SASS, with SCSS syntax](http://sass-lang.com/guide) as CSS preprocessor.
Also you can check your scss files syntax with
```bash
scss-lint
```
## Accessibility
To maintain accessibility level, if you add new colors use a [Color contrast checker](http://webaim.org/resources/contrastchecker/) (WCAG AA is mandatory, WCAG AAA is recommended).

View File

@@ -0,0 +1,155 @@
# Configure connection to the Census
The objective of this service is to be able to configure the connection with the Town Hall Census through the Administration panel without having to modify the application code.
It should be noted that to properly configure this connection will require a technical profile that knows the WebService of your City Council.
Currently the application was designed to send only the **document number** and **document type**. With this new feature is enabled the possibility of sending if necessary the fields **date of birth** and **postal code**.
## Activate feature
In the section **Configuration > Global Configuration** a new tab **Remote Census Configuration** has been added.
If we have the feature deactivated we will see an informative text that will indicate us how to activate it:
![Feature disabled](../../img/remote_census/feature-disabled-en.png)
To activate the feature you must follow the instructions of the previous image:
1. Access through the administration panel of your application to the section **Settings > Features** and activate the module **Configure connection to the remote census (SOAP)** as shown below:
![Feature enabled](../../img/remote_census/feature-enabled-en.png)
## Configuration
Once the feature is activated, we can access the section **Settings > Global Settings** and click on the tab **Remote Census Configuration**.
In this screen you will be able to fill in all the necessary information to be able to configure the connection with the Census of each Town Hall.
The information to be filled in is divided into three sections:
1. **General Information**
- **Endpoint**: Host name where the census service is available (wsdl).
![General information - Endpoint](../../img/remote_census/general-information-endpoint-en.png)
1. **Request Data**
In this section we will fill in all the necessary fields to be able to make a request to verify a user through the Census of the City council.
![Request Data](../../img/remote_census/request-data-en.png)
To help you understand how to fill in each of the fields, we will rely on a supposed WebService that receives a method called `:get_habita_datos` with the following structure:
```
{
request: {
codigo_institucion: 12, # Static Value
codigo_portal: 5, # Static Value
codigo_usuario: 10, # Static Value
documento: 12345678Z, # Dynamic value related to Document Number
tipo_documento: 1, # Dynamic value related to Document Type
nivel: 3 # Static Value
}
}
```
Required fields for the request:
- **Request method name**: Request method name accepted by the City Census WebService.
Example:
![Request Data - Method name](../../img/remote_census/request-data-method-name-en.png)
- **Request Structure**: Structure of the request received by the WebService of the Census of the City Council. The "static" values of this request should be reported. The "dynamic" values related to Document Type, Document Number, Date of Birth and Postal Code should be filled with null value.
Example:
![Request Data - Structure](../../img/remote_census/request-data-structure-en.png)
![Request Data - Structure](../../img/remote_census/request-data-structure-info-en.png)
- **Path for document type**: Path in the request structure that sends the Document Type.
*NOTE: DO NOT FILL IN if the WebService does not require the Document Type to verify a user.*
Example:
![Request Data - Path document type](../../img/remote_census/request-data-path-document-type-en.png)
- **Path for document number**: Path in the request structure that sends the Document Number.
*NOTE: DO NOT FILL IN if the WebService does not require the Document Number to verify a user.*
Example:
![Request Data - Path document number](../../img/remote_census/request-data-path-document-number-en.png)
- **Path for date of birth**: Path in the request structure that sends the Date of Birth.
*NOTE: DO NOT FILL IN if the WebService does not require the Date of Birth to verify a user.*
In the case of *Example* we will fill it in blank, since it is not necessary to send the date of birth to verify a user.
Example:
![Request Data - Path date of birth](../../img/remote_census/request-data-path-date-of-birth-en.png)
- **Path for Postal Code**: Path in the request structure that sends the Postal Code.
*NOTE: DO NOT FILL IN if the WebService does not require the Postal Code to verify a user.*
En el caso del *Example* lo dejaríamos en blanco, ya que no se necesita enviar el código postal para verificar a un usuario.
Example:
![Request Data - Path postal code](../../img/remote_census/request-data-path-postal-code-en.png)
1. **Response data**
In this section we will configure all the necessary fields to be able to receive the answer of the WebService and to verify a user in the application.
![Response Data](../../img/remote_census/response-data-en.png)
As in the previous section we will define an example answer, to help you understand how to fill in each of the fields in this section.
```
{
get_habita_datos_response: {
get_habita_datos_return: {
datos_habitante: {
item: {
fecha_nacimiento_string: "31-12-1980",
identificador_documento: "12345678Z",
descripcion_sexo: "Varón",
nombre: "José",
apellido1: "García"
}
},
datos_vivienda: {
item: {
codigo_postal: "28013",
codigo_distrito: "01"
}
}
}
}
}
```
Required fields to parse the response:
- **Path for Date of Birth**: In what path of the response is the user's Date of Birth?.
Example:
![Response Data - Path date of birth](../../img/remote_census/response-data-path-date-of-birth-en.png)
- **Path for Postal Code**: In what path of the response is the user's Postal Code?.
Example:
![Response Data - Path postal code](../../img/remote_census/response-data-path-postal-code-en.png)
- **Path for District**: In what path of the response is the user's District?.
Example:
![Response Data - Path district](../../img/remote_census/response-data-path-district-en.png)
- **Path for Gender**: In what path of response is the user's Gender?.
Example:
![Response Data - Path Gender](../../img/remote_census/response-data-path-gender-en.png)
- **Path for Name**: In what path of the response is the user's Name?.
Example:
![Response Data - Path Name](../../img/remote_census/response-data-path-name-en.png)
- **Path for the Last Name**: In what path of the response is the user's Last Name?.
Example:
![Response Data - Path Last Name](../../img/remote_census/response-data-path-last-name-en.png)
- **Condition for detecting a valid response**: What response path has to come informed to be considered a valid response and user verified.
Example:
![Response Data - Path valid response](../../img/remote_census/response-data-path-valid-response-en.png)
Once the general data, the necessary fields of the request and "all" fields to validate the response have been filled in correctly, the application will be able to verify any user through the defined WebService.

View File

@@ -0,0 +1,7 @@
# Technical Features
* [OAuth](oauth.md)
* [GraphQL](graphql.md)
* [Recommendations](recommendations.md)
* [Configure Census Connection](census_configuration.md)
* [Local Census](local_census.md)

View File

@@ -0,0 +1,122 @@
# Globalize
Follow this steps to add [Globalize](https://github.com/globalize/globalize) to a model (the gem [`globalize_accessors`](https://github.com/globalize/globalize-accessors) is also used).
## 1. Define the attributes to be translated
We should add in the model the attributes that are going to be translated. To do that, use the `translates` option followed by the attribute names.
We also need to add the option `globalize_accessors` to include all the locales we want to support. This gem generates all the methods needed by the application (`title_en`, `title_es`, etc.). If you want to include **all** the translated fields in **all** the defined languages in your application, just call `globalize_accessors` without any option (as the [documentation](https://github.com/globalize/globalize-accessors#example) says).
```
# Supposing a model Post with title and text attributes
class Post < ActiveRecord::Base
translates :title, :text
globalize_accessors locales: [:en, :es, :fr, :nl, :val, :pt_br]
end
```
## 2. Create the migration to generate the translations table
We must create a migration to generate the table where the translations are going to be stored. The table must have a column for each attribute we want to translate. To migrate the stored data in the original table, add the option `:migrate_data => true` in the migration.
```
class AddTranslatePost < ActiveRecord::Migration
def self.up
Post.create_translation_table!({
title: :string,
text: :text
}, {
:migrate_data => true
})
end
def self.down
Post.drop_translation_table! :migrate_data => true
end
end
```
## 3. Add the `Translatable` module
Add the `Translatable` module in the controller that will handle the translations.
```
class PostController < Admin::BaseController
include Translatable
...
```
Make sure that the controller has the functions `resource_model` and `resource`, which return the name of the model and the object we want to save the translations for, respectively.
```
...
def resource_model
Post
end
def resource
@post = Post.find(params[:id])
end
...
```
## 4. Add the translation params to the permitted params
Add as permitted params those dedicated to translations. To do that, the module `Translatable` owns a function called `translation_params(params)`, which will receive the object param and will return those keys with a value. It takes into account the languages defined for that model.
```
# Following the example, we pass the params[:post] because is the one that has the information.
attributes = [:title, :description]
params.require(:post).permit(*attributes, translation_params(params[:post]))
```
## 5. Add the fields in the form
Add the fields to the form for creating and editing the translations. Remember that, to do this, there is a function in the helper that encapsules the `Globalize.with_locale` logic in a block called `globalize(locale) do`.
The fields that are going to be translated should be named `<attribute_name>_<locale>`, for example `title_en`, so when that information arrives to the server, it can classify the parameters.
Remember that, to avoid errors when using locales like `pt-BR`, `es-ES`, etc. (those whose region is specified by a '-'), we must use a function called `neutral_locale(locale)`, defined in the `GlobalizeHelper`. This function converts this type of locales in lower case and underscored, so `pt-BR` will transform in `pt_br`. This format is compatible with `globalize_accessors`, whereas the official is not because the method names like `title_pt-BR` are not allowed. When using this function, the method will call `title_pt_br` and it will not generate conflicts when comparing `pt-BR` with `pt_br`.
## 6. Add hidden parameters to delete translations
Add the hidden parameters to the form to delete translations:
```
<%= hidden_field_tag "delete_translations[#{locale}]", 0 %>
```
We must add the link "Remove translation" to delete translations, which should have:
- an id with this format: `delete-<neutral locale>`, where "neutral locale" is the result of the function `neutral_locale(locale)`.
- an attribute `data-locale` with the value of `neutral_locale(locale)`.
- the class `delete-language`.
```
<%= link_to t("admin.milestones.form.remove_language"), "#",
id: "delete-#{neutral_locale(locale)}",
class: 'delete-language',
data: { locale: neutral_locale(locale) } %>
```
The CSS styles and the rest of the classes will depend on the designed UI for that translations (if the link should show or hide, for example).
## 7. Add the translations for the new model to the `dev_seed`
So that they will be generated when the DB is restored. For example, to create a post whose description is translated.
```
section "Creating post with translations" do
post = Post.new(title: title)
I18n.available_locales.map do |locale|
neutral_locale = locale.to_s.downcase.underscore.to_sym
Globalize.with_locale(neutral_locale) do
post.description = "Description for locale #{locale}"
post.save
end
end
end
```

431
docs/en/features/graphql.md Normal file
View File

@@ -0,0 +1,431 @@
# API Documentation
* [Characteristics](#characteristics)
* [GraphQL](#graphql)
* [Making API requests](#making-api-requests)
* [Supported clients](#supported-clients)
* [GraphiQL](#graphiql)
* [Postman](#postman)
* [HTTP libraries](#http-libraries)
* [Available information](#available-information)
* [Examples of queries](#examples-of-queries)
* [Request a single record from a collection](#request-a-single-record-from-a-collection)
* [Request a complete collection](#request-a-complete-collection)
* [Pagination](#pagination)
* [Accessing several resources in a single request](#accessing-several-resources-in-a-single-request)
* [Security limitations](#security-limitations)
* [Example of too deep query](#example-of-too-deep-query)
* [Example of too complex query](#example-of-too-complex-query)
* [Code examples](#code-examples)
## Characteristics
* Read-only API
* Public access, no authentication needed
* Uses GraphQL technology:
* Maximum page size (and the default) is 25 records
* Maximum query depth is set at 8 levels
* A maximum of two collections can be requested within the same query
* Support for GET requests (query must be inside the *query string*) and POST requests (query must be within the *body*, encoded as `application/json` or `application/graphql`)
## GraphQL
The Consul Democracy API uses GraphQL [http://graphql.org](http://graphql.org), the [Ruby implementation](http://graphql-ruby.org/), to be specific. If you're not familiar with this kind of APIs, it's recommended to make some research about GraphQL before.
One of the characteristics that differentiates a REST API from a GraphQL one is that with the last one it's possible for the client to build its own *custom queries*, so the server will only return information in which we're interested.
GraphQL queries are written following a standard which resembles to JSON, for example:
```
{
proposal(id: 1) {
id,
title,
public_author {
id,
username
}
}
}
```
Responses are formatted in JSON:
```json
{
"data": {
"proposal": {
"id": 1,
"title": "Hacer las calles del centro de Madrid peatonales",
"public_author": {
"id": 2,
"username": "electrocronopio"
}
}
}
}
```
## Making API requests
Following [the official recommendations](http://graphql.org/learn/serving-over-http/), the Consul Democracy API supports the following kind of requests:
* GET requests, with the query inside the *query string*.
* POST requests
* With the query inside the *body*, with `Content-Type: application/json`
* With the query inside the *body*, with `Content-Type: application/graphql`
### Supported clients
Because it's an API that works through HTTP, any tool capable of making this kind of requests is capable of querying the API.
This section presents a few examples about how to make requests using:
* GraphiQL
* Chrome extensions like Postman
* Any HTTP library
#### GraphiQL
[GraphiQL](https://github.com/graphql/graphiql) is a browser interface for making queries against a GraphQL API. It's also an additional source of documentation. It's deployed in the route `/graphiql` and it's the best way to get familiar with GraphQL-based APIs.
![GraphiQL](../../img/graphql/graphiql.png)
It has three main panels:
* The left panel is used to write the query.
* The central panel shows the result of the request.
* The right panel (occultable) shows a documentation autogenerated from the models and fields exposed in the API.
#### Postman
Example of `GET` request, with the query as part of the *query string*:
![Postman GET](../../img/graphql/graphql-postman-get.png)
Example of `POST` request, with the query as part of the *body* and encoded as `application/json`:
![Postman POST](../../img/graphql/graphql-postman-post-headers.png)
The query must be located inside a valid JSON document, as the value of the `"query"` key:
![Postman POST](../../img/graphql/graphql-postman-post-body.png)
#### HTTP libraries
Sure you can use any HTTP library available for most programming languages.
**IMPORTANT**: Due to security protocols from the Madrid City Council servers, it's necessary to include a *User Agent* header from a web browser so the request is not rejected. For example:
`User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36`
## Available information
The [config/api.yml](../../config/api.yml) file contains a complete list of all the models (and their attributes) which are currently being exposed in the API.
The models are the following:
| Model | Description |
| ----------------------- | ----------------------------- |
| `User` | Users |
| `Debate` | Debates |
| `Proposal` | Proposals |
| `Comment` | Comments on debates, proposals and other comments |
| `Geozone` | Geozones (districts) |
| `ProposalNotification` | Notifications related to proposals |
| `Tag` | Tags on debates and proposals |
| `Vote` | Information related to votes |
## Examples of queries
### Request a single record from a collection
```
{
proposal(id: 2) {
id,
title,
comments_count
}
}
```
Response:
```json
{
"data": {
"proposal": {
"id": 2,
"title": "Crear una zona cercada para perros en Las Tablas",
"comments_count": 10
}
}
}
```
### Request a complete collection
```
{
proposals {
edges {
node {
title
}
}
}
}
```
Response:
```json
{
"data": {
"proposals": {
"edges": [
{
"node": {
"title": "ELIMINACION DE ZONA APARCAMIENTO EXCLUSIVO FUNCIONARIOS EN MADRID"
}
},
{
"node": {
"title": "iluminación de zonas deportivas"
}
}
]
}
}
}
```
#### Pagination
The maximum (and default) number of records that each page contains is set to 25. For navigating through the different pages it's necessary to request also information relative to the `endCursor`:
```
{
proposals(first: 25) {
pageInfo {
hasNextPage
endCursor
}
edges {
node {
title
}
}
}
}
```
The response:
```json
{
"data": {
"proposals": {
"pageInfo": {
"hasNextPage": true,
"endCursor": "NQ=="
},
"edges": [
# ...
]
}
}
}
```
To retrieve the next page, you have to pass as a parameter the cursor received in the previous request, and so on:
```
{
proposals(first: 25, after: "NQ==") {
pageInfo {
hasNextPage
endCursor
}
edges {
node {
title
}
}
}
}
```
### Accessing several resources in a single request
This query requests information about several models in a single request: `Proposal`, `User`, `Geozone` and `Comment`:
```
{
proposal(id: 15262) {
id,
title,
public_author {
username
},
geozone {
name
},
comments(first: 2) {
edges {
node {
body
}
}
}
}
}
```
## Security limitations
Allowing a client to customize queries is a major risk factor. If too complex queries were allowed, it would be possible to perform a DoS attack against the server.
There are three main mechanisms to prevent such abuses:
* Pagination of results
* Limit the maximum depth of the queries
* Limit the amount of information that is possible to request in a query
### Example of too deep query
The maximum depth of queries is currently set at 8. Deeper queries (such as the following) will be rejected:
```
{
user(id: 1) {
public_proposals {
edges {
node {
id,
title,
comments {
edges {
node {
body,
public_author {
username
}
}
}
}
}
}
}
}
}
```
The response will look something like this:
```json
{
"errors": [
{
"message": "Query has depth of 9, which exceeds max depth of 8"
}
]
}
```
### Example of too complex query
The main risk factor is when multiple collections of resources are requested in the same query. The maximum number of collections that can appear in the same query is limited to 2. The following query requests information from the `users`, `debates` and `proposals` collections, so it will be rejected:
```
{
users {
edges {
node {
public_debates {
edges {
node {
title
}
}
},
public_proposals {
edges {
node {
title
}
}
}
}
}
}
}
```
The response will look something like this:
```json
{
"errors": [
{
"message": "Query has complexity of 3008, which exceeds max complexity of 2500"
},
{
"message": "Query has complexity of 3008, which exceeds max complexity of 2500"
},
{
"message": "Query has complexity of 3008, which exceeds max complexity of 2500"
}
]
}
```
However, it is possible to request information belonging to more than two models in a single query, as long as you do not try to access the entire collection. For example, the following query that accesses the `User`, `Proposal` and `Geozone` models is valid:
```
{
user(id: 468501) {
id
public_proposals {
edges {
node {
title
geozone {
name
}
}
}
}
}
}
```
The response:
```json
{
"data": {
"user": {
"id": 468501,
"public_proposals": {
"edges": [
{
"node": {
"title": "Empadronamiento necesario para la admisión en GoFit Vallehermoso",
"geozone": {
"name": "Chamberí"
}
}
}
]
}
}
}
}
```
## Code examples
The [doc/api/examples](https://github.com/consuldemocracy/consuldemocracy/tree/master/doc/api/examples/ruby) directory contains examples of code to access the API.

View File

@@ -0,0 +1,33 @@
# Local Census
To provide to administrator users a way to manage the local census database through the administration panel **Settings > Manage local census**. Currently the only way to manipulate this table records is through the rails console.
Allow administrators users to manage this table in two different ways:
- **Manually**: one by one through a CRUD interface.
- **Automatically**: through an importation process.
## Manually
Provide a way to manage local census records to administrator users through administration interface.
- Local Census Page
![Manage local census](../../img/local_census/manage-local-census-en.png)
- Add new record
![Create local census record](../../img/local_census/add-local-census-record-en.png)
Features:
1. Search by document_number: As local_census_records could contain a lot of records we have added a search feature to allow administrators to find existing records by document_number.
1. Avoid the introduction of duplicated records: A model validation has been added to the following attributes pair [:document_number, :document_type]
## Automatically
Allow administrator users to import local census records though CSV file.
- Local Census Page
![Manage local census csv](../../img/local_census/manage-local-census-csv-en.png)
- Import CSV
![Create local census records csv](../../img/local_census/add-local-census-records-csv-en.png)

View File

@@ -0,0 +1,240 @@
# Multitenancy
## What's multitenancy and how does it work
The multitenancy feature allows managing several independent institutions ("tenants") using the same application. For example, in our case, a user who signs up for a certain tenant will only be able to sign in on that tenant, and that user's data won't be available from any other tenant.
Which tenant we're accessing depends on the URL we're using in the browser to access the application. In Consul Democracy, the current tenant is established by the subdomain used in this URL. For example, if we used the domain `solarsystemexample.org` to manage the planets in the Solar System, using the URL `https://mercury.solarsystemexample.org` we'd access data from the planet Mercury while using the URL `https://venus.solarsystemexample.org` we'd access data from the planet Venus. It's also be possible to use different domains per tenant (for example, `earthexample.org`).
## Enabling multitenancy
### Preliminary steps after upgrading from Consul Democracy version 1.5.0
If you're upgrading a Consul Democracy installation to version 2.0.0 from version 1.5.0, you'll have to follow these steps before enabling multitenancy. These steps aren't necessary on new Consul Democracy installations.
First, after deploying version 2.0.0 to your production server, execute the release tasks:
```
RAILS_ENV=production bin/rails consul:execute_release_tasks
```
After runing this command, you might get the following warning:
> The database search path has been updated. Restart the application to apply the changes.
If that's the case, restart the application. If not, make sure the `config/database.yml` file contains the line `schema_search_path: "public,shared_extensions"` and, if that's not the case, add it for example below the line saying `adapter: postgresql` and restart the application.
Next, open a database console with a user having permission to create and manage database extensions:
```
sudo -u postgres psql -d consul_production
```
If you didn't use the [installer](https://github.com/consuldemocracy/installer/) to install Consul Democracy, you might need to execute a couple of queries to make sure the Rails database user has permission to create schemas and the shared extensions schema has the right permissions:
```
CREATE SCHEMA shared_extensions AUTHORIZATION <replace_with_rails_database_username>;
GRANT CREATE ON DATABASE consul_production TO <replace_with_rails_database_username>;
GRANT usage ON SCHEMA shared_extensions TO public;
```
Whether or not you installed Consul Democracy with the installer, run:
```
ALTER EXTENSION pg_trgm SET SCHEMA shared_extensions;
ALTER EXTENSION unaccent SET SCHEMA shared_extensions;
```
### Common step for all Consul Democracy installations
There are two possible ways to enable multitenancy:
* Adding `config.multitenancy = true` inside the `class Application < Rails::Application` class in the `config/application_custom.rb` file
* Replacing the line `multitenancy: false` with `multitenancy: true` (or adding it if it isn't already there) in the `config/secrets.yml` file
The difference between these options is that the first one uses a file under version control while the second one uses a file which isn't under version control. Choose the first option if you'd like to have this change in your git repository; otherwise, use the second one.
After enabling this option, restart the application.
## Managing tenants
Once multitenancy has been enabled and the application has been restarted, you'll see a new "Multitenancy" section inside the "Settings" menu in the Consul Democracy admin panel.
![New section with the list of tenants, with their name and domain or subdomain](../../img/multitenancy/index-en.png)
This section will only be available from the "main" tenant (the one which is created by default). It will not be possible to add/edit tenants by accessing the admin section of any other tenant.
Since removing a tenant would delete **all** its associated data, making it impossible to restore it, Consul Democracy doesn't allow deleting a tenant using the admin panel. However, it's possible to disable a tenant so it cannot be accessed.
The interface to manage tenants is very simple, needing just a name and a domain or subdomain.
![Form to edit a tenant, with name and domain or subdomain fields; radio buttons are used to choose domain or subdomain](../../img/multitenancy/form-en.png)
The name will be used to set the default site name for new tenants. Note that, once a tenant is created, changing this name will have no effect. To change the site name of an existing tenant, edit it in the "Global settings" section in the administration of that tenant.
The domain or subdomain will be used to access this tenant. If you've got a domain like `solarsystemexample.org` and would like to access tenants using subdomains (like `mars.solarsystemexample.org`), choose "Use a subdomain". If you're using a different domain for the tenant (like `marsexample.org`), choose "Use a different domain".
Note that, if you use a different domain for a tenant, you'll have to configure your SSL certificates, web server and DNS so they support that domain and point to your Consul Democracy application.
When adding a new tenant, an admin user **copying the same login data as the administrator creating the tenant** will be automatically created. Note this user is stored in the database schema of the new tenant, so changing their password in one tenant won't change their password in any other tenants.
## Steps to take after adding a tenant
### SSL certificates
In order to make it possible to access the application using secure HTTPS/SSL connections, you'll need a valid SSL certificate for the tenant you've just added. Since every institution using Consul Democracy has a different system to manage these certificates, getting a valid SSL certificate for the new tenant will need a different process depending on the way your institution manages these certificates.
If you've installed Consul Democracy using the installer and are using Certbot to manage these certificates, you have two options.
One option would be adding each certificate manually every time you create a tenant. For example, in orer to add a tenant using the `mars` subdomain in the `solarsystemexample.org` domain, run:
```
sudo certbot certonly --nginx --noninteractive --agree-tos --expand -d solarsystemexample.org,mars.solarsystemexample.org
```
If you're going to add many subdomains at different times, this task can be tedious. Another option is enabling any subdomain. In order to achieve this goal, you need access to your DNS configuration in order to follow the instructions you'll get by either using one of the [Certbot DNS plugins](https://eff-certbot.readthedocs.io/en/stable/using.html#dns-plugins) or the [manual generation of the certificate](https://eff-certbot.readthedocs.io/en/stable/using.html#manual) with the following command:
```
sudo certbot certonly --manual --agree-tos --expand -d solarsystemexample.org,*.solarsystemexample.org
```
You'll be asked to create a DNS TXT record with the subdomain `_acme-challenge` on your domain, with a certain value. You might also be asked to create a file with a certain name containing a certain content (usually in a `.well-known/acme-challenge` folder); if that's the case, assuming you're using Consul Democracy's default folders, create it in `/home/deploy/consul/current/public/.well-known/acme-challenge/`.
After doing so, update your web server configuration file (by default `/etc/nginx/sites-enabled/default`) so it uses the generated certificate, and restart the web server with `sudo systemctl restart nginx`.
### Sending e-mails
In order to reduce the chance your application sends emails which are erronously identified as spam, you might want to edit the fields "Sender email name" and "Sender email address" in the administration panel of the new tenant. The default values for these fields are the name and subdomain introduced when creating the tenant.
![Fields to edit sender email name and address](../../img/multitenancy/email-settings-en.png)
If you'd like to use a different mail configuration for the new tenant, like one for a hypothetical `jupiter` subdomain, edit the `config/secrets.yml` file this way:
```
production:
# (...) Other secrets
multitenancy: true
tenants:
jupiter:
mailer_delivery_method: :smtp
smtp_settings:
:address: <mail_server>
:port: <port>
:domain: <your_domain>
:user_name: <username>
:password: <password>
:authentication: "plain"
:enable_starttls_auto: true
# (...) Other secrets
```
After editing this file, restart the application.
### Sign in via social networks
If you've configured applications so users can sign in via Twitter, Google, Facebook or Wordpress, you need to allow the new tenant to access these applications. You have two options.
The first option is changing your existing application using the Twitter/Google/Facebook/Wordpress dashboard and add the new tenant's URL to the list of allowed domains. When doing so, take into account your application's terms and conditions settings, which might not be compatible with this option.
The other option is creating a new Twitter/Google/Facebook/Wordpress application and configuring it so it can be used from the new tenant. In this case, you'll have to add the configuration of this application to the `config/secrets.yml` file. For example, if you've added a tenant using the `saturn` subdomain, edit the file this way, filling in the keys and secrets of the services you're using:
```
production:
# (...) Other secrets
multitenancy: true
tenants:
saturn:
twitter_key: <twitter_key>
twitter_secret: <twitter_secret>
facebook_key: <facebook_key>
facebook_secret: <facebook_secret>
google_oauth2_key: <google_key>
google_oauth2_secret: <google_secret>
wordpress_oauth2_key: <wordpress_key>
wordpress_oauth2_secret: <wordpress_secret>
wordpress_oauth2_site: <wordpress_site>
# (...) Other secrets
```
After editing this file, restart the application.
## Information to take into account during development
### Maintenance of the schema.rb file
When Consul Democracy creates a tenant, it loads the content of the `db/schema.rb` file to create a new database schema for the new tenant. This means that if for some reason this file doesn't contain the same database structure you'd get by creating a new database and running the migrations with `rake db:migrate`, you could end up with different database table or columns on different tenants. This could result in a disastrous situation.
In order to avoid it, we recommend checking the integrity of the `db/schema.rb` file in your continuous integration system. If you're doing continuous intergration using GitHub Actions, you can use the workflow already included in Consul Democracy. Pull requests adding this check on GitLab CI or other continuous intergration environments are welcome.
### Using custom styles for a tenant with CSS
When the multitenancy feature is enabled, Consul Democracy adds a class to the `<html>` element, making it possible to apply styles (or JavaScript events) to just a specific tenant. For example, the tenant with the `uranus` subdomain would have the `tenant-uranus` class.
This way, it'll be possible to overwrite the default styles for just this tenant by creating a new stylesheet in the `app/assets/stylesheets/custom/` folder:
```
.tenant-uranus {
// Styles that will only be applied to the Uranus tenant
}
```
To easily change the default colors on a specific tenant, you can use CSS variables; their usage is documented in the [app/assets/stylesheets/custom/tenants.scss](https://github.com/consuldemocracy/consuldemocracy/blob/master/app/assets/stylesheets/custom/tenants.scss) file. For example, to make the brand colors green on the tenant with the `uranus` subdomain, write:
```
.tenant-uranus {
--brand: #350;
--brand-secondary: #173a00;
}
```
### Using different custom ERB views for a tenant
Sometimes it might be convenient to use completely different views for different tenants. For example, a certain tenant might use a footer that has nothing to do with the default one.
In these cases, instead of adding conditions like `case Tenant.current_schema` to the view, using a different file might result in code easier to maintain.
For this purpose, we can use [Rails variants](https://guides.rubyonrails.org/layouts_and_rendering.html#the-variants-option), which means that, for example, a tenant named `milky-way` will use a view file ending with `.html+milky-way.erb` if it's available. That is, in order to use a different `application.html.erb` layout for the `milky-way` tenant, add a new file under `app/views/custom/layouts/application.html+milky-way.erb`.
We recommend only using this feature when there are substantial differences between the default view and the specific view for a tenant. If the differences are small, use `if` or `case` conditions instead in order to avoid code duplication.
The same principle works for components too, but in this case, when using the `custom/` folder to add ERB files for a tenant, the default tenant ERB file needs to be added to the `custom/` folder as well; if there aren't changes to this file, a symbolic link will do.
For example, if you're writing a custom `admin/action_component` component view for the `milky-way` tenant but don't need to change this file for the default tenant:
1. Create the `app/components/custom/admin/action_component.rb` file according to the [components customization documentation](../customization/components.md)
1. Create the custom view for the `milky-way` tenant and save it under `app/components/custom/admin/action_component.html+milky-way.erb`
1. Enter the `app/components/custom/admin/` folder and run `ln -s ../../admin/action_component.html.erb`
## Current limitations of multitenancy
The multitenancy feature was first included in Consul Democracy 2.0.0 and there are a few things that are still missing.
### Applications which can be accessed from multiple domains
You might have a Consul Democracy application which can be accessed from two different domains; for example, `solarsystemexample.org` and a domain in Spanish named `ejemplodesistemasolar.org`.
In this case, the source code needs to be changed a little so multitenancy works with both domains. In particular, the `allowed_domains` method in the `Tenant` class needs to be changed in order to include both domains. See the [models customization documentation](../customization/models.md) for examples on how to customize methods like this one.
### Custom images per tenant
The administration panel in Consul Democracy contains a "Custom images" section, where you can customize some (but not all) images appearing in the application. Using this interface allows having different images per tenant.
Sometimes it's useful to have a certain image under version control, though. For instance, if we'd like to use a different logo for a tenant with the `neptune` subdomain, we'd put that file under `app/assets/images/custom/tenants/neptune/logo_header.png`.
However, this will only work for images which can already be configured through the administration interface. If you'd like to customize a different image, you'll have to change the code rendering it. For instance, to make it possible to customize the `avatar_admin.png` image, replace the code `image_tag("avatar_admin.png")` with `image_tag(image_path_for("avatar_admin.png"))`.
### Databases on different servers for different tenants
In Consul Democracy 2.0.0, data from all tenants is stored in the same database and so it isn't possible to use several databases on different servers.
If this feature is requested often, it'll be possible to include it in Consul Democracy in the future. However, Consul Democracy 2.0.0 uses Rails 6.0 and this feature will require upgrading to Rails 6.1 or even Rails 7.0.
### Different languages per tenant
In Consul Democracy 2.0.0, every tenant is available in the same languages, so it wouldn't be possible (for instance) to enable French in one tenant and German in a different one; you'd have to enable both languages in both tenants.
Implementing this feature is planned for Consul Democracy 2.1.0.
### Deleting tenants
Since removing a tenant would delete **all** its associated data, making it impossible to restore it, Consul Democracy doesn't allow deleting tenants using the admin panel and only allows disabling them so they cannot be accessed. To completely delete a tenant, use the Rails console.

32
docs/en/features/oauth.md Normal file
View File

@@ -0,0 +1,32 @@
# OAuth
You can configure authentication services with external OAuth suppliers, right now Twitter, Facebook and Google are supported.
## 1. Create an App on the platform
For each platform, go to their developers section and follow their guides to create an app.
## 2. Set your Consul Democracy's url
They'll ask you for your Consul Democracy's auth URL, and as you can see running `rake routes` at your Consul Democracy repo locally:
```bash
user_omniauth_authorize GET|POST /users/auth/:provider(.:format) users/omniauth_callbacks#passthru {:provider=>/twitter|facebook|google_oauth2/}
```
So for example the URL for facebook application would be `yourdomain.com/users/auth/facebook/callback`
## 3. Set key & secret values
When you complete the application registration you'll get a *key* and *secret* values, those need to be stored at your `config/secrets.yml` file:
```yml
twitter_key: ""
twitter_secret: ""
facebook_key: ""
facebook_secret: ""
google_oauth2_key: ""
google_oauth2_secret: ""
```
*NOTE:* Also in the case of Google, verify that the APIs *Contacts API* and *Google+ API* are enabled for the application.

View File

@@ -0,0 +1,29 @@
# Debates & Proposals Recommendations
Logged in users can see recommended Debates or Proposals listed with the ordering option "recommendations".
The list shows, ordered by votes descending, those elements that:
1. Have tags that interests the user. Being those tags the ones on the proposals that the user follows.
2. The user isn't the author.
3. In the case of proposals: only those that haven't reached the required threshold of votes, hiding as well those that the user is already following.
## How to try it
In our local installation, if we haven't logged in, we can check at <http://localhost:3000/proposals> that the "recommendations" ordering isn't present:
![Recommendations not logged in](../../img/recommendations/recommendations_not_logged_in.jpg)
Once we log in we see the menu, but because we don't aren't following any proposals we get the message "Follow proposals so we can give you recommendations" at <http://localhost:3000/proposals?locale=en&order=recommendations&page=1>
![Recommendations no follows](../../img/recommendations/recommendations_no_follows.jpg)
After following any proposal with the "Follow citizen proposal" on the side menu:
![Recommendations follow button](../../img/recommendations/recommendations_follow_button.jpg)
We can finally see some recommendations:
![Recommendations with follows](../../img/recommendations/recommendations_with_follows.jpg)
The feature works the same for debates

View File

@@ -0,0 +1,13 @@
# Communication
The preferred way to report any missing piece of information is [opening an issue in the project's Github repo](https://github.com/consuldemocracy/docs/issues/new).
For more informal communication, chat with us at [Consul Democracy's gitter](https://gitter.im/consul/consul).
Before doing it, **please take some time to check the [existing issues](https://github.com/consuldemocracy/consuldemocracy/issues) and make sure what you are about to report isn't already reported** by another person. In case someone else reported the same problem before or a similar one, and you have more details about it, you can write a comment in the issue page... a little more help can make a huge difference!
In order to write a new issue, take into account these few tips to make it easy to read and comprehend:
- Try to use a descriptive and to-the-point title.
- It's a good idea to include some sections -in case they're needed- such as: steps to reproduce the bug, expected behaviour/response, actual response or screenshots.
- Also it could be helpful to provide your operating system, browser version and installed plugins.

View File

@@ -0,0 +1,17 @@
# Configure your fork
## Travis CI
[Travis](https://travis-ci.org/) is a Continuous Integration service, free for OpenSource projects (like Consul Democracy and its forks). It will help you check on each Pull Request if the test suite is alright.
1. Visit <https://github.com/marketplace/travis-ci> and click the "**Install it for free**" green button at the bottom of the page.
2. Click on the "**Complete order and begin installation**" green button.
3. If you are asked to Authorize Travis CI to access your Github account, check the organization or user where you have your Consul Democracy fork at the bottom and click the "**Authorize travis-ci**" button.
4. Visit your [Travis profile](https://travis-ci.org/profile/) and enable Travis for your Consul Democracy fork in the list of repositories.
5. Click on the sprocket icon to the right of the repository to see the builds.
6. Check that everything is well configured by creating a test Pull Request (editing a simple .md file could help).

View File

@@ -0,0 +1,22 @@
# Creating your fork
Consul Democracy git repo is hosted at Github.com, we recommend using it for your fork's repo to make things easier. But you can use any other service like Bitbucket or Gitlab if you want to, just don't forget to put a reference link back to Consul Democracy on the footer to comply with project's license (GPL Affero 3).
1. [Register an user account on Github](https://github.com/join) if you don't have one.
2. [Create an Organization](https://help.github.com/articles/creating-a-new-organization-from-scratch/) on Github with the name of your city or the organization that's going to use Consul Democracy. **This is not mandatory**, but it will help understand the fork's purpose and future contributions by other users.
3. [Fork Consul Democracy](https://help.github.com/articles/fork-a-repo/) using the **fork** button on the top right corner at <https://github.com/consuldemocracy/consuldemocracy>
4. [Clone your fork repository](https://help.github.com/articles/cloning-a-repository/) on to your computer.
****IMPORTANT NOTICE**: Do not fork `https://github.com/AyuntamientoMadrid/consul`, it's a common mistake that leads to multiple and grave problems.
## Why make code public?
We strongly recommend making code public for multiple reasons:
- **Transparency**: It should be part of the culture of public entities that adopt Consul Democracy, as well as any organization or group.
- **Support**: If you need technical help, both community and Consul Democracy core team will be able to understand and advice by easily seeing involved code.
- **Collaboration**: By other professionals, citizens, etc...
- Last but not least, Consul Democracy is distributed under the **[AGPLv3](https://github.com/consuldemocracy/consuldemocracy/blob/master/LICENSE-AGPLv3.txt) license** that commands to publish source code.

View File

@@ -0,0 +1,6 @@
# Getting started
* [Fork Consul Democracy](create.md)
* [Configure your fork](configuration.md)
* [Keep your fork updated](update.md)
* [Communication](communication.md)

View File

@@ -0,0 +1,69 @@
# Keeping your fork updated
## Configuring your git remotes
If you created your fork correctly and cloned it locally, running:
```bash
git remote -v
```
it should output something alike:
> origin git@github.com:your_user_name/consuldemocracy.git (fetch)\
> origin git@github.com:your_user_name/consuldemocracy.git (push)
Now we have to add Consul Democracy's github as upstream remote with:
```bash
git remote add upstream git@github.com:consuldemocracy/consuldemocracy.git
```
and to check everything is fine with
```bash
git remote -v
```
again you should get:
> upstream git@github.com:consuldemocracy/consuldemocracy.git (fetch)\
> upstream git@github.com:consuldemocracy/consuldemocracy.git (push)\
> origin git@github.com:your_user_name/consuldemocracy.git (fetch)\
> origin git@github.com:your_user_name/consuldemocracy.git (push)
## Pulling changes from Consul Democracy
Start by creating a branch named **upstream** from your **master** branch to apply Consul Democracy changes:
```bash
git checkout master
git pull
git checkout -b upstream
```
Then we can fetch all changes from the **Consul Democracy** remote server with:
```bash
git fetch upstream
```
And then you can choose to either:
A. Get all the latest changes on Consul Democracy's **master** branch with `git merge upstream/master`.
B. Just update up to an specific release tag (so you can do incremental updates if you're more than one release behind). For example to update up to [v0.9](https://github.com/consuldemocracy/consuldemocracy/releases/tag/v0.9) release just: `git merge v0.9`.
## Merging changes
After the previous section `merge` command, there are three possible outcomes:
A. You get a nice `Already up-to-date.` response. That means your fork is up to date with Consul Democracy 😊👌.
B. You get a screen on your git configured editor showing the commit message `Merge remote-tracking branch 'upstream/master' into upstream`. That means git was able to grab latest changes from Consul Democracy's master branch, and it can merge them without code change conflicts. Finish the commit.
C. You get some git errors along with a `Automatic merge failed; fix conflicts and then commit the result.` message. That means there are conflicts between the code changes you did and the ones done on Consul Democracy repository since the last time you update it. That's the main reason we strongly recommend often updates of your fork (think at least monthly). Resolve merge conflicts carefully and commit them.
Now you can just simply push your **upstream** branch to github and create a Pull Request so you can easily check all changes going into your repo, and see your tests suite runs.
Remember you can always quickly check changes that will come from Consul Democracy to your fork by replacing **your_org_name** on the url: <https://github.com/your_org_name/consuldemocracy/compare/master...consuldemocracy:master>.

View File

@@ -0,0 +1,80 @@
# Basic Configuration
Once you have Consul Democracy running on the server, there are some basic configuration options that you probably want to define in order to start using it. To do this you will need to open your Consul Democracy installation through any internet browser and log in with the administration user \(initially it is the `admin@consul.dev` user with the password `12345678`\).
Once you have logged in you will see on the top right of the screen the "Admin" link that will take you to the administration interface. From this interface you can configure the following basic options:
## Global configuration parameters
In the side menu you will find the option "Settings" and then the submenu "Global Settings". Here you will find many interesting parameters, but at the moment we recommend you to define some of the most basic ones. Later, when you are more familiar with the tool, you will be able to reconfigure other parameters:
* Site name. This name will appear in the subject of emails, help pages...
* Sender email name. This name will appear as the name of the sender in the emails sent from the application. As for example the email that the users receive to confirm that they have created their account.
* Sender email address. This email address will appear in the emails sent from the application.
* Main URL. Main URL of your website
* Minimum age needed to participate. If you use a user verification system this will be the minimum age that users will be required to be. The user verification system will be discussed in more detail later.
* Number of supports necessary for approval of a Proposal. If you use the citizen proposals section, you can define a minimum number of supports that the proposals need in order to be considered. Any user will be able to create proposals but only those that reach that value will be taken into account.
* Level x public official. Consul Democracy allows some user accounts to be marked as "official accounts" and their interventions on the platform are highlighted. This for example is used in a city if you want to define accounts for the Mayor, Councillors, etc. This public official option will allow you to define the official label that appears next to the user names of these accounts from most important \(level 1\) to least \(level 5\).
## Categories of proposals
When users create proposals on the platform, a few general categories are suggested to help organize the proposals. To define these categories you can go to the "Global Settings" menu and then to the "Proposal Topics" submenu. At the top you can write topics and create them with the button below.
## Definition of Geozones
Geozones are smaller territorial areas than the area in which you use Consul Democracy \(e.g. districts in a city in which Consul Democracy is used\). If the geozones are activated, it will allow for example that the citizen proposals are assigned to a specific area, or that the votings are restricted to people living in some area.
In the side menu you will find the option "Settings" and then the submenu "Manage geozones". To the right the button "Create geozone" will allow you to create new geozones. Only the name is necessary to define them, but you can add other data that are useful in certain sections. Initially we recommend that you start by defining only the names of the zones.
Once defined if you create a citizen proposal you will see how one of the options in the proposal creation form allows you to choose if your proposal refers to a specific geozone.
If you activate the geozones you can also display an image that represents the area with the zones. You can change this image in the "Global settings" menu in the "Customize images" submenu. The default image you can change is the one titled "map".
## Map to geolocate proposals
You can allow users to place proposals on a map when creating proposals. To do this you have to define which map you want to show.
First go to the "Settings" menu and to the "Global Settings" submenu. There you will find three parameters that you will have to fill in:
* Latitude. Latitude to show the map position
* Length. Length to show the map position
* Zoom. Zoom to show the position of the map. You can try an initial value and then change it later.
At the top of this page you will find three tabs: "Configuration settings", "Features", "Map configuration". Now go to the second tab "Features".
On this page you will find one of the functionalities titled "Proposals and budget investments geolocation ". The message "Functionality enabled" should appear on your right. If not, click on the "Enable" button.
Then, at the top of this page, go to the "Map configuration" tab. If everything has been configured correctly you will see here the map centered on the latitude and longitude you entered before. You can correctly center the map and change the zoom level directly on the map by clicking on the "Update" button below it.
## Emails to users
Consul Democracy sends a series of emails to users by default. For example when creating a user account, trying to recover a password, receiving a message from another user, etc.
All emails sent can be viewed in the menu "Messages to users" in the submenu "System Emails". There you will be able to preview each email and see the file where the content of the email is in case you want to change it.
## Basic information pages
Consul Democracy has a number of basic information pages that will be shown to users, e.g. "Privacy Policy", "Frequently Asked Questions", "Congratulations you have just created your user account", etc.
You can see the pages that exist by default and modify them in the menu "Site Content" in the submenu "Custom Pages".
## Main page of the site
When users open your Consul Democracy installation they will see the home page of the platform. This page is fully configurable, so that you can show the content that seems most relevant to you. You can modify it from the menu "Site content" in the submenu "Homepage".
Try creating "Headers" and "Cards" and activating the different functionalities you will find below to see the effect they have on your homepage.
## Platform texts
If you access the menu "Site content" and the submenu "Custom information texts" you will see different tabs with a series of texts. These are all the texts displayed on the platform. By default you can use the existing ones, but at any time you can access this section to modify any of the texts.
For more information on how to add new translations to your version of Consul Democracy access the "Texts and translations" section of this documentation.
## Channels of participation
By default you will find in Consul Democracy different ways of participation for users. To begin with and familiarise yourself with the tool, we recommend that you have all of them activated, but you can deactivate the ones that do not seem necessary to you. To do this, go to the "Settings" menu and then to the "Global Settings" submenu. At the top of this page you will find three tabs: "Configuration settings", "Features", "Map configuration". Go to the second tab "Features".
You will find different functionalities with the names of the different participation channels "Debates", "Proposals", "Voting", "Collaborative Legislation" and "Participatory Budgets". You can deactivate any of the functionalities and it will no longer be shown in your Consul Democracy installation.
### More information and detailed documentation
These options above will allow you to have a basic version of Consul Democracy to start using. We recommend that you access the [Consul Democracy Documentation and Guides](documentation_and_guides.md) section where you can find more detailed documentation.

View File

@@ -0,0 +1,80 @@
# Create a deploy user
[The installer](https://github.com/consuldemocracy/installer) by default connects as the `root` user only to create a `deploy` user. This `deploy` user is the one who installs all libraries. If you do not have `root` access, please ask your system administrator to follow these instructions to create a user manually.
You could create a user called `deploy` or any other name. As as example, we are going to create a user named `jupiter`.
```
adduser jupiter
```
I'm using jupiter as the user name, you should change that for whatever makes sense to you. Input a password when prompted, and just leave empty the rest of the options.
Let's create a `wheel` group and add the user `jupiter` to this group.
```
sudo groupadd wheel
sudo usermod -a -G wheel jupiter
```
Now let's give sudo privileges to the `wheel` group and allow it to not use a password, this is important so that the installer doesn't get stalled waiting for a password.
First we open the sudoers file:
```
sudo visudo -f /etc/sudoers
```
And we add this line at the end:
```
%wheel ALL=(ALL) NOPASSWD: ALL
```
Now we need to give the keys of the server to the new user. Dont close the server terminal window, because you can lock yourself out of your server if there is a mistake.
Let's create the necessary directory in the server to upload the public key:
```
su jupiter
cd ~
mkdir .ssh
cd .ssh
nano authorized_keys
```
Make sure you have [generated a public key](generating_ssh_key.md) in your local terminal.
Open another local terminal window (not in the server) and type:
```
cat ~/.ssh/id_rsa.pub
```
Copy the content of your public key to the file authorized_keys that should still be open in the server.
Test that your user can log in by typing:
```
ssh jupiter@your-copied-ip-address
```
You should see the server welcome page and a prompt like this:
```
jupiter@consuldemocracyserver:~$
```
Note the username at the prompt is not "root", but your username. So everything is fine and we can now block the root account from outside access and also stop allowing password access so only people with SSH keys can log in.
Type the following command to edit the SSH config file of the server:
```
sudo nano /etc/ssh/sshd_config
```
Look for the "PasswordAuthentication yes" line and change it to "PasswordAuthentication no". Type Control-K to close the nano editor and type:
```
sudo service ssh restart
```

View File

@@ -0,0 +1,163 @@
# Configuration for development and test environments (Debian GNU/Linux 9.8)
## Superuser
Note that 'sudo' is not installed by default in Debian. It's possible to install and configure it, you can find information [here](https://wiki.debian.org/sudo). But we don't recommend it cause you may have other problems. We recommend running the following commands as a superuser, so make sure the very first command you run is:
```
su
```
> For [Vagrant](/en/installation/vagrant.md) run:
> ```
> sudo su -
> ```
## System update
Run a general system update:
```bash
apt-get update
```
## Git
Git is officially maintained in Debian:
```
apt-get install git
```
## Curl
Curl is officially maintained in Debian:
```
apt-get install curl
```
## Ruby version manager
Ruby versions packaged in official repositories are not suitable to work with Consul Democracy, so we'll have to install it manually.
One possible tool is rvm:
### As a local user
```
command curl -sSL https://rvm.io/mpapis.asc | gpg --import -
command curl -sSL https://rvm.io/pkuczynski.asc | gpg --import -
curl -L https://get.rvm.io | bash -s stable
```
then add rvm script source to user's bash (~/.bashrc) (this step is only necessary if you can't execute the rvm command)
```
[[ -s /usr/local/rvm/scripts/rvm ]] && source /usr/local/rvm/scripts/rvm
```
and finally, reload .bashrc to be able to run RVM
```
source ~/.bashrc
```
## Node.js
To compile the assets, you'll need a JavaScript runtime. Node.js is the preferred option. As with Ruby, we don't recommend installing Node from your distro's repositories.
To install it, you can use [n](https://github.com/tj/n)
Run the following command on your terminal:
```
curl -L https://git.io/n-install | bash -s -- -y lts
```
And it will install the latest LTS (Long Term Support) Node version on your `$HOME` folder automatically (This makes use of [n-install](https://github.com/mklement0/n-install))
Reload .bashrc to be able to run node
```
source /root/.bashrc
```
Check it's correctly installed by running:
```
node -v
```
## PostgreSQL (>=9.4)
PostgreSQL version 9.4 is not official in debian 9.
So you have to add a repository, the official postgresql works fine.
Add the repository to apt, for example creating file */etc/apt/sources.list.d/pgdg.list* with:
```
deb http://security.debian.org/debian-security jessie/updates main
```
afterwards you'll have to download the key, and install it, by:
```
wget https://www.postgresql.org/media/keys/ACCC4CF8.asc
apt-key add ACCC4CF8.asc
```
and install postgresql
```
apt-get update
apt-get install postgresql-9.4 postgresql-server-dev-9.4 postgresql-contrib-9.4
```
You also need to configure a user for your database. As an example, we'll choose the username "consul":
```
su - postgres
createuser consul --createdb --superuser --pwprompt
exit
```
## Imagemagick
Install Imagemagick:
```bash
apt-get install imagemagick
```
## ChromeDriver
To run E2E integration tests, we use Selenium along with Headless Chrome.
To get it working, install the chromedriver package:
```bash
apt-get install chromedriver
ln -s /usr/lib/chromedriver /usr/local/bin/
```
Make sure it's working as expected by running the following command:
```bash
chromedriver --version
```
You should receive an output with the latest version of ChromeDriver. If that's the case, you're good to go!
If you are using an Arch-based distro, installing `chromium` from the `extra` repository should be sufficient.
You also have the option of just installing ChromeDriver from AUR. If you use `pacaur`, run the following command:
```bash
pacaur -S chromedriver
```
Now you're ready to go get Consul Democracy [installed](local_installation.md)!!

View File

@@ -0,0 +1,186 @@
# Deploying on Heroku
## Manual deployment
This tutorial assumes that you have already managed to clone Consul Democracy on your machine and gotten it to work.
1. First, create a [Heroku](https://www.heroku.com) account if it isn't already done.
2. Install the [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) and sign in using
```bash
heroku login
```
3. Go to your Consul Democracy repository and instantiate the process
```bash
cd consuldemocracy
heroku create your-app-name
```
You can add the flag `--region eu` if you want to use their European servers instead of the US ones.
If _your-app-name_ is not already taken, Heroku should now create your app.
4. Create a database using
```bash
heroku addons:create heroku-postgresql
```
You should now have access to an empty Postgres database whose address was automatically saved as an environment variable named _DATABASE\_URL_. Consul Democracy will automatically connect to it when deployed.
5. **(Not needed)** Add a file name _heroku.yml_ at the root of your project and paste the following in it
```yml
build:
languages:
- ruby
packages:
- imagemagick
run:
web: bundle exec rails server -e ${RAILS_ENV:-production}
```
6. Now, generate a secret key and save it to an ENV variable named SECRET\_KEY\_BASE using
```bash
heroku config:set SECRET_KEY_BASE=$(rails secret)
```
Also add your server address:
```bash
heroku config:set SERVER_NAME=myserver.address.com
```
You need to let the app know where the configuration variables are stored by adding a link to the ENV variables in _config/secrets.yml_
```yml
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
server_name: <%= ENV["SERVER_NAME"] %>
```
and commit this file in the repo by commenting out the corresponding line in the _.gitignore_.
```gitignore
#/config/secrets.yml
```
**Remember not to commit the file if you have any sensitive information in it!**
7. You can now push your app using
```bash
git push heroku your-branch:master
```
8. It won't work straight away because the database doesn't contain the tables needed. To create them, run
```bash
heroku run rake db:migrate
heroku run rake db:seed
```
If you want to add the test data in the database, move `gem 'faker', '~> 1.8.7'` outside of `group :development` and run
```bash
heroku config:set DATABASE_CLEANER_ALLOW_REMOTE_DATABASE_URL=true
heroku config:set DATABASE_CLEANER_ALLOW_PRODUCTION=true
heroku run rake db:dev_seed
```
9. Your app should now be ready to use. You can open it with
```bash
heroku open
```
You also can run the console on heroku using
```bash
heroku console --app your-app-name
```
10. Heroku doesn't allow to save images or documents in its servers, so it's necessary to setup a permanent storage space.
See [our S3 guide](./using-aws-s3-as-storage.md) for more details about configuring Paperclip with S3.
### Configure Sendgrid
Add the SendGrid add-on in Heroku. It will create a SendGrid account for you with `ENV["SENDGRID_USERNAME"]` and `ENV["SENDGRID_PASSWORD"]`.
Add this to `config/secrets.yml`, under the `production:` section:
```
mailer_delivery_method: :smtp
smtp_settings:
:address: "smtp.sendgrid.net"
:port: 587
:domain: "heroku.com"
:user_name: ENV["SENDGRID_USERNAME"]
:password: ENV["SENDGRID_PASSWORD"]
:authentication: "plain"
:enable_starttls_auto: true
```
Important: Turn on one worker dyno so that emails get sent.
## Optional but recommended
### Install rails\_12factor and specify the Ruby version
**The rails\_12factor is only useful if you use a version of Consul Democracy older than 1.0.0. The latter uses Rails 5 which includes the changes.**
As recommended by Heroku, you can add the gem rails\_12factor and specify the version of Ruby you want to use. You can do so by adding
```ruby
gem 'rails_12factor'
ruby 'x.y.z'
```
in the file _Gemfile\_custom_, where `x.y.z` is the version defined in the `.ruby-version` file in the Consul Democracy repository. Don't forget to run
```bash
bundle install
```
to generate _Gemfile.lock_ before committing and pushing to the server.
### Use Puma as a web server
Heroku recommends to use Puma to improve the responsiveness of your app on [a number of levels](http://blog.scoutapp.com/articles/2017/02/10/which-ruby-app-server-is-right-for-you).
If you want to allow more concurrency, uncomment the line:
```ruby
workers ENV.fetch("WEB_CONCURRENCY") { 2 }
```
You can find an explanation for each of these settings in the [Heroku tutorial](https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server).
The last part is to change the _web_ task to use Puma by changing it to this in your _heroku.yml_ file:
```yml
web: bundle exec puma -C config/puma.rb
```
### Add configuration variables to tune your app from the dashboard
The free and hobby versions of Heroku are barely enough to run an app like Consul Democracy. To optimise the response time and make sure the app doesn't run out of memory, you can [change the number of workers and threads](https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#workers) that Puma uses.
My recommended settings are one worker and three threads. You can set it by running these two commands:
```bash
heroku config:set WEB_CONCURRENCY=1
heroku config:set RAILS_MAX_THREADS=3
```
I also recommend to set the following:
```bash
heroku config:set RAILS_SERVE_STATIC_FILES=enabled
heroku config:set RAILS_ENV=production
```

View File

@@ -0,0 +1,59 @@
# Installing Consul Democracy on a Digital Ocean VPS
These instructions will help you register and buy a server in Digital Ocean to install Consul Democracy.
First you need to [sign up](https://cloud.digitalocean.com/registrations/new) and provide your personal information.
Once you are logged in, you need to create a Droplet (thats the name that Digital Ocean uses for a Virtual Server). Click on the “Create” green button at the top of the page and select "Droplets":
![Digital Ocean Droplets](../../img/digital_ocean/droplets.png)
In the next page, you need to select Ubuntu (it should be pre-selected) and change the version **from 18.04 x64 to 16.04 x64**.
![Digital Ocean Choose an image](../../img/digital_ocean/image.png)
In the "Choose a size" section select the **$80/mo 16GB/6CPUs** option if this is going to be a production server. If you are just setting up a test system with a few users the cheapest $5/mo option can be enough.
![Digital Ocean Choose a size](../../img/digital_ocean/size.png)
Leave the rest of the options with their defaults until “Choose a datacenter”. Select the one that will be geographically closer to your users. If you are in the EU, select either Frankfurt or Amsterdam data centers.
![Digital Ocean Choose a region](../../img/digital_ocean/region.png)
In the "Add you SSH keys" section click "New SSH Key" button.
![Digital Ocean Add your SSH Keys](../../img/digital_ocean/ssh_keys.png)
In the pop up window that appears you need to copy and paste the public key that we [generated in the previous step](generating_ssh_key.md). To see the content of this key in the terminal window type:
```
cat ~/.ssh/id_rsa.pub
```
You should see a text like this:
```
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDy/BXU0OsK8KLLXpd7tVnqDU+d4ZS2RHQmH+hv0BFFdP6PmUbKdBDigRqG6W3QBexB2DpVcb/bmHlfhzDlIHJn/oki+SmUYLSWWTWuSeF/1N7kWf9Ebisk6hiBkh5+i0oIJYvAUsNm9wCayQ+i3U3NjuB25HbgtyjR3jDPIhmg1xv0KZ8yeVcU+WJth0pIvwq+t4vlZbwhm/t2ah8O7hWnbaGV/MZUcj0/wFuiad98yk2MLGciV6XIIq+MMIEWjrrt933wAgzEB8vgn9acrDloJNvqx25uNMpDbmoNXJ8+/P3UDkp465jmejVd/6bRaObXplu2zTv9wDO48ZpsaACP your_username@your_computer_name
```
Select and copy all the text and paste it in the pop-up window like this:
![Digital Ocean New SSH Key](../../img/digital_ocean/new_ssh.png)
Please note that there will be two little green checks. If they are not there, retry copying the text because you probably left something out. Give your key a meaningful name, like **Consul_Democracy_key** and click "Add SSH Key" button.
By using an SSH key instead of a user/password combination to access your server, it will be much more secure, as only someone with the private SSH key can access the server.
Now in the "Choose a hostname" section change the default for something more meaningful, like **consuldemocracyserver** for example.
![Digital Ocean hostname](../../img/digital_ocean/hostname.png)
At the bottom of the page youll see a summary of your options. Check that everything is OK and click the big green "Create" button.
![Digital Ocean create](../../img/digital_ocean/create.png)
It will take a few minutes, and at the end you will have a shiny new server. It will look like this in the Digital Ocean page:
![Digital Ocean server](../../img/digital_ocean/server.png)
Next to setup Consul Democracy in the server check the [installer's README](https://github.com/consuldemocracy/installer)

View File

@@ -0,0 +1,160 @@
# Using Docker for local development
You can use Docker to have a local Consul Democracy installation for development if:
- You're having troubles having [prerequisites](prerequisites.md) installed.
- You want to do a quick local installation just to try Consul Democracy or make a demo.
- You prefer not to interfere with other rails installations.
## Prerequisites
You should have installed Docker and Docker Compose in your machine:
### macOS
You can follow the [official docker install](https://docs.docker.com/docker-for-mac/install/)
Or if you have [homebrew](http://brew.sh) and [cask](https://caskroom.github.io/) installed you can just:
```bash
brew install docker
brew install docker-compose
brew cask install docker
open -a docker
```
You'll be asked to give Docker app permissions and type your password, then you're set.
### Linux
1. Install Docker:
```bash
sudo apt-get update
sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
sudo apt-add-repository 'deb https://apt.dockerproject.org/repo ubuntu-xenial main'
sudo apt-get update
apt-cache policy docker-engine
sudo apt-get install -y docker-engine
```
2. Install Docker Compose
```bash
sudo curl -o /usr/local/bin/docker-compose -L "https://github.com/docker/compose/releases/download/1.15.0/docker-compose-$(uname -s)-$(uname -m)"
sudo chmod +x /usr/local/bin/docker-compose
```
### Windows
Go to the [https://www.docker.com/get-started](Get Started with Docker) page. Under Docker Desktop, select Download for Windows with default options checked, and run. Should take about 5 minutes.
If you encounter the "WSL 2 installation incomplete" error:
1. Start PowerShell as Administrator
1. Run `dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart`
1. Run `dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart`
1. Install [WSL2 Linux kernel update package for x64 machines](https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi)
1. Run `wsl --set-default-version 2`
1. Restart your PC
1. The Docker Enginer will start up. Give it a few minutes. You now have the option of using the docker desktop app (GUI) and `docker` PowerShell/Bash commands
## Installation
Clone the repo on your computer and enter the folder:
```bash
git clone https://github.com/consuldemocracy/consuldemocracy.git
cd consuldemocracy
```
### macOS & Linux
Then lets create our secrets and database config files based on examples:
```bash
cp config/secrets.yml.example config/secrets.yml
cp config/database-docker.yml.example config/database.yml
```
Then you'll have to build the container with:
```bash
POSTGRES_PASSWORD=password docker-compose build
```
Start the database service:
```bash
POSTGRES_PASSWORD=password docker-compose up -d database
```
You can now initialize your development DB and populate it with:
```
POSTGRES_PASSWORD=password docker-compose run app rake db:create db:migrate
POSTGRES_PASSWORD=password docker-compose run app rake db:dev_seed
```
### Windows
Pending to be completed... Contributions Welcome!
## Running local Consul Democracy with Docker
### macOS & Linux
Now we can finally run the application with:
```bash
POSTGRES_PASSWORD=password docker-compose up
```
And you'll be able to access it at your browser visiting [http://localhost:3000](http://localhost:3000)
Additionally, if you want to run the rails console just run in another terminal:
```bash
POSTGRES_PASSWORD=password docker-compose run app rails console
```
To verify the containers are up execute:
```bash
docker ps .
```
You should see output similar to this:
![docker ps](https://i.imgur.com/ASvzXrd.png)
### Windows
Pending to be completed... Contributions Welcome!
## Having trouble?
Run these commands at **Consul Democracy's directory**, to erase all your previous Consul Democracy's Docker images and containers. Then restart the Docker [installation process](#installation):
1. Remove all Consul Democracy images:
```bash
docker-compose down --rmi all -v --remove-orphans
```
2. Remove all Consul Democracy containers
```bash
docker-compose rm -f -s -v
```
3. Verify if there is some container yet:
```bash
docker ps -a
```
Case positive, remove each one manually:
```bash
docker container rm <container_id>
```

View File

@@ -0,0 +1,9 @@
# Consul Democracy Documentation and guides
There are several guides where you can read very detailed information about Consul Democracy and its possibilities. You can find them all at: <http://consuldemocracy.org/en/#documentation>
- **Consul Democracy Use Guide**. In this guide you can see different ways to use Consul Democracy and examples of participation processes.
- **Consul Democracy Administration Guide**. This guide contains detailed information on the administration and management of Consul Democracy.
- **Consul Democracy Communication Guide**. This guide can give you an initial idea of how to plan communication campaigns to invite people to use your Consul Democracy platform. Communication is a key issue in getting relevant participation and engagement.
In addition to these guides you can access the [Consul Democracy Community](http://community.consulproject.org/), a discussion space to share more documentation, questions, learning, etc.

View File

@@ -0,0 +1,18 @@
# Generating your SSH keys
These instructions will help you generate a public key with which you can connect to the server without using a password.
In the terminal window, type:
```
ssh-keygen
```
When prompted for the file in which to save the key just press ENTER to leave the default. When prompted for a passphrase, just press ENTER again to leave this empty. At the end you should see a message like this:
```
Your identification has been saved in /your_home/.ssh/id_rsa.
Your public key has been saved in /your_home/.ssh/id_rsa.pub.
```
Take note of the **id_rsa.pub** file location, because youll need the content of this file later.

View File

@@ -0,0 +1,5 @@
# Installer
## Installation notes for Production and Staging servers
Check out the [installer's README](https://github.com/consuldemocracy/installer).

View File

@@ -0,0 +1,11 @@
# Introduction
These are our recommendations for the different environments and purposes:
- To setup Consul Democracy for a production environment we recommend using the [installer](https://github.com/consuldemocracy/installer).
- For developers working on a Consul Democracy fork we recommend using a UNIX based system (Linux or Mac) and installing Consul Democracy [locally system wide](local_installation.md).
- If you run into problems configuring Consul Democracy locally system wide and would like to show Consul Democracy for demo purposes we recommend using [Docker](docker.md) in a local machine.
- We also have a [Heroku guide](deploying-on-heroku.md) which can be used for demo purposes in a remote server.

View File

@@ -0,0 +1,73 @@
# Local installation
Before installing Consul Democracy and having it up and running make sure you all [prerequisites](prerequisites.md) installed.
1. First, clone the [Consul Democracy Github repository](https://github.com/consuldemocracy/consuldemocracy/) and enter the project folder:
```bash
git clone https://github.com/consuldemocracy/consuldemocracy.git
cd consuldemocracy
```
2. Install the Ruby version we need with your Ruby version manager. Here are some examples:
```bash
rvm install `cat .ruby-version` # If you're using RVM
rbenv install `cat .ruby-version` # If you're using rbenv
asdf install ruby `cat .ruby-version` # If you're using asdf
```
3. Check we're using the Ruby version we've just installed:
```bash
ruby -v
=> # (it should be the same as the version in the .ruby-version file)
```
4. Install [Bundler](http://bundler.io/):
```bash
gem install bundler --version 1.17.1
```
5. Install the required gems using Bundler:
```bash
bundle
```
6. Copy the environment example configuration files inside new readable ones:
```bash
cp config/database.yml.example config/database.yml
cp config/secrets.yml.example config/secrets.yml
```
And setup database credentials with your `consul` user in your new `database.yml` file.
7. Run the following [Rake tasks](https://github.com/ruby/rake) to create and fill your local database with the minimum data needed to run the application:
```bash
bin/rake db:create
bin/rake db:setup
bin/rake db:dev_seed
bin/rake db:test:prepare
```
8. Check everything is fine by running the test suite (beware it might take more than an hour):
```bash
bin/rspec
```
9. Now you have all set, run the application:
```bash
bin/rails s
```
Congratulations! Your local Consul Democracy application will be running now at `http://localhost:3000`.
In case you want to access the local application as admin, a default user verified and with admin permissions was created by the seed files with **username** `admin@consul.dev` and **password** `12345678`.
If you need an specific user to perform actions such as voting without admin permissions, a default verified user is also available with **username** `verified@consul.dev` and **password** `12345678`.

View File

@@ -0,0 +1,103 @@
# Configuration for development and test environments (macOS)
## Homebrew
Homebrew is a very popular package manager for OS X. It's advised to use it since it makes the installation of some of the dependencies much easier.
You can find the installation instructions at: [brew.sh](http://brew.sh)
## XCode and XCode Command Line Tools
To install *git* you'll first need to install *Xcode* (download it from the Mac App Store) and its *Xcode Command Line Tools* (you can install them from the Xcode's app menu)
## Git and Github
You can download git from: [git-scm.com/download/mac](https://git-scm.com/download/mac)
## Ruby version manager
OS X already comes with a preinstalled Ruby version, but it's quite old and we need a newer one. One of the multiple ways of installing Ruby in OS X is through *rbenv*. The installation instructions are in its GitHub repository and are pretty straight-forward:
[github.com/rbenv/rbenv](https://github.com/rbenv/rbenv)
## Node.js
To compile the assets, you'll need a JavaScript runtime. OS X comes with an integrated runtime called `Apple JavaScriptCore` but Node.js is the preferred option.
To install it, you can use [n](https://github.com/tj/n)
Run the following command on your terminal:
```
curl -L https://git.io/n-install | bash -s -- -y lts
```
And it will install the latest LTS (Long Term Support) Node version on your `$HOME` folder automatically (This makes use of [n-install](https://github.com/mklement0/n-install))
## PostgreSQL (>=9.4)
```
brew install postgres
```
Once installed, we need to *initialize* it:
```
initdb /usr/local/var/postgres
```
Now we're going to configure some things related to the *default user*. First we start postgres server with:
```
postgres -D /usr/local/var/postgres
```
At this point we're supposed to have postgres correctly installed and a default user will automatically be created (whose name will match our username). This user hasn't got a password yet.
If we run `psql` we'll login into the postgres console with the default user. Probably it will fail since its required that a default database exists for that user. We can create it by typing:
```
createdb 'your_username'
```
If we run `psql` again we should now get access to postgres console. With `\du` you can see the current users list.
In case you want to set a password for your user you can make it through postgres console by:
```
ALTER USER your_username WITH PASSWORD 'your_password';
```
Now we'll create the *consul* user, the one the application is using. Run in postgres console:
```
CREATE ROLE consul WITH PASSWORD '000';
ALTER ROLE consul WITH SUPERUSER;
ALTER ROLE consul WITH login;
```
If at any point during PostgreSQL installation you feel you have messed things up, you can uninstall it and start again by running:
```
brew uninstall postgres
```
You'll have to delete also this directory (otherwise the new installation will generate conflicts, source: [gist.github.com/lxneng/741932](https://gist.github.com/lxneng/741932)):
```
rm -rf /usr/local/var/postgres
```
## ChromeDriver
```
brew install chromedriver
```
## Imagemagick
```
brew install imagemagick
```
Now that we have all the dependencies installed we can go ahead and [install Consul Democracy](local_installation.md).

View File

@@ -0,0 +1,38 @@
# Mail Server Configuration
This is an example of how to integrate a mailing service with Consul Democracy.
In this example we use [Mailgun](https://www.mailgun.com/).
## Create an account in Mailgun
![Creating an account in Mailgun](../../img/mailserver/mailgun-create-account.png)
* Skip the credit card form
* And activate your account with the link sent by email
## Domain configuration
* Go to the Domains section: ![Mailgun domain section](../../img/mailserver/mailgun-domains.png)
* Since you don't have a domain yet, you should click in the sandbox that is already created
* Remember the following credentials: ![Mailgun sandbox](../../img/mailserver/mailgun-sandbox.png)
## Consul Democracy mailing configuration
* Go to the `config/secrets.yml` file
* Change the lines on the file to configure the mail server under the section `staging`, `preproduction` or `production`, depending on your setup:
```yml
mailer_delivery_method: :smtp
smtp_settings:
:address: "<smtp address>"
:port: 587
:domain: "<domain>"
:user_name: "<user_name>"
:password: "<password>"
:authentication: "plain"
:enable_starttls_auto: true
```
* Fill `<smtp address>`, `<domain>`, `<user_name>` and `<password>` with your information
* Save the file and restart your Consul Democracy application

View File

@@ -0,0 +1,94 @@
# Manual installation for production
**WARNING:** This method is *not recommended* and not officially supported, since you should use the [installer](https://github.com/consuldemocracy/installer) instead. Use this method if the installer isn't an option and you can already deal with PostgreSQL, puma or passenger, NGNIX and SSL (with letsencrypt, for instance).
This guide assumes you've already [installed all the necessary packages](prerequisites.md) on your system.
The created directory structure herein is to be used with [capistrano](https://capistranorb.com/documentation/getting-started/structure/).
## Folder structure
First, create the main folder, clone the repo to a repo directory, and create the needed folders:
```
mkdir consul
cd consul
git clone --mirror https://github.com/consuldemocracy/consuldemocracy.git repo
mkdir releases shared
mkdir shared/log shared/tmp shared/config shared/public shared/storage
mkdir -p shared/public/assets shared/public/system shared/public/ckeditor_assets shared/public/machine_learning/data
```
## Initial release
Extract from the repo the first release to the respective directory, and create the symbolic link of the current release (replace `<latest_consuldemocracy_stable_version>` with the latest version number, like 1.3.1 or 1.4.1):
```
cd repo
git archive <latest_consuldemocracy_stable_version> | tar -x -f - -C ../releases/first
cd ..
ln -s releases/first current
```
## Gems installation
Install the gems Consul Democracy depends on:
```
cd releases/first
bundle install --path ../../shared/bundle --without development test
cd ../..
```
## Configuration files
Generate the `database.yml` and `secrets.yml` files:
```
cp current/config/secrets.yml.example shared/config/secrets.yml
cp current/config/database.yml.example shared/config/database.yml
cd releases/first/config
ln -s ../../../shared/config/database.yml
ln -s ../../../shared/config/secrets.yml
cd ../../..
```
Edit the `shared/config/database.yml` file, filling in `username` and `password` with the data generated during the [PostgreSQL setup](debian.md#postgresql-94).
We now need to generate a secret key:
```
cd current
bin/rake secret RAILS_ENV=production
cd ..
```
Copy that generated key, and edit the `shared/config/secrets.yml` file; under the section `production`, change the following data:
```
secret_key_base: enter_the_secret_key_you_have_just_generated
server_name: enter_your_domain
```
If you aren't using a SSL certificate, replace the line saying `force_ssl: true` with `force_ssl: false`.
## Database setup
Create a database, load the seeds and compile the assets:
```
cd current
bin/rake db:migrate RAILS_ENV=production
bin/rake db:seed RAILS_ENV=production
bin/rake assets:precompile RAILS_ENV=production
```
## Starting the application
And, finally, start the Rails server:
```
bin/rails s -e production
```
Congratulations! Your server is now running in the production environment :smile:.

View File

@@ -0,0 +1,6 @@
# Prerequisites Installation
* [Ubuntu Linux](ubuntu.md)
* [Debian Linux](debian.md)
* [MacOS](macos.md)
* [Windows](windows.md)

View File

@@ -0,0 +1,21 @@
# Production and Staging servers
## Recommended Minimum System Requirements
### 1. Production Server
- Distribution: Ubuntu 16.04.X
- RAM: 32GB
- Processor: Quad core
- Hard Drive: 20 GB
- Database: Postgres
### 2. Staging Server
- Distribution: Ubuntu 16.04.X
- RAM: 16GB
- Processor: Dual core
- Hard Drive: 20 GB
- Database: Postgres
If your city has a population of over 1.000.000, consider balancing your load using 2-3 production servers and a separate server for the database.

View File

@@ -0,0 +1,111 @@
# Configuration for development and test environments (Ubuntu 18.04)
## System update
Run a general system update:
```bash
sudo apt update
```
## Git
Git is officially maintained in Ubuntu:
```bash
sudo apt install git
```
## Ruby version manager
Ruby versions packaged in official repositories are not suitable to work with Consul Democracy, so we'll have to install it manually.
First, we need to install Ruby's development dependencies:
```bash
sudo apt install libssl-dev autoconf bison build-essential libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm5 libgdbm-dev
```
The next step is installing a Ruby version manager, like rbenv:
```bash
wget -q https://github.com/rbenv/rbenv-installer/raw/master/bin/rbenv-installer -O- | bash
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
source ~/.bashrc
```
## Node.js
To compile the assets, you'll need a JavaScript runtime. Node.js is the preferred option.
Run the following command on your terminal:
```bash
sudo apt install nodejs
```
## PostgreSQL
Install postgresql and its development dependencies with:
```bash
sudo apt install postgresql libpq-dev
```
You also need to configure a user for your database. As an example, we'll choose the username "consul":
```bash
sudo -u postgres createuser consul --createdb --superuser --pwprompt
```
To make sure the UTF-8 enconding is used, create a file:
```
sudo nano /etc/profile.d/lang.sh
```
Add the following:
```
export LANGUAGE="en_US.UTF-8"
export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
```
Reconfigure Postgres to use the UTF-8 encoding:
`````
sudo su - postgres
psql
update pg_database set datistemplate=false where datname='template1';
drop database Template1;
create database template1 with owner=postgres encoding='UTF-8'
lc_collate='en_US.utf8' lc_ctype='en_US.utf8' template template0;
update pg_database set datistemplate=true where datname='template1';
\q
exit
`````
## Imagemagick
Install Imagemagick:
```bash
sudo apt install imagemagick
```
## ChromeDriver
To run E2E integration tests, we use Selenium along with Headless Chrome.
To get it working, install the chromium-chromedriver package and make sure it's available on your shell's PATH:
```bash
sudo apt install chromium-chromedriver
sudo ln -s /usr/lib/chromium-browser/chromedriver /usr/local/bin/
```
Now you're ready to go [get Consul Democracy installed](local_installation.md)!

View File

@@ -0,0 +1,87 @@
# Using AWS S3 as file storage
While Consul Democracy keeps most of its data in a PostgreSQL database, all the files such as documents or images have to be stored elsewhere.
To take care of them, Consul Democracy uses the [Paperclip gem](https://github.com/thoughtbot/paperclip) (Warning: this gem is now deprecated and Consul Democracy will probably migrate to ActiveStorage in the future. Check that this is not already the case before using this guide).
By default, the attachments are stored on the filesystem. However, with services such as Heroku, there is no persistent storage which means that these files are periodically erased.
This tutorial explains how to configure Paperclip to use [AWS S3](https://aws.amazon.com/fr/s3/). It doesn't recommend S3 or the use of Amazon services and will hopefully be expanded to include configuration for [fog storage](http://fog.io/storage/).
## Adding the gem *aws-sdk-s3*
First, add the following line in your *Gemfile_custom*
```
gem 'aws-sdk-s3', '~> 1'
```
Make sure to have a recent version of paperclip (Consul Democracy is currently using 5.2.1, which doesn't recognize *aws-sdk-s3*). In your Gemfile, the line should be:
```
gem 'paperclip', '~> 6.1.0'
```
Run `bundle install` to apply your changes.
## Adding your credentials in *secrets.yml*
This guide will assume that you have an Amazon account configured to use S3 and that you created a bucket for your instance of Consul Democracy. It is highly recommended to use a different bucket for each instance (production, preproduction, staging).
You will need the following information:
- the **name** of the S3 bucket
- the **region** of the S3 bucket (`eu-central-1` for UE-Francfort for example)
- the **hostname** of the S3 bucket (`s3.eu-central-1.amazonaws.com` for Francfort, for example)
- an **access key id** and a **secret access key** with read/write permission to that bucket
**WARNING:** It is recommended to create IAM users that will only have read/write permission to the bucket you want to use for that specific instance of Consul Democracy.
Once you have these pieces of information, you can save them as environment variables of the instance running Consul Democracy. In this tutorial, we save them respectively as *AWS_S3_BUCKET*, *AWS_S3_REGION*, *AWS_S3_HOSTNAME*, *AWS_ACCESS_KEY_ID* and *AWS_SECRET_ACCESS_KEY*.
Add the following block in your *secrets.yml* file:
```
aws: &aws
aws_s3_region: <%= ENV["AWS_S3_REGION"] %>
aws_access_key_id: <%= ENV["AWS_ACCESS_KEY_ID"] %>
aws_secret_access_key: <%= ENV["AWS_SECRET_ACCESS_KEY"] %>
aws_s3_bucket: <%= ENV["AWS_S3_BUCKET"] %>
aws_s3_host_name: <%= ENV["AWS_S3_HOST_NAME"] %>
```
and `<<: *aws` under the environments which you want to use S3 with, for example:
```
production:
[...]
<<: *aws
```
## Configuring Paperclip
First, activate Paperclip's URI adapter by creating the file *config/initializers/paperclip.rb* with the following content:
```
Paperclip::UriAdapter.register
```
Finally, add the following lines in the environment file of the instance which you want to use S3 with. In production, you should for example edit *config/environments/production.rb*.
```
# Paperclip settings to store images and documents on S3
config.paperclip_defaults = {
storage: :s3,
preserve_files: true,
s3_host_name: Rails.application.secrets.aws_s3_host_name,
s3_protocol: :https,
s3_credentials: {
bucket: Rails.application.secrets.aws_s3_bucket,
access_key_id: Rails.application.secrets.aws_access_key_id,
secret_access_key: Rails.application.secrets.aws_secret_access_key,
s3_region: Rails.application.secrets.aws_s3_region,
}
}
```
You will need to restart to apply the changes.

View File

@@ -0,0 +1,45 @@
# Vagrant
Install [Vagrant](https://www.vagrantup.com/) and setup a virtual machine with [Linux](prerequisites.md)
Vagrant is compatible for [Debian](/en/installation/debian.md) and [Ubuntu](/en/installation/ubuntu.md).
## Browser configuration
To access the application through the browser at `localhost:3000` we must forward a port and run the rails server with a binding option:
## Port forwarding
Open the Vagrant configuration file:
```
nano Vagranfile
```
Find this line:
```
# config.vm.network "forwarded_port", guest: 80, host: 8080
```
And change it for this configuration:
```
config.vm.network "forwarded_port", guest: 3000, host: 3000
```
Reload your virtual machine:
```
vagrant reload
```
## Running the rails server
In your virtual machine, run the application server, binding to your local ip address:
```
bin/rails s -b 0.0.0.0
```
Now you should be able to see the application running in your browser at url `localhost:3000`! :tada:

View File

@@ -0,0 +1,3 @@
# Windows
Windows is not yet officially supported. Please install [Virtual Box](https://www.virtualbox.org/) to setup a virtual machine in [Linux](prerequisites.md).

View File

@@ -0,0 +1,46 @@
# Code of conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language.
* Being respectful of differing viewpoints and experiences.
* Gracefully accepting constructive criticism.
* Focusing on what is best for the community.
* Showing empathy towards other community members.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances.
* Trolling, insulting/derogatory comments, and personal or political attacks.
* Public or private harassment.
* Publishing others' private information, such as a physical or electronic address, without explicit permission.
* Other conduct which could reasonably be considered inappropriate in a professional setting.
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [consul@madrid.es](mailto:consul@madrid.es). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version].
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -0,0 +1,39 @@
# Contributing
We appreciate you want to help us by contributing to Consul Democracy. Here's a guide we made describing how to contribute changes to the project.
## Reporting an issue
If you have seen anything wrong in the platform performance or directly in the code, we encourage you to [open an issue in the Consul Democracy Github repository](https://github.com/consuldemocracy/consuldemocracy/issues/new).
Before doing it, **please take some time to check the [existing issues](https://github.com/consuldemocracy/consuldemocracy/issues) and make sure what you are about to report isn't already reported** by another person. In case someone else reported the same problem before, if you have more details about it you can write a comment in the issue page -a little more help can make a huge difference!
In order to write a new issue, take into account these few tips to make it easy to read and comprehend:
- Try to use a descriptive and to-the-point title.
- It's a good idea to include some sections -in case they're needed- such as: steps to reproduce the bug, expected behaviour/response, actual response or screenshots.
- Also it could be helpful to provide your operating system, browser version and installed plugins.
## Resolving an issue
[Issues in Consul Democracy](https://github.com/consuldemocracy/consuldemocracy/issues) labeled with `PRs-welcome` are well defined features ready to be implemented by whoever wants to do it. In the other hand, the `not-ready` label marks features or changes not well defined yet or subject to an internal decision, so we recommend not to try to resolve them until the admins come to a resolution.
We suggest to follow these steps to keep a good track of the changes you're about to make:
- First of all, add a comment to the issue to make everyone know you are going to work on it. If the issue has someone assigned it means that person is already solving it.
- Fork the project.
- Create a feature branch based on the `master` branch. To make it easier to identify, you can name it with the issue number followed by a concise and descriptive name (e.g. `123-fix_proposals_link`).
- Work in your branch committing there your changes.
- Make sure all tests are passing. In case you're extending or creating a new feature, consider adding its own specs.
- Once you've finished, send a **pull request** to the [Consul Democracy repository](https://github.com/consuldemocracy/consuldemocracy/) describing your solution to help us understand it. It's also important to tell what issue you're addressing, so specify it in the pull request description's first line (e.g. `Fixes #123`).
- Our core team will review your PR and suggest changes if necessary. If everything looks good, your changes will be merged :)
> **Working on your first Pull Request?** You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github).
## Other ways of contributing
We'll appreciate any kind of contribution to Consul Democracy. Even if you can't contribute to it coding, you still can:
- Create issues about any problem or error you've encountered.
- Help translate the platform to other languages you master at [Consul Democracy's Crowdin](https://crwd.in/consul).
- Help with [Consul Democracy's documentation](https://github.com/consuldemocracy/docs).

View File

@@ -0,0 +1,663 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (c) 2015 Ayuntamiento de Madrid
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

View File

@@ -0,0 +1,4 @@
# Open Source project
* [Code of conduct](code_of_conduct.md)
* [Contributing](contributing.md)

83
docs/es/README.md Normal file
View File

@@ -0,0 +1,83 @@
![Logotipo de CONSUL DEMOCRACY](../img/consul_logo.png)
# CONSUL DEMOCRACY
Aplicación de Participación Ciudadana y Gobierno Abierto
![Estado de los tests](https://github.com/consuldemocracy/consuldemocracy/workflows/tests/badge.svg)
[![Code Climate](https://codeclimate.com/github/consuldemocracy/consuldemocracy/badges/gpa.svg)](https://codeclimate.com/github/consuldemocracy/consuldemocracy)
[![Coverage Status](https://coveralls.io/repos/github/consuldemocracy/consuldemocracy/badge.svg?branch=master)](https://coveralls.io/github/consuldemocracy/consuldemocracy?branch=master)
[![Crowdin](https://d322cqt584bo4o.cloudfront.net/consul/localized.svg)](https://translate.consuldemocracy.org/)
[![License: AGPL v3](https://img.shields.io/badge/License-AGPL%20v3-blue.svg)](http://www.gnu.org/licenses/agpl-3.0)
[![Accessibility conformance](https://img.shields.io/badge/accessibility-WAI:AA-green.svg)](https://www.w3.org/WAI/eval/Overview)
[![A11y issues checked with Rocket Validator](https://rocketvalidator.com/badges/checked_with_rocket_validator.svg?url=https://rocketvalidator.com)](https://rocketvalidator.com/opensource)
[![Join the chat at https://gitter.im/consul/consul](https://badges.gitter.im/consul/consul.svg)](https://gitter.im/consul/consul?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Help wanted](https://img.shields.io/badge/help-wanted-brightgreen.svg?style=flat-square)](https://github.com/consuldemocracy/consuldemocracy/issues?q=is%3Aopen+label%3A"help+wanted")
Este es el repositorio de código abierto de la Aplicación de Participación Ciudadana CONSUL DEMOCRACY, creada originariamente por el Ayuntamiento de Madrid.
## Documentación
Por favor visita la documentación que está siendo completada en [https://docs.consuldemocracy.org](https://docs.consuldemocracy.org) para conocer más sobre este proyecto, cómo comenzar tu propio fork, instalarlo, personalizarlo y usarlo como administrador/mantenedor.
## Web CONSUL DEMOCRACY Project
Puedes acceder a la página principal del proyecto en [http://consuldemocracy.org](http://consuldemocracy.org) donde puedes encontrar documentación sobre el uso de la plataforma, videos y enlaces al espacio de la comunidad.
## Configuración para desarrollo y tests
**NOTA**: para unas instrucciones más detalladas consulta la [documentación](https://docs.consuldemocracy.org)
Prerequisitos: tener instalado git, Ruby 3.0.6, CMake, pkg-config, shared-mime-info, Node.js y PostgreSQL (9.5 o superior).
```bash
git clone https://github.com/consuldemocracy/consuldemocracy.git
cd consuldemocracy
bundle install
cp config/database.yml.example config/database.yml
cp config/secrets.yml.example config/secrets.yml
bin/rake db:create
bin/rake db:migrate
bin/rake db:dev_seed
RAILS_ENV=test rake db:setup
```
Para ejecutar la aplicación en local:
```
bin/rails s
```
Para ejecutar los tests:
```
bin/rspec
```
Puedes usar el usuario administrador por defecto del fichero seeds:
**user:** admin@consul.dev
**pass:** 12345678
Pero para ciertas acciones, como apoyar, necesitarás un usuario verificado, el fichero seeds proporciona uno:
**user:** verified@consul.dev
**pass:** 12345678
## Estado del proyecto
El desarrollo de esta aplicación comenzó el [15 de Julio de 2015](https://github.com/consuldemocracy/consuldemocracy/commit/8db36308379accd44b5de4f680a54c41a0cc6fc6) y el código fue puesto en producción el día 7 de Septiembre de 2015 en [decide.madrid.es](https://decide.madrid.es). Desde entonces se le añaden mejoras y funcionalidades constantemente. Las funcionalidades actuales se pueden consultar en la [la página del projecto](http://consuldemocracy.org/es) y las futuras funcionalidades en el [Roadmap](https://github.com/consuldemocracy/consuldemocracy/projects/6) y [el listado de issues](https://github.com/consuldemocracy/consuldemocracy/issues).
## Licencia
El código de este proyecto está publicado bajo la licencia AFFERO GPL v3 (ver [LICENSE-AGPLv3.txt](open_source/license.md))
## Contribuciones
Ver fichero [CONTRIBUTING_ES.md](https://github.com/consuldemocracy/consuldemocracy/blob/master/CONTRIBUTING_ES.md)
## Desarrollo en local con Docker
Puedes leer la guía en [https://consul_docs.gitbooks.io/docs/content/es/getting_started/docker.html](https://consul_docs.gitbooks.io/docs/content/es/getting_started/docker.html)

5
docs/es/book.json Normal file
View File

@@ -0,0 +1,5 @@
{
"gitbook": ">= 3.0.0",
"title": "Documentación Consul Democracy",
"description": "Aplicación de Gobierno Abierto y Participación Ciudadana"
}

View File

@@ -0,0 +1,25 @@
# Componentes
En el caso de los componentes, la personalización puede utilizarse para cambiar tanto la lógica (incluida en un archivo `.rb`) como la vista (incluida en un archivo `.erb`). Si solo quieres personalizar la lógica, por ejemplo del componente `Admin::TableActionsComponent`, crea el archivo `app/components/custom/admin/table_actions_component.rb` con el siguiente contenido:
```ruby
require_dependency Rails.root.join("app", "components", "admin", "table_actions_component").to_s
class Admin::TableActionsComponent
# Tu lógica personalizada aquí
end
```
Si, por el contrario, también quieres personalizar la vista, necesitas una pequeña modificación. En lugar del código anterior, utiliza:
```ruby
class Admin::TableActionsComponent < ApplicationComponent; end
require_dependency Rails.root.join("app", "components", "admin", "table_actions_component").to_s
class Admin::TableActionsComponent
# Tu lógica personalizada aquí
end
```
Esto hará que el componente utilice la vista en `app/components/custom/admin/table_actions_component.html.erb`. Puedes crear este archivo y personalizarlo según tus necesidades.

View File

@@ -0,0 +1,11 @@
# Customization
* [Introducción](introduction.md)
* [Traducciones y Textos](translations.md)
* [Imágenes](images.md)
* [Vistas y Estilos](views_and_styles.md)
* [Javascript](javascript.md)
* [Modelos](models.md)
* [Componentes](components.md)
* [Gemas](gems.md)
* [Adaptar la aplicación](overwriting.md)

View File

@@ -0,0 +1,9 @@
# Gemfile
Para agregar librerías (gems) nuevas puedes hacerlo en el fichero `Gemfile_custom`. Por ejemplo si quieres agregar la gema [rails-footnotes](https://github.com/josevalim/rails-footnotes) debes hacerlo agregandole
```ruby
gem 'rails-footnotes', '~> 4.0'
```
Y siguiendo el flujo clásico en Ruby on Rails (`bundle install` y seguir con los pasos específicos de la gema en la documentación)

View File

@@ -0,0 +1,17 @@
# Imágenes
Si quieres sobreescribir alguna imagen debes primero fijarte el nombre que tiene, por defecto se encuentran en `app/assets/images`. Por ejemplo si quieres modificar `app/assets/images/logo_header.png` debes poner otra con ese mismo nombre en el directorio `app/assets/images/custom`. Los iconos que seguramente quieras modificar son:
* apple-touch-icon-200.png
* icon_home.png
* logo_email.png
* logo_header.png
* map.jpg
* social_media_icon.png
* social_media_icon_twitter.png
## Mapa de la ciudad
Puedes encontrar el mapa de la ciudad en [`/app/assets/images/map.jpg`](https://github.com/consuldemocracy/consuldemocracy/blob/master/app/assets/images/map.jpg), simplemente reemplazalo con una imagen de los distritos de tu ciudad ([ejemplo](https://github.com/consuldemocracy/consuldemocracy/blob/master/app/assets/images/map.jpg)).
Después te recomendamos utilizar una herramienta online como <http://imagemap-generator.dariodomi.de/> o <https://www.image-map.net/> para generar las coordenadas para poder establecer un [image-map](https://www.w3schools.com/tags/tag_map.asp) sobre cada distrito. Estas coordenadas deben ser introducidas en la respectiva Geozona creada en el panel de administración (`/admin/geozones`)

View File

@@ -0,0 +1,147 @@
# Personalización
Puedes modificar Consul Democracy y ponerle tu propia imagen, para esto debes primero [crear tu propio fork](../getting_started/create.md).
Hemos creado una estructura específica donde puedes sobreescribir y personalizar la aplicación para que puedas actualizar sin que tengas problemas al hacer merge y se sobreescriban por error tus cambios. Intentamos que Consul Democracy sea una aplicación Ruby on Rails lo más plain vanilla posible para facilitar el acceso de nuevas desarrolladoras.
## Ficheros y directorios especiales
Para adaptar tu fork de Consul Democracy puedes utilizar alguno de los directorios `custom` que están en las rutas:
* `config/locales/custom/`
* `app/assets/images/custom/`
* `app/views/custom/`
* `app/controllers/custom/`
* `app/models/custom/`
Aparte de estos directorios también cuentas con ciertos ficheros para:
* `app/assets/stylesheets/custom.css`
* `app/assets/stylesheets/_custom_settings.css`
* `app/assets/javascripts/custom.js`
* `Gemfile_custom`
* `config/application.custom.rb`
## Traducciones remotas bajo demanda del usuario
Este servicio tiene como objetivo poder ofrecer todos los contenidos dinámicos de la aplicación (propuestas, debates, inversiones presupuestarias y comentarios) en diferentes idiomas sin la necesidad de que un usuario ó un administrador haya creado cada una de sus traducciones.
Cuando un usuario accede a una pantalla con un idioma donde parte del contenido dinámico que esta visualizando no tiene traducciones, dispondrá de un botón para solicitar la traducción de todo el contenido. Este contenido se enviará a un traductor automático (en este caso [Microsoft TranslatorText](https://azure.microsoft.com/es-es/products/cognitive-services/translator/)) y en cuanto se obtenga la respuesta, todas estas traducciones estarán disponibles para cualquier usuario.
### Como empezar
Para poder utilizar esta funcionalidad es necesario realizar los siguientes pasos:
1. Disponer de una api key para conectarse con el servicio de traducción. Para ello necesitamos una [cuenta en Azure](https://azure.microsoft.com/es-es/)
1. Una vez que haya iniciado sesión en el portal de Azure, subscríbase a Traductor en Cognitive Services.
1. Una vez subscrito al servicio de Translator Text, tendrá accesibles 2 api keys en la sección **Administración de recursos > Claves y punto de conexión** que serán necesarias para la configuración del servicio de traducciones en su aplicación.
### Configuración
Para activar el servicio de traducciones en su aplicación debe completar los siguientes pasos
#### Añadir api key en la aplicación
En el apartado anterior hemos comentado que una vez subscritos al servicio de traducciones disponemos de 2 api keys. Para configurar el servicio correctamente en nuestra aplicación deberemos añadir una de las dos api keys en el archivo `secrets.yml` en la sección `apis:` con la key `microsoft_api_key` como podemos ver en la siguiente imágen:
![Add api key to secrets](../../img/translations/remote_translations/add-api-key-to-secrets.png)
#### Activar funcionalidad
Una vez disponemos de la nueva key en el `secrets.yml` ya podemos proceder a activar la funcionalidad. Para activar la funcionalidad deberá realizar 2 pasos:
1. Ejecutar el siguiente comando `bin/rake settings:create_remote_translations_setting RAILS_ENV=production`
1. Acceder a través del panel de administración de su aplicación a la sección **Configuración > Funcionalidades** y activar el módulo de **Traducciones Remotas** como se puede ver a continuación:
![Active remote translations](../../img/translations/remote_translations/active-remote-translations-es.png)
### Funcionalidad
Una vez tenemos la api key en nuestro `secrets.yml` y el módulo activado, los usuarios ya podrán utilizar la funcionalidad.
Para aclarar el funcionamiento, se adjuntan unos pantallazos de como interactua la aplicación con nuestros usuarios:
* Cuando un usuario accede a una pantalla en un idioma en el que no están disponibles todas las traducciones, le aparecerá un texto en la parte superior de la pantalla y un botón para poder solicitar la traducción. (**Nota:** *En el caso de acceder con un idioma no soportado por el servicio de traducción no se mostrará ningún texto ni botón de traducción. Ver sección: Idiomas disponibles para la traducción remota*)
![Display text and button](../../img/translations/remote_translations/display-text-and-button-es.png)
* Una vez el usuario pulsa el botón de `Traducir página` se encolan las traducciones y se recarga la pantalla con un notice (*informando que se han solicitado correctamente las traducciones*) y un texto informativo en la cabecera (*explicando cuando podrá ver estas traducciones*).
![Display notice and text after enqueued translations](../../img/translations/remote_translations/display-notice-and-text-after-enqueued-es.png)
* Si un usuario accede a una pantalla que no dispone de traducciones pero ya han sido solicitadas por otro usuario. La aplicación no le mostrará el botón de traducir, pero si un texto informativo en la cabecera (*explicando cuando podrá ver estas traducciones*).
![Display text explaining that translations are pending](../../img/translations/remote_translations/display-text-translations-pending-es.png)
* Las peticiones de traducción se delegan a `Delayed Job` y en cuanto haya sido procesada, el usuario después de refrescar su página podrá ver el contenido traducido.
![Display translated content](../../img/translations/remote_translations/display-translated-content-es.png)
### Idiomas disponibles para la traducción remota
Actualmente estos son todos los [idiomas disponibles](https://api.cognitive.microsofttranslator.com/languages?api-version=3.0) en el servicio de traducción:
```yml
["af", "am", "ar", "as", "az", "ba", "bg", "bn", "bo", "bs", "ca", "cs", "cy", "da", "de", "dv", "el", "en", "es", "et", "eu", "fa", "fi", "fil", "fj", "fo", "fr", "fr-CA", "ga", "gl", "gu", "ha", "he", "hi", "hr", "hsb", "ht", "hu", "hy", "id", "ig", "ikt", "is", "it", "iu", "iu-Latn", "ja", "ka", "kk", "km", "kmr", "kn", "ko", "ku", "ky", "ln", "lo", "lt", "lug", "lv", "lzh", "mg", "mi", "mk", "ml", "mn-Cyrl", "mn-Mong", "mr", "ms", "mt", "mww", "my", "nb", "ne", "nl", "nso", "nya", "or", "otq", "pa", "pl", "prs", "ps", "pt", "pt-PT", "ro", "ru", "run", "rw", "sk", "sl", "sm", "sn", "so", "sq", "sr-Cyrl", "sr-Latn", "st", "sv", "sw", "ta", "te", "th", "ti", "tk", "tlh-Latn", "tlh-Piqd", "tn", "to", "tr", "tt", "ty", "ug", "uk", "ur", "uz", "vi", "xh", "yo", "yua", "yue", "zh-Hans", "zh-Hant", "zu"]
```
De todos los idiomas que actualmente tiene Consul Democracy definidos (`available_locales`) en `config/application.rb` el único que no está en la lista anterior y por lo tanto no se ofrece servicio de traducción es el valenciano `["val"]`.
### Costes
El servicio de traducción utilizado tiene los [precios](https://azure.microsoft.com/es-es/pricing/details/cognitive-services/translator/) más competitivos del mercado.
El precio por cada 1 Millón de caracteres traducidos asciende a 10 $ y sin ningún tipo de coste fijo al mes.
Aunque se han tomado medidas técnicas para evitar un mal uso de este servicio, recomendamos la creación de Alertas que ofrece Azure para que un Administrador pueda ser notificado en el caso de detectar un uso fuera de lo común del servicio. Este servicio tiene un coste de 0,10 $ al mes.
Para crear una Alerta en Azure debemos seguir los siguientes pasos:
1. Inicie sesión en **Azure Portal**.
1. Accede al servicio **Traductor** creado anteriormente.
1. Accede en el menu lateral a **Supervisión > Alertas**:
1. Accedemos a **Crear regla de alertas**
1. En **Selección de una señal** seleccionamos `Text Characters Translated`
1. Una vez seleccionada debemos definir la lógica de la Alerta para que se ajuste a nuestras necesidades. Ej: Rellene el campo "Operador" con el valor "Mayor que", rellene el campo "Tipo de Agregación" con el valor "Total" y por último rellene el campo "Valor del umbral" por el número de caracteres que consideramos que deben traducirse antes de ser notificados. En esta sección también se puede configurar el periodo de tiempo y la frecuencia de evaluación.
1. Para poder ser notificados tenemos que crear un **Grupo de Acciones** y asociarla a esta Alerta que estamos creando. Para ello accedemos al botón de **Crear** y rellenamos el formulario. Como se puede observar hay diferentes tipos de acciones, debemos seleccionar **Correo electrónico/SMS/Insertar/Voz** y configurar la opción que consideremos conveniente según nuestras necesidades.
1. Una vez creado este grupo de acciones, ya queda directamente asociado a la regla que estamos creando.
1. Por último ya solo queda añadir un nombre y clicar sobre el botón **Revisar y crear**
### Añadir un nuevo servicio de traducción
En el caso de que se quieran integrar más servicios de traducción por cualquier motivo (aparece un nuevo en el mercado más competitivo, se quiere cambiar para contemplar los idiomas que actualmente no tienen soporte, etc) se ha dejado preparado el código para poder añadirlo con las mínimas modificaciones posibles.
Esto es posible gracias a la class `RemoteTranslations::Caller` que es una capa intermedia entre la gestión de los contenidos sin traducir y el Cliente de traducción de Microsoft utilizado actualmente.
Una buena solución para añadir otro servicio de traducción sería sustituir la llamada al `MicrosoftTranslateClient` dentro del método `translations` del `RemoteTranslations::Caller` por el nuevo servicio implementado.
En caso de querer convivir con ambos sólo debería gestionarse en que caso queremos utilizar uno u otro, ya sea mediante condiciones especificas en el código o mediante una gestión en los Settings de la aplicación.
```ruby
class RemoteTranslationsCaller
...
def translations
@translations ||= RemoteTranslations::Microsoft::Client.new.call(fields_values, locale)
# Add new RemoteTranslations Client
# @translations = RemoteTranslations::NewTranslateClient::Client.new.call(fields_values, locale_to)
end
...
end
```
## Interfaz de traducción
Esta funcionalidad permite a los usuarios introducir contenidos dinámicos en diferentes idiomas a la vez. Cualquier usuario administrador de Consul Democracy puede activar o desactivar esta funcionalidad a través del panel de administración de la aplicación. Si desactivas esta funcionalidad (configuración de la funcionalidad por defecto) los usuarios sólo podrán introducir un idioma.
### Activar funcionalidad
Para activar la funcionalidad deberá realizar 2 pasos:
1. Ejecutar el siguiente comando `bin/rake settings:create_translation_interface_setting RAILS_ENV=production` (Este paso sólo es necesario para instalaciones de Consul Democracy existentes que incorporan esta funcionalidad, para nuevas instalaciones no es necesario)
1. Accedediendo como usuario administrador a través del panel de administración de su aplicación a la sección **Configuración > Funcionalidades** y activando el módulo de **Interfaz de traducción** como se puede ver a continuación:
![Active interface translations](../../img/translations/interface_translations/active-interface-translations-es.png)
### Casos de uso
Dependiendo de si activamos o desactivamos el módulo de **Interfaz de traducción** veremos los formularios accesibles por el usuario de la siguiente manera:
* Cuando la interfaz de traducción esta activa:
Como podemos ver en la imagen a continuación la interfaz de traducción tiene 2 selectores, el primero "Seleccionar idioma" permite cambiar entre los lenguajes activos y el segundo selector "Añadir idioma" permite añadir nuevos idiomas al formulario. Los campos traducibles se pueden distinguir fácilmente mediante un fondo azul de los que no lo son. También disponemos de un botón `Eliminar idioma` para eliminar un idioma en caso de necesitarlo. Si un usuario elimina accidentalmente un idioma puede recuperarlo añadiendo dicho idioma otra vez al formulario.
Esta funcionalidad está visible tanto para las páginas de creación como para las páginas de edición.
![Translations inteface enabled](../../img/translations/interface_translations/translations-interface-enabled-es.png)
* Cuando la interfaz de traducción esta desactivada:
Cuando esta funcionalidad está desactivada los formularios se renderizan sin la interfaz de traducción y sin resaltar los campos traducibles con fondo azul.
![Translations inteface enabled](../../img/translations/interface_translations/translations-interface-disabled-es.png)

View File

@@ -0,0 +1,15 @@
# Javascript
Si quieres agregar código Javascript puedes hacerlo en el fichero `app/assets/javascripts/custom.js`. Por ejemplo si quieres que salga una alerta puedes poner lo siguiente:
```js
$(function(){
alert('foobar');
});
```
Si trabajas con código coffeescript puedes revisarlo con [coffeelint](http://www.coffeelint.org/) (instalalo con `npm install -g coffeelint`) :
```bash
coffeelint .
```

View File

@@ -0,0 +1,75 @@
# Modelos
Si quieres agregar modelos nuevos, o modificar o agregar métodos a uno ya existente puedes hacerlo en `app/models/custom`. En el caso de los modelos antiguos debes primero hacer un require de la dependencia.
Por ejemplo en el caso del Ayuntamiento de Madrid se requiere comprobar que el código postal durante la verificación sigue un cierto formato (empieza con 280). Esto se realiza creando este fichero en `app/models/custom/verification/residence.rb`:
```ruby
require_dependency Rails.root.join('app', 'models', 'verification', 'residence').to_s
class Verification::Residence
validate :postal_code_in_madrid
validate :residence_in_madrid
def postal_code_in_madrid
errors.add(:postal_code, I18n.t('verification.residence.new.error_not_allowed_postal_code')) unless valid_postal_code?
end
def residence_in_madrid
return if errors.any?
unless residency_valid?
errors.add(:residence_in_madrid, false)
store_failed_attempt
Lock.increase_tries(user)
end
end
private
def valid_postal_code?
postal_code =~ /^280/
end
end
```
No olvides poner los tests relevantes en `spec/models/custom`, siguiendo con el ejemplo pondriamos lo siguiente en `spec/models/custom/residence_spec.rb`:
```ruby
require 'rails_helper'
describe Verification::Residence do
let(:residence) { build(:verification_residence, document_number: "12345678Z") }
describe "verification" do
describe "postal code" do
it "should be valid with postal codes starting with 280" do
residence.postal_code = "28012"
residence.valid?
expect(residence.errors[:postal_code].size).to eq(0)
residence.postal_code = "28023"
residence.valid?
expect(residence.errors[:postal_code].size).to eq(0)
end
it "should not be valid with postal codes not starting with 280" do
residence.postal_code = "12345"
residence.valid?
expect(residence.errors[:postal_code].size).to eq(1)
residence.postal_code = "13280"
residence.valid?
expect(residence.errors[:postal_code].size).to eq(1)
expect(residence.errors[:postal_code]).to include("In order to be verified, you must be registered in the municipality of Madrid.")
end
end
end
end
```

View File

@@ -0,0 +1,14 @@
# Adaptar application.rb
Cuando necesites extender o modificar el `config/application.rb` puedes hacerlo a través del fichero `config/application_custom.rb`. Por ejemplo si quieres modificar el idioma por defecto al inglés pondrías lo siguiente:
```ruby
module Consul
class Application < Rails::Application
config.i18n.default_locale = :en
config.i18n.available_locales = [:en, :es]
end
end
```
Recuerda que para ver reflejado estos cambios debes reiniciar el servidor de desarrollo.

View File

@@ -0,0 +1,39 @@
# Traducciones y Textos
## Traducciones
Actualmente Consul Democracy esta traducido total o parcialmente a multiples idiomas, visita el proyecto en [Crowdin](https://translate.consuldemocracy.org/)
[Únete a los traductores](https://crwd.in/consul) para ayudar a completar los existentes, o contacta con nosotros a través del [gitter de Consul Democracy](https://gitter.im/consul/consul) para convertirte en Revisor y validar las contribuciones de los traductores.
En el caso de que tu lenguage no este presente en el proyecto de Crowdin, por favor [abre una incicencia](https://github.com/consuldemocracy/consuldemocracy/issues/new?title=New language&body=Hello I would like to have my language INSERT YOUR LANGUAGE NAME added to Consul Democracy) y lo añadiremos rápidamente.
Si quieres ver las traducciones de los textos de la web, puedes encontrarlos en los ficheros formato YML disponibles en `config/locales/`. Puedes leer la [guía de internacionalización](http://guides.rubyonrails.org/i18n.html) de Ruby on Rails sobre como funciona este sistema.
## Textos personalizados
Dado que Consul Democracy está en evolución continua con nuevas funcionalidades, y para que mantener tu fork actualizado sea más sencillo, recomendamos no modificar los ficheros de traducciones, es una mejor idea "sobreescribirlos" usando ficheros personalizados en caso de necesidad de alterar un texto.
Así pues las adaptaciones las debes poner en el directorio `config/locales/custom/`, recomendamos poner solo los textos que quieras personalizar. Por ejemplo si quieres personalizar el texto de "Ayuntamiento de Madrid, 2016" que se encuentra en el footer en todas las páginas, primero debemos ubicar en que plantilla se encuentra (`app/views/layouts/_footer.html.erb`), vemos que en el código pone lo siguiente:
```ruby
<%= t("layouts.footer.copyright", year: Time.current.year) %>
```
Y que en el fichero `config/locales/es/general.yml` sigue esta estructura (solo ponemos lo relevante para este caso):
```yml
es:
layouts:
footer:
copyright: Ayuntamiento de Madrid, %{year}
```
Si creamos el fichero `config/locales/custom/es/general.yml` y modificamos "Ayuntamiento de Madrid" por el nombre de la organización que se este haciendo la modificación. Recomendamos directamente copiar los ficheros `config/locales/` e ir revisando y corrigiendo las que querramos, borrando las líneas que no querramos traducir.
## Mantener tus Textos Personalizados y Lenguajes
Consul Democracy tiene la gema [i18n-tasks](https://github.com/glebm/i18n-tasks), es una herramienta estupenda para gestionar textos i18n. Prueba en tu consola `i18n-tasks health` para ver un reporte de estado.
Si tienes un lenguaje propio diferente al Inglés, deberias añadirlo al fichero de configuración [i18n-tasks.yml para las variables `base_locale` y `locales`](https://github.com/consuldemocracy/consuldemocracy/blob/master/config/i18n-tasks.yml#L4-L7) de forma que los ficheros de tu idioma también sean comprobados.

View File

@@ -0,0 +1,33 @@
# Vistas y Estilos
## Vistas (HTML)
Si quieres modificar el HTML de alguna página puedes hacerlo copiando el HTML de `app/views` y poniendolo en `app/views/custom` respetando los subdirectorios que encuentres ahí. Por ejemplo si quieres modificar `app/views/pages/conditions.html` debes copiarlo y modificarla en `app/views/custom/pages/conditions.html.erb`
## Estilos CSS con SASS
Si quieres cambiar algun selector CSS (de las hojas de estilo) puedes hacerlo en el fichero `app/assets/stylesheets/custom.scss`. Por ejemplo si quieres cambiar el color del header (`.top-links`) puedes hacerlo agregando:
```css
.top-links {
background: red;
}
```
Si quieres cambiar alguna variable de [foundation](http://foundation.zurb.com/) puedes hacerlo en el fichero `app/assets/stylesheets/_custom_settings.scss`. Por ejemplo para cambiar el color general de la aplicación puedes hacerlo agregando:
```css
$brand: #446336;
```
Usamos un preprocesador de CSS, [SASS, con la sintaxis SCSS](http://sass-lang.com/guide).
Además puedes comprobar la sintaxis de tus ficheros scss con:
```bash
scss-lint
```
## Accesibilidad
Para mantener el nivel de accesibilidad, si añades colores nuevos utiliza un [Comprobador de contraste de color](http://webaim.org/resources/contrastchecker/) (WCAG AA es obligatorio, WCAG AAA es recomendable)

View File

@@ -0,0 +1,156 @@
# Configurar conexión con el Censo
Este servicio tiene como objetivo poder configurar la conexión con el Censo de Ayuntamiento a través del panel de Administración sin necesidad de modificar el código de la aplicación.
Cabe destacar que para configurar correctamente esta conexión se requerirá de un perfil técnico que conozca el WebService de su Ayuntamiento.
Actualmente la aplicación estaba pensada para enviar solo el **numero de documento** y el **tipo de documento**. Con esta nueva funcionalidad se habilita la posibilidad de enviar en caso de ser necesario los campos **fecha de nacimiento** y **código postal**
## Activar la funcionalidad
En la sección **Configuración > Configuración Global** se ha añadido una nueva pestaña **Configuración del Censo Remoto**.
Si tenemos la funcionalidad desactivada veremos un texto informativo que nos indicará como activarla:
![Feature disabled](../../img/remote_census/feature-disabled-es.png)
Para activar la funcionalidad deberá seguir las instrucciones de la imagen anterior:
1. Acceder a través del panel de administración de su aplicación a la sección **Configuración > Funcionalidades** y activar el módulo de **Configurar conexión al censo remoto (SOAP)** como se puede ver a continuación:
![Feature enabled](../../img/remote_census/feature-enabled-es.png)
## Configuración
Una vez activada la funcionalidad, podremos acceder a la sección **Configuración > Configuración Global** y clicar en la pestaña **Configuración del Censo Remoto**.
En esta pantalla se podrá rellenar toda la información necesaria para poder configurar la conexión con el Censo de cada Ayuntamiento.
La información a rellenar esta dividida en tres apartados:
1. **Información General**
- **Endpoint**: Nombre del host donde se encuentra el servicio del Censo con el que queremos conectarnos (wsdl).
![General information - Endpoint](../../img/remote_census/general-information-endpoint-es.png)
1. **Información para realizar la Petición**
En esta sección rellenaremos todos los campos necesarios para poder realizar una petición para verificar un usuario contra el Censo del Ayuntamiento.
![Request Data](../../img/remote_census/request-data-es.png)
Para ayudar a entender como rellenar cada uno de los campos, nos basaremos en un supuesto WebService que recibe un método llamado `:get_habita_datos` con la siguiente estructura:
```
{
request: {
codigo_institucion: 12, #Valor estático
codigo_portal: 5, #Valor estático
codigo_usuario: 10, #Valor estático
documento: 12345678Z, #Valor dinámico relacionado con Número de Documento
tipo_documento: 1, #Valor dinámico relacionado con Tipo de Documento
codigo_idioma: 102, #Valor estático
nivel: 3 #Valor estático
}
}
```
Campos necesarios para la petición:
- **Nombre del método de la petición**: Nombre del método que acepta el WebService del Censo del Ayuntamiento.
Ejemplo:
![Request Data - Method name](../../img/remote_census/request-data-method-name-es.png)
- **Estructura de la petición**: Estructura de la petición que recibe el WebService del Censo del Ayuntamiento. Los valores "fijos" de esta petición deberán informarse. Los valores "dinámicos" relacionados con Tipo de Documento, Número de Documento, Fecha de Nacimiento y Código Postal deberán dejarse con valor null.
Ejemplo:
![Request Data - Structure](../../img/remote_census/request-data-structure-es.png)
![Request Data - Structure](../../img/remote_census/request-data-structure-info-es.png)
- **Ruta para Tipo de Documento**: Ruta donde se encuentra el campo en la estructura de la petición que envía el Tipo de Documento.
*NOTA: NO RELLENAR en caso de que el WebService no requiera el Tipo de Documento para verificar un usuario.*
Ejemplo:
![Request Data - Path document type](../../img/remote_census/request-data-path-document-type-es.png)
- **Ruta para Número de Documento**: Ruta donde se encuentra campo en la estructura de la petición que envía el Número de Documento.
*NOTA: NO RELLENAR en caso de que el WebService no requiera el Número de Documento para verificar un usuario.*
Ejemplo:
![Request Data - Path document number](../../img/remote_census/request-data-path-document-number-es.png)
- **Ruta para Fecha de Nacimiento**: Ruta donde se encuentra campo en la estructura de la petición que envía la Fecha de Nacimiento.
*NOTA: NO RELLENAR en caso de que el WebService no requiera la Fecha de Nacimiento para verificar un usuario.*
En el caso del *Ejemplo* lo dejaríamos en blanco, ya que no se necesita enviar la fecha de nacimiento para verificar a un usuario.
Ejemplo:
![Request Data - Path date of birth](../../img/remote_census/request-data-path-date-of-birth-es.png)
- **Ruta para Código Postal**: Ruta donde se encuentra campo en la estructura de la petición que envía el Código Postal.
*NOTA: NO RELLENAR en caso de que el WebService no requiera el Código Postal para verificar un usuario.*
En el caso del *Ejemplo* lo dejaríamos en blanco, ya que no se necesita enviar el código postal para verificar a un usuario.
Ejemplo:
![Request Data - Path postal code](../../img/remote_census/request-data-path-postal-code-es.png)
1. **Información para parsear la respuesta**
En esta sección configuraremos todos los campos necesarios para poder recibir la respuesta del WebService y verificar a un usuario en la aplicación.
![Response Data](../../img/remote_census/response-data-es.png)
Al igual que en el apartado anterior definiremos un ejemplo de respuesta, para ayudar a entender como rellenar cada uno de los campos de esta sección.
```
{
get_habita_datos_response: {
get_habita_datos_return: {
datos_habitante: {
item: {
fecha_nacimiento_string: "31-12-1980",
identificador_documento: "12345678Z",
descripcion_sexo: "Varón",
nombre: "José",
apellido1: "García"
}
},
datos_vivienda: {
item: {
codigo_postal: "28013",
codigo_distrito: "01"
}
}
}
}
}
```
Campos necesarios para parsear la respuesta:
- **Ruta para la Fecha de Nacimiento**: En que ruta de la respuesta se encuentra la Fecha de Nacimiento.
Ejemplo:
![Response Data - Path date of birth](../../img/remote_census/response-data-path-date-of-birth-es.png)
- **Ruta para el Código Postal**: En que ruta de la respuesta se encuentra el Código Postal.
Ejemplo:
![Response Data - Path postal code](../../img/remote_census/response-data-path-postal-code-es.png)
- **Ruta para el Distrito**: En que ruta de la respuesta se encuentra el Distrito.
Ejemplo:
![Response Data - Path district](../../img/remote_census/response-data-path-district-es.png)
- **Ruta para el Género**: En que ruta de la respuesta se encuentra el Género.
Ejemplo:
![Response Data - Path Gender](../../img/remote_census/response-data-path-gender-es.png)
- **Ruta para el Nombre**: En que ruta de la respuesta se encuentra Nombre.
Ejemplo:
![Response Data - Path Name](../../img/remote_census/response-data-path-name-es.png)
- **Ruta para el Apellido**: En que ruta de la respuesta se encuentra el Apellido
Ejemplo:
![Response Data - Path Last Name](../../img/remote_census/response-data-path-last-name-es.png)
- **Condición para detectar una respuesta válida**: Que ruta de la respuesta tiene que venir informado para considerarse una respuesta válida.
Ejemplo:
![Response Data - Path valid response](../../img/remote_census/response-data-path-valid-response-es.png)
Una vez rellenados correctamente los datos generales, los campos necesarios de la petición y "todos" los campos para validar la respuesta, la aplicación podrá verificar cualquier usuario contra el WebService definido.

View File

@@ -0,0 +1,7 @@
# Funcionalidades Técnicas
* [OAuth](oauth.md)
* [GraphQL](graphql.md)
* [Recomendaciones](recommendations.md)
* [Configurar conexión con el Censo](census_configuration.md)
* [Censo Local](local_census.md)

View File

@@ -0,0 +1,123 @@
# Globalize
Sigue estos pasos para añadir [Globalize](https://github.com/globalize/globalize) a un modelo de la aplicación (también se hace uso de la gema [`globalize_accessors`](https://github.com/globalize/globalize-accessors)).
## 1. Definir los atributos a traducir
Hay que definir los atributos que se quieran traducir en el modelo. Para ello, hay que añadir la opción `translates` seguida de los nombres de los atributos.
También deberemos añadir la opción `globalize_accessors` con todos aquellos locales a los que queramos tener acceso. Esta gema generará los métodos `title_en`, `title_es`, etc., y que se usan en la aplicación. Si lo que quieres es incluir **todos** los campos traducidos en **todos** los idiomas definidos en tu aplicación, puedes llamar a `globalize_accessors` sin ninguna opción (tal y como se explica en la [documentación](https://github.com/globalize/globalize-accessors#example)).
```
# Suponiendo un modelo Post con attributos title y text
class Post < ActiveRecord::Base
translates :title, :text
globalize_accessors locales: [:en, :es, :fr, :nl, :val, :pt_br]
end
```
## 2. Crear la migración para generar la tabla de traducciones
Hay que crear una migración para generar la tabla donde se almacenarán todas las traducciones de ese modelo. La tabla deberá tener una columna por cada atributo que queramos traducir. Para migrar los datos ya almacenados (en la tabla original), hay que añadir la opción `:migrate_data => true` en la propia migración:
```
class AddTranslatePost < ActiveRecord::Migration
def self.up
Post.create_translation_table!({
title: :string,
text: :text
}, {
:migrate_data => true
})
end
def self.down
Post.drop_translation_table! :migrate_data => true
end
end
```
## 3. Añadir el módulo `Translatable`
Añadir el módulo `Translatable` en el controlador que vaya a gestionar las traducciones.
```
class Post < Admin::BaseController
include Translatable
...
```
Hay que asegurarse de que este controlador tiene las funciones `resource_model` y `resource`, que devuelven el nombre del modelo y el objeto para el que se van a gestionar las traducciones, respectivamente.
```
...
def resource_model
Post
end
def resource
@post = Post.find(params[:id])
end
...
```
## 4. Añadir los parámetros de las traducciones a los parámetros permitidos
Añadir como parámetros permitidos aquellos que estén dedicados a las traducciones. Para eso, el módulo `Translatable` posee una función llamada `translation_params(params)`, a la que se le pasan el parámetro del objeto. A partir de esos parámetros, y teniendo en cuenta los idiomas definidos para ese modelo, la función devuelve aquellos parámetros que contengan un valor.
```
# Siguiendo con el ejemplo, en este caso se le pasarían los parámetros params[:post], porque es el
# hash que contiene toda la información.
attributes = [:title, :description]
params.require(:post).permit(*attributes, translation_params(params[:post]))
```
## 5. Añadir los campos a traducir en los formularios
Añadir los campos a los formularios de creación y edición para poder crear las traducciones. Recordar que, para esto, existe una función en el helper que engloba la lógica de `Globalize.with_locale` en un bloque llamado `globalize(locale) do`.
Los campos que vayan a editar la información a traducir deberán llamarse `<nombre_attributo>_<locale>`, por ejemplo `title_en`, de manera que, cuando esa información llegue al servidor, el helper pueda clasificar los parametros.
Recuerda que, para evitar errores al usar locales como `pt-BR`, `es-ES`, etc. (aquellos cuya región está especificada por '-'), hay que utilizar la función `neutral_locale(locale)`, definida en el `GlobalizeHelper`. Esta función convierte este tipo de locales en minúsculas con guiones bajos, con lo que `pt-BR` pasará a ser `pt_br`. Este formato es compatible con `globalize_accessor`, al contrario que el oficial, puesto que los métodos generados tendrían el nombre `title_pt-BR`, que es un formato erróneo. Al usar esa función, el método pasará a llamarse `title_pt_br`, que es correcto, y, además, no genera conflictos en las vistas a la hora de comparar el locale `pt-BR` con el modificado `pt_br`. Se usará siempre el segundo.
## 6. Añadir los parámetros ocultos para borrar traducciones
Al formulario que se use para editar las traducciones se le deberá añadir el parámetro oculto que las marca para que se borren:
```
<%= hidden_field_tag "delete_translations[#{locale}]", 0 %>
```
También habrá que añadir el link de "Eliminar idioma", que deberá tener:
- un id con el formato `delete-<locale neutro>`, siendo "locale neutro" el resultado de la función `neutral_locale(locale)`.
- un atributo `data-locale` con el valor de `neutral_locale(locale)`.
- la clase `delete-language`.
```
<%= link_to t("admin.milestones.form.remove_language"), "#",
id: "delete-#{neutral_locale(locale)}",
class: 'delete-language',
data: { locale: neutral_locale(locale) } %>
```
Los estilos de CSS y el resto de clases que se le quieran añadir dependerán de la interfaz que se haya diseñado para gestionar esas traducciones (si se debe ocultar o no dependiendo del idioma seleccionado, por ejemplo).
## 7. Añadir al `dev_seed` las traducciones del nuevo modelo
Para que se generen cuando se restablezca la base de datos. Por ejemplo, para crear un post cuya descripción está traducida:
```
section "Creating post with translations" do
post = Post.new(title: title)
I18n.available_locales.map do |locale|
neutral_locale = locale.to_s.downcase.underscore.to_sym
Globalize.with_locale(neutral_locale) do
post.description = "Description for locale #{locale}"
post.save
end
end
end
```

431
docs/es/features/graphql.md Normal file
View File

@@ -0,0 +1,431 @@
# Documentación de la API
* [Características](#caracteristicas)
* [GraphQL](#graphql)
* [Haciendo peticiones a la API](#haciendo-peticiones-a-la-api)
* [Clientes soportados](#clientes-soportados)
* [GraphiQL](#graphiql)
* [Postman](#postman)
* [Librerías HTTP](#librerias-http)
* [Información disponible](#informacion-disponible)
* [Ejemplos de consultas](#ejemplos-de-consultas)
* [Recuperar un único elemento de una colección](#recuperar-un-unico-elemento-de-una-coleccion)
* [Recuperar una colección completa](#recuperar-una-coleccion-completa)
* [Paginación](#paginacion)
* [Acceder a varios recursos en una única petición](#acceder-a-varios-recursos-en-una-unica-peticion)
* [Limitaciones de seguridad](#limitaciones-de-seguridad)
* [Ejemplo de consulta demasiado profunda](#ejemplo-de-consulta-demasiado-profunda)
* [Ejemplo de consulta demasiado compleja](#ejemplo-de-consulta-demasiado-compleja)
* [Ejemplos de código](#ejemplos-de-codigo)
<h2 id="caracteristicas">Características</h2>
* API de sólo lectura
* Acceso público, sin autenticación
* Usa GraphQL por debajo
* El tamaño máximo (y por defecto) de página está establecido a 25
* La profundiad máxima de las consultas es de 8 niveles
* Como máximo se pueden solicitar 2 colecciones en una misma consulta
* Soporte para peticiones GET (consulta dentro del *query string*) y POST (consulta dentro del *body*, como `application/json` o `application/graphql`).
## GraphQL
La API de Consul Democracy utiliza GraphQL [http://graphql.org](https://graphql.org), en concreto la [implementación en Ruby](http://graphql-ruby.org/). Si no estás familiarizado con este tipo de APIs, es recomendable investigar un poco sobre GraphQL previamente.
Una de las caracteríticas que diferencian una API REST de una GraphQL es que con esta última es posible construir *consultas personalizadas*, de forma que el servidor nos devuelva únicamente la información en la que estamos interesados.
Las consultas en GraphQL están escritas siguiendo un estándar que presenta ciertas similitudes con el formato JSON, por ejemplo:
```
{
proposal(id: 1) {
id,
title,
public_author {
id,
username
}
}
}
```
Las respuestas son en formato JSON:
```json
{
"data": {
"proposal": {
"id": 1,
"title": "Hacer las calles del centro de Madrid peatonales",
"public_author": {
"id": 2,
"username": "electrocronopio"
}
}
}
}
```
## Haciendo peticiones a la API
Siguiendo las [directrices oficiales](http://graphql.org/learn/serving-over-http/), la API de Consul Democracy soporta los siguientes tipos de peticiones:
* Peticiones GET, con la consulta dentro del *query string*.
* Peticiones POST
* Con la consulta dentro del *body*, con `Content-Type: application/json`
* Con la consulta dentro del *body*, con `Content-Type: application/graphql`
### Clientes soportados
Al ser una API que funciona a través de HTTP, cualquier herramienta capaz de realizar este tipo de peticiones resulta válida.
Esta sección contiene unos pequeños ejemplos sobre cómo hacer las peticiones a través de:
* GraphiQL
* Extensiones de Chrome como Postman
* Cualquier librería HTTP
#### GraphiQL
[GraphiQL](https://github.com/graphql/graphiql) es una interfaz de navegador para realizar consultas a una API GraphQL, así como una fuente adicional de documentación. Está desplegada en la ruta `/graphiql` y es la mejor forma de familiarizarse una API basada en GraphQL.
![GraphiQL](../../img/graphql/graphiql.png)
Tiene tres paneles principales:
* En el panel de la izquierda se escribe la consulta a realizar.
* El panel central muestra el resultado de la petición.
* El panel derecho (ocultable) contiene una documentación autogenerada a partir de la información expuesta en la API.
#### Postman
Ejemplo de petición `GET`, con la consulta como parte del *query string*:
![Postman GET](../../img/graphql/graphql-postman-get.png)
Ejemplo de petición `POST`, con la consulta como parte del *body* y codificada como `application/json`:
![Postman POST](../../img/graphql/graphql-postman-post-headers.png)
La consulta debe estar ubicada en un documento JSON válido, como valor de la clave `"query"`:
![Postman POST](../../img/graphql/graphql-postman-post-body.png)
<h4 id="librerias-http">Librerías HTTP</h4>
Por supuesto es posible utilizar cualquier librería HTTP de lenguajes de programación.
**IMPORTANTE**: Debido a los protocolos de seguridad de los servidores del Ayuntamiento de Madrid, es necesario incluir un *User Agent* perteneciente a un navegador para que la petición no sea descartada. Por ejemplo:
`User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36`
<h2 id="informacion-disponible">Información disponible</h2>
El fichero [config/api.yml](../../config/api.yml) contiene una lista completa de los modelos (y sus campos) que están expuestos actualmente en la API.
La lista de modelos es la siguiente:
| Modelo | Descripción |
| ----------------------- | ---------------------------- |
| `User` | Usuarios |
| `Debate` | Debates |
| `Proposal` | Propuestas |
| `Comment` | Comentarios en debates, propuestas y otros comentarios |
| `Geozone` | Geozonas (distritos) |
| `ProposalNotification` | Notificaciones asociadas a propuestas |
| `Tag` | Tags en debates y propuestas |
| `Vote` | Información sobre votos |
## Ejemplos de consultas
<h3 id="recuperar-un-unico-elemento-de-una-coleccion">Recuperar un único elemento de una colección</h3>
```
{
proposal(id: 2) {
id,
title,
comments_count
}
}
```
Respuesta:
```json
{
"data": {
"proposal": {
"id": 2,
"title": "Crear una zona cercada para perros en Las Tablas",
"comments_count": 10
}
}
}
```
<h3 id="recuperar-una-coleccion-completa">Recuperar una colección completa</h3>
```
{
proposals {
edges {
node {
title
}
}
}
}
```
Respuesta:
```json
{
"data": {
"proposals": {
"edges": [
{
"node": {
"title": "ELIMINACION DE ZONA APARCAMIENTO EXCLUSIVO FUNCIONARIOS EN MADRID"
}
},
{
"node": {
"title": "iluminación de zonas deportivas"
}
}
]
}
}
}
```
<h4 id="paginacion">Paginación</h4>
Actualmente el número máximo (y por defecto) de elementos que se devuelven en cada página está establecido a 25. Para poder navegar por las distintas páginas es necesario solicitar además información relativa al `endCursor`:
```
{
proposals(first: 25) {
pageInfo {
hasNextPage
endCursor
}
edges {
node {
title
}
}
}
}
```
La respuesta:
```json
{
"data": {
"proposals": {
"pageInfo": {
"hasNextPage": true,
"endCursor": "NQ=="
},
"edges": [
# ...
]
}
}
}
```
Para recuperar la siguiente página, hay que pasar como parámetro el cursor recibido en la petición anterior, y así sucesivamente:
```
{
proposals(first: 25, after: "NQ==") {
pageInfo {
hasNextPage
endCursor
}
edges {
node {
title
}
}
}
}
```
<h3 id="acceder-a-varios-recursos-en-una-unica-peticion">Acceder a varios recursos en una única petición</h3>
Esta consulta solicita información relativa a varios modelos distintos en una única petición: `Proposal`, `User`, `Geozone` y `Comment`:
```
{
proposal(id: 15262) {
id,
title,
public_author {
username
},
geozone {
name
},
comments(first: 2) {
edges {
node {
body
}
}
}
}
}
```
## Limitaciones de seguridad
Permitir que un cliente personalice las consultas supone un factor de riesgo importante. Si se permitiesen consultas demasiado complejas, sería posible realizar un ataque DoS contra el servidor.
Existen tres mecanismos principales para evitar este tipo de abusos:
* Paginación de resultados
* Limitar la profundidad máxima de las consultas
* Limitar la cantidad de información que es posible solicitar en una consulta
### Ejemplo de consulta demasiado profunda
La profundidad máxima de las consultas está actualmente establecida en 8. Consultas más profundas (como la siguiente), serán rechazadas:
```
{
user(id: 1) {
public_proposals {
edges {
node {
id,
title,
comments {
edges {
node {
body,
public_author {
username
}
}
}
}
}
}
}
}
}
```
La respuesta obtenida tendrá el siguiente aspecto:
```json
{
"errors": [
{
"message": "Query has depth of 9, which exceeds max depth of 8"
}
]
}
```
### Ejemplo de consulta demasiado compleja
El principal factor de riesgo se da cuando se solicitan varias colecciones de recursos en una misma consulta. El máximo número de colecciones que pueden aparecer en una misma consulta está limitado a 2. La siguiente consulta solicita información de las colecciónes `users`, `debates` y `proposals`, así que será rechazada:
```
{
users {
edges {
node {
public_debates {
edges {
node {
title
}
}
},
public_proposals {
edges {
node {
title
}
}
}
}
}
}
}
```
La respuesta obtenida tendrá el siguiente aspecto:
```json
{
"errors": [
{
"message": "Query has complexity of 3008, which exceeds max complexity of 2500"
},
{
"message": "Query has complexity of 3008, which exceeds max complexity of 2500"
},
{
"message": "Query has complexity of 3008, which exceeds max complexity of 2500"
}
]
}
```
No obstante sí que es posible solicitar información perteneciente a más de dos modelos en una única consulta, siempre y cuando no se intente acceder a la colección completa. Por ejemplo, la siguiente consulta que accede a los modelos `User`, `Proposal` y `Geozone` es válida:
```
{
user(id: 468501) {
id
public_proposals {
edges {
node {
title
geozone {
name
}
}
}
}
}
}
```
La respuesta:
```json
{
"data": {
"user": {
"id": 468501,
"public_proposals": {
"edges": [
{
"node": {
"title": "Empadronamiento necesario para la admisión en GoFit Vallehermoso",
"geozone": {
"name": "Chamberí"
}
}
}
]
}
}
}
}
```
<h2 id="ejemplos-de-codigo">Ejemplos de código</h2>
El directorio [doc/api/examples](https://github.com/consuldemocracy/consuldemocracy/tree/master/doc/api/examples/ruby) contiene ejemplos de código para acceder a la API.

View File

@@ -0,0 +1,33 @@
# Censo Local
Proporcionar a los usuarios administradores una forma de gestionar la base de datos del censo local a través del panel de administración **Configuración > Gestionar censo local**. Actualmente la única manera de manipular los registros de esta tabla es a través de la consola de rails.
Permitir a los usuarios de administradores gestionar esta tabla de dos maneras diferentes:
- **Manualmente**: uno por uno a través de una interfaz CRUD.
- **Automáticamente**: a través de un proceso de importación.
## Manualmente
Provide a way to manage local census records to administrator users through administration interface.
- Página de censo local
![Manage local census](../../img/local_census/manage-local-census-es.png)
- Añadir un nuevo registro
![Create local census record](../../img/local_census/add-local-census-record-es.png)
Funcionalidades:
1. Búsqueda por número_de_documento: Como local_census_records podría contener muchos registros, hemos añadido una función de búsqueda para permitir a los administradores encontrar los registros existentes por número de documento.
1. Evitar la introducción de registros duplicados: Se ha añadido una validación de modelo al siguiente par de atributos [:número_de_documento, :tipo_de_documento]
## Automáticamente
Permite a los usuarios administradores importar registros del censo local a través de un archivo CSV.
- Página de censo local
![Manage local census csv](../../img/local_census/manage-local-census-csv-en.png)
- Página para importar un CSV
![Create local census records csv](../../img/local_census/add-local-census-records-csv-en.png)

View File

@@ -0,0 +1,240 @@
# Multientidad
## Qué es multientidad y cómo funciona
La funcionalidad denominada "multientidad" permite la gestión de varias instituciones ("entidades") independientes dentro de una misma aplicación. Por ejemplo, en nuestro caso, un usuario que se dé de alta en una entidad estará solamente dado de alta en esa entidad y sus datos no serán accesibles desde ninguna de las otras entidades.
A qué entidad accedemos se determina a partir de la URL a la que se accede con el navegador. En Consul Democracy se determina esta entidad a partir del subdominio de esta URL; por ejemplo, si utilizásemos el dominio `ejemplodesistemasolar.org` para gestionar los diferentes planetas del sistema solar, al acceder a `https://mercurio.ejemplodesistemasolar.org` accederíamos a los datos del planeta Mercurio mientras que al acceder a `https://venus.ejemplodesistemasolar.org` accederíamos a los datos del planeta Venus. También es posible utilizar distintos dominios por entidad (por ejemplo, `ejemplodetierra.org`).
## Habilitar multientidad
### Pasos preliminares tras actualizar desde la versión 1.5.0 de Consul Democracy
Si has actualizado una instalación de Consul Democracy a la versión 2.0.0 desde la versión 1.5.0, deberás realizar los siguientes pasos antes de habilitar multientidad. Estos pasos no son necesarios en nuevas instalaciones de Consul Democracy.
Así, en primer lugar, tras subir la versión 2.0.0 al servidor de producción, tendrás que ejecutar las tareas de actualización de versión:
```
RAILS_ENV=production bin/rails consul:execute_release_tasks
```
Es posible que, tras ejecutar esta orden, veas el siguiente aviso:
> The database search path has been updated. Restart the application to apply the changes.
Si es así, reincia la aplicación. Si no has recibido este aviso, comprueba que el fichero `config/database.yml` contiene la línea `schema_search_path: "public,shared_extensions"` y, de no ser así, añádela por ejemplo bajo la línea que dice `adapter: postgresql` y reincia la aplicación.
Una vez hecho esto, deberás abrir una consola de base de datos utilizando un usuario que tenga permisos para crear y modificar extensiones de base de datos:
```
sudo -u postgres psql -d consul_production
```
Si no usaste el [instalador](https://github.com/consuldemocracy/installer/) para instalar Consul Democracy, es posible que tengas que ejecutar las siguientes consultas de base de datos para garantizar los permisos del usuario de Rails para crear esquemas así como el acceso al esquema de extensiones compartidas:
```
CREATE SCHEMA shared_extensions AUTHORIZATION <reemplazar_con_usuario_de_rails_de_base_de_datos>;
GRANT CREATE ON DATABASE consul_production TO <reemplazar_con_usuario_de_rails_de_base_de_datos>;
GRANT usage ON SCHEMA shared_extensions TO public;
```
Tanto si usaste el instalador como si no, ejecuta:
```
ALTER EXTENSION pg_trgm SET SCHEMA shared_extensions;
ALTER EXTENSION unaccent SET SCHEMA shared_extensions;
```
### Paso común a todas las instalaciones de Consul Democracy
Existen dos posibles maneras de habilitar multientidad:
* Añadiendo `config.multitenancy = true` dentro de la clase `class Application < Rails::Application` del fichero `config/application_custom.rb`
* Cambiando la línea `multitenancy: false` por `multitenancy: true` (o añadiéndola si no está ya ahí) en el fichero `config/secrets.yml`
La diferencia entre ambas opciones está en que la primera utiliza un fichero que se encuentra bajo control de versiones y la segunda un fichero que no se encuentra bajo control de versiones. Elige la primera opción si deseas este cambio en el código de tu repositorio git y la segunda opción en caso contrario.
Tras habilitar esta opción, reinicia la aplicación.
## Gestión de entidades
Una vez habilitada la funcionalidad de multientidad y reiniciada la aplicación, aparecerá una nueva sección "Multientidad" dentro del menú "Configuración" de la administración de Consul Democracy.
![Nueva sección con el listado de entidades, con su nombre y dominio o subdominio](../../img/multitenancy/index-es.png)
Esta sección solamente estará disponible desde la entidad "principal" (la que se crea por defecto). Las entidades que se creen desde aquí no tendrán acceso a esta sección y por tanto no podrán a su vez añadir o editar nuevas entidades.
Dado que eliminar una entidad borraría **todos** los datos relacionados con esa entidad y no se podrían restaurar, no existe la opción de eliminar una entidad ya creada desde este panel de administración. Sin embargo, es posible deshabilitar una entidad, haciendo que sea imposible acceder a la misma.
La interfaz de administración de entidades es muy sencilla, necesitando solamente un nombre y un subdominio.
![Formulario de edición de entidad, con nombre y dominio o subdominio; es posible seleccionar si se utiliza un dominio o un subdominio](../../img/multitenancy/form-es.png)
El nombre se usará como nombre del sitio por defecto para nuevas entidades. Nótese que, una vez una entidad se ha creado, cambiar este nombre no tendrá ningún efecto. Para cambiar el nombre del sitio de una entidad existente, edítalo en la sección "Configuración global" de la administración de esa entidad.
El dominio o subdominio será el que la aplicación utilice para acceder a la entidad. Si tienes un dominio como `ejemplodesistemasolar.org` y quieres acceder a las entidades utilizando subdominios (como `marte.ejemplodesistemasolar.org`), elige "Utiliza un subdominio". Si estás usando un dominio diferente para la entidad (como `ejemplodemarte.org`), elige "Utiliza un dominio distinto".
Nótese que, si estás usando un dominio distinto para una entidad, tendrás que configurar tus certificados SSL, servidor web y DNS para que acepten ese dominio y apunten a tu aplicación Consul Democracy.
Al añadir una nueva entidad, se creará automáticamente un usuario con permiso de administrador para esta nueva entidad **cuyos datos de acceso serán una copia de los del administrador que crea la entidad**. Este usuario se almacenará en el esquema de base de datos de la nueva entidad, con lo que cambiar su contraseña en una entidad no cambiará su contraseña en otras entidades.
## Pasos a realizar tras añadir una entidad
### Certificados SSL
Para que la aplicación sea accesible utilizando conexiones seguras de HTTPS/SSL, deberás tener un certificado SSL válido para la entidad que acabas de añadir. Dado que cada institución que utiliza Consul Democracy tiene su propio sistema para gestionar estos certificados, conseguir un certificado para la nueva entidad variará en función del sistema que utilice tu institución.
Si has instalado Consul Democracy usando el instalador y estás usando Certbot para gestionar estos certificados, tienes dos opciones.
Una opción es añadir manualmente cada certificado cada vez que creas una entidad. Por ejemplo, para añadir la entidad con subdominio `marte` al dominio `ejemplodesistemasolar.org`, ejecuta:
```
sudo certbot certonly --nginx --noninteractive --agree-tos --expand -d ejemplodesistemasolar.org,marte.ejemplodesistemasolar.org
```
Si vas a añadir muchos subdominios en distintos momentos, esta tarea puede resultar tediosa. Una alternativa es habilitar cualquier subdominio. Para conseguir esto, deberás tener acceso al panel de administración de tu dominio (DNS) para poder seguir las instrucciones al utilizar bien alguno de los [plugins DNS de Certbot](https://eff-certbot.readthedocs.io/en/stable/using.html#dns-plugins) o la [generación manual del certificado](https://eff-certbot.readthedocs.io/en/stable/using.html#manual) con la siguiente orden:
```
sudo certbot certonly --manual --agree-tos --expand -d ejemplodesistemasolar.org,*.ejemplodesistemasolar.org
```
Se te pedirá crear un registro TXT en el DNS de tu dominio con el subdominio `_acme-challenge` y con un cierto valor. También es posible que se te pida crear un archivo con un cierto nombre y un cierto contenido (normalmente en un directorio llamado `.well-known/acme-challenge`); si ese es el caso, asumiendo que estás usando los directorios por defecto de Consul Democracy, crea el fichero en `/home/deploy/consul/current/public/.well-known/acme-challenge/`.
Después de esto, actualiza la configuración de tu servidor web (por defecto, `/etc/nginx/sites-enabled/default`) para que use el certificado que se ha generado, y reinicia el servidor web con `sudo systemctl restart nginx`.
### Envío de correos electrónicos
Para disminuir la probabilidad de que los correos enviados por la aplicación sean identificados como fraudulentos, puede que quieras editar los campos "Nombre email remitente" y "Dirección email remitente" en el panel de administración de la nueva entidad. Los valores por defecto de estos campos son el nombre y el subdominio que se utilizaron al crear la entidad.
![Campos para editar el nombre y la dirección del remitente](../../img/multitenancy/email-settings-es.png)
Si quieres utilizar una configuración de envío de correo electrónico diferente para una entidad, como podría ser una que utilice `jupiter` como subdominio, edita el fichero `config/secrets.yml` de la siguiente manera:
```
production:
# (...) Otros secretos
multitenancy: true
tenants:
jupiter:
mailer_delivery_method: :smtp
smtp_settings:
:address: <servidor_de_correo>
:port: <puerto>
:domain: <tu_dominio>
:user_name: <usuario>
:password: <contraseña>
:authentication: "plain"
:enable_starttls_auto: true
# (...) Otros secretos
```
Tras editar el fichero, reinicia la aplicación.
### Identificación mediante redes sociales
Si utilizas aplicaciones para que los usuarios puedan identificarse mediante Twitter, Google, Facebook o Wordpress, deberás hacer que la nueva entidad pueda identificarse con estos servicios. Para ello, tienes dos opciones.
Como primera opción, en el panel de configuración de Twitter/Google/Facebook/Wordpress, puedes modificar tu aplicación existente y añadir la URL de la nueva entidad en la lista de dominios permitidos. Al hacer esto, ten en cuenta la configuración de los términos y condiciones de tu aplicación, que puede no siempre ser compatible con esta opción.
Y como segunda opción, puedes crear una nueva aplicación de Twitter/Google/Facebook/Wordpress y configurarla para su uso desde el dominio de la nueva entidad. En este caso, deberás añadir la configuración de esta aplicación al fichero `config/secrets.yml`. Por ejemplo, si administrases una entidad con el subdominio `saturno`, edita el fichero de esta manera, rellenando la información de aquellos servicios que estés utilizando:
```
production:
# (...) Otros secretos
multitenancy: true
tenants:
saturno:
twitter_key: <clave_twitter>
twitter_secret: <secreto_twitter>
facebook_key: <clave_facebook>
facebook_secret: <secreto_facebook>
google_oauth2_key: <clave_google>
google_oauth2_secret: <secreto_google>
wordpress_oauth2_key: <clave_wordpress>
wordpress_oauth2_secret: <secreto_wordpress>
wordpress_oauth2_site: <sitio_wordpress>
# (...) Otros secretos
```
Tras editar el fichero, reinicia la aplicación.
## Información a tener en cuenta al realizar desarrollos
### Mantenimiento del fichero schema.rb
Cuando Consul Democracy crea una entidad, utiliza el fichero `db/schema.rb` para crear un nuevo esquema de la base de datos para esta entidad. Esto significa que, si por alguna razón este fichero no contiene la misma estructura de base de datos que se generaría creando una nueva base de datos y ejecutando las migraciones con `rake db:migrate`, podría darse el caso de que diferentes entidades tuvieran diferentes tablas o columnas en sus esquemas de base de datos. Las consecuencias de esta configuración podrían ser fatales.
Para evitarlo, recomendamos encarecidamente comprobar en tu sistema de integración continua que el fichero `db/schema.rb` que se encuentra en control de versiones es correcto. Consul Democracy incluye ya esta comprobación si realizas la integración continua con GitHub Actions. Contribuciones incluyendo esta comprobación en GitLab CI u otros entornos son más que bienvenidas.
### Estilos personalizados para cada entidad mediante CSS
Cuando la funcionalidad de multientidad está activada, Consul Democracy añade una clase al elemento `<html>` para que sea posible aplicar estilos (o eventos de JavaScript) solamente en ciertas entidades. Por ejemplo, en la entidad con subdominio `urano` este elemento tendría la clase `tenant-urano`.
Así, es posible sobrescribir los estilos para una entidad específica añadiendo a alguna hoja de estilos en la carpeta `app/assets/stylesheets/custom/`:
```
.tenant-urano {
// Estilos que solamente se aplican a Urano
}
```
Para cambiar los colores en una determinada entidad de forma sencilla, puedes utilizar variables de CSS; su uso aparece documentado en el fichero [app/assets/stylesheets/custom/tenants.scss](https://github.com/consuldemocracy/consuldemocracy/blob/master/app/assets/stylesheets/custom/tenants.scss). Por ejemplo, para utilizar tonos de verde en los colores principales de la entidad con subdominio `urano`, puedes escribir:
```
.tenant-urano {
--brand: #350;
--brand-secondary: #173a00;
}
```
### Vistas personalizadas para cada entidad con ERB
En ocasiones puede resultar conveniente utilizar vistas completamente distintas. Por ejemplo, una entidad podría usar un pie de página que no tuviera nada que ver con el de otras entidades.
En estos casos, en lugar de añadir condiciones como `case Tenant.current_schema` a la vista, usar un fichero distinto podría resultar en código más fácil de mantener.
Para esto, podemos usar las "[variantes](https://guides.rubyonrails.org/layouts_and_rendering.html#the-variants-option)" que ofrece Rails, que hacen que por ejemplo una entidad llamada `via-lactea` use como vista un fichero terminado en `.html+via-lactea.erb` si este fichero existe. Es decir, para usar un archivo `application.html.erb` diferente para la entidad `via-lactea`, crea un nuevo archivo en `app/views/custom/layouts/application.html+via-lactea.erb`.
Recomendamos utilizar esta funcionalidad solamente cuando haya diferencias sustanciales entre la vista por defecto y la vista específica para una entidad. Si las diferencias son pequeñas, usa condiciones `if` o `case` en su lugar para evitar duplicación de código.
El mismo principio funciona también con componentes, solo que en este caso, al usar el directorio `custom/` para añadir archivos ERB para una entidad, el archivo ERB de la entidad por defecto también tiene que añadirse al directorio `custom/`; si no hay cambios en este fichero, valdrá con un enlace simbólico.
Por ejemplo, si estás escribiendo una vista personalizada del componente `admin/action_component` para la entidad `via-lactea` pero no vas a cambiar esta vista para la entidad por defecto:
1. Crea el archivo `app/components/custom/admin/action_component.rb` tal y como se indica en la [documentación de personalización de componentes](../customization/components.md)
1. Crea la vista personalizada para la entidad `via-lactea` y guárdala en `app/components/custom/admin/action_component.html+via-lactea.erb`
1. Entra en el directorio `app/components/custom/admin/` y ejecuta `ln -s ../../admin/action_component.html.erb`
## Limitaciones actuales de multientidad
La funcionalidad de multientidad se incluyó por primera vez en Consul Democracy 2.0.0 y hay algunas cosas que todavía no están disponibles.
### Aplicaciones disponibles desde múltiples dominios
Es posible que permitas acceder a tu aplicación de Consul Democracy desde dos dominios distintos; por ejemplo, `ejemplodesistemasolar.org` y un dominio en inglés llamado `solarsystemexample.org`.
En este caso, para conseguir que multientidad funcione con ambos dominios, es necesario cambiar ligeramente el código fuente de la aplicación. En concreto, hay que cambiar el método `allowed_domains` de la clase `Tenant` para que incluya ambos dominios. En la [documentación de personalización de modelos](../customization/models.md) puedes ver ejemplos de cómo personalizar métodos como este.
### Imágenes personalizadas por entidad
El panel de administración de Consul Democracy contiene una sección llamada "Personalizar imágenes", donde es posible personalizar algunas (aunque no todas) de las imágenes que aparecen en la aplicación. Usar esta interfaz permite tener imágenes distintas para cada entidad.
A veces, sin embargo, es útil incluir ciertas imágenes bajo control de versiones. Por ejemplo, si quisiéramos usar un logo distinto para una entidad en el subdominio `neptuno`, pondríamos ese archivo en `app/assets/images/custom/tenants/neptuno/logo_header.png`.
Este sistema tiene una limitación y es que solamente funcionará para imágenes que se pueden cambiar desde la interfaz de administración. Si quieres personalizar otra imagen, tendrás que cambiar el código que la renderiza. Por ejemplo, para que sea posible personalizar la imagen `avatar_admin.png`, cambia el código `image_tag("avatar_admin.png")` por `image_tag(image_path_for("avatar_admin.png"))`.
### Bases de datos en distintos servidores para cada entidad
En la versión 2.0.0 de Consul Democracy, los datos de todas las entidades se almacenan en la misma base de datos y por tanto no es posible usar bases de datos en distintos servidores.
En caso de que esta funcionalidad sea suficientemente solicitada, podrá incluirse en Consul Democracy en el futuro. Hay que tener en cuenta que la versión 2.0.0 de Consul Democracy utiliza Rails 6.0 y que para esta funcionalidad será necesario usar Rails 6.1 o incluso Rails 7.0.
### Idiomas distintos para distintas entidades
En la versión 2.0.0 de COSNSUL, todas las entidades están disponibles en los mismos idiomas, con lo que no sería posible (por ejemplo) que una entidad estuviera disponible en francés y otra en alemán, sino que ambas tendrían que estar disponibles en ambos idiomas.
Implementar esta posibilidad está planeado para la versión 2.1.0 de Consul Democracy.
### Borrado de entidades
Dado que eliminar una entidad borraría **todos** los datos relacionados con esa entidad y no se podrían restaurar, Consul Democracy no ofrece la opción de eliminar una entidad ya creada desde el panel de administración y solamente permite deshabilitarlas para que no sea posible acceder a ellas. Para eliminar una entidad, utiliza la consola de Rails.

32
docs/es/features/oauth.md Normal file
View File

@@ -0,0 +1,32 @@
# OAuth
Puedes configurar la autenticación con servicios externos usando OAuth, por ahora están soportados Twitter, Facebook y Google.
## 1. Crea una aplicación en la plataforma
Para cada plataforma, sigue las instrucciones en la sección de desarrolladores de su página web.
## 2. Establece la url de tu Consul Democracy
Te preguntarán por la URL de autenticación de tu instalación de Consul Democracy, y como podrás comprobar corriendo la tarea `rake routes` en tu repositorio local:
```bash
user_omniauth_authorize GET|POST /users/auth/:provider(.:format) users/omniauth_callbacks#passthru {:provider=>/twitter|facebook|google_oauth2/}
```
Por ejemplo para facebook la URL sería `yourdomain.com/users/auth/facebook/callback`
## 3. Establece la clave y secreto
Cuando completes el registro de la aplicación en su plataforma te darán un *key* y *secret*, estos deben ser almacenados en tu fichero `config/secrets.yml`:
```yml
twitter_key: ""
twitter_secret: ""
facebook_key: ""
facebook_secret: ""
google_oauth2_key: ""
google_oauth2_secret: ""
```
*NOTA:* Además en el caso de Google, verifica que las APIs de *Contacts API* y *Google+ API* están habilitadas para tu aplicación en su plataforma.

View File

@@ -0,0 +1,29 @@
# Recomendaciones de Debates y Propuestas
Para Debates y Propuestas los usuarios logueados pueden encontrar elementos recomendados usando el filtro de ordenación "Recomendaciones".
En este listado se muestran, ordenados por votos de forma descendiente, aquellos elementos que:
1. Tengan etiquetas que interesen al usuario. Siendo las etiquetas de su interés aquellas usadas en propuestas que ha seguido.
2. El usuario no sea el autor de los mismos.
3. Sólo en el caso de las propuestas: únicamente se muestran aquellas que aún no hayan llegado al umbral de votos requerido, ocultándose además aquellas que el usuario este siguiendo.
## Cómo probar la funcionalidad
En nuestra instalación en local, si no hemos iniciado sesión, podemos comprobar visitando <http://localhost:3000/proposals> que no aparece la opción de ordenación "Recomendaciones"
![Recommendations not logged in](../../img/recommendations/recommendations_not_logged_in.jpg)
Una vez iniciada sesión aparece el menú de ordenación, pero al no tener intereses nos muestra un mensaje "Sigue propuestas para que podamos darte recomendaciones" si lo visitamos en <http://localhost:3000/proposals?locale=en&order=recommendations&page=1>
![Recommendations no follows](../../img/recommendations/recommendations_no_follows.jpg)
Tras seguir una propuesta cualquiera con el botón de "Seguir propuesta ciudadana" que aparece en el menu lateral:
![Recommendations follow button](../../img/recommendations/recommendations_follow_button.jpg)
Podemos comprobar que tenemos recomendaciones:
![Recommendations with follows](../../img/recommendations/recommendations_with_follows.jpg)
La funcionalidad es similar en el menú de debates.

View File

@@ -0,0 +1,13 @@
# Comunicación
Para comunicar sugerencias/incidencias te animamos a [abrir una incidencia en el repositorio de Documentación de Consul Democracy](https://github.com/consuldemocracy/consuldemocracy/issues/new).
Para comunicaciones más informales, chatea con nosotros en el [gitter de consul](https://gitter.im/consul/consul)
Antes de hacerlo, **por favor tómate un tiempo para comprobar los [issues ya existentes](https://github.com/consuldemocracy/consuldemocracy/issues) y asegúrate de que lo que estás a punto de reportar no ha sido reportado previamente** por otra persona. De ser así, si tienes más detalles acerca de la incidencia puedes escribir un comentario en la página ¡un poco de ayuda puede marcar una gran diferencia!
Para escribir un nuevo issue, ten en cuenta estas recomendaciones para hacerlo más fácil de leer y comprender:
- Intenta usar un título descriptivo.
- Es buena idea incluir algunas secciones -en caso de que sean necesarias- como los pasos para reproducir el error, el comportamiento o respuesta que cabría esperar, la respuesta que devuelve o capturas de pantalla.
- También puede ser de ayuda incluir en la descripción tu sistema operativo, versión del navegador que usaste y posibles plugins instalados.

View File

@@ -0,0 +1,17 @@
# Configura tu fork
## Travis CI
[Travis](https://travis-ci.org/) es un servicio de Integración Contínua, gratuito para proyectos OpenSource (como Consul Democracy y sus forks). Te ayudará a vigilar que en las Pull Requests no se rompan los tests.
1. Visita <https://github.com/marketplace/travis-ci> y haz click en el botón verde "**Install it for free**"" al pie de la página.
2. Haz click en el botón verde "**Complete order and begin installation**"
3. Si se te solicita acceso a tu cuenta de Github por parte de Travis CIaccess, marca la organización o usuario bajo el cual reside tu fork de Consul Democracy y haz click en el botón "**Authorize travis-ci**".
4. Visita [tu perfil en Travis](https://travis-ci.org/profile/) y habilita Travis para tu fork de Consul Democracy en el listado de repositorios.
5. Haz click en el icono de un piñón a la derecha del repositorio para ver las builds.
6. Comprueba que todo está bien configurado creando un Pull Request de prueba (editar un simple fichero .md podría servir).

View File

@@ -0,0 +1,22 @@
# Crea tu fork
El repositorio git de Consul Democracy está hospedado en Github.com, recomendamos lo uses para tu fork para hacer las cosas mas fáciles. Pero puedes usar cualquier otro servicio como Bitbucket o Gitlab si deseas, pero no te olvides de poner el enlace en el footer a tu repositorio en cumplimiento con la licencia de este proyecto (GPL Affero 3).
1. [Registra una cuenta de usuario en Github](https://github.com/join) si no tienes una ya.
2. [Crea una Organización](https://help.github.com/articles/creating-a-new-organization-from-scratch/) en Github con el nombre de la ciudad u organización que usará Consul Democracy. **Esto no es obligatorio**, pero ayudará a entender el propósito del fork y la colaboración de otros usuarios.
3. [Forkea Consul Democracy](https://help.github.com/articles/fork-a-repo/) usando el botón de **fork** en la esquina superior derecha de <https://github.com/consuldemocracy/consuldemocracy>
4. [Clona el repositorio de tu fork](https://help.github.com/articles/cloning-a-repository/) en tu ordenador
****ADVERTENCIA IMPORTANTE**: No hagas un fork de `https://github.com/AyuntamientoMadrid/consul`, es una equivocación frecuente que conlleva múltiples y graves problemas.
## ¿Porqué hacer el código público?
Recomendamos publicar el código por varias razones:
- **Transparencia**: Debería ser parte de la cultura de aquellas entidades públicas que adopten Consul Democracy, así como cualquier organización o grupo.
- **Soporte**: Si necesitas ayuda técnica, el resto de la comunidad o el equipo de Consul Democracy podrán entender y aconsejar mas fácilmente al ver el código implicado.
- **Colaboración**: Por parte de otros profesionales, ciudadanos, etc...
- Por último y no menos importante, Consul Democracy se distribuye bajo la **licencia [AGPLv3](https://github.com/consuldemocracy/consuldemocracy/blob/master/LICENSE-AGPLv3.txt)** que obliga a publicar el codigo fuente.

View File

@@ -0,0 +1,6 @@
# Getting started
* [Fork Consul Democracy](create.md)
* [Configure your fork](configuration.md)
* [Keep your fork updated](update.md)
* [Communication](communication.md)

View File

@@ -0,0 +1,69 @@
# Manten tu fork actualizado
## Configura tus servidores remotos de git
Si creaste correctamente tu fork y lo clonaste localmente, usando:
```bash
git remote -v
```
deberías ver algo como:
> origin git@github.com:your_user_name/consuldemocracy.git (fetch)\
> origin git@github.com:your_user_name/consuldemocracy.git (push)
Ahora debes añadir el repositorio git de Consul Democracy como servidor remoto con:
```bash
git remote add upstream git@github.com:consuldemocracy/consuldemocracy.git
```
comprueba de nuevo que con:
```bash
git remote -v
```
deberías recibir algo como:
> upstream git@github.com:consuldemocracy/consuldemocracy.git (fetch)\
> upstream git@github.com:consuldemocracy/consuldemocracy.git (push)\
> origin git@github.com:your_user_name/consuldemocracy.git (fetch)\
> origin git@github.com:your_user_name/consuldemocracy.git (push)
## Obteniendo cambios de Consul Democracy
Empieza creando una rama **upstream** a partir de tu rama **master** sobre la que trabajar:
```bash
git checkout master
git pull
git checkout -b upstream
```
Y actualiza la información del repositorio de Consul Democracy con las referencias a las ramas, tags, etc..:
```bash
git fetch upstream
```
Y por fin puedes elegir entre:
A. Actualizar con los últimos cambios de la rama **master** usando `git merge upstream/master`
B. Sólo actualizar hasta cierta versión (en el caso de que prefieras actualizar de forma incremental, si estas varias versiones por detrás). Por ejemplo para actualizarte a la versión [v0.9](https://github.com/consuldemocracy/consuldemocracy/releases/tag/v0.9) utilizamos el tag asociado: `git merge v0.9`
## Fusionando cambios
Tras el `merge` de la anterior sección, hay tres posibles escenarios:
A. Obtienes una respuesta `Already up-to-date.`. Eso significa que tu fork esta al dia con los cambios de Consul Democracy 😊👌
B. Se abre una ventana del editor que tengas configurado en git, mostrando el mensaje de commit `Merge remote-tracking branch 'upstream/master' into upstream`. Esto significa que git fue capaz de mezclar los cambios de Consul Democracy sobre tu código sin encontrar problemas o conflictos. Termina el commit.
C. Recibes mensajes de error de git junto con un `Automatic merge failed; fix conflicts and then commit the result.`. Esto significa que se han encontrado conflictos entre los cambios en tu código y los cambios que se realizaron en Consul Democracy desde la última vez que actualizaste tu fork. Esta es una de las principales razones para intentar mantener tu fork lo más al dia posible, realizando este proceso al menos mensualmente. Resuelve manualmente los conflictos para terminar el merge y haz un commit.
Ahora simplemente sube la rama **upstream** a github y crea un Pull Request, así podrás ver de manera sencilla todos los cambios que se han realizado en el repositorio y verás también como arranca la suite de tests.
Recuerda que siempre puedes comprobar rápidamente los cambios que tienes pendientes de integrar de Consul Democracy a tu fork sustituyendo **your_org_name** en la url: <https://github.com/your_org_name/consuldemocracy/compare/master...consuldemocracy:master>

View File

@@ -0,0 +1,81 @@
# Configuración básica
Una vez que tengas Consul Democracy funcionando en el servidor, hay algunas opciones básicas de configuración que probablemente quieras definir para poder empezar a usarlo.
Para ello deberás acceder a tu instalación de Consul Democracy a través de cualquier navegador de internet e identificarte con el usuario de administración (inicialmente es el usuario `admin@consul.dev` con la contraseña `12345678`). Una vez identificado verás en la parte superior derecha de la pantalla el enlace "Admin" que te llevará a la interfaz de administración. Desde esta interfaz puedes configurar las siguientes opciones básicas:
## Parámetros de la configuración global
En el menú lateral encontrarás la opción "Configuración" y posteriormente el submenú "Configuración global". Aquí encontrarás muchos parámetros interesantes, pero por el momento te recomendamos definir algunos de los más básicos. Más adelante cuando estés más familiarizado con la herramienta podrás volver a configurar otros parámetros:
- Nombre del sitio. Este nombre aparecerá en el asunto de emails, páginas de ayuda...
- Nombre email remitente. Este nombre aparecerá como nombre del remitente en los emails enviados desde la aplicación. Como por ejemplo el email que los usuarios reciben para confirmar que han creado su cuenta.
- Dirección email remitente. Esta dirección de email aparecerá en los emails enviados desde la aplicación.
- URL general de la web. URL principal de tu web.
- Edad mínima para participar. Si utilizas un sistema de verificación de usuarios esta será la edad mínima que se exigirá a los usuarios. Sobre el sistema de verificación de usuarios hablaremos en más detalle más adelante.
- Número de apoyos necesarios para aprobar una Propuesta. Si utilizas la sección de propuestas ciudadanas, puedes definir un mínimo de apoyos que necesitan las propuestas para ser consideradas. Cualquier usuario podrá crear propuestas pero solo las que lleguen a ese valor serán tenidas en cuenta.
- Cargos públicos de nivel x. Consul Democracy permite que algunas cuentas de usuario se marquen como "cuentas oficiales" apareciendo más resaltadas sus intervenciones en la plataforma. Esto por ejemplo se usa en una ciudad si se quieren definir cuentas para el Alcalde, los Concejales, etc. Esta opción de cargos públicos te permitirá definir la etiqueta oficial que aparece al lado de los nombres de usuario de estas cuentas de mayor importancia (nivel 1) a menor (nivel 5).
## Categorías de las propuestas
Cuando los usuarios crean propuestas en la plataforma se sugieren unas categorías generales, para ayudar a organizar las propuestas. Para definir estas categorías puedes entrar en el menú "Configuración global" y luego en el submenú "Temas de propuestas". En la parte superior puedes escribir temas y crearlos con el botón que aparece a continuación.
## Definición de geozonas
Las geozonas son áreas territoriales más pequeñas que la zona en la que usas Consul Democracy (por ejemplo los distritos en una ciudad en la que se use Consul Democracy). Si las activas permitirá por ejemplo que las propuestas ciudadanas se asignen a una zona concreta, o que las votaciones estén restringidas a la gente que viva en alguna zona.
En el menú lateral encontrarás la opción "Configuración" y posteriormente el submenú "Gestionar distritos". A la derecha el botón "Crear distrito" te permitirá crear nuevas geozonas. Solo el nombre es necesario para definirlas, pero podrás agregar otros datos que son útiles en ciertas secciones. Inicialmente te recomendamos que empieces definiendo sólo los nombres de las zonas.
Una vez definidas si creas una propuesta ciudadana verás como una de las opciones en el formulario de creación te permite elegir si tu propuesta se refiere a una geozona concreta.
Si activas las geozonas puedes también mostrar una imagen que represente el área con las zonas. Esta imagen puedes cambiarla en el menú "Configuración global" en el submenú "Personalizar imágenes". La imagen por defecto que podrás cambiar es la titulada "map".
## Mapa para geolocalizar propuestas
Puedes permitir que al crear propuestas los usuarios puedan situarlas en un mapa. Para ello tienes que definir qué mapa quieres mostrar.
Accede en primer lugar al menú "Configuración" y posteriormente al submenú "Configuración global". Allí encontrarás tres parámetros que tendrás que rellenar:
- Latitud. Latitud para mostrar la posición del mapa
- Longitud. Longitud para mostrar la posición del mapa
- Zoom. Zoom para mostrar la posición del mapa. Puedes probar con un valor inicial y luego cambiarlo más adelante.
En la parte superior de esta página encontrarás tres pestañas: "Configuración Global", "Funcionalidades" y "Configuración del Mapa". Accede ahora a la segunda pestaña "Funcionalidades".
En esta página encontrarás una de las funcionalidades titulada como "Geolocalización de propuestas y proyectos de gasto". Deberá aparecer el mensaje "Funcionalidad activada" a su derecha. Si no es así haz click en el botón "Activar".
A continuación, en la parte superior de esta página accede a la pestaña "Configuración del Mapa". Si todo ha sido configurado correctamente verás aquí el mapa centrado en la latitud y longitud que introdujiste antes. Puedes centrar correctamente el mapa y cambiar el nivel de zoom directamente sobre el mapa, pulsando luego el botón "Actualizar" que hay debajo de él.
## Emails a usuarios
Consul Democracy envía por defecto una serie de correos electrónicos a los usuarios. Por ejemplo al crear una cuenta de usuario, al intentar recuperar la contraseña, al recibir un mensaje de otro usuario, etc.
Todos los correos que se envían puedes visualizarlos en el menú "Mensajes a usuarios" en el submenú "Emails del sistema". Ahí podrás previsualizar cada correo electrónico y ver el archivo donde está el contenido del correo por si quieres cambiarlo.
## Páginas básicas de información
Consul Democracy cuenta con una serie de páginas básicas de información que se mostrarán a los usuarios. Por ejemplo "Política de Privacidad", "Preguntas Frecuentes", "Felicidades acabas de crear tu cuenta de usuario", etc.
Puedes ver las páginas que existen por defecto y modificarlas en el menú "Contenido del sitio" en el submenú "Personalizar Páginas".
## Página principal del sitio
Al acceder a tu instalación de Consul Democracy los usuarios verán la página principal de la plataforma. Esta página es totalmente configurable, para que muestres el contenido que te parezca más relevante. Puedes modificarla desde el menú "Contenido del sitio" en el submenú "Homepage".
Prueba a crear "Encabezados" y "Tarjetas" y a activar las diferentes funcionalidades que encontrarás debajo para ver el efecto que producen en tu página principal.
## Textos de la plataforma
Si accedes al menú "Contenido del sitio" y al submenú "Personalizar textos" verás diferentes pestañas con una serie de textos. Estos son todos los textos que se muestran en la plataforma. Por defecto puedes utilizar los que existen, pero en cualquier momento puedes acceder a esta sección para modificar cualquiera de los textos.
Para tener más información sobre cómo añadir nuevas traducciones a tu versión de Consul Democracy accede a la sección "Textos y traducciones" de esta documentación.
## Canales de participación
Por defecto encontrarás en Consul Democracy diferentes formas de participación para los usuarios. Para empezar y familiarizarte con la plataforma te recomendamos tenerlos todos activados, pero puedes desactivar todos los que no te parezcan necesarios. Para ello accede al menú "Configuración" y posteriormente al submenú "Configuración global". En la parte superior de esta página encontrarás tres pestañas: "Configuración Global", "Funcionalidades" y "Configuración del Mapa". Accede a la segunda pestaña "Funcionalidades".
Encontrarás diversas funcionalidades con los nombres de los diferentes canales de participación "Debates", "Propuestas", "Votaciones", "Legislación Colaborativa" y "Presupuestos Participativos". Puedes desactivar cualquiera de las funcionalidades y dejará de mostrarse en tu instalación de Consul Democracy.
### Más información y documentación detallada
Estas opciones anteriores te permitirán tener una versión básica de Consul Democracy que empezar a usar. Te recomendamos acceder a la sección [Documentación y guías sobre Consul Democracy](documentation_and_guides.md) donde podrás encontrar más documentación detallada.

View File

@@ -0,0 +1,82 @@
# Crear un usuario para hacer la instalación
[El instalador](https://github.com/consuldemocracy/installer) de forma predeterminada se conecta como el usuario `root` sólo para crear un usuario `deploy`. Este usuario `deploy` es el que instala todas las librerías. Si no tiene acceso `root`, por favor pídale a su administrador de sistemas que siga estas instrucciones para crear un usuario manualmente.
Puede crear un usuario llamado `deploy` o utilizar cualquier otro nombre. Como ejemplo, vamos a crear un usuario llamado `jupiter`.
```
adduser jupiter
```
Estoy usando jupiter como nombre de usuario, debería cambiar eso por lo que sea que tenga sentido para usted. Introduzca una contraseña cuando se le pida y deje vacías el resto de las opciones.
Creemos un grupo `wheel` y añadamos al usuario `jupiter` al grupo.
```
sudo groupadd wheel
sudo usermod -a -G wheel jupiter
```
**Recuerde cambiar jupiter** por cualquier nombre de usuario que haya elegido en el paso anterior.
Ahora démosle al grupo `wheel` derechos de superadministración sin necesidad de usar contraseña, esto es importante para que el instalador no se quede parado esperando una contraseña.
Primero debemos abrir el archivo `sudoers`:
```
sudo visudo -f /etc/sudoers
```
Y añadimos esta línea al final del archivo:
```
%wheel ALL=(ALL) NOPASSWD: ALL
```
Ahora tenemos que dar las claves del servidor al nuevo usuario. No cierre la ventana de la terminal del servidor, porque puede bloquearse si hay un error.
Y escriba los siguientes comandos para crear el archivo necesario donde subir la clave pública:
```
su jupiter
cd ~
mkdir .ssh
cd .ssh
nano authorized_keys
```
Asegúrese que ha [generado una clave pública](generating_ssh_key.md) en su terminal local.
Abra otra ventana de terminal local (no en el servidor) y escriba:
```
cat ~/.ssh/id_rsa.pub
```
Copie el contenido de ese comando al archivo `authorized_keys` que debería seguir abierto en el servidor.
Compruebe que su usuario puede iniciar sesión escribiendo:
```
ssh jupiter@your-copied-ip-address
```
Debería ver la página de bienvenida del servidor y un mensaje como este:
```
jupiter@consuldemocracyserver:~$
```
Note que el nombre de usuario en el prompt no es "root", sino su nombre de usuario. Así que todo está bien y ahora podemos bloquear la cuenta root del acceso externo y también dejar de permitir el acceso con contraseña para que sólo las personas con claves SSH puedan iniciar sesión.
Escriba el siguiente comando para editar el archivo de configuración SSH del servidor:
```
sudo nano /etc/ssh/sshd_config
```
Busque la línea "PasswordAuthentication yes" y cámbiela por "PasswordAuthentication no". Escriba Control-K para cerrar el editor nano y escriba:
```
sudo service ssh restart
```

View File

@@ -0,0 +1,161 @@
# Configuración para los entornos de desarrollo y pruebas (Debian GNU/Linux 9.8)
## Super usuario
El programa 'sudo' no viene instalado en Debian por defecto. Su instalación y configuración es posible, se puede encontrar información al respecto [aquí](https://wiki.debian.org/es/sudo). Pero no lo recomendamos porque puede causar otros problemas. Recomendamos que se ejecuten las siguientes instrucciones como un super usuario, así que asegúrate de que la primera instrucción que ejecutes sea:
```
su
```
> Para [Vagrant](/es/installation/vagrant.md) ejecutar:
> ```
> sudo su -
> ```
## Actualización de sistema
Ejecuta una actualización general de las librerías de sistema:
```bash
apt-get update
```
## Git
Git es mantenido oficialmente en Debian:
```
apt-get install git
```
## Curl
Curl es mantenido oficialmente en Debian:
```
apt-get install curl
```
## Gestor de versiones de Ruby
Las versiones de Ruby empaquetadas en repositorios oficiales no son aptas para trabajar con Consul Democracy, así que debemos instalar manualmente.
Una opción es utilizar rvm:
### Como usuario local
```
command curl -sSL https://rvm.io/mpapis.asc | gpg --import -
command curl -sSL https://rvm.io/pkuczynski.asc | gpg --import -
curl -L https://get.rvm.io | bash -s stable
```
después añadimos el script rvm a nuestro bash (~/.bashrc) (este paso sólo es necesario si no puedes ejecutar el comando rvm)
```
[[ -s /usr/local/rvm/scripts/rvm ]] && source /usr/local/rvm/scripts/rvm
```
por úlitmo, volvemos a cargar el .bashrc para poder ejecutar RVM
```
source ~/.bashrc
```
## Node.js
Para compilar los archivos estáticos (JS, CSS, imágenes, etc.), es necesario un _runtime_ de JavaScript. Node.js es la opción recomendada. Al igual que como ocurre con Ruby, no es recomendable instalar Node directamente de los repositorios de tu distribución Linux.
Para instalar Node, puedes usar [n](https://github.com/tj/n)
Ejecuta el siguiente comando en tu terminal:
```
curl -L https://git.io/n-install | bash -s -- -y lts
```
Y este instalará automáticamente la versión LTS (_Long Term Support_, inglés para "Soporte a largo plazo") más reciente de Node en tu directorio `$HOME` (Este comando hace uso de [n-install](https://github.com/mklement0/n-install))
vuelve a cargar el .bashrc para poder ejecutar node
```
source /root/.bashrc
```
Comprueba que está correctamente instalado ejecutando:
```
node -v
```
## PostgreSQL (>=9.4)
La versión 9.4 de PostgreSQL no es oficial en Debian 9.
Así que debemos añadir el respositorio oficial de postgresql a apt, por ejemplo creando el fichero */etc/apt/sources.list.d/pgdg.list* con:
```
deb http://security.debian.org/debian-security jessie/updates main
```
después deberás descargar la key e instalarla:
```
wget https://www.postgresql.org/media/keys/ACCC4CF8.asc
apt-key add ACCC4CF8.asc
```
y finalmente instalar postgresql
```
apt-get update
apt-get install postgresql-9.4 postgresql-server-dev-9.4 postgresql-contrib-9.4
```
Para el correcto funcionamiento de Consul Democracy, necesitas confgurar un usuario para tu base de datos. Como ejemplo, crearemos un usuario llamado "consul":
```
su - postgres
createuser consul --createdb --superuser --pwprompt
exit
```
## Imagemagick
Instala Imagemagick:
```bash
apt-get install imagemagick
```
## ChromeDriver
Para realizar pruebas de integración, usamos Selenium junto a Headless Chrome.
Para ello, primero instala el siguiente paquete:
```bash
apt-get install chromedriver
ln -s /usr/lib/chromedriver /usr/local/bin/
```
Asegúrate de que todo funciona como es debido ejecutando el siguiente comando:
```bash
chromedriver --version
```
Deberías recibir un mensaje indicando la última versión de ChromeDriver. Si ese es el caso, está todo listo
Si te encuentras usando una distro basada en Arch, instalando `chromium` desde el repositorio `extra` debería ser suficiente
También tienes la opción de solo instalar ChromeDriver desde AUR. Si usas `pacaur`, ejecuta el siguiente comando:
```bash
pacaur -S chromedriver
```
Ya estás listo para [instalar Consul Democracy](local_installation.md)!!

View File

@@ -0,0 +1,186 @@
# Instalación en Heroku
## Instalación manual
Este tutorial asume que ya has conseguido clonar Consul Democracy en tu máquina y conseguir que funcione.
1. En primer lugar, necesitas crear una cuenta en [Heroku](https://www.heroku.com) si no lo has hecho ya.
2. Instala [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) e inicia sesión con:
```bash
heroku login
```
3. Accede a tu repositorio de Consul Democracy y crea una instancia
```bash
cd consuldemocracy
heroku create your-app-name
```
Puedes añadir `--region eu` si quieres utilizar servidores europeos en lugar de los estadounidenses.
Si _your-app-name_ no existe aún, Heroku creará tu aplicación.
4. Crea la base de datos con
```bash
heroku addons:create heroku-postgresql
```
Ahora deberías tener acceso a una base de datos Postgres vacía cuya dirección se guardó automáticamente como una variable de entorno llamada _DATABASE\_URL_. Consul Democracy se conectará automáticamente a ella durante la instalación.
5. **(No es necesario)** Crea un archivo con el nombre _heroku.yml_ en la raíz del proyecto y añade el siguiente código
```yml
build:
languages:
- ruby
packages:
- imagemagick
run:
web: bundle exec rails server -e ${RAILS_ENV:-production}
```
6. Ahora, genera una clave secreta y guárdala en la variable de entorno SECRET\_KEY\_BASE de la siguinte manera
```bash
heroku config:set SECRET_KEY_BASE=$(rails secret)
```
Añade también la dirección de tu servidor:
```bash
heroku config:set SERVER_NAME=myserver.address.com
```
Es necesario que la aplicación sepa dónde se almacenan las variables de configuración añadiendo un enlace a las variables de entorno en _config/secrets.yml_
```yml
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
server_name: <%= ENV["SERVER_NAME"] %>
```
y añade este archivo en el repositorio comentando la línea correspondiente en el _.gitignore_.
```gitignore
#/config/secrets.yml
```
**¡Recuerda no añadir el archivo si tienes información sensible en él!**
7. Ahora ya puedes subir tu aplicación utilizando:
```bash
git push heroku your-branch:master
```
8. No funcionará de inmediato porque la base de datos no contiene las tablas necesarias. Para crearlas, ejecuta
```bash
heroku run rake db:migrate
heroku run rake db:seed
```
Si quieres añadir los datos de prueba en la base de datos, mueve `gem 'faker', '~> 1.8.7'` fuera del `group :development` y ejecuta:
```bash
heroku config:set DATABASE_CLEANER_ALLOW_REMOTE_DATABASE_URL=true
heroku config:set DATABASE_CLEANER_ALLOW_PRODUCTION=true
heroku run rake db:dev_seed
```
9. Ahora tu aplicación debería estar ya opertaiva. Puedes abrirla con
```bash
heroku open
```
También puedes arrancar la consola en heroku utilizando
```bash
heroku console --app your-app-name
```
10. Heroku no permite guardar imágenes o documentos en sus servidores, por lo que es necesario configurar un nuevo espacio de almacenamiento.
Consulta [nuestra guía de S3](./using-aws-s3-as-storage.md) para más detalles sobre la configuración de Paperclip con S3.
### Configurar Sendgrid
Añade el complemento (add-on) de SendGrid en Heroku. Esto creará una cuenta de SendGrid para la aplicación con `ENV["SENDGRID_USERNAME"]` y `ENV["SENDGRID_PASSWORD"]`.
Añade el siguiente código a `config/secrets.yml`, en la sección `production:`:
```
mailer_delivery_method: :smtp
smtp_settings:
:address: "smtp.sendgrid.net"
:port: 587
:domain: "heroku.com"
:user_name: ENV["SENDGRID_USERNAME"]
:password: ENV["SENDGRID_PASSWORD"]
:authentication: "plain"
:enable_starttls_auto: true
```
Importante: Activa un "worker dyno" para que se envíen los correos electrónicos.
### Opcional (pero recomendado)
### Instalar rails\_12factor y especificar la versión de Ruby
**Instalar rails\_12factor sólo es útil si utilizas una versión de Consul Democracy anterior a la 1.0.0. La última versión utiliza Rails 5 que ya incluye los cambios.**
Como nos recomienda Heroku, puedes añadir la gema rails\_12factor y especificar la versión de Ruby a utilizar. Puedes hacerlo añadiendo:
```ruby
gem 'rails_12factor'
ruby 'x.y.z'
```
en el archivo _Gemfile\_custom_, donde `x.y.z` es la versión definida en el fichero `.ruby-version` del repositorio de Consul Democracy. No olvides ejecutar
```bash
bundle install
```
para generar el _Gemfile.lock_ antes de añadir los cambios y subirlos al servidor.
### Utilizar Puma como servidor web
Heroku recomienda utilizar Puma para mejorar el [rendimiento](http://blog.scoutapp.com/articles/2017/02/10/which-ruby-app-server-is-right-for-you) de la aplicación.
Si quieres permitir más concurrencia, descomenta la siguiente linea:
```ruby
workers ENV.fetch("WEB_CONCURRENCY") { 2 }
```
Puedes encontrar una explicación para diferentes configuraciones en el siguiente [tutorial de Heroku](https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server).
Por último hay que cambiar la tarea _web_ para usar Puma cambiándola en el archivo _heroku.yml_ con el siguiente código:
```yml
web: bundle exec puma -C config/puma.rb
```
### Añadir variables de configuración desde el panel de control
Las versiones gratuita y hobby de Heroku no son suficientes para ejecutar una aplicación como Consul Democracy. Para optimizar el tiempo de respuesta y asegurarte de que la aplicación no se quede sin memoria, puedes [cambiar el número de "workers" e hilos](https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#workers) que utiliza Puma.
La configuración recomendada es un "worker" y tres hilos. Puedes configurarlo ejecutando estos dos comandos:
```bash
heroku config:set WEB_CONCURRENCY=1
heroku config:set RAILS_MAX_THREADS=3
```
También es recomendable configurar las siguientes variables:
```bash
heroku config:set RAILS_SERVE_STATIC_FILES=enabled
heroku config:set RAILS_ENV=production
```

View File

@@ -0,0 +1,59 @@
# Instalando Consul Democracy en un VPS de Digital Ocean
Estas instrucciones le ayudaran a registrarse y comprar un servidor en Digital Ocean para instalar Consul Democracy.
Primero necesita [registrarse](https://cloud.digitalocean.com/registrations/new) y proporcionar su información personal.
Una vez que haya iniciado sesión, deberá crear un Droplet (ese es el nombre que Digital Ocean utiliza para un Servidor Virtual). Haga clic en el botón verde "Crear" en la parte superior de la página y seleccione "Droplets":
![Digital Ocean Droplets](../../img/digital_ocean/droplets.png)
En la página siguiente, debe seleccionar Ubuntu (debería estar preseleccionado) y cambiar la versión **de 18.04 x64 a 16.04 x64**.
![Digital Ocean Choose an image](../../img/digital_ocean/image.png)
En la sección "Elegir un tamaño" seleccione la opción **$80/mo 16GB/6CPUs** si va a ser un servidor de producción. Si está configurando un sistema de prueba con unos pocos usuarios, la opción más barata de $5/mes puede ser suficiente.
![Digital Ocean Choose a size](../../img/digital_ocean/size.png)
Deje el resto de las opciones con sus valores por defecto hasta "Elegir un centro de datos". Seleccione el que esté geográficamente más cerca de sus usuarios. Si se encuentra en la UE, seleccione los centros de datos de Frankfurt o Amsterdam.
![Digital Ocean Choose a region](../../img/digital_ocean/region.png)
En la sección "Añadir claves SSH" pulse el botón "Nueva clave SSH".
![Digital Ocean Add your SSH Keys](../../img/digital_ocean/ssh_keys.png)
En la ventana emergente que aparece es necesario copiar y pegar la clave pública que [generamos en el paso anterior](generating_ssh_key.md). Para ver el contenido de esta clave en la ventana del terminal, escriba:
```
cat ~/.ssh/id_rsa.pub
```
Debería ver un texto como este:
```
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDy/BXU0OsK8KLLXpd7tVnqDU+d4ZS2RHQmH+hv0BFFdP6PmUbKdBDigRqG6W3QBexB2DpVcb/bmHlfhzDlIHJn/oki+SmUYLSWWTWuSeF/1N7kWf9Ebisk6hiBkh5+i0oIJYvAUsNm9wCayQ+i3U3NjuB25HbgtyjR3jDPIhmg1xv0KZ8yeVcU+WJth0pIvwq+t4vlZbwhm/t2ah8O7hWnbaGV/MZUcj0/wFuiad98yk2MLGciV6XIIq+MMIEWjrrt933wAgzEB8vgn9acrDloJNvqx25uNMpDbmoNXJ8+/P3UDkp465jmejVd/6bRaObXplu2zTv9wDO48ZpsaACP your_username@your_computer_name
```
Seleccione y copie todo el texto y péguelo en la ventana emergente de la siguiente manera:
![Digital Ocean New SSH Key](../../img/digital_ocean/new_ssh.png)
Tenga en cuenta que habrá dos pequeños checks verdes. Si no están ahí, vuelva a intentar copiar el texto porque probablemente omitió algo. Dé a su clave un nombre significativo, como **Consul_Democracy_key** y haga clic en el botón "Add SSH Key" (Añadir clave SSH).
Al utilizar una clave SSH en lugar de una combinación de usuario/contraseña para acceder a su servidor, será mucho más seguro, ya que sólo alguien con la clave privada SSH puede acceder al servidor.
Ahora en la sección "Choose a hostname" cambie el valor por defecto por algo más significativo, como **consuldemocracyserver** por ejemplo.
![Digital Ocean hostname](../../img/digital_ocean/hostname.png)
En la parte inferior de la página verás un resumen de tus opciones. Compruebe que todo está bien y haga clic en el botón grande verde "Crear".
![Digital Ocean create](../../img/digital_ocean/create.png)
Tardará unos minutos, y al final tendrá un brillante nuevo servidor. Se verá así en la página de Digital Ocean:
![Digital Ocean server](../../img/digital_ocean/server.png)
Lo siguiente es configurar Consul Democracy en el servidor. Por favor [leer estas instrucciones](https://github.com/consuldemocracy/installer)

View File

@@ -0,0 +1,160 @@
# Usando Docker para desarrollo en local
Puedes usar Docker para tener una instalación local de Consul Democracy si:
- Estás teniendo problemas para instalar los [prerrequisitos](prerequisites.md) correctamente.
- Quieres tener una instalación local rápidamente para probar o hacer una demo.
- Prefieres no interferir con instalaciones de apps Rails existentes.
## Prerrequisitos
Debes tener instalador Docker y Docker Compose en tu ordenador:
### macOS
Puedes seguir la [guía oficial de docker](https://docs.docker.com/docker-for-mac/install/)
O si tienes instalado [homebrew](http://brew.sh) y [cask](https://caskroom.github.io/) puedes ejecutar:
```bash
brew install docker
brew install docker-compose
brew cask install docker
open -a docker
```
La aplicación de Docker te pedirá darle permisos e intrudocir tu contraseña.
### Linux
1. Instala Docker:
```bash
sudo apt-get update
sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
sudo apt-add-repository 'deb https://apt.dockerproject.org/repo ubuntu-xenial main'
sudo apt-get update
apt-cache policy docker-engine
sudo apt-get install -y docker-engine
```
2. Instala Docker Compose
```bash
sudo curl -o /usr/local/bin/docker-compose -L "https://github.com/docker/compose/releases/download/1.15.0/docker-compose-$(uname -s)-$(uname -m)"
sudo chmod +x /usr/local/bin/docker-compose
```
### Windows
En la página de [https://www.docker.com/get-started](Empezando con Docker), en la sección "Docker Desktop", selecciona "Download for Windows", y ejecútalo. Debería tardar unos 5 minutos.
Si encuentras el error "WSL 2 installation incomplete":
1. Ejecuta PowerShell como administrator
1. Ejecuta `dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart`
1. Ejecuta `dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart`
1. Instala el [paquete de actualización de WSL2 para 64 bits](https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi)
1. Ejecuta `wsl --set-default-version 2`
1. Reinicia el sistema
1. Se iniciará Docker Enginer. tardará unos minutos. Tras esto, tendrás la opción de usar la applicación de Docker Desktop y la orden `docker` de PowerShell/Bash
## Instalación
Clona el repositorio en tu ordenador y entra en el directorio:
```bash
git clone https://github.com/consuldemocracy/consuldemocracy.git
cd consuldemocracy
```
### macOS & Linux
Creamos nuestros ficheros de secrets y database basados en los ejemplos:
```bash
cp config/secrets.yml.example config/secrets.yml
cp config/database-docker.yml.example config/database.yml
```
Y generamos el contenedor:
```bash
POSTGRES_PASSWORD=password docker-compose build
```
Arrancamos el servicio de base de datos:
```bash
POSTGRES_PASSWORD=password docker-compose up -d database
```
Ahora podemos crear la base de datos e introducir datos de prueba:
```
POSTGRES_PASSWORD=password docker-compose run app rake db:create db:migrate
POSTGRES_PASSWORD=password docker-compose run app rake db:dev_seed
```
### Windows
Pendiente de ser completado... ¡Se agradecen las Contribuciones!
## Corriendo Consul Democracy en local con Docker
### macOS & Linux
Una vez instalado, puedes lanzar la aplicación con:
```bash
POSTGRES_PASSWORD=password docker-compose up
```
Y podrás acceder a la aplicación desde tu navegador visitando [http://localhost:3000](http://localhost:3000)
Adicionalmente, si quieres lanzar por ejemplo la consola de rails:
```bash
POSTGRES_PASSWORD=password docker-compose run app rails console
```
Para verificar que los contenedores estan corriendo usa:
```bash
docker ps .
```
Deberías obtener algo similar a:
![docker ps](https://i.imgur.com/ASvzXrd.png)
### Windows
Pendiente de ser completado... ¡Se agradecen las Contribuciones!
## ¿Tienes problemas?
Ejecute los comandos en el **directorio de Consul Democracy**, para borrar todas las imágenes y contenedores anteriores del Docker de Consul Democracy. Luego, reinicie el [proceso de instalación](#instalacion) de Docker:
1. Quitar todas las imágenes de Consul Democracy:
```bash
docker-compose down --rmi all -v --remove-orphans
```
2. Quitar todos los contenedores de Consul Democracy
```bash
docker-compose rm -f -s -v
```
3. Verificar si todavía hay algún contenedor:
```bash
docker ps -a
```
Caso positivo, eliminar cada uno de forma manual:
```bash
docker container rm <container_id>
```

View File

@@ -0,0 +1,9 @@
# Documentación y guías sonbre Consul Democracy
Hay diversas guías donde puedes leer información muy detallada sobre Consul Democracy y sus posibilidades. Puedes encontrarlas todas en: <http://consuldemocracy.org/es/#documentation>
- **Guía de uso de Consul Democracy**. En esta guía puedes ver las diferentes maneras de usar Consul Democracy y ejemplos de procesos de participación.
- **Guía de administración de Consul Democracy**. Esta guía contiene información detallada sobre la administración y gestión de Consul Democracy.
- **Guía de comunicación de Consul Democracy**. Esta guía te puede ofrecer una idea inicial de cómo planear campañas de comunicación para invitar a la gente a usar tu instalación de Consul Democracy. La comunicación es una cuestión clave a la hora de conseguir una participación relevante.
Además de estas guías puedes acceder a la [Comunidad Consul Democracy](http://community.consulproject.org/), un espacio de debate para compartir más documentación, dudas, aprendizajes, etc.

View File

@@ -0,0 +1,18 @@
# Generación de claves SSH
Estas instrucciones le ayudarán a generar una clave pública con la que podrá conectarse al servidor sin necesidad de utilizar una contraseña.
En la ventana del terminal, escriba:
```
ssh-keygen
```
Cuando se le pida el archivo en el que guardar la clave, sólo tiene que pulsar ENTER para dejar el valor predeterminado. Cuando se le pida una frase de contraseña, pulse ENTER de nuevo para dejarla vacía. Al final debería ver un mensaje como este:
```
Your identification has been saved in /your_home/.ssh/id_rsa.
Your public key has been saved in /your_home/.ssh/id_rsa.pub.
```
Tome nota de la ubicación del archivo **id_rsa.pub**, porque necesitará el contenido de este archivo más adelante.

View File

@@ -0,0 +1,5 @@
# Instalador
## Instrucciones de instalación para entornos de Producción y Pruebas
Se encuentran en el [repositorio del instalador](https://github.com/consuldemocracy/installer)

View File

@@ -0,0 +1,11 @@
# Introducción
Estas son nuestras recomendaciones para los diferentes entornos y propósitos:
- Para configurar Consul Democracy para un entorno de producción, recomendamos utilizar el [instalador](https://github.com/consuldemocracy/installer).
- Para los programadores que trabajan en un entorno de desarrollo, recomendamos instalar Consul Democracy en un sistema basado en UNIX (Linux o Mac) y hacer una [instalación local](local_installation.md) de Consul Democracy.
- Si tienes problemas para hacer una instalación local y deseas mostrar Consul Democracy para fines de demostración, te recomendamos que utilices [Docker](docker.md) en tu ordenador personal.
- También tenemos una [Guía Heroku](deploying-on-heroku.md) que se puede utilizar para fines de demostración en un servidor remoto.

View File

@@ -0,0 +1,73 @@
# Instalación local
Antes de comenzar a instalar Consul Democracy, comprueba que tengas todos los [prerrequisitos](prerequisites.md) correctamente instalados.
1. Primero, clona el [repositorio de Consul Democracy en Github](https://github.com/consuldemocracy/consuldemocracy/) y ve a la carpeta del proyecto:
```bash
git clone https://github.com/consuldemocracy/consuldemocracy.git
cd consuldemocracy
```
2. Instala la versión de Ruby necesaria con el gestor de versiones de tu elección. Algunos ejemplos:
```bash
rvm install `cat .ruby-version` # Si usas RVM
rbenv install `cat .ruby-version` # Si usas rbenv
asdf install ruby `cat .ruby-version` # Si usas asdf
```
3. Comprueba que estemos usando la versión de Ruby que acabamos de instalar:
```bash
ruby -v
=> # (debería aparecer la versión mencionada en el fichero .ruby-version)
```
4. Instala [Bundler](http://bundler.io/)
```bash
gem install bundler --version 1.17.1
```
5. Instala las gemas requeridas usando Bundler:
```bash
bundle
```
6. Copia los archivos de configuración de ejemplo del entorno dentro de unos nuevos válidos:
```bash
cp config/database.yml.example config/database.yml
cp config/secrets.yml.example config/secrets.yml
```
Y configura los de tu usuario de base de datos `consul` en `database.yml`
7. Ejecuta las siguientes [tareas Rake](https://github.com/ruby/rake) para crear y rellenar tu base de datos local con el mínimo de información necesaria para que la aplicación funcione correctamente:
```bash
bin/rake db:create
bin/rake db:setup
bin/rake db:dev_seed
bin/rake db:test:prepare
```
8. Comprueba que todo funciona correctamente lanzando la suite de tests (ten en cuenta que podría tardar más de una hora):
```bash
bin/rspec
```
9. Ahora que ya está todo listo puedes ejecutar la aplicación:
```bash
bin/rails s
```
¡Felicidades! Tu aplicación Consul Democracy local estará corriendo en `http://localhost:3000`.
En caso de que quieras acceder a la aplicación local como usuario administrador existe un usuario por defecto verificado y con permisos con **nombre de usuario** `admin@consul.dev` y **contraseña** `12345678`.
Si necesitas un usuario específico que pueda realizar acciones como votar sin permisos de administración, dispones de otro usuario verificado con **nombre de usuario** `verified@consul.dev` y **contraseña** `12345678`.

View File

@@ -0,0 +1,109 @@
# Configuración para los entornos de desarrollo y pruebas (Mac OS X)
## Homebrew
Homebrew es un gestor de paquetes para OS X muy popular. Es recomendable usarlo pues facilita enormemente la instalación de algunos de los paquetes necesarios.
Puedes encontrar las instrucciones de instalación en: [brew.sh](http://brew.sh)
## XCode y XCode Command Line Tools
Para utilizar git necesitarás instalar *Xcode* (está en la Mac App Store) y las *Xcode Command Line Tools* (se instalan desde el menú de Xcode).
## Git y Github
Puedes descargar git desde: [git-scm.com/download/mac](https://git-scm.com/download/mac)
## Gestor de versiones de Ruby
OS X ya viene con una versión preinstalada de ruby, pero es bastante vieja y en nuestro caso no nos sirve. Una de las formas de instalar Ruby es a través de rbenv. Las instrucciones de instalación están en su GitHub y son bastante claras:
[github.com/rbenv/rbenv](https://github.com/rbenv/rbenv)
## Bundler
```
gem install bundler
```
## Node.js
Para compilar los archivos estáticos (JS, CSS, imágenes, etc.), es necesario un _runtime_ de JavaScript. OS X viene con un _runtime_ integrado llamado `Apple JavaScriptCore` pero Node.js es la opción recomendada.
Para instalar Node, puedes usar [n](https://github.com/tj/n)
Ejecuta el siguiente comando en tu terminal:
```
curl -L https://git.io/n-install | bash -s -- -y lts
```
Y este instalará automáticamente la versión LTS (_Long Term Support_, inglés para "Soporte a largo plazo") más reciente de Node en tu directorio `$HOME` (Este comando hace uso de [n-install](https://github.com/mklement0/n-install))
## PostgreSQL (>=9.4)
```
brew install postgres
```
Una vez instalado es necesario *inicializar* la instalación:
```
initdb /usr/local/var/postgres
```
Ahora vamos a configurar algunos aspectos del usuario por defecto. Primero iniciamos el servidor de postgres con:
```
postgres -D /usr/local/var/postgres
```
Llegados a este punto se supone que tenemos postgres correctamente instalado y se nos habrá creado un usuario por defecto (cuyo nombre es nuestro nombre de usuario), y que (todavía) no tiene contraseña.
Si ejecutamos `psql` accederemos a la consola de postgres con el usuario por defecto. Probablemente fallará porque es necesario que de antemano exista una base de datos por defecto para dicho usuario. Podemos crearla ejecutando sobre la terminal:
```
createdb 'tu_nombre_de_usuario'
```
Si ahora ejecutamos `psql` de nuevo deberíamos poder acceder correctamente a la consola de postgres. Si sobre la consola de postgres ejecutas `\du` puede ver la lista de usuarios actual.
En el caso de que quieras asignarte una contraseña puedes hacerlo desde la consola de postgres con:
```
ALTER USER tu_nombre_usuario WITH PASSWORD 'tu_contraseña';
```
Ahora vamos a crear el usuario *consul*, que es el que utiliza la aplicación. Ejecuta sobre la consola de postgres:
```
CREATE ROLE consul WITH PASSWORD '000';
ALTER ROLE consul WITH SUPERUSER;
ALTER ROLE consul WITH login;
```
Si en algún momento durante la instalación de PostgreSQL y sospechas que te has equivocado y deseas desinstalarlo y volver a empezar desde cero:
```
brew uninstall postgres
```
También tendrás que borrar el siguiente directorio para que no de conflictos cuando intentes volver a instalarlo (fuente: [gist.github.com/lxneng/741932](https://gist.github.com/lxneng/741932)):
```
rm -rf /usr/local/var/postgres
```
## ChromeDriver
```
brew install chromedriver
```
## Imagemagick
```
brew install imagemagick
```
Ahora que ya tenemos todas las dependencias instalado podemos proceder con la [instalación de Consul Democracy](local_installation.md)

View File

@@ -0,0 +1,38 @@
# Configuración del servidor de correo
Este es un ejemplo de cómo integrar un servicio de correo con Consul Democracy.
En este ejemplo usamos [Mailgun](https://www.mailgun.com/).
## Crear una cuenta en Mailgun
![Creando una cuenta en Mailgun](../../img/mailserver/mailgun-create-account.png)
* Puedes omitir el formulario de tarjeta de crédito
* Y activa tu cuenta con el enlace enviado por correo electrónico
## Configuración del dominio
* Ve a la sección "domain": ![Mailgun sección domain](../../img/mailserver/mailgun-domains.png)
* Como todavía no tienes un dominio, debes pinchar en el "sandbox" que ya está creado
* Recuerda las siguientes credenciales: ![Mailgun sandbox](../../img/mailserver/mailgun-sandbox.png)
## Configuración del correo en Consul Democracy
* Ve al archivo `config/secrets.yml`
* Modifica las líneas en el archivo para configurar el servidor de correo:
```yml
mailer_delivery_method: :smtp
smtp_settings:
:address: "<smtp address>"
:port: 587
:domain: "<domain>"
:user_name: "<user_name>"
:password: "<password>"
:authentication: "plain"
:enable_starttls_auto: true
```
* Rellena `<smtp address>`, `<domain>`, `<user_name>` y `<password>` con tu información.
* Guarda el fichero y reinicia tu aplicación Consul Democracy

View File

@@ -0,0 +1,93 @@
# Instalación manual en producción
**AVISO:** Recomendamos *no usar* este sistema, para el que no damos soporte oficial, ya que siempre que sea posible debe utilizarse el [instalador](https://github.com/consuldemocracy/installer). Utiliza este método si usar el instalador no es una opción y si tienes experiencia configurando PostgreSQL, puma o passenger, NGNIX y SSL (con letsencrypt, por ejemplo).
Esta guía asume que ya has [instalado todas las dependencias necesarias](prerequisites.md) en tu sistema.
La estructura de directorios que se crea a continuación está pensada para usarse con [capistrano](https://capistranorb.com/documentation/getting-started/structure/).
## Estructura de directorios
En primer lugar, crea el directorio principal, clona el repositorio y crea los subdirectorios necesarios:
```
mkdir consul && cd consul
git clone --mirror https://github.com/consuldemocracy/consuldemocracy.git repo
mkdir releases shared
mkdir shared/log shared/tmp shared/config shared/public shared/storage
mkdir -p shared/public/assets shared/public/system shared/public/ckeditor_assets shared/public/machine_learning/data
```
## Versión inicial
Crea una primera carpeta en "releases" a partir del repositorio, junto con un enlace simbólico a la versión actual (sustituye `<latest_consul_stable_version>` por el número de la última versión estable de Consul Democracy, como 1.3.1 o 1.4.1):
```
cd repo
git archive <latest_consul_stable_version> | tar -x -f - -C ../releases/first
cd ..
ln -s releases/first current
```
## Instalación de gemas
Instala las gemas de las que depende Consul Democracy:
```
cd releases/first
bundle install --path ../../shared/bundle --without development test
cd ../..
```
## Ficheros de configuración
Genera los ficheros `database.yml` y `secrets.yml`:
```
cp current/config/secrets.yml.example shared/config/secrets.yml
cp current/config/database.yml.example shared/config/database.yml
cd releases/first/config
ln -s ../../../shared/config/database.yml
ln -s ../../../shared/config/secrets.yml
cd ../../..
```
Edita el fichero `shared/config/database.yml`, rellenando `username` y `password` con los datos generador durante la [configuración de PostgreSQL](debian.md#postgresql-94).
Ahora generamos una clave secreta:
```
cd current
bin/rake secret RAILS_ENV=production
cd ..
```
Copia la clave generada y edita el fichero `shared/config/secrets.yml`; en la sección `production`, cambia los siguientes datos:
```
secret_key_base: introduce_la_clave_secreta_que_acabas_de_generar
server_name: introduce_tu_dominio
```
Si no tienes un certificado SSL, cambia además `force_ssl: true` por `force_ssl: false`.
## Base de datos
Crea una base de datos, genera los datos necesarios para que la aplicación funcione y compila los ficheros de CSS y JavaScript:
```
cd current
bin/rake db:migrate RAILS_ENV=production
bin/rake db:seed RAILS_ENV=production
bin/rake assets:precompile RAILS_ENV=production
```
## Arranque de la aplicación
Y, por último, inicia el servidor de Rails:
```
bin/rails s -e production
```
¡Enhorabuena! Ahora tu servidor está funcionando en el entorno de producción :smile:.

View File

@@ -0,0 +1,6 @@
# Instalación de Prerrequisitos
* [Ubuntu Linux](ubuntu.md)
* [Debian Linux](debian.md)
* [MacOS](macos.md)
* [Windows](windows.md)

View File

@@ -0,0 +1,21 @@
# Servidores de producción y pruebas
## Requisitos de sistema mínimos recomendados
### 1. Production Server
- Distrubution: Ubuntu 16.04.X
- RAM: 32GB
- Processor: Quad core
- Hard Drive: 20 GB
- Database: Postgres
### 2. Staging Server
- Distrubution: Ubuntu 16.04.X
- RAM: 16GB
- Processor: Dual core
- Hard Drive: 20 GB
- Database: Postgres
Si tu ciudad tiene una población superior a 1.000.000, considera añadir un balanceador de carga y usar 2-3 servidores de producción, además de un servidor de base de datos dedicado.

View File

@@ -0,0 +1,111 @@
# Configuración para los entornos de desarrollo y pruebas (Ubuntu 18.04)
## Actualización de sistema
Ejecuta una actualización general de las librerías de sistema:
```bash
sudo apt update
```
## Git
Git es mantenido oficialmente en Ubuntu:
```bash
sudo apt install git
```
## Gestor de versiones de Ruby
Las versiones de Ruby empaquetadas en repositorios oficiales no son aptas para trabajar con Consul Democracy, así que debemos instalarlo manualmente.
En primer lugar, necesitamos los siguiente paquetes para poder instalar Ruby:
```bash
sudo apt install libssl-dev autoconf bison build-essential libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm5 libgdbm-dev
```
A continuación instalaremos un gestor de versiones de Ruby, como rbenv:
```bash
wget -q https://github.com/rbenv/rbenv-installer/raw/master/bin/rbenv-installer -O- | bash
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
source ~/.bashrc
```
## Node.js
Para compilar los archivos estáticos (JS, CSS, imágenes, etc.), es necesario un _runtime_ de JavaScript. Node.js es la opción recomendada.
Ejecuta en tu terminal:
```bash
sudo apt install nodejs
```
## PostgreSQL
Instala postgresql y sus dependencias de desarrollo con:
```bash
sudo apt install postgresql libpq-dev
```
Para el correcto funcionamiento de Consul Democracy, necesitas confgurar un usuario para tu base de datos. Como ejemplo, crearemos un usuario llamado "consul":
```bash
sudo -u postgres createuser consul --createdb --superuser --pwprompt
```
Para asegurarse que se utiliza la codificación con UTF-8, crea un archivo:
```
sudo nano /etc/profile.d/lang.sh
```
Añade las siguientes líneas:
```
export LANGUAGE="en_US.UTF-8"
export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
```
Reconfigura Postgres para utilizar la codificación UTF-8:
`````
sudo su - postgres
psql
update pg_database set datistemplate=false where datname='template1';
drop database Template1;
create database template1 with owner=postgres encoding='UTF-8'
lc_collate='en_US.utf8' lc_ctype='en_US.utf8' template template0;
update pg_database set datistemplate=true where datname='template1';
\q
exit
`````
## Imagemagick
Instala Imagemagick:
```bash
sudo apt install imagemagick
```
## ChromeDriver
Para realizar pruebas de integración, usamos Selenium junto a Headless Chrome.
Para poder utilizarlo, instala el paquete chromium-chromedrive y asegúrate de que se encuentre enlazado en algún directorio que esté en la variable de entorno PATH:
```bash
sudo apt install chromium-chromedriver
sudo ln -s /usr/lib/chromium-browser/chromedriver /usr/local/bin/
```
¡Ya estás listo para [instalar Consul Democracy](local_installation.md)!

View File

@@ -0,0 +1,45 @@
# Vagrant
Instale [Vagrant](https://www.vagrantup.com/) y configure una máquina virtual con [Linux](prerequisites.md)
Vagrant es compatible para [Debian](/es/installation/debian.md) y [Ubuntu](/es/installation/ubuntu.md).
## Browser configuration
Para acceder a la aplicación a través del navegador en la url `localhost:3000` debe enrutar el puerto de la aplicación y ejectuar el servidor de la aplicación con la opción `-b`:
## Enrutar el puerto de la aplicación
Abra el archivo de configuración de Vagrant:
```
nano Vagranfile
```
Encuentre esta línea:
```
# config.vm.network "forwarded_port", guest: 80, host: 8080
```
Cámbiela por esta:
```
config.vm.network "forwarded_port", guest: 3000, host: 3000
```
Recargue la máquina virtual:
```
vagrant reload
```
## Ejecutar el servidor
En su máquina virtual, debe ejecutar la aplicación enlanzándola a su IP local:
```
bin/rails s -b 0.0.0.0
```
Ahora debería ver la aplicación desde el navegardor en la url `localhost:3000` :tada:

View File

@@ -0,0 +1,3 @@
# Windows
De momento Windows no es un sistema operativo compatible. Por favor instale [Virtual Box](https://www.virtualbox.org/) para crear una máquina virtual en [Linux](prerequisites.md).

View File

@@ -0,0 +1,46 @@
# Código de conducta
## Nuestro compromiso
En el interés de fomentar una comunidad abierta y acogedora, nosotros como contribuyentes y administradores nos comprometemos a hacer de la participación en nuestro proyecto y nuestra comunidad una experiencia libre de acoso para todos, independientemente de la edad, dimensión corporal, discapacidad, etnia, identidad y expresión de género, nivel de experiencia, nacionalidad, apariencia física, raza, religión, identidad u orientación sexual.
## Nuestros estándares
Ejemplos de comportamiento que contribuyen a crear un ambiente positivo:
* Uso de lenguaje amable e inclusivo.
* Respeto a diferentes puntos de vista y experiencias.
* Aceptación de críticas constructivas.
* Enfocarse en lo que es mejor para la comunidad.
* Mostrar empatía a otros miembros de la comunidad.
Ejemplos de comportamiento inaceptable por participantes:
* Uso de lenguaje o imágenes sexuales y atención sexual no deseada.
* Comentarios insultantes o despectivos (*trolling*) y ataques personales o políticos.
* Acoso público o privado.
* Publicación de información privada de terceros sin su consentimiento, como direcciones físicas o electrónicas.
* Otros tipos de conducta que pudieran considerarse inapropiadas en un entorno profesional..
## Nuestras responsabilidades
Los administradores del proyecto son responsables de clarificar los estándares de comportamiento aceptable y se espera que tomen medidas correctivas y apropiadas en respuesta a situaciones de conducta inaceptable.
Los administradores del proyecto tienen el derecho y la responsabilidad de eliminar, editar o rechazar comentarios, *commits*, código, ediciones de documentación, *issues*, y otras contribuciones que no estén alineadas con este Código de Conducta, o de prohibir temporal o permanentemente a cualquier colaborador cuyo comportamiento sea inapropiado, amenazante, ofensivo o perjudicial.
## Alcance
Este código de conducta aplica tanto a espacios del proyecto como a espacios públicos donde un individuo esté en representación del proyecto o comunidad. Ejemplos de esto incluye el uso de la cuenta oficial de correo electrónico, publicaciones a través de las redes sociales oficiales, o presentaciones con personas designadas en eventos *online* u *offline*. La representación del proyecto puede ser clarificada explicitamente por los administradores del proyecto.
## Aplicación
Ejemplos de abuso, acoso u otro tipo de comportamiento inaceptable puede ser reportado al equipo del proyecto en [consul@madrid.es](mailto:consul@madrid.es). Todas las quejas serán revisadas e investigadas, generando un resultado apropiado a las circunstancias. El equipo del proyecto está obligado a mantener confidencialidad de la persona que reportó el incidente. Detalles específicos acerca de las políticas de aplicación pueden ser publicadas por separado.
Administradores que no sigan o que no hagan cumplir este Código de Conducta pueden ser eliminados de forma temporal o permanente del equipo administrador.
## Atribución
Este Código de Conducta es una adaptación del [Contributor Covenant][homepage], versión 1.4, disponible en [http://contributor-covenant.org/version/1/4/es/][version].
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/es/

View File

@@ -0,0 +1,39 @@
# Contribuciones
Te agradecemos que quieras colaborar contribuyendo a Consul Democracy. Aquí tienes una guía donde consultar cómo sugerir cambios y mejoras al proyecto.
## Reportar un issue
Si has visto algún error en la plataforma o directamente en el código, te animamos a [abrir un issue en el repositorio en Github de Consul Democracy](https://github.com/consuldemocracy/consuldemocracy/issues/new).
Antes de hacerlo, **por favor tómate un tiempo para comprobar los [issues ya existentes](https://github.com/consuldemocracy/consuldemocracy/issues) y asegúrate de que lo que estás a punto de reportar no ha sido reportado previamente** por otra persona. De ser así, si tienes más detalles acerca de la incidencia puedes escribir un comentario en la página del issue ¡un poco de ayuda puede marcar una gran diferencia!
Para escribir un nuevo issue, ten en cuenta estas recomendaciones para hacerlo más fácil de leer y comprender:
- Intenta usar un título descriptivo.
- Es buena idea incluir algunas secciones -en caso de que sean necesarias- como los pasos para reproducir el error, el comportamiento o respuesta que cabría esperar, la respuesta que devuelve o capturas de pantalla.
- También puede ser de ayuda incluir en la descripción tu sistema operativo, versión del navegador que usaste y posibles plugins instalados.
## Resolver un issue
[Los issues en Consul Democracy](https://github.com/consuldemocracy/consuldemocracy/issues) con la etiqueta `PRs-welcome` son funcionalidades bien definidas que están listas para ser implementadas por cualquiera que se ofrezca a ello. Por otra parte, la etiqueta `not-ready` indica las funcionalidades o cambios que aún están pendientes de concretar, por lo que recomendamos no intentar resolverlos hasta que los/as administradores/as lleguen a una resolución.
Te sugerimos seguir los siguientes pasos para facilitar el seguimiento de los cambios que vayas a hacer:
- Primero, añade un comentario en el issue para notificar que vas resolverlo. Si el issue tiene a alguien asignado significa que ya hay alguien encargado de él.
- Crea un fork del proyecto.
- Crea una rama de funcionalidad basada en la rama `master`. Para identificarla más fácilmente, puedes nombrarla con el número del issue seguido de un nombre conciso y descriptivo (por ejemplo: `123-fix_proposals_link`).
- Desarrolla los cambios haciendo commits en tu nueva rama.
- Asegúrate de que todos los tests pasan. Si estás extendiendo una funcionalidad o creando una nueva, considera añadir sus propios tests.
- Cuando hayas terminado, envía un **pull request** al [repositorio de Consul Democracy](https://github.com/consuldemocracy/consuldemocracy/) describiendo la solución que propones para ayudarnos a entenderlo. También es importante que especifiques qué issue estás resolviendo al principio de la descripción del PR (por ejemplo, `Fixes #123`).
- El equipo de Consul Democracy revisará tu PR y podrá sugerir cambios si son necesarios. Una vez esté todo bien, tus cambios serán introducidos en el proyecto :)
> **¿Es tu primer Pull Request?** Puedes aprender cómo contribuir a un proyecto en Github siguiendo los tutoriales [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github) (en inglés).
## Otras formas de contribuir
Agradecemos cualquier tipo de contribución a Consul Democracy. Incluso si no puedes contribuir al código del proyecto, puedes:
- Crear issues sobre cualquier problema o error que hayas encontrado.
- Ayudar a traducir la plataforma a otros idiomas que domines en el proyecto de [Consul Democracy en Crowdin](https://crwd.in/consul).
- Ayudar con la [documentación de Consul Democracy](https://github.com/consuldemocracy/docs).

Some files were not shown because too many files have changed in this diff Show More