-
class AuthenticateUser
-
prepend SimpleCommand
-
-
def initialize(email, password)
-
@email = email
-
@password = password
-
end
-
-
def call
-
JsonWebToken.encode(user_id: user.id) if user
-
end
-
-
private
-
-
attr_accessor :email, :password
-
-
-
def user
-
user = User.find_by_email(email)
-
if (!user)
-
errors.add :user_authentication, 'invalid user'
-
return nil
-
end
-
associate = Associate.where(association_state: 'running').find_by_user_id(user.id)
-
cruzaGrafos = CruzaGrafosUser.where('user_state=? OR in_trial=?', 'running', 'true' ).find_by_user_id(user.id)
-
return user if associate && associate.user.valid_password?(password)
-
return user if cruzaGrafos && cruzaGrafos.user.valid_password?(password)
-
-
errors.add :user_authentication, 'invalid credentials'
-
nil
-
end
-
end
-
class AuthorizeApiRequest
-
prepend SimpleCommand
-
-
def initialize(headers = {})
-
@headers = headers
-
end
-
-
def call
-
user
-
end
-
-
private
-
-
attr_reader :headers
-
-
def user
-
begin
-
@user ||= User.find(decoded_auth_token[:user_id]) if decoded_auth_token
-
rescue ActiveRecord::RecordNotFound => e
-
@user = nil
-
end
-
@user || errors.add(:token, 'Invalid token') && nil
-
end
-
-
def decoded_auth_token
-
@decoded_auth_token ||= JsonWebToken.decode(http_auth_header)
-
end
-
-
def http_auth_header
-
if headers['Authorization'].present?
-
return headers['Authorization'].split(' ').last
-
else
-
errors.add(:token, 'Missing token')
-
end
-
nil
-
end
-
end
-
class Admin::ApiController < ApplicationController
-
respond_to :json
-
before_action :authenticate_request
-
-
def validateAssociate
-
associate = Associate.find_by_cpf(params[:cpf])
-
if associate
-
render json: associate.to_json
-
else
-
render json: { msg: false }, status: :unauthorized
-
end
-
end
-
-
def me
-
render json: {
-
user_data: {
-
email: @current_user.email,
-
full_name: @current_user.name,
-
id: @current_user.id,
-
associate: @current_user.associate ? @current_user.associate.id : nil,
-
cruza_grafos: @current_user.cruza_grafos_user ? @current_user.cruza_grafos_user.id : nil,
-
cpf: if @current_user.associate
-
@current_user.associate.cpf
-
else
-
@current_user.cruza_grafos_user ? @current_user.cruza_grafos_user.cpf : nil
-
end,
-
}
-
}
-
end
-
end
-
class Admin::AssociatesController < ApplicationController
-
# before_action :authenticate_admin!
-
before_action :set_associate, only: %i[show edit update destroy]
-
-
# GET /admin_associates
-
def index
-
@associates = Associate.all
-
end
-
-
# GET /admin_associates/1
-
def show; end
-
-
# GET /admin_associates/new
-
def new
-
@associate = Associate.new
-
end
-
-
# GET /admin_associates/1/edit
-
def edit; end
-
-
# POST /admin_associates
-
def create
-
@associate = Associate.new(associate_params)
-
-
if @associate.save
-
redirect_to [:admin, @associate], notice: 'Associate was successfully created.'
-
else
-
render :new
-
end
-
end
-
-
# PATCH/PUT /admin_associates/1
-
def update
-
if @associate.update(associate_params)
-
redirect_to [:admin, @associate], notice: 'Associate was successfully updated.'
-
else
-
render :edit
-
end
-
end
-
-
# DELETE /admin_associates/1
-
def destroy
-
@associate.destroy
-
redirect_to admin_associates_url, notice: 'Admin associate was successfully destroyed.'
-
end
-
-
private
-
# Use callbacks to share common setup or constraints between actions.
-
def set_admin_associate
-
@associate = Associate.find(params[:id])
-
end
-
-
# Only allow a trusted parameter "white list" through.
-
def admin_associate_params
-
params.require(:associate).permit(:cpf, :phone, :country, :state, :city, :zipcode, :address_street, :neighborhood, :address_number, :address_complement, :activity_description, :details_file, :accepted_terms, :active, :accepted_terms_at, :approval_payment_date, :valid_until, :association_state, :payment_type, :code_of_ethics_terms, :code_of_ethics_terms_at, :whatsapp)
-
end
-
end
-
class Admin::AuthenticationController < ApplicationController
-
skip_before_action :authenticate_request
-
before_action :authenticate_internal_token
-
-
-
def authenticate
-
command = AuthenticateUser.call(params[:email], params[:password])
-
-
if command.success?
-
render json: { success: true, auth_token: command.result }
-
else
-
render json: { success: false, error: command.errors }, status: :unauthorized
-
end
-
end
-
-
def authenticate_internal_token
-
render json: { error: 'Not Authorized' }, status: 401 unless params[:token] == ENV['TOKEN_API']
-
end
-
end
-
class Admin::CruzaGrafosUsersController < ApplicationController
-
before_action :set_admin_cruza_grafos_user, only: [:show, :edit, :update, :destroy]
-
before_action :authenticate_admin!
-
layout 'admin'
-
-
-
# GET /admin/cruza_grafos_users
-
def index
-
@admin_cruza_grafos_users = CruzaGrafosUser.all
-
respond_to do |format|
-
format.html
-
format.xlsx
-
end
-
end
-
-
# GET /admin/cruza_grafos_users/1
-
def show
-
if @admin_cruza_grafos_user
-
@payments = @admin_cruza_grafos_user.payments
-
end
-
end
-
-
# GET /admin/cruza_grafos_users/new
-
def new
-
@admin_cruza_grafos_user = CruzaGrafosUser.new
-
end
-
-
# GET /admin/cruza_grafos_users/1/edit
-
def edit
-
@types = CruzaGrafosType.all
-
end
-
-
# POST /admin/cruza_grafos_users
-
def create
-
@admin_cruza_grafos_user = CruzaGrafosUser.new(admin_cruza_grafos_user_params)
-
-
if @admin_cruza_grafos_user.save
-
render @admin_cruza_grafos_user, notice: 'Cruza grafos user was successfully created.'
-
else
-
render :new
-
end
-
end
-
-
# PATCH/PUT /admin/cruza_grafos_users/1
-
def update
-
@payments = @admin_cruza_grafos_user.payments
-
if @admin_cruza_grafos_user.update(admin_cruza_grafos_user_params)
-
# redirect_to @admin_cruza_grafos_user, notice: 'Cruza grafos user was successfully updated.'
-
render :show
-
else
-
render :edit
-
end
-
end
-
-
# DELETE /admin/cruza_grafos_users/1
-
def destroy
-
@admin_cruza_grafos_user.destroy
-
redirect_to admin_cruza_grafos_users_url, notice: 'Cruza grafos user was successfully destroyed.'
-
end
-
-
def start; end
-
def approve_moderation
-
CruzaGrafosUser.find(params['id']).approve_moderation!
-
redirect_to admin_cruza_grafos_users_path
-
end
-
def reject_moderation
-
cruzaGrafosUser = CruzaGrafosUser.find(params['id'])
-
cruzaGrafosUser.motive = params['reason']
-
cruzaGrafosUser.save
-
cruzaGrafosUser.reject_moderation!
-
redirect_to admin_cruza_grafos_users_path
-
end
-
def payment_confirm; end
-
def payment_reject; end
-
def expire; end
-
-
private
-
# Use callbacks to share common setup or constraints between actions.
-
def set_admin_cruza_grafos_user
-
@admin_cruza_grafos_user = CruzaGrafosUser.find(params[:id])
-
end
-
-
# Only allow a trusted parameter "white list" through.
-
def admin_cruza_grafos_user_params
-
# params.fetch(:admin_cruza_grafos_user, {})
-
params.require(:cruza_grafos_user).permit!
-
end
-
-
end
-
class AdminsController < ApplicationController
-
respond_to :html
-
before_action :set_admin, only: %i[show edit update destroy]
-
layout 'admin'
-
-
before_action :authenticate_admin!
-
-
def index
-
@admins = Admin.all
-
end
-
-
def show; end
-
-
def edit; end
-
-
def new
-
@admin = Admin.new
-
end
-
-
def create
-
@admin = Admin.new(admin_params)
-
-
if @admin.save
-
redirect_to admin_path(@admin), notice: 'User was successfully created.'
-
else
-
render :new
-
end
-
end
-
-
def update
-
if admin_params[:password].blank? && admin_params[:password_confirmation].blank?
-
admin_params.delete(:password)
-
admin_params.delete(:password_confirmation)
-
end
-
if @admin.update(admin_params)
-
redirect_to admin_path(@admin), notice: 'User was successfully updated.'
-
else
-
render :edit
-
end
-
end
-
-
def destroy
-
@admin.destroy
-
redirect_to admins_path, notice: 'User was successfully destroyed.'
-
end
-
-
private
-
def set_admin
-
@admin = Admin.find_by(id: params[:id])
-
end
-
-
def admin_params
-
params.require(:admin).permit!
-
end
-
end
-
class ApplicationController < ActionController::Base
-
before_action :load_menu_options
-
before_action :configure_permitted_parameters, if: :devise_controller?
-
-
before_action :authenticate_request, if: :json_request
-
-
protect_from_forgery if: :json_request # return null session when API call
-
protect_from_forgery with: :exception, unless: :json_request
-
-
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
-
add_breadcrumb 'home', '/'
-
-
protected
-
def record_not_found
-
redirect_to '/404.html', status: 302
-
end
-
-
def load_menu_options
-
@main_menu_options = MainMenuOption.all
-
@secundary_menu_options = SecundaryMenuOption.all
-
end
-
-
def configure_permitted_parameters
-
devise_parameter_sanitizer.permit(
-
:sign_up, keys: %i[name birthday email country state city institution association_type newsletter active]
-
)
-
devise_parameter_sanitizer.permit(:sign_in, keys: %i[login password])
-
end
-
-
def after_sign_in_path_for(resource)
-
request.env['omniauth.origin'] || stored_location_for(resource) || root_path_for_resource(resource)
-
end
-
-
def root_path_for_resource(resource)
-
resource.is_a?(Admin) ? admin_homes_path : user_logged_path
-
end
-
-
def json_request
-
request.format.json?
-
end
-
-
def authenticate_request
-
@current_user = AuthorizeApiRequest.call(request.headers).result
-
render json: { error: 'Not Authorized' }, status: 401 unless @current_user
-
end
-
-
end
-
class AssociatesController < ApplicationController
-
before_action :authenticate_user!
-
require 'date'
-
-
def new
-
@associate = Associate.new(current_user.attributes.slice('country', 'state', 'city'))
-
@association_types = AssociationType.all
-
end
-
-
def create
-
@associate = Associate.new(associate_params)
-
@associate.user_id = current_user.id
-
@associate.payment_type = 'pending'
-
@associate.accepted_terms_at = DateTime.now
-
@associate.code_of_ethics_terms_at = DateTime.now
-
if (!@associate.association_type.nil? && @associate.association_type.description == 'Profissional e/ou estudante de pós-graduação')
-
@associate.conclusion_date = nil # Campo anulado quando não se é estudante de graduação
-
end
-
if @associate.save
-
@associate.start!
-
redirect_to user_logged_path
-
else
-
@association_types = AssociationType.all
-
render :new
-
end
-
end
-
-
def edit; end
-
-
def update; end
-
-
def destroy; end
-
-
def associate_params
-
params.require(:associate).permit!
-
end
-
end
-
class ContactController < ApplicationController
-
respond_to :html
-
-
def new
-
@contact = Contact.new
-
-
breadcrumb_title = "Fale Conosco"
-
add_breadcrumb breadcrumb_title
-
end
-
-
def create
-
recaptcha_valid = verify_recaptcha(action: 'contact', minimum_score: ENV['RECAPTCHA_MINSCORE'].to_i, action: 'create', secret_key: ENV['RECAPTCHA_SECRETKEY'])
-
@contact = Contact.new(contact_params)
-
if recaptcha_valid
-
if @contact.valid?
-
ContactMailer.mail_message(@contact).deliver_now
-
flash.now[:notice] = "Mensagem enviada. Obrigado por entrar em contato!"
-
redirect_to contact_new_url
-
else
-
flash.now[:error] = "Ops, não foi possível enviar sua mensagem. Veja se os campos estão preenchidos corretamente e tente mais uma vez."
-
-
breadcrumb_title = "Fale Conosco"
-
add_breadcrumb breadcrumb_title
-
-
render :new
-
end
-
else
-
flash.now[:error] = "Ops, não foi possível completar a validação anti-robo. Tente novamente."
-
-
breadcrumb_title = "Fale Conosco"
-
add_breadcrumb breadcrumb_title
-
-
render :new
-
end
-
end
-
-
private
-
def contact_params
-
params.require(:contact).permit(:name, :email, :phone, :message, :subject)
-
end
-
-
end
-
class ContentsController < ApplicationController
-
before_action :set_content, only: %i[show edit destroy update publish unpublish]
-
layout 'admin', only: %i[index new create show edit destroy update publish unpublish]
-
respond_to :html
-
-
def index
-
@contents = klass.fulltext_search(params[:q]).page(params[:page] || 1).per(10)
-
end
-
-
def of_type
-
type = params[:type]
-
type = 'news_index' if type == 'news'
-
redirect_to send("admin_#{type}_path", page: params[:page])
-
end
-
-
def list
-
@contents = Kaminari.paginate_array(klass.published_and_filtered(admin_signed_in?, params[:filter_selected]))
-
@contents = @contents.page(params[:page] || 1).per(10)
-
@filter = klass.filters
-
add_breadcrumb t("activerecord.models.#{params[:type].underscore}.other")
-
end
-
-
def search
-
@contents = Content.published(admin_signed_in?).fulltext_search(params[:q]).page(params[:page] || 1).per(5)
-
end
-
-
def exhibit
-
@content = Content.published(admin_signed_in?).find_by!(slug: params[:slug])
-
breadcrumb_title = t("activerecord.models.#{content_type.underscore}.other")
-
breadcrumb_url = '/' + t("activerecord.models.#{content_type.underscore}.slug")
-
add_breadcrumb breadcrumb_title, breadcrumb_url
-
respond_with(@content)
-
end
-
-
def show
-
@content = Content.find_by!(slug: params[:id])
-
respond_with(@content)
-
end
-
-
def new
-
@content = klass.new
-
@sections = Section.all
-
@tags = klass_info.new
-
build_content_type
-
@croped_image_size = klass.croped_image_size
-
end
-
-
def edit
-
@croped_image_size = klass.croped_image_size
-
@sections = Section.all
-
build_content_type
-
end
-
-
def create
-
@tags = klass_info.new
-
@content = klass.new(content_params)
-
# @content.online_course_info.associate_price_cents = content_params[:online_course_info_attributes][:associate_price_cents].to_f * 100
-
@croped_image_size = klass.croped_image_size
-
if @content.save
-
redirect_to index_path
-
else
-
build_content_type
-
if !@content.errors.details[:slug].blank?
-
@content.errors.messages[:title] = ["Esse titulo já está sendo usado em outra noticia. Não se pode repetir o título pois a URL é gerada dele, e não se pode repetir URL"]
-
end
-
render :new
-
end
-
end
-
-
def update
-
@croped_image_size = klass.croped_image_size
-
if @content.update(content_params)
-
redirect_to index_path
-
else
-
render :edit
-
end
-
end
-
-
def destroy
-
@content.destroy
-
redirect_to index_path
-
end
-
-
def publish
-
@content.update(published: true)
-
redirect_to index_path
-
end
-
-
def unpublish
-
@content.update(published: false)
-
redirect_to index_path
-
end
-
-
private
-
def build_content_type
-
return if @content.send("#{content_type.underscore}_info").present?
-
@content.send("build_#{content_type.underscore}_info")
-
end
-
-
def content_type
-
return @content.type if @content.present?
-
params[:type]&.camelize || 'Content'
-
end
-
-
def klass
-
content_type.constantize
-
end
-
-
def klass_info
-
"#{content_type}Info".constantize
-
end
-
-
def index_path
-
if content_type == 'News'
-
send('admin_news_index_path')
-
else
-
send("admin_#{content_type.underscore.pluralize}_path")
-
end
-
end
-
-
def set_content
-
@content = klass.find_by(slug: params[:id])
-
@tags = klass_info.new
-
end
-
-
def content_params
-
params[:content].permit!
-
end
-
end
-
class CruzaGrafosUsersController < ApplicationController
-
before_action :set_cruza_grafos_user, only: [:show, :edit, :update, :destroy]
-
-
# GET /cruza_grafos_users
-
def index
-
@cruza_grafos_users = CruzaGrafosUser.all
-
end
-
-
# GET /cruza_grafos_users/1
-
def show
-
end
-
-
# GET /cruza_grafos_users/new
-
def new
-
@cruza_grafos_user = CruzaGrafosUser.new
-
end
-
-
# GET /cruza_grafos_users/1/edit
-
def edit
-
end
-
-
# POST /cruza_grafos_users
-
def create
-
@cruza_grafos_user = CruzaGrafosUser.new(cruza_grafos_user_params)
-
@cruza_grafos_user.user = current_user
-
@cruza_grafos_user.start
-
if @cruza_grafos_user.save
-
redirect_to user_logged_path, notice: 'Cruza grafos user was successfully created.'
-
else
-
render :new
-
end
-
end
-
-
# PATCH/PUT /cruza_grafos_users/1
-
def update
-
if @cruza_grafos_user.update(cruza_grafos_user_params)
-
redirect_to @cruza_grafos_user, notice: 'Cruza grafos user was successfully updated.'
-
else
-
render :edit
-
end
-
end
-
-
# DELETE /cruza_grafos_users/1
-
def destroy
-
@cruza_grafos_user.destroy
-
redirect_to cruza_grafos_users_url, notice: 'Cruza grafos user was successfully destroyed.'
-
end
-
-
private
-
# Use callbacks to share common setup or constraints between actions.
-
def set_cruza_grafos_user
-
@cruza_grafos_user = CruzaGrafosUser.find(params[:id])
-
end
-
-
# Only allow a trusted parameter "white list" through.
-
def cruza_grafos_user_params
-
params.require(:cruza_grafos_user).permit!
-
end
-
end
-
class DashboardsController < ApplicationController
-
before_action :authenticate_admin!
-
layout 'admin'
-
-
def home; end
-
end
-
require 'google/apis/youtube_v3'
-
class ExclusiveContentCongressController < ExclusiveContentController
-
respond_to :html
-
-
PLAYLISTS = {
-
2020 => {'name' => 'Congresso 2020', 'description' => 'O 15º Congresso Internacional de Jornalismo Investigativo, o primeiro a ser realizado em formato virtual, aconteceu entre os dias 10 e 13.set.2020. Desinformação, segurança digital, liberdade de expressão, jornalismo ambiental e polarização foram alguns dos temas abordados na edição de 2020.', 'slug' => '15-congresso-da-abraji', 'thumb' => 'congress-2020/15-congresso-da-abraji.png', 'botao' => 'Assistir Congresso', 'list'=> [
-
{'name' => 'VII Seminário de Pesquisa','description' => 'O VII Seminário de Pesquisa em Jornalismo Investigativo integrou a programação do 15º Congresso, realizado anualmente pela Abraji. É um espaço para discutir estudos acadêmicos sobre jornalismo investigativo. No evento, foram apresentadas 15 pesquisas inéditas.', 'playlist_id' => 'PLd76UQ8_K_EWquBPFVvWrVwutC4iiDnSm', 'slug' => 'vii-seminario-de-pesquisa', 'thumb' => 'vii-seminario-de-pesquisa.jpg', 'botao' => 'Assistir playlist'},
-
{'name' => '1º dia do 15º Congresso','description' => 'O 15º Congresso Internacional de Jornalismo Investigativo da Abraji foi realizado virtualmente em 11.set.2020 e 12.set.2020. No primeiro dia, desinformação, segurança digital, liberdade de expressão, terras indígenas, cobertura policial, jurídica e política estiveram em pauta. Entre os convidados, o ministro do STF Alexandre de Moraes, Miguel Nicolelis, Craig Silverman, Patrícia Campos Mello, além de outros grandes nomes.', 'playlist_id' => 'PLd76UQ8_K_EVXveWqO75ca6j-zoyMuEKC', 'slug' => '1-dia-do-15-congresso-da-abraji', 'thumb' => '1-dia-do-15-congresso.jpg', 'botao' => 'Assistir playlist'},
-
{'name' => '2º dia do 15º Congresso','description' => 'No segundo dia, jornalismo ambiental, modelos de negócio, redes sociais, saúde mental, polarização, Lei de Acesso à informação, podcasts e cobertura da pandemia foram alguns dos temas abordados. Entre os convidados, Jonathan Watts, Renata Lo Prete, Katia Brasil, Fernando Rodrigues, Cécile Prieur, Jason Stanley, entre outros nomes de destaque.', 'playlist_id' => 'PLd76UQ8_K_EUDG13hK_2q1mbcKEtRClUg', 'slug' => '2-dia-do-15-congresso-da-abraji', 'thumb' => '2-dia-do-15-congresso.jpg', 'botao' => 'Assistir playlist'},
-
{'name' => '2º Domingo de Dados','description' => 'O 2º Domingo de Dados fez parte do 15º Congresso. Nas oficinas de jornalismo de dados, foram trabalhadas linguagens de programação como R, Python e SQL, além de estatística para jornalistas. Grandes investigações baseadas em dados e visualizações, cobertura das eleições e Open Source Intelligence também estiveram em debate. Entre os instrutores, jornalistas, desenvolvedores especializados e pesquisadores de cada tema.', 'playlist_id' => 'PLd76UQ8_K_EU57xBtPLiEBxdwlD9U9hJl', 'slug' => '2-domingo-de-dados', 'thumb' => '2-domingo-de-dados.jpg', 'botao' => 'Assistir playlist'}
-
]
-
}, 2021 => {'name' => 'Congresso 2021', 'description' => 'Prepare-se para assistir ao maior evento de jornalistas do país que aconteceu entre os dias 23 e 29.ago.2021, de forma virtual. O 16º Congresso Internacional de Jornalismo Investigativo foi gratuito e está disponível exclusivamente para associados e associadas da Abraji.', 'slug' => '16-congresso-da-abraji', 'thumb' => 'congress-2021/16-congresso-da-abraji.png', 'botao' => 'Assistir Congresso', 'list'=>[
-
{'name' => '1º dia do 16º Congresso','description' => 'No primeiro dia do 16º Congresso Internacional de Jornalismo Investigativo, convidados do Brasil e do mundo discutiram temas como liberdade de expressão, jornalismo literário na Amazônia e modelos de negócio. Três oficinas, a cerimônia de homenagem desta edição e a entrevista com Renan Calheiros também marcaram esse 1º dia do evento.', 'playlist_id' => 'PLd76UQ8_K_EVnQU7Wq8ITkIl-RrRMmJIS', 'slug' => '1-dia-do-16-congresso-da-abraji', 'thumb' => '1-dia-do-16-congresso-da-abraji.png', 'botao' => 'Assistir playlist'},
-
{'name' => '2º dia do 16º Congresso','description' => 'No segundo dia do evento, destacaram-se os debates sobre investigações jornalísticas no governo Bolsonaro, documentários do Frontline, cobertura de educação, assédio virtual nos veículos de imprensa, além da discussão sobre jornalistas assassinados no México e no Brasil.', 'playlist_id' => 'PLd76UQ8_K_EXkNpXiwEn3SGdrBMr25eoZ', 'slug' => '2-dia-do-16-congresso-da-abraji', 'thumb' => '2-dia-do-16-congresso-da-abraji.png', 'botao' => 'Assistir playlist'},
-
{'name' => '3º dia do 16º Congresso','description' => 'Investigações transnacionais sobre meio ambiente, cobertura jornalística sobre feminicídio e sobre a pandemia de covid-19 no Amazonas, jornalismo investigativo no streaming internacional e como aumentar a diversidade racial na imprensa estiveram entre os assuntos que marcaram o 3º dia do 16º Congresso da Abraji. Nesse dia, o público também pôde conhecer um pouco mais sobre as ferramentas e os projetos da Abraji e de seus parceiros.', 'playlist_id' => 'PLd76UQ8_K_EUzfAR41JTQ_6yk49f8jfwD', 'slug' => '3-dia-do-16-congresso-da-abraji', 'thumb' => '3-dia-do-16-congresso-da-abraji.png', 'botao' => 'Assistir playlist'},
-
{'name' => '4º dia do 16º Congresso','description' => 'Durante o 4º dia do Congresso da Abraji, palestrantes discutiram investigações de abusos sexuais e de redes de espiritualidade, jornalismo local, assédio judicial, inteligência artificial no jornalismo, entre outros assuntos. Uma mesa com o youtuber e comunicador digital Felipe Neto debateu o que profissionais de imprensa e comunicadores digitais podem aprender uns com os outros.', 'playlist_id' => 'PLd76UQ8_K_EXDwzPvoLkEsyWQUk9_NwEO', 'slug' => '4-dia-do-16-congresso-da-abraji', 'thumb' => '4-dia-do-16-congresso-da-abraji.png', 'botao' => 'Assistir playlist'},
-
{'name' => '5º dia do 16º Congresso','description' => 'Entre as questões abordadas no último dia, estiveram o desafio das eleições de 2022 para os checadores de fatos e o TSE; como construir uma relação de confiança com o público jovem; erros e acertos da cobertura policial a partir dos casos Lázaro e Jacarezinho; e o contexto de trabalho semelhante enfrentado por mulheres jornalistas no Brasil e na Índia. A entrevista com Fernando Gabeira e o documentário de homenagem a organizações que defendem a liberdade de expressão e de imprensa também estiveram entre os conteúdos que fecharam a programação.', 'playlist_id' => 'PLd76UQ8_K_EXjy1Ubycexg_PZelSXPFdb', 'slug' => '5-dia-do-16-congresso-da-abraji', 'thumb' => '5-dia-do-16-congresso-da-abraji.png', 'botao' => 'Assistir playlist'},
-
{'name' => 'VIII Seminário de Pesquisa de Jornalismo Investigativo','description' => ' O VIII Seminário de Pesquisa, um espaço criado para discutir estudos acadêmicos sobre jornalismo investigativo, foi realizado no dia 28.ago.2021, integrado à programação do 16º Congresso Internacional de Jornalismo Investigativo. Além da apresentação de artigos científicos e de trabalhos de conclusão de curso (TCCs), a Abraji promoveu debates com especialistas sobre questões que mobilizaram jornalistas e pesquisadores entre 2020 e 2021.', 'playlist_id' => 'PLd76UQ8_K_EWBY_Uo1KcOJv7BG2r3JNTK', 'slug' => 'viii-seminario-de-pesquisa', 'thumb' => 'viii-seminario-de-pesquisa.png', 'botao' => 'Assistir playlist'},
-
{'name' => '3º Domingo de Dados','description' => ' No dia 29.ago.2021, ocorreu a 3ª edição do Domingo de Dados, voltada para oficinas e debates sobre jornalismo de dados. O evento, que fez parte da programação do 16º Congresso Internacional de Jornalismo Investigativo, incluiu painéis que trabalharam linguagens de programação como R, Python e SQL. Open Source Intelligence e grandes investigações baseadas em dados e visualizações também foram temas abordados no 3º Domingo de Dados.', 'playlist_id' => 'PLd76UQ8_K_EWrsTYJgv_oGmO_IQlg3Tv0', 'slug' => '3-domingo-de-dados', 'thumb' => '3-domingo-de-dados.png', 'botao' => 'Assistir playlist'}
-
]
-
}, 2022 => {'name' => 'Congresso 2022', 'description' => 'Em 2022, pela primeira vez, a Abraji realizou o maior encontro de jornalistas do país de forma mista - on-line e presencial. O 17º Congresso Internacional de Jornalismo Investigativo aconteceu entre os dias 3 e 7.ago.2022. A parte presencial aconteceu em São Paulo, na FAAP (Fundação Armando Alvares Penteado).', 'slug' => '17-congresso-da-abraji', 'thumb' => 'congress-2022/17-congresso-da-abraji.png', 'botao' => 'Assistir Congresso','list'=>[
-
{'name' => '1º dia do 17º Congresso','description' => 'No primeiro dia do evento, convidados do Brasil e do mundo discutiram temas como direitos humanos, jornalismo no streaming, invasão de privacidade, ameaças a mulheres jornalistas, eleições 2022 e o assassinato do jornalista Dom Phillips e do indigenista Bruno Pereira. Oficinas com dicas de investigação, direito autoral no podcast e investigação no Judiciário também marcaram o primeiro dia do 17º Congresso, realizado de forma on-line.', 'playlist_id' => 'PLd76UQ8_K_EWBFIvvpSsuuXI8yFk0t8B4', 'slug' => '1-dia-do-17-congresso-da-abraji', 'thumb' => '1-dia-do-17-congresso-da-abraji.png', 'botao' => 'Assistir playlist', 'link'=>'https://youtube.com/playlist?list=PLd76UQ8_K_EWBFIvvpSsuuXI8yFk0t8B4'},
-
{'name' => '2º dia do 17º Congresso','description' => 'Mulheres jornalistas na guerra, big techs e suas responsabilidades, guerra na Rússia e jornalismo independente foram alguns dos assuntos abordados no segundo dia do evento. Também foram realizadas oficinas sobre desinformação eleitoral, dados eleitorais e monitoramento de prefeituras.', 'playlist_id' => 'PLd76UQ8_K_EWrGyl4F0oGDbZ_IBuMgCD2', 'slug' => '2-dia-do-17-congresso-da-abraji', 'thumb' => '17-congresso-da-abraji.png', 'botao' => 'Assistir playlist', 'link'=>'https://youtube.com/playlist?list=PLd76UQ8_K_EWrGyl4F0oGDbZ_IBuMgCD2'},
-
{'name' => '3º dia do 17º Congresso','description' => 'No primeiro dia da versão presencial, foram discutidas importantes investigações que levaram a grandes escândalos políticos, entre outros assuntos. Confira ainda a cerimônia de homenagem do 17º Congresso.', 'playlist_id' => 'PLd76UQ8_K_EVkvgfJwLbsxpllEW9UT-oH', 'slug' => '4-dia-do-17-congresso-da-abraji', 'thumb' => '3-dia-do-17-congresso-da-abraji.png', 'botao' => 'Assistir playlist', 'link'=>'https://youtube.com/playlist?list=PLd76UQ8_K_EVkvgfJwLbsxpllEW9UT-oH'},
-
{'name' => '4º dia do 17º Congresso','description' => 'Entre os destaques deste dia, estão a palestra sobre a resistência do jornalismo durante governos autoritários e a sessão que tratou dos bastidores do trabalho que investigou a invasão do Capitólio.', 'playlist_id' => 'PLd76UQ8_K_EUNsJk11dnvMaCEJG-8LUK4', 'slug' => '5-dia-do-17-congresso-da-abraji', 'thumb' => '4-dia-do-17-congresso-da-abraji.png', 'botao' => 'Assistir playlist', 'link'=> 'https://www.youtube.com/playlist?list=PLd76UQ8_K_EUNsJk11dnvMaCEJG-8LUK4'},
-
{'name' => 'IX Seminário de Pesquisa de Jornalismo Investigativo','description' => 'O IX Seminário de Pesquisa, um espaço criado para discutir estudos acadêmicos sobre jornalismo investigativo, foi realizado nos dias 3 e 4.ago.2022, integrado à programação on-line do 17º Congresso. Além da discussão sobre os artigos científicos, foram apresentados os trabalhos de conclusão de curso (TCCs).', 'playlist_id' => 'PLd76UQ8_K_EX5xxm4i1UVJCRAYol7dnDo', 'slug' => '17-congresso-da-abraji', 'thumb' => 'ix-seminario-de-pesquisa.png', 'botao' => 'Assistir playlist', 'link'=>'https://youtube.com/playlist?list=PLd76UQ8_K_EX5xxm4i1UVJCRAYol7dnDo'}
-
]
-
}, 1 => {'name' => 'Canal de escuta', 'description' => 'Para atender às normas do código de ética interno, a Abraji, em parceria com o SafeSpace, abriu um canal de escuta pelo qual as pessoas associadas podem enviar relatos de assédio, discriminação, bullying, corrupção, fraude, entre outros tipos de má conduta. Esse canal foi idealizado para promover acolhimento e respeito nas relações estabelecidas pela/na Abraji.', 'slug' => 'others', 'thumb' => 'others/safespace.png', 'botao' => 'Acessar tutorial e canal de escuta', 'fileName'=>'abraji-safe-space.pdf'},
-
2 => {'name' => 'Lista de transmissão (Whatsapp)', 'description' => 'Que tal receber de forma mais rápida as notícias e notas publicadas pela Abraji, além de informações sobre eventos, cursos, iniciativas e oportunidades na área? Participe da lista de transmissão da Abraji no WhatsApp. Após clicar no botão abaixo, que vai te direcionar para o aplicativo de mensagens, você deverá iniciar uma conversa e salvar o contato em sua agenda para entrar na lista e receber as mensagens compartilhadas.', 'slug' => 'others', 'thumb' => 'others/whatsapp.png', 'botao' => 'Entrar na lista de transmissão', 'link'=>'https://wa.me/5511959788904?text=Eu%20quero%20fazer%20parte%20da%20lista%20de%20transmiss%C3%A3o%20de%20associados/as%20da%20Abraji' }
-
}.freeze
-
-
-
def list
-
add_breadcrumb 'Conteúdo Exclusivo'
-
@playlists = PLAYLISTS.sort_by {|k, v| -k }.to_h
-
end
-
-
def playlists
-
@year = params[:year].to_i
-
add_breadcrumb 'Conteúdo Exclusivo', exclusive_content_congress_list_url
-
add_breadcrumb 'Congresso '+@year.to_s
-
-
@playlists = PLAYLISTS[@year]['list']
-
end
-
-
def playlist
-
@year = params[:year].to_i
-
@slug = params[:slug]
-
@playlists = PLAYLISTS[@year]['list']
-
@playlist = @playlists.select{|key, hash| key["slug"] == @slug }
-
-
add_breadcrumb 'Conteúdo Exclusivo', exclusive_content_congress_list_url
-
add_breadcrumb 'Congresso '+@year.to_s, exclusive_content_congress_playlists_url
-
add_breadcrumb @playlist[0]['name']
-
-
youtube = Google::Apis::YoutubeV3::YouTubeService.new
-
youtube.key = ENV['YT_KEY']
-
@video = youtube.list_playlist_items('snippet', playlist_id: @playlist[0]['playlist_id'], max_results: 20)
-
-
@playlistsMenu = congressPlaylistsMenu
-
end
-
-
def download
-
send_file 'app/assets/arquivos/conteudo-exclusivo/'+ params[:filename]
-
end
-
-
private
-
def congressPlaylistsMenu
-
PLAYLISTS[@year]['list'].select{|key, hash| key["slug"] != params[:slug] }
-
end
-
end
-
class ExclusiveContentController < ApplicationController
-
before_action :authenticate_user!
-
before_action :redirect_to_home_logged, :if => :is_not_eligible_to_access?
-
-
private
-
#exceptions to access exclusive content:
-
# Allow access to Domingo de dados page if User institution is "Universidade Positivo" and date now is <= than 30 days from created_at
-
def is_user_institution_from_universidade_positivo?
-
current_user.institution == "Universidade Positivo" && is_user_in_30_days_from_created_at? && (request.fullpath == "/congresso-2020/2-domingo-de-dados" || request.fullpath == "/congresso-2020")
-
end
-
-
#rules to access exclusive content
-
# Disalow access to users that are not associated
-
def is_user_not_associated?
-
current_user.associate.nil? || !current_user.associate.running?
-
end
-
-
def is_user_in_30_days_from_created_at?
-
(Date.today) <= (current_user.created_at + 30.days)
-
end
-
-
#before action: is not elegible to access?
-
def is_not_eligible_to_access?
-
is_user_not_associated? && !is_user_institution_from_universidade_positivo?
-
end
-
-
#if not in rules and exceptions redirect to home logged
-
def redirect_to_home_logged
-
redirect_to user_logged_url(:show => 'exclusive')
-
end
-
end
-
class HelpdesksController < ApplicationController
-
before_action :set_helpdesk, only: %i[show edit destroy publish unpublish]
-
layout 'admin'
-
-
before_action :authenticate_admin!
-
-
def index
-
@helpdesks = Helpdesk.all
-
end
-
-
def show; end
-
-
def new
-
@helpdesk = Helpdesk.new
-
@helpdesk_info = HelpdeskInfo.new
-
end
-
-
def edit; end
-
-
def create
-
@helpdesk = Helpdesk.new(helpdesk_params.except(:helpdesk_infos))
-
@helpdesk.helpdesk_info = HelpdeskInfo.new(note: helpdesk_params[:helpdesk_infos][:note],
-
content_type: @helpdesk.type)
-
if @helpdesk.save
-
@helpdesk.helpdesk_info.content = @helpdesk
-
@helpdesk.helpdesk_info.save
-
redirect_to helpdesk_path(id: @helpdesk.id)
-
else
-
render :new
-
end
-
end
-
-
def update
-
@helpdesk = Helpdesk.find(params[:helpdesk][:id])
-
if @helpdesk.update(helpdesk_params.except(:helpdesk_infos))
-
@helpdesk.helpdesk_info.update_attributes(helpdesk_params[:helpdesk_infos]) if @helpdesk.helpdesk_info.present?
-
render :show
-
else
-
render :edit
-
end
-
end
-
-
def destroy
-
@helpdesk.destroy
-
redirect_to helpdesks_url
-
end
-
-
def publish
-
@helpdesk.update_attributes(published: true)
-
redirect_to helpdesks_path
-
end
-
-
def unpublish
-
@helpdesk.update_attributes(published: false)
-
redirect_to helpdesks_path
-
end
-
-
private
-
def set_helpdesk
-
@helpdesk = Helpdesk.find(params[:id])
-
end
-
-
def helpdesk_params
-
params.require(:helpdesk).permit(
-
[:id, :image, :title, :title_summary, :content, section_ids: [], helpdesk_infos: [:note]]
-
)
-
end
-
end
-
class HomesController < ApplicationController
-
before_action :set_home, only: %i[exhibit show edit update destroy activate deactivate]
-
before_action :authenticate_admin!
-
-
layout 'admin'
-
-
def index
-
@homes = Home.all
-
end
-
-
def exhibit
-
render 'pages/home', layout: 'application'
-
end
-
-
def show; end
-
-
def new
-
@home = Home.new
-
@home.build_home_primary_section
-
4.times do |i|
-
@home.home_primary_section.home_contents.build[i]
-
@home.home_primary_section.home_contents[i].position = i
-
end
-
3.times do |i|
-
@home.home_secondary_sections.build
-
3.times do |j|
-
@home.home_secondary_sections[i].home_contents.build[j]
-
@home.home_secondary_sections[i].home_contents[j].position = j
-
end
-
end
-
end
-
-
def edit; end
-
-
def create
-
@home = Home.new(home_params)
-
4.times do |i|
-
@home.home_primary_section.home_contents[i].position = i
-
end
-
3.times do |i|
-
3.times do |j|
-
@home.home_secondary_sections[i].home_contents[j].position = j
-
end
-
end
-
if @home.save
-
redirect_to admin_homes_path, notice: 'Home was successfully created.'
-
else
-
render :new
-
end
-
end
-
-
def update
-
if @home.update(home_params)
-
redirect_to admin_homes_path, notice: 'Home was successfully updated.'
-
else
-
render :edit
-
end
-
end
-
-
def destroy
-
@home.destroy
-
redirect_to [:admin, @home], notice: 'Home was successfully destroyed.'
-
end
-
-
def activate
-
Home.where(active: true).each { |home| home.update(active: false) }
-
@home.update active: true
-
redirect_to admin_homes_path, notice: 'Home was successfully activated.'
-
end
-
-
def deactivate
-
@home.active = false
-
@home.save
-
redirect_to admin_homes_path, notice: 'Home was successfully deactivated.'
-
end
-
-
private
-
def set_home
-
@home = Home.find_by!(slug: params[:id])
-
# @home2 = Home.joins(:home_sections).joins(:home_contents).where(slug: params[:id])
-
-
# @home.home_primary_section.home_contents = @home.home_primary_section.home_contents.order(:position)
-
# @home.home_secondary_sections.each do |hsc|
-
# hsc.home_contents = hsc.home_contents.order(:position)
-
# end
-
end
-
-
def home_params
-
params.require(:home).permit(
-
[
-
:title, :active, :id, :slug, :top_banner, :top_banner_description, :top_banner_link,
-
home_primary_section_attributes: [
-
:id, home_contents_attributes: %i[id section_id title description url image position]
-
],
-
home_secondary_sections_attributes: [
-
:id, :section_id, home_contents_attributes: %i[id title description url image position]
-
]
-
]
-
)
-
end
-
-
def home_secondary_sections_params
-
home_content_params = []
-
secondary_secion_attributes = home_params[:home_secondary_sections_attributes].to_h.delete('0')
-
hss_keys = secondary_secion_attributes[:home_contents_attributes].keys
-
hss_keys.each_with_index do |_hk, i|
-
home_content_params << secondary_secion_attributes[:home_contents_attributes][hss_keys[i]]
-
end
-
home_content_params
-
end
-
end
-
class InstitucionalPersonsController < ApplicationController
-
respond_to :html
-
before_action :set_institucional_person, only: %i[show edit update destroy publish unpublish]
-
layout 'admin'
-
-
before_action :authenticate_admin!
-
-
def index
-
@institucionalPersons = InstitucionalPerson.order(:order).all
-
@groups = InstitucionalPersonsGroup.order(order: :asc).all
-
end
-
-
def sort
-
params[:institucional].each_with_index do |id, index|
-
InstitucionalPerson.where(id: id.gsub('#','-')).update_all(order: index + 1)
-
end
-
-
head :ok
-
end
-
-
def show; end
-
-
def edit;
-
@institucionalPerson = InstitucionalPerson.published(admin_signed_in?).find_by!(id: params[:id])
-
@institucionalPersonsGroups = InstitucionalPersonsGroup.all()
-
end
-
-
def exhibit
-
@institucionalPerson = InstitucionalPerson.published(admin_signed_in?).find_by!(id: params[:id])
-
-
breadcrumb_title = @institucionalPerson.name
-
breadcrumb_url = '/'
-
add_breadcrumb breadcrumb_title, breadcrumb_url
-
-
render layout: 'application'
-
end
-
-
def new
-
@institucionalPersonPath = admin_institucional_person_index_path
-
@institucionalPersonsGroups = InstitucionalPersonsGroup.all()
-
@institucionalPerson = InstitucionalPerson.new
-
end
-
-
def create
-
@institucionalPersonPath = admin_institucional_person_index_path
-
@institucionalPersonsGroups = InstitucionalPersonsGroup.all()
-
@institucionalPerson = InstitucionalPerson.new(institucional_persons_params)
-
if @institucionalPerson.save
-
respond_with(@institucionalPerson, :location => admin_institucional_person_index_path)
-
else
-
render :new
-
end
-
end
-
-
def update
-
@institucionalPersonPath = admin_institucional_person_path
-
@institucionalPerson = InstitucionalPerson.find_by id: params[:institucional_person][:id]
-
if @institucionalPerson.update(institucional_persons_params)
-
# render :show
-
redirect_to admin_institucional_person_index_path
-
else
-
render :new
-
end
-
end
-
-
def destroy
-
@institucionalPerson.destroy
-
redirect_to admin_institucional_person_index_path
-
end
-
-
def publish
-
@institucionalPerson.update(published: true)
-
redirect_to admin_institucional_person_path
-
end
-
-
def unpublish
-
@institucionalPerson.update(published: false)
-
redirect_to admin_institucional_person_path
-
end
-
-
private
-
def set_institucional_person
-
@institucionalPerson = InstitucionalPerson.find_by(id: params[:id])
-
end
-
-
def institucional_persons_params
-
params.require(:institucional_person).permit([:name], [:description], [:photo], [:role], [:institucional_persons_group_id], [:id])
-
end
-
end
-
require 'google/apis/youtube_v3'
-
class PagesController < ApplicationController
-
respond_to :html
-
-
def home
-
@home = Home.find_by(active: true)
-
end
-
-
def institutional
-
@groups = InstitucionalPersonsGroup.order(order: :asc).all
-
add_breadcrumb 'Institucional'
-
end
-
-
def institutional_transparence
-
@recent_documentation = RecentDocumentation.all
-
@activity_reports = ActivityReport.all
-
@audit_reports = AuditReport.all
-
add_breadcrumb 'Institucional', '/institucional'
-
add_breadcrumb 'Transparência'
-
end
-
-
def institutional_patrimonial_fund
-
@deponents = Deponent.all
-
@regulations = Regulation.all
-
groupId = InstitucionalPersonsGroup.find_by_name('conselho curador').id
-
@curators = InstitucionalPerson.where(institucional_persons_group_id: groupId, published: true).order(order: :asc)
-
add_breadcrumb 'Institucional', '/institucional'
-
add_breadcrumb 'Fundo Patrimonial'
-
end
-
-
def institutional_documentaries
-
add_breadcrumb 'Institucional', '/institucional'
-
add_breadcrumb 'Documentários dos Homenageados'
-
youtube = Google::Apis::YoutubeV3::YouTubeService.new
-
youtube.key = ENV['YT_KEY']
-
@video = youtube.list_playlist_items('snippet', playlist_id: 'PLd76UQ8_K_EXbKb3HDah2ans4rWE8EG9J', max_results: 20)
-
end
-
-
def institutional_privacy_policy
-
add_breadcrumb 'Institucional', '/institucional'
-
add_breadcrumb 'Política de Privacidade'
-
end
-
-
def institutional_codigo_de_conduta_etica
-
add_breadcrumb 'Institucional', '/institucional'
-
add_breadcrumb 'Código de conduta ética'
-
@page_content = StaticContent.find_by(slug:request.fullpath.gsub("/institucional/",""))
-
end
-
-
def cruza_grafos_terms_of_use
-
add_breadcrumb 'CruzaGrafos', '/cruzagrafos'
-
add_breadcrumb 'Termos de Uso'
-
end
-
-
def cruza_grafos_privacy_policy
-
add_breadcrumb 'CruzaGrafos', '/cruzagrafos'
-
add_breadcrumb 'Política de Privacidade'
-
end
-
-
def protecao_legal_e_litigancia
-
add_breadcrumb 'Proteção Legal e Litigância'
-
@page_content = StaticContent.find_by(slug:request.fullpath.tr('/', '')).content
-
end
-
-
end
-
class PaymentController < ApplicationController
-
before_action :authenticate_user!, only: [:pay_association_logged_user]
-
skip_before_action :verify_authenticity_token, only: :notification
-
before_action :set_headers
-
-
def new
-
@user = params[:userId]
-
@payment = Payment.new
-
end
-
-
def create
-
@payment = Payment.new(payment_params)
-
-
if @payment.save
-
redirect_to admin_user_path(@payment), notice: 'Payment was successfully created.'
-
else
-
render :new
-
end
-
end
-
-
def manual_pay
-
@payment = Payment.find(params['id'])
-
if (@payment.payable.valid?)
-
@payment.manual_pay!
-
end
-
redirect_to admin_user_path(@payment.user), flash: { error: @payment.payable.errors.messages }
-
end
-
-
def change_payment_value
-
payment = Payment.find(params['id'])
-
payment.price_cents = payment_value_params.to_f*100
-
payment.save
-
redirect_to admin_user_path(payment.user)
-
end
-
-
def covid_voucher
-
payment = Payment.find_by(user_id: current_user.id, status: "nil", payable_type: "Associate")
-
payment.name = 'association covid voucher'
-
payment.price_cents = 100
-
payment.save
-
redirect_to user_logged_path
-
-
end
-
-
def pay_association_logged_user
-
# -- Valida o Código de Éticas
-
form_code_of_ethics_terms_value = 0
-
if !params()['associate'].nil?
-
form_code_of_ethics_terms_value = params()['associate']['code_of_ethics_terms']
-
end
-
-
need_ethics = AssociatesFacade.accept_code_ethics(current_user.id, form_code_of_ethics_terms_value)
-
-
# --
-
if(need_ethics==false)
-
session()[:need_ethics] = "0"
-
status = pay_association(current_user.id)
-
if (!status)
-
redirect_to user_logged_path
-
end
-
else
-
session()[:need_ethics] = "1"
-
redirect_to user_logged_path
-
end
-
end
-
-
def pay_association_by_link
-
user_id = params[:user_id]
-
-
if(AssociatesFacade.has_accepted_ethics(user_id))
-
if !user_id.empty?
-
status = pay_association(user_id)
-
if (!status)
-
redirect_to user_logged_path
-
end
-
end
-
else
-
redirect_to new_user_session_path + "?need_ethics=1"
-
end
-
end
-
-
def pay_cruza_grafo_link
-
current_user = User.find_by_id(params[:user_id])
-
status = pay_cruza_grafo()
-
if (!status)
-
redirect_to user_logged_path
-
end
-
end
-
-
def pay_cruza_grafo
-
if (params[:type_id])
-
cg_type = CruzaGrafosType.find(params[:type_id])
-
else
-
cg_type = CruzaGrafosType.find(type_params[:type_id])
-
end
-
cruza_grafos_user = current_user.cruza_grafos_user
-
cruza_grafos_user.cruza_grafos_type = cg_type
-
cruza_grafos_user.save
-
payment = Payment.find_by(user_id: current_user.id, status: "nil", payable_type: "CruzaGrafosUser")
-
-
if(!payment)
-
cruza_grafos_user.create_cruza_grafo_payment cg_type
-
payment = Payment.find_by(user_id: current_user.id, status: "nil", payable_type: "CruzaGrafosUser")
-
else
-
payment.price_cents = cg_type.price_cents
-
payment.price_currency = cg_type.price_currency
-
payment.name = 'Cruza Grafos - ' + cg_type.description
-
payment.save
-
end
-
-
pag_seguro_payment = PagSeguro::PaymentRequest.new
-
-
pag_seguro_payment.reference = payment.id
-
pag_seguro_payment.notification_url = payment_notification_url
-
# EMAIL TESTE DE RETORNO
-
# pag_seguro_payment.notification_url = 'http://chuffi.synology.me:3000/payment/notification'
-
pag_seguro_payment.redirect_url = user_return_url
-
-
pag_seguro_payment.items << {
-
id: cruza_grafos_user.id,
-
description: 'Cruza Grafos - ' + cg_type.description,
-
amount: payment.price_cents.to_f/100.0,
-
weight: 0
-
}
-
response = pag_seguro_payment.register
-
-
if response.errors.any?
-
raise response.errors.join("\n")
-
else
-
redirect_to response.url
-
end
-
end
-
-
def notification
-
puts("PAGSEGURO-TRANSACTION")
-
transactionXML = PagSeguro::Transaction.find_by_notification_code(params[:notificationCode])
-
if transactionXML.errors.empty?
-
payment = Payment.find(transactionXML.reference)
-
transaction = create_transaction(payment, transactionXML)
-
if payment.payable_type == "Associate"
-
handle_associate_payment_notification(payment, transaction)
-
elsif payment.payable_type == "CruzaGrafosUser"
-
handle_grafos_payment_notification(payment, transaction)
-
end
-
end
-
render body: nil, status: 200
-
# render nothing: true, status: 200
-
end
-
-
def handle_associate_payment_notification(payment, transaction)
-
case transaction.statusId
-
when 1 #Aguardando pagamento
-
if payment.may_start?
-
payment.start!
-
payment.payable.pay!
-
end
-
when 2 #Em análise
-
if payment.may_analyze?
-
payment.analyze!
-
end
-
when 3 #Paga
-
if payment.may_pay?
-
payment.pay_date = Time.now
-
payment.pay!
-
if payment.payable.may_pay?
-
payment.payable.pay!
-
end
-
payment.payable.paid!
-
end
-
when 4 #Disponível
-
if payment.may_finish?
-
payment.finish!
-
if payment.payable.may_pay?
-
payment.payable.pay!
-
end
-
if payment.payable.may_paid?
-
payment.payable.paid!
-
end
-
end
-
when 5 #Em disputa
-
if payment.may_dispute?
-
payment.dispute!
-
end
-
when 6 #Devolvida
-
if payment.may_return?
-
payment.return!
-
payment.payable.not_paid!
-
end
-
when 7 #Cancelada
-
if payment.may_cancel?
-
payment.cancel!
-
payment.payable.not_paid!
-
end
-
end
-
# console.debug(transaction.inspect)
-
# binding.pry()
-
end
-
-
def handle_grafos_payment_notification(payment, transaction)
-
case transaction.statusId
-
when 1 #Aguardando pagamento
-
if payment.may_start?
-
payment.start!
-
payment.payable.user_paid!
-
end
-
when 2 #Em análise
-
if payment.may_analyze?
-
payment.analyze!
-
end
-
when 3 #Paga
-
if payment.may_pay?
-
payment.pay_date = Time.now
-
if !payment.pay!
-
puts payment.errors.inspect
-
end
-
if payment.payable.may_user_paid?
-
payment.payable.user_paid!
-
end
-
payment.payable.payment_confirm!
-
end
-
when 4 #Disponível
-
if payment.may_finish?
-
payment.finish!
-
if payment.payable.may_user_paid?
-
payment.payable.user_paid!
-
end
-
if payment.payable.may_ payment_confirm?
-
payment.payable.payment_confirm!
-
end
-
end
-
when 5 #Em disputa
-
if payment.may_dispute?
-
payment.dispute!
-
end
-
when 6 #Devolvida
-
if payment.may_return?
-
payment.return!
-
payment.payable.not_paid!
-
end
-
when 7 #Cancelada
-
if payment.may_cancel?
-
payment.cancel!
-
payment.payable.not_paid!
-
end
-
end
-
end
-
-
def create_transaction(payment, transactionXML)
-
transaction = Transaction.new
-
transaction.payment = payment
-
transaction.code = transactionXML.code
-
transaction.paymentLink = transactionXML.payment_link
-
transaction.typeId = transactionXML.type_id
-
transaction.statusId = transactionXML.status.id
-
transaction.paymentMethodTypeId = transactionXML.payment_method.type_id
-
transaction.paymentMethodCode = transactionXML.payment_method.code
-
transaction.grossamount = transactionXML.gross_amount
-
transaction.discountAmount = transactionXML.discount_amount
-
transaction.netAmount = transactionXML.net_amount
-
transaction.extraAmount = transactionXML.extra_amount
-
transaction.installments = transactionXML.installments
-
transaction.escrowEndDate = transactionXML.escrow_end_date
-
transaction.creditor_fees = transactionXML.creditor_fees.to_json
-
transaction.items = transactionXML.items.to_json
-
transaction.sender = transactionXML.sender.to_json
-
transaction.shipping = transactionXML.shipping.to_json
-
# raise transaction.errors.inspect unless transaction.valid?
-
if !transaction.save
-
puts transaction.errors.inspect
-
end
-
return transaction
-
end
-
-
def set_headers
-
headers['Access-Control-Allow-Origin'] = '*'
-
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
-
headers['Access-Control-Request-Method'] = '*'
-
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
-
end
-
-
def receipt
-
@payment = Payment.find(params[:id])
-
@transaction= Transaction.find_by(payment_id: params[:id])
-
x = @payment.user_id
-
@user = User.find_by(id: x)
-
@associate = Associate.find_by(user_id: x)
-
y = @associate.association_type_id
-
@association_types = AssociationType.find(y)
-
render :receipt, layout: false
-
-
end
-
-
private
-
-
def payment_params
-
params.require(:payment).permit!
-
end
-
-
def type_params
-
params.require(:type).permit!
-
end
-
-
def payment_value_params
-
params.require(:value)
-
end
-
-
def pay_association(user_id)
-
associate = Associate.find_by(user_id: user_id)
-
payment = Payment.find_by(user_id: user_id, status: "nil", payable_type: "Associate")
-
-
if (associate.nil?)
-
return false
-
end
-
-
if(!payment)
-
associate.create_association_payment
-
payment = Payment.find_by(user_id: user_id, status: "nil", payable_type: "Associate")
-
end
-
-
pag_seguro_payment = PagSeguro::PaymentRequest.new
-
-
pag_seguro_payment.reference = payment.id
-
pag_seguro_payment.notification_url = payment_notification_url
-
# pag_seguro_payment.notification_url = 'http://chuffi.synology.me:3000/payment/notification'
-
pag_seguro_payment.redirect_url = user_return_url
-
-
pag_seguro_payment.items << {
-
id: associate.association_type.id,
-
description: payment.payable_type,
-
amount: payment.price_cents.to_f/100.0,
-
weight: 0
-
}
-
response = pag_seguro_payment.register
-
-
if response.errors.any?
-
raise response.errors.join("\n")
-
else
-
redirect_to response.url
-
end
-
end
-
-
end
-
class ProjectsController < ApplicationController
-
before_action :set_project, only: %i[show edit destroy publish unpublish]
-
layout 'admin'
-
-
before_action :authenticate_admin!
-
-
def index
-
@projects = Project.all
-
end
-
-
def show; end
-
-
def new
-
@project = Project.new
-
@project_info = ProjectInfo.new
-
end
-
-
def edit; end
-
-
def create
-
@project = Project.new(project_params.except(:project_infos))
-
@project.section_ids = params[:project]['section_ids']
-
@project.project_info = ProjectInfo.new(link: project_params[:project_infos][:link],
-
content_type: @project.type)
-
if @project.save
-
@project.project_info.content = @project
-
@project.project_info.save
-
redirect_to project_path(id: @project.id)
-
else
-
render :new
-
end
-
end
-
-
def update
-
@project = Project.find(params[:project][:id])
-
if @project.update(project_params.except(:project_infos))
-
@project.project_info.update_attributes(project_params[:project_infos]) if @project.project_info.present?
-
render :show
-
else
-
render :edit
-
end
-
end
-
-
def destroy
-
@project.destroy
-
redirect_to projects_url
-
end
-
-
def publish
-
@project.update_attributes(published: true)
-
redirect_to projects_path
-
end
-
-
def unpublish
-
@project.update_attributes(published: false)
-
redirect_to projects_path
-
end
-
-
private
-
def set_project
-
@project = Project.find(params[:id])
-
end
-
-
def project_params
-
params.require(:project).permit([:image, :title, :title_summary, :content, section_ids: [], project_infos: [:link]])
-
end
-
end
-
class SectionsController < ApplicationController
-
respond_to :html
-
before_action :set_section, only: %i[show edit update destroy publish unpublish]
-
layout 'admin'
-
-
#before_action :authenticate_admin!
-
-
def index
-
@sections = Section.all
-
end
-
-
def show; end
-
-
def edit; end
-
-
def exhibit
-
@section = Section.published(admin_signed_in?).find_by!(slug: params[:slug])
-
@news = News.section_contents(@section)
-
@publications = Publication.section_contents(@section)
-
@congresses = Congress.section_contents(@section)
-
@helpdesks = Helpdesk.section_contents(@section)
-
@projects = Project.section_contents(@section)
-
@classroomcourses = ClassroomCourse.section_contents(@section)
-
@onlinecourses = OnlineCourse.section_contents(@section)
-
-
breadcrumb_title = @section.name
-
breadcrumb_url = '/' + @section.slug
-
add_breadcrumb breadcrumb_title, breadcrumb_url
-
-
render layout: 'application'
-
end
-
-
def new
-
@section = Section.new
-
end
-
-
def create
-
@section = Section.new(section_params)
-
if @section.save
-
respond_with(@section)
-
else
-
render :new
-
end
-
end
-
-
def update
-
@section = Section.find_by id: params[:section][:id]
-
if @section.update(section_params)
-
render :show
-
else
-
render :new
-
end
-
end
-
-
def destroy
-
@section.destroy
-
end
-
-
def publish
-
@section.update(published: true)
-
redirect_to admin_sections_path
-
end
-
-
def unpublish
-
@section.update(published: false)
-
redirect_to admin_sections_path
-
end
-
-
private
-
def set_section
-
@section = Section.find_by(slug: params[:id])
-
end
-
-
def section_params
-
params.require(:section).permit([:name], [:description], [:banner], [:css_class], [:id])
-
end
-
end
-
class StaticContentsController < ApplicationController
-
respond_to :html
-
before_action :set_static_content, only: [:show, :edit, :update, :destroy]
-
layout 'admin'
-
-
# GET /static_contents
-
def index
-
@static_contents = StaticContent.all
-
end
-
-
# GET /static_contents/1
-
def show
-
end
-
-
# GET /static_contents/new
-
def new
-
@static_content = StaticContent.new
-
end
-
-
# GET /static_contents/1/edit
-
def edit
-
end
-
-
# POST /static_contents
-
def create
-
@static_content = StaticContent.new(static_content_params)
-
-
if @static_content.save
-
render :show, notice: 'Static content was successfully created.'
-
else
-
render :new
-
end
-
end
-
-
# PATCH/PUT /static_contents/1
-
def update
-
if @static_content.update(static_content_params)
-
render :show, notice: 'Static content was successfully updated.'
-
else
-
render :edit
-
end
-
end
-
-
# DELETE /static_contents/1
-
def destroy
-
@static_content.destroy
-
redirect_to static_contents_url, notice: 'Static content was successfully destroyed.'
-
end
-
-
private
-
# Use callbacks to share common setup or constraints between actions.
-
def set_static_content
-
@static_content = StaticContent.find_by(slug: params[:id])
-
end
-
-
# Only allow a trusted parameter "white list" through.
-
def static_content_params
-
params.require(:static_content).permit(:title, :content)
-
end
-
end
-
class TransitionController < ApplicationController
-
-
def email_validation
-
@errors = false
-
if(params[:email])
-
if(!params[:email].blank?)
-
user = User.find_by_email(params[:email])
-
if(user && user.updated_at < Time.new(2020, 5, 13))
-
redirect_to controller: 'transition', action: 'update_info', id: user.id
-
else
-
@errors = true
-
render :email_validation
-
end
-
else
-
@errors = true
-
render :email_validation
-
end
-
end
-
end
-
-
def update_info
-
@association_types = AssociationType.all
-
if(!params[:id].blank?)
-
@user_associate_form = UserAssociateTransitionForm.new_with_user(User.find(params[:id]))
-
clean_empty_old_fields
-
else
-
redirect_to root_path
-
end
-
end
-
-
def save_info
-
@association_types = AssociationType.all
-
@user_associate_form = UserAssociateTransitionForm.new(user_associate_form_whitelist)
-
@user_associate_form.user = User.find(params[:id])
-
if @user_associate_form.valid?
-
messages = @user_associate_form.save
-
if messages == true
-
redirect_to root_path
-
else
-
messages.each do |error|
-
@user_associate_form.errors.add(error[0], error[1][0])
-
end
-
render :update_info
-
end
-
else
-
@user_associate_form.errors.each do |attribute, message|
-
end
-
render :update_info
-
end
-
end
-
-
-
-
private
-
def user_associate_form_whitelist
-
flatten_date_array params[:user_associate_transition_form], :birthday
-
params.require(:user_associate_transition_form).permit!
-
end
-
-
def flatten_date_array parameters, *attributes
-
attributes.each do |attribute|
-
parameters[attribute] = Date.new *(1..3).map { |e| parameters.delete("#{attribute}(#{e}i)").to_i}
-
end
-
end
-
-
def email_form_whitelist
-
params.require(:email)
-
end
-
-
def clean_empty_old_fields
-
if(@user_associate_form.phone == '00000000000')
-
@user_associate_form.phone = ''
-
end
-
if(@user_associate_form.country == '-')
-
@user_associate_form.country = ''
-
end
-
if(@user_associate_form.state == '-')
-
@user_associate_form.state = ''
-
end
-
if(@user_associate_form.city == '-')
-
@user_associate_form.city = ''
-
end
-
if(@user_associate_form.zipcode == '-')
-
@user_associate_form.zipcode = ''
-
end
-
if(@user_associate_form.address_street == '-')
-
@user_associate_form.address_street = ''
-
end
-
if(@user_associate_form.neighborhood == '-')
-
@user_associate_form.neighborhood = ''
-
end
-
if(@user_associate_form.address_number == '-')
-
@user_associate_form.address_number = ''
-
end
-
if(@user_associate_form.activity_description == '-')
-
@user_associate_form.activity_description = ''
-
end
-
end
-
end
-
class UserAssociateAdminController < ApplicationController
-
before_action :authenticate_admin!
-
layout 'admin'
-
-
def edit
-
@association_types = AssociationType.all
-
if(params[:id])
-
@user_associate_form = UserAssociateAdminEditForm.new_with_user(User.find(params[:id]))
-
else
-
@user_associate_form = UserAssociateAdminEditForm.new_with_user(current_user)
-
end
-
end
-
-
def update
-
@association_types = AssociationType.all
-
@user_associate_form = UserAssociateAdminEditForm.new(user_associate_form_whitelist)
-
@user_associate_form.user = User.find(params[:id])
-
@user_associate_form.admin = current_admin
-
-
if @user_associate_form.valid?
-
if @user_associate_form.save
-
redirect_to admin_users_path
-
else
-
@user_associate_form.errors.each do |attribute, message|
-
end
-
render :edit
-
end
-
else
-
@user_associate_form.errors.each do |attribute, message|
-
end
-
render :edit
-
end
-
end
-
-
private
-
def user_associate_form_whitelist
-
if(params[:user_associate_admin_edit_form]["valid_until(3i)"])
-
flatten_date_array params[:user_associate_admin_edit_form], :birthday, :valid_until, :approval_payment_date, :conclusion_date
-
else
-
flatten_date_array params[:user_associate_admin_edit_form], :birthday
-
end
-
-
flatten_datetime_array params[:user_associate_admin_edit_form], :code_of_ethics_terms_at, :accepted_terms_at
-
params.require(:user_associate_admin_edit_form).permit!
-
end
-
-
def flatten_datetime_array parameters, *attributes
-
attributes.each do |attribute|
-
parameters[attribute] = DateTime.new *(1..5).map { |e| parameters.delete("#{attribute}(#{e}i)").to_i}
-
end
-
end
-
-
def flatten_date_array parameters, *attributes
-
attributes.each do |attribute|
-
parameters[attribute] = Date.new *(1..3).map { |e| parameters.delete("#{attribute}(#{e}i)").to_i}
-
end
-
end
-
-
end
-
class UserAssociateController < ApplicationController
-
before_action :authenticate_user!
-
-
-
def home_logged
-
@user = current_user
-
@associate = Associate.where(user: current_user).first
-
@types = CruzaGrafosType.all
-
@need_ethics = session()[:need_ethics]
-
-
if(!@associate.nil? && @associate.code_of_ethics_terms)
-
@need_ethics = "0"
-
end
-
end
-
-
def payment
-
@associate = Associate.where(user_id: current_user.name).first
-
@payments = Kaminari.paginate_array(Payment.filtered(current_user, params[:filter_selected]))
-
@payments = @payments.page(params[:page] || 1).per(10)
-
@filter = Payment.filters.map{ |name| [ t("activerecord.models.payment.filter.#{name}"), name] }
-
end
-
-
def return
-
@associate = Associate.where(user_id: current_user.name).first
-
end
-
-
def get_association_payment
-
if Associate.where(user_id: current_user.name).first.isAssociationValid
-
flash[:notice] = "Sua associação ainda é valida"
-
render :action => :home_logged
-
else
-
redirect_to :payment_create_path
-
end
-
end
-
-
def edit
-
@association_types = AssociationType.all
-
if(!params[:id].blank?)
-
@user_associate_form = UserAssociateEditForm.new_with_user(User.find(params[:id]))
-
else
-
@user_associate_form = UserAssociateEditForm.new_with_user(current_user)
-
end
-
# @cpf_inalterado = @user_associate_form.cpf
-
end
-
-
def update
-
@association_types = AssociationType.all
-
@user_associate_form = UserAssociateEditForm.new(user_associate_form_whitelist)
-
@user_associate_form.user = User.find(params[:id])
-
if !@user_associate_form.user.associate.nil? && @user_associate_form.details_file.nil?
-
@user_associate_form.details_file = @user_associate_form.user.associate.details_file
-
end
-
if !@user_associate_form.user.associate.nil? && @user_associate_form.association_type.nil?
-
@user_associate_form.association_type = AssociationType.find(params[:user_associate_edit_form][:association_type_id])
-
end
-
if @user_associate_form.valid?
-
if @user_associate_form.save
-
redirect_to user_logged_path
-
else
-
@user_associate_form.errors.add(:cpf, 'CFP Já cadastrados')
-
render :edit
-
end
-
else
-
@user_associate_form.errors.each do |attribute, message|
-
end
-
render :edit
-
end
-
end
-
-
private
-
def user_associate_form_whitelist
-
if params[:user_associate_edit_form]["conclusion_date(2i)"].blank?
-
flatten_date_array params[:user_associate_edit_form], :birthday
-
else
-
flatten_date_array params[:user_associate_edit_form], :birthday, :conclusion_date
-
end
-
params.require(:user_associate_edit_form).permit!
-
end
-
-
def flatten_date_array parameters, *attributes
-
attributes.each do |attribute|
-
parameters[attribute] = Date.new *(1..3).map { |e| parameters.delete("#{attribute}(#{e}i)").to_i}
-
end
-
end
-
-
end
-
class Users::ConfirmationsController < Devise::ConfirmationsController
-
# GET /resource/confirmation/new
-
# def new
-
# super
-
# end
-
-
# POST /resource/confirmation
-
# def create
-
# super
-
# end
-
-
# GET /resource/confirmation?confirmation_token=abcdef
-
# def show
-
# super
-
# end
-
-
# protected
-
-
# The path used after resending confirmation instructions.
-
# def after_resending_confirmation_instructions_path_for(resource_name)
-
# super(resource_name)
-
# end
-
-
# The path used after confirmation.
-
# def after_confirmation_path_for(resource_name, resource)
-
# super(resource_name, resource)
-
# end
-
end
-
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
-
# You should configure your model like this:
-
# devise :omniauthable, omniauth_providers: [:twitter]
-
-
# You should also create an action method in this controller like this:
-
# def twitter
-
# end
-
-
# More info at:
-
# https://github.com/plataformatec/devise#omniauth
-
-
# GET|POST /resource/auth/twitter
-
# def passthru
-
# super
-
# end
-
-
# GET|POST /users/auth/twitter/callback
-
# def failure
-
# super
-
# end
-
-
# protected
-
-
# The path used when OmniAuth fails
-
# def after_omniauth_failure_path_for(scope)
-
# super(scope)
-
# end
-
end
-
class Users::PasswordsController < Devise::PasswordsController
-
# GET /resource/password/new
-
# def new
-
# super
-
# end
-
-
# POST /resource/password
-
def create
-
recaptcha_valid = verify_recaptcha(action: 'changePassword', minimum_score: ENV['RECAPTCHA_MINSCORE'].to_i, action: 'create', secret_key: ENV['RECAPTCHA_SECRETKEY'])
-
if recaptcha_valid
-
super
-
else
-
flash.now[:error] = "Ops, não foi possível completar a validação anti-robo."
-
respond_with resource, location: new_user_password_path(resource_name)
-
end
-
end
-
-
# GET /resource/password/edit?reset_password_token=abcdef
-
# def edit
-
# super
-
# end
-
-
# PUT /resource/password
-
# def update
-
# super
-
# end
-
-
# protected
-
# def after_resetting_password_path_for(resource)
-
# super(resource)
-
# end
-
-
# The path used after sending reset password instructions
-
protected
-
def after_sending_reset_password_instructions_path_for(resource_name)
-
"#{new_user_password_url}?modal=show"
-
end
-
end
-
class Users::RegistrationsController < Devise::RegistrationsController
-
before_action :configure_sign_up_params, only: [:create]
-
before_action :configure_account_update_params, only: [:update]
-
-
# GET /resource/sign_up
-
def new
-
add_breadcrumb 'registrar-se'
-
@states = State.all
-
@statesArray = []
-
@states.each do |n|
-
@statesArray << n.sigla
-
end
-
super
-
end
-
-
# POST /resource
-
def create
-
@user = User.new(params['user'].permit!)
-
recaptcha_valid = verify_recaptcha(model: @user, action: 'registration', minimum_score: ENV['RECAPTCHA_MINSCORE'].to_i, action: 'create',secret_key: ENV['RECAPTCHA_SECRETKEY'])
-
if recaptcha_valid
-
super
-
else
-
flash.now[:error] = "Ops, não foi possível completar a validação anti-robo."
-
respond_with resource, location: new_registration_path(resource_name)
-
end
-
end
-
-
# GET /resource/edit
-
def edit
-
@association_types = AssociationType.all
-
super
-
end
-
-
# PUT /resource
-
def update
-
super
-
end
-
-
# DELETE /resource
-
def destroy
-
super
-
end
-
-
# GET /resource/cancel
-
# Forces the session data which is usually expired after sign
-
# in to be expired now. This is useful if the user wants to
-
# cancel oauth signing in/up in the middle of the process,
-
# removing all OAuth session data.
-
def cancel
-
super
-
end
-
-
protected
-
-
# If you have extra params to permit, append them to the sanitizer.
-
def configure_sign_up_params
-
devise_parameter_sanitizer.permit(:sign_up, keys: %i[attribute name birthday email password password_confirmation country state city institution association_type newsletter])
-
end
-
-
# If you have extra params to permit, append them to the sanitizer.
-
def configure_account_update_params
-
devise_parameter_sanitizer.permit(:account_update, keys: %i[attribute name birthday email password password_confirmation country state city institution association_type newsletter])
-
end
-
-
# The path used after sign up.
-
def after_sign_up_path_for(resource)
-
if params[:f] == 'associate'
-
new_associate_path
-
else
-
user_logged_path
-
end
-
end
-
-
# The path used after sign up for inactive accounts.
-
def after_inactive_sign_up_path_for(resource)
-
super(resource)
-
end
-
end
-
class Users::SessionsController < Devise::SessionsController
-
# before_action :configure_sign_in_params, only: [:create]
-
-
# GET /resource/sign_in
-
def new
-
@need_ethics = params()['need_ethics']
-
if(@need_ethics == "1")
-
flash.now[:error] = t("devise.sessions.pay_need_ethics")
-
end
-
super
-
end
-
-
# POST /resource/sign_in
-
def create
-
recaptcha_valid = verify_recaptcha(action: 'login', minimum_score: ENV['RECAPTCHA_MINSCORE'].to_i, action: 'create', secret_key: ENV['RECAPTCHA_SECRETKEY'])
-
if recaptcha_valid
-
super
-
else
-
flash.now[:error] = "Ops, não foi possível completar a validação anti-robo."
-
respond_with resource, location: new_user_session_path
-
end
-
end
-
-
# def create
-
# if validate_antirobot(params[:token], params[:tUsuario])
-
# super
-
# else
-
# flash.now[:error] = "Ops, não foi possível completar a validação anti-robo."
-
# respond_with resource, location: new_user_session_path
-
# end
-
# end
-
-
# DELETE /resource/sign_out
-
def destroy
-
super
-
end
-
-
protected
-
-
def after_sign_in_path_for(resource)
-
-
if params[:f] == 'associate'
-
new_associate_path
-
else
-
user_logged_path
-
end
-
if resource.is_a?(User) && !resource.active?
-
sign_out resource
-
flash.now[:error] = 'Essa conta está desativada'
-
root_path
-
new_user_session_path
-
else
-
super
-
end
-
end
-
# If you have extra params to permit, append them to the sanitizer.
-
# def configure_sign_in_params
-
# devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
-
# end
-
end
-
class Users::UnlocksController < Devise::UnlocksController
-
# GET /resource/unlock/new
-
# def new
-
# super
-
# end
-
-
# POST /resource/unlock
-
# def create
-
# super
-
# end
-
-
# GET /resource/unlock?unlock_token=abcdef
-
# def show
-
# super
-
# end
-
-
# protected
-
-
# The path used after sending unlock password instructions
-
# def after_sending_unlock_instructions_path_for(resource)
-
# super(resource)
-
# end
-
-
# The path used after unlocking the resource
-
# def after_unlock_path_for(resource)
-
# super(resource)
-
# end
-
end
-
class UsersController < ApplicationController
-
skip_before_action :verify_authenticity_token, :only => [:multiple_update]
-
before_action :set_user, only: %i[show edit update destroy]
-
before_action :authenticate_admin!
-
layout 'admin'
-
-
TRANSLATE_FILTER_LABEL = {
-
'name_likeness' => 'Nome',
-
'email_likeness' => 'Email',
-
'cpf_value' => 'CPF',
-
'state_likeness' => 'Estado',
-
'city_likeness' => 'Cidade',
-
'association_state_value' => 'Estado da associacao',
-
'association_type_id_value' => 'Perfil de Pagamento',
-
'birthday_start' => 'Aniversario de',
-
'birthday_end' => 'Aniversario para',
-
'created_at_start' => 'Data de Inscricao de',
-
'created_at_end' => 'Data de Inscricao para',
-
'valid_until_start' => 'Data de Vencimento de',
-
'valid_until_end' => 'Data de Vencimento para',
-
}.freeze
-
# GET /users
-
def index
-
-
@array = []
-
@filtros = ""
-
@association_types = AssociationType.all
-
if params[:q].present?
-
@users = User.fulltext_search(params[:q])
-
elsif params[:filter_by].present?
-
@users = User.filter_by(params[:filter_by][:user])
-
-
params[:filter_by][:user].each do |_filter_name, filter_value|
-
next if filter_value.blank?
-
if( (_filter_name.include? "_start") || (_filter_name.include? "_end"))
-
@filtros = "#{@filtros}, [#{TRANSLATE_FILTER_LABEL[_filter_name]}: #{DateTime.strptime(filter_value, '%Y-%m-%d').strftime("%d/%m/%Y") }]"
-
else
-
@filtros = "#{@filtros}, [#{TRANSLATE_FILTER_LABEL[_filter_name]}: #{filter_value}]"
-
@array << [_filter_name, filter_value]
-
end
-
end
-
-
params[:filter_by][:associate].each do |_filter_name, filter_value|
-
next if filter_value.blank?
-
@associates = Associate.filter_by(params[:filter_by][:associate])
-
@users = @users.where(id: @associates.map(&:user_id))
-
names = []
-
if ( _filter_name == 'association_type_id_value')
-
AssociationType.where(id: filter_value).each do |associationType|
-
names << associationType.description
-
end
-
@filtros = "#{@filtros}, [#{TRANSLATE_FILTER_LABEL[_filter_name]}: #{names}]"
-
elsif( _filter_name == 'association_state_value')
-
filter_value.each do |name|
-
names << t('activerecord.models.associate.'+name).titleize
-
end
-
@filtros = "#{@filtros}, [#{TRANSLATE_FILTER_LABEL[_filter_name]}: #{names}]"
-
elsif( (_filter_name.include? "_start") || (_filter_name.include? "_end"))
-
@filtros = "#{@filtros}, [#{TRANSLATE_FILTER_LABEL[_filter_name]}: #{DateTime.strptime(filter_value, '%Y-%m-%d').strftime("%d/%m/%Y") }]"
-
else
-
@filtros = "#{@filtros}, [#{TRANSLATE_FILTER_LABEL[_filter_name]}: #{filter_value}]"
-
end
-
-
@array << [_filter_name, filter_value]
-
# break
-
end
-
else
-
@users = User.all
-
end
-
@users_paginate = @users.page(params[:page] || 1).per(50)
-
@users_length = @users.count
-
respond_to do |format|
-
format.html
-
format.xlsx
-
end
-
end
-
-
# GET /users/1
-
def show
-
if @user.associate
-
@payments = @user.payments
-
end
-
end
-
-
# GET /users/new
-
def new
-
@user = User.new
-
@singular_table_name = User.new
-
end
-
-
# GET /users/1/edit
-
def edit; end
-
-
# POST /users
-
def create
-
@user = User.new(user_params)
-
-
if @user.save
-
redirect_to admin_user_path(@user), notice: 'User was successfully created.'
-
else
-
render :new
-
end
-
end
-
-
# PATCH/PUT /users/1
-
def update
-
if @user.update(user_params)
-
redirect_to admin_user_path(@user), notice: 'User was successfully updated.'
-
else
-
render :edit
-
end
-
end
-
-
# DELETE /users/1
-
def destroy
-
@user.destroy
-
redirect_to admin_users_path, notice: 'User was successfully destroyed.'
-
end
-
-
def associate_start
-
User.find(params['id']).associate.start!
-
redirect_to admin_users_path
-
end
-
-
def associate_approve
-
User.find(params['id']).associate.approve!
-
redirect_to admin_users_path
-
end
-
-
def associate_reject
-
user = User.find(params['id'])
-
user.associate.motive = params['reason']
-
user.associate.save
-
user.associate.reject!
-
redirect_to admin_users_path
-
end
-
-
def associate_paid
-
associate = User.find(params['id']).associate
-
payment = associate.payments.where(payable_type: "Associate").where(payable_id: associate.id).where(status: 'awaiting_payment').first()
-
payment.manual_pay!
-
# @associate.payment_type = 'paid'
-
# associate.paid!
-
# payment = associate.payments.where(payable_type: "Associate").where(payable_id:
-
# payment.pay_date = Time.now
-
-
-
redirect_to admin_users_path
-
end
-
-
def associate_expire
-
User.find(params['id']).associate.expire!
-
redirect_to admin_users_path
-
end
-
-
-
private
-
# Use callbacks to share common setup or constraints between actions.
-
def set_user
-
@user = User.find(params[:id])
-
end
-
-
# Only allow a trusted parameter "white list" through.
-
def user_params
-
params.require(:user).permit(
-
:name, :birthday, :email, :institution, :newsletter, :active, :password,
-
:password_confirmation, :country, :state, :city, :active
-
# :password_confirmation, :country, :state, :city, :association_type
-
)
-
end
-
end
-
class AssociatesFacade
-
def self.has_accepted_ethics(userid)
-
associate = Associate.where(user_id: userid).first()
-
return (associate.code_of_ethics_terms)
-
end
-
-
def self.accept_code_ethics(userid, accepted)
-
need_ethics = false
-
-
if(AssociatesFacade.has_accepted_ethics(userid) == false)
-
if(accepted == "1")
-
associate = Associate.where(user_id: userid).first()
-
associate.code_of_ethics_terms = true
-
associate.code_of_ethics_terms_at = DateTime.now
-
associate.save
-
need_ethics = false
-
else
-
need_ethics = true
-
end
-
end
-
-
return need_ethics
-
end
-
-
def self.expire_associates
-
puts( Time.now.to_s+ "--START DO JOB DE ASSOCIADOS")
-
Associate.where(association_state: 'running', :valid_until => (Time.now - 30.days)..(Time.now + 30.days))
-
.or(Associate.where(association_state: 'expired', :valid_until => (Time.now - 10.days)..Time.now))
-
.each do |associate|
-
puts("Email:" + associate.user.email + " Validade: "+associate.valid_until.to_date.to_s)
-
case
-
when (associate.valid_until.to_date - 30.days) == Date.today
-
-
associate.will_expired_actions
-
puts("Enviado lembrete de 30 dias restantes")
-
-
when (associate.valid_until.to_date - 10.days) == Date.today
-
-
associate.send_will_expired_email(10)
-
puts( "Enviado lembrete de 10 dias restantes")
-
-
when (associate.valid_until.to_date - 5.days) == Date.today
-
-
associate.send_will_expired_email(5)
-
puts( "Enviado lembrete de 5 dias restantes")
-
-
when (associate.valid_until.to_date <= Date.today && associate.association_state == 'running')
-
associate.expire
-
puts( "Enviado lembrete de associacao expirada")
-
-
when (associate.valid_until.to_date + 5.days) == Date.today
-
-
associate.send_expired_email(5)
-
puts( "Enviado lembrete de 5 dias de associação expirada")
-
-
when (associate.valid_until.to_date + 10.days) == Date.today
-
-
associate.send_expired_email(10)
-
puts("Enviado lembrete de 10 dias de associação expirada")
-
else
-
puts("Nenhuma ação feita")
-
end
-
-
end
-
puts( Time.now.to_s+ "--START DO JOB DE USUARIO CRUZA GRAFO")
-
-
CruzaGrafosUser.where(user_state: 'running', valid_until: Time.now)
-
.each do |cruzaGrafoUser|
-
puts("Email:" + cruzaGrafoUser.user.email + " Validade: "+cruzaGrafoUser.valid_until.to_date.to_s)
-
cruzaGrafoUser.expire
-
end
-
-
CruzaGrafosUser.where(in_trial: true, valid_until: Time.now)
-
.each do |cruzaGrafoUser|
-
puts("Email:" + cruzaGrafoUser.user.email + "Trial finalizado ")
-
cruzaGrafoUser.expireTrial
-
end
-
puts("JOB EXECUTADO")
-
end
-
-
end
-
class UserAssociateAdminEditForm
-
include ActiveModel::Model
-
-
USER_ATTRIBUTES = [:name, :birthday, :country, :state, :city, :institution, :newsletter, :active, :email]
-
-
ASSOCIATE_ATTRIBUTES = [:country, :state, :city, :zipcode, :address_street, :neighborhood, :address_number,
-
:address_complement, :activity_description, :phone, :cpf,
-
:details_file, :accepted_terms, :approval_payment_date, :valid_until,
-
:association_type_id, :conclusion_date, :acting_medium, :color_or_race,
-
:gender, :code_of_ethics_terms, :code_of_ethics_terms_at, :accepted_terms_at, :whatsapp]
-
-
attr_accessor *(USER_ATTRIBUTES + ASSOCIATE_ATTRIBUTES)
-
attr_accessor :user, :admin
-
-
validates :name, :birthday, :country, :state, :city, :email, presence: true
-
validates :phone, :zipcode, :address_street, :neighborhood, :address_number, :approval_payment_date, :valid_until,
-
:association_type_id, :code_of_ethics_terms, :color_or_race, presence: true, if: :associate
-
-
validates :code_of_ethics_terms, acceptance: { message: "Este associado ainda não deu aceite neste termo"}, if: :associate
-
-
validate :cpf_uniqueness, if: :associate
-
-
validates_cpf_format_of :cpf, if: :associate
-
-
def cpf_uniqueness
-
if (associate.cpf != self.cpf)
-
if (Associate.where(cpf: self.cpf).first)
-
errors.add(:cpf, 'Este cpf já está cadastrado na nossa base')
-
end
-
end
-
end
-
-
def self.new_with_user(user)
-
attrs = user.attributes.slice(*USER_ATTRIBUTES.map(&:to_s))
-
attrs = attrs.merge(user.associate.attributes.slice(*ASSOCIATE_ATTRIBUTES.map(&:to_s))) if user.associate.present?
-
user_associate = new(attrs)
-
user_associate.user = user
-
-
user_associate
-
end
-
-
def associate
-
user.try(:associate)
-
end
-
-
def save
-
if !valid?
-
return false
-
end
-
if user.associate.blank?
-
return user.update(instance_values.slice(*USER_ATTRIBUTES.map(&:to_s)))
-
else
-
return (user.update(instance_values.slice(*USER_ATTRIBUTES.map(&:to_s))) &&
-
user.associate.update(instance_values.slice(*ASSOCIATE_ATTRIBUTES.map(&:to_s))))
-
end
-
end
-
-
end
-
class UserAssociateEditForm
-
include ActiveModel::Model
-
include ActiveModel::Dirty
-
# include UsersHelper
-
-
define_attribute_methods :cpf
-
-
USER_ATTRIBUTES = [:name, :birthday, :country, :state, :city, :institution, :newsletter]
-
-
ASSOCIATE_ATTRIBUTES = [:country, :state, :city, :zipcode, :address_street, :neighborhood, :address_number,
-
:address_complement, :activity_description, :phone, :cpf, :association_type,
-
:conclusion_date, :details_file, :association_type_id, :color_or_race, :gender, :code_of_ethics_terms, :code_of_ethics_terms_at, :acting_medium, :whatsapp]
-
-
# mount_uploader :details_file, FileUploader
-
-
attr_accessor *(USER_ATTRIBUTES + ASSOCIATE_ATTRIBUTES)
-
attr_accessor :user
-
-
validates :name, :birthday, :country, :state, :city, presence: true
-
validates :phone, :zipcode, :address_street, :code_of_ethics_terms, :neighborhood, :address_number, :association_type_id, :color_or_race, presence: true, if: :associate
-
-
validates :code_of_ethics_terms, acceptance: { message: "Este associado ainda não deu aceite neste termo"}, if: :associate
-
-
validates_cpf_format_of :cpf, if: :associate
-
validates_presence_of :conclusion_date, :if => lambda { |o| o.association_type_id == '2a3ee51c-434a-40e6-a96c-622b36c6a596' }
-
-
def self.new_with_user(user)
-
attrs = user.attributes.slice(*USER_ATTRIBUTES.map(&:to_s))
-
attrs = attrs.merge(user.associate.attributes.slice(*ASSOCIATE_ATTRIBUTES.map(&:to_s))) if user.associate.present?
-
user_associate = new(attrs)
-
user_associate.details_file = user.associate.details_file if user.associate.present?
-
user_associate.association_type = user.associate.association_type if user.associate.present?
-
user_associate.user = user
-
-
user_associate
-
end
-
-
def associate
-
user.try(:associate)
-
end
-
-
def save
-
return unless valid?
-
user.update(instance_values.slice(*USER_ATTRIBUTES.map(&:to_s)))
-
return true if user.associate.blank?
-
if !user.associate.update(instance_values.slice(*ASSOCIATE_ATTRIBUTES.map(&:to_s)))
-
return false
-
else
-
return true
-
end
-
-
end
-
-
end
-
class UserAssociateTransitionForm
-
include ActiveModel::Model
-
include ActiveModel::Dirty
-
-
define_attribute_methods :cpf
-
-
USER_ATTRIBUTES = [:name, :birthday, :country, :state, :city, :institution, :newsletter, :email, :password ,:password_confirmation]
-
-
ASSOCIATE_ATTRIBUTES = [:country, :state, :city, :zipcode, :address_street, :neighborhood, :address_number,
-
:address_complement, :activity_description, :phone, :cpf, :color_or_race, :gender, :acting_medium]
-
-
attr_accessor *(USER_ATTRIBUTES + ASSOCIATE_ATTRIBUTES)
-
attr_accessor :user
-
-
validates :name, :birthday, :country, :state, :city, :email, presence: true
-
validates :phone, :zipcode, :address_street, :neighborhood, :address_number, :activity_description, :color_or_race, presence: true, if: :associate
-
-
validates :password, confirmation: true
-
validates :password_confirmation, presence: true
-
validates :password, length: { in: 6..20 }
-
-
validates_cpf_format_of :cpf, if: :associate
-
-
def self.new_with_user(user)
-
attrs = user.attributes.slice(*USER_ATTRIBUTES.map(&:to_s))
-
attrs = attrs.merge(user.associate.attributes.slice(*ASSOCIATE_ATTRIBUTES.map(&:to_s))) if user.associate.present?
-
user_associate = new(attrs)
-
user_associate.user = user
-
-
user_associate
-
end
-
-
def associate
-
user.try(:associate)
-
end
-
-
def save
-
return unless valid?
-
if !user.update(instance_values.slice(*USER_ATTRIBUTES.map(&:to_s)))
-
return user.errors.messages
-
end
-
return true if user.associate.blank?
-
if !user.associate.update(instance_values.slice(*ASSOCIATE_ATTRIBUTES.map(&:to_s)))
-
return user.associate.errors.messages
-
else
-
return true
-
end
-
-
end
-
end
-
1
module AdminAssociatesHelper
-
end
-
1
module ApplicationHelper
-
1
def contains_errors(record)
-
return unless record.present? && record.errors.present?
-
content_tag(:div, 'Revise os problemas em vermelho abaixo:', class: 'alert alert-danger')
-
end
-
-
1
def no_cache_image
-
r = Random.new
-
r.rand(100...10_000)
-
end
-
-
1
def youtube_video(url)
-
render :partial => 'layouts/site/video', :locals => { :url => url }
-
end
-
-
end
-
1
module ContentHelper
-
1
def content_type
-
params[:type]
-
end
-
-
1
def content_type_name
-
t("activerecord.models.#{content_type}.one")
-
end
-
-
1
def content_type_name_plural
-
t("activerecord.models.#{content_type}.other")
-
end
-
-
1
def content_type_path(content)
-
send("admin_#{content_type}_path", content)
-
end
-
-
1
def new_content_type_path
-
send("new_admin_#{content_type}_path")
-
end
-
-
1
def edit_content_type_path(content)
-
send("edit_admin_#{content_type}_path", content)
-
end
-
-
1
def unpublish_content_type_path(content)
-
send("unpublish_admin_#{content_type}_path", content)
-
end
-
-
1
def publish_content_type_path(content)
-
send("publish_admin_#{content_type}_path", content)
-
end
-
-
# if content list comes from search or content
-
1
def search_context
-
return true if params[:action] == 'search'
-
end
-
-
# create social share url
-
1
def make_social_url(_conent_type, content_slug)
-
url_to_share = 'http://www.abraji.org.br/'
-
return url_to_share + content_slug if _conent_type.empty?
-
url_to_share + _conent_type + '/' + content_slug
-
end
-
-
1
def card_css_class(content)
-
content.image.present? ? ' card-image' : ' card-noimage'
-
end
-
-
1
def exhibit_path(content)
-
return unless content.try(:type)
-
type = content.type.underscore
-
type = 'course' if type.include?('course')
-
send("exhibit_#{type}_path", content.slug)
-
end
-
end
-
1
module HelpdesksHelper
-
end
-
1
module PagesHelper
-
1
def hello_world(text)
-
content_tag(:h1, text, class: 'alguma')
-
end
-
end
-
1
module PaymentHelper
-
end
-
1
module ProjectsHelper
-
end
-
1
module SectionsHelper
-
1
def published?(section)
-
section.published
-
end
-
-
1
def card_columns(count)
-
case count
-
when 1
-
'col-sm-6'
-
when 2
-
'col-sm-6'
-
when 3
-
'col-sm-4'
-
when 4
-
'col-sm-3'
-
else
-
'col-sm-3'
-
end
-
end
-
end
-
1
module StaticContentsHelper
-
end
-
1
module TransitionHelper
-
end
-
1
module UserAssociateControllerHelper
-
end
-
class CpfInput < SimpleForm::Inputs::Base
-
def input(wrapper_options)
-
currency = options.delete(:currency) || default_currency
-
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
-
-
content_tag(:div, input_group(currency, merged_input_options), class: 'input-group')
-
end
-
-
private
-
-
def input_group(currency, merged_input_options)
-
"#{currency_addon(currency)} #{@builder.text_field(attribute_name, merged_input_options)}".html_safe
-
end
-
-
def currency_addon(currency)
-
content_tag(:span, currency, class: 'input-group-addon')
-
end
-
-
def default_currency
-
'$'
-
end
-
end
-
class CurrencyInput < SimpleForm::Inputs::Base
-
def input(wrapper_options)
-
currency = options.delete(:currency) || default_currency
-
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
-
-
content_tag(:div, input_group(currency, merged_input_options), class: 'input-group')
-
end
-
-
private
-
-
def input_group(currency, merged_input_options)
-
"#{currency_addon(currency)} #{@builder.text_field(attribute_name, merged_input_options)}".html_safe
-
end
-
-
def currency_addon(currency)
-
content_tag(:span, currency, class: 'input-group-addon')
-
end
-
-
def default_currency
-
'$'
-
end
-
end
-
class ApplicationMailer < ActionMailer::Base
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
class ContactMailer < ApplicationMailer
-
-
def mail_message(contact)
-
@contact = contact
-
email_to = contact.subject_to_email_enum.find { |key, email| key == contact.subject }
-
subject_selected = contact.subject_enum.find { |label, value| value == contact.subject }
-
email_from = contact.email
-
subject = "[Fale Conosco: abraji.org.br] " + subject_selected[0]
-
-
mail to:email_to[1], :reply_to => email_from, subject: subject
-
end
-
end
-
class CruzaGrafosMailer < ApplicationMailer
-
def moderate(user)
-
@user = user
-
mail to: (ENV['EMAIL_MODERACAO']+', '+ ENV['EMAIL_FINANCEIRO']), subject: "Novo pedido de inscrição no Cruza Grafos de #{@user.name}."
-
end
-
-
def wait_moderation(user)
-
@user = user
-
mail to: @user.email, subject: 'Pedido de inscrição no Cruza Grafos'
-
end
-
-
def approved(user)
-
@user = user
-
mail to: @user.email, subject: 'Sua inscrição no Cruza Grafos foi aprovada'
-
end
-
-
def reject(user)
-
@user = user
-
@motive = user.cruza_grafos_user.motive
-
mail to: @user.email, subject: 'Sobre seu pedido de inscrição no Cruza Grafos à Abraji'
-
end
-
-
def paid(user)
-
@user = user
-
mail to: ENV['EMAIL_FINANCEIRO'], subject: "A inscrição no Cruza Grafos do #{@user.name} teve o pagamento aprovado."
-
end
-
-
def paidUser(user)
-
@user = user
-
mail to: @user.email, subject: "Seu pagamento da inscrição no Cruza Grafos da Abraji foi aprovado."
-
end
-
-
def will_expired(user, time)
-
@user = user
-
@time = time
-
if time == 5 || time == 10 || time == 30
-
subject = subject = 'Sua inscrição no Cruza Grafos irá expirar em '+time.to_s+' dias.'
-
else
-
subject = 'Sua inscrição no Cruza Grafos irá expirar.'
-
end
-
mail to: @user.email, subject: subject
-
end
-
-
def expired(user, time)
-
@user = user
-
@time = time
-
if time == 5 || time == 10
-
subject = 'Sua inscrição no Cruza Grafos expirou faz '+time.to_s+' dias.'
-
else
-
subject = 'Sua inscrição no Cruza Grafos expirou.'
-
end
-
mail to: @user.email, subject: subject
-
end
-
-
end
-
class UserMailer < ApplicationMailer
-
def moderate(user)
-
@user = user
-
mail to: (ENV['EMAIL_MODERACAO']+', '+ ENV['EMAIL_FINANCEIRO']), subject: "Novo pedido de Moderação de #{@user.name}."
-
end
-
-
def paid(user)
-
@user = user
-
mail to: ENV['EMAIL_FINANCEIRO'], subject: "Associação do #{@user.name} teve o pagamento aprovado."
-
end
-
-
def paidUser(user)
-
@user = user
-
mail to: @user.email, subject: "Seu pagamento de Associação da Abraji foi aprovado."
-
end
-
-
def wait_moderation(user)
-
@user = user
-
mail to: @user.email, subject: 'Pedido de associação'
-
end
-
-
def approved(user)
-
@user = user
-
mail to: @user.email, subject: 'Sua associação à Abraji foi aprovada'
-
end
-
-
def reject(user)
-
@user = user
-
@motive = user.associate.motive
-
mail to: @user.email, subject: 'Sobre seu pedido de associação à Abraji'
-
end
-
-
def welcome(user)
-
@user = user
-
mail to: @user.email, subject: "Bem vindo #{@user.name} à Abraji"
-
end
-
-
def associated(user)
-
@user = user
-
mail to: @user.email, subject: 'Cofirmação de associação da Abraji'
-
end
-
-
def will_expired(user, time, assocTypeChange = false)
-
@user = user
-
@time = time
-
@assocTypeChange = assocTypeChange
-
if time == 5 || time == 10 || time == 30
-
subject = subject = 'Sua associação Abraji irá expirar em '+time.to_s+' dias.'
-
else
-
subject = 'Sua associação Abraji irá expirar.'
-
end
-
mail to: @user.email, subject: subject
-
end
-
-
def expired(user, time)
-
@user = user
-
@time = time
-
if time == 5 || time == 10
-
subject = 'Sua associação Abraji expirou faz '+time.to_s+' dias.'
-
else
-
subject = 'Sua associação Abraji expirou.'
-
end
-
mail to: @user.email, subject: subject
-
end
-
-
end
-
class ActivityReport < FileRecord
-
def self.json_file_path
-
'institutional/transparence/relatorio_de_atividades.json'
-
end
-
end
-
1
class Admin < ApplicationRecord
-
#include RailsAdmin::Admin
-
-
# Include default devise modules. Others available are:
-
# :confirmable, :lockable, :registerable, :timeoutable and :omniauthable
-
1
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
-
-
1
validates :name, presence: true
-
1
validates :username, presence: true, uniqueness: { case_sensitive: false }
-
-
1
attr_writer :login
-
-
1
def login
-
@login || username
-
end
-
-
1
def self.find_for_database_authentication(warden_conditions)
-
conditions = warden_conditions.dup
-
return find_by(conditions.to_h) if conditions.key?(:username) || conditions.key?(:email)
-
login = conditions.delete(:login)
-
return unless login
-
where(conditions.to_h).find_by(['lower(username) = :value OR lower(email) = :value', { value: login.downcase }])
-
end
-
end
-
1
class ApplicationRecord < ActiveRecord::Base
-
1
self.abstract_class = true
-
end
-
class Associate < ApplicationRecord
-
include AASM
-
default_scope -> { order(accepted_terms_at: :desc) }
-
-
before_save :remove_mask, :if => [:cpf, :phone]
-
before_validation :remove_mask , :if => [:cpf]
-
has_many :payments, as: :payable, dependent: :destroy
-
-
PAYMENT_TYPES = %w[pending professional_unique professional_parcel student_unique student_parcel].freeze
-
-
belongs_to :user, dependent: :destroy
-
belongs_to :association_type
-
-
FILTER_DATE_SCOPES = %i[valid_until].freeze
-
FILTER_VALUE_SCOPES = %i[cpf association_state association_type_id].freeze
-
include Concerns::Filterable
-
-
COLOR_OR_RACE_ENUM = {
-
'Branca' => 'white',
-
'Parda' => 'parda',
-
'Preta' => 'black',
-
'Amarela' => 'yellow',
-
'Indígena' => 'indigenous'
-
}.freeze
-
-
def color_or_race_list
-
COLOR_OR_RACE_ENUM
-
end
-
-
GENDER_ENUM = {
-
'Feminino' => 'female',
-
'Masculino' => 'male',
-
'Não-binário' => 'non-binary',
-
'Transgênero' => 'transgender'
-
}.freeze
-
-
def gender_list
-
GENDER_ENUM
-
end
-
-
mount_uploader :details_file, FileUploader
-
-
validates :phone, :country, :cpf, :state, :city, :zipcode, :address_street, :neighborhood, :address_number,
-
:activity_description, :accepted_terms, :code_of_ethics_terms, :details_file, :association_type, :color_or_race, presence: true
-
-
validates_cpf_format_of :cpf, if: -> {self.country == "BR"}
-
validates_uniqueness_of :cpf, message: "O CPF já foi cadastrado!"
-
-
validates :payment_type, inclusion: { in: PAYMENT_TYPES }
-
-
aasm column: 'association_state' do
-
state :nil, initial: true #estado inicial da criação
-
state :new_associate, after_enter: :send_moderator_email #Estado inicial do associado (pendente de moderação)
-
state :approved, after_enter: :approved_actions #Associado moderado e aprovado (pendente de pagamento)
-
state :awaiting_payment, after_enter: :awaiting_payment_actions #Associado inicia o pagamento (pendente aprovação do pagamento)
-
state :running, after_enter: :running_actions #Associado pagou (pendente chegar na data de expiração)
-
state :rejected, after_enter: :send_reject_email #Associado moderado e rejeitado
-
state :expired, after_enter: :expired_actions
-
-
event :start do
-
transitions from: [:nil], to: :new_associate
-
end
-
-
event :approve do
-
transitions from: [:new_associate, :rejected], to: :approved
-
end
-
-
event :reject do
-
transitions from: %i[new_associate approved running], to: :rejected
-
end
-
-
event :pay do
-
transitions from: [:approved, :expired], to: :awaiting_payment
-
end
-
-
event :not_paid do
-
transitions from: [:awaiting_payment], to: :approved
-
end
-
-
event :paid do
-
transitions from: [:awaiting_payment, :expired, :running], to: :running
-
end
-
-
event :expire do
-
transitions from: [:running], to: :expired
-
end
-
-
event :manual_paid do
-
transitions from: %i[nil new_associate awaiting_payment approved running rejected expired], to: :running
-
end
-
-
end
-
-
def send_moderator_email
-
begin
-
# Send to moderator
-
UserMailer.moderate(user).deliver
-
# Send to user
-
UserMailer.wait_moderation(user).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
-
end
-
-
def approved_actions
-
# grava data da moderação
-
self.moderate_date = Time.now
-
self.save
-
-
create_association_payment
-
-
# enviar email
-
send_approved_email
-
end
-
-
def create_association_payment
-
# criar pagamento
-
payment = Payment.new
-
payment.user = self.user
-
payment.payable = self
-
payment.name = 'new_association '+self.association_type.description
-
payment.price_cents = self.association_type.annuity_cents
-
payment.price_currency = self.association_type.annuity_currency
-
payment.payable_type = "Associate"# can only be Associate or Course for the polymorph
-
# raise payment.errors.inspect unless payment.valid?
-
payment.save
-
end
-
-
def send_approved_email
-
begin
-
UserMailer.approved(user).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
end
-
-
def awaiting_payment_actions; end
-
-
def running_actions; end
-
-
def send_reject_email
-
self.moderate_date = Time.now
-
self.save
-
begin
-
UserMailer.reject(user).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
end
-
-
def expired_actions
-
if !self.save
-
Rails.logger.error 'Problema ao expirar associção. Error message: ' + self.errors.messages.to_s
-
Rails.logger.error 'Expiração forçada'
-
self.save(validate: false)
-
end
-
send_expired_email(0)
-
end
-
-
def will_expired_actions
-
if self.association_type.description == "Estudante de graduação" && Date.today > self.conclusion_date
-
self.association_type = AssociationType.find_by(description: "Profissional e/ou estudante de pós-graduação")
-
if !self.save
-
Rails.logger.error 'Problema ao mudar tipo de associção. Error message: ' + self.errors.messages.to_s
-
Rails.logger.error 'Expiração forçada'
-
self.save(validate: false)
-
end
-
create_association_payment
-
send_will_expired_email(30, true)
-
else
-
create_association_payment
-
send_will_expired_email(30)
-
end
-
end
-
-
def send_will_expired_email(days, assocTypeChange = false)
-
begin
-
UserMailer.will_expired(user, days, assocTypeChange).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
end
-
-
def send_expired_email(days)
-
begin
-
UserMailer.expired(user, days).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
end
-
-
def isAssociationValid
-
-
end
-
-
def remove_mask
-
self.cpf = self.cpf.gsub(/[^a-zA-Z0-9]/, '')
-
self.phone = self.phone.gsub(/[^0-9]/, '')
-
end
-
-
def valid_for_covid_voucher
-
if Date.today.year == 2020
-
# if self.user.email.include?("covid") && Date.today.year == 2020
-
if Payment.where(payable: self, status: 'paid', created_at: Date.new(2019, 1, 1).beginning_of_year..Date.new(2019, 1, 1).end_of_year).empty?
-
return false
-
else
-
return true
-
end
-
else
-
return false
-
end
-
-
end
-
-
def covid_voucher_active
-
Payment.find_by(payable: self, payable_type: "Associate", name:'association covid voucher')
-
end
-
-
end
-
class AssociationType < ApplicationRecord
-
has_one :associate
-
end
-
class AuditReport < FileRecord
-
def self.json_file_path
-
'institutional/transparence/relatorio_de_auditorias.json'
-
end
-
end
-
class Ckeditor::Asset < ApplicationRecord
-
include Ckeditor::Orm::ActiveRecord::AssetBase
-
-
delegate :url, :current_path, :content_type, to: :data
-
-
validates :data, presence: true
-
end
-
class Ckeditor::AttachmentFile < Ckeditor::Asset
-
mount_uploader :data, CkeditorAttachmentFileUploader, mount_on: :data_file_name
-
-
def url_thumb
-
@url_thumb ||= Ckeditor::Utils.filethumb(filename)
-
end
-
end
-
class Ckeditor::Picture < Ckeditor::Asset
-
mount_uploader :data, CkeditorPictureUploader, mount_on: :data_file_name
-
-
def url_content
-
url(:content)
-
end
-
end
-
class ClassroomCourse < Content
-
include RailsAdmin::ClassroomCourse
-
-
accepts_nested_attributes_for :classroom_course_info, allow_destroy: true
-
delegate :registration_phase, :duration, :number_of_students, :details_file,
-
:highlighted, :address, :date, :price, :contact_phone_number,
-
:contact_email, to: :classroom_course_info, allow_nil: true
-
-
validates :classroom_course_info, presence: true
-
-
attr_accessor :details_file_cachess
-
-
def self.section_contents(section)
-
section.contents.where(type: 'ClassroomCourse').limit(1)
-
end
-
end
-
class ClassroomCourseInfo < ApplicationRecord
-
include RailsAdmin::ClassroomCourseInfo
-
-
belongs_to :content, inverse_of: :classroom_course_info
-
-
mount_uploader :details_file, FileUploader
-
-
after_initialize :init
-
-
def init
-
self.contact_email ||= 'cursos@abraji.org.br'
-
self.contact_phone_number ||= '+55 11 3159-0344'
-
end
-
-
REGISTRATION_PHASE_ENUM = {
-
'Pré-Inscrição' => 'pre-register',
-
'Inscrições Abertas' => 'open',
-
'Encerrado' => 'closed'
-
}.freeze
-
-
def registration_phase_enum
-
REGISTRATION_PHASE_ENUM
-
end
-
-
def title
-
'editar dados do curso'
-
end
-
-
validates :contact_email, presence: true
-
validates :contact_phone_number, presence: true
-
validates :duration, presence: true
-
validates :number_of_students, presence: true
-
end
-
1
module Concerns::Filterable
-
1
extend ActiveSupport::Concern
-
-
1
def self.included(base)
-
1
base.scope :filter_by_field_start, ->(field, start_time) { where("#{field} >= ?", start_time) }
-
1
base.scope :filter_by_field_end, ->(field, end_time) { where("#{field} <= ?", end_time) }
-
1
base.scope :filter_by_field_likeness, ->(field, text) { where("#{field} ilike ?", "%#{text}%") }
-
1
base.scope :filter_by_field_truthness, ->(field) { where(field => true) }
-
1
base.scope :filter_by_field_value, ->(field, value) { where(field => value) }
-
-
1
if defined?(base::FILTER_DATE_SCOPES)
-
1
base::FILTER_DATE_SCOPES.to_a.each do |field|
-
2
base.scope :"filter_by_#{field}_start", ->(start_time) { filter_by_field_start(field, start_time) }
-
2
base.scope :"filter_by_#{field}_end", ->(end_time) { filter_by_field_end(field, end_time) }
-
end
-
end
-
1
if defined?(base::FILTER_TEXT_SCOPES)
-
1
base::FILTER_TEXT_SCOPES.to_a.each do |field|
-
4
base.scope :"filter_by_#{field}_likeness", ->(text) { filter_by_field_likeness(field, text) }
-
end
-
end
-
1
if defined?(base::FILTER_TRUTHY_SCOPES)
-
base::FILTER_TRUTHY_SCOPES.to_a.each do |field|
-
base.scope :"filter_by_#{field}_truthness", -> () { filter_by_field_truthness(field) }
-
end
-
end
-
1
if defined?(base::FILTER_VALUE_SCOPES)
-
base::FILTER_VALUE_SCOPES.to_a.each do |field|
-
base.scope :"filter_by_#{field}_value", ->(value) { filter_by_field_value(field, value) }
-
end
-
end
-
-
1
base.scope :filter_by, ->(params) {
-
result = where(nil)
-
filter_scopes = []
-
filter_scopes += base::FILTER_DATE_SCOPES.collect { |x| (x.to_s + '_start').to_sym } if defined?(base::FILTER_DATE_SCOPES)
-
filter_scopes += base::FILTER_DATE_SCOPES.collect { |x| (x.to_s + '_end').to_sym } if defined?(base::FILTER_DATE_SCOPES)
-
filter_scopes += base::FILTER_TEXT_SCOPES.collect { |x| (x.to_s + '_likeness').to_sym } if defined?(base::FILTER_TEXT_SCOPES)
-
filter_scopes += base::FILTER_TRUTHY_SCOPES.collect { |x| (x.to_s + '_truthness').to_sym } if defined?(base::FILTER_TRUTHY_SCOPES)
-
filter_scopes += base::FILTER_VALUE_SCOPES.collect { |x| (x.to_s + '_value').to_sym } if defined?(base::FILTER_VALUE_SCOPES)
-
params.each do |filter_name, filter_value|
-
next if !filter_scopes.include?(filter_name.to_sym) || filter_value.blank?
-
result = result.send("filter_by_#{filter_name}", filter_value)
-
end
-
result
-
}
-
end
-
end
-
module Concerns::Publishable
-
extend ActiveSupport::Concern
-
-
included do
-
scope :published, ->(admin) { admin ? where(nil) : where("(published = true AND publish_date < ?) OR (published = true AND publish_date IS NULL)", Time.now) }
-
end
-
-
def publish
-
update published: true
-
end
-
-
def unpublish
-
update published: false
-
end
-
-
def slug_value
-
respond_to?(:title) ? title : name
-
end
-
-
def slug_value_changed?
-
respond_to?(:title) ? title_changed? : name_changed?
-
end
-
end
-
1
module Concerns::PublishableSections
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
scope :published, ->(admin) { admin ? where(nil) : where('published = true') }
-
end
-
-
1
def publish
-
update published: true
-
end
-
-
1
def unpublish
-
update published: false
-
end
-
-
1
def slug_value
-
respond_to?(:title) ? title : name
-
end
-
-
1
def slug_value_changed?
-
respond_to?(:title) ? title_changed? : name_changed?
-
end
-
end
-
class Congress < Content
-
include RailsAdmin::Congress
-
-
accepts_nested_attributes_for :congress_info, allow_destroy: true
-
delegate :videos, :link, to: :congress_info, allow_nil: true
-
-
def self.filters
-
[['Todos os congressos', 'all']] + super()
-
end
-
-
def self.croped_image_size
-
{ 'width': 674, 'height': 282 }
-
end
-
-
def self.section_contents(section)
-
section.contents.where(type: 'Congress').limit(4)
-
end
-
end
-
class CongressInfo < ApplicationRecord
-
include RailsAdmin::CongressInfo
-
-
belongs_to :content, inverse_of: :congress_info
-
-
validates :content, presence: true
-
-
def title
-
'editar dados do congresso'
-
end
-
-
def videos_s=(string)
-
self.videos = string.split(',')
-
end
-
-
def videos_s
-
videos.join(',')
-
end
-
end
-
class Contact
-
include ActiveModel::Model
-
-
attr_accessor :name
-
attr_accessor :email
-
attr_accessor :phone
-
attr_accessor :message
-
attr_accessor :subject
-
-
validates :name, :email, :phone, :message, :subject, presence: true
-
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
-
-
SUBJECT_LIST = [['Tornar-se associado','tornar-se-associado'],['Regularizar minha associação','regularizar-minha-associacao'],['Fazer uma doação','fazer-uma-doacao'],['Informações sobre cursos','informacoes-sobre-cursos'],['Informações sobre o Congresso','informacoes-sobre-o-congresso'],['Pedidos de informação e entrevistas','pedidos-de-informacao-e-entrevista'],['Outro','outro']].freeze
-
-
SUBJECT_TO_EMAIL_LIST = [['tornar-se-associado','abraji@abraji.org.br'],['regularizar-minha-associacao','financeiro@abraji.org.br'],['fazer-uma-doacao','financeiro@abraji.org.br'],['informacoes-sobre-cursos','cursos@abraji.org.br'],['informacoes-sobre-o-congresso','contato@abraji.org.br'],['pedidos-de-informacao-e-entrevista','abraji@abraji.org.br'],['outro','abraji@abraji.org.br']].freeze
-
-
def subject_enum
-
SUBJECT_LIST
-
end
-
-
def subject_to_email_enum
-
SUBJECT_TO_EMAIL_LIST
-
end
-
end
-
-
class Content < ApplicationRecord
-
default_scope -> { order(created_at: :desc) }
-
include Sluggi::Slugged
-
include Concerns::Publishable
-
include PgSearch
-
-
mount_base64_uploader :image, ImageUploader, file_name: ->(c) {
-
return Random.rand(100...999_999) if c.title.blank?
-
c.title.downcase.strip.tr(' ', '-').gsub(/[^\w-]/, '')+Time.now.nsec.to_s
-
}
-
-
validates :title, presence: true, uniqueness: { case_sensitive: false, scope: :type }
-
validates :slug, presence: true, uniqueness: { case_sensitive: false, scope: :type }
-
validates :content, presence: true
-
-
before_save :set_summary_fields
-
-
has_and_belongs_to_many :sections, inverse_of: :contents
-
has_one :classroom_course_info, dependent: :destroy, inverse_of: :content
-
has_one :congress_info, dependent: :destroy, inverse_of: :content
-
has_one :online_course_info, dependent: :destroy, inverse_of: :content
-
has_one :helpdesk_info, dependent: :destroy, inverse_of: :content
-
has_one :news_info, dependent: :destroy, inverse_of: :content
-
has_one :project_info, dependent: :destroy, inverse_of: :content
-
has_one :publication_info, dependent: :destroy, inverse_of: :content
-
has_many :payments, as: :payable, dependent: :destroy
-
-
def self.filters
-
Section.all.map { |section| [section.name, section.slug] }
-
end
-
-
# section filter
-
def self.published_and_filtered(admin, filter)
-
all_contents = published(admin)
-
if Section.where(slug: filter).exists?
-
section = Section.find_by(slug: filter)
-
return all_contents & section.contents
-
end
-
all_contents
-
end
-
-
# each letter represents a weight while searching
-
pg_search_scope :any_word_search, against: {
-
title: 'A', title_summary: 'B', content: 'C'
-
}, using: { tsearch: { prefix: true, any_word: true } }
-
pg_search_scope :exact_search, against: {
-
title: 'A', title_summary: 'B', content: 'C'
-
}, using: { tsearch: { prefix: true, any_word: false } }
-
-
def self.fulltext_search(text)
-
return all if text.blank?
-
['"', "'"].any? { |quotation| text.include?(quotation) } ? exact_search(text) : any_word_search(text)
-
end
-
-
def extra_info?
-
send("#{type.underscore}_info").present?
-
end
-
-
def css_class
-
return '' if sections.blank?
-
sections.length > 1 ? 'noclass' : sections.first.css_class
-
end
-
-
def set_summary_fields
-
self.title_summary = title if title_summary.blank?
-
self.content_summary = content if content_summary.blank?
-
end
-
-
def self.croped_image_size
-
{ 'width': 674, 'height': 282 }
-
end
-
end
-
class Course
-
def self.published(admin)
-
online_courses = OnlineCourse.published(admin)
-
classroom_courses = ClassroomCourse.published(admin)
-
-
classroom_highlighted = sort_courses(classroom_courses.select(&:highlighted))
-
online_open_inscription = filter_course_phase(online_courses, 'open')
-
online_pre_inscription = filter_course_phase(online_courses, 'pre-register')
-
online_close_inscription = filter_course_phase(online_courses, 'closed')
-
classroom_unhighlighted = sort_courses(classroom_courses.reject(&:highlighted))
-
-
classroom_highlighted + online_open_inscription + online_pre_inscription +
-
online_close_inscription + classroom_unhighlighted
-
end
-
-
def self.sort_courses(courses)
-
courses.sort_by { |h| h[:created_at] }.reverse
-
end
-
-
def self.filter_course_phase(courses, phase)
-
sort_courses(courses.select { |course| course.registration_phase == phase })
-
end
-
-
def self.filters
-
{
-
'Todos os cursos' => 'all',
-
'Cursos presenciais' => 'classroom',
-
'Cursos On-Line' => 'online',
-
'Cursos On-Line - Inscrições Abertas' => 'online_open_inscription',
-
'Cursos On-Line - Pré Incrição' => 'online_pre_inscription',
-
'Cursos On-Line - Inscrições Encerradas' => 'online_close_inscription'
-
}
-
end
-
-
def self.published_and_filtered(admin, filter)
-
all_courses = published(admin)
-
return all_courses unless %w[
-
classroom online online_open_inscription online_pre_inscription online_close_inscription
-
].include?(filter)
-
return all_courses.select { |course| course.is_a?(ClassroomCourse) } if filter == 'classroom'
-
online_courses = all_courses.select { |course| course.is_a?(OnlineCourse) }
-
case filter
-
when 'online_open_inscription'
-
online_courses.select { |course| course.registration_phase == 'open' }
-
when 'online_pre_inscription'
-
online_courses.select { |course| course.registration_phase == 'pre-register' }
-
when 'online_close_inscription'
-
online_courses.select { |course| course.registration_phase == 'closed' }
-
else
-
online_courses
-
end
-
end
-
end
-
class CruzaGrafosType < ApplicationRecord
-
has_one :cruza_grafos_user
-
end
-
class CruzaGrafosUser < ApplicationRecord
-
include AASM
-
belongs_to :user
-
belongs_to :cruza_grafos_type, optional: true
-
has_many :payments, as: :payable, dependent: :destroy
-
-
mount_uploader :details_file, FileUploader
-
-
validates :company, :professional_attachment, :how_did_you_know, :why_interested, :cpf_cnpj,
-
:work_company_link, :social_media_link, :terms_of_use, :privacy_policy, presence: true
-
-
before_save :remove_mask, :if => [:cpf_cnpj]
-
before_validation :remove_mask , :if => [:cpf_cnpj]
-
validates_uniqueness_of :cpf_cnpj
-
validate :cpf_cnpf_presence_validation
-
-
def cpf_cnpf_presence_validation
-
if !CPF.valid?(cpf_cnpj) && !CNPJ.valid?(cpf_cnpj)
-
errors.add(:cpf_cnpj, "cpf/cnpj inválidos")
-
end
-
end
-
-
def remove_mask
-
self.cpf_cnpj = self.cpf_cnpj.gsub(/[^a-zA-Z0-9]/, '')
-
end
-
-
def create_cruza_grafo_payment cg_type
-
# criar pagamento
-
payment = Payment.new
-
payment.user = self.user
-
payment.payable = self
-
payment.name = 'Cruza Grafos - ' + cg_type.description
-
payment.price_cents = cg_type.price_cents
-
payment.price_currency = cg_type.price_currency
-
payment.payable_type = "CruzaGrafosUser"# can only be Associate or Course for the polymorph
-
# raise payment.errors.inspect unless payment.valid?
-
payment.save
-
end
-
-
-
def useTrial
-
return if self.used_trial
-
self.used_trial = true
-
self.in_trial = true
-
self.valid_until = Date.today + 30.days
-
if !self.save
-
puts self.errors.message
-
end
-
end
-
-
def expireTrial
-
return unless self.in_trial
-
self.used_trial = true
-
self.in_trial = false
-
self.valid_until = Date.today
-
if !self.save
-
puts self.errors.message
-
end
-
end
-
-
aasm column: 'user_state' do
-
state :nil, initial: true #estado inicial da criação
-
state :waiting_moderation, after_enter: :waiting_moderation_actions #assim que concluido o cadastro, ja vai pra moderação
-
state :waiting_pay_user, after_enter: :waiting_pay_user_actions #depois de moderado fica a espera do pagamento
-
state :waiting_pay_confirm, after_enter: :waiting_pay_confirm_actions # apos pagamento espera confirmação do pagamento
-
state :running, after_enter: :running_actions #pagamento confirmado começa a contar o serviço
-
state :rejected_moderation, after_enter: :reject_moderation_actions #se a moderação for negada
-
state :rejected_payment, after_enter: :reject_payment_actions #se a moderação for negada
-
state :expired, after_enter: :expired_actions # quando o tempo pago expira
-
-
event :start do # assim que o usuario completa o cadastro ele ja vai para moderação
-
transitions from: [:nil, :rejected_moderation], to: :waiting_moderation
-
end
-
-
event :approve_moderation do # a moderação foi aprovada - agora falta o usuario pagar
-
transitions from: [:waiting_moderation, :rejected_payment], to: :waiting_pay_user
-
end
-
-
event :reject_moderation do # moderação rejeiada
-
transitions from: %i[waiting_moderation], to: :rejected_moderation
-
end
-
-
event :user_paid do # o usuario pagou e vai ter que esperar confirmação
-
transitions from: [:waiting_pay_user], to: :waiting_pay_confirm
-
end
-
-
event :payment_confirm do # pagamento confirmado
-
transitions from: [:waiting_pay_confirm, :expired], to: :running
-
end
-
-
event :payment_reject do # pagamento rejeitado
-
transitions from: [:waiting_pay_confirm], to: :rejected_payment
-
end
-
-
event :not_paid do
-
transitions from: [:running], to: :waiting_pay_user
-
end
-
-
event :expire do # serviço expirado
-
transitions from: [:running], to: :expired
-
end
-
-
event :manual_paid do
-
transitions from: %i[nil waiting_moderation waiting_pay_user waiting_pay_confirm running expired], to: :running
-
end
-
end
-
-
def waiting_moderation_actions
-
begin
-
# Send to moderator
-
CruzaGrafosMailer.moderate(user).deliver
-
# Send to user
-
CruzaGrafosMailer.wait_moderation(user).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
end
-
def waiting_pay_user_actions
-
useTrial
-
# grava data da moderação
-
self.moderate_date = Time.now
-
self.save
-
add_cg_payment
-
-
# enviar email
-
begin
-
CruzaGrafosMailer.approved(user).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
-
end
-
def waiting_pay_confirm_actions; end
-
def running_actions
-
# para casos de pagamento manual faz o check de expiração do trial
-
expireTrial
-
self.approval_payment_date = Time.now
-
#TODO enviar email??
-
end
-
def reject_moderation_actions
-
self.moderate_date = Time.now
-
self.save
-
begin
-
CruzaGrafosMailer.reject(user).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
end
-
def rejected_payment_actions; end
-
-
def expired_actions
-
if !self.save
-
Rails.logger.error 'Problema ao expirar inscrição Cruza Grafo. Error message: ' + self.errors.messages.to_s
-
Rails.logger.error 'Expiração forçada'
-
self.save(validate: false)
-
else
-
add_cg_payment
-
begin
-
CruzaGrafosMailer.expired(user, 0).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
end
-
end
-
-
def add_cg_payment
-
#expira qualquer pagamento antigo de CG
-
Payment.where(user_id: self.user.id, payable_type: "CruzaGrafosUser").update_all( status: "expired")
-
# cria um pagamento inicial qualquer
-
cg_type = CruzaGrafosType.first
-
self.cruza_grafos_type = cg_type
-
self.save
-
self.create_cruza_grafo_payment cg_type
-
end
-
end
-
class Curator < Person
-
def self.json_file_path
-
'institutional/conselho_curador.json'
-
end
-
end
-
class Deponent < Person
-
def self.json_file_path
-
'institutional/fund/depoimentos.json'
-
end
-
end
-
class Director < Person
-
def self.json_file_path
-
'institutional/diretoria.json'
-
end
-
end
-
class FileRecord < JsonModel
-
attr_accessor :name, :url, :active
-
end
-
class Helpdesk < Content
-
include RailsAdmin::Helpdesk
-
-
accepts_nested_attributes_for :helpdesk_info, allow_destroy: true
-
delegate :note, :details_file, to: :helpdesk_info, allow_nil: true
-
-
attr_accessor :details_file_cache
-
-
def self.filters
-
[['Todos os Helpsesks', 'all']] + super()
-
end
-
-
def self.section_contents(section)
-
section.contents.where(type: 'Helpdesk').limit(4)
-
end
-
end
-
class HelpdeskInfo < ApplicationRecord
-
include RailsAdmin::HelpdeskInfo
-
-
belongs_to :content, inverse_of: :helpdesk_info
-
-
mount_uploader :details_file, FileUploader
-
-
validates :content, presence: true
-
-
def title
-
'editar dados do helpdesk'
-
end
-
end
-
class Home < ApplicationRecord
-
include Sluggi::Slugged
-
include Concerns::Publishable
-
has_one :home_primary_section, class_name: 'HomePrimarySection', inverse_of: :home, dependent: :destroy
-
has_many :home_secondary_sections, class_name: 'HomeSecondarySection', inverse_of: :home, dependent: :destroy
-
accepts_nested_attributes_for :home_primary_section
-
accepts_nested_attributes_for :home_secondary_sections
-
mount_base64_uploader :top_banner, ImageUploader, file_name: ->(hc) { hc.title.downcase.strip.tr(' ', '-').gsub(/[^\w-]/, '')+Time.now.nsec.to_s }
-
-
validates :title, :home_primary_section, :home_secondary_sections, presence: true
-
end
-
class HomeContent < ApplicationRecord
-
default_scope -> { order(created_at: :asc) }
-
-
belongs_to :home_section, inverse_of: :home_contents
-
belongs_to :section, optional: true
-
mount_base64_uploader :image, ImageUploader, file_name: ->(hc) { hc.title.downcase.strip.tr(' ', '-').gsub(/[^\w-]/, '')+Time.now.nsec.to_s }
-
-
validates :title, :url, :description, presence: true
-
end
-
1
class HomePrimarySection < HomeSection
-
1
belongs_to :home, inverse_of: :home_primary_section
-
1
accepts_nested_attributes_for :home_contents
-
end
-
1
class HomeSecondarySection < HomeSection
-
1
belongs_to :home, inverse_of: :home_secondary_sections
-
1
accepts_nested_attributes_for :home_contents
-
-
1
validates :section, presence: true
-
end
-
1
class HomeSection < ApplicationRecord
-
1
default_scope -> { order(created_at: :asc) }
-
1
belongs_to :home
-
1
belongs_to :section, optional: true
-
-
1
has_many :home_contents, inverse_of: :home_section, dependent: :destroy
-
-
1
accepts_nested_attributes_for :home_contents
-
end
-
class InstitucionalPerson < ApplicationRecord
-
include Concerns::Publishable
-
self.table_name = "institucional_persons"
-
-
mount_base64_uploader :photo, ImageUploader, file_name: ->(hc) { hc.name.downcase.strip.tr(' ', '-').gsub(/[^\w-]/, '')+Time.now.nsec.to_s }
-
-
belongs_to :institucional_persons_group, inverse_of: :institucional_persons
-
-
validates :name, :description, :photo, :institucional_persons_group_id, presence: true
-
-
end
-
class InstitucionalPersonsGroup < ApplicationRecord
-
-
self.table_name = "institucional_persons_groups"
-
-
has_many :institucional_persons, inverse_of: :institucional_persons_group
-
-
validates :name, presence: true
-
-
end
-
class JsonModel
-
include ActiveModel::Model
-
-
def self.all
-
load_data(json_file_path).map { |attrs| new(attrs) }
-
end
-
-
def self.load_data(relative_path)
-
JSON.parse File.read("app/assets/data/#{relative_path}")
-
end
-
-
def self.json_file_path
-
raise NotImplementedError
-
end
-
end
-
class MainMenuOption < JsonModel
-
attr_accessor :session, :slug, :active, :subsessions
-
-
def self.json_file_path
-
'main_menu.json'
-
end
-
end
-
class News < Content
-
include RailsAdmin::News
-
-
accepts_nested_attributes_for :news_info, allow_destroy: true
-
delegate :author, :published_at, to: :news_info, allow_nil: true
-
-
validates :news_info, presence: true
-
-
def self.filters
-
[['Todos as Notícias', 'all']] + super() + [
-
%w[Clipping clipping], ['Notas Abraji', 'abraji-notes'], %w[Congresso congress]
-
]
-
end
-
-
# def self.croped_image_size
-
# { 'width': 218, 'height': 218 }
-
# end
-
-
def self.published_and_filtered(admin, filter)
-
return published_by_tags(admin, filter) if published_by_tags(admin, filter).exists?
-
super(admin, filter)
-
end
-
-
def self.published_by_tags(admin, filter)
-
return where(id: nil) if filter.blank?
-
joins(:news_info).where("news_infos.tags @> '{#{filter}}'").published(admin)
-
end
-
-
def self.section_contents(section)
-
section.contents.where(type: 'News').limit(4)
-
end
-
end
-
class NewsInfo < ApplicationRecord
-
include RailsAdmin::NewsInfo
-
-
belongs_to :content, inverse_of: :news_info
-
-
TAGS_ENUM = {
-
'Clipping' => 'clipping',
-
'Congresso' => 'congress',
-
'Notas da Abraji' => 'abraji-notes'
-
}.freeze
-
-
def tags_enum
-
TAGS_ENUM
-
end
-
-
validates :content, presence: true
-
validates :author, presence: true
-
validates :published_at, presence: true
-
-
def title
-
'editar dados da notícia'
-
end
-
end
-
class OnlineCourse < Content
-
include RailsAdmin::OnlineCourse
-
-
accepts_nested_attributes_for :online_course_info, allow_destroy: true
-
delegate :registration_phase, :duration, :start_date, :number_of_students,
-
:non_associate_price, :associate_price, :registration_url, :price,
-
to: :online_course_info, allow_nil: true
-
-
validates :online_course_info, presence: true
-
-
def self.section_contents(section)
-
@onlinecourse = section.contents.joins(:online_course_info)
-
.where(%q("online_course_infos"."registration_phase" = 'pre-register'))
-
.limit(3)
-
return @onlinecourse if @onlinecourse.count == 3
-
@onlinecourse += section.contents.joins(:online_course_info)
-
.where(%q("online_course_infos"."registration_phase" = 'open'))
-
.limit(3 - @onlinecourse.count)
-
end
-
end
-
class OnlineCourseInfo < ApplicationRecord
-
include RailsAdmin::OnlineCourseInfo
-
-
belongs_to :content, inverse_of: :online_course_info
-
-
REGISTRATION_PHASE_ENUM = {
-
'Pré-Inscrição' => 'pre-register',
-
'Inscrições Abertas' => 'open',
-
'Encerrado' => 'closed'
-
}.freeze
-
-
def registration_phase_enum
-
REGISTRATION_PHASE_ENUM
-
end
-
-
def title
-
'editar dados do curso'
-
end
-
-
validates :registration_phase, presence: true
-
monetize :associate_price_cents, currency: :brl, numericality: { greater_than_or_equal_to: 0 }, disable_validation: true
-
monetize :non_associate_price_cents, currency: :brl, numericality: { greater_than_or_equal_to: 0 }
-
-
def price(user)
-
user.associate.present? ? associate_price : non_associate_price
-
end
-
end
-
class Payment < ApplicationRecord
-
include AASM
-
-
PAYMENT_STATES = %w[nil awaiting_payment in_analyze paid manual_paid avaliable in_dispute returned canceled].freeze
-
PAYMENT_TYPE = %w[Associate Course CruzaGrafosUser].freeze
-
belongs_to :user
-
belongs_to :payable, polymorphic: true, optional: true
-
has_many :transactions, dependent: :destroy
-
-
validates :status, inclusion: { in: PAYMENT_STATES }
-
validates :payable_type, inclusion: { in: PAYMENT_TYPE }
-
validates :payable_id, presence: true
-
-
monetize :price_cents, currency: :brl, numericality: { greater_than_or_equal_to: 0 }
-
-
def self.filters
-
PAYMENT_TYPE + %w[all]
-
end
-
-
def self.filtered(user, filter)
-
if filter == 'all'
-
return Payment.where(user: user)
-
else
-
return Payment.where(user: user, payable_type: filter)
-
end
-
end
-
-
aasm column: 'status' do
-
state :nil, initial: true
-
state :awaiting_payment, after_enter: :awaiting_payment_actions
-
state :in_analyze, after_enter: :in_analyze_actions
-
state :paid, after_enter: :paid_actions
-
state :manual_paid
-
state :available, after_enter: :available_actions
-
state :in_dispute, after_enter: :in_dispute_actions
-
state :returned, after_enter: :returned_actions
-
state :canceled, after_enter: :canceled_actions
-
-
event :start do
-
transitions from: :nil, to: :awaiting_payment
-
end
-
-
event :pay do
-
transitions from: %i[nil in_analyze awaiting_payment in_dispute canceled], to: :paid
-
end
-
-
event :manual_pay do
-
transitions from: %i[nil in_analyze awaiting_payment in_dispute canceled manual_paid], to: :manual_paid, guard: :manual_paid_actions?
-
end
-
-
event :analyze do
-
transitions from: [:awaiting_payment], to: :in_analyze
-
end
-
-
event :cancel do
-
transitions from: %i[in_analyze awaiting_payment], to: :canceled
-
end
-
-
event :dispute do
-
transitions from: %i[paid available], to: :in_dispute
-
end
-
-
event :return do
-
transitions from: %i[paid available in_dispute], to: :returned
-
end
-
-
event :finish do
-
transitions from: %i[awaiting_payment paid in_dispute], to: :available
-
end
-
end
-
-
def awaiting_payment_actions; end
-
def in_analyze_actions; end
-
def paid_actions
-
self.pay_date = Time.now
-
self.origin = 'pagseguro'
-
self.save()
-
-
if self.payable_type == "Associate"
-
associate_payment
-
elsif self.payable_type == "CruzaGrafosUser"
-
grafos_payment
-
end
-
-
end
-
-
def associate_payment
-
user.associate.approval_payment_date = Time.now
-
#se ele pagou antes de expirar soma um ano ao dia de expiração
-
if user.associate.running?
-
user.associate.valid_until = user.associate.valid_until + 1.years
-
else # se não, vai valer por 1 anos a partir de agora
-
user.associate.valid_until = Date.today + 1.years
-
end
-
user.associate.save()
-
if user.associate.may_paid?
-
user.associate.paid!
-
else
-
Rails.logger.error 'Problema pagar associado:' + user.associate.errors.messages.to_s
-
end
-
begin
-
UserMailer.paid(user).deliver
-
UserMailer.paidUser(user).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
end
-
-
def grafos_payment
-
user.cruza_grafos_user.approval_payment_date = Time.now
-
#se ele pagou antes de expirar soma um ano ao dia de expiração
-
if user.cruza_grafos_user.running?
-
user.cruza_grafos_user.valid_until = user.associate.valid_until + 30.days
-
else # se não, vai valer por 30 dias a partir de agora
-
user.cruza_grafos_user.valid_until = Date.today + 30.days
-
end
-
user.cruza_grafos_user.save()
-
if user.cruza_grafos_user.may_payment_confirm?
-
user.cruza_grafos_user.payment_confirm!
-
else
-
Rails.logger.error 'Problema pagar CG_user:' + user.cruza_grafos_user.errors.messages.to_s
-
end
-
begin
-
CruzaGrafosMailer.paid(user).deliver
-
CruzaGrafosMailer.paidUser(user).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
end
-
-
def manual_paid_actions?
-
self.pay_date = Date.today
-
self.origin = 'manual-payment'
-
-
if self.payable_type == "CruzaGrafosUser"
-
if user.cruza_grafos_user.running?
-
user.cruza_grafos_user.valid_until = user.cruza_grafos_user.valid_until + user.cruza_grafos_user.cruza_grafos_type.days
-
else # se não, vai valer por x dias a partir de agora
-
user.cruza_grafos_user.valid_until = Date.today + user.cruza_grafos_user.cruza_grafos_type.days
-
end
-
self.name = 'Cruza Grafos - ' + self.payable.cruza_grafos_type.description
-
self.price_cents = self.payable.cruza_grafos_type.price_cents
-
self.price_currency = self.payable.cruza_grafos_type.price_currency
-
user.cruza_grafos_user.approval_payment_date = Time.now
-
user.cruza_grafos_user.manual_paid
-
user.cruza_grafos_user.save()
-
end
-
self.save()
-
if self.payable_type == "Associate"
-
if user.associate.running?
-
user.associate.valid_until = user.associate.valid_until + 1.years
-
else # se não, vai valer por 1 anos a partir de agora
-
user.associate.valid_until = Date.today + 1.years
-
end
-
user.associate.approval_payment_date = Time.now
-
user.associate.save()
-
if(user.associate.valid?)
-
user.associate.manual_paid!
-
else
-
return false
-
end
-
#criar uma transaction com o manual pay
-
transaction = Transaction.new
-
transaction.paymentMethodCode = '6798312'
-
transaction.payment_id = self.id
-
transaction.save
-
-
end
-
-
-
-
end
-
def available_actions; end
-
def in_dispute_actions; end
-
def returned_actions; end
-
def canceled_actions; end
-
-
def generate_pagseguro_payment(user_payment, current_user)
-
-
end
-
-
# payment.cents = price(user).cents
-
# payment.currency = price(user).currency
-
# Payment.create(user: u, payable: o, price: 150)
-
end
-
class Person < JsonModel
-
attr_accessor :role, :name, :text, :picture_url, :active
-
end
-
class Project < Content
-
include RailsAdmin::Project
-
-
accepts_nested_attributes_for :project_info, allow_destroy: true
-
delegate :link, :published_at, to: :project_info, allow_nil: true
-
-
def self.filters
-
[['Todos os Projetos', 'all']] + super()
-
end
-
-
def self.section_contents(section)
-
section.contents.where(type: 'Project').limit(4)
-
end
-
end
-
class ProjectInfo < ApplicationRecord
-
include RailsAdmin::ProjectInfo
-
-
belongs_to :content, inverse_of: :project_info
-
-
validates :content, presence: true
-
-
def title
-
'editar dados do projeto'
-
end
-
end
-
class Publication < Content
-
include RailsAdmin::Publication
-
-
accepts_nested_attributes_for :publication_info, allow_destroy: true
-
delegate :author, :subject, :pages, :publisher, :link, :details_file,
-
to: :publication_info, allow_nil: true
-
-
validates :publication_info, presence: true
-
-
attr_accessor :details_file_cache
-
-
def self.filters
-
[['Todos as Publicações', 'all']] + super()
-
end
-
-
def self.croped_image_size
-
{ 'width': 396, 'height': 489 }
-
end
-
-
def self.section_contents(section)
-
section.contents.where(type: 'Publication').limit(2)
-
end
-
end
-
class PublicationInfo < ApplicationRecord
-
include RailsAdmin::PublicationInfo
-
-
mount_uploader :details_file, FileUploader
-
-
belongs_to :content, inverse_of: :publication_info
-
-
validates :content, presence: true
-
validates :author, presence: true
-
validates :subject, presence: true
-
validates :pages, presence: true, numericality: true
-
-
def title
-
'editar dados da publicação'
-
end
-
end
-
class RecentDocumentation < FileRecord
-
def self.json_file_path
-
'institutional/transparence/documentacao_mais_recente.json'
-
end
-
end
-
class Regulation < FileRecord
-
def self.json_file_path
-
'institutional/fund/regulamento.json'
-
end
-
end
-
1
class Section < ApplicationRecord
-
1
include RailsAdmin::Section
-
1
include Sluggi::Slugged
-
1
include Concerns::PublishableSections
-
-
1
mount_uploader :banner, ImageUploader
-
-
1
has_and_belongs_to_many :contents, inverse_of: :sections
-
-
1
validates :name, presence: true, uniqueness: { case_sensitive: false }
-
end
-
class SecundaryMenuOption < JsonModel
-
attr_accessor :session, :slug, :active
-
-
def self.json_file_path
-
'secundary_menu.json'
-
end
-
end
-
class State < JsonModel
-
attr_accessor :nome, :sigla
-
-
def self.json_file_path
-
'states.json'
-
end
-
end
-
class StaticContent < ApplicationRecord
-
include Sluggi::Slugged
-
-
validates :title, presence: true, uniqueness: { case_sensitive: false }
-
validates :slug, presence: true, uniqueness: { case_sensitive: false}
-
-
def slug_value
-
title
-
end
-
-
def slug_value_changed?
-
title_changed?
-
end
-
-
end
-
class Supervisor < Person
-
def self.json_file_path
-
'/institutional/conselho_fiscal.json'
-
end
-
end
-
class Team < Person
-
def self.json_file_path
-
'institutional/equipe.json'
-
end
-
end
-
class Transaction < ApplicationRecord
-
-
belongs_to :payment, optional: true
-
-
end
-
1
require 'cpf_cnpj'
-
1
class User < ApplicationRecord
-
1
default_scope -> { order(created_at: :desc) }
-
# Include default admins modules. Others available are:
-
# :confirmable, :lockable, :timeoutable and :omniauthable
-
1
devise :database_authenticatable, :registerable,
-
:recoverable, :rememberable, :trackable, :validatable
-
-
1
has_one :associate, dependent: :destroy
-
1
has_one :cruza_grafos_user, dependent: :destroy
-
1
has_many :payments, dependent: :destroy
-
-
1
after_create :send_welcome_email
-
-
1
include PgSearch
-
-
1
FILTER_DATE_SCOPES = %i[created_at birthday].freeze
-
1
FILTER_TEXT_SCOPES = %i[name city state email].freeze
-
1
include Concerns::Filterable
-
-
1
attr_writer :login
-
-
1
validates_uniqueness_of :email
-
-
# each letter represents a weight while searching
-
1
pg_search_scope :any_word_search, against: {
-
name: 'A', email: 'B'
-
}, using: { tsearch: { prefix: true, any_word: true } }
-
1
pg_search_scope :exact_search, against: {
-
name: 'A', email: 'B'
-
}, using: { tsearch: { prefix: true, any_word: false } }
-
-
1
def login
-
@login || email
-
end
-
-
1
def self.find_for_database_authentication(warden_conditions)
-
conditions = warden_conditions.dup
-
return find_by(conditions.to_h) if conditions.key?(:email)
-
login = conditions.delete(:login)
-
return unless login
-
where(conditions.to_h).find_by(['lower(email) = :value', { value: login.downcase }])
-
end
-
-
1
private
-
1
def password_required?
-
new_record? || password.present?
-
end
-
-
1
def self.fulltext_search(text)
-
return all if text.blank?
-
['"', "'"].any? { |quotation| text.include?(quotation) } ? exact_search(text) : any_word_search(text)
-
end
-
-
1
def send_welcome_email
-
begin
-
UserMailer.welcome(self).deliver
-
rescue => e
-
puts 'Problema ao enviar email. Possivel problema de SMTP - error message: '+ e.message
-
end
-
end
-
end
-
class JsonWebToken
-
class << self
-
def encode(payload, exp = 24.hours.from_now)
-
payload[:exp] = exp.to_i
-
JWT.encode(payload, Rails.application.secrets.secret_key_base)
-
end
-
-
def decode(token)
-
body = JWT.decode(token, Rails.application.secrets.secret_key_base)[0]
-
HashWithIndifferentAccess.new body
-
rescue
-
nil
-
end
-
end
-
end
-
1
module RailsAdmin
-
1
module Config
-
1
module Actions
-
1
class Publish < RailsAdmin::Config::Actions::Base
-
1
RailsAdmin::Config::Actions.register(self)
-
-
1
register_instance_option :member do
-
1
true
-
end
-
-
1
register_instance_option :visible? do
-
bindings[:object].respond_to?(:published) &&
-
authorized &&
-
!bindings[:object].published
-
end
-
-
1
register_instance_option :controller do
-
proc do
-
@object.publish
-
redirect_to back_or_index
-
end
-
end
-
-
1
register_instance_option :link_icon do
-
'icon-eye-open'
-
end
-
-
1
register_instance_option :pjax? do
-
false
-
end
-
end
-
end
-
end
-
end
-
1
module RailsAdmin
-
1
module Config
-
1
module Actions
-
1
class Unpublish < RailsAdmin::Config::Actions::Base
-
1
RailsAdmin::Config::Actions.register(self)
-
-
1
register_instance_option :member do
-
1
true
-
end
-
-
1
register_instance_option :visible? do
-
bindings[:object].respond_to?(:published) &&
-
authorized &&
-
bindings[:object].published
-
end
-
-
1
register_instance_option :controller do
-
proc do
-
@object.unpublish
-
redirect_to back_or_index
-
end
-
end
-
-
1
register_instance_option :link_icon do
-
'icon-eye-close'
-
end
-
-
1
register_instance_option :pjax? do
-
false
-
end
-
end
-
end
-
end
-
end
-
1
module ButtonComponents
-
1
def cancel_button(*args)
-
options = args.extract_options!
-
options[:class] = [options[:class], 'btn-primary'].compact
-
args << options
-
cancel = options.delete(:cancel)
-
template.link_to(I18n.t('simple_form.buttons.cancel'), cancel, class: 'btn submit_buttons', id: 'cancel') if cancel
-
end
-
end
-
1
SimpleForm::FormBuilder.send :include, ButtonComponents