Compare commits

...

5 Commits

8 changed files with 159 additions and 40 deletions

View File

@@ -96,17 +96,7 @@ class QboController < ApplicationController
CustomerSyncJob.perform_later(full_sync: true) CustomerSyncJob.perform_later(full_sync: true)
EstimateSyncJob.perform_later(full_sync: true) EstimateSyncJob.perform_later(full_sync: true)
InvoiceSyncJob.perform_later(full_sync: true) InvoiceSyncJob.perform_later(full_sync: true)
EmployeeSyncJob.perform_later(full_sync: true)
# Update info in background
Thread.new do
if Qbo.exists?
Employee.sync
# Record the last sync time
Qbo.update_time_stamp
end
ActiveRecord::Base.connection.close
end
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_to :home, flash: { notice: I18n.t(:label_syncing) }
end end

View File

@@ -0,0 +1,35 @@
#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 EmployeeSyncJob < ApplicationJob
queue_as :default
retry_on StandardError, wait: 5.minutes, attempts: 5
def perform(full_sync: false, id: nil)
qbo = Qbo.first
return unless qbo
log "Starting #{full_sync ? 'full' : 'incremental'} sync for employee ##{id || 'all'}..."
service = EmployeeSyncService.new(qbo: qbo)
if id.present?
service.sync_by_id(id)
else
service.sync(full_sync: full_sync)
end
end
private
def log(msg)
Rails.logger.info "[EmployeeSyncJob] #{msg}"
end
end

View File

@@ -15,6 +15,7 @@ class WebhookProcessJob < ActiveJob::Base
Customer Customer
Invoice Invoice
Estimate Estimate
Employee
].freeze ].freeze
# Process incoming QBO webhook notifications and sync relevant data to Redmine # Process incoming QBO webhook notifications and sync relevant data to Redmine

View File

@@ -21,14 +21,17 @@ class CustomerToken < ApplicationRecord
TOKEN_EXPIRATION = 1.month TOKEN_EXPIRATION = 1.month
# Check if the token has expired
def expired? def expired?
expires_at.present? && expires_at <= Time.current expires_at.present? && expires_at <= Time.current
end end
# Remove expired tokens from the database
def self.remove_expired_tokens def self.remove_expired_tokens
where("expires_at <= ?", Time.current).delete_all where("expires_at <= ?", Time.current).delete_all
end end
# Get or create a token for the given issue
def self.get_token(issue) def self.get_token(issue)
return unless issue return unless issue
return unless User.current.allowed_to?(:view_issues, issue.project) return unless User.current.allowed_to?(:view_issues, issue.project)
@@ -41,10 +44,12 @@ class CustomerToken < ApplicationRecord
private private
# Generate a unique token for the customer
def generate_token def generate_token
self.token ||= SecureRandom.urlsafe_base64(32) self.token ||= SecureRandom.urlsafe_base64(32)
end end
# Generate an expiration date for the token
def generate_expire_date def generate_expire_date
self.expires_at ||= Time.current + TOKEN_EXPIRATION self.expires_at ||= Time.current + TOKEN_EXPIRATION
end end

View File

@@ -12,38 +12,17 @@ class Employee < ActiveRecord::Base
has_many :users has_many :users
validates_presence_of :id, :name validates_presence_of :id, :name
def self.sync
qbo = Qbo.first
employees = qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Employee.new(company_id: qbo.realm_id, access_token: access_token)
service.all
end
return unless employees self.primary_key = :id
transaction do # Sync all employees, typically triggered by a scheduled task or manual sync request
employees.each { |e| def self.sync
logger.info "Processing employee #{e.id}" EmployeeSyncJob.perform_later(full_sync: true)
employee = find_or_create_by(id: e.id)
employee.name = e.display_name
employee.id = e.id
employee.save!
}
end
end end
# Sync a single employee by ID, typically triggered by a webhook notification or manual sync request
def self.sync_by_id(id) def self.sync_by_id(id)
qbo = Qbo.first EmployeeSyncJob.perform_later(id: id)
employee = qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Employee.new(company_id: qbo.realm_id, access_token: access_token)
service.fetch_by_id(id)
end
return unless employee
employee = find_or_create_by(id: employee.id)
employee.name = employee.display_name
employee.id = employee.id
employee.save!
end end
end end

View File

@@ -22,6 +22,7 @@ class Invoice < ActiveRecord::Base
doc_number doc_number
end end
# Sync all invoices from QuickBooks, typically triggered by a scheduled task or manual sync request
def self.sync def self.sync
InvoiceSyncJob.perform_later(full_sync: true) InvoiceSyncJob.perform_later(full_sync: true)
end end

View File

@@ -0,0 +1,93 @@
#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 EmployeeSyncService
PAGE_SIZE = 1000
def initialize(qbo:)
@qbo = qbo
end
# Sync all employees, or only those updated since the last sync
def sync(full_sync: false)
log "Starting #{full_sync ? 'full' : 'incremental'} employee sync"
@qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Employee.new(company_id: @qbo.realm_id, access_token: access_token)
page = 1
loop do
collection = fetch_page(service, page, full_sync)
entries = Array(collection&.entries)
break if entries.empty?
entries.each { |remote| persist(remote) }
break if entries.size < PAGE_SIZE
page += 1
end
end
log "Employee sync complete"
end
# Sync a single employee by its QBO ID, used for webhook updates
def sync_by_id(id)
@qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Employee.new(company_id: @qbo.realm_id, access_token: access_token)
remote = service.fetch_by_id(id)
persist(remote)
end
end
private
# Fetch a page of employees, either all or only those updated since the last sync
def fetch_page(service, page, full_sync)
start_position = (page - 1) * PAGE_SIZE + 1
if full_sync
service.query("SELECT * FROM Employee STARTPOSITION #{start_position} MAXRESULTS #{PAGE_SIZE}")
else
last_update = Employee.maximum(:qbo_updated_at) || 1.year.ago
service.query(<<~SQL.squish)
SELECT * FROM Employee
WHERE MetaData.LastUpdatedTime > '#{last_update.utc.iso8601}'
STARTPOSITION #{start_position}
MAXRESULTS #{PAGE_SIZE}
SQL
end
end
# Create or update a local Employee record based on the QBO remote data
def persist(remote)
employee = Employee.find_or_initialize_by(id: remote.id)
if remote.active?
employee.name = remote.display_name
if employee.changed?
employee.save
log "Updated employee #{remote.id}"
end
else
if employee.persisted?
employee.destroy
log "Deleted employee #{remote.id}"
end
end
rescue => e
log "Failed to sync employee #{remote.id}: #{e.message}"
end
def log(msg)
Rails.logger.info "[EmployeeSyncService] #{msg}"
end
end

View File

@@ -0,0 +1,15 @@
#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 AddEmployeeTimestamp < ActiveRecord::Migration[7.0]
def change
add_timestamps(:employees, null: true)
end
end