Extract company register

Closes #1079, #916, #1077
This commit is contained in:
Artur Beljajev 2019-02-09 16:35:01 +02:00
parent 8c4e6f1656
commit 83f8a9fb6a
44 changed files with 530 additions and 610 deletions

View file

@ -98,6 +98,8 @@ gem 'jquery-ui-rails', '5.0.5'
gem 'active_model-errors_details' # Backport from Rails 5, https://github.com/rails/rails/pull/18322 gem 'active_model-errors_details' # Backport from Rails 5, https://github.com/rails/rails/pull/18322
gem 'airbrake' gem 'airbrake'
gem 'company_register', github: 'internetee/company_register', branch: :master
group :development do group :development do
# deploy # deploy
gem 'mina', '0.3.1' # for fast deployment gem 'mina', '0.3.1' # for fast deployment

View file

@ -8,6 +8,15 @@ GIT
activesupport (>= 3.0, < 6.0) activesupport (>= 3.0, < 6.0)
request_store (~> 1.1.0) request_store (~> 1.1.0)
GIT
remote: https://github.com/internetee/company_register.git
revision: da7130542304fc543c90d54cd037d019a777c526
branch: master
specs:
company_register (0.1.0)
activesupport
savon
GIT GIT
remote: https://github.com/internetee/data-migrate.git remote: https://github.com/internetee/data-migrate.git
revision: 35d22b09ff37a4e9d61ab326ad5d8eb0edf1fc81 revision: 35d22b09ff37a4e9d61ab326ad5d8eb0edf1fc81
@ -456,6 +465,7 @@ DEPENDENCIES
capybara capybara
coderay (= 1.1.0) coderay (= 1.1.0)
coffee-rails (= 4.1.0) coffee-rails (= 4.1.0)
company_register!
countries countries
daemons-rails (= 1.2.1) daemons-rails (= 1.2.1)
data_migrate! data_migrate!

View file

@ -30,15 +30,6 @@ module Api
header.gsub(pattern, '') if header&.match(pattern) header.gsub(pattern, '') if header&.match(pattern)
end end
def associated_domains(user)
country_code, ident = user.registrant_ident.split('-')
BusinessRegistryCache.fetch_associated_domains(ident, country_code)
rescue Soap::Arireg::NotAvailableError => error
Rails.logger.fatal("[EXCEPTION] #{error}")
user.domains
end
def authenticate def authenticate
decryptor = AuthTokenDecryptor.create_with_defaults(bearer_token) decryptor = AuthTokenDecryptor.create_with_defaults(bearer_token)
decryptor.decrypt_token decryptor.decrypt_token

View file

@ -4,8 +4,6 @@ module Api
module V1 module V1
module Registrant module Registrant
class ContactsController < ::Api::V1::Registrant::BaseController class ContactsController < ::Api::V1::Registrant::BaseController
before_action :set_contacts_pool
def index def index
limit = params[:limit] || 200 limit = params[:limit] || 200
offset = params[:offset] || 0 offset = params[:offset] || 0
@ -20,8 +18,8 @@ module Api
status: :bad_request) && return status: :bad_request) && return
end end
@contacts = @contacts_pool.limit(limit).offset(offset) contacts = current_user_contacts.limit(limit).offset(offset)
serialized_contacts = @contacts.map do |item| serialized_contacts = contacts.map do |item|
serializer = Serializers::RegistrantApi::Contact.new(item) serializer = Serializers::RegistrantApi::Contact.new(item)
serializer.to_json serializer.to_json
end end
@ -30,7 +28,7 @@ module Api
end end
def show def show
@contact = @contacts_pool.find_by(uuid: params[:uuid]) @contact = current_user_contacts.find_by(uuid: params[:uuid])
if @contact if @contact
render json: @contact render json: @contact
@ -40,7 +38,7 @@ module Api
end end
def update def update
contact = @contacts_pool.find_by!(uuid: params[:uuid]) contact = current_user_contacts.find_by!(uuid: params[:uuid])
contact.name = params[:name] if params[:name].present? contact.name = params[:name] if params[:name].present?
contact.email = params[:email] if params[:email].present? contact.email = params[:email] if params[:email].present?
contact.phone = params[:phone] if params[:phone].present? contact.phone = params[:phone] if params[:phone].present?
@ -97,22 +95,10 @@ module Api
private private
def set_contacts_pool def current_user_contacts
country_code, ident = current_registrant_user.registrant_ident.to_s.split '-' current_registrant_user.contacts
associated_domain_ids = begin rescue CompanyRegister::NotAvailableError
BusinessRegistryCache.fetch_by_ident_and_cc(ident, country_code).associated_domain_ids current_registrant_user.direct_contacts
end
available_contacts_ids = begin
DomainContact.where(domain_id: associated_domain_ids).pluck(:contact_id) |
Domain.where(id: associated_domain_ids).pluck(:registrant_id)
end
@contacts_pool = Contact.where(id: available_contacts_ids)
rescue Soap::Arireg::NotAvailableError => error
Rails.logger.fatal("[EXCEPTION] #{error}")
render json: { errors: [{ base: ['Business Registry not available'] }] },
status: :service_unavailable and return
end end
end end
end end

View file

@ -18,7 +18,7 @@ module Api
status: :bad_request) && return status: :bad_request) && return
end end
@domains = associated_domains(current_registrant_user).limit(limit).offset(offset) @domains = current_user_domains.limit(limit).offset(offset)
serialized_domains = @domains.map do |item| serialized_domains = @domains.map do |item|
serializer = Serializers::RegistrantApi::Domain.new(item) serializer = Serializers::RegistrantApi::Domain.new(item)
@ -29,8 +29,7 @@ module Api
end end
def show def show
domain_pool = associated_domains(current_registrant_user) @domain = current_user_domains.find_by(uuid: params[:uuid])
@domain = domain_pool.find_by(uuid: params[:uuid])
if @domain if @domain
serializer = Serializers::RegistrantApi::Domain.new(@domain) serializer = Serializers::RegistrantApi::Domain.new(@domain)
@ -39,6 +38,14 @@ module Api
render json: { errors: [{ base: ['Domain not found'] }] }, status: :not_found render json: { errors: [{ base: ['Domain not found'] }] }, status: :not_found
end end
end end
private
def current_user_domains
current_registrant_user.domains
rescue CompanyRegister::NotAvailableError
current_registrant_user.direct_domains
end
end end
end end
end end

View file

@ -1,21 +1,19 @@
class Registrant::ContactsController < RegistrantController class Registrant::ContactsController < RegistrantController
helper_method :domain_ids
helper_method :domain helper_method :domain
helper_method :fax_enabled? helper_method :fax_enabled?
skip_authorization_check only: %i[edit update] skip_authorization_check only: %i[edit update]
def show def show
@contact = Contact.where(id: contacts).find_by(id: params[:id]) @contact = current_user_contacts.find(params[:id])
authorize! :read, @contact authorize! :read, @contact
end end
def edit def edit
@contact = Contact.where(id: contacts).find(params[:id]) @contact = current_user_contacts.find(params[:id])
end end
def update def update
@contact = Contact.where(id: contacts).find(params[:id]) @contact = current_user_contacts.find(params[:id])
@contact.attributes = contact_params @contact.attributes = contact_params
response = update_contact_via_api(@contact.uuid) response = update_contact_via_api(@contact.uuid)
updated = response.is_a?(Net::HTTPSuccess) updated = response.is_a?(Net::HTTPSuccess)
@ -31,38 +29,10 @@ class Registrant::ContactsController < RegistrantController
private private
def contacts
begin
DomainContact.where(domain_id: domain_ids).pluck(:contact_id) | Domain.where(id: domain_ids).pluck(:registrant_id)
rescue Soap::Arireg::NotAvailableError => error
flash[:notice] = I18n.t(error.json[:message])
Rails.logger.fatal("[EXCEPTION] #{error.to_s}")
[]
end
end
def domain_ids
@domain_ids ||= begin
ident_cc, ident = current_registrant_user.registrant_ident.to_s.split '-'
BusinessRegistryCache.fetch_by_ident_and_cc(ident, ident_cc).associated_domain_ids
end
end
def domain def domain
current_user_domains.find(params[:domain_id]) current_user_domains.find(params[:domain_id])
end end
def current_user_domains
ident_cc, ident = current_registrant_user.registrant_ident.split '-'
begin
BusinessRegistryCache.fetch_associated_domains ident, ident_cc
rescue Soap::Arireg::NotAvailableError => error
flash[:notice] = I18n.t(error.json[:message])
Rails.logger.fatal("[EXCEPTION] #{error.to_s}")
current_registrant_user.domains
end
end
def contact_params def contact_params
permitted = %i[ permitted = %i[
name name

View file

@ -1,22 +1,24 @@
class Registrant::DomainsController < RegistrantController class Registrant::DomainsController < RegistrantController
def index def index
authorize! :view, :registrant_domains authorize! :view, :registrant_domains
params[:q] ||= {} params[:q] ||= {}
normalize_search_parameters do normalize_search_parameters do
@q = domains.search(params[:q]) @q = current_user_domains.search(params[:q])
@domains = @q.result.page(params[:page]) @domains = @q.result.page(params[:page])
end end
@domains = @domains.per(params[:results_per_page]) if params[:results_per_page].to_i.positive? @domains = @domains.per(params[:results_per_page]) if params[:results_per_page].to_i.positive?
end end
def show def show
@domain = domains.find(params[:id]) @domain = current_user_domains.find(params[:id])
authorize! :read, @domain authorize! :read, @domain
end end
def domain_verification_url def domain_verification_url
authorize! :view, :registrant_domains authorize! :view, :registrant_domains
dom = domains.find(params[:id]) dom = current_user_domains.find(params[:id])
if (dom.statuses.include?(DomainStatus::PENDING_UPDATE) || dom.statuses.include?(DomainStatus::PENDING_DELETE_CONFIRMATION)) && if (dom.statuses.include?(DomainStatus::PENDING_UPDATE) || dom.statuses.include?(DomainStatus::PENDING_DELETE_CONFIRMATION)) &&
dom.pending_json.present? dom.pending_json.present?
@ -34,7 +36,7 @@ class Registrant::DomainsController < RegistrantController
authorize! :view, :registrant_domains authorize! :view, :registrant_domains
params[:q] ||= {} params[:q] ||= {}
normalize_search_parameters do normalize_search_parameters do
@q = domains.search(params[:q]) @q = current_user_domains.search(params[:q])
@domains = @q @domains = @q
end end
@ -49,21 +51,6 @@ class Registrant::DomainsController < RegistrantController
private private
def set_domain
@domain = domains.find(params[:id])
end
def domains
ident_cc, ident = current_registrant_user.registrant_ident.split '-'
begin
BusinessRegistryCache.fetch_associated_domains ident, ident_cc
rescue Soap::Arireg::NotAvailableError => error
flash[:notice] = I18n.t(error.json[:message])
Rails.logger.fatal("[EXCEPTION] #{error.to_s}")
current_registrant_user.domains
end
end
def normalize_search_parameters def normalize_search_parameters
ca_cache = params[:q][:valid_to_lteq] ca_cache = params[:q][:valid_to_lteq]
begin begin

View file

@ -19,4 +19,18 @@ class RegistrantController < ApplicationController
def user_for_paper_trail def user_for_paper_trail
current_registrant_user.present? ? current_registrant_user.id_role_username : 'anonymous' current_registrant_user.present? ? current_registrant_user.id_role_username : 'anonymous'
end end
def current_user_contacts
current_registrant_user.contacts
rescue CompanyRegister::NotAvailableError
flash.now[:notice] = t('registrant.company_register_unavailable')
current_registrant_user.direct_contacts
end
def current_user_domains
current_registrant_user.domains
rescue CompanyRegister::NotAvailableError
flash.now[:notice] = t('registrant.company_register_unavailable')
current_registrant_user.direct_domains
end
end end

View file

@ -1,66 +0,0 @@
=begin
The portal for registrants has to offer an overview of the domains the user is related to directly or through an organisation.
Personal relation is defined by matching the personal identification code associated with a domain and the one acquired on
authentication using electronic ID. Association through a business organisation requires a query to business registry.
* when user logs in the personal identification code is sent to business registry (using XML service)
* business registry returns the list of business registry codes the user is a board member of
* the list is cached for two days (configurable)
* during that time no new queries are made to business registry for that personal identification code
and the cached organisation code listing is used
* user sees the listing of domains that are associated with him/her directly or through registered organisation
* UI of the portal displays the list of organisation codes and names used to fetch additional domains for the user
(currently by clicking on a username in top right corner of the screen).
Also time and date of the query to the business registry is displayed with the list of organisations.
* if the query to the business registry fails for any reason the list of
domains associated directly with the user is still displayed with an error message indicating a problem
with receiving current list business entities. Outdated list of organisations cannot be used.
=end
class BusinessRegistryCache < ActiveRecord::Base
def associated_domain_ids
contact_ids = Contact.where(ident_type: 'org', ident: associated_businesses, ident_country_code: ident_country_code).pluck(:id)
contact_ids += Contact.where(ident_type: 'priv', ident: ident, ident_country_code: ident_country_code).pluck(:id)
domain_ids = []
unless contact_ids.blank?
domain_ids = DomainContact.distinct.where(contact_id: contact_ids).pluck(:domain_id)
end
domain_ids += Domain.where(registrant_id: contact_ids).pluck(:id)
domain_ids
end
def associated_domains
Domain.includes(:registrar, :registrant).where(id: associated_domain_ids)
end
class << self
def fetch_associated_domains(ident_code, ident_cc)
fetch_by_ident_and_cc(ident_code, ident_cc).associated_domains
end
def fetch_by_ident_and_cc(ident_code, ident_cc)
cache = BusinessRegistryCache.where(ident: ident_code, ident_country_code: ident_cc).first_or_initialize
msg_start = "[Ariregister] #{ident_cc}-#{ident_code}:"
# fetch new data if cache is expired
if cache.retrieved_on && cache.retrieved_on > (Time.zone.now - Setting.days_to_keep_business_registry_cache.days)
Rails.logger.info("#{msg_start} Info loaded from cache")
return cache
end
cache.attributes = business_registry.associated_businesses(ident_code, ident_cc)
Rails.logger.info("#{msg_start} Info loaded from server")
cache.save
cache
end
def business_registry
Soap::Arireg.new
end
end
end

View file

@ -263,6 +263,28 @@ class Contact < ActiveRecord::Base
state state
) )
end end
def registrant_user_contacts(registrant_user)
# In Rails 5, can be replaced with a much simpler `or` query method and the raw SQL parts can
# be removed.
from("(#{registrant_user_direct_contacts(registrant_user).to_sql} UNION " \
"#{registrant_user_indirect_contacts(registrant_user).to_sql}) AS contacts")
end
def registrant_user_direct_contacts(registrant_user)
where(ident_type: PRIV, ident: registrant_user.ident, ident_country_code: registrant_user
.country.alpha2)
end
private
def registrant_user_indirect_contacts(registrant_user)
ident = registrant_user.companies.collect(&:registration_number)
where(ident_type: ORG,
ident: ident,
ident_country_code: registrant_user.country.alpha2)
end
end end
def roid def roid
@ -431,7 +453,6 @@ class Contact < ActiveRecord::Base
# fetch domains # fetch domains
domains = Domain.where("domains.id IN (#{filter_sql})") domains = Domain.where("domains.id IN (#{filter_sql})")
domains = domains.where("domains.id" => params[:leave_domains]) if params[:leave_domains]
domains = domains.includes(:registrar).page(page).per(per) domains = domains.includes(:registrar).page(page).per(per)
if sorts.first == "registrar_name".freeze if sorts.first == "registrar_name".freeze

View file

@ -205,6 +205,56 @@ class Domain < ActiveRecord::Base
def nameserver_required? def nameserver_required?
Setting.nameserver_required Setting.nameserver_required
end end
def registrant_user_domains(registrant_user)
# In Rails 5, can be replaced with a much simpler `or` query method and the raw SQL parts can
# be removed.
from(
"(#{registrant_user_domains_by_registrant(registrant_user).to_sql} UNION " \
"#{registrant_user_domains_by_contact(registrant_user).to_sql}) AS domains"
)
end
def registrant_user_direct_domains(registrant_user)
# In Rails 5, can be replaced with a much simpler `or` query method and the raw SQL parts can
# be removed.
from(
"(#{registrant_user_direct_domains_by_registrant(registrant_user).to_sql} UNION " \
"#{registrant_user_direct_domains_by_contact(registrant_user).to_sql}) AS domains"
)
end
def registrant_user_administered_domains(registrant_user)
# In Rails 5, can be replaced with a much simpler `or` query method and the raw SQL parts can
# be removed.
from(
"(#{registrant_user_domains_by_registrant(registrant_user).to_sql} UNION " \
"#{registrant_user_domains_by_admin_contact(registrant_user).to_sql}) AS domains"
)
end
private
def registrant_user_domains_by_registrant(registrant_user)
where(registrant: registrant_user.contacts)
end
def registrant_user_domains_by_contact(registrant_user)
joins(:domain_contacts).where(domain_contacts: { contact_id: registrant_user.contacts })
end
def registrant_user_domains_by_admin_contact(registrant_user)
joins(:domain_contacts).where(domain_contacts: { contact_id: registrant_user.contacts,
type: [AdminDomainContact] })
end
def registrant_user_direct_domains_by_registrant(registrant_user)
where(registrant: registrant_user.direct_contacts)
end
def registrant_user_direct_domains_by_contact(registrant_user)
joins(:domain_contacts).where(domain_contacts: { contact_id: registrant_user.direct_contacts })
end
end end
def name=(value) def name=(value)

View file

@ -13,43 +13,34 @@ class RegistrantUser < User
registrant_ident.to_s.split('-').last registrant_ident.to_s.split('-').last
end end
def country_code def country
registrant_ident.to_s.split('-').first alpha2_code = registrant_ident.to_s.split('-').first
Country.new(alpha2_code)
end end
# In Rails 5, can be replaced with a much simpler `or` query method and the raw SQL parts can be def companies(company_register = CompanyRegister::Client.new)
# removed. company_register.representation_rights(citizen_personal_code: ident,
# https://guides.rubyonrails.org/active_record_querying.html#or-conditions citizen_country_code: country.alpha3)
def domains
domains_where_is_contact = begin
Domain.joins(:domain_contacts)
.where(domain_contacts: { contact_id: contacts })
end
domains_where_is_registrant = Domain.where(registrant_id: contacts)
Domain.from(
"(#{domains_where_is_registrant.to_sql} UNION " \
"#{domains_where_is_contact.to_sql}) AS domains"
)
end end
def contacts def contacts
Contact.where(ident_type: 'priv', ident: ident, ident_country_code: country_code) Contact.registrant_user_contacts(self)
end
def direct_contacts
Contact.registrant_user_direct_contacts(self)
end
def domains
Domain.registrant_user_domains(self)
end
def direct_domains
Domain.registrant_user_direct_domains(self)
end end
def administered_domains def administered_domains
domains_where_is_administrative_contact = begin Domain.registrant_user_administered_domains(self)
Domain.joins(:domain_contacts)
.where(domain_contacts: { contact_id: contacts, type: [AdminDomainContact] })
end
domains_where_is_registrant = Domain.where(registrant_id: contacts)
Domain.from(
"(#{domains_where_is_registrant.to_sql} UNION " \
"#{domains_where_is_administrative_contact.to_sql}) AS domains"
)
end end
def to_s def to_s

View file

@ -36,7 +36,6 @@ class Setting < RailsSettings::CachedSettings
transfer_wait_time transfer_wait_time
invoice_number_min invoice_number_min
invoice_number_max invoice_number_max
days_to_keep_business_registry_cache
days_to_keep_invoices_active days_to_keep_invoices_active
days_to_keep_overdue_invoices_active days_to_keep_overdue_invoices_active
days_to_renew_domain_before_expire days_to_renew_domain_before_expire

View file

@ -1,209 +0,0 @@
# coding: utf-8
require 'savon'
=begin
Estonian Business registry provides information about registered companies via xml (SOAP over HTTPS).
Note:
The SSL endpoint certificate is self signed.
Documentation:
http://www.rik.ee/et/e-ariregister/xml-teenus
Specifications are in Eng and Est
User contract required
Testing:
https://demo-ariregxml.rik.ee:447/testariport/?wsdl
http://demo-ariregxml.rik.ee:81
https://demo-ariregxml.rik.ee:447
Live service:
https://ariregxml.rik.ee/ariport/?wsdl
https://ariregxml.rik.ee/
Implements Soap::Arireg # associated_businesses
8. arireg.paringesindus_v4
Rights of representation of all persons related to the company (newer)
http://www2.rik.ee/schemas/xtee/arireg/live/paringesindus_v4.xsd
expects personal id code, to fetch list of registered business id codes
returning {ident: person, ident_country_code: ... associated_businesses: [...id_codes...]}
=end
# do some SSL set up?
# ssl_version
# ssl_verify_mode
# ssl_cert_key_file
# ssl_cert_key
# ssl_cert_key_password
# ssl_cert_file
# ssl_cert
# ssl_ca_cert_file
# ssl_ca_cert
module Soap
class Arireg
class NotAvailableError < StandardError
attr_accessor :json
def initialize(params)
params[:message] = "#{I18n.t(:business_registry_service_not_available)}" unless params.key? :message
@json = params
super(params)
end
end
class << self
attr_accessor :wsdl, :host, :username, :password
end
def initialize
if self.class.username.nil?
self.class.username = ENV['arireg_username']
self.class.password = ENV['arireg_password']
end
if self.class.wsdl.nil?
self.class.wsdl = ENV['arireg_wsdl']
self.class.host = ENV['arireg_host']
end
# note Savon has error if https w/non-standard port,
# use non-standard force to pre-set endpoint
@client = Savon.client(wsdl: self.class.wsdl,
host: self.class.host,
endpoint: "#{self.class.host}/cgi-bin/consumer_proxy")
@session = nil
end
# retrieve business id codes for business that a person has a legal role
def associated_businesses(ident, ident_cc = 'EST')
begin
msg = {
'fyysilise_isiku_kood' => ident,
'fyysilise_isiku_koodi_riik' => country_code_3(ident_cc)
}
Rails.logger.info "[Ariregister] Request sent with data: #{msg.inspect}"
response = @client.call :paringesindus_v4, message: body(msg)
content = extract response, :paringesindus_v4_response
Rails.logger.info "[Ariregister] Got response with data: #{content.inspect}"
if content.present? && content[:ettevotjad].key?(:item)
business_ident = items(content, :ettevotjad).map{|item| item[:ariregistri_kood]}
else
business_ident = []
end
{
ident: ident,
ident_country_code: ident_cc,
# ident_type: 'priv',
retrieved_on: Time.now,
associated_businesses: business_ident
}
rescue Savon::SOAPFault => fault
Rails.logger.error "[Ariregister] #{fault} Äriregister arireg #{self.class.username} at #{self.class.host }"
raise NotAvailableError.new(exception: fault)
rescue HTTPI::SSLError => ssl_error
Rails.logger.error "[Ariregister] #{ssl_error} at #{self.class.host}"
raise NotAvailableError.new(exception: ssl_error)
rescue SocketError => sock
Rails.logger.error "[Ariregister] #{sock}"
raise NotAvailableError.new(exception: sock)
end
end
def debug
@client.globals.log_level :debug
@client.globals.log true
@client.globals.pretty_print_xml true
@debug = true
@client
end
private
# add required elements to request
def body(args)
if @session.nil?
args['ariregister_kasutajanimi'] = self.class.username
args['ariregister_parool'] = self.class.password
else
args['ariregister_sessioon'] = @session
end
{keha: args}
end
# TLA --- three letter acronym required not two letter acronym, transform
def country_code_3(code)
if code.length == 2
code = CC2X3[code]
raise NotAvailableError.new(message: 'Unrecognized Country') if code.nil?
end
code
end
def extract(response, element)
# response envelope body has again header/body under element; header is user and password returned
response.hash[:envelope][:body][element][:keha]
end
def items(content, parent)
items = content[parent][:item]
items.is_a?(Array) ? items : [items]
end
CC2X3 = {"AF"=>"AFG", "AX"=>"ALA", "AL"=>"ALB", "DZ"=>"DZA", "AS"=>"ASM",
"AD"=>"AND", "AO"=>"AGO", "AI"=>"AIA", "AQ"=>"ATA", "AG"=>"ATG",
"AR"=>"ARG", "AM"=>"ARM", "AW"=>"ABW", "AU"=>"AUS", "AT"=>"AUT",
"AZ"=>"AZE", "BS"=>"BHS", "BH"=>"BHR", "BD"=>"BGD", "BB"=>"BRB",
"BY"=>"BLR", "BE"=>"BEL", "BZ"=>"BLZ", "BJ"=>"BEN", "BM"=>"BMU",
"BT"=>"BTN", "BO"=>"BOL", "BQ"=>"BES", "BA"=>"BIH", "BW"=>"BWA",
"BV"=>"BVT", "BR"=>"BRA", "IO"=>"IOT", "BN"=>"BRN", "BG"=>"BGR",
"BF"=>"BFA", "BI"=>"BDI", "CV"=>"CPV", "KH"=>"KHM", "CM"=>"CMR",
"CA"=>"CAN", "KY"=>"CYM", "CF"=>"CAF", "TD"=>"TCD", "CL"=>"CHL",
"CN"=>"CHN", "CX"=>"CXR", "CC"=>"CCK", "CO"=>"COL", "KM"=>"COM",
"CD"=>"COD", "CG"=>"COG", "CK"=>"COK", "CR"=>"CRI", "CI"=>"CIV",
"HR"=>"HRV", "CU"=>"CUB", "CW"=>"CUW", "CY"=>"CYP", "CZ"=>"CZE",
"DK"=>"DNK", "DJ"=>"DJI", "DM"=>"DMA", "DO"=>"DOM", "EC"=>"ECU",
"EG"=>"EGY", "SV"=>"SLV", "GQ"=>"GNQ", "ER"=>"ERI", "EE"=>"EST",
"ET"=>"ETH", "FK"=>"FLK", "FO"=>"FRO", "FJ"=>"FJI", "FI"=>"FIN",
"FR"=>"FRA", "GF"=>"GUF", "PF"=>"PYF", "TF"=>"ATF", "GA"=>"GAB",
"GM"=>"GMB", "GE"=>"GEO", "DE"=>"DEU", "GH"=>"GHA", "GI"=>"GIB",
"GR"=>"GRC", "GL"=>"GRL", "GD"=>"GRD", "GP"=>"GLP", "GU"=>"GUM",
"GT"=>"GTM", "GG"=>"GGY", "GN"=>"GIN", "GW"=>"GNB", "GY"=>"GUY",
"HT"=>"HTI", "HM"=>"HMD", "VA"=>"VAT", "HN"=>"HND", "HK"=>"HKG",
"HU"=>"HUN", "IS"=>"ISL", "IN"=>"IND", "ID"=>"IDN", "IR"=>"IRN",
"IQ"=>"IRQ", "IE"=>"IRL", "IM"=>"IMN", "IL"=>"ISR", "IT"=>"ITA",
"JM"=>"JAM", "JP"=>"JPN", "JE"=>"JEY", "JO"=>"JOR", "KZ"=>"KAZ",
"KE"=>"KEN", "KI"=>"KIR", "KP"=>"PRK", "KR"=>"KOR", "KW"=>"KWT",
"KG"=>"KGZ", "LA"=>"LAO", "LV"=>"LVA", "LB"=>"LBN", "LS"=>"LSO",
"LR"=>"LBR", "LY"=>"LBY", "LI"=>"LIE", "LT"=>"LTU", "LU"=>"LUX",
"MO"=>"MAC", "MK"=>"MKD", "MG"=>"MDG", "MW"=>"MWI", "MY"=>"MYS",
"MV"=>"MDV", "ML"=>"MLI", "MT"=>"MLT", "MH"=>"MHL", "MQ"=>"MTQ",
"MR"=>"MRT", "MU"=>"MUS", "YT"=>"MYT", "MX"=>"MEX", "FM"=>"FSM",
"MD"=>"MDA", "MC"=>"MCO", "MN"=>"MNG", "ME"=>"MNE", "MS"=>"MSR",
"MA"=>"MAR", "MZ"=>"MOZ", "MM"=>"MMR", "NA"=>"NAM", "NR"=>"NRU",
"NP"=>"NPL", "NL"=>"NLD", "NC"=>"NCL", "NZ"=>"NZL", "NI"=>"NIC",
"NE"=>"NER", "NG"=>"NGA", "NU"=>"NIU", "NF"=>"NFK", "MP"=>"MNP",
"NO"=>"NOR", "OM"=>"OMN", "PK"=>"PAK", "PW"=>"PLW", "PS"=>"PSE",
"PA"=>"PAN", "PG"=>"PNG", "PY"=>"PRY", "PE"=>"PER", "PH"=>"PHL",
"PN"=>"PCN", "PL"=>"POL", "PT"=>"PRT", "PR"=>"PRI", "QA"=>"QAT",
"RE"=>"REU", "RO"=>"ROU", "RU"=>"RUS", "RW"=>"RWA", "BL"=>"BLM",
"SH"=>"SHN", "KN"=>"KNA", "LC"=>"LCA", "MF"=>"MAF", "PM"=>"SPM",
"VC"=>"VCT", "WS"=>"WSM", "SM"=>"SMR", "ST"=>"STP", "SA"=>"SAU",
"SN"=>"SEN", "RS"=>"SRB", "SC"=>"SYC", "SL"=>"SLE", "SG"=>"SGP",
"SX"=>"SXM", "SK"=>"SVK", "SI"=>"SVN", "SB"=>"SLB", "SO"=>"SOM",
"ZA"=>"ZAF", "GS"=>"SGS", "SS"=>"SSD", "ES"=>"ESP", "LK"=>"LKA",
"SD"=>"SDN", "SR"=>"SUR", "SJ"=>"SJM", "SZ"=>"SWZ", "SE"=>"SWE",
"CH"=>"CHE", "SY"=>"SYR", "TW"=>"TWN", "TJ"=>"TJK", "TZ"=>"TZA",
"TH"=>"THA", "TL"=>"TLS", "TG"=>"TGO", "TK"=>"TKL", "TO"=>"TON",
"TT"=>"TTO", "TN"=>"TUN", "TR"=>"TUR", "TM"=>"TKM", "TC"=>"TCA",
"TV"=>"TUV", "UG"=>"UGA", "UA"=>"UKR", "AE"=>"ARE", "GB"=>"GBR",
"UM"=>"UMI", "US"=>"USA", "UY"=>"URY", "UZ"=>"UZB", "VU"=>"VUT",
"VE"=>"VEN", "VN"=>"VNM", "VG"=>"VGB", "VI"=>"VIR", "WF"=>"WLF",
"EH"=>"ESH", "YE"=>"YEM", "ZM"=>"ZMB", "ZW"=>"ZWE"}
end
end

View file

@ -43,7 +43,6 @@
= render 'setting_row', var: :transfer_wait_time = render 'setting_row', var: :transfer_wait_time
= render 'setting_row', var: :ds_digest_type = render 'setting_row', var: :ds_digest_type
= render 'setting_row', var: :client_side_status_editing_enabled = render 'setting_row', var: :client_side_status_editing_enabled
= render 'setting_row', var: :days_to_keep_business_registry_cache
= render 'setting_row', var: :api_ip_whitelist_enabled = render 'setting_row', var: :api_ip_whitelist_enabled
= render 'setting_row', var: :registrar_ip_whitelist_enabled = render 'setting_row', var: :registrar_ip_whitelist_enabled
= render 'setting_row', var: :request_confrimation_on_registrant_change_enabled = render 'setting_row', var: :request_confrimation_on_registrant_change_enabled

View file

@ -3,7 +3,7 @@
<!-- Used by Mobile-ID login --> <!-- Used by Mobile-ID login -->
<% type = (flash[:notice]) ? 'bg-success' : 'bg-danger' %> <% type = (flash[:notice]) ? 'bg-success' : 'bg-danger' %>
<% type = 'bg-warning' if flash[:warning] %> <% type = 'bg-warning' if flash[:warning] %>
<div class="<%= type %> alert"> <div class="<%= type %> alert<%= ' alert-info' if flash[:notice].present? %>">
<%= flash[:notice] || flash[:alert] || flash[:warning] %> <%= flash[:notice] || flash[:alert] || flash[:warning] %>
</div> </div>
</div> </div>

View file

@ -1,5 +1,4 @@
<% domains = contact.all_domains(page: params[:domain_page], per: 20, params: <% domains = contact.all_domains(page: params[:domain_page], per: 20, params: params) %>
params.merge(leave_domains: domain_ids)) %>
<div class="panel panel-default"> <div class="panel panel-default">
<div class="panel-heading"> <div class="panel-heading">

View file

@ -83,12 +83,11 @@ key_path: '/home/registry/registry/shared/ca/private/webclient.key.pem'
epp_hostname: 'registry.gitlab.eu' epp_hostname: 'registry.gitlab.eu'
repp_url: 'https://repp.gitlab.eu/repp/v1/' repp_url: 'https://repp.gitlab.eu/repp/v1/'
# Estonian Business Registry # Estonian Company Register
# http://www.rik.ee/en/e-business-registry/xml-service company_register_username:
arireg_username: company_register_password:
arireg_password: company_register_cache_period_days: '2'
arireg_wsdl: 'https://demo-ariregxml.rik.ee:447/testariport/?wsdl' company_register_test_mode: 'true' # Requests in test mode are free of charge
arireg_host: 'http://demo-ariregxml.rik.ee:81/'
# Mobile-ID and ID-card login # Mobile-ID and ID-card login
# https://www.id.ee/?id=35760 General how-to # https://www.id.ee/?id=35760 General how-to

View file

@ -0,0 +1,6 @@
CompanyRegister.configure do |config|
config.username = ENV['company_register_username']
config.password = ENV['company_register_password']
config.cache_period = ENV['company_register_cache_period_days'].to_i.days
config.test_mode = ENV['company_register_test_mode'] == 'true'
end

View file

@ -12,5 +12,4 @@
ActiveSupport::Inflector.inflections(:en) do |inflect| ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym 'DNS' inflect.acronym 'DNS'
inflect.irregular 'business_registry_cache', 'business_registry_caches'
end end

View file

@ -32,8 +32,6 @@ if con.present? && con.table_exists?('settings')
Setting.save_default(:client_side_status_editing_enabled, false) Setting.save_default(:client_side_status_editing_enabled, false)
Setting.save_default(:days_to_keep_business_registry_cache, 2)
Setting.save_default(:invoice_number_min, 131050) Setting.save_default(:invoice_number_min, 131050)
Setting.save_default(:invoice_number_max, 149999) Setting.save_default(:invoice_number_max, 149999)
Setting.save_default(:directo_monthly_number_min, 309901) Setting.save_default(:directo_monthly_number_min, 309901)

View file

@ -405,7 +405,6 @@ en:
sim_error: 'SIM application error' sim_error: 'SIM application error'
internal_error: 'Internal error' internal_error: 'Internal error'
client_side_status_editing_error: 'Parameter value policy error. Client-side object status management not supported' client_side_status_editing_error: 'Parameter value policy error. Client-side object status management not supported'
business_registry_service_not_available: "Business Registry service Ärireg is not available"
# DEPP # DEPP
activemodel: activemodel:

View file

@ -0,0 +1,5 @@
en:
registrant:
company_register_unavailable: >-
Company register is unavailable.
Domains and contacts associated via organizations are not shown.

View file

@ -0,0 +1,5 @@
class DropBusinessRegistryCaches < ActiveRecord::Migration
def change
drop_table :business_registry_caches
end
end

View file

@ -598,40 +598,6 @@ CREATE SEQUENCE public.blocked_domains_id_seq
ALTER SEQUENCE public.blocked_domains_id_seq OWNED BY public.blocked_domains.id; ALTER SEQUENCE public.blocked_domains_id_seq OWNED BY public.blocked_domains.id;
--
-- Name: business_registry_caches; Type: TABLE; Schema: public; Owner: -; Tablespace:
--
CREATE TABLE public.business_registry_caches (
id integer NOT NULL,
ident character varying,
ident_country_code character varying,
retrieved_on timestamp without time zone,
associated_businesses character varying[],
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
--
-- Name: business_registry_caches_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
CREATE SEQUENCE public.business_registry_caches_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
--
-- Name: business_registry_caches_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
ALTER SEQUENCE public.business_registry_caches_id_seq OWNED BY public.business_registry_caches.id;
-- --
-- Name: certificates; Type: TABLE; Schema: public; Owner: -; Tablespace: -- Name: certificates; Type: TABLE; Schema: public; Owner: -; Tablespace:
-- --
@ -2594,13 +2560,6 @@ ALTER TABLE ONLY public.banklink_transactions ALTER COLUMN id SET DEFAULT nextva
ALTER TABLE ONLY public.blocked_domains ALTER COLUMN id SET DEFAULT nextval('public.blocked_domains_id_seq'::regclass); ALTER TABLE ONLY public.blocked_domains ALTER COLUMN id SET DEFAULT nextval('public.blocked_domains_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.business_registry_caches ALTER COLUMN id SET DEFAULT nextval('public.business_registry_caches_id_seq'::regclass);
-- --
-- Name: id; Type: DEFAULT; Schema: public; Owner: - -- Name: id; Type: DEFAULT; Schema: public; Owner: -
-- --
@ -3001,14 +2960,6 @@ ALTER TABLE ONLY public.blocked_domains
ADD CONSTRAINT blocked_domains_pkey PRIMARY KEY (id); ADD CONSTRAINT blocked_domains_pkey PRIMARY KEY (id);
--
-- Name: business_registry_caches_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--
ALTER TABLE ONLY public.business_registry_caches
ADD CONSTRAINT business_registry_caches_pkey PRIMARY KEY (id);
-- --
-- Name: certificates_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace: -- Name: certificates_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
-- --
@ -3508,13 +3459,6 @@ CREATE INDEX index_accounts_on_registrar_id ON public.accounts USING btree (regi
CREATE INDEX index_blocked_domains_on_name ON public.blocked_domains USING btree (name); CREATE INDEX index_blocked_domains_on_name ON public.blocked_domains USING btree (name);
--
-- Name: index_business_registry_caches_on_ident; Type: INDEX; Schema: public; Owner: -; Tablespace:
--
CREATE INDEX index_business_registry_caches_on_ident ON public.business_registry_caches USING btree (ident);
-- --
-- Name: index_certificates_on_api_user_id; Type: INDEX; Schema: public; Owner: -; Tablespace: -- Name: index_certificates_on_api_user_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
-- --
@ -4985,6 +4929,8 @@ INSERT INTO schema_migrations (version) VALUES ('20190102115333');
INSERT INTO schema_migrations (version) VALUES ('20190102144032'); INSERT INTO schema_migrations (version) VALUES ('20190102144032');
INSERT INTO schema_migrations (version) VALUES ('20190209150026');
INSERT INTO schema_migrations (version) VALUES ('20190311111718'); INSERT INTO schema_migrations (version) VALUES ('20190311111718');
INSERT INTO schema_migrations (version) VALUES ('20190312211614'); INSERT INTO schema_migrations (version) VALUES ('20190312211614');

View file

@ -17,7 +17,6 @@ RSpec.describe Setting do
transfer_wait_time transfer_wait_time
invoice_number_min invoice_number_min
invoice_number_max invoice_number_max
days_to_keep_business_registry_cache
days_to_keep_invoices_active days_to_keep_invoices_active
days_to_keep_overdue_invoices_active days_to_keep_overdue_invoices_active
days_to_renew_domain_before_expire days_to_renew_domain_before_expire

View file

@ -1,7 +0,0 @@
one:
ident: 1234
ident_country_code: US
associated_businesses: []
retrieved_on: 2010-07-05 10:30
created_at: 2010-07-05 10:30
updated_at: 2010-07-05 10:30

View file

@ -5,33 +5,15 @@ class RegistrantApiContactsTest < ApplicationIntegrationTest
def setup def setup
super super
@original_registry_time = Setting.days_to_keep_business_registry_cache @contact = contacts(:john)
Setting.days_to_keep_business_registry_cache = 1
travel_to Time.zone.parse('2010-07-05')
@user = users(:registrant) @user = users(:registrant)
@auth_headers = { 'HTTP_AUTHORIZATION' => auth_token } @auth_headers = { 'HTTP_AUTHORIZATION' => auth_token }
end end
def teardown
super
Setting.days_to_keep_business_registry_cache = @original_registry_time
travel_back
end
def test_root_returns_contact_list
get '/api/v1/registrant/contacts', {}, @auth_headers
assert_equal(200, response.status)
json_body = JSON.parse(response.body, symbolize_names: true)
assert_equal(4, json_body.count)
array_of_contact_codes = json_body.map { |x| x[:code] }
assert(array_of_contact_codes.include?('william-001'))
assert(array_of_contact_codes.include?('jane-001'))
end
def test_root_accepts_limit_and_offset_parameters def test_root_accepts_limit_and_offset_parameters
contacts(:william).update!(ident: '1234', ident_type: 'priv', ident_country_code: 'US')
assert_equal 3, @user.contacts.size
get '/api/v1/registrant/contacts', { 'limit' => 1, 'offset' => 0 }, @auth_headers get '/api/v1/registrant/contacts', { 'limit' => 1, 'offset' => 0 }, @auth_headers
response_json = JSON.parse(response.body, symbolize_names: true) response_json = JSON.parse(response.body, symbolize_names: true)
assert_equal(200, response.status) assert_equal(200, response.status)
@ -39,26 +21,15 @@ class RegistrantApiContactsTest < ApplicationIntegrationTest
get '/api/v1/registrant/contacts', {}, @auth_headers get '/api/v1/registrant/contacts', {}, @auth_headers
response_json = JSON.parse(response.body, symbolize_names: true) response_json = JSON.parse(response.body, symbolize_names: true)
assert_equal(4, response_json.count) assert_equal(3, response_json.count)
end end
def test_get_contact_details_by_uuid def test_get_contact_details_by_uuid
get '/api/v1/registrant/contacts/0aa54704-d6f7-4ca9-b8ca-2827d9a4e4eb', {}, @auth_headers get api_v1_registrant_contact_path(@contact.uuid), nil, @auth_headers
assert_equal(200, response.status)
contact = JSON.parse(response.body, symbolize_names: true) assert_response :ok
assert_equal('william@inbox.test', contact[:email])
end
def test_root_returns_503_when_business_registry_is_not_available
raise_not_available = -> (a, b) { raise Soap::Arireg::NotAvailableError.new({}) }
BusinessRegistryCache.stub :fetch_by_ident_and_cc, raise_not_available do
get '/api/v1/registrant/contacts', {}, @auth_headers
assert_equal(503, response.status)
response_json = JSON.parse(response.body, symbolize_names: true) response_json = JSON.parse(response.body, symbolize_names: true)
assert_equal({ errors: [base: ['Business Registry not available']] }, response_json) assert_equal 'john@inbox.test', response_json[:email]
end
end end
def test_get_contact_details_by_uuid_returns_404_for_non_existent_contact def test_get_contact_details_by_uuid_returns_404_for_non_existent_contact

View file

@ -5,23 +5,12 @@ class RegistrantApiDomainsTest < ApplicationIntegrationTest
def setup def setup
super super
@original_registry_time = Setting.days_to_keep_business_registry_cache
Setting.days_to_keep_business_registry_cache = 1
travel_to Time.zone.parse('2010-07-05')
@domain = domains(:hospital) @domain = domains(:hospital)
@registrant = @domain.registrant @registrant = @domain.registrant
@user = users(:registrant) @user = users(:registrant)
@auth_headers = { 'HTTP_AUTHORIZATION' => auth_token } @auth_headers = { 'HTTP_AUTHORIZATION' => auth_token }
end end
def teardown
super
Setting.days_to_keep_business_registry_cache = @original_registry_time
travel_back
end
def test_get_domain_details_by_uuid def test_get_domain_details_by_uuid
get '/api/v1/registrant/domains/5edda1a5-3548-41ee-8b65-6d60daf85a37', {}, @auth_headers get '/api/v1/registrant/domains/5edda1a5-3548-41ee-8b65-6d60daf85a37', {}, @auth_headers
assert_equal(200, response.status) assert_equal(200, response.status)

View file

@ -5,22 +5,11 @@ class RegistrantApiRegistryLocksTest < ApplicationIntegrationTest
def setup def setup
super super
@original_registry_time = Setting.days_to_keep_business_registry_cache
Setting.days_to_keep_business_registry_cache = 1
travel_to Time.zone.parse('2010-07-05')
@user = users(:registrant) @user = users(:registrant)
@domain = domains(:airport) @domain = domains(:airport)
@auth_headers = { 'HTTP_AUTHORIZATION' => auth_token } @auth_headers = { 'HTTP_AUTHORIZATION' => auth_token }
end end
def teardown
super
Setting.days_to_keep_business_registry_cache = @original_registry_time
travel_back
end
def test_can_lock_a_not_locked_domain def test_can_lock_a_not_locked_domain
post '/api/v1/registrant/domains/2df2c1a1-8f6a-490a-81be-8bdf29866880/registry_lock', post '/api/v1/registrant/domains/2df2c1a1-8f6a-490a-81be-8bdf29866880/registry_lock',
{}, @auth_headers {}, @auth_headers
@ -101,11 +90,19 @@ class RegistrantApiRegistryLocksTest < ApplicationIntegrationTest
end end
def test_technical_contact_cannot_lock_a_domain def test_technical_contact_cannot_lock_a_domain
post '/api/v1/registrant/domains/647bcc48-8d5e-4a04-8ce5-2a3cd17b6eab/registry_lock', domain = domains(:shop)
{}, @auth_headers contact = contacts(:john)
domain.update!(registrant: contacts(:william).becomes(Registrant))
domain.tech_contacts = [contact]
domain.admin_contacts.clear
assert_equal 'US-1234', @user.registrant_ident
assert_equal '1234', contact.ident
assert_equal 'US', contact.ident_country_code
post api_v1_registrant_domain_registry_lock_path(domain.uuid), nil, @auth_headers
assert_response :unauthorized
response_json = JSON.parse(response.body, symbolize_names: true) response_json = JSON.parse(response.body, symbolize_names: true)
assert_equal(401, response.status)
assert_equal({ errors: [{ base: ['Only administrative contacts can manage registry locks'] }] }, assert_equal({ errors: [{ base: ['Only administrative contacts can manage registry locks'] }] },
response_json) response_json)
end end
@ -123,6 +120,7 @@ class RegistrantApiRegistryLocksTest < ApplicationIntegrationTest
end end
def test_locking_domains_returns_serialized_domain_object def test_locking_domains_returns_serialized_domain_object
travel_to Time.zone.parse('2010-07-05')
assert_equal 'Best Names', @domain.registrar.name assert_equal 'Best Names', @domain.registrar.name
assert_equal 'https://bestnames.test', @domain.registrar.website assert_equal 'https://bestnames.test', @domain.registrar.website

View file

@ -0,0 +1,50 @@
require 'test_helper'
require 'auth_token/auth_token_creator'
CompanyRegisterClientStub = Struct.new(:any_method) do
def representation_rights(citizen_personal_code:, citizen_country_code:)
raise CompanyRegister::NotAvailableError
end
end
class RegistrantApiV1ContactDetailsTest < ActionDispatch::IntegrationTest
setup do
@contact = contacts(:john)
@user = users(:registrant)
end
def test_returns_direct_contact_when_company_register_is_unavailable
assert_equal '1234', @contact.ident
assert_equal Contact::PRIV, @contact.ident_type
assert_equal 'US', @contact.ident_country_code
assert_equal 'US-1234', @user.registrant_ident
CompanyRegister::Client.stub(:new, CompanyRegisterClientStub.new) do
get api_v1_registrant_contact_path(@contact.uuid), nil, 'HTTP_AUTHORIZATION' => auth_token,
'Content-Type' => Mime::JSON.to_s
end
response_json = JSON.parse(response.body, symbolize_names: true)
assert_equal '1234', response_json[:ident]
end
def test_unmanaged_contact_cannot_be_accessed
assert_equal 'US-1234', @user.registrant_ident
@contact.update!(ident: '12345')
get api_v1_registrant_contact_path(@contact.uuid), nil, 'HTTP_AUTHORIZATION' => auth_token,
'Content-Type' => Mime::JSON.to_s
assert_response :not_found
response_json = JSON.parse(response.body, symbolize_names: true)
assert_equal ({ errors: [base: ['Contact not found']] }), response_json
end
private
def auth_token
token_creator = AuthTokenCreator.create_with_defaults(@user)
hash = token_creator.token_in_hash
"Bearer #{hash[:access_token]}"
end
end

View file

@ -0,0 +1,75 @@
require 'test_helper'
require 'auth_token/auth_token_creator'
CompanyRegisterClientStub = Struct.new(:any_method) do
def representation_rights(citizen_personal_code:, citizen_country_code:)
raise CompanyRegister::NotAvailableError
end
end
class RegistrantApiV1ContactListTest < ActionDispatch::IntegrationTest
setup do
@contact = contacts(:john)
@user = users(:registrant)
end
def test_returns_direct_contacts
delete_indirect_contact
assert_equal '1234', @contact.ident
assert_equal Contact::PRIV, @contact.ident_type
assert_equal 'US', @contact.ident_country_code
assert_equal 'US-1234', @user.registrant_ident
get api_v1_registrant_contacts_path, nil, 'HTTP_AUTHORIZATION' => auth_token,
'Content-Type' => Mime::JSON.to_s
response_json = JSON.parse(response.body, symbolize_names: true)
assert_equal 1, response_json.size
assert_equal '1234', response_json.first[:ident][:code]
end
def test_returns_indirect_contacts
delete_direct_contact
@contact = contacts(:acme_ltd)
assert_equal 'acme-ltd-001', @contact.code
get api_v1_registrant_contacts_path, nil, 'HTTP_AUTHORIZATION' => auth_token,
'Content-Type' => Mime::JSON.to_s
response_json = JSON.parse(response.body, symbolize_names: true)
assert_equal 1, response_json.size
assert_equal 'acme-ltd-001', response_json.first[:code]
end
def test_returns_direct_contacts_when_company_register_is_unavailable
assert_equal '1234', @contact.ident
assert_equal Contact::PRIV, @contact.ident_type
assert_equal 'US', @contact.ident_country_code
assert_equal 'US-1234', @user.registrant_ident
CompanyRegister::Client.stub(:new, CompanyRegisterClientStub.new) do
get api_v1_registrant_contacts_path, nil, 'HTTP_AUTHORIZATION' => auth_token,
'Content-Type' => Mime::JSON.to_s
end
response_json = JSON.parse(response.body, symbolize_names: true)
assert_equal 1, response_json.size
assert_equal '1234', response_json.first[:ident][:code]
end
private
def delete_direct_contact
ActiveRecord::Base.connection.disable_referential_integrity { contacts(:john).delete }
end
def delete_indirect_contact
ActiveRecord::Base.connection.disable_referential_integrity { contacts(:acme_ltd).delete }
end
def auth_token
token_creator = AuthTokenCreator.create_with_defaults(@user)
hash = token_creator.token_in_hash
"Bearer #{hash[:access_token]}"
end
end

View file

@ -6,18 +6,13 @@ class RegistrantApiV1ContactUpdateTest < ActionDispatch::IntegrationTest
@contact = contacts(:john) @contact = contacts(:john)
@original_address_processing_setting = Setting.address_processing @original_address_processing_setting = Setting.address_processing
@original_business_registry_cache_setting = Setting.days_to_keep_business_registry_cache
@original_fax_enabled_setting = ENV['fax_enabled'] @original_fax_enabled_setting = ENV['fax_enabled']
@current_user = users(:registrant) @user = users(:registrant)
Setting.days_to_keep_business_registry_cache = 1
travel_to Time.zone.parse('2010-07-05')
end end
teardown do teardown do
Setting.address_processing = @original_address_processing_setting Setting.address_processing = @original_address_processing_setting
Setting.days_to_keep_business_registry_cache = @original_business_registry_cache_setting
ENV['fax_enabled'] = @original_fax_enabled_setting ENV['fax_enabled'] = @original_fax_enabled_setting
end end
@ -52,8 +47,8 @@ class RegistrantApiV1ContactUpdateTest < ActionDispatch::IntegrationTest
end end
def test_update_fax_when_enabled def test_update_fax_when_enabled
@contact.update!(fax: '+666.6')
ENV['fax_enabled'] = 'true' ENV['fax_enabled'] = 'true'
@contact = contacts(:william)
patch api_v1_registrant_contact_path(@contact.uuid), { fax: '+777.7' }.to_json, patch api_v1_registrant_contact_path(@contact.uuid), { fax: '+777.7' }.to_json,
'HTTP_AUTHORIZATION' => auth_token, 'HTTP_AUTHORIZATION' => auth_token,
@ -101,7 +96,7 @@ class RegistrantApiV1ContactUpdateTest < ActionDispatch::IntegrationTest
end end
def test_address_is_optional_when_enabled def test_address_is_optional_when_enabled
@contact = contacts(:william) @contact.update!(street: 'any', zip: 'any', city: 'any', state: 'any', country_code: 'US')
Setting.address_processing = true Setting.address_processing = true
patch api_v1_registrant_contact_path(@contact.uuid), { name: 'any' }.to_json, patch api_v1_registrant_contact_path(@contact.uuid), { name: 'any' }.to_json,
@ -113,18 +108,18 @@ class RegistrantApiV1ContactUpdateTest < ActionDispatch::IntegrationTest
end end
def test_address_cannot_be_updated_when_disabled def test_address_cannot_be_updated_when_disabled
@contact = contacts(:william) @contact.update!(street: 'old street')
@original_address = @contact.address
Setting.address_processing = false Setting.address_processing = false
patch api_v1_registrant_contact_path(@contact.uuid), { address: { city: 'new city' } }.to_json, patch api_v1_registrant_contact_path(@contact.uuid), { address: { street: 'new street' } }
.to_json,
'HTTP_AUTHORIZATION' => auth_token, 'HTTP_AUTHORIZATION' => auth_token,
'Accept' => Mime::JSON, 'Accept' => Mime::JSON,
'Content-Type' => Mime::JSON.to_s 'Content-Type' => Mime::JSON.to_s
@contact.reload @contact.reload
assert_response :bad_request assert_response :bad_request
assert_equal @original_address, @contact.address assert_not_equal 'new street', @contact.street
error_msg = 'Address processing is disabled and therefore cannot be updated' error_msg = 'Address processing is disabled and therefore cannot be updated'
assert_equal ({ errors: [{ address: [error_msg] }] }), JSON.parse(response.body, assert_equal ({ errors: [{ address: [error_msg] }] }), JSON.parse(response.body,
@ -160,10 +155,15 @@ class RegistrantApiV1ContactUpdateTest < ActionDispatch::IntegrationTest
end end
def test_legal_persons_disclosed_attributes_cannot_be_changed def test_legal_persons_disclosed_attributes_cannot_be_changed
business_registry_caches(:one).update!(associated_businesses: %w[1234]) @contact = contacts(:acme_ltd)
@contact.update!(ident_type: Contact::ORG,
ident: '1234', # contacts(:acme_ltd).ident
disclosed_attributes: %w[]) assert_equal '1234567', @contact.ident
assert_equal Contact::ORG, @contact.ident_type
assert_equal 'US', @contact.ident_country_code
@contact.update!(disclosed_attributes: %w[])
assert_equal 'US-1234', @user.registrant_ident
assert_no_changes -> { @contact.disclosed_attributes } do assert_no_changes -> { @contact.disclosed_attributes } do
patch api_v1_registrant_contact_path(@contact.uuid), { disclosed_attributes: %w[name] } patch api_v1_registrant_contact_path(@contact.uuid), { disclosed_attributes: %w[name] }
@ -222,7 +222,7 @@ class RegistrantApiV1ContactUpdateTest < ActionDispatch::IntegrationTest
end end
def test_unmanaged_contact_cannot_be_updated def test_unmanaged_contact_cannot_be_updated
@current_user.update!(registrant_ident: 'US-1234') assert_equal 'US-1234', @user.registrant_ident
@contact.update!(ident: '12345') @contact.update!(ident: '12345')
patch api_v1_registrant_contact_path(@contact.uuid), { name: 'new name' }.to_json, patch api_v1_registrant_contact_path(@contact.uuid), { name: 'new name' }.to_json,
@ -252,7 +252,7 @@ class RegistrantApiV1ContactUpdateTest < ActionDispatch::IntegrationTest
private private
def auth_token def auth_token
token_creator = AuthTokenCreator.create_with_defaults(@current_user) token_creator = AuthTokenCreator.create_with_defaults(@user)
hash = token_creator.token_in_hash hash = token_creator.token_in_hash
"Bearer #{hash[:access_token]}" "Bearer #{hash[:access_token]}"
end end

View file

@ -9,6 +9,14 @@ class ContactTest < ActiveSupport::TestCase
assert @contact.valid?, proc { @contact.errors.full_messages } assert @contact.valid?, proc { @contact.errors.full_messages }
end end
def test_private_entity
assert_equal 'priv', Contact::PRIV
end
def test_legal_entity
assert_equal 'org', Contact::ORG
end
def test_invalid_without_email def test_invalid_without_email
@contact.email = '' @contact.email = ''
assert @contact.invalid? assert @contact.invalid?
@ -48,4 +56,27 @@ class ContactTest < ActiveSupport::TestCase
assert_equal 'EE', @contact.country_code assert_equal 'EE', @contact.country_code
assert_equal address, @contact.address assert_equal address, @contact.address
end end
def test_returns_registrant_user_direct_contacts
assert_equal Contact::PRIV, @contact.ident_type
assert_equal '1234', @contact.ident
assert_equal 'US', @contact.ident_country_code
registrant_user = RegistrantUser.new(registrant_ident: 'US-1234')
registrant_user.stub(:companies, []) do
assert_equal [@contact], Contact.registrant_user_contacts(registrant_user)
assert_equal [@contact], Contact.registrant_user_direct_contacts(registrant_user)
end
end
def test_returns_registrant_user_indirect_contacts
@contact.update!(ident_type: Contact::ORG)
assert_equal '1234', @contact.ident
assert_equal 'US', @contact.ident_country_code
registrant_user = RegistrantUser.new(registrant_ident: 'US-1234')
registrant_user.stub(:companies, [OpenStruct.new(registration_number: '1234')]) do
assert_equal [@contact], Contact.registrant_user_contacts(registrant_user)
end
end
end end

View file

@ -17,4 +17,57 @@ class DomainTest < ActiveSupport::TestCase
domain = Domain.new(name: 'shop.test') domain = Domain.new(name: 'shop.test')
assert_equal 'shop.test', domain.domain_name.to_s assert_equal 'shop.test', domain.domain_name.to_s
end end
def test_returns_registrant_user_domains_by_registrant
registrant = contacts(:john).becomes(Registrant)
assert_equal registrant, @domain.registrant
registrant_user = RegistrantUser.new
registrant_user.stub(:contacts, [registrant]) do
assert_includes Domain.registrant_user_domains(registrant_user), @domain
end
end
def test_returns_registrant_user_domains_by_contact
contact = contacts(:jane)
assert_not_equal contact.becomes(Registrant), @domain.registrant
assert_includes @domain.contacts, contact
registrant_user = RegistrantUser.new
registrant_user.stub(:contacts, [contact]) do
assert_includes Domain.registrant_user_domains(registrant_user), @domain
end
end
def test_returns_registrant_user_administered_domains_by_registrant
registrant = contacts(:john).becomes(Registrant)
assert_equal registrant, @domain.registrant
registrant_user = RegistrantUser.new
registrant_user.stub(:contacts, [registrant]) do
assert_includes Domain.registrant_user_administered_domains(registrant_user), @domain
end
end
def test_returns_registrant_user_administered_domains_by_administrative_contact
contact = contacts(:jane)
assert_not_equal contact.becomes(Registrant), @domain.registrant
assert_includes @domain.admin_contacts, contact
registrant_user = RegistrantUser.new
registrant_user.stub(:contacts, [contact]) do
assert_includes Domain.registrant_user_administered_domains(registrant_user), @domain
end
end
def test_does_not_return_registrant_user_administered_domains_by_technical_contact
contact = contacts(:william)
assert_not_equal contact.becomes(Registrant), @domain.registrant
assert_includes @domain.tech_contacts, contact
registrant_user = RegistrantUser.new
registrant_user.stub(:contacts, [contact]) do
assert_not_includes Domain.registrant_user_administered_domains(registrant_user), @domain
end
end
end end

View file

@ -11,29 +11,8 @@ class RegistrantUserTest < ActiveSupport::TestCase
super super
end end
def test_domains_returns_an_list_of_distinct_domains_associated_with_a_specific_id_code def test_ident_helper_method
domain_names = @user.domains.pluck(:name)
assert_equal(4, domain_names.length)
# User is a registrant, but not a contact for the domain. Should be included in the list.
assert(domain_names.include?('shop.test'))
end
def test_administered_domains_returns_a_list_of_domains
domain_names = @user.administered_domains.pluck(:name)
assert_equal(3, domain_names.length)
# User is a tech contact for the domain.
refute(domain_names.include?('library.test'))
end
def test_contacts_returns_an_list_of_contacts_associated_with_a_specific_id_code
assert_equal(1, @user.contacts.count)
end
def test_ident_and_country_code_helper_methods
assert_equal('1234', @user.ident) assert_equal('1234', @user.ident)
assert_equal('US', @user.country_code)
end end
def test_first_name_from_username def test_first_name_from_username
@ -45,4 +24,44 @@ class RegistrantUserTest < ActiveSupport::TestCase
user = RegistrantUser.new(username: 'John Doe') user = RegistrantUser.new(username: 'John Doe')
assert_equal 'Doe', user.last_name assert_equal 'Doe', user.last_name
end end
def test_returns_country
user = RegistrantUser.new(registrant_ident: 'US-1234')
assert_equal Country.new('US'), user.country
end
def test_queries_company_register_for_associated_companies
assert_equal 'US-1234', @user.registrant_ident
company_register = Minitest::Mock.new
company_register.expect(:representation_rights, %w[acme ace], [{ citizen_personal_code: '1234',
citizen_country_code: 'USA' }])
assert_equal %w[acme ace], @user.companies(company_register)
company_register.verify
end
def test_returns_contacts
Contact.stub(:registrant_user_contacts, %w(john jane)) do
assert_equal %w(john jane), @user.contacts
end
end
def test_returns_direct_contacts
Contact.stub(:registrant_user_direct_contacts, %w(john jane)) do
assert_equal %w(john jane), @user.direct_contacts
end
end
def test_returns_domains
Domain.stub(:registrant_user_domains, %w(shop airport)) do
assert_equal %w(shop airport), @user.domains
end
end
def test_returns_administered_domains
Domain.stub(:registrant_user_administered_domains, %w(shop airport)) do
assert_equal %w(shop airport), @user.administered_domains
end
end
end end

View file

@ -3,14 +3,12 @@ require 'test_helper'
class RegistrantAreaContactDetailsTest < ApplicationSystemTestCase class RegistrantAreaContactDetailsTest < ApplicationSystemTestCase
setup do setup do
sign_in users(:registrant) sign_in users(:registrant)
@domain = domains(:shop)
@contact = contacts(:john) @contact = contacts(:john)
Setting.days_to_keep_business_registry_cache = 1
travel_to Time.zone.parse('2010-07-05')
end end
def test_general_data def test_general_data
visit registrant_domain_contact_url(domains(:shop), @contact) visit registrant_domain_contact_url(@domain, @contact)
assert_text 'Code john-001' assert_text 'Code john-001'
assert_text 'Name John' assert_text 'Name John'
@ -32,4 +30,12 @@ class RegistrantAreaContactDetailsTest < ApplicationSystemTestCase
assert_no_text 'Name John' assert_no_text 'Name John'
end end
end end
def test_unmanaged_contact_cannot_be_accessed
@contact.update!(ident: '12345')
assert_raises ActiveRecord::RecordNotFound do
visit registrant_domain_contact_url(@domain, @contact)
end
end
end end

View file

@ -7,18 +7,14 @@ class RegistrantAreaContactUpdateTest < ApplicationIntegrationTest
sign_in users(:registrant) sign_in users(:registrant)
@original_address_processing_setting = Setting.address_processing @original_address_processing_setting = Setting.address_processing
@original_business_registry_cache_setting = Setting.days_to_keep_business_registry_cache
@original_fax_enabled_setting = ENV['fax_enabled'] @original_fax_enabled_setting = ENV['fax_enabled']
@original_registrant_api_base_url_setting = ENV['registrant_api_base_url'] @original_registrant_api_base_url_setting = ENV['registrant_api_base_url']
ENV['registrant_api_base_url'] = 'https://api.test' ENV['registrant_api_base_url'] = 'https://api.test'
Setting.days_to_keep_business_registry_cache = 1
travel_to Time.zone.parse('2010-07-05')
end end
teardown do teardown do
Setting.address_processing = @original_address_processing_setting Setting.address_processing = @original_address_processing_setting
Setting.days_to_keep_business_registry_cache = @original_business_registry_cache_setting
ENV['fax_enabled'] = @original_fax_enabled_setting ENV['fax_enabled'] = @original_fax_enabled_setting
ENV['registrant_api_base_url'] = @original_registrant_api_base_url_setting ENV['registrant_api_base_url'] = @original_registrant_api_base_url_setting
end end
@ -90,7 +86,11 @@ class RegistrantAreaContactUpdateTest < ApplicationIntegrationTest
def test_form_is_pre_populated_with_address_when_enabled def test_form_is_pre_populated_with_address_when_enabled
Setting.address_processing = true Setting.address_processing = true
@contact = contacts(:william) @contact.update!(street: 'Main Street',
zip: '12345',
city: 'New York',
state: 'New York State',
country_code: 'US')
visit edit_registrant_domain_contact_url(@domain, @contact) visit edit_registrant_domain_contact_url(@domain, @contact)
@ -143,9 +143,10 @@ class RegistrantAreaContactUpdateTest < ApplicationIntegrationTest
def test_unmanaged_contact_cannot_be_updated def test_unmanaged_contact_cannot_be_updated
@contact.update!(ident: '12345') @contact.update!(ident: '12345')
assert_raises ActiveRecord::RecordNotFound do
visit registrant_domain_contact_url(@domain, @contact) visit registrant_domain_contact_url(@domain, @contact)
assert_no_button 'Edit' end
assert_no_link 'Edit'
end end
def test_fail_gracefully def test_fail_gracefully

View file

@ -4,9 +4,6 @@ class RegistrantAreaDomainDetailsTest < ApplicationSystemTestCase
setup do setup do
sign_in users(:registrant) sign_in users(:registrant)
@domain = domains(:shop) @domain = domains(:shop)
Setting.days_to_keep_business_registry_cache = 1
travel_to Time.zone.parse('2010-07-05')
end end
def test_general_data def test_general_data

View file

@ -1,12 +1,17 @@
require 'test_helper' require 'test_helper'
CompanyRegisterClientStub = Struct.new(:any_method) do
def representation_rights(citizen_personal_code:, citizen_country_code:)
raise CompanyRegister::NotAvailableError
end
end
class RegistrantAreaDomainListTest < ApplicationSystemTestCase class RegistrantAreaDomainListTest < ApplicationSystemTestCase
setup do setup do
sign_in users(:registrant) @user = users(:registrant)
@domain = domains(:shop) sign_in @user
Setting.days_to_keep_business_registry_cache = 1 @domain = domains(:shop)
travel_to Time.zone.parse('2010-07-05')
end end
def test_show_domain_list def test_show_domain_list
@ -22,4 +27,31 @@ class RegistrantAreaDomainListTest < ApplicationSystemTestCase
visit registrant_domains_url visit registrant_domains_url
assert_no_text 'metro.test' assert_no_text 'metro.test'
end end
def test_notification_when_company_register_is_unavailable
CompanyRegister::Client.stub(:new, CompanyRegisterClientStub.new) do
visit registrant_domains_url
end
assert_text 'Company register is unavailable. Domains and contacts associated via' \
' organizations are not shown.'
end
def test_show_direct_domains_when_company_register_is_unavailable
assert_equal 'US-1234', @user.registrant_ident
contact = contacts(:john)
assert_equal '1234', contact.ident
assert_equal Contact::PRIV, contact.ident_type
assert_equal 'US', contact.ident_country_code
assert_equal contact.becomes(Registrant), @domain.registrant
assert_equal 'shop.test', @domain.name
CompanyRegister::Client.stub(:new, CompanyRegisterClientStub.new) do
visit registrant_domains_url
end
assert_text 'shop.test'
end
end end

View file

@ -3,9 +3,6 @@ require 'test_helper'
class RegistrantDomainsTest < ApplicationSystemTestCase class RegistrantDomainsTest < ApplicationSystemTestCase
setup do setup do
sign_in users(:registrant) sign_in users(:registrant)
Setting.days_to_keep_business_registry_cache = 1
travel_to Time.zone.parse('2010-07-05')
end end
def test_shows_domains_where_current_user_is_registrant def test_shows_domains_where_current_user_is_registrant

View file

@ -4,15 +4,6 @@ class RegistrantLayoutTest < ApplicationSystemTestCase
def setup def setup
super super
sign_in(users(:registrant)) sign_in(users(:registrant))
Setting.days_to_keep_business_registry_cache = 1
travel_to Time.zone.parse('2010-07-05')
end
def teardown
super
travel_back
end end
def test_has_link_to_rest_whois_and_internet_ee def test_has_link_to_rest_whois_and_internet_ee

View file

@ -16,6 +16,16 @@ require 'support/task_test_case'
Setting.address_processing = false Setting.address_processing = false
Setting.registry_country_code = 'US' Setting.registry_country_code = 'US'
class CompanyRegisterClientStub
Company = Struct.new(:registration_number)
def representation_rights(citizen_personal_code:, citizen_country_code:)
[Company.new('1234567')]
end
end
CompanyRegister::Client = CompanyRegisterClientStub
class ActiveSupport::TestCase class ActiveSupport::TestCase
include FactoryBot::Syntax::Methods include FactoryBot::Syntax::Methods