Compare commits

...

51 Commits

Author SHA1 Message Date
a97d867610 Fixed the UI, now working 2026-03-05 07:53:23 -05:00
021a9ec0c6 Added Issue safe attributes for line items 2026-03-05 07:28:30 -05:00
f056c27bc5 Merge branch 'master' into lineitems 2026-03-05 07:08:30 -05:00
2520892e2c 2026.3.1 2026-03-04 20:14:16 -05:00
b96678a2e9 fixed accident deleteion details_cache_key 2026-03-04 20:09:13 -05:00
bccfcd9dbc cache qbo details to reduce api calls 2026-03-04 20:06:22 -05:00
8ba99b7db2 Fixed eager loading issues 2026-03-04 19:18:06 -05:00
aff7d0c48e removed uneeded logging of issue and project contents. 2026-03-04 18:37:30 -05:00
e9b3b1c838 Merge branch 'master' into dev 2026-03-04 17:42:42 -05:00
2fc2f94cd1 Fixed combining of estimate pdf 2026-03-04 13:23:59 -05:00
681747e08b Got the UI working 2026-03-04 07:55:35 -05:00
9f9810686f removed logging 2026-03-03 20:36:23 -05:00
f041e1bce4 Added logging for completed pull 2026-03-03 20:05:19 -05:00
d44d5e2fb7 Fixed log prefix 2026-03-03 19:54:50 -05:00
4403267abb Moved QBO fetch from customer model into service 2026-03-03 19:49:36 -05:00
be400c2b2a Added logging for errors when editing 2026-03-03 19:22:15 -05:00
23e565a304 raise exceptions if not initialized properly 2026-03-02 22:57:13 -05:00
2e2b17fac3 log should be private 2026-03-02 22:54:26 -05:00
28db5cb8c8 removed unused code 2026-03-02 22:50:43 -05:00
0df15693d2 removed unused begin 2026-03-02 22:49:53 -05:00
f8b1c72394 show all customer when search is blank 2026-03-02 22:49:18 -05:00
899237c5ab Reduced blanket rescues, added respond_to_missing?, and extracted push into CustomerPushService 2026-03-02 22:41:22 -05:00
f02b50ae26 Added time stamps to each qbo entity model 2026-03-02 07:10:13 -05:00
485a977d1a Use Safe Navigation Operator &. 2026-03-01 21:31:28 -05:00
03d5a5d148 Always show sync status 2026-03-01 21:25:07 -05:00
0deab9dbd3 2026.3.0 2026-03-01 19:35:55 -05:00
899c9878c4 Fix: only attach invoices if document is updated 2026-03-01 19:27:23 -05:00
eb6beea5fa Initial line item idea 2026-03-01 15:04:25 -05:00
b95a3b6623 Refactor: Update billing error messages in locale for consistency and clarity 2026-03-01 12:35:54 -05:00
ef3f00c445 Refactor: Replace BillingValidator with inline validations in bill method and update error messages in locale 2026-03-01 12:29:20 -05:00
46f06df995 Removed unused service 2026-03-01 12:14:53 -05:00
b15b88f48d Fix: Correct I18n reference in last_sync method for proper translation 2026-03-01 01:07:43 -05:00
7b7b07b5fa fixed file name 2026-03-01 01:01:26 -05:00
16ca1caabc Refactor: Enhance QboWebhookProcessor with logging for signature validation 2026-03-01 00:58:46 -05:00
69d266bdca formatting 2026-03-01 00:45:27 -05:00
3728ec2a12 Refactor: Improve address formatting in CustomersController and enhance HTML rendering for billing and shipping addresses 2026-03-01 00:40:11 -05:00
cefa36c880 Removed unsued Customer destroy method 2026-03-01 00:28:57 -05:00
ed111fefe7 Refactor: Update QBO connection handling to use QboConnectionService for consistency across services and controllers 2026-03-01 00:27:06 -05:00
5a662f67b8 Removed sync from migration 2026-02-28 23:45:55 -05:00
6e90548dbb Removed unused method 2026-02-28 22:56:03 -05:00
f921f227e2 Refactor: Introduce PdfServiceBase for shared PDF fetching functionality and update Invoice/Estimate controllers to utilize new services 2026-02-28 21:59:01 -05:00
a34ae46358 Refactor: Simplify invoice PDF fetching and introduce InvoicePdfService for better organization 2026-02-28 21:36:16 -05:00
e4cfb0674e Refactor: Enhance estimate loading and syncing logic in EstimateController 2026-02-28 21:20:35 -05:00
348c521491 Added comments 2026-02-28 20:03:19 -05:00
6cee8c1d81 Fix: Remove logging of fetched page information in SyncServiceBase 2026-02-28 19:59:50 -05:00
d4a0aa1db5 Refactor: Introduce SyncServiceBase for shared functionality across sync services 2026-02-28 19:47:45 -05:00
12884a211e Added comments 2026-02-28 18:04:38 -05:00
4ed71f5667 Fix: Remove unnecessary QBO configuration check in billing enqueue method 2026-02-28 18:01:32 -05:00
8303dec501 Fix: Raise error if no QBO configuration is found in sync jobs 2026-02-28 17:58:11 -05:00
9b07ae7073 Fix: Ensure retry_on configuration specifies wait time and attempts for error handling 2026-02-28 17:51:48 -05:00
baf321d4d6 Fix: Update retry_on configuration to specify wait time for error handling 2026-02-28 17:51:31 -05:00
49 changed files with 993 additions and 833 deletions

View File

@@ -66,79 +66,76 @@ class CustomersController < ApplicationController
# create a new customer # create a new customer
def create def create
@customer = Customer.new(allowed_params) @customer = Customer.new(allowed_params)
if @customer.save @customer.save
flash[:notice] = t :notice_customer_created log "Customer ##{@customer.id} created successfully."
redirect_to @customer flash[:notice] = t :notice_customer_created
else redirect_to @customer
flash[:error] = @customer.errors.full_messages.to_sentence rescue => e
redirect_to new_customer_path log "Failed to create customer: #{e.message}"
end flash[:error] = e.message
redirect_to new_customer_path
end end
# display a specific customer # display a specific customer
def show def show
begin @customer = Customer.find_by_id(params[:id])
@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) @open_issues = @customer.issues
@shipping_address = address_to_s(@customer.shipping_address) .joins(:status)
@closed_issues = (@issues - @issues.open) .includes(:status, :project, :tracker, :priority)
@hours = 0 .where(issue_statuses: { is_closed: false })
@closed_hours = 0 .order(id: :desc)
@issues.open.each { |i| @hours+= i.total_spent_hours }
@closed_issues.each { |i| @closed_hours+= i.total_spent_hours } @closed_issues = @customer.issues
rescue .joins(:status)
flash[:error] = t :notice_customer_not_found .includes(:status, :project, :tracker, :priority)
render_404 .where(issue_statuses: { is_closed: true })
end .order(id: :desc)
@hours = TimeEntry
.joins(:issue)
.where(issues: { id: @open_issues.select(:id) })
.sum(:hours)
@closed_hours = TimeEntry
.joins(:issue)
.where(issues: { id: @closed_issues.select(:id) })
.sum(:hours)
rescue => e
Rails.logger.error "Failed to load customer ##{params[:id]}: #{e.message}\n#{e.backtrace.join("\n")}"
flash[:error] = e.message
render_404
end end
# return an HTML form for editing a customer # return an HTML form for editing a customer
def edit def edit
begin @customer = Customer.find_by_id(params[:id])
@customer = Customer.find_by_id(params[:id]) return render_404 unless @customer
rescue rescue => e
flash[:error] = t :notice_customer_not_found log "Failed to edit customer"
render_404 flash[:error] = e.message
end render_404
end end
# update a specific customer # update a specific customer
def update def update
begin @customer = Customer.find_by_id(params[:id])
@customer = Customer.find_by_id(params[:id]) @customer.update(allowed_params)
if @customer.update(allowed_params) flash[:notice] = t :notice_customer_updated
flash[:notice] = t :notice_customer_updated redirect_to @customer
redirect_to @customer rescue => e
else log "Failed to update customer: #{e.message}"
redirect_to edit_customer_path flash[:error] = e.message
flash[:error] = @customer.errors.full_messages.to_sentence if @customer.errors redirect_to edit_customer_path
end
rescue
flash[:error] = t :notice_customer_not_found
render_404
end
end
# delete a customer
def destroy
begin
Customer.find_by_id(params[:id]).destroy
flash[:notice] = t :notice_customer_deleted
redirect_to action: :index
rescue
flash[:error] = t :notice_customer_not_deleted
render_404
end
end end
# creates new customer view tokens, removes expired tokens & redirects to newly created customer view with new token. # creates new customer view tokens, removes expired tokens & redirects to newly created customer view with new token.
def share def share
issue = Issue.find(params[:id]) issue = Issue.find(params[:id])
token = issue.share_token token = issue.share_token
redirect_to view_path(token.token) redirect_to view_path(token.token)
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
flash[:error] = t(:notice_issue_not_found) flash[:error] = t(:notice_issue_not_found)
render_404 render_404
@@ -212,17 +209,26 @@ class CustomersController < ApplicationController
end end
# format a quickbooks address to a human readable string # format a quickbooks address to a human readable string
def address_to_s (address) def address_to_s(address)
return if address.nil? return if address.nil?
string = address.line1 if address.line1
string << "\n" + address.line2 if address.line2 lines = [
string << "\n" + address.line3 if address.line3 address.line1,
string << "\n" + address.line4 if address.line4 address.line2,
string << "\n" + address.line5 if address.line5 address.line3,
string << " " + address.city if address.city address.line4,
string << ", " + address.country_sub_division_code if address.country_sub_division_code address.line5
string << " " + address.postal_code if address.postal_code ].compact_blank
return string
city_line = [
address.city,
address.country_sub_division_code,
address.postal_code
].compact_blank.join(" ")
lines << city_line unless city_line.blank?
lines.join("\n")
end end
def log(msg) def log(msg)

View File

@@ -8,71 +8,72 @@
# #
#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. #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 EstimateController < ApplicationController class EstimateController < ApplicationController
include AuthHelper include AuthHelper
before_action :require_user, unless: -> { session[:token].nil? }
skip_before_action :verify_authenticity_token, :check_if_login_required, unless: -> { session[:token].nil? }
before_action :load_estimate, only: [:show, :doc]
before_action :require_user, unless: proc {|c| session[:token].nil? } # Displays the estimate PDF in the browser or redirects with an error if not found.
skip_before_action :verify_authenticity_token, :check_if_login_required, unless: proc {|c| session[:token].nil? }
def get_estimate
log "Searching for estimate with params: #{params.inspect}"
e = Estimate.find_by_doc_number(params[:search]) if params[:search]
e = Estimate.find_by_id(params[:id]) if params[:id]
# Force sync for estimate by doc number if not found
if e.nil? && params[:search]
begin
Estimate.sync_by_doc_number(params[:search])
e = Estimate.find_by_doc_number(params[:search])
rescue
log "Estimate.find_by_doc_number failed"
end
end
# Force sync for estimate by id if not found
if e.nil? && params[:id]
begin
Estimate.sync_by_id(params[:id])
e = Estimate.find_by_id(params[:id])
rescue
log "Estimate.find_by_id failed"
end
end
return e
end
#
# Downloads and forwards the estimate pdf
#
def show
estimate = get_estimate
begin
send_data estimate.pdf, filename: "estimate #{estimate.doc_number}.pdf", disposition: :inline, type: "application/pdf"
rescue
redirect_to :back, flash: { error: I18n.t(:notice_estimate_not_found) }
end
end
#
# Downloads estimate by document number
#
def doc def doc
estimate = get_estimate render_pdf(@estimate)
end
begin
send_data estimate.pdf, filename: "estimate #{estimate.doc_number}.pdf", disposition: :inline, type: "application/pdf" # Displays the estimate PDF in the browser or redirects with an error if not found.
rescue def show
redirect_to :back, flash: { error: I18n.t(:notice_estimate_not_found) } render_pdf(@estimate)
end
end end
private private
# Loads the estimate based on ID or doc number, with a fallback to sync if not found locally.
def load_estimate
log "Attempting to load Estimate with params: #{params.inspect}"
@estimate = find_estimate || sync_and_find_estimate
unless @estimate
redirect_back fallback_location: root_path, flash: { error: I18n.t(:notice_estimate_not_found) }
end
end
# Attempts to find the estimate locally by ID or doc number.
def find_estimate
return Estimate.find_by(doc_number: params[:search]) if params[:search].present?
return Estimate.find_by(id: params[:id]) if params[:id].present?
end
# If the estimate is not found locally, attempts to sync it from the source and find it again.
def sync_and_find_estimate
if params[:search].present?
log "Estimate #{params[:search]} not found locally. Syncing by doc number."
Estimate.sync_by_doc_number(params[:search])
return Estimate.find_by(doc_number: params[:search])
end
if params[:id].present?
log "Estimate #{params[:id]} not found locally. Syncing by ID."
Estimate.sync_by_id(params[:id])
return Estimate.find_by(id: params[:id])
end
nil
rescue StandardError => e
log "Estimate sync failed: #{e.message}"
nil
end
# Renders the estimate PDF or redirects with an error if rendering fails.
def render_pdf(estimate)
pdf, ref = EstimatePdfService.new(qbo: QboConnectionService.current!).fetch_pdf(doc_ids: [estimate.id])
send_data( pdf, filename: "estimate #{ref}.pdf", disposition: :inline, type: "application/pdf" )
rescue StandardError => e
log "PDF render failed for Estimate #{estimate&.id}: #{e.message}"
redirect_back fallback_location: root_path, flash: { error: I18n.t(:notice_estimate_not_found) }
end
# Logs messages with a consistent prefix for easier debugging.
def log(msg) def log(msg)
Rails.logger.info "[EstimateController] #{msg}" Rails.logger.info "[EstimateController] #{msg}"
end end
end
end

View File

@@ -8,53 +8,29 @@
# #
#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. #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 InvoiceController < ApplicationController class InvoiceController < ApplicationController
include AuthHelper include AuthHelper
require 'combine_pdf'
before_action :require_user, unless: proc {|c| session[:token].nil? } before_action :require_user, unless: -> { session[:token].nil? }
skip_before_action :verify_authenticity_token, :check_if_login_required, unless: proc {|c| session[:token].nil? } skip_before_action :verify_authenticity_token, :check_if_login_required, unless: -> { session[:token].nil? }
# # Displays the invoice PDF in the browser or redirects with an error if not found.
# Downloads and forwards the invoice pdf
#
def show def show
log "Processing request for URL: #{request.original_url}" log "Processing request for #{request.original_url}"
begin
qbo = Qbo.first
qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Invoice.new(company_id: qbo.realm_id, access_token: access_token)
# If multiple id's then pull each pdf & combine them
if params[:invoice_ids]
log "Grabbing pdfs for " + params[:invoice_ids].join(', ')
ref = ""
params[:invoice_ids].each do |i|
log "processing " + i
invoice = service.fetch_by_id(i)
ref += " #{invoice.doc_number}"
@pdf << CombinePDF.parse(service.pdf(invoice)) unless @pdf.nil?
if @pdf.nil?
@pdf = CombinePDF.parse(service.pdf(invoice))
end
end
@pdf = @pdf.to_pdf
else
invoice = service.fetch_by_id(params[:id])
@pdf = service.pdf(invoice)
ref = invoice.doc_number
end
send_data @pdf, filename: "invoice #{ref}.pdf", disposition: :inline, type: "application/pdf" invoice_ids = Array(params[:invoice_ids] || params[:id])
end pdf, ref = InvoicePdfService.new(qbo: QboConnectionService.current!).fetch_pdf(doc_ids: invoice_ids)
rescue
redirect_to :back, flash: { error: I18n.t(:notice_invoice_not_found) } send_data pdf, filename: "invoice #{ref}.pdf", disposition: :inline, type: "application/pdf"
end
rescue StandardError => e
log "Invoice PDF failure: #{e.message}"
redirect_back fallback_location: root_path, flash: { error: I18n.t(:notice_invoice_not_found) }
end end
private private
# Logs messages with a consistent prefix for easier debugging.
def log(msg) def log(msg)
Rails.logger.info "[InvoiceController] #{msg}" Rails.logger.info "[InvoiceController] #{msg}"
end end
end end

View File

View File

@@ -9,129 +9,68 @@
#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. #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 QboController < ApplicationController class QboController < ApplicationController
require 'openssl'
include AuthHelper include AuthHelper
before_action :require_user, except: :webhook before_action :require_user, except: :webhook
skip_before_action :verify_authenticity_token, :check_if_login_required, only: [:webhook] skip_before_action :verify_authenticity_token, :check_if_login_required, only: :webhook
def allowed_params # Initiates the OAuth authentication process by redirecting the user to the QuickBooks authorization URL. The callback URL is generated based on the application's settings and routes.
params.permit(:code, :state, :realmId, :id)
end
#
# Called when the user requests that Redmine to connect to QBO
#
def authenticate def authenticate
redirect_uri = "#{Setting.protocol}://#{Setting.host_name + qbo_oauth_callback_path}" redirect_to QboOauthService.authorization_url(callback_url: callback_url)
log "redirect_uri: #{redirect_uri}"
oauth2_client = Qbo.construct_oauth2_client
grant_url = oauth2_client.auth_code.authorize_url(redirect_uri: redirect_uri, response_type: "code", state: SecureRandom.hex(12), scope: "com.intuit.quickbooks.accounting")
redirect_to grant_url
end end
# # Handles the OAuth callback from QuickBooks. Exchanges the authorization code for access and refresh tokens, saves the connection details, and redirects to the sync page with a success notice. If any error occurs during the process, logs the error and redirects back to the plugin settings page with an error message.
# Called by QBO after authentication has been processed
#
def oauth_callback def oauth_callback
if params[:state].present? QboOauthService.exchange!(code: params[:code], callback_url: callback_url, realm_id: params[:realmId])
oauth2_client = Qbo.construct_oauth2_client
# use the state value to retrieve from your backend any information you need to identify the customer in your system redirect_to qbo_sync_path, flash: { notice: I18n.t(:label_connected) }
redirect_uri = "#{Setting.protocol}://#{Setting.host_name + qbo_oauth_callback_path}"
if resp = oauth2_client.auth_code.get_token(params[:code], redirect_uri: redirect_uri) rescue StandardError => e
log "OAuth failure: #{e.message}"
# Remove the last authentication information redirect_to plugin_settings_path(:redmine_qbo), flash: { error: I18n.t(:label_error) }
Qbo.delete_all
# Save the authentication information
qbo = Qbo.new
qbo.update(oauth2_access_token: resp.token, oauth2_refresh_token: resp.refresh_token, realm_id: params[:realmId])
qbo.refresh_token!
if qbo.save!
redirect_to qbo_sync_path, flash: { notice: I18n.t(:label_connected) }
else
redirect_to plugin_settings_path(:redmine_qbo), flash: { error: I18n.t(:label_error) }
end
end
end
end end
# Manual Billing # Manual billing endpoint to trigger the billing process for a specific issue. Validates the issue and its associations, enqueues a job to bill the issue's time entries, and redirects back to the issue with a notice. If validation fails, redirects back with an error message.
def bill def bill
issue = Issue.find_by(id: params[:id]) issue = Issue.find_by(id: params[:id])
return render_404 unless issue raise I18n.t(:notice_error_issue_not_found) unless issue
raise I18n.t(:notice_billing_error_no_customer) unless issue.customer
unless issue.customer raise I18n.t(:notice_billing_error_no_employee) unless issue.assigned_to&.employee_id.present?
redirect_to issue, flash: { error: I18n.t(:label_billing_error_no_customer) } raise I18n.t(:notice_billing_error_no_qbo) unless Qbo.exists?
return
end
unless issue.assigned_to&.employee_id.present?
redirect_to issue, flash: { error: I18n.t(:label_billing_error_no_employee) }
return
end
unless Qbo.first
redirect_to issue, flash: { error: I18n.t(:label_billing_error_no_qbo) }
return
end
BillIssueTimeJob.perform_later(issue.id) BillIssueTimeJob.perform_later(issue.id)
redirect_to issue, flash: { redirect_to issue, flash: { notice: "#{I18n.t(:label_billing_enqueued)} #{issue.customer.name}"}
notice: I18n.t(:label_billing_enqueued) + " #{issue.customer.name}"
} rescue StandardError => e
redirect_to issue || root_path, flash: { error: e.message }
end end
# # Manual sync endpoint to trigger a full synchronization of QuickBooks entities with the local database. Enqueues all relevant sync jobs and redirects to the home page with a notice that syncing has started.
# Synchronizes the QboCustomer table with QBO
#
def sync def sync
log "Syncing EVERYTHING" QboSyncDispatcher.full_sync!
CustomerSyncJob.perform_later(full_sync: true)
EstimateSyncJob.perform_later(full_sync: true)
InvoiceSyncJob.perform_later(full_sync: true)
EmployeeSyncJob.perform_later(full_sync: true)
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_to :home, flash: { notice: I18n.t(:label_syncing) }
end end
# QuickBooks Webhook Callback # Endpoint to receive QuickBooks webhook notifications. Validates the request and processes the payload to sync relevant data to Redmine. Responds with appropriate HTTP status codes based on success or failure of processing.
def webhook def webhook
log "Webhook received" QboWebhookProcessor.process!(request: request)
signature = request.headers['intuit-signature']
key = Setting.plugin_redmine_qbo['settingsWebhookToken']
body = request.raw_post
digest = OpenSSL::Digest.new('sha256')
computed = Base64.strict_encode64(OpenSSL::HMAC.digest(digest, key, body))
unless secure_compare(computed, signature)
log "Invalid webhook signature"
head :unauthorized
return
end
WebhookProcessJob.perform_later(body)
head :ok head :ok
rescue StandardError => e
log "Webhook failure: #{e.message}"
head :unauthorized
end end
private private
# Securely compare two strings to prevent timing attacks. Returns false if either string is blank or if they do not match. # Constructs the OAuth callback URL based on the application's settings and routes. This URL is used during the OAuth flow to redirect users back to the application after authentication with QuickBooks.
def secure_compare(a, b) def callback_url
return false if a.blank? || b.blank? "#{Setting.protocol}://#{Setting.host_name}#{qbo_oauth_callback_path}"
ActiveSupport::SecurityUtils.secure_compare(a, b)
end end
# Logs messages with a consistent prefix for easier debugging and monitoring.
def log(msg) def log(msg)
Rails.logger.info "[QboController] #{msg}" Rails.logger.info "[QboController] #{msg}"
end end
end end

View File

@@ -10,6 +10,7 @@
class BillIssueTimeJob < ActiveJob::Base class BillIssueTimeJob < ActiveJob::Base
queue_as :default queue_as :default
retry_on StandardError, wait: 5.minutes, attempts: 5
# Perform billing of unbilled time entries for a given issue by creating corresponding TimeActivity records in QuickBooks Online, and then marking those entries as billed in Redmine. This job is typically triggered after an invoice is created or updated to ensure all relevant time is captured for billing. # Perform billing of unbilled time entries for a given issue by creating corresponding TimeActivity records in QuickBooks Online, and then marking those entries as billed in Redmine. This job is typically triggered after an invoice is created or updated to ensure all relevant time is captured for billing.
def perform(issue_id) def perform(issue_id)
@@ -26,7 +27,7 @@ class BillIssueTimeJob < ActiveJob::Base
return if totals.blank? return if totals.blank?
log "Aggregated hours for billing: #{totals.inspect}" log "Aggregated hours for billing: #{totals.inspect}"
qbo = Qbo.first qbo = QboConnectionService.current!
raise "No QBO configuration found" unless qbo raise "No QBO configuration found" unless qbo
qbo.perform_authenticated_request do |access_token| qbo.perform_authenticated_request do |access_token|
@@ -57,16 +58,10 @@ class BillIssueTimeJob < ActiveJob::Base
# Create TimeActivity records in QBO for each activity type with the appropriate hours and link them to the issue's assigned employee and customer # Create TimeActivity records in QBO for each activity type with the appropriate hours and link them to the issue's assigned employee and customer
def create_time_activities(issue, totals, access_token, qbo) def create_time_activities(issue, totals, access_token, qbo)
log "Creating TimeActivity records in QBO for issue ##{issue.id}" log "Creating TimeActivity records in QBO for issue ##{issue.id}"
time_service = Quickbooks::Service::TimeActivity.new(
company_id: qbo.realm_id, time_service = Quickbooks::Service::TimeActivity.new( company_id: qbo.realm_id, access_token: access_token)
access_token: access_token item_service = Quickbooks::Service::Item.new( company_id: qbo.realm_id, access_token: access_token )
)
item_service = Quickbooks::Service::Item.new(
company_id: qbo.realm_id,
access_token: access_token
)
totals.each do |activity_name, hours_float| totals.each do |activity_name, hours_float|
next if activity_name.blank? next if activity_name.blank?
next if hours_float.to_f <= 0 next if hours_float.to_f <= 0

View File

@@ -14,8 +14,8 @@ class CustomerSyncJob < ApplicationJob
# Perform a full sync of all customers, or an incremental sync of only those updated since the last sync # Perform a full sync of all customers, or an incremental sync of only those updated since the last sync
def perform(full_sync: false, id: nil) def perform(full_sync: false, id: nil)
qbo = Qbo.first qbo = QboConnectionService.current!
return unless qbo raise "No QBO configuration found" unless qbo
log "Starting #{full_sync ? 'full' : 'incremental'} sync for customer ##{id || 'all'}..." log "Starting #{full_sync ? 'full' : 'incremental'} sync for customer ##{id || 'all'}..."

View File

@@ -12,9 +12,10 @@ class EmployeeSyncJob < ApplicationJob
queue_as :default queue_as :default
retry_on StandardError, wait: 5.minutes, attempts: 5 retry_on StandardError, wait: 5.minutes, attempts: 5
# Performs a sync of employees from QuickBooks Online.
def perform(full_sync: false, id: nil) def perform(full_sync: false, id: nil)
qbo = Qbo.first qbo = QboConnectionService.current!
return unless qbo raise "No QBO configuration found" unless qbo
log "Starting #{full_sync ? 'full' : 'incremental'} sync for employee ##{id || 'all'}..." log "Starting #{full_sync ? 'full' : 'incremental'} sync for employee ##{id || 'all'}..."

View File

@@ -12,9 +12,10 @@ class EstimateSyncJob < ApplicationJob
queue_as :default queue_as :default
retry_on StandardError, wait: 5.minutes, attempts: 5 retry_on StandardError, wait: 5.minutes, attempts: 5
# Performs a sync of estimates from QuickBooks Online.
def perform(full_sync: false, id: nil, doc_number: nil) def perform(full_sync: false, id: nil, doc_number: nil)
qbo = Qbo.first qbo = QboConnectionService.current!
return unless qbo raise "No QBO configuration found" unless qbo
log "Starting #{full_sync ? 'full' : 'incremental'} sync for estimate ##{id || doc_number || 'all'}..." log "Starting #{full_sync ? 'full' : 'incremental'} sync for estimate ##{id || doc_number || 'all'}..."

View File

@@ -12,9 +12,10 @@ class InvoiceSyncJob < ApplicationJob
queue_as :default queue_as :default
retry_on StandardError, wait: 5.minutes, attempts: 5 retry_on StandardError, wait: 5.minutes, attempts: 5
# Performs a sync of invoices from QuickBooks Online.
def perform(full_sync: false, id: nil) def perform(full_sync: false, id: nil)
qbo = Qbo.first qbo = QboConnectionService.current!
return unless qbo raise "No QBO configuration found" unless qbo
log "Starting #{full_sync ? 'full' : 'incremental'} sync for invoice ##{id || 'all'}..." log "Starting #{full_sync ? 'full' : 'incremental'} sync for invoice ##{id || 'all'}..."

View File

@@ -0,0 +1,24 @@
#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 QboSyncDispatcher
SYNC_JOBS = [
CustomerSyncJob,
EstimateSyncJob,
InvoiceSyncJob,
EmployeeSyncJob
].freeze
# Dispatches all synchronization jobs to perform a full sync of QuickBooks entities with the local database. Each job is enqueued with the `full_sync` flag set to true.
def self.full_sync!
SYNC_JOBS.each { |job| job.perform_later(full_sync: true) }
end
end

View File

@@ -0,0 +1,42 @@
#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 QboWebhookProcessor
# Processes the incoming QuickBooks webhook request by validating the signature and enqueuing a background job to handle the webhook payload. Raises an error if the signature is invalid.
def self.process!(request:)
body = request.raw_post
signature = request.headers['intuit-signature']
secret = Setting.plugin_redmine_qbo['settingsWebhookToken']
raise "Invalid signature" unless valid_signature?(body, signature, secret)
WebhookProcessJob.perform_later(body)
end
private
# Validates the QuickBooks webhook request by computing the HMAC signature and comparing it to the provided signature. Returns false if either the signature or secret is blank, or if the computed signature does not match the provided signature.
def self.valid_signature?(body, signature, secret)
return false if signature.blank? || secret.blank?
log "Validating signature"
digest = OpenSSL::Digest.new('sha256')
computed = Base64.strict_encode64(
OpenSSL::HMAC.digest(digest, secret, body)
)
ActiveSupport::SecurityUtils.secure_compare(computed, signature)
end
def self.log(msg)
Rails.logger.info "[QboWebhookProcessor] #{msg}"
end
end

View File

@@ -10,6 +10,7 @@
class WebhookProcessJob < ActiveJob::Base class WebhookProcessJob < ActiveJob::Base
queue_as :default queue_as :default
retry_on StandardError, wait: 5.minutes, attempts: 5
ALLOWED_ENTITIES = %w[ ALLOWED_ENTITIES = %w[
Customer Customer

View File

@@ -11,13 +11,15 @@
class Customer < ActiveRecord::Base class Customer < ActiveRecord::Base
include Redmine::Acts::Searchable include Redmine::Acts::Searchable
include Redmine::Acts::Event include Redmine::Acts::Event
include Redmine::I18n
has_many :issues has_many :issues
has_many :invoices has_many :invoices
has_many :estimates has_many :estimates
validates_presence_of :id, :name validates_presence_of :id, :name
before_validation :normalize_phone_numbers
self.primary_key = :id self.primary_key = :id
@@ -30,128 +32,116 @@ class Customer < ActiveRecord::Base
:type => :to_s, :type => :to_s,
:description => Proc.new {|o| "#{I18n.t :label_primary_phone}: #{o.phone_number} #{I18n.t:label_mobile_phone}: #{o.mobile_phone_number}"}, :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} :datetime => Proc.new {|o| o.updated_at || o.created_at}
# Convenience Method # 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.
# returns the customer's email def details
def email return Quickbooks::Model::Customer.new unless id.present?
pull unless @details
begin @details ||= begin
return @details.email_address.address xml = Rails.cache.fetch(details_cache_key, expires_in: 10.minutes) do
rescue fetch_details.to_xml_ns
return nil end
Quickbooks::Model::Customer.from_xml(xml)
end end
end end
# Generates a unique cache key for storing this customer's QBO details.
def details_cache_key
"customer:#{id}:qbo_details:#{updated_at.to_i}"
end
# Returns the customer's email address
def email
details
return @details&.email_address&.address
end
# Convenience Method # Updates the customer's email address
# Sets the email
def email=(s) def email=(s)
pull unless @details details
@details.email_address = s @details.email_address = s
end end
# Convenience Method # Returns the last sync time formatted for display. If no sync has occurred, returns a default message.
# returns the customer's primary phone def self.last_sync
def primary_phone return I18n.t(:label_qbo_never_synced) unless maximum(:updated_at)
pull unless @details format_time(maximum(:updated_at))
begin
return @details.primary_phone.free_form_number
rescue
return nil
end
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 # Customers are not bound by a project
# but we need to implement this method for the Redmine::Acts::Searchable interface # but we need to implement this method for the Redmine::Acts::Searchable interface
def project def project
nil nil
end end
# Convenience Method # Magic Method
# returns the customer's mobile phone # Maps Get/Set methods to QBO customer object
def mobile_phone def method_missing(method_name, *args, &block)
pull unless @details if Quickbooks::Model::Customer.method_defined?(method_name)
begin details
return @details.mobile_phone.free_form_number @details.public_send(method_name, *args, &block)
rescue else
return nil super
end end
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 # Updates the custome's mobile phone number
def mobile_phone=(n) def mobile_phone=(n)
pull unless @details details
pn = Quickbooks::Model::TelephoneNumber.new pn = Quickbooks::Model::TelephoneNumber.new
pn.free_form_number = n pn.free_form_number = n
@details.mobile_phone = pn @details.mobile_phone = pn
#update our locally stored number too
update_mobile_phone_number
end 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 # Updates Both local DB name & QBO display_name
def name=(s) def name=(s)
pull unless @details details
@details.display_name = s @details.display_name = s
super super
end 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 # Updates the customer's primary phone number
# Maps Get/Set methods to QBO customer object def primary_phone=(n)
def method_missing(sym, *arguments) details
# Check to see if the method exists pn = Quickbooks::Model::TelephoneNumber.new
if Quickbooks::Model::Customer.method_defined?(sym) pn.free_form_number = n
# download details if required @details.primary_phone = pn
pull unless @details end
method_name = sym.to_s
# Setter # 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.
if method_name[-1, 1] == "=" def respond_to_missing?(method_name, include_private = false)
@details.method(method_name).call(arguments[0]) Quickbooks::Model::Customer.method_defined?(method_name) || super
# Getter
else
return @details.method(method_name).call
end
end
end end
# Seach for customers by name or phone number # Seach for customers by name or phone number
def self.search(search) def self.search(search)
#return none if search.blank?
search = sanitize_sql_like(search) search = sanitize_sql_like(search)
where("name LIKE ? OR phone_number LIKE ? OR mobile_phone_number LIKE ?", "%#{search}%", "%#{search}%", "%#{search}%") where("name LIKE ? OR phone_number LIKE ? OR mobile_phone_number LIKE ?", "%#{search}%", "%#{search}%", "%#{search}%")
end end
@@ -170,39 +160,28 @@ class Customer < ActiveRecord::Base
ids.index_with { |id| id } ids.index_with { |id| id }
end end
# proforms a bruteforce sync operation # performs a sync operation for all customers
def self.sync def self.sync
CustomerSyncJob.perform_later(full_sync: false) CustomerSyncJob.perform_later(full_sync: false)
end end
# proforms a bruteforce sync operation # performs a sync operation for a specific customer
def self.sync_by_id(id) def self.sync_by_id(id)
CustomerSyncJob.perform_later(id: id) CustomerSyncJob.perform_later(id: id)
end end
# returns a human readable string # returns a human readable string
def to_s 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 end
# Push the updates # Push the updates
def save_with_push def save_with_push
begin log "Starting push for customer ##{self.id}..."
qbo = Qbo.first qbo = QboConnectionService.current!
@details = qbo.perform_authenticated_request do |access_token| CustomerService.new(qbo: qbo, customer: self).push()
service = Quickbooks::Service::Customer.new( Rails.cache.delete(details_cache_key)
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
save_without_push save_without_push
end end
@@ -210,19 +189,18 @@ class Customer < ActiveRecord::Base
alias_method :save, :save_with_push alias_method :save, :save_with_push
private private
# pull the details # 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 pull def fetch_details
begin return Quickbooks::Model::Customer.new unless id.present?
raise Exception unless self.id log "Fetching details for customer ##{id} from QBO..."
qbo = Qbo.first qbo = QboConnectionService.current!
@details = qbo.perform_authenticated_request do |access_token| CustomerService.new(qbo: qbo, customer: self).pull()
service = Quickbooks::Service::Customer.new(company_id: qbo.realm_id, access_token: access_token) end
service.fetch_by_id(self.id)
end # Log messages with the entity type for better traceability
rescue Exception => e def log(msg)
@details = Quickbooks::Model::Customer.new Rails.logger.info "[Customer] #{msg}"
end
end end
end end

View File

@@ -10,11 +10,19 @@
class Employee < ActiveRecord::Base class Employee < ActiveRecord::Base
include Redmine::I18n
has_many :users has_many :users
validates_presence_of :id, :name validates_presence_of :id, :name
self.primary_key = :id self.primary_key = :id
# Returns the last sync time formatted for display. If no sync has occurred, returns a default message.
def self.last_sync
return I18n.t(:label_qbo_never_synced) unless maximum(:updated_at)
format_time(maximum(:updated_at))
end
# Sync all employees, typically triggered by a scheduled task or manual sync request # Sync all employees, typically triggered by a scheduled task or manual sync request
def self.sync def self.sync
EmployeeSyncJob.perform_later(full_sync: true) EmployeeSyncJob.perform_later(full_sync: true)

View File

@@ -10,11 +10,19 @@
class Estimate < ActiveRecord::Base class Estimate < ActiveRecord::Base
include Redmine::I18n
has_and_belongs_to_many :issues has_and_belongs_to_many :issues
belongs_to :customer belongs_to :customer
validates_presence_of :doc_number, :id validates_presence_of :doc_number, :id
self.primary_key = :id self.primary_key = :id
# Returns the last sync time formatted for display. If no sync has occurred, returns a default message.
def self.last_sync
return I18n.t(:label_qbo_never_synced) unless maximum(:updated_at)
format_time(maximum(:updated_at))
end
# returns a human readable string # returns a human readable string
def to_s def to_s
return self[:doc_number] return self[:doc_number]
@@ -35,51 +43,7 @@ class Estimate < ActiveRecord::Base
EstimateSyncJob.perform_later(doc_number: number) EstimateSyncJob.perform_later(doc_number: number)
end end
# download the pdf from quickbooks
def pdf
log "Downloading PDF for estimate ##{self.id}..."
qbo = Qbo.first
qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Estimate.new(company_id: qbo.realm_id, access_token: access_token)
estimate = service.fetch_by_id(id)
service.pdf(estimate)
end
end
# Magic Method
# Maps Get/Set methods to QBO estimate object
def method_missing(sym, *arguments)
# Check to see if the method exists
if Quickbooks::Model::Estimate.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
end
private private
# pull the details
def pull
log "Pulling details for estimate ##{self.id}..."
begin
raise Exception unless self.id
qbo = Qbo.first
@details = qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Estimate.new(company_id: qbo.realm_id, access_token: access_token)
service(:estimate).fetch_by_id(self.id)
end
rescue Exception => e
@details = Quickbooks::Model::Estimate.new
end
end
def log(msg) def log(msg)
Rails.logger.info "[Estimate] #{msg}" Rails.logger.info "[Estimate] #{msg}"

View File

@@ -9,6 +9,9 @@
#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. #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 Invoice < ActiveRecord::Base class Invoice < ActiveRecord::Base
include Redmine::I18n
has_and_belongs_to_many :issues has_and_belongs_to_many :issues
belongs_to :customer belongs_to :customer
@@ -17,6 +20,12 @@ class Invoice < ActiveRecord::Base
self.primary_key = :id self.primary_key = :id
# Returns the last sync time formatted for display. If no sync has occurred, returns a default message.
def self.last_sync
return I18n.t(:label_qbo_never_synced) unless maximum(:updated_at)
format_time(maximum(:updated_at))
end
# Return the invoice's document number as its string representation # Return the invoice's document number as its string representation
def to_s def to_s
doc_number doc_number

7
app/models/line_item.rb Normal file
View File

@@ -0,0 +1,7 @@
class LineItem < ApplicationRecord
belongs_to :issue
validates :description, presence: true
validates :quantity, numericality: { greater_than: 0 }
validates :unit_price, numericality: { greater_than_or_equal_to: 0 }
end

View File

@@ -12,24 +12,35 @@ class Qbo < ActiveRecord::Base
include QuickbooksOauth include QuickbooksOauth
include Redmine::I18n include Redmine::I18n
validate :single_record_only, on: :create
# Updates last sync time stamp # Updates last sync time stamp
def self.update_time_stamp def self.update_time_stamp
date = DateTime.now date = DateTime.now
log "Updating QBO timestamp to #{date}" log "Updating QBO timestamp to #{date}"
qbo = Qbo.first qbo = QboConnectionService.current!
qbo.last_sync = date qbo.last_sync = date
qbo.save qbo.save
end end
# Returns the last sync time formatted for display. If no sync has occurred, returns a default message.
def self.last_sync def self.last_sync
format_time(Qbo.first.last_sync) qbo = QboConnectionService.current!
return I18n.t(:label_qbo_never_synced) unless qbo&.last_sync
format_time(qbo.last_sync)
end end
private private
# Logs a message with a QBO-specific prefix for easier identification in the logs.
def self.log(msg) def self.log(msg)
logger.info "[QBO] #{msg}" logger.info "[QBO] #{msg}"
end end
# Validates that only one QBO connection record exists in the database. Adds an error if a record already exists.
def single_record_only
errors.add(:base, "Only one QBO connection allowed") if Qbo.exists?
end
end end

View File

@@ -0,0 +1,62 @@
#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 CustomerService
# 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
# Pulls the customer data from QuickBooks Online.
def pull
return Quickbooks::Model::Customer.new unless @customer.present?
log "Fetching details for customer ##{@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(@customer.id)
end
rescue => e
log "Fetch failed for #{@customer.id}: #{e.message}"
Quickbooks::Model::Customer.new
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
private
# Log messages with the entity type for better traceability
def log(msg)
Rails.logger.info "[CustomerService] #{msg}"
end
end

View File

@@ -8,88 +8,25 @@
# #
#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. #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 CustomerSyncService class CustomerSyncService < SyncServiceBase
PAGE_SIZE = 1000
def initialize(qbo:)
@qbo = qbo
end
# Sync all customers, or only those updated since the last sync
def sync(full_sync: false)
log "Starting #{full_sync ? 'full' : 'incremental'} customer sync"
@qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Customer.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 "Customer sync complete"
end
# Sync a single customer by its QBO ID, used for webhook updates
def sync_by_id(id)
@qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Customer.new(company_id: @qbo.realm_id, access_token: access_token)
remote = service.fetch_by_id(id)
persist(remote)
end
end
private private
# Fetch a page of customers, either all or only those updated since the last sync # Specify the local model this service syncs
def fetch_page(service, page, full_sync) def self.model_class
start_position = (page - 1) * PAGE_SIZE + 1 Customer
if full_sync
service.query("SELECT * FROM Customer STARTPOSITION #{start_position} MAXRESULTS #{PAGE_SIZE}")
else
last_update = Customer.maximum(:updated_at) || 1.year.ago
service.query(<<~SQL.squish)
SELECT * FROM Customer
WHERE MetaData.LastUpdatedTime > '#{last_update.utc.iso8601}'
STARTPOSITION #{start_position}
MAXRESULTS #{PAGE_SIZE}
SQL
end
end end
# Create or update a local Customer record based on the QBO remote data # Determine if the remote entity should be deleted locally (e.g. if it's marked inactive in QBO)
def persist(remote) def destroy_remote?(remote)
local = Customer.find_or_initialize_by(id: remote.id) !remote.active?
if remote.active?
local.name = remote.display_name
local.phone_number = remote.primary_phone&.free_form_number&.gsub(/\D/, '')
local.mobile_phone_number = remote.mobile_phone&.free_form_number&.gsub(/\D/, '')
if local.changed?
local.save
log "Updated customer #{remote.id}"
end
else
if local.persisted?
local.destroy
log "Deleted customer #{remote.id}"
end
end
rescue => e
log "Failed to sync customer #{remote.id}: #{e.message}"
end end
def log(msg) # Map relevant attributes from the QBO Customer to the local Customer model
Rails.logger.info "[CustomerSyncService] #{msg}" def process_attributes(local, remote)
local.name = remote.display_name
local.phone_number = remote.primary_phone&.free_form_number&.gsub(/\D/, '')
local.mobile_phone_number = remote.mobile_phone&.free_form_number&.gsub(/\D/, '')
end end
end end

View File

@@ -8,86 +8,23 @@
# #
#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. #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 class EmployeeSyncService < SyncServiceBase
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 private
# Fetch a page of employees, either all or only those updated since the last sync # Specify the local model this service syncs
def fetch_page(service, page, full_sync) def self.model_class
start_position = (page - 1) * PAGE_SIZE + 1 Employee
if full_sync
service.query("SELECT * FROM Employee STARTPOSITION #{start_position} MAXRESULTS #{PAGE_SIZE}")
else
last_update = Employee.maximum(: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 end
# Create or update a local Employee record based on the QBO remote data # Determine if the remote entity should be deleted locally (e.g. if it's marked inactive in QBO)
def persist(remote) def destroy_remote?(remote)
local = Employee.find_or_initialize_by(id: remote.id) !remote.active?
if remote.active?
local.name = remote.display_name
if local.changed?
local.save
log "Updated employee #{remote.id}"
end
else
if local.persisted?
local.destroy
log "Deleted employee #{remote.id}"
end
end
rescue => e
log "Failed to sync employee #{remote.id}: #{e.message}"
end end
def log(msg) # Map relevant attributes from the QBO Employee to the local Employee model
Rails.logger.info "[EmployeeSyncService] #{msg}" def process_attributes(local, remote)
local.name = remote.display_name
end end
end end

View File

@@ -0,0 +1,16 @@
#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 EstimatePdfService < PdfServiceBase
def self.model_class
Estimate
end
end

View File

@@ -8,95 +8,20 @@
# #
#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. #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 EstimateSyncService class EstimateSyncService < SyncServiceBase
PAGE_SIZE = 1000
def initialize(qbo:)
@qbo = qbo
end
# Sync all estimates, or only those updated since the last sync
def sync(full_sync: false)
log "Starting #{full_sync ? 'full' : 'incremental'} estimate sync"
@qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Estimate.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 "Estimate sync complete"
end
# Sync a single estimate by its QBO ID, used for webhook updates
def sync_by_doc(doc_number)
log "Syncing estimate by doc_number: #{doc_number}"
@qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Estimate.new(company_id: @qbo.realm_id, access_token: access_token)
remote = service.find_by( :doc_number, doc_number).first
log "Found estimate with ID #{remote.id} for doc_number #{doc_number}" if remote
persist(remote)
end
end
# Sync a single estimate by its QBO ID, used for webhook updates
def sync_by_id(id)
log "Syncing estimate by ID: #{id}"
@qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Estimate.new(company_id: @qbo.realm_id, access_token: access_token)
remote = service.fetch_by_id(id)
persist(remote)
end
end
private private
# Fetch a page of estimates, either all or only those updated since the last sync # Specify the local model this service syncs
def fetch_page(service, page, full_sync) def self.model_class
log "Fetching page #{page} of estimates (full_sync: #{full_sync})" Estimate
start_position = (page - 1) * PAGE_SIZE + 1
if full_sync
service.query("SELECT * FROM Estimate STARTPOSITION #{start_position} MAXRESULTS #{PAGE_SIZE}")
else
last_update = Estimate.maximum(:updated_at) || 1.year.ago
service.query(<<~SQL.squish)
SELECT * FROM Estimate
WHERE MetaData.LastUpdatedTime > '#{last_update.utc.iso8601}'
STARTPOSITION #{start_position}
MAXRESULTS #{PAGE_SIZE}
SQL
end
end end
# Create or update a local Estimate record based on the QBO remote data # Map relevant attributes from the QBO Estimate to the local Estimate model
def persist(remote) def process_attributes(local, remote)
log "Persisting estimate #{remote.id}"
local = Estimate.find_or_initialize_by(id: remote.id)
local.doc_number = remote.doc_number local.doc_number = remote.doc_number
local.txn_date = remote.txn_date local.txn_date = remote.txn_date
local.customer = Customer.find_by(id: remote.customer_ref&.value) local.customer = Customer.find_by(id: remote.customer_ref&.value)
if local.changed?
local.save
log "Updated estimate #{remote.id}"
end
rescue => e
log "Failed to sync estimate #{remote.id}: #{e.message}"
end end
def log(msg)
Rails.logger.info "[EstimateSyncService] #{msg}"
end
end end

View File

@@ -1,26 +1,16 @@
#The License #The MIT License (MIT)
# #
#Copyright (c) 2016 - 2026 Rick Barrette - All Rights Reserved #Copyright (c) 2016 - 2026 rick barrette
#
#Unauthorized copying of this software and associated documentation files (the "Software"), via any medium is strictly prohibited.
# #
#Proprietary and confidential #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 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. #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 InvoicePdfService < PdfServiceBase
class CreateLineItems < ActiveRecord::Migration[5.1] def self.model_class
def change Invoice
create_table :line_items do |t|
t.integer :item_id
t.float :amount
t.string :description
t.float :unit_price
t.float :quantity
t.boolean :billed
end
add_reference :line_items, :issues, index: true
end end
end
end

View File

@@ -22,7 +22,7 @@ class InvoicePushService
@invoice.update_column(:qbo_sync_locked, true) @invoice.update_column(:qbo_sync_locked, true)
qbo = Qbo.first qbo = QboConnectionService.current!
qbo.perform_authenticated_request do |access_token| qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Invoice.new( company_id: qbo.realm_id, access_token: access_token) service = Quickbooks::Service::Invoice.new( company_id: qbo.realm_id, access_token: access_token)

View File

@@ -8,88 +8,28 @@
# #
#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. #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 InvoiceSyncService class InvoiceSyncService < SyncServiceBase
PAGE_SIZE = 1000
def initialize(qbo:)
@qbo = qbo
end
# Sync all invoices, or only those updated since the last sync
def sync(full_sync: false)
log "Starting #{full_sync ? 'full' : 'incremental'} invoice sync"
@qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Invoice.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 "Invoice sync complete"
end
# Sync a single invoice by its QBO ID, used for webhook updates
def sync_by_id(id)
@qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Invoice.new(company_id: @qbo.realm_id, access_token: access_token)
remote = service.fetch_by_id(id)
persist(remote)
end
end
private private
# Fetch a page of invoices, either all or only those updated since the last sync # Specify the local model this service syncs
def fetch_page(service, page, full_sync) def self.model_class
start_position = (page - 1) * PAGE_SIZE + 1 Invoice
if full_sync
service.query("SELECT * FROM Invoice STARTPOSITION #{start_position} MAXRESULTS #{PAGE_SIZE}")
else
last_update = Invoice.maximum(:qbo_updated_at) || 1.year.ago
service.query(<<~SQL.squish)
SELECT * FROM Invoice
WHERE MetaData.LastUpdatedTime > '#{last_update.utc.iso8601}'
STARTPOSITION #{start_position}
MAXRESULTS #{PAGE_SIZE}
SQL
end
end end
# Create or update a local Invoice record based on the QBO remote data # Map relevant attributes from the QBO Invoice to the local Invoice model
def persist(remote) def process_attributes(local, remote)
local = Invoice.find_or_initialize_by(id: remote.id)
local.doc_number = remote.doc_number local.doc_number = remote.doc_number
local.txn_date = remote.txn_date local.txn_date = remote.txn_date
local.due_date = remote.due_date local.due_date = remote.due_date
local.total_amount = remote.total local.total_amount = remote.total
local.balance = remote.balance local.balance = remote.balance
local.qbo_updated_at = remote.meta_data&.last_updated_time local.qbo_updated_at = remote.meta_data&.last_updated_time
local.customer = Customer.find_by(id: remote.customer_ref&.value) local.customer = Customer.find_by(id: remote.customer_ref&.value)
if local.changed?
local.save
log "Updated invoice #{remote.doc_number} (#{remote.id})"
end
InvoiceAttachmentService.new(local, remote).attach
rescue => e
log "Failed to sync invoice #{remote.doc_number} (#{remote.id}): #{e.message}"
end end
def log(msg) # Attach QBO Invoices to the local Issues
Rails.logger.info "[InvoiceSyncService] #{msg}" def attach_documents(local, remote)
InvoiceAttachmentService.new(local, remote).attach
end end
end end

View File

@@ -0,0 +1,66 @@
#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 PdfServiceBase
require 'combine_pdf'
# Subclasses should initialize with a QBO client instance
def initialize(qbo:)
@qbo = qbo
@entity = self.class.model_class
end
# Subclasses must implement this to specify which document model to download pdf (e.g. Estimate, Invoice)
def self.model_class
raise NotImplementedError
end
# Fetches the PDF for the given entity IDs. If multiple IDs are provided, their PDFs are combined into a single document.
def fetch_pdf(doc_ids:)
log "Fetching PDFs for #{@entity} IDs: #{doc_ids.join(', ')}"
@qbo.perform_authenticated_request do |access_token|
service_class = "Quickbooks::Service::#{@entity.name}".constantize
service = service_class.new(company_id: @qbo.realm_id, access_token: access_token)
return single_pdf(service, doc_ids.first) if doc_ids.size == 1
combined_pdf(service, doc_ids)
end
end
private
# Fetches a single PDF for the given invoice ID.
def single_pdf(service, id)
log "Fetching PDF for #{@entity} ID: #{id}"
entity = service.fetch_by_id(id)
[service.pdf(entity), entity.doc_number]
end
# Combines PDFs for multiple entity IDs into a single PDF document and returns it along with a reference string.
def combined_pdf(service, ids)
log "Combining PDFs for #{@entity} IDs: #{ids.join(', ')}"
pdf = CombinePDF.new
ref = []
ids.each do |id|
entity = service.fetch_by_id(id)
ref << entity.doc_number
pdf << CombinePDF.parse(service.pdf(entity))
end
[pdf.to_pdf, ref.join(" ")]
end
# Logs messages with a consistent prefix for easier debugging.
def log(msg)
Rails.logger.info "[#{@entity}PdfService] #{msg}"
end
end

View File

@@ -0,0 +1,32 @@
#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 QboConnectionService
# Replaces the existing QBO connection with new credentials. Deletes all existing records and creates a new one with the provided token, refresh token, and realm ID. Refreshes the token immediately after creation.
def self.replace!(token:, refresh_token:, realm_id:)
Qbo.transaction do
Qbo.destroy_all
qbo = Qbo.create!(
oauth2_access_token: token,
oauth2_refresh_token: refresh_token,
realm_id: realm_id
)
qbo.refresh_token!
qbo
end
end
# Returns the current QBO connection record. Raises an error if no connection exists.
def self.current!
Qbo.first || raise("QBO not connected")
end
end

View File

@@ -0,0 +1,33 @@
#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 QboOauthService
# Generates the QuickBooks OAuth authorization URL with the specified callback URL. The URL includes necessary parameters such as response type, state, and scope.
def self.authorization_url(callback_url:)
client.auth_code.authorize_url(
redirect_uri: callback_url,
response_type: "code",
state: SecureRandom.hex(12),
scope: "com.intuit.quickbooks.accounting"
)
end
# Exchanges the authorization code for access and refresh tokens. Creates or replaces the QBO connection record with the new credentials and refreshes the token immediately after creation.
def self.exchange!(code:, callback_url:, realm_id:)
resp = client.auth_code.get_token(code, redirect_uri: callback_url)
QboConnectionService.replace!( token: resp.token, refresh_token: resp.refresh_token, realm_id: realm_id )
end
# Constructs and returns an OAuth2 client instance configured with the application's credentials and settings.
def self.client
Qbo.construct_oauth2_client
end
end

View File

@@ -0,0 +1,127 @@
#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 SyncServiceBase
PAGE_SIZE = 1000
# Subclasses should initialize with a QBO client instance
def initialize(qbo:)
raise "No QBO configuration found" unless qbo
@qbo = qbo
@entity = self.class.model_class
end
# Subclasses must implement this to specify which local model they sync (e.g. Customer, Invoice)
def self.model_class
raise NotImplementedError
end
# Sync all entities, or only those updated since the last sync
def sync(full_sync: false)
log "Starting #{full_sync ? 'full' : 'incremental'} #{@entity.name} sync"
@qbo.perform_authenticated_request do |access_token|
service_class = "Quickbooks::Service::#{@entity.name}".constantize
service = service_class.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 "#{@entity.name} sync complete"
end
# Sync a single entity by its QBO ID, used for webhook updates
def sync_by_id(id)
log "Syncing #{@entity.name} with ID #{id}"
@qbo.perform_authenticated_request do |access_token|
service_class = "Quickbooks::Service::#{@entity.name}".constantize
service = service_class.new(company_id: @qbo.realm_id, access_token: access_token)
remote = service.fetch_by_id(id)
persist(remote)
end
end
private
def attach_documents(local, remote)
# Override in subclasses if the entity has attachments (e.g. Invoice)
end
# Determine if a remote entity should be deleted locally (e.g. if it's marked inactive in QBO)
def destroy_remote?(remote)
false
end
# Log messages with the entity type for better traceability
def log(msg)
Rails.logger.info "[#{@entity.name}SyncService] #{msg}"
end
# Fetch a page of entities, either all or only those updated since the last sync
def fetch_page(service, page, full_sync)
log "Fetching page #{page} of #{@entity.name} from QBO (#{full_sync ? 'full' : 'incremental'} sync)"
start_position = (page - 1) * PAGE_SIZE + 1
if full_sync
service.query("SELECT * FROM #{@entity.name} STARTPOSITION #{start_position} MAXRESULTS #{PAGE_SIZE}")
else
last_update = @entity.maximum(:updated_at) || 1.year.ago
service.query(<<~SQL.squish)
SELECT * FROM #{@entity.name}
WHERE MetaData.LastUpdatedTime > '#{last_update.utc.iso8601}'
STARTPOSITION #{start_position}
MAXRESULTS #{PAGE_SIZE}
SQL
end
end
# Create or update a local entity record based on the QBO remote data
def persist(remote)
local = @entity.find_or_initialize_by(id: remote.id)
if destroy_remote?(remote)
if local.persisted?
local.destroy
log "Deleted #{@entity.name} #{remote.id}"
end
return
end
# Map remote attributes to local model fields, this should be implemented in subclasses
process_attributes(local, remote)
if local.changed?
local.save!
log "Updated #{@entity.name} #{remote.id}"
# Handle attaching documents if applicable to invoices
attach_documents(local, remote)
end
rescue => e
log "Failed to sync #{@entity.name} #{remote.id}: #{e.message}"
end
# This method should be implemented in subclasses to map remote attributes to local model
def process_attributes(local, remote)
raise NotImplementedError, "Subclasses must implement process_attributes"
end
end

View File

@@ -13,22 +13,22 @@
<tr> <tr>
<th><%=t(:label_primary_phone)%></th> <th><%=t(:label_primary_phone)%></th>
<td><%= number_to_phone(customer.primary_phone.gsub(/[^\d]/, '').to_i, area_code: true) if customer.primary_phone %></td> <td><%= number_to_phone(customer&.primary_phone&.gsub(/[^\d]/, '').to_i, area_code: true) %></td>
</tr> </tr>
<tr> <tr>
<th><%=t(:label_mobile_phone)%></th> <th><%=t(:label_mobile_phone)%></th>
<td><%= number_to_phone(customer.mobile_phone.gsub(/[^\d]/, '').to_i, area_code: true) if customer.mobile_phone %></td> <td><%= number_to_phone(customer&.mobile_phone&.gsub(/[^\d]/, '').to_i, area_code: true) %></td>
</tr> </tr>
<tr> <tr>
<th><%=t(:label_billing_address)%></th> <th><%=t(:label_billing_address)%></th>
<td><%= @billing_address %></td> <td><pre><%= @billing_address %></pre></td>
</tr> </tr>
<tr> <tr>
<th><%=t(:label_shipping_address)%></th> <th><%=t(:label_shipping_address)%></th>
<td><%= @shipping_address %></td> <td><pre><%= @shipping_address %></pre></td>
</tr> </tr>
<tr> <tr>

View File

@@ -46,8 +46,8 @@
</div> </div>
<br/> <br/>
<h3><%=@issues.open.count%> <%=t(:label_open_issues)%> - <%=@hours.round(1)%> <%=t(:label_hours)%></h3> <h3><%=@open_issues.count%> <%=t(:label_open_issues)%> - <%=@hours.round(1)%> <%=t(:label_hours)%></h3>
<%= render partial: 'issues/list_simple', locals: {issues: @issues.open} %> <%= render partial: 'issues/list_simple', locals: {issues: @open_issues.open} %>
<h3><%=@closed_issues.count%> <%=t(:label_closed_issues)%> - <%= @closed_hours.round(1)%> <%=t(:label_hours)%></h3> <h3><%=@closed_issues.count%> <%=t(:label_closed_issues)%> - <%= @closed_hours.round(1)%> <%=t(:label_hours)%></h3>
<%= render partial: 'issues/list_simple', locals: {issues: @closed_issues} %> <%= render partial: 'issues/list_simple', locals: {issues: @closed_issues} %>

View File

@@ -7,3 +7,6 @@
<p> <p>
<%= select_estimate %> <%= select_estimate %>
</p> </p>
<%= render "line_items/issue_form", f: f %>

View File

@@ -0,0 +1,34 @@
<% @issue.line_items.build if @issue.line_items.empty? %>
<div class="box tabular" data-nested-form data-wrapper-selector=".line-item">
<p><strong>Line Items</strong></p>
<table class="list line-items-table">
<thead>
<tr>
<th>Description</th>
<th style="width:120px;">Quantity</th>
<th style="width:150px;">Unit Price</th>
<th style="width:80px;"></th>
</tr>
</thead>
<tbody data-nested-form-container>
<%= f.fields_for :line_items do |item_form| %>
<%= render "line_items/line_item_fields", f: item_form %>
<% end %>
</tbody>
</table>
<template data-nested-form-template>
<%= f.fields_for :line_items, LineItem.new, child_index: "NEW_RECORD" do |item_form| %>
<%= render "line_items/line_item_fields", f: item_form %>
<% end %>
</template>
<p>
<button type="button" class="icon icon-add" data-nested-form-add>
Add Line Item
</button>
</p>
</div>

View File

@@ -0,0 +1,34 @@
<tr class="line-item">
<%= f.hidden_field :id %>
<%= f.hidden_field :_destroy %>
<td>
<%= f.text_field :description,
size: 50,
placeholder: "Description",
:no_label => true %>
</td>
<td>
<%= f.number_field :quantity,
step: 1,
min: 1,
style: "width:90px;",
:no_label => true %>
</td>
<td>
<%= f.number_field :unit_price,
step: 0.01,
style: "width:120px;",
:no_label => true %>
</td>
<td style="text-align:center;">
<button type="button"
class="icon-only icon-del"
title="Remove"
data-nested-form-remove>
</button>
</td>
</tr>

View File

@@ -1 +1 @@
<b><%=t(:label_last_sync)%>: </b> <%= Qbo.last_sync if Qbo.exists? %> <b><%=t(:label_last_sync)%>: </b> <%= Qbo.last_sync %>

View File

@@ -66,12 +66,12 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
<tr> <tr>
<th><%=t(:label_oauth_expires)%></th> <th><%=t(:label_oauth_expires)%></th>
<td><%= if Qbo.exists? then Qbo.first.oauth2_access_token_expires_at end %> <td><%= QboConnectionService.current!&.oauth2_access_token_expires_at %>
</tr> </tr>
<tr> <tr>
<th><%=t(:label_oauth2_refresh_token_expires_at)%></th> <th><%=t(:label_oauth2_refresh_token_expires_at)%></th>
<td><%= if Qbo.exists? then Qbo.first.oauth2_refresh_token_expires_at end %> <td><%= QboConnectionService.current!&.oauth2_refresh_token_expires_at %>
</tr> </tr>
</tbody> </tbody>
@@ -89,19 +89,19 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
<br/> <br/>
<div> <div>
<b><%=t(:label_customer_count)%>:</b> <%= Customer.count%> <b><%=t(:label_customer_count)%>:</b> <%= Customer.count%> @ <%= Customer.last_sync %>
</div> </div>
<div> <div>
<b><%=t(:label_employee_count)%>:</b> <%= Employee.count %> <b><%=t(:label_employee_count)%>:</b> <%= Employee.count %> @ <%= Employee.last_sync %>
</div> </div>
<div> <div>
<b><%=t(:label_invoice_count)%>:</b> <%= Invoice.count %> <b><%=t(:label_invoice_count)%>:</b> <%= Invoice.count %> @ <%= Invoice.last_sync%>
</div> </div>
<div> <div>
<b><%=t(:label_estimate_count)%>:</b> <%= Estimate.count %> <b><%=t(:label_estimate_count)%>:</b> <%= Estimate.count %> @ <%= Estimate.last_sync %>
</div> </div>
<br/> <br/>

View File

@@ -0,0 +1,53 @@
(function () {
function initNestedForms() {
document.querySelectorAll("[data-nested-form]").forEach(function (wrapper) {
if (wrapper.dataset.initialized === "true") return;
wrapper.dataset.initialized = "true";
const container = wrapper.querySelector("[data-nested-form-container]");
const template = wrapper.querySelector("[data-nested-form-template]");
if (!container || !template) return;
wrapper.addEventListener("click", function (event) {
const addButton = event.target.closest("[data-nested-form-add]");
const removeButton = event.target.closest("[data-nested-form-remove]");
// ADD
if (addButton) {
event.preventDefault();
const content = template.innerHTML.replace(
/NEW_RECORD/g,
Date.now().toString()
);
container.insertAdjacentHTML("beforeend", content);
}
// REMOVE
if (removeButton) {
event.preventDefault();
const lineItem = removeButton.closest(wrapper.dataset.wrapperSelector);
if (!lineItem) return;
const destroyField = lineItem.querySelector("input[name*='_destroy']");
if (destroyField) {
destroyField.value = "1";
lineItem.style.display = "none";
} else {
lineItem.remove();
}
}
});
});
}
// Works for full load
document.addEventListener("DOMContentLoaded", initNestedForms);
// Works for Turbo navigation
document.addEventListener("turbo:load", initNestedForms);
})();

View File

@@ -27,10 +27,6 @@ en:
label_balance_with_jobs: "Balance With Jobs" label_balance_with_jobs: "Balance With Jobs"
label_bill_time: "Bill Time" label_bill_time: "Bill Time"
label_billing_address: "Billing Address" label_billing_address: "Billing Address"
label_billing_error: "Customer could not be billed. Check for Customer or Assignee and try again."
label_billing_error_no_customer: "Cannot bill without an assigned customer."
label_billing_error_no_employee: "Cannot bill without an assigned employee."
label_billing_error_no_qbo: "Cannot bill without a QuickBooks connection. Please connect to QuickBooks and try again."
label_billing_enqueued: "Billing has been enqueued for issue" label_billing_enqueued: "Billing has been enqueued for issue"
label_billed_success: "Successfully billed " label_billed_success: "Successfully billed "
label_client_id: "Intuit QBO OAuth2 Client ID" label_client_id: "Intuit QBO OAuth2 Client ID"
@@ -66,6 +62,7 @@ en:
label_model: "Model" label_model: "Model"
label_name: "Name" label_name: "Name"
label_new_customer: "New Customer" label_new_customer: "New Customer"
label_qbo_never_synced: "Never Synced"
label_no_customers: "There are no customers matching the search term(s)." label_no_customers: "There are no customers matching the search term(s)."
label_no_estimates: "No Estimates" label_no_estimates: "No Estimates"
label_no_invoices: "No Invoices" label_no_invoices: "No Invoices"
@@ -90,11 +87,15 @@ en:
label_webhook_token: "Intuit QBO Webhook Token" label_webhook_token: "Intuit QBO Webhook Token"
label_week: "Week" label_week: "Week"
label_year: "Year" label_year: "Year"
notice_billing_error_no_customer: "Cannot bill without an assigned customer."
notice_billing_error_no_employee: "Cannot bill without an assigned employee."
notice_billing_error_no_qbo: "Cannot bill without a QuickBooks connection. Please connect to QuickBooks and try again."
notice_customer_created: "Customer created in QuickBooks" notice_customer_created: "Customer created in QuickBooks"
notice_customer_deleted: "Customer deleted in QuickBooks" notice_customer_deleted: "Customer deleted in QuickBooks"
notice_customer_not_deleted: "Customer could not be deleted in QuickBooks" notice_customer_not_deleted: "Customer could not be deleted in QuickBooks"
notice_customer_not_found: "Customer not found in QuickBooks" notice_customer_not_found: "Customer not found in QuickBooks"
notice_customer_updated: "Customer updated in QuickBooks" notice_customer_updated: "Customer updated in QuickBooks"
notice_error_issue_not_found: "The issue could not be found. Please check the issue and try again."
notice_error_project_nil: "The issue's project is nil. Set project to:" notice_error_project_nil: "The issue's project is nil. Set project to:"
notice_error_tracker_nil: "The issue's tracker is nil. Set tracker to:" notice_error_tracker_nil: "The issue's tracker is nil. Set tracker to:"
notice_estimate_created: "Estimate created in QuickBooks" notice_estimate_created: "Estimate created in QuickBooks"

View File

@@ -11,45 +11,8 @@
class AddTxnDates < ActiveRecord::Migration[5.1] class AddTxnDates < ActiveRecord::Migration[5.1]
def change def change
begin add_column :qbo_invoices, :txn_date, :date
add_column :qbo_invoices, :txn_date, :date add_column :qbo_estimates, :txn_date, :date
add_column :qbo_estimates, :txn_date, :date
reversible do |direction|
direction.up {
break unless Qbo.first
QboEstimate.reset_column_information
QboInvoice.reset_column_information
say "Sync Estimates"
QboEstimate.sync
say "Sync Invoices"
qbo = Qbo.first
invoices = qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Invoice.new(company_id: qbo.realm_id, access_token: access_token)
service.all
end
return unless invoices
invoices.each { |invoice|
# Load the invoice into the database
qbo_invoice = QboInvoice.find_or_create_by(id: invoice.id)
qbo_invoice.doc_number = invoice.doc_number
qbo_invoice.id = invoice.id
qbo_invoice.customer_id = invoice.customer_ref
qbo_invoice.txn_date = invoice.txn_date
qbo_invoice.save!
}
}
end
rescue
logger.error "AddTxnDates Failed"
end
end end
end end

View File

@@ -12,6 +12,5 @@ class RemoveQboItems < ActiveRecord::Migration[5.1]
def change def change
drop_table :qbo_items drop_table :qbo_items
drop_table :qbo_purchases drop_table :qbo_purchases
drop_table :line_items
end end
end end

View File

@@ -0,0 +1,42 @@
#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 CreateLineItems < ActiveRecord::Migration[7.0]
def change
create_table :line_items do |t|
t.integer :issue_id, null: false
t.text :description, null: false
t.decimal :quantity,
precision: 15,
scale: 4,
null: false,
default: 0
t.decimal :unit_price,
precision: 15,
scale: 4,
null: false,
default: 0
t.decimal :line_total,
precision: 15,
scale: 4,
null: false,
default: 0
t.timestamps
end
add_index :line_items, :issue_id
add_foreign_key :line_items, :issues
end
end

View File

@@ -14,7 +14,7 @@ Redmine::Plugin.register :redmine_qbo do
name 'Redmine QBO plugin' name 'Redmine QBO plugin'
author 'Rick Barrette' author 'Rick Barrette'
description 'A pluging for Redmine to connect with QuickBooks Online to create Time Activity Entries for billable hours logged when an Issue is closed' description 'A pluging for Redmine to connect with QuickBooks Online to create Time Activity Entries for billable hours logged when an Issue is closed'
version '2026.2.16' version '2026.3.1'
url 'https://github.com/rickbarrette/redmine_qbo' url 'https://github.com/rickbarrette/redmine_qbo'
author_url 'https://barrettefabrication.com' author_url 'https://barrettefabrication.com'
settings default: {empty: true}, partial: 'qbo/settings' settings default: {empty: true}, partial: 'qbo/settings'
@@ -25,6 +25,7 @@ Redmine::Plugin.register :redmine_qbo do
Issue.safe_attributes :estimate_id Issue.safe_attributes :estimate_id
Issue.safe_attributes :invoice_id Issue.safe_attributes :invoice_id
User.safe_attributes :employee_id User.safe_attributes :employee_id
Issue.safe_attributes :line_items_attributes
TimeEntry.safe_attributes :billed TimeEntry.safe_attributes :billed
# set per_page globally # set per_page globally

View File

@@ -21,8 +21,6 @@ module RedmineQbo
f = context[:form] f = context[:form]
issue = context[:issue] issue = context[:issue]
project = context[:project] project = context[:project]
log issue.inspect
log project.inspect
# Customer Name Text Box with database backed autocomplete # Customer Name Text Box with database backed autocomplete
# onchange event will update the hidden customer_id field # onchange event will update the hidden customer_id field
@@ -64,7 +62,8 @@ module RedmineQbo
locals: { locals: {
search_customer: search_customer, search_customer: search_customer,
customer_id: customer_id, customer_id: customer_id,
select_estimate: select_estimate select_estimate: select_estimate,
f: context[:form]
} }
} }
) )

View File

@@ -20,7 +20,7 @@ module RedmineQbo
#Employee.update_all #Employee.update_all
# Check to see if there is a quickbooks user attached to the issue # Check to see if there is a quickbooks user attached to the issue
@selected = context[:user].employee.id if context[:user].employee @selected = context[:user]&.employee&.id
# Generate the drop down list of quickbooks contacts # Generate the drop down list of quickbooks contacts
return "<p>#{context[:form].select :employee_id, Employee.all.pluck(:name, :id), selected: @selected, include_blank: true}</p>" return "<p>#{context[:form].select :employee_id, Employee.all.pluck(:name, :id), selected: @selected, include_blank: true}</p>"

View File

@@ -18,7 +18,8 @@ module RedmineQbo
safe_join([ safe_join([
javascript_include_tag( 'application.js', plugin: :redmine_qbo), javascript_include_tag( 'application.js', plugin: :redmine_qbo),
javascript_include_tag( 'autocomplete-rails.js', plugin: :redmine_qbo), javascript_include_tag( 'autocomplete-rails.js', plugin: :redmine_qbo),
javascript_include_tag( 'checkbox_controller.js', plugin: :redmine_qbo) javascript_include_tag( 'checkbox_controller.js', plugin: :redmine_qbo),
javascript_include_tag( 'nested_form_controller.js', plugin: :redmine_qbo)
]) ])
end end

View File

@@ -23,6 +23,8 @@ module RedmineQbo
belongs_to :customer_token, primary_key: :id belongs_to :customer_token, primary_key: :id
belongs_to :estimate, primary_key: :id belongs_to :estimate, primary_key: :id
has_and_belongs_to_many :invoices has_and_belongs_to_many :invoices
has_many :line_items, dependent: :destroy
accepts_nested_attributes_for :line_items, allow_destroy: true
before_save :titlize_subject before_save :titlize_subject
after_commit :enqueue_billing, on: :update after_commit :enqueue_billing, on: :update
@@ -39,11 +41,9 @@ module RedmineQbo
# Enqueue a background job to bill the time spent on this issue to the associated customer in Quickbooks, if the issue is closed and has a customer assigned. # Enqueue a background job to bill the time spent on this issue to the associated customer in Quickbooks, if the issue is closed and has a customer assigned.
def enqueue_billing def enqueue_billing
log "Checking if issue needs to be billed for issue ##{id}" log "Checking if issue needs to be billed for issue ##{id}"
#return unless saved_change_to_status_id?
return unless closed? return unless closed?
return unless customer.present? return unless customer.present?
return unless assigned_to&.employee_id.present? return unless assigned_to&.employee_id.present?
return unless Qbo.first
log "Enqueuing billing for issue ##{id}" log "Enqueuing billing for issue ##{id}"
BillIssueTimeJob.perform_later(id) BillIssueTimeJob.perform_later(id)

View File

@@ -260,8 +260,9 @@ module RedmineQbo
# Check to see if there is an estimate attached, then combine them # Check to see if there is an estimate attached, then combine them
if issue.estimate if issue.estimate
e_pdf, ref = EstimatePdfService.new(qbo: QboConnectionService.current!).fetch_pdf(doc_ids: [issue.estimate.id])
pdf = CombinePDF.parse(pdf.output, allow_optional_content: true) pdf = CombinePDF.parse(pdf.output, allow_optional_content: true)
pdf << CombinePDF.parse(issue.estimate.pdf) pdf << CombinePDF.parse(e_pdf)
return pdf.to_pdf return pdf.to_pdf
end end