diff --git a/app/controllers/customers_controller.rb b/app/controllers/customers_controller.rb index 9e88b93..0197dd0 100644 --- a/app/controllers/customers_controller.rb +++ b/app/controllers/customers_controller.rb @@ -66,67 +66,60 @@ class CustomersController < ApplicationController # create a new customer def create @customer = Customer.new(allowed_params) - if @customer.save - flash[:notice] = t :notice_customer_created - redirect_to @customer - else - flash[:error] = @customer.errors.full_messages.to_sentence - redirect_to new_customer_path - end + @customer.save + log "Customer ##{@customer.id} created successfully." + flash[:notice] = t :notice_customer_created + redirect_to @customer + rescue => e + log "Failed to create customer: #{e.message}" + flash[:error] = e.message + redirect_to new_customer_path end # display a specific customer def show - begin - @customer = Customer.find_by_id(params[:id]) - @issues = @customer.issues.order(id: :desc) - @billing_address = address_to_s(@customer.billing_address) - @shipping_address = address_to_s(@customer.shipping_address) - @closed_issues = (@issues - @issues.open) - @hours = 0 - @closed_hours = 0 - @issues.open.each { |i| @hours+= i.total_spent_hours } - @closed_issues.each { |i| @closed_hours+= i.total_spent_hours } - rescue - flash[:error] = t :notice_customer_not_found - render_404 - end + @customer = Customer.find_by_id(params[:id]) + return render_404 unless @customer + @issues = @customer.issues&.order(id: :desc) + @billing_address = address_to_s(@customer.billing_address) + @shipping_address = address_to_s(@customer.shipping_address) + @closed_issues = (@issues - @issues.open) + @hours = 0 + @closed_hours = 0 + @issues.open.each { |i| @hours+= i.total_spent_hours } + @closed_issues.each { |i| @closed_hours+= i.total_spent_hours } + rescue => e + log "Failed to load customer ##{params[:id]}: #{e.message}" + flash[:error] = e.message + render_404 end # return an HTML form for editing a customer def edit - begin - @customer = Customer.find_by_id(params[:id]) - rescue - flash[:error] = t :notice_customer_not_found - render_404 - end + @customer = Customer.find_by_id(params[:id]) + return render_404 unless @customer + rescue + flash[:error] = t :notice_customer_not_found + render_404 end # update a specific customer def update - begin - @customer = Customer.find_by_id(params[:id]) - if @customer.update(allowed_params) - flash[:notice] = t :notice_customer_updated - redirect_to @customer - else - redirect_to edit_customer_path - flash[:error] = @customer.errors.full_messages.to_sentence if @customer.errors - end - rescue - flash[:error] = t :notice_customer_not_found - render_404 - end + @customer = Customer.find_by_id(params[:id]) + @customer.update(allowed_params) + flash[:notice] = t :notice_customer_updated + redirect_to @customer + rescue => e + log "Failed to update customer: #{e.message}" + flash[:error] = e.message + redirect_to edit_customer_path end # creates new customer view tokens, removes expired tokens & redirects to newly created customer view with new token. def share issue = Issue.find(params[:id]) - token = issue.share_token redirect_to view_path(token.token) - rescue ActiveRecord::RecordNotFound flash[:error] = t(:notice_issue_not_found) render_404 diff --git a/app/models/customer.rb b/app/models/customer.rb index b633783..2ddc74d 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -19,6 +19,7 @@ class Customer < ActiveRecord::Base has_many :estimates validates_presence_of :id, :name + before_validation :normalize_phone_numbers self.primary_key = :id @@ -31,22 +32,21 @@ class Customer < ActiveRecord::Base :type => :to_s, :description => Proc.new {|o| "#{I18n.t :label_primary_phone}: #{o.phone_number} #{I18n.t:label_mobile_phone}: #{o.mobile_phone_number}"}, :datetime => Proc.new {|o| o.updated_at || o.created_at} - - # Convenience Method - # returns the customer's email + + # Returns the details of the customer. If the details have already been fetched, it returns the cached version. Otherwise, it fetches the details from QuickBooks Online and caches them for future use. This method is used to access the customer's information in a way that minimizes unnecessary API calls to QBO, improving performance and reducing latency. + def details + @details ||= fetch_details + end + + # Returns the customer's email address def email - pull unless @details - begin - return @details.email_address.address - rescue - return nil - end + details + return @details&.email_address&.address end - # Convenience Method - # Sets the email + # Updates the customer's email address def email=(s) - pull unless @details + details @details.email_address = s end @@ -56,109 +56,78 @@ class Customer < ActiveRecord::Base format_time(maximum(:updated_at)) end - # Convenience Method - # returns the customer's primary phone - def primary_phone - pull unless @details - begin - return @details.primary_phone.free_form_number - rescue - return nil - end - end - - # Convenience Method - # Updates the customer's primary phone number - def primary_phone=(n) - pull unless @details - pn = Quickbooks::Model::TelephoneNumber.new - pn.free_form_number = n - @details.primary_phone = pn - #update our locally stored number too - update_phone_number - end - # Customers are not bound by a project # but we need to implement this method for the Redmine::Acts::Searchable interface def project nil end - # Convenience Method - # returns the customer's mobile phone - def mobile_phone - pull unless @details - begin - return @details.mobile_phone.free_form_number - rescue - return nil + # Magic Method + # Maps Get/Set methods to QBO customer object + def method_missing(method_name, *args, &block) + if Quickbooks::Model::Customer.method_defined?(method_name) + details + @details.public_send(method_name, *args, &block) + else + super end end + + # returns the customer's mobile phone + def mobile_phone + details + return @details&.mobile_phone&.free_form_number + end - # Convenience Method # Updates the custome's mobile phone number def mobile_phone=(n) - pull unless @details + details pn = Quickbooks::Model::TelephoneNumber.new pn.free_form_number = n @details.mobile_phone = pn - #update our locally stored number too - update_mobile_phone_number end - # Convenience Method - # Sets the notes - def notes=(s) - pull unless @details - @details.notes = s - end - - # update the localy stored phone number as a plain string with no special chars - def update_phone_number - begin - self.phone_number = self.primary_phone.tr('^0-9', '') - rescue - return nil - end - end - - # update the localy stored phone number as a plain string with no special chars - def update_mobile_phone_number - begin - self.mobile_phone_number = self.mobile_phone.tr('^0-9', '') - rescue - return nil - end - end - - # Convenience Method # Updates Both local DB name & QBO display_name def name=(s) - pull unless @details + details @details.display_name = s super end + + # Normalizes phone numbers by removing non-digit characters. This method is called before validation to ensure that phone numbers are stored in a consistent format, which can help with searching and integration with external systems like QuickBooks Online. + def normalize_phone_numbers + self.phone_number = phone_number.to_s.gsub(/\D/, '') if phone_number.present? + self.mobile_phone_number = mobile_phone_number.to_s.gsub(/\D/, '') if mobile_phone_number.present? + end + + # Sets the notes for the customer + def notes=(s) + details + @details.notes = s + end + + # returns the customer's primary phone + def primary_phone + details + return @details&.primary_phone&.free_form_number + end - # Magic Method - # Maps Get/Set methods to QBO customer object - def method_missing(sym, *arguments) - # Check to see if the method exists - if Quickbooks::Model::Customer.method_defined?(sym) - # download details if required - pull unless @details - method_name = sym.to_s - # Setter - if method_name[-1, 1] == "=" - @details.method(method_name).call(arguments[0]) - # Getter - else - return @details.method(method_name).call - end - end + # Updates the customer's primary phone number + def primary_phone=(n) + details + pn = Quickbooks::Model::TelephoneNumber.new + pn.free_form_number = n + @details.primary_phone = pn + end + + # Repsonds to missing methods by delegating to the QBO customer details object if the method is defined there. This allows for dynamic access to any attributes or methods of the QBO customer without having to explicitly define them in the Customer model, providing flexibility and reducing boilerplate code. + def respond_to_missing?(method_name, include_private = false) + Quickbooks::Model::Customer.method_defined?(method_name) || super end # Seach for customers by name or phone number def self.search(search) + return none if term.blank? search = sanitize_sql_like(search) where("name LIKE ? OR phone_number LIKE ? OR mobile_phone_number LIKE ?", "%#{search}%", "%#{search}%", "%#{search}%") end @@ -177,39 +146,27 @@ class Customer < ActiveRecord::Base ids.index_with { |id| id } end - # proforms a bruteforce sync operation + # performs a sync operation for all customers def self.sync CustomerSyncJob.perform_later(full_sync: false) end - # proforms a bruteforce sync operation + # performs a sync operation for a specific customer def self.sync_by_id(id) CustomerSyncJob.perform_later(id: id) end # returns a human readable string def to_s - return "#{self[:name]} - #{phone_number.split(//).last(4).join unless phone_number.nil?}" + last4 = phone_number&.last(4) + last4.present? ? "#{name} - #{last4}" : name.to_s end # Push the updates def save_with_push - begin - qbo = Qbo.first - @details = qbo.perform_authenticated_request do |access_token| - service = Quickbooks::Service::Customer.new( - company_id: qbo.realm_id, - access_token: access_token - ) - service.update(@details) - end - - self.id = @details.id - rescue => e - errors.add(:base, e.message) - return false - end - + qbo = QboConnectionService.current! + log "Starting push for customer ##{self.id}..." + CustomerPushService.new(qbo: qbo, customer: self).push() save_without_push end @@ -217,19 +174,27 @@ class Customer < ActiveRecord::Base alias_method :save, :save_with_push private - - # pull the details - def pull - begin - raise Exception unless self.id - qbo = QboConnectionService.current! - @details = qbo.perform_authenticated_request do |access_token| - service = Quickbooks::Service::Customer.new(company_id: qbo.realm_id, access_token: access_token) - service.fetch_by_id(self.id) - end - rescue Exception => e - @details = Quickbooks::Model::Customer.new + + # Fetches the customer's details from QuickBooks Online. If the customer has an ID, it makes an authenticated request to QBO to retrieve the customer's information. If the customer does not have an ID or if there is an error during the fetch, it returns a new instance of Quickbooks::Model::Customer with default values. This method is used to ensure that the customer object has the most up-to-date information from QBO when needed. + def fetch_details + return Quickbooks::Model::Customer.new unless id.present? + log "Fetching details for customer ##{id} from QBO..." + qbo = QboConnectionService.current! + qbo.perform_authenticated_request do |access_token| + service = Quickbooks::Service::Customer.new( + company_id: qbo.realm_id, + access_token: access_token + ) + service.fetch_by_id(id) end + rescue => e + log "Fetch failed for #{id}: #{e.message}" + Quickbooks::Model::Customer.new + end + + # Log messages with the entity type for better traceability + def log(msg) + Rails.logger.info "[Customer] #{msg}" end end diff --git a/app/services/customer_push_service.rb b/app/services/customer_push_service.rb new file mode 100644 index 0000000..5fc1fe1 --- /dev/null +++ b/app/services/customer_push_service.rb @@ -0,0 +1,43 @@ +#The MIT License (MIT) +# +#Copyright (c) 2016 - 2026 rick barrette +# +#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +# +#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +# +#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +class CustomerPushService + + # Initializes the service with a QBO client and an optional customer record. The QBO client is used to communicate with QuickBooks Online, while the customer record contains the data that needs to be pushed to QBO. If no customer is provided, the service will not perform any operations. + def initialize(qbo:, customer: nil) + raise "No QBO configuration found" unless qbo + raise "Customer record is required for push operation" unless customer + @qbo = qbo + @customer = customer + end + + # Log messages with the entity type for better traceability + def log(msg) + Rails.logger.info "[CustomerPushService] #{msg}" + end + + # Pushes the customer data to QuickBooks Online. This method handles the communication with QBO, including authentication and error handling. It uses the QBO client to send the customer data and logs the process for monitoring and debugging purposes. If the push is successful, it returns the customer record; otherwise, it logs the error and returns false. + def push + log "Pushing customer ##{@customer.id} to QBO..." + + customer = @qbo.perform_authenticated_request do |access_token| + service = Quickbooks::Service::Customer.new( + company_id: @qbo.realm_id, + access_token: access_token + ) + service.update(@customer.details) + end + + @customer.id = customer.id unless @customer.persisted? + log "Push for customer ##{@customer.id} completed." + return @customer + end + +end \ No newline at end of file