zuora_connect 2.1.1 → 3.0.0.pre.e
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/app/controllers/zuora_connect/static_controller.rb +84 -17
- data/app/models/zuora_connect/app_instance_base.rb +175 -106
- data/app/models/zuora_connect/zuora_user.rb +1 -1
- data/config/initializers/postgresql_adapter.rb +71 -1
- data/config/initializers/prometheus.rb +80 -23
- data/config/initializers/redis.rb +4 -4
- data/config/initializers/resque.rb +14 -12
- data/config/initializers/unicorn.rb +30 -2
- data/config/routes.rb +5 -1
- data/lib/metrics/net.rb +7 -7
- data/lib/middleware/json_parse_errors.rb +13 -2
- data/lib/middleware/metrics_middleware.rb +48 -72
- data/lib/resque/dynamic_queues.rb +1 -1
- data/lib/resque/plugins/app_instance_job.rb +6 -10
- data/lib/zuora_connect.rb +6 -63
- data/lib/zuora_connect/controllers/helpers.rb +229 -89
- data/lib/zuora_connect/engine.rb +2 -1
- data/lib/zuora_connect/railtie.rb +6 -64
- data/lib/zuora_connect/version.rb +1 -1
- data/lib/zuora_connect/zuora_audit.rb +31 -0
- metadata +19 -7
- data/app/models/zuora_connect/telegraf.rb +0 -97
- data/lib/logging/connect_formatter.rb +0 -44
- data/lib/metrics/influx/point_value.rb +0 -79
@@ -12,14 +12,14 @@ module Resque
|
|
12
12
|
when "Hash"
|
13
13
|
data = args.merge({:worker_class => self.to_s})
|
14
14
|
end
|
15
|
-
if Rails.logger.is_a?(Ougai::Logger)
|
15
|
+
if Rails.logger.is_a?(Ougai::Logger)
|
16
16
|
Rails.logger.with_fields = {job: data, trace_id: SecureRandom.uuid, name: "RailsWorker"}
|
17
17
|
end
|
18
18
|
|
19
19
|
begin
|
20
|
-
connection_count ||= 0
|
20
|
+
connection_count ||= 0
|
21
21
|
@appinstance = ZuoraConnect::AppInstance.find(args['app_instance_id'].to_i)
|
22
|
-
|
22
|
+
Rails.logger.info('Starting job')
|
23
23
|
|
24
24
|
@appinstance.new_session(holding_pattern: true)
|
25
25
|
rescue ActiveRecord::RecordNotFound => exception
|
@@ -52,12 +52,12 @@ module Resque
|
|
52
52
|
return
|
53
53
|
rescue ZuoraConnect::Exceptions::ConnectCommunicationError => exception
|
54
54
|
Rails.logger.warn("Enqueue Job Again ~ 2 mins", exception)
|
55
|
-
@appinstance.queue_pause(time: 2.minutes.to_i)
|
55
|
+
@appinstance.queue_pause(time: 2.minutes.to_i)
|
56
56
|
Resque.enqueue_to(self.job.queue, self.job.payload['class'], args)
|
57
57
|
return
|
58
58
|
rescue Net::ReadTimeout, Net::OpenTimeout, Errno::ECONNRESET, Errno::ECONNREFUSED, SocketError => exception
|
59
59
|
Rails.logger.warn("Enqueue Job Again ~ 2 mins", exception)
|
60
|
-
@appinstance.queue_pause(time: 2.minutes.to_i)
|
60
|
+
@appinstance.queue_pause(time: 2.minutes.to_i)
|
61
61
|
Resque.enqueue_to(self.job.queue, self.job.payload['class'], args)
|
62
62
|
return
|
63
63
|
end
|
@@ -68,10 +68,6 @@ module Resque
|
|
68
68
|
@appinstance.cache_app_instance if defined?(@appinstance)
|
69
69
|
Rails.logger.flush if Rails.logger.methods.include?(:flush)
|
70
70
|
end
|
71
|
-
|
72
|
-
def job_start_log(args)
|
73
|
-
Rails.logger.info("Starting job")
|
74
|
-
end
|
75
71
|
end
|
76
72
|
end
|
77
|
-
end
|
73
|
+
end
|
data/lib/zuora_connect.rb
CHANGED
@@ -9,10 +9,12 @@ require 'resque/silence_done'
|
|
9
9
|
require 'resque/self_lookup'
|
10
10
|
require 'resque/plugins/custom_logger'
|
11
11
|
require 'resque/plugins/app_instance_job'
|
12
|
-
require 'logging/connect_formatter'
|
13
|
-
require 'metrics/influx/point_value'
|
14
12
|
require 'metrics/net'
|
15
13
|
require 'mono_logger'
|
14
|
+
require 'zuora_connect/zuora_audit'
|
15
|
+
require 'active_record'
|
16
|
+
require 'zuora_observability'
|
17
|
+
::ActiveRecord::Base.send :include, ZuoraConnect::ZuoraAudit
|
16
18
|
|
17
19
|
module ZuoraConnect
|
18
20
|
class << self
|
@@ -26,68 +28,9 @@ module ZuoraConnect
|
|
26
28
|
when 'test'
|
27
29
|
Rails.logger
|
28
30
|
else
|
29
|
-
@logger ||= custom_logger(name: "Connect", level: Rails.logger.level)
|
31
|
+
@logger ||= ZuoraObservability::Logger.custom_logger(name: "Connect", level: Rails.logger.level)
|
30
32
|
end
|
31
33
|
end
|
32
|
-
|
33
|
-
def custom_logger(name: "", level: Rails.logger.present? ? Rails.logger.level : MonoLogger::INFO, type: :ougai)
|
34
|
-
#puts name + ' - ' + {Logger::WARN => 'Logger::WARN', Logger::ERROR => 'Logger::ERROR', Logger::DEBUG => 'Logger::DEBUG', Logger::INFO => 'Logger::INFO' }[level] + ' - '
|
35
|
-
if type == :ougai
|
36
|
-
require 'ougai'
|
37
|
-
require "ougai/formatters/customizable"
|
38
|
-
#logger = Ougai::Logger.new(MonoLogger.new(STDOUT))
|
39
|
-
logger = Ougai::Logger.new(STDOUT)
|
40
|
-
logger.level = level
|
41
|
-
if ZuoraConnect.configuration.json_logging
|
42
|
-
logger.formatter = Ougai::Formatters::ConnectFormatter.new(name)
|
43
|
-
logger.before_log = lambda do |data|
|
44
|
-
data[:trace_id] = ZuoraConnect::RequestIdMiddleware.request_id if ZuoraConnect::RequestIdMiddleware.request_id.present?
|
45
|
-
data[:zuora_trace_id] = ZuoraConnect::RequestIdMiddleware.zuora_request_id if ZuoraConnect::RequestIdMiddleware.zuora_request_id.present?
|
46
|
-
#data[:traces] = {amazon_id: data[:trace_id], zuora_id: data[:zuora_trace_id]}
|
47
|
-
end
|
48
|
-
else
|
49
|
-
logger.formatter = Ougai::Formatters::Customizable.new(
|
50
|
-
format_err: proc do |data|
|
51
|
-
next nil unless data.key?(:err)
|
52
|
-
err = data.delete(:err)
|
53
|
-
" #{err[:name]} (#{err[:message]})\n #{err[:stack]}"
|
54
|
-
end,
|
55
|
-
format_data: proc do |data|
|
56
|
-
data.delete(:app_instance_id); data.delete(:tenant_ids); data.delete(:organization); data.delete(:environment)
|
57
|
-
format('%s %s: %s', 'DATA'.ljust(6), Time.now.strftime('%FT%T.%6NZ'), "#{data.to_json}") if data.present?
|
58
|
-
end,
|
59
|
-
format_msg: proc do |severity, datetime, _progname, data|
|
60
|
-
msg = data.delete(:msg)
|
61
|
-
format('%s %s: %s', severity.ljust(6), datetime, msg)
|
62
|
-
end
|
63
|
-
)
|
64
|
-
logger.formatter.datetime_format = '%FT%T.%6NZ'
|
65
|
-
end
|
66
|
-
else
|
67
|
-
logger = MonoLogger.new(STDOUT)
|
68
|
-
logger.level = level
|
69
|
-
logger.formatter = proc do |serverity, datetime, progname, msg|
|
70
|
-
begin
|
71
|
-
msg = JSON.parse(msg)
|
72
|
-
rescue JSON::ParserError => ex
|
73
|
-
end
|
74
|
-
if ZuoraConnect.configuration.json_logging
|
75
|
-
require 'json'
|
76
|
-
store = {
|
77
|
-
name: name,
|
78
|
-
level: serverity,
|
79
|
-
timestamp: datetime.strftime('%FT%T.%6NZ'),
|
80
|
-
pid: Process.pid,
|
81
|
-
message: name == "ActionMailer" ? msg.strip : msg
|
82
|
-
}
|
83
|
-
JSON.dump(store) + "\n"
|
84
|
-
else
|
85
|
-
format('%s %s: %s', serverity.ljust(6), datetime, msg) + "\n"
|
86
|
-
end
|
87
|
-
end
|
88
|
-
end
|
89
|
-
return logger
|
90
|
-
end
|
91
34
|
end
|
92
35
|
|
93
36
|
module Controllers
|
@@ -144,7 +87,7 @@ module ZuoraConnect
|
|
144
87
|
verify_server_cert: false,
|
145
88
|
log_level: Logger::INFO,
|
146
89
|
service_name: ENV['DEIS_APP'].present? ? ENV['DEIS_APP'] : Rails.application.class.parent_name,
|
147
|
-
logger:
|
90
|
+
logger: ZuoraObservability::Logger.custom_logger(name: "ElasticAPM", level: MonoLogger::WARN)
|
148
91
|
})
|
149
92
|
defaults.merge!({disable_send: true}) if defined?(Rails::Console)
|
150
93
|
|
@@ -124,16 +124,22 @@ module ZuoraConnect
|
|
124
124
|
ElasticAPM.set_user(session["#{@appinstance.id}::user::email"]) if defined?(ElasticAPM) && ElasticAPM.running?
|
125
125
|
PaperTrail.whodunnit = session["#{@appinstance.id}::user::email"] if defined?(PaperTrail)
|
126
126
|
end
|
127
|
+
|
128
|
+
locale = (session["#{@appinstance.id}::user::locale"] || "").gsub("_", "-")
|
127
129
|
begin
|
128
|
-
locale = session["#{@appinstance.id}::user::locale"]
|
129
130
|
I18n.locale = locale.present? ? locale : @appinstance.locale
|
130
131
|
rescue I18n::InvalidLocale => ex
|
132
|
+
if locale.include?("-")
|
133
|
+
locale = locale.split("-").first
|
134
|
+
retry
|
135
|
+
elsif locale != session["#{@appinstance.id}::user::language"]
|
136
|
+
locale = session["#{@appinstance.id}::user::language"]
|
137
|
+
retry
|
138
|
+
end
|
131
139
|
ZuoraConnect.logger.error(ex) if !ZuoraConnect::AppInstance::IGNORED_LOCALS.include?(ex.locale.to_s.downcase)
|
132
140
|
end
|
133
|
-
|
134
|
-
|
135
|
-
rescue
|
136
|
-
ZuoraConnect.logger.error(ex)
|
141
|
+
if @appinstance.user_timezone.blank?
|
142
|
+
@appinstance.set_timezone(timezone: session["#{@appinstance.id}::user::timezone"], type: :default)
|
137
143
|
end
|
138
144
|
end
|
139
145
|
rescue ZuoraConnect::Exceptions::InvalidCredentialSet => ex
|
@@ -219,6 +225,80 @@ module ZuoraConnect
|
|
219
225
|
return (request.headers['ZuoraCurrentEntity'].present? || cookies['ZuoraCurrentEntity'].present?)
|
220
226
|
end
|
221
227
|
|
228
|
+
def create_new_instance
|
229
|
+
ZuoraConnect::AppInstance.read_master_db do
|
230
|
+
Thread.current[:appinstance] = nil
|
231
|
+
ZuoraConnect.logger.with_fields = {} if ZuoraConnect.logger.is_a?(Ougai::Logger)
|
232
|
+
Rails.logger.with_fields = {} if Rails.logger.is_a?(Ougai::Logger)
|
233
|
+
|
234
|
+
if defined?(ElasticAPM) && ElasticAPM.running? && ElasticAPM.respond_to?(:set_label)
|
235
|
+
ElasticAPM.set_label(:trace_id, request.uuid)
|
236
|
+
end
|
237
|
+
|
238
|
+
zuora_host = request.headers['zuora-host']
|
239
|
+
zuora_entity_id = (request.headers['zuora-entity-ids'] || '').gsub(
|
240
|
+
'-',
|
241
|
+
''
|
242
|
+
).split(',').first
|
243
|
+
|
244
|
+
# Validate host present
|
245
|
+
if zuora_host.blank?
|
246
|
+
render json: {
|
247
|
+
status: 401,
|
248
|
+
message: 'zuora-host header was not supplied.'
|
249
|
+
}, status: :unauthorized
|
250
|
+
return
|
251
|
+
end
|
252
|
+
|
253
|
+
# Validate entity-ids present
|
254
|
+
if zuora_entity_id.blank?
|
255
|
+
render json: {
|
256
|
+
status: 401,
|
257
|
+
message: 'zuora-entity-ids header was not supplied.'
|
258
|
+
}, status: :unauthorized
|
259
|
+
return
|
260
|
+
end
|
261
|
+
|
262
|
+
rest_domain = ZuoraAPI::Login.new(url: "https://#{zuora_host}").rest_domain
|
263
|
+
app_instance_id = ZuoraConnect::AppInstance.where(
|
264
|
+
'zuora_entity_ids ?& array[:entities] AND zuora_domain = :host',
|
265
|
+
entities: [zuora_entity_id],
|
266
|
+
host: rest_domain
|
267
|
+
).pluck(:id).first
|
268
|
+
|
269
|
+
if app_instance_id.present?
|
270
|
+
render json: {
|
271
|
+
status: 409,
|
272
|
+
message: 'Instance already exists.',
|
273
|
+
app_instance_id: app_instance_id
|
274
|
+
}, status: 409
|
275
|
+
else
|
276
|
+
Apartment::Tenant.switch!("public")
|
277
|
+
retry_count = 3
|
278
|
+
begin
|
279
|
+
@appinstance = new_instance(
|
280
|
+
next_instance_id,
|
281
|
+
zuora_entity_id,
|
282
|
+
rest_domain,
|
283
|
+
retry_count: retry_count
|
284
|
+
)
|
285
|
+
rescue ActiveRecord::RecordNotUnique
|
286
|
+
retry if (retry_count -= 1).positive?
|
287
|
+
return
|
288
|
+
end
|
289
|
+
|
290
|
+
app_instance_id = @appinstance.id
|
291
|
+
end
|
292
|
+
|
293
|
+
begin
|
294
|
+
Apartment::Tenant.switch!('public')
|
295
|
+
Apartment::Tenant.create(app_instance_id.to_s)
|
296
|
+
rescue Apartment::TenantExists
|
297
|
+
ZuoraConnect.logger.debug('Tenant Already Exists')
|
298
|
+
end
|
299
|
+
end
|
300
|
+
end
|
301
|
+
|
222
302
|
private
|
223
303
|
def setup_instance_via_prod_mode
|
224
304
|
zuora_entity_id = request.headers['ZuoraCurrentEntity'] || cookies['ZuoraCurrentEntity']
|
@@ -226,7 +306,7 @@ module ZuoraConnect
|
|
226
306
|
if zuora_entity_id.present?
|
227
307
|
zuora_tenant_id = cookies['Zuora-Tenant-Id']
|
228
308
|
zuora_user_id = cookies['Zuora-User-Id']
|
229
|
-
zuora_host = request.headers[
|
309
|
+
zuora_host = request.headers['HTTP_X_FORWARDED_HOST'] || request.headers['Zuora-Host'] || 'apisandbox.zuora.com'
|
230
310
|
|
231
311
|
zuora_details = {'host' => zuora_host, 'user_id' => zuora_user_id, 'tenant_id' => zuora_tenant_id, 'entity_id' => zuora_entity_id}
|
232
312
|
auth_headers = {}
|
@@ -328,13 +408,16 @@ module ZuoraConnect
|
|
328
408
|
|
329
409
|
zuora_user_id = cookies['Zuora-User-Id'] || session["ZuoraCurrentIdentity"]['userId']
|
330
410
|
|
331
|
-
#One deployed instance
|
332
411
|
if appinstances.size == 1
|
333
412
|
ZuoraConnect.logger.debug("Instance is #{appinstances.to_h.keys.first}")
|
334
413
|
@appinstance = ZuoraConnect::AppInstance.find(appinstances.to_h.keys.first)
|
414
|
+
end
|
335
415
|
|
416
|
+
# One deployed instance with credentials
|
417
|
+
if defined?(@appinstance) && !@appinstance['zuora_logins'].nil?
|
336
418
|
#Add user/update
|
337
419
|
begin
|
420
|
+
ZuoraConnect::ZuoraUser.reset_table_name
|
338
421
|
@zuora_user = ZuoraConnect::ZuoraUser.where(:zuora_user_id => zuora_user_id).first
|
339
422
|
rescue ActiveRecord::StatementInvalid => ex
|
340
423
|
if ex.message.include?("PG::UndefinedTable") && ex.message.include?("zuora_users")
|
@@ -355,10 +438,12 @@ module ZuoraConnect
|
|
355
438
|
@zuora_user = ZuoraConnect::ZuoraUser.create!(:zuora_user_id => zuora_user_id, :zuora_identity_response => {zuora_entity_id => session["ZuoraCurrentIdentity"]})
|
356
439
|
end
|
357
440
|
@zuora_user.session = session
|
441
|
+
ZuoraConnect::ZuoraUser.current_user_id = zuora_user_id
|
358
442
|
session["#{@appinstance.id}::user::localUserId"] = @zuora_user.id
|
359
443
|
session["#{@appinstance.id}::user::email"] = session['ZuoraCurrentIdentity']["username"]
|
360
444
|
session["#{@appinstance.id}::user::timezone"] = session['ZuoraCurrentIdentity']["timeZone"]
|
361
|
-
session["#{@appinstance.id}::user::
|
445
|
+
session["#{@appinstance.id}::user::language"] = session['ZuoraCurrentIdentity']["language"]
|
446
|
+
session["#{@appinstance.id}::user::locale"] = session['ZuoraCurrentIdentity']["locale"]
|
362
447
|
session["appInstance"] = @appinstance.id
|
363
448
|
|
364
449
|
#We have multiple, user must pick
|
@@ -380,79 +465,85 @@ module ZuoraConnect
|
|
380
465
|
return
|
381
466
|
end
|
382
467
|
Apartment::Tenant.switch!("public")
|
383
|
-
|
384
|
-
|
385
|
-
|
468
|
+
retry_count = 3
|
469
|
+
task_data = {}
|
470
|
+
begin
|
471
|
+
ActiveRecord::Base.transaction do
|
472
|
+
ActiveRecord::Base.connection.execute('LOCK public.zuora_users IN ACCESS EXCLUSIVE MODE')
|
386
473
|
|
387
|
-
|
388
|
-
|
389
|
-
return
|
390
|
-
end
|
474
|
+
unless defined?(@appinstance)
|
475
|
+
appinstances = ZuoraConnect::AppInstance.where("zuora_entity_ids ?& array[:entities] = true AND zuora_domain = :host", entities: [zuora_entity_id], host: zuora_client.rest_domain).pluck(:id, :name)
|
391
476
|
|
392
|
-
|
393
|
-
|
394
|
-
|
395
|
-
|
396
|
-
|
397
|
-
'customAuthorities' => [],
|
398
|
-
'additionalInformation' => {
|
399
|
-
'description' => "This user is for #{user} application.",
|
400
|
-
'name' => "#{user} API User #{next_id}"
|
401
|
-
}
|
402
|
-
}
|
403
|
-
|
404
|
-
oauth_response, response = zuora_client.rest_call(
|
405
|
-
method: :post,
|
406
|
-
body: body.to_json,
|
407
|
-
url: zuora_client.rest_endpoint("genesis/clients").gsub('v1/', ''),
|
408
|
-
session_type: zuora_client.class == ZuoraAPI::Oauth ? :bearer : :basic,
|
409
|
-
headers: auth_headers
|
410
|
-
)
|
477
|
+
if appinstances.size > 0
|
478
|
+
redirect_to "https://#{zuora_host}/apps/newlogin.do?retURL=#{request.fullpath}"
|
479
|
+
return
|
480
|
+
end
|
481
|
+
end
|
411
482
|
|
412
|
-
|
413
|
-
|
414
|
-
|
415
|
-
|
416
|
-
|
417
|
-
|
483
|
+
next_id = defined?(@appinstance) ? @appinstance.id : next_instance_id
|
484
|
+
if task_data.blank?
|
485
|
+
user = (ENV['DEIS_APP'] || "Application").split('-').map(&:capitalize).join(' ')
|
486
|
+
body = {
|
487
|
+
'userId' => zuora_user_id,
|
488
|
+
'entityIds' => [zuora_entity_id.unpack("a8a4a4a4a12").join('-')],
|
489
|
+
'customAuthorities' => [],
|
490
|
+
'additionalInformation' => {
|
491
|
+
'description' => "This user is for #{user} application.",
|
492
|
+
'name' => "#{user} API User #{next_id}"
|
493
|
+
}
|
494
|
+
}
|
495
|
+
|
496
|
+
oauth_response, response = zuora_client.rest_call(
|
497
|
+
method: :post,
|
498
|
+
body: body.to_json,
|
499
|
+
url: zuora_client.rest_endpoint("genesis/clients").gsub('v1/', ''),
|
500
|
+
session_type: zuora_client.class == ZuoraAPI::Oauth ? :bearer : :basic,
|
501
|
+
headers: auth_headers
|
502
|
+
)
|
503
|
+
|
504
|
+
new_zuora_client = ZuoraAPI::Oauth.new(url: "https://#{zuora_host}", oauth_client_id: oauth_response["clientId"], oauth_secret: oauth_response["clientSecret"] )
|
505
|
+
if session["ZuoraCurrentUserInfo"].blank?
|
506
|
+
client_describe, response = new_zuora_client.rest_call(url: zuora_client.rest_endpoint("genesis/user/info").gsub('v1/', ''), session_type: :bearer)
|
507
|
+
else
|
508
|
+
client_describe = session["ZuoraCurrentUserInfo"]
|
509
|
+
end
|
418
510
|
|
419
|
-
|
420
|
-
|
421
|
-
|
422
|
-
|
423
|
-
|
424
|
-
|
425
|
-
|
426
|
-
|
427
|
-
|
428
|
-
|
429
|
-
|
430
|
-
|
431
|
-
|
432
|
-
|
433
|
-
|
434
|
-
|
435
|
-
|
436
|
-
|
437
|
-
|
438
|
-
|
439
|
-
|
440
|
-
|
441
|
-
|
442
|
-
rescue ActiveRecord::RecordNotUnique => ex
|
443
|
-
if (retry_count += 1) < 3
|
444
|
-
@appinstance.assign_attributes({:api_token => rand(36**64).to_s(36), :token => rand(36**64).to_s(36)})
|
445
|
-
retry
|
511
|
+
available_entities = client_describe["accessibleEntities"].select {|entity| entity['id'] == zuora_entity_id}
|
512
|
+
task_data = {
|
513
|
+
"id": next_id,
|
514
|
+
"name": client_describe["tenantName"],
|
515
|
+
"mode": "Collections",
|
516
|
+
"status": "Running",
|
517
|
+
ZuoraConnect::AppInstance::LOGIN_TENANT_DESTINATION => {
|
518
|
+
"tenant_type": "Zuora",
|
519
|
+
"username": session["ZuoraCurrentIdentity"]["username"],
|
520
|
+
"url": new_zuora_client.url,
|
521
|
+
"status": "Active",
|
522
|
+
"oauth_client_id": oauth_response['clientId'],
|
523
|
+
"oauth_secret": oauth_response['clientSecret'],
|
524
|
+
"authentication_type": "OAUTH",
|
525
|
+
"entities": available_entities.map {|e| e.merge({'displayName' => client_describe["tenantName"]})}
|
526
|
+
},
|
527
|
+
"tenant_ids": available_entities.map{|e| e['entityId']}.uniq,
|
528
|
+
}
|
529
|
+
end
|
530
|
+
|
531
|
+
if defined?(@appinstance)
|
532
|
+
@appinstance.zuora_logins = task_data
|
533
|
+
@appinstance.save(:validate => false)
|
446
534
|
else
|
447
|
-
|
448
|
-
|
449
|
-
|
450
|
-
|
451
|
-
:
|
452
|
-
|
453
|
-
|
535
|
+
@appinstance = new_instance(
|
536
|
+
next_id,
|
537
|
+
zuora_entity_id,
|
538
|
+
zuora_client.rest_domain,
|
539
|
+
task_data: task_data,
|
540
|
+
retry_count: retry_count
|
541
|
+
)
|
454
542
|
end
|
455
543
|
end
|
544
|
+
rescue ActiveRecord::RecordNotUnique
|
545
|
+
retry if (retry_count -= 1).positive?
|
546
|
+
return
|
456
547
|
end
|
457
548
|
|
458
549
|
Apartment::Tenant.switch!("public")
|
@@ -483,8 +574,8 @@ module ZuoraConnect
|
|
483
574
|
|
484
575
|
rescue ZuoraAPI::Exceptions::ZuoraAPIError, Exception => ex
|
485
576
|
if ex.message.include?("Referenced User resource(s) not found") && ex.class == ZuoraAPI::Exceptions::ZuoraAPIError
|
486
|
-
locals = {title: "Provisioning Error", message: "New
|
487
|
-
render "zuora_connect/static/error_handled", locals: locals, status:
|
577
|
+
locals = {title: "Provisioning Error", message: "New tenants need to be provisioned by API Gateway('#{ex.message}'). Please contact support."}
|
578
|
+
render "zuora_connect/static/error_handled", locals: locals, status: 200, layout: false
|
488
579
|
else
|
489
580
|
session.clear
|
490
581
|
if defined?(ex.response) && ex.response.present? && defined?(ex.response.body)
|
@@ -540,28 +631,77 @@ module ZuoraConnect
|
|
540
631
|
end
|
541
632
|
end
|
542
633
|
|
634
|
+
def next_instance_id
|
635
|
+
min_instance_id = 24_999_999
|
636
|
+
(ZuoraConnect::AppInstance.all.where("id > #{min_instance_id}").order(id: :desc).limit(1).pluck(:id).first || min_instance_id) + 1
|
637
|
+
end
|
638
|
+
|
639
|
+
def new_instance(id, zuora_entity_id, rest_domain, task_data: nil, retry_count: 0)
|
640
|
+
app_instance = ZuoraConnect::AppInstance.new(
|
641
|
+
:id => id,
|
642
|
+
:api_token => generate_token,
|
643
|
+
:token => generate_token,
|
644
|
+
:oauth_expires_at => Time.now + 1000.years,
|
645
|
+
:zuora_domain => rest_domain,
|
646
|
+
:zuora_entity_ids => [zuora_entity_id]
|
647
|
+
)
|
648
|
+
|
649
|
+
if task_data.nil?
|
650
|
+
# no encryption
|
651
|
+
app_instance['zuora_logins'] = task_data
|
652
|
+
else
|
653
|
+
# kms encrypt
|
654
|
+
app_instance.zuora_logins = task_data
|
655
|
+
end
|
656
|
+
|
657
|
+
begin
|
658
|
+
app_instance.save(:validate => false)
|
659
|
+
rescue ActiveRecord::RecordNotUnique
|
660
|
+
raise if retry_count > 1
|
661
|
+
|
662
|
+
Thread.current[:appinstance] = nil
|
663
|
+
session['appInstance'] = nil
|
664
|
+
render 'zuora_connect/static/error_handled', :locals => {
|
665
|
+
:title => 'Application could not create unique tokens.',
|
666
|
+
:message => 'Please contact support or retry launching application.'
|
667
|
+
}, :layout => false
|
668
|
+
return
|
669
|
+
end
|
670
|
+
|
671
|
+
app_instance
|
672
|
+
end
|
673
|
+
|
674
|
+
def generate_token
|
675
|
+
rand(36**64).to_s(36)
|
676
|
+
end
|
677
|
+
|
543
678
|
def setup_instance_via_dev_mode
|
544
679
|
session["appInstance"] = ZuoraConnect.configuration.dev_mode_appinstance
|
545
|
-
|
546
|
-
|
547
|
-
values = {
|
548
|
-
|
680
|
+
session["#{ZuoraConnect.configuration.dev_mode_appinstance}::admin"] = ZuoraConnect.configuration.dev_mode_admin
|
681
|
+
|
682
|
+
values = {
|
683
|
+
id: ZuoraConnect.configuration.dev_mode_appinstance,
|
684
|
+
name: "Developer Instance",
|
685
|
+
access_token: ZuoraConnect.configuration.dev_mode_user,
|
686
|
+
refresh_token: ZuoraConnect.configuration.dev_mode_pass,
|
687
|
+
token: ZuoraConnect.configuration.dev_mode_pass+ZuoraConnect.configuration.dev_mode_pass,
|
688
|
+
api_token: ZuoraConnect.configuration.dev_mode_pass+ZuoraConnect.configuration.dev_mode_pass
|
689
|
+
}
|
690
|
+
|
691
|
+
@appinstance = ZuoraConnect::AppInstance.find_by(:id => ZuoraConnect.configuration.dev_mode_appinstance.to_i)
|
692
|
+
ZuoraConnect::ZuoraUser.current_user_id = 0
|
549
693
|
if @appinstance.blank?
|
550
694
|
Apartment::Tenant.switch!("public")
|
551
695
|
begin
|
552
|
-
Apartment::Tenant.create(
|
696
|
+
Apartment::Tenant.create(ZuoraConnect.configuration.dev_mode_appinstance.to_s)
|
553
697
|
rescue Apartment::TenantExists => ex
|
554
|
-
Apartment::Tenant.drop(
|
698
|
+
Apartment::Tenant.drop(ZuoraConnect.configuration.dev_mode_appinstance.to_s)
|
555
699
|
retry
|
556
700
|
end
|
557
|
-
|
558
|
-
@appinstance = ZuoraConnect::AppInstance.new(:id => values[:appinstance].to_i, :access_token => values[:user], :refresh_token => values[:key], :token => "#{values[:key]}#{values[:key]}", :api_token => "#{values[:key]}#{values[:key]}")
|
559
|
-
@appinstance.save(:validate => false)
|
560
|
-
end
|
561
|
-
if @appinstance.access_token.blank? || @appinstance.refresh_token.blank? || @appinstance.token.blank? || @appinstance.api_token.blank?
|
562
|
-
@appinstance.update_attributes!(:access_token => values["user"], :refresh_token => values["key"], :token => "#{values[:key]}#{values[:key]}", :api_token => "#{values[:key]}#{values[:key]}")
|
701
|
+
@appinstance = ZuoraConnect::AppInstance.new()
|
563
702
|
end
|
564
|
-
|
703
|
+
@appinstance.assign_attributes(values)
|
704
|
+
@appinstance.save(:validate => false)
|
565
705
|
end
|
566
706
|
end
|
567
707
|
end
|