Change place lib repository

This commit is contained in:
Xavier J 2016-12-02 17:03:52 +01:00
parent 27cc62ea1e
commit 1a3e23c6ef
21 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,36 @@
module Carto
module Bano
# input : address
# output : Array List label address
class AddressRetriever
def initialize(address)
@address = address
end
def list
@list ||= convert_driver_result_to_full_address
end
private
def driver
@driver ||= Carto::Bano::Driver.new @address, 5
end
def convert_driver_result_to_full_address
result = JSON.parse(driver.call)
if result['features'].size == 0
Rails.logger.error "unable to find location for address #{@address}"
return []
end
result['features'].inject([]) do |acc, feature|
acc.push feature['properties']['label']
end
rescue TypeError, JSON::ParserError
[]
end
end
end
end

View file

@ -0,0 +1,22 @@
module Carto
module Bano
# input : string (address)
# output : json
class Driver
def initialize(address, limit = 1)
@address = address
@limit = limit
end
def call
RestClient.get api_url, params: { q: @address, limit: @limit }
rescue RestClient::ServiceUnavailable
nil
end
def api_url
'http://api-adresse.data.gouv.fr/search'
end
end
end
end

View file

@ -0,0 +1,30 @@
module Carto
module Bano
# input : address
# output : point RGeo::Cartesian::PointImpl
class PointRetriever
def initialize(address)
@address = address
end
def point
@point ||= convert_driver_result_to_point
end
private
def driver
@driver ||= Carto::Bano::Driver.new @address
end
def convert_driver_result_to_point
result = JSON.parse(driver.call)
if result['features'].size == 0
Rails.logger.error "unable to find location for address #{@address}"
return nil
end
RGeo::GeoJSON.decode(result['features'][0]['geometry'], json_parser: :json)
end
end
end
end

View file

@ -0,0 +1,34 @@
module Carto
module GeoAPI
class Driver
def self.regions
call regions_url
end
def self.departements
call departements_url
end
def self.pays
File.open('lib/carto/geo_api/pays.json').read
end
private
def self.call api_url
RestClient.get api_url, params: { fields: :nom }
rescue RestClient::ServiceUnavailable
nil
end
def self.departements_url
'https://geo.api.gouv.fr/departements'
end
def self.regions_url
'https://geo.api.gouv.fr/regions'
end
end
end
end

View file

@ -0,0 +1,851 @@
[
{
"nom": "FRANCE"
},
{
"nom": "----"
},
{
"nom": "ACORES, MADERE"
},
{
"nom": "AFGHANISTAN"
},
{
"nom": "AFRIQUE DU SUD"
},
{
"nom": "ALASKA"
},
{
"nom": "ALBANIE"
},
{
"nom": "ALGERIE"
},
{
"nom": "ALLEMAGNE"
},
{
"nom": "ANDORRE"
},
{
"nom": "ANGOLA"
},
{
"nom": "ANGUILLA"
},
{
"nom": "ANTIGUA-ET-BARBUDA"
},
{
"nom": "ANTILLES NEERLANDAISES"
},
{
"nom": "ARABIE SAOUDITE"
},
{
"nom": "ARGENTINE"
},
{
"nom": "ARMENIE"
},
{
"nom": "ARUBA"
},
{
"nom": "AUSTRALIE"
},
{
"nom": "AUTRICHE"
},
{
"nom": "AZERBAIDJAN"
},
{
"nom": "BAHAMAS"
},
{
"nom": "BAHREIN"
},
{
"nom": "BANGLADESH"
},
{
"nom": "BARBADE"
},
{
"nom": "BELGIQUE"
},
{
"nom": "BELIZE"
},
{
"nom": "BENIN"
},
{
"nom": "BERMUDES"
},
{
"nom": "BHOUTAN"
},
{
"nom": "BIELORUSSIE"
},
{
"nom": "BIRMANIE"
},
{
"nom": "BOLIVIE"
},
{
"nom": "BONAIRE, SAINT EUSTACHE ET SABA"
},
{
"nom": "BOSNIE-HERZEGOVINE"
},
{
"nom": "BOTSWANA"
},
{
"nom": "BOUVET (ILE)"
},
{
"nom": "BRESIL"
},
{
"nom": "BRUNEI"
},
{
"nom": "BULGARIE"
},
{
"nom": "BURKINA"
},
{
"nom": "BURUNDI"
},
{
"nom": "CAIMANES (ILES)"
},
{
"nom": "CAMBODGE"
},
{
"nom": "CAMEROUN"
},
{
"nom": "CAMEROUN ET TOGO"
},
{
"nom": "CANADA"
},
{
"nom": "CANARIES (ILES)"
},
{
"nom": "CAP-VERT"
},
{
"nom": "CENTRAFRICAINE (REPUBLIQUE)"
},
{
"nom": "CHILI"
},
{
"nom": "CHINE"
},
{
"nom": "CHRISTMAS (ILE)"
},
{
"nom": "CHYPRE"
},
{
"nom": "CLIPPERTON (ILE)"
},
{
"nom": "COCOS ou KEELING (ILES)"
},
{
"nom": "COLOMBIE"
},
{
"nom": "COMORES"
},
{
"nom": "CONGO"
},
{
"nom": "CONGO (REPUBLIQUE DEMOCRATIQUE)"
},
{
"nom": "COOK (ILES)"
},
{
"nom": "COREE"
},
{
"nom": "COREE (REPUBLIQUE DE)"
},
{
"nom": "COREE (REPUBLIQUE POPULAIRE DEMOCRATIQUE DE)"
},
{
"nom": "COSTA RICA"
},
{
"nom": "COTE D'IVOIRE"
},
{
"nom": "CROATIE"
},
{
"nom": "CUBA"
},
{
"nom": "CURAÇAO"
},
{
"nom": "DANEMARK"
},
{
"nom": "DJIBOUTI"
},
{
"nom": "DOMINICAINE (REPUBLIQUE)"
},
{
"nom": "DOMINIQUE"
},
{
"nom": "EGYPTE"
},
{
"nom": "EL SALVADOR"
},
{
"nom": "EMIRATS ARABES UNIS"
},
{
"nom": "EQUATEUR"
},
{
"nom": "ERYTHREE"
},
{
"nom": "ESPAGNE"
},
{
"nom": "ESTONIE"
},
{
"nom": "ETATS MALAIS NON FEDERES"
},
{
"nom": "ETATS-UNIS"
},
{
"nom": "ETHIOPIE"
},
{
"nom": "EX-REPUBLIQUE YOUGOSLAVE DE MACEDOINE"
},
{
"nom": "FEROE (ILES)"
},
{
"nom": "FIDJI"
},
{
"nom": "FINLANDE"
},
{
"nom": "GABON"
},
{
"nom": "GAMBIE"
},
{
"nom": "GEORGIE"
},
{
"nom": "GEORGIE DU SUD ET LES ILES SANDWICH DU SUD"
},
{
"nom": "GHANA"
},
{
"nom": "GIBRALTAR"
},
{
"nom": "GOA"
},
{
"nom": "GRECE"
},
{
"nom": "GRENADE"
},
{
"nom": "GROENLAND"
},
{
"nom": "GUADELOUPE"
},
{
"nom": "GUAM"
},
{
"nom": "GUATEMALA"
},
{
"nom": "GUERNESEY"
},
{
"nom": "GUINEE"
},
{
"nom": "GUINEE EQUATORIALE"
},
{
"nom": "GUINEE-BISSAU"
},
{
"nom": "GUYANA"
},
{
"nom": "GUYANE"
},
{
"nom": "HAITI"
},
{
"nom": "HAWAII (ILES)"
},
{
"nom": "HEARD ET MACDONALD (ILES)"
},
{
"nom": "HONDURAS"
},
{
"nom": "HONG-KONG"
},
{
"nom": "HONGRIE"
},
{
"nom": "ILES PORTUGAISES DE L'OCEAN INDIEN"
},
{
"nom": "INDE"
},
{
"nom": "INDONESIE"
},
{
"nom": "IRAN"
},
{
"nom": "IRAQ"
},
{
"nom": "IRLANDE, ou EIRE"
},
{
"nom": "ISLANDE"
},
{
"nom": "ISRAEL"
},
{
"nom": "ITALIE"
},
{
"nom": "JAMAIQUE"
},
{
"nom": "JAPON"
},
{
"nom": "JERSEY"
},
{
"nom": "JORDANIE"
},
{
"nom": "KAMTCHATKA"
},
{
"nom": "KAZAKHSTAN"
},
{
"nom": "KENYA"
},
{
"nom": "KIRGHIZISTAN"
},
{
"nom": "KIRIBATI"
},
{
"nom": "KOSOVO"
},
{
"nom": "KOWEIT"
},
{
"nom": "LA REUNION"
},
{
"nom": "LABRADOR"
},
{
"nom": "LAOS"
},
{
"nom": "LESOTHO"
},
{
"nom": "LETTONIE"
},
{
"nom": "LIBAN"
},
{
"nom": "LIBERIA"
},
{
"nom": "LIBYE"
},
{
"nom": "LIECHTENSTEIN"
},
{
"nom": "LITUANIE"
},
{
"nom": "LUXEMBOURG"
},
{
"nom": "MACAO"
},
{
"nom": "MADAGASCAR"
},
{
"nom": "MALAISIE"
},
{
"nom": "MALAWI"
},
{
"nom": "MALDIVES"
},
{
"nom": "MALI"
},
{
"nom": "MALOUINES, OU FALKLAND (ILES)"
},
{
"nom": "MALTE"
},
{
"nom": "MAN (ILE)"
},
{
"nom": "MANDCHOURIE"
},
{
"nom": "MARIANNES DU NORD (ILES)"
},
{
"nom": "MAROC"
},
{
"nom": "MARSHALL (ILES)"
},
{
"nom": "MARTINIQUE"
},
{
"nom": "MAURICE"
},
{
"nom": "MAURITANIE"
},
{
"nom": "MAYOTTE"
},
{
"nom": "MEXIQUE"
},
{
"nom": "MICRONESIE (ETATS FEDERES DE)"
},
{
"nom": "MOLDAVIE"
},
{
"nom": "MONACO"
},
{
"nom": "MONGOLIE"
},
{
"nom": "MONTENEGRO"
},
{
"nom": "MONTSERRAT"
},
{
"nom": "MOZAMBIQUE"
},
{
"nom": "NAMIBIE"
},
{
"nom": "NAURU"
},
{
"nom": "NEPAL"
},
{
"nom": "NICARAGUA"
},
{
"nom": "NIGER"
},
{
"nom": "NIGERIA"
},
{
"nom": "NIUE"
},
{
"nom": "NORFOLK (ILE)"
},
{
"nom": "NORVEGE"
},
{
"nom": "NOUVELLE-CALEDONIE"
},
{
"nom": "NOUVELLE-ZELANDE"
},
{
"nom": "OCEAN INDIEN (TERRITOIRE BRITANNIQUE DE L')"
},
{
"nom": "OMAN"
},
{
"nom": "OUGANDA"
},
{
"nom": "OUZBEKISTAN"
},
{
"nom": "PAKISTAN"
},
{
"nom": "PALAOS (ILES)"
},
{
"nom": "PALESTINE (Etat de)"
},
{
"nom": "PANAMA"
},
{
"nom": "PAPOUASIE-NOUVELLE-GUINEE"
},
{
"nom": "PARAGUAY"
},
{
"nom": "PAYS-BAS"
},
{
"nom": "PEROU"
},
{
"nom": "PHILIPPINES"
},
{
"nom": "PITCAIRN (ILE)"
},
{
"nom": "POLOGNE"
},
{
"nom": "POLYNESIE FRANCAISE"
},
{
"nom": "PORTO RICO"
},
{
"nom": "PORTUGAL"
},
{
"nom": "POSSESSIONS BRITANNIQUES AU PROCHE-ORIENT"
},
{
"nom": "PRESIDES"
},
{
"nom": "PROVINCES ESPAGNOLES D'AFRIQUE"
},
{
"nom": "QATAR"
},
{
"nom": "REPUBLIQUE DEMOCRATIQUE ALLEMANDE"
},
{
"nom": "REPUBLIQUE FEDERALE D'ALLEMAGNE"
},
{
"nom": "ROUMANIE"
},
{
"nom": "ROYAUME-UNI"
},
{
"nom": "RUSSIE"
},
{
"nom": "RWANDA"
},
{
"nom": "SAHARA OCCIDENTAL"
},
{
"nom": "SAINT-BARTHELEMY"
},
{
"nom": "SAINT-CHRISTOPHE-ET-NIEVES"
},
{
"nom": "SAINT-MARIN"
},
{
"nom": "SAINT-MARTIN"
},
{
"nom": "SAINT-MARTIN (PARTIE NEERLANDAISE)"
},
{
"nom": "SAINT-PIERRE-ET-MIQUELON"
},
{
"nom": "SAINT-VINCENT-ET-LES GRENADINES"
},
{
"nom": "SAINTE HELENE, ASCENSION ET TRISTAN DA CUNHA"
},
{
"nom": "SAINTE-LUCIE"
},
{
"nom": "SALOMON (ILES)"
},
{
"nom": "SAMOA AMERICAINES"
},
{
"nom": "SAMOA OCCIDENTALES"
},
{
"nom": "SAO TOME-ET-PRINCIPE"
},
{
"nom": "SENEGAL"
},
{
"nom": "SERBIE"
},
{
"nom": "SEYCHELLES"
},
{
"nom": "SIBERIE"
},
{
"nom": "SIERRA LEONE"
},
{
"nom": "SINGAPOUR"
},
{
"nom": "SLOVAQUIE"
},
{
"nom": "SLOVENIE"
},
{
"nom": "SOMALIE"
},
{
"nom": "SOUDAN"
},
{
"nom": "SOUDAN ANGLO-EGYPTIEN, KENYA, OUGANDA"
},
{
"nom": "SOUDAN DU SUD"
},
{
"nom": "SRI LANKA"
},
{
"nom": "SUEDE"
},
{
"nom": "SUISSE"
},
{
"nom": "SURINAME"
},
{
"nom": "SVALBARD et ILE JAN MAYEN"
},
{
"nom": "SWAZILAND"
},
{
"nom": "SYRIE"
},
{
"nom": "TADJIKISTAN"
},
{
"nom": "TAIWAN"
},
{
"nom": "TANGER"
},
{
"nom": "TANZANIE"
},
{
"nom": "TCHAD"
},
{
"nom": "TCHECOSLOVAQUIE"
},
{
"nom": "TCHEQUE (REPUBLIQUE)"
},
{
"nom": "TERR. DES ETATS-UNIS D'AMERIQUE EN AMERIQUE"
},
{
"nom": "TERR. DES ETATS-UNIS D'AMERIQUE EN OCEANIE"
},
{
"nom": "TERR. DU ROYAUME-UNI DANS L'ATLANTIQUE SUD"
},
{
"nom": "TERRE-NEUVE"
},
{
"nom": "TERRES AUSTRALES FRANCAISES"
},
{
"nom": "TERRITOIRES DU ROYAUME-UNI AUX ANTILLES"
},
{
"nom": "THAILANDE"
},
{
"nom": "TIMOR ORIENTAL"
},
{
"nom": "TOGO"
},
{
"nom": "TOKELAU"
},
{
"nom": "TONGA"
},
{
"nom": "TRINITE-ET-TOBAGO"
},
{
"nom": "TUNISIE"
},
{
"nom": "TURKESTAN RUSSE"
},
{
"nom": "TURKMENISTAN"
},
{
"nom": "TURKS ET CAIQUES (ILES)"
},
{
"nom": "TURQUIE"
},
{
"nom": "TURQUIE D'EUROPE"
},
{
"nom": "TUVALU"
},
{
"nom": "UKRAINE"
},
{
"nom": "URUGUAY"
},
{
"nom": "VANUATU"
},
{
"nom": "VATICAN, ou SAINT-SIEGE"
},
{
"nom": "VENEZUELA"
},
{
"nom": "VIERGES BRITANNIQUES (ILES)"
},
{
"nom": "VIERGES DES ETATS-UNIS (ILES)"
},
{
"nom": "VIET NAM"
},
{
"nom": "VIET NAM DU NORD"
},
{
"nom": "VIET NAM DU SUD"
},
{
"nom": "WALLIS-ET-FUTUNA"
},
{
"nom": "YEMEN"
},
{
"nom": "YEMEN (REPUBLIQUE ARABE DU)"
},
{
"nom": "YEMEN DEMOCRATIQUE"
},
{
"nom": "ZAMBIE"
},
{
"nom": "ZANZIBAR"
},
{
"nom": "ZIMBABWE"
}
]

View file

@ -0,0 +1,11 @@
module Carto
# this class take a string in input and return a point
class Geocodeur
def self.convert_adresse_to_point(address)
Carto::Bano::PointRetriever.new(address).point
rescue RestClient::Exception, JSON::ParserError => e
Rails.logger.error e.message
nil
end
end
end

View file

@ -0,0 +1,29 @@
class CARTO::SGMAP::API
def initialize
end
def self.search_qp(geojson)
endpoint = "/quartiers-prioritaires/search"
call(base_url + endpoint, {geojson: geojson.to_s})
end
def self.search_cadastre(geojson)
endpoint = "/cadastre/geometrie"
call(base_url + endpoint, {geojson: geojson.to_s})
end
private
def self.call(url, params = {})
verify_ssl_mode = OpenSSL::SSL::VERIFY_NONE
RestClient::Resource.new(
url,
verify_ssl: verify_ssl_mode,
).post params[:geojson], content_type: 'application/json'
end
def self.base_url
'https://apicarto.sgmap.fr'
end
end

View file

@ -0,0 +1,32 @@
class CARTO::SGMAP::Cadastre::Adapter
def initialize(coordinates)
@coordinates = GeojsonService.to_json_polygon_for_cadastre(coordinates)
end
def data_source
@data_source ||= JSON.parse(CARTO::SGMAP::API.search_cadastre(@coordinates), symbolize_names: true)
end
def to_params
data_source[:features].inject([]) do |acc, feature|
tmp = filter_properties feature[:properties]
tmp[:geometry] = feature[:geometry]
acc << tmp
end
end
def filter_properties properties
{
surface_intersection: properties[:surface_intersection],
surface_parcelle: properties[:surface_parcelle],
numero: properties[:numero],
feuille: properties[:feuille],
section: properties[:section],
code_dep: properties[:code_dep],
nom_com: properties[:nom_com],
code_com: properties[:code_com],
code_arr: properties[:code_arr]
}
end
end

View file

@ -0,0 +1,22 @@
class CARTO::SGMAP::QuartiersPrioritaires::Adapter
def initialize(coordinates)
@coordinates = GeojsonService.to_json_polygon_for_qp(coordinates)
end
def data_source
@data_source ||= JSON.parse(CARTO::SGMAP::API.search_qp(@coordinates), symbolize_names: true)
end
def to_params
params = {}
data_source[:features].each do |feature|
qp_code = feature[:properties][:code]
params[qp_code] = feature[:properties]
params[qp_code][:geometry] = feature[:geometry]
end
params
end
end

View file

@ -0,0 +1,74 @@
# Source: https://github.com/gitlabhq/gitlabhq/blob/master/lib/file_size_validator.rb
class FileSizeValidator < ActiveModel::EachValidator
MESSAGES = { is: :wrong_size, minimum: :size_too_small, maximum: :size_too_big }.freeze
CHECKS = { is: :==, minimum: :>=, maximum: :<= }.freeze
DEFAULT_TOKENIZER = lambda { |value| value.split(//) }
RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]
def initialize(options)
if range = (options.delete(:in) || options.delete(:within))
raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
options[:minimum], options[:maximum] = range.begin, range.end
options[:maximum] -= 1 if range.exclude_end?
end
super
end
def check_validity!
keys = CHECKS.keys & options.keys
if keys.empty?
raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
end
keys.each do |key|
value = options[key]
unless (value.is_a?(Integer) && value >= 0) || value.is_a?(Symbol)
raise ArgumentError, ":#{key} must be a nonnegative Integer or symbol"
end
end
end
def validate_each(record, attribute, value)
raise(ArgumentError, "A CarrierWave::Uploader::Base object was expected") unless value.kind_of? CarrierWave::Uploader::Base
value = (options[:tokenizer] || DEFAULT_TOKENIZER).call(value) if value.kind_of?(String)
CHECKS.each do |key, validity_check|
next unless check_value = options[key]
check_value =
case check_value
when Integer
check_value
when Symbol
record.send(check_value)
end
value ||= [] if key == :maximum
value_size = value.size
next if value_size.send(validity_check, check_value)
errors_options = options.except(*RESERVED_OPTIONS)
errors_options[:file_size] = help.number_to_human_size check_value
default_message = options[MESSAGES[key]]
errors_options[:message] ||= default_message if default_message
record.errors.add(attribute, MESSAGES[key], errors_options)
end
end
def help
Helper.instance
end
class Helper
include Singleton
include ActionView::Helpers::NumberHelper
end
end

20
app/lib/github/api.rb Normal file
View file

@ -0,0 +1,20 @@
class Github::API
def self.base_uri
'https://api.github.com'
end
def self.latest_release
call '/repos/sgmap/tps/releases/latest'
end
private
def self.call(end_point, params = {})
RestClient::Resource.new(
base_uri+end_point, timeout: 5
).get(params: params)
rescue RestClient::Forbidden
nil
end
end

View file

@ -0,0 +1,11 @@
class Github::Releases
def self.latest
latest_release = Github::API.latest_release
return nil if latest_release.nil?
release = Hashie::Mash.new JSON.parse(latest_release)
release.published_at = release.published_at.to_date.strftime('%d/%m/%Y')
release
end
end

43
app/lib/siade/api.rb Normal file
View file

@ -0,0 +1,43 @@
class SIADE::API
class << self
attr_accessor :token
end
def initialize
end
def self.entreprise(siren)
endpoint = "/v2/entreprises/#{siren}"
call(base_url + endpoint)
end
def self.etablissement(siret)
endpoint = "/v2/etablissements/#{siret}"
call(base_url + endpoint)
end
def self.exercices(siret)
endpoint = "/v1/etablissements/exercices/#{siret}"
call(base_url + endpoint)
end
def self.rna(siret)
endpoint = "/v1/associations/#{siret}"
call(base_url + endpoint)
end
def self.call(url, params = {})
params.merge!(token: SIADETOKEN)
verify_ssl_mode = OpenSSL::SSL::VERIFY_NONE
RestClient::Resource.new(
url,
verify_ssl: verify_ssl_mode
).get(params: params)
end
def self.base_url
SIADEURL
end
end

View file

@ -0,0 +1,45 @@
class SIADE::EntrepriseAdapter
def initialize(siren)
@siren = siren
end
def data_source
@data_source ||= JSON.parse(SIADE::API.entreprise(@siren), symbolize_names: true)
rescue
@data_source = nil
end
def to_params
params = {}
data_source[:entreprise].each do |k, v|
params[k] = v if attr_to_fetch.include?(k)
end
params[:date_creation] = Time.at(params[:date_creation]).to_datetime
params
rescue
nil
end
def attr_to_fetch
[:siren,
:capital_social,
:numero_tva_intracommunautaire,
:forme_juridique,
:forme_juridique_code,
:nom_commercial,
:raison_sociale,
:siret_siege_social,
:code_effectif_entreprise,
:date_creation,
:nom,
:prenom]
end
def mandataires_sociaux
data_source[:entreprise][:mandataires_sociaux]
rescue
nil
end
end

View file

@ -0,0 +1,50 @@
class SIADE::EtablissementAdapter
def initialize(siret)
@siret = siret
end
def data_source
@data_source ||= JSON.parse(SIADE::API.etablissement(@siret), symbolize_names: true)
end
def to_params
params = {}
data_source[:etablissement].each do |k, v|
params[k] = v if attr_to_fetch.include?(k)
end
params[:adresse] = adresse
data_source[:etablissement][:adresse].each do |k, v|
params[k] = v if address_attribut_to_fetch.include?(k)
end
params
rescue
nil
end
def attr_to_fetch
[:siret,
:siege_social,
:naf,
:libelle_naf
]
end
def adresse
adresse = ''
[:l1, :l2, :l3, :l4, :l5, :l6, :l7].each do |line|
adresse = adresse + data_source[:etablissement][:adresse][line] + "\r\n" unless data_source[:etablissement][:adresse][line].nil?
end
adresse
end
def address_attribut_to_fetch
[:numero_voie,
:type_voie,
:nom_voie,
:complement_adresse,
:code_postal,
:localite,
:code_insee_localite]
end
end

View file

@ -0,0 +1,23 @@
class SIADE::ExercicesAdapter
def initialize(siret)
@siret = siret
end
def data_source
@data_source ||= JSON.parse(SIADE::API.exercices(@siret), symbolize_names: true)
rescue
@data_source = nil
end
def to_params
data_source[:exercices]
rescue
nil
end
def attr_to_fetch
[:ca,
:dateFinExercice,
:date_fin_exercice_timestamp]
end
end

View file

@ -0,0 +1,35 @@
class SIADE::RNAAdapter
def initialize(siret)
@siret = siret
end
def data_source
@data_source ||= JSON.parse(SIADE::API.rna(@siret), symbolize_names: true)
end
def to_params
params = {}
data_source[:association].each do |k, v|
params[k] = v if attr_to_fetch.include?(k)
end
params[:association_id] = params[:id]
params.delete(:id)
params
rescue
nil
end
def attr_to_fetch
[:id,
:titre,
:objet,
:date_creation,
:date_declaration,
:date_publication
]
end
end

0
app/lib/tasks/.keep Normal file
View file

View file

@ -0,0 +1,114 @@
namespace :cloudstorage do
task init: :environment do
os_config = (YAML.load_file(Fog.credentials_path))['default']
@os = OpenStack::Connection.create(
{
username: os_config['openstack_username'],
api_key: os_config['openstack_api_key'],
auth_method: "password",
auth_url: "https://auth.cloud.ovh.net/v2.0/",
authtenant_name: os_config['openstack_tenant'],
service_type: "object-store",
region: os_config['openstack_region']
}
)
@cont = @os.container(CarrierWave::Uploader::Base.fog_directory)
end
desc 'Move local attestations on cloud storage'
task migrate: :environment do
puts 'Starting migration'
Rake::Task['cloudstorage:init'].invoke
error_count = 0
[Cerfa, PieceJustificative, Procedure].each { |c|
c.all.each { |entry|
content = (c == Procedure) ? entry.logo : entry.content
unless content.current_path.nil? || File.exist?(File.dirname(content.current_path) + '/uploaded')
secure_token = SecureRandom.uuid
filename = "#{entry.class.to_s.underscore}-#{secure_token}#{File.extname(content.current_path)}"
puts "Uploading #{content.current_path}"
begin
@cont.create_object(filename, {}, File.open(content.current_path))
File.open(File.dirname(content.current_path) + '/uploaded', "w+") { |f| f.write(File.basename(content.current_path)) }
File.open(File.dirname(content.current_path) + '/filename_cloudstorage', "w+") { |f| f.write(filename) }
File.open(File.dirname(content.current_path) + '/secure_token_cloudstorage', "w+") { |f| f.write(secure_token) }
entry.update_column(c == Procedure ? :logo : :content, filename)
entry.update_column(c == Procedure ? :logo_secure_token : :content_secure_token, secure_token)
rescue Errno::ENOENT
puts "ERROR: #{content.current_path} does not exist!"
File.open('upload_errors.report', "a+") { |f| f.write(content.current_path) }
error_count += 1
end
else
if !content.current_path.nil? && File.exist?(File.dirname(content.current_path) + '/uploaded')
filename = File.open(File.dirname(content.current_path) + '/filename_cloudstorage', "r").read
secure_token = File.open(File.dirname(content.current_path) + '/secure_token_cloudstorage', "r").read
entry.update_column(c == Procedure ? :logo : :content, filename)
entry.update_column(c == Procedure ? :logo_secure_token : :content_secure_token, secure_token)
puts "RESTORE IN DATABASE: #{filename} "
elsif !content.current_path.nil?
puts "Skipping #{content.current_path}"
end
end
}
}
puts "There were #{error_count} errors while uploading files. See upload_errors.report file for details."
puts 'Enf of migration'
end
desc 'Clear documents in tenant and revert file entries in database'
task :revert do
Rake::Task['cloudstorage:init'].invoke
[Cerfa, PieceJustificative, Procedure].each { |c|
c.all.each { |entry|
content = (c == Procedure) ? entry.logo : entry.content
unless content.current_path.nil?
if File.exist?(File.dirname(content.current_path) + '/uploaded')
previous_filename = File.read(File.dirname(content.current_path) + '/uploaded')
entry.update_column(c == Procedure ? :logo : :content, previous_filename)
entry.update_column(c == Procedure ? :logo_secure_token : :content_secure_token, nil)
puts "restoring #{content.current_path} db data to #{previous_filename}"
@cont.delete_object(File.open(File.dirname(content.current_path) + '/filename_cloudstorage', "r").read)
FileUtils.rm(File.dirname(content.current_path) + '/uploaded')
FileUtils.rm(File.dirname(content.current_path) + '/filename_cloudstorage')
FileUtils.rm(File.dirname(content.current_path) + '/secure_token_cloudstorage')
end
end
}
}
end
desc 'Clear old documents in tenant'
task :clear do
Rake::Task['cloudstorage:init'].invoke
@cont.objects.each { |object|
puts "Removing #{object}"
@cont.delete_object(object)
}
end
task :clear_old_objects do
Rake::Task['cloudstorage:init'].invoke
@cont.objects_detail.each { |object, details|
last_modified = DateTime.parse(details[:last_modified])
@cont.delete_object(object) unless last_modified.utc > (Time.now - 2.year).utc
}
end
end

65
app/lib/tasks/dev.rake Normal file
View file

@ -0,0 +1,65 @@
namespace :dev do
desc 'Initialise dev environment'
task :init do
puts 'start initialisation'
Rake::Task['dev:generate_token_file'].invoke
Rake::Task['dev:generate_franceconnect_file'].invoke
Rake::Task['dev:generate_fog_credentials_file'].invoke
Rake::Task['dev:generate_features_file'].invoke
puts 'end initialisation'
end
task :generate_token_file do
puts 'creating token.rb file'
res = `rake secret`.gsub("\n", '')
file = File.new('config/initializers/token.rb', 'w+')
comment = <<EOF
EOF
file.write(comment)
file.write("TPS::Application.config.SIADETOKEN = '#{res}'")
file.close
end
task :generate_franceconnect_file do
file = File.new('config/france_connect.yml', 'w+')
comment = <<EOF
particulier_identifier: plop
particulier_secret: plip
particulier_redirect_uri: 'http://localhost:3000/france_connect/particulier/callback'
particulier_authorization_endpoint: 'https://fcp.integ01.dev-franceconnect.fr/api/v1/authorize'
particulier_token_endpoint: 'https://fcp.integ01.dev-franceconnect.fr/api/v1/token'
particulier_userinfo_endpoint: 'https://fcp.integ01.dev-franceconnect.fr/api/v1/userinfo'
particulier_logout_endpoint: 'https://fcp.integ01.dev-franceconnect.fr/api/v1/logout'
EOF
file.write(comment)
file.close
end
task :generate_fog_credentials_file do
puts 'creating fog_credentials.test.yml file'
content = <<EOF
default:
openstack_tenant: "ovh_fake_tenant_name"
openstack_api_key: "ovh_fake_password"
openstack_username: "ovh_fake_username"
openstack_auth_url: "https://auth.cloud.ovh.net/v2.0/tokens"
openstack_region: "SBG1"
EOF
file = File.new("config/fog_credentials.test.yml", "w+")
file.write(content)
file.close
end
task :generate_features_file do
puts 'creating features.yml file'
content = <<EOF
remote_storage: true
EOF
file = File.new("config/initializers/features.yml", "w+")
file.write(content)
file.close
end
end

View file

@ -0,0 +1,118 @@
require 'csv'
require 'json'
namespace :opensimplif_import do
task :import_all => :environment do
puts 'start opensimplif'
Rake::Task['opensimplif_import:import_proposition'].invoke
Rake::Task['opensimplif_import:import_piste'].invoke
Rake::Task['opensimplif_import:import_mesure'].invoke
puts 'end import opensimplif'
end
task :import_proposition do
file_path = "lib/tasks/161102_OS_Inputs_test_propositions.csv"
procedure_id = 35
matching = [
{id: 44, key: 'Intitulé de la proposition'},
{id: 43, key: 'Champ concerné'},
{id: 45, key: 'Champ ministériel chef de file'},
{id: 59, key: 'Date de la proposition'},
{id: 60, key: 'Moment de vie'},
{id: 61, key: 'Source'},
{id: 48, key: 'Description de la proposition'}
]
puts 'start propositions'
import file_path, procedure_id, matching
puts 'done propositions'
end
task :import_piste do
file_path = "lib/tasks/161102_OS_Inputs_test_pistes.csv"
procedure_id = 36
matching = [
{id: 81, key: 'Intitulé de la piste *'},
{id: 82, key: 'Usager concerné *'},
{id: 83, key: 'Champ ministériel chef de file *'},
{id: 84, key: 'Champ ministériel contributeur'},
{id: 85, key: 'Date de saisine'},
{id: 66, key: 'Moment de vie'},
{id: 80, key: 'Source de la piste'},
{id: 70, key: 'Description de la piste '},
{id: 68, key: 'Objectifs / bénéfices attendus'},
{id: 65, key: 'Description détaillée des démarches impactées par la piste'},
{id: 69, key: 'Levier de mise en oeuvre'},
{id: 67, key: 'Précision sur le levier de meo'},
{id: 64, key: 'Calendrier de mise en oeuvre'}
]
puts 'start piste'
import file_path, procedure_id, matching
puts 'done pistes'
end
task :import_mesure do
file_path = "lib/tasks/161102_OS_Inputs_test_mesures.csv"
procedure_id = 37
matching = [
{id: 107, key: 'Intitulé projet / mesure'},
{id: 104, key: 'Champ concerné'},
{id: 105, key: 'Champ ministériel chef de file'},
{id: 112, key: 'Direction chef de file'},
{id: 106, key: 'Champ ministériel contributeur'},
{id: 113, key: 'Direction contributrice'},
{id: 92, key: 'Moment de vie'},
{id: 109, key: 'Date d\'annonce'},
{id: 114, key: 'N° de la mesure'},
{id: 115, key: 'Responsable ministère'},
{id: 116, key: 'Responsable SGMAP'},
{id: 89, key: 'Actions réalisées'},
{id: 95, key: 'Etapes nécessaires à l\'atteinte de la cible et alertes'},
{id: 102, key: 'Alertes'},
{id: 101, key: 'Échéance initiale'},
{id: 96, key: 'Échéance prévisionnelle / réelle'},
{id: 94, key: 'Appréciation avancement'},
{id: 91, key: 'Etat d\'avancement LOLF'},
{id: 111, key: '§ de com'}
]
puts 'start mesures'
import file_path, procedure_id, matching
puts 'done mesures'
end
def self.import file_path, procedure_id, matching
user = User.find_or_create_by(email: 'import@opensimplif.modernisation.fr')
unless user.valid?
user.password = 'TPSpassword2016'
user.save
end
file ||= CSV.open(file_path, :col_sep => ";", :headers => true).map { |x| x.to_h }.to_json
file = JSON.parse(file)
procedure = Procedure.find(procedure_id)
user.dossiers.where(procedure_id: procedure.id).destroy_all
file.each do |proposition|
dossier = Dossier.create procedure: procedure, user: user, state: :initiated
dossier.champs.each do |champ|
matching.each do |match|
if match[:id] == champ.type_de_champ.id
champ.update_column :value, proposition[match[:key]]
break
end
end
end
end
end
end