Class: ZuoraConnect::AppInstanceBase
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- ZuoraConnect::AppInstanceBase
- Defined in:
- app/models/zuora_connect/app_instance_base.rb
Direct Known Subclasses
Instance Attribute Summary collapse
-
#api_version ⇒ Object
Returns the value of attribute api_version.
-
#last_refresh ⇒ Object
Returns the value of attribute last_refresh.
-
#logins ⇒ Object
Returns the value of attribute logins.
-
#mode ⇒ Object
Returns the value of attribute mode.
-
#options ⇒ Object
Returns the value of attribute options.
-
#password ⇒ Object
Returns the value of attribute password.
-
#s3_client ⇒ Object
Returns the value of attribute s3_client.
-
#task_data ⇒ Object
Returns the value of attribute task_data.
-
#username ⇒ Object
Returns the value of attribute username.
-
#valid ⇒ Object
Returns the value of attribute valid.
Class Method Summary collapse
- .decrypt_response(resp) ⇒ Object
- .refresh_aggregate_table(aggregate_name: 'all_tasks_processing', table_name: 'tasks', where_clause: "where status in ('Processing', 'Queued')", index_table: true) ⇒ Object
- .update_functions ⇒ Object
Instance Method Summary collapse
- #api_limit(start: true, time: 2.minutes.to_i) ⇒ Object
- #api_limit? ⇒ Boolean
- #attr_builder(field, val) ⇒ Object
- #build_task(task_data, session) ⇒ Object
- #cache_app_instance ⇒ Object
- #catalog_loaded? ⇒ Boolean
-
#catalog_lookup(entity_id: nil, object: :product, object_id: nil, child_objects: false, cache: false) ⇒ Object
Catalog lookup provides method to lookup zuora catalog efficiently.
- #catalog_outdated?(time: Time.now - 12.hours) ⇒ Boolean
- #data_lookup(session: {}) ⇒ Object
- #decrypt_data(data: nil, rescue_return: nil) ⇒ Object
- #encrypt_data(data: nil) ⇒ Object
- #encryptor ⇒ Object
- #get_catalog(page_size: 5, zuora_login: self.login_lookup(type: "Zuora").first, entity_id: nil) ⇒ Object
- #get_s3_file_url(key) ⇒ Object
- #init ⇒ Object
- #instance_failure(failure) ⇒ Object
- #login_lookup(type: "Zuora") ⇒ Object
- #method_missing(method_sym, *arguments, &block) ⇒ Object
- #new_session(session: self.data_lookup, username: self.access_token, password: self.refresh_token) ⇒ Object
- #oauth_expired? ⇒ Boolean
- #queue_pause(time: nil) ⇒ Object
- #queue_paused? ⇒ Boolean
- #queue_start ⇒ Object
- #refresh(session = nil) ⇒ Object
- #refresh_oauth ⇒ Object
- #save_data(session = Hash.new) ⇒ Object
- #send_email ⇒ Object
-
#update_logins(options) ⇒ Object
Example “ftp_login_14”,“username”: “ftplogin7”,“tenant_type”: “Custom”,“password”: “test2”,“url”: “www.ftp.com”,“custom_data”: { “path”: “/var/usr/test”} This can update an existing login This can add a new login This can change to another existing login.
- #updateOption(optionId, value) ⇒ Object
- #upload_to_s3(local_file, s3_path = nil) ⇒ Object
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_sym, *arguments, &block) ⇒ Object
576 577 578 579 580 581 582 583 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 576 def method_missing(method_sym, *arguments, &block) if method_sym.to_s.include?("login") Rails.logger.fatal("Method Missing #{method_sym}") Rails.logger.fatal("Instance Data: #{self.task_data}") Rails.logger.fatal("Instance Logins: #{self.logins}") end super end |
Instance Attribute Details
#api_version ⇒ Object
Returns the value of attribute api_version.
6 7 8 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 6 def api_version @api_version end |
#last_refresh ⇒ Object
Returns the value of attribute last_refresh.
6 7 8 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 6 def last_refresh @last_refresh end |
#logins ⇒ Object
Returns the value of attribute logins.
6 7 8 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 6 def logins @logins end |
#mode ⇒ Object
Returns the value of attribute mode.
6 7 8 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 6 def mode @mode end |
#options ⇒ Object
Returns the value of attribute options.
6 7 8 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 6 def @options end |
#password ⇒ Object
Returns the value of attribute password.
6 7 8 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 6 def password @password end |
#s3_client ⇒ Object
Returns the value of attribute s3_client.
6 7 8 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 6 def s3_client @s3_client end |
#task_data ⇒ Object
Returns the value of attribute task_data.
6 7 8 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 6 def task_data @task_data end |
#username ⇒ Object
Returns the value of attribute username.
6 7 8 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 6 def username @username end |
#valid ⇒ Object
Returns the value of attribute valid.
6 7 8 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 6 def valid @valid end |
Class Method Details
.decrypt_response(resp) ⇒ Object
518 519 520 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 518 def self.decrypt_response(resp) OpenSSL::PKey::RSA.new(ZuoraConnect.configuration.private_key).private_decrypt(resp) end |
.refresh_aggregate_table(aggregate_name: 'all_tasks_processing', table_name: 'tasks', where_clause: "where status in ('Processing', 'Queued')", index_table: true) ⇒ Object
589 590 591 592 593 594 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 589 def self.refresh_aggregate_table(aggregate_name: 'all_tasks_processing', table_name: 'tasks', where_clause: "where status in ('Processing', 'Queued')", index_table: true) self.update_functions #Broke function into two parts to ensure transaction size was small enough ActiveRecord::Base.connection.execute('SELECT "shared_extensions".refresh_aggregate_table(\'%s\', \'%s\', %s, \'Table\');' % [aggregate_name, table_name, ActiveRecord::Base.connection.quote(where_clause)]) ActiveRecord::Base.connection.execute('SELECT "shared_extensions".refresh_aggregate_table(\'%s\', \'%s\', %s, \'Index\');' % [aggregate_name, table_name, ActiveRecord::Base.connection.quote(where_clause)]) if index_table end |
.update_functions ⇒ Object
585 586 587 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 585 def self.update_functions ActiveRecord::Base.connection.execute(File.read("#{Gem.loaded_specs["zuora_connect"].gem_dir}/app/views/sql/refresh_aggregate_table.txt")) end |
Instance Method Details
#api_limit(start: true, time: 2.minutes.to_i) ⇒ Object
85 86 87 88 89 90 91 92 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 85 def api_limit(start: true, time: 2.minutes.to_i) if start Redis.current.set("APILimits:#{self.id}", true) Redis.current.expire("APILimits:#{self.id}", time) else Redis.current.del("APILimits:#{self.id}") end end |
#api_limit? ⇒ Boolean
94 95 96 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 94 def api_limit? return Redis.current.get("APILimits:#{self.id}").to_bool end |
#attr_builder(field, val) ⇒ Object
571 572 573 574 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 571 def attr_builder(field,val) singleton_class.class_eval { attr_accessor "#{field}" } send("#{field}=", val) end |
#build_task(task_data, session) ⇒ Object
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 463 def build_task(task_data, session) @task_data = task_data @mode = @task_data["mode"] @task_data.each do |k,v| if k.match(/^(.*)_login$/) tmp = ZuoraConnect::Login.new(v) if !session.nil? && v["tenant_type"] == "Zuora" if tmp.entities.size > 0 tmp.entities.each do |value| entity_id = value["id"] tmp.client(entity_id).current_session = session["#{self.id}::#{k}::#{entity_id}:session"] if !session.nil? && v["tenant_type"] == "Zuora" && session["#{self.id}::#{k}::#{entity_id}:session"] end else tmp.client.current_session = session["#{self.id}::#{k}:session"] if !session.nil? && v["tenant_type"] == "Zuora" && session["#{self.id}::#{k}:session"] end end @logins[k] = tmp self.attr_builder(k, @logins[k]) elsif k == "options" v.each do |opt| @options[opt["config_name"]] = opt end elsif k == "user_settings" self.timezone = v["timezone"] self.locale = v["local"] end end Thread.current[:appinstance] = self end |
#cache_app_instance ⇒ Object
40 41 42 43 44 45 46 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 40 def cache_app_instance if defined?(Redis.current) Redis.current.set("AppInstance:#{self.id}", encrypt_data(data: self.save_data)) Redis.current.expire("AppInstance:#{self.id}", 60.minutes.to_i) Redis.current.del("Deleted:#{self.id}") end end |
#catalog_loaded? ⇒ Boolean
120 121 122 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 120 def catalog_loaded? return ActiveRecord::Base.connection.execute('SELECT id FROM "public"."zuora_connect_app_instances" WHERE "id" = %s AND catalog = \'{}\' LIMIT 1' % [self.id]).first.nil? end |
#catalog_lookup(entity_id: nil, object: :product, object_id: nil, child_objects: false, cache: false) ⇒ Object
Catalog lookup provides method to lookup zuora catalog efficiently. entity_id: If the using catalog json be field to store multiple entity product catalogs. object: The Object class desired to be returned. Available [:product, :rateplan, :charge] object_id: The id or id’s of the object/objects to be returned. child_objects: Whether to include child objects of the object in question. cache: Store individual “1” object lookup in redis for caching.
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 130 def catalog_lookup(entity_id: nil, object: :product, object_id: nil, child_objects: false, cache: false) entity_reference = entity_id.blank? ? 'Default' : entity_id if object_id.present? && ![Array, String].include?(object_id.class) raise "Object Id can only be a string or an array of strings" end if defined?(Redis.current) && object_id.present? && object_id.class == String stub_catalog = decrypt_data(data: Redis.current.get("Catalog:#{self.id}:#{object_id}:Children:#{child_objects}")) object_hierarchy = decrypt_data(data: Redis.current.get("Catalog:#{self.id}:#{object_id}:Hierarchy")) end if defined?(object_hierarchy) object_hierarchy ||= (JSON.parse(ActiveRecord::Base.connection.execute('SELECT catalog_mapping #> \'{%s}\' AS item FROM "public"."zuora_connect_app_instances" WHERE "id" = %s LIMIT 1' % [entity_reference, self.id]).first["item"] || "{}") [object_id] || {"productId" => "SAFTEY", "productRatePlanId" => "SAFTEY", "productRatePlanChargeId" => "SAFTEY"}) end case object when :product if object_id.blank? string = "SELECT "\ "json_object_agg(product_id, product #{child_objects ? '' : '- \'productRatePlans\''}) AS item "\ "FROM "\ "\"public\".\"zuora_connect_app_instances\", "\ "jsonb_each((\"public\".\"zuora_connect_app_instances\".\"catalog\" #> '{%s}' )) AS e(product_id, product) "\ "WHERE "\ "\"id\" = %s" % [entity_reference, self.id] else if object_id.class == String string = "SELECT "\ "(catalog #> '{%s, %s}') #{child_objects ? '' : '- \'productRatePlans\''} AS item "\ "FROM "\ "\"public\".\"zuora_connect_app_instances\" "\ "WHERE "\ "\"id\" = %s" % [entity_reference, object_id, self.id] elsif object_id.class == Array string = "SELECT "\ "json_object_agg(product_id, product #{child_objects ? '' : '- \'productRatePlans\''}) AS item "\ "FROM "\ "\"public\".\"zuora_connect_app_instances\", "\ "jsonb_each((\"public\".\"zuora_connect_app_instances\".\"catalog\" #> '{%s}' )) AS e(product_id, product) "\ "WHERE "\ "\"product_id\" IN (\'%s\') AND "\ "\"id\" = %s" % [entity_reference, object_id.join("\',\'"), self.id] end end when :rateplan if object_id.blank? string = "SELECT "\ "json_object_agg(rateplan_id, rateplan #{child_objects ? '' : '- \'productRatePlanCharges\''}) AS item "\ "FROM "\ "\"public\".\"zuora_connect_app_instances\", "\ "jsonb_each((\"public\".\"zuora_connect_app_instances\".\"catalog\" #> '{%s}' )) AS e(product_id, product), "\ "jsonb_each(product #> '{productRatePlans}') AS ee(rateplan_id, rateplan) "\ "WHERE "\ "\"id\" = %s" % [entity_reference, self.id] else if object_id.class == String string = "SELECT "\ "(catalog #> '{%s, %s, productRatePlans, %s}') #{child_objects ? '' : '- \'productRatePlanCharges\''} AS item "\ "FROM "\ "\"public\".\"zuora_connect_app_instances\" "\ "WHERE "\ "\"id\" = %s" % [entity_reference, object_hierarchy['productId'], object_id, self.id] elsif object_id.class == Array string = "SELECT "\ "json_object_agg(rateplan_id, rateplan #{child_objects ? '' : '- \'productRatePlanCharges\''}) AS item "\ "FROM "\ "\"public\".\"zuora_connect_app_instances\", "\ "jsonb_each((\"public\".\"zuora_connect_app_instances\".\"catalog\" #> '{%s}' )) AS e(product_id, product), "\ "jsonb_each(product #> '{productRatePlans}') AS ee(rateplan_id, rateplan) "\ "WHERE "\ "\"rateplan_id\" IN (\'%s\') AND "\ "\"id\" = %s" % [entity_reference, object_id.join("\',\'"), self.id] end end when :charge if object_id.blank? string = "SELECT "\ "json_object_agg(charge_id, charge) as item "\ "FROM "\ "\"public\".\"zuora_connect_app_instances\", "\ "jsonb_each((\"public\".\"zuora_connect_app_instances\".\"catalog\" #> '{%s}' )) AS e(product_id, product), "\ "jsonb_each(product #> '{productRatePlans}') AS ee(rateplan_id, rateplan), "\ "jsonb_each(rateplan #> '{productRatePlanCharges}') AS eee(charge_id, charge) "\ "WHERE "\ "\"id\" = %s" % [entity_reference, self.id] else if object_id.class == String string = "SELECT "\ "catalog #> '{%s, %s, productRatePlans, %s, productRatePlanCharges, %s}' AS item "\ "FROM "\ "\"public\".\"zuora_connect_app_instances\" "\ "WHERE "\ "\"id\" = %s" % [entity_reference, object_hierarchy['productId'], object_hierarchy['productRatePlanId'], object_id, self.id] elsif object_id.class == Array string = "SELECT "\ "json_object_agg(charge_id, charge) AS item "\ "FROM "\ "\"public\".\"zuora_connect_app_instances\", "\ "jsonb_each((\"public\".\"zuora_connect_app_instances\".\"catalog\" #> '{%s}' )) AS e(product_id, product), "\ "jsonb_each(product #> '{productRatePlans}') AS ee(rateplan_id, rateplan), "\ "jsonb_each(rateplan #> '{productRatePlanCharges}') AS eee(charge_id, charge) "\ "WHERE "\ "\"charge_id\" IN (\'%s\') AND "\ "\"id\" = %s" % [entity_reference, object_id.join("\',\'"), self.id] end end else raise "Available objects include [:product, :rateplan, :charge]" end stub_catalog ||= JSON.parse(ActiveRecord::Base.connection.execute(string).first["item"] || "{}") if defined?(Redis.current) && object_id.present? && object_id.class == String Redis.current.set("Catalog:#{self.id}:#{object_id}:Hierarchy", encrypt_data(data: object_hierarchy)) Redis.current.set("Catalog:#{self.id}:#{object_id}:Children:#{child_objects}", encrypt_data(data: stub_catalog)) if cache end return stub_catalog end |
#catalog_outdated?(time: Time.now - 12.hours) ⇒ Boolean
116 117 118 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 116 def catalog_outdated?(time: Time.now - 12.hours) return self.catalog_updated_at.blank? || (self.catalog_updated_at < time) end |
#data_lookup(session: {}) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 22 def data_lookup(session: {}) if defined?(PaperTrail) PaperTrail.whodunnit = session["#{self.id}::user::email"].present? ? session["#{self.id}::user::email"] : nil if session.present? end if defined?(Redis.current) cached_instance = Redis.current.get("AppInstance:#{self.id}") if cached_instance.blank? Rails.logger.info('Cached AppInstance Missing') return {} else Rails.logger.info('Cached AppInstance Found') return decrypt_data(data: cached_instance, rescue_return: {}) end else return session end end |
#decrypt_data(data: nil, rescue_return: nil) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 48 def decrypt_data(data: nil, rescue_return: nil) return data if data.blank? begin if Rails.env == 'development' return JSON.parse(data) else begin return JSON.parse(encryptor.decrypt_and_verify(CGI::unescape(data))) rescue ActiveSupport::MessageVerifier::InvalidSignature => ex Rails.logger.fatal('Error Decrypting') return rescue_return end end rescue JSON::ParserError => ex Rails.logger.fatal('Error Parsing') return rescue_return end end |
#encrypt_data(data: nil) ⇒ Object
67 68 69 70 71 72 73 74 75 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 67 def encrypt_data(data: nil) return data if data.blank? if Rails.env == 'development' return data.to_json else return encryptor.encrypt_and_sign(data.to_json) end end |
#encryptor ⇒ Object
77 78 79 80 81 82 83 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 77 def encryptor # Default values for Rails 4 apps key_iter_num, key_size, salt, signed_salt = [1000, 64, "encrypted cookie", "signed encrypted cookie"] key_generator = ActiveSupport::KeyGenerator.new(Rails.application.secrets.secret_key_base, iterations: key_iter_num) secret, sign_secret = [key_generator.generate_key(salt), key_generator.generate_key(signed_salt)] return ActiveSupport::MessageEncryptor.new(secret, sign_secret) end |
#get_catalog(page_size: 5, zuora_login: self.login_lookup(type: "Zuora").first, entity_id: nil) ⇒ Object
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 275 def get_catalog(page_size: 5, zuora_login: self.login_lookup(type: "Zuora").first, entity_id: nil) entity_reference = entity_id.blank? ? 'Default' : entity_id Rails.logger.info("Fetch Catalog") Rails.logger.info("Zuora Entity: #{entity_id.blank? ? 'default' : entity_id}") login = zuora_login.client(entity_reference) old_logger = ActiveRecord::Base.logger ActiveRecord::Base.logger = nil ActiveRecord::Base.connection.execute('UPDATE "public"."zuora_connect_app_instances" SET "catalog" = jsonb_set("catalog", \'{tmp}\', \'{}\'), "catalog_mapping" = jsonb_set("catalog_mapping", \'{tmp}\', \'{}\') where "id" = %{id}' % {:id => self.id}) response = {'nextPage' => login.rest_endpoint("catalog/products?pageSize=#{page_size}")} while !response["nextPage"].blank? url = login.rest_endpoint(response["nextPage"].split('/v1/').last) Rails.logger.debug("Fetch Catalog URL #{url}") output_json, response = login.rest_call(:debug => false, :url => url, :errors => [ZuoraAPI::Exceptions::ZuoraAPISessionError], :timeout_retry => true) Rails.logger.debug("Fetch Catalog Response Code #{response.code}") if !output_json['success'] =~ (/(true|t|yes|y|1)$/i) || output_json['success'].class != TrueClass Rails.logger.error("Fetch Catalog DATA #{output_json.to_json}") raise ZuoraAPI::Exceptions::ZuoraAPIError.new("Error Getting Catalog: #{output_json}") end output_json["products"].each do |product| ActiveRecord::Base.connection.execute('UPDATE "public"."zuora_connect_app_instances" SET "catalog_mapping" = jsonb_set("catalog_mapping", \'{tmp, %s}\', \'%s\') where "id" = %s' % [product["id"], {"productId" => product["id"]}.to_json.gsub("'", "''"), self.id]) rateplans = {} product["productRatePlans"].each do |rateplan| ActiveRecord::Base.connection.execute('UPDATE "public"."zuora_connect_app_instances" SET "catalog_mapping" = jsonb_set("catalog_mapping", \'{tmp, %s}\', \'%s\') where "id" = %s' % [rateplan["id"], {"productId" => product["id"], "productRatePlanId" => rateplan["id"]}.to_json.gsub("'", "''"), self.id]) charges = {} rateplan["productRatePlanCharges"].each do |charge| ActiveRecord::Base.connection.execute('UPDATE "public"."zuora_connect_app_instances" SET "catalog_mapping" = jsonb_set("catalog_mapping", \'{tmp, %s}\', \'%s\') where "id" = %s' % [charge["id"], {"productId" => product["id"], "productRatePlanId" => rateplan["id"], "productRatePlanChargeId" => charge["id"]}.to_json.gsub("'", "''"), self.id]) charges[charge["id"]] = charge.merge({"productId" => product["id"], "productName" => product["name"], "productRatePlanId" => rateplan["id"], "productRatePlanName" => rateplan["name"] }) end rateplan["productRatePlanCharges"] = charges rateplans[rateplan["id"]] = rateplan.merge({"productId" => product["id"], "productName" => product["name"]}) end product["productRatePlans"] = rateplans ActiveRecord::Base.connection.execute('UPDATE "public"."zuora_connect_app_instances" SET "catalog" = jsonb_set("catalog", \'{tmp, %s}\', \'%s\') where "id" = %s' % [product["id"], product.to_json.gsub("'", "''"), self.id]) end end # Move from tmp to actual ActiveRecord::Base.connection.execute('UPDATE "public"."zuora_connect_app_instances" SET "catalog" = jsonb_set("catalog", \'{%{entity}}\', "catalog" #> \'{tmp}\'), "catalog_mapping" = jsonb_set("catalog_mapping", \'{%{entity}}\', "catalog_mapping" #> \'{tmp}\') where "id" = %{id}' % {:entity => entity_reference, :id => self.id}) if defined?(Redis.current) Redis.current.keys("Catalog:#{self.id}:*").each do |key| Redis.current.del(key.to_s) end end # Clear tmp holder ActiveRecord::Base.connection.execute('UPDATE "public"."zuora_connect_app_instances" SET "catalog" = jsonb_set("catalog", \'{tmp}\', \'{}\'), "catalog_mapping" = jsonb_set("catalog_mapping", \'{tmp}\', \'{}\') where "id" = %{id}' % {:id => self.id}) ActiveRecord::Base.logger = old_logger self.update_column(:catalog_updated_at, Time.now.utc) self.touch # DO NOT RETURN CATALOG. THIS IS NOT SCALABLE WITH LARGE CATALOGS. USE THE CATALOG_LOOKUP method provided return true end |
#get_s3_file_url(key) ⇒ Object
503 504 505 506 507 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 503 def get_s3_file_url(key) require 'aws-sdk-s3' signer = Aws::S3::Presigner.new(client: self.s3_client) url = signer.presigned_url(:get_object, bucket: ZuoraConnect.configuration.s3_bucket_name, key: "#{ZuoraConnect.configuration.s3_folder_name}/#{self.id.to_s}/#{key}") end |
#init ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 8 def init @options = Hash.new @logins = Hash.new @valid = false self.attr_builder("timezone", ZuoraConnect.configuration.default_time_zone) self.attr_builder("locale", ZuoraConnect.configuration.default_locale) PaperTrail.whodunnit = "Backend" if defined?(PaperTrail) Apartment::Tenant.switch!(self.id) if(ActiveRecord::Migrator.needs_migration?) Apartment::Migrator.migrate(self.id) end Thread.current[:appinstance] = self end |
#instance_failure(failure) ⇒ Object
263 264 265 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 263 def instance_failure(failure) raise failure end |
#login_lookup(type: "Zuora") ⇒ Object
267 268 269 270 271 272 273 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 267 def login_lookup(type: "Zuora") results = [] self.logins.each do |name, login| results << login if login.tenant_type == type end return results end |
#new_session(session: self.data_lookup, username: self.access_token, password: self.refresh_token) ⇒ Object
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 339 def new_session(session: self.data_lookup, username: self.access_token, password: self.refresh_token) @api_version = "v2" @username = username @password = password @last_refresh = session["#{self.id}::last_refresh"] ## DEV MODE TASK DATA MOCKUP if ZuoraConnect.configuration.mode != "Production" self. = ZuoraConnect.configuration. ZuoraConnect.configuration.dev_mode_logins.each do |k,v| tmp = ZuoraConnect::Login.new(v) self.logins[k] = tmp self.attr_builder(k, tmp) end self.mode = ZuoraConnect.configuration.dev_mode_mode else if session.nil? || (!session.nil? && self.id != session["appInstance"].to_i) || session["#{self.id}::task_data"].blank? || ( session["#{self.id}::last_refresh"].blank? || session["#{self.id}::last_refresh"].to_i < ZuoraConnect.configuration.timeout.ago.to_i ) Rails.logger.info("[#{self.id}] REFRESHING - Session Nil") if session.nil? Rails.logger.info("[#{self.id}] REFRESHING - AppInstance ID(#{self.id}) does not match session id(#{session["appInstance"].to_i})") if (!session.nil? && self.id != session["appInstance"].to_i) Rails.logger.info("[#{self.id}] REFRESHING - Task Data Blank") if session["#{self.id}::task_data"].blank? Rails.logger.info("[#{self.id}] REFRESHING - No Time on Cookie") if session["#{self.id}::last_refresh"].blank? Rails.logger.info("[#{self.id}] REFRESHING - Session Old") if (session["#{self.id}::last_refresh"].blank? || session["#{self.id}::last_refresh"].to_i < ZuoraConnect.configuration.timeout.ago.to_i ) self.refresh(session) else Rails.logger.info("[#{self.id}] REBUILDING") build_task(session["#{self.id}::task_data"], session) end end begin I18n.locale = self.locale rescue I18n::InvalidLocale => ex Rails.logger.error("Invalid Locale: #{ex.}") end Time.zone = self.timezone @valid = true Thread.current[:appinstance] = self return self end |
#oauth_expired? ⇒ Boolean
567 568 569 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 567 def oauth_expired? (expires_at < Time.now) end |
#queue_pause(time: nil) ⇒ Object
102 103 104 105 106 107 108 109 110 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 102 def queue_pause(time: nil) if time.present? raise "Time must be fixnum of seconds." if time.class != Fixnum Redis.current.set("resque:PauseQueue:#{self.id}", true) Redis.current.expire("resque:PauseQueue:#{self.id}", time) else Redis.current.set("resque:PauseQueue:#{self.id}", true) end end |
#queue_paused? ⇒ Boolean
98 99 100 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 98 def queue_paused? return Redis.current.get("resque:PauseQueue:#{self.id}").to_bool end |
#queue_start ⇒ Object
112 113 114 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 112 def queue_start Redis.current.del("resque:PauseQueue:#{self.id}") end |
#refresh(session = nil) ⇒ Object
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 433 def refresh(session = nil) count ||= 0 start = Time.now response = HTTParty.get(ZuoraConnect.configuration.url + "/api/#{self.api_version}/tools/tasks/#{self.id}.json",:body => {:access_token => self.access_token}) response_time = Time.now - start Rails.logger.info("[#{self.id}] REFRESHING - Connect Request Time #{response_time.round(2).to_s}") if response.code == 200 @last_refresh = Time.now.to_i build_task(JSON.parse(response.body), session) else raise ZuoraConnect::Exceptions::ConnectCommunicationError.new("Error Communicating with Connect", response.body, response.code) end rescue Net::ReadTimeout, Net::OpenTimeout, Errno::EPIPE, Errno::ECONNRESET, Errno::ECONNREFUSED, SocketError if count < 2 count += 1 retry else raise end rescue ZuoraConnect::Exceptions::ConnectCommunicationError => ex if count < 2 && ex.code == 401 self.refresh_oauth count += 1 retry else raise end end |
#refresh_oauth ⇒ Object
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 522 def refresh_oauth count ||= 0 start = Time.now Rails.logger.info("[#{self.id}] REFRESHING - OAuth") params = { :grant_type => "refresh_token", :redirect_uri => ZuoraConnect.configuration.oauth_client_redirect_uri, :refresh_token => self.refresh_token } response = HTTParty.post("#{ZuoraConnect.configuration.url}/oauth/token",:body => params) response_time = Time.now - start Rails.logger.info("[#{self.id}] REFRESHING - OAuth in #{response_time.round(2).to_s}") response_body = JSON.parse(response.body) if response.code == 200 self.refresh_token = response_body["refresh_token"] self.access_token = response_body["access_token"] self.oauth_expires_at = Time.at(response_body["created_at"].to_i) + response_body["expires_in"].seconds self.save(:validate => false) else Rails.logger.fatal("REFRESHING - OAuth Failed - Code #{response.code}") raise ZuoraConnect::Exceptions::ConnectCommunicationError.new("Error Refreshing Access Token", response.body, response.code) end rescue Net::ReadTimeout, Net::OpenTimeout, Errno::EPIPE, Errno::ECONNRESET, Errno::ECONNREFUSED, SocketError => ex if count < 2 count += 1 retry else raise end rescue ZuoraConnect::Exceptions::ConnectCommunicationError => ex if count < 3 Rails.logger.info("REFRESHING - OAuth Failed - Retrying(#{count})") self.reload sleep(5) count += 1 retry else Rails.logger.fatal("REFRESHING - OAuth Failed") raise end end |
#save_data(session = Hash.new) ⇒ Object
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 378 def save_data(session = Hash.new) self.logins.each do |key, login| if login.tenant_type == "Zuora" if login.available_entities.size > 1 && Rails.application.config.session_store != ActionDispatch::Session::CookieStore login.available_entities.each do |entity_key| session["#{self.id}::#{key}::#{entity_key}:session"] = login.client(entity_key).current_session end else session["#{self.id}::#{key}:session"] = login.client.current_session end end end session["#{self.id}::task_data"] = self.task_data session["#{self.id}::last_refresh"] = self.last_refresh session["appInstance"] = self.id return session end |
#send_email ⇒ Object
493 494 495 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 493 def send_email end |
#update_logins(options) ⇒ Object
Example “ftp_login_14”,“username”: “ftplogin7”,“tenant_type”: “Custom”,“password”: “test2”,“url”: “www.ftp.com”,“custom_data”: { “path”: “/var/usr/test”} This can update an existing login This can add a new login This can change to another existing login
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 409 def update_logins() count ||= 0 response = HTTParty.post(ZuoraConnect.configuration.url + "/api/#{self.api_version}/tools/tasks/#{self.id}/logins",:body => {:access_token => self.username}.merge()) if response.code == 200 return JSON.parse(response.body) else raise ZuoraConnect::Exceptions::ConnectCommunicationError.new("Error Communicating with Connect", response.body, response.code) end rescue Net::ReadTimeout, Net::OpenTimeout, Errno::EPIPE, Errno::ECONNRESET, Errno::ECONNREFUSED, SocketError if (count += 1) < 2 retry else raise end rescue ZuoraConnect::Exceptions::ConnectCommunicationError => ex if count < 2 && ex.code == 401 self.refresh_oauth count += 1 retry else raise end end |
#updateOption(optionId, value) ⇒ Object
396 397 398 399 400 401 402 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 396 def updateOption(optionId, value) if self.access_token && self.refresh_token return HTTParty.get(ZuoraConnect.configuration.url + "/api/#{self.api_version}/tools/application_options/#{optionId}/edit?value=#{value}",:body => {:access_token => self.username}) else return false end end |
#upload_to_s3(local_file, s3_path = nil) ⇒ Object
497 498 499 500 501 |
# File 'app/models/zuora_connect/app_instance_base.rb', line 497 def upload_to_s3(local_file,s3_path = nil) s3_path = local_file.split("/").last if s3_path.nil? obj = self.s3_client.bucket(ZuoraConnect.configuration.s3_bucket_name).object("#{ZuoraConnect.configuration.s3_folder_name}/#{self.id.to_s}/#{s3_path}}") obj.upload_file(local_file, :server_side_encryption => 'AES256') end |