Add tests for billing time, OAuth, patches and helpers

BillIssueTimeJob (hours by activity, partial failure and retry, quoted
item names), the QuickBooks connection and token refresh, the business
report's periods and database figures, the Redmine page patches and
hooks (issue page, form, history, issue list column and filter, billed
time, user employee, bill/share links, issue PDF with its estimate,
activity), RefundGateway, the refund email and PDF, the services' query
string and emailing, invoice lines' LinkedTxn, combined PDFs, invoice
attachment, and the plugin settings page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-20 16:41:58 -05:00
1 parent da82f7e12c
commit 17f24f9641
6 files changed
+823

No files matched your search

+10
View File
@@ -131,6 +131,16 @@ class QboAdminPagesTest < Redmine::IntegrationTest
end
end
def test_plugin_settings_page
RedmineQboBilling::Company.stubs(:settings).returns(custom_fields: [{ id: 1, name: 'Sales Rep' }, { id: 2, name: 'VIN' }])
QboSyncStatus.queued('Invoice')
admin
get '/settings/plugin/redmine_qbo'
assert_response :success
assert_match "grantUrl: '/qbo/authenticate'", response.body
assert_select 'body', text: /VIN/
end
# ---- business report ----
def test_report_needs_the_permission
+224
View File
@@ -0,0 +1,224 @@
#The MIT License (MIT)
#
#Copyright (c) 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.
require File.expand_path('../test_helper', __dir__)
# What the plugin adds to Redmine's own pages: the issue's customer, estimate and invoices, the issue form, the
# issue list's Customer column and filter, spent time's Billed column, the issue history, the user form's
# employee, the bill and share links, the issue PDF, and the activity page
class RedminePagesTest < Redmine::IntegrationTest
include QboFakeServiceHelper
fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations, :workflows, :journals,
:journal_details, :time_entries, :queries
def setup
@customer = local_customer(9101, 'Jane Customer')
local_customer(9102, 'Bob Builder')
Estimate.where(id: 598).delete_all
Invoice.where(id: 601).delete_all
@estimate = Estimate.create!(id: 598, doc_number: '1068', customer_id: 9101)
@invoice = Invoice.create!(id: 601, doc_number: '1234', customer_id: 9101, txn_date: Date.new(2026, 11, 12))
@issue = Issue.find(1)
@issue.update_columns(customer_id: 9101, estimate_id: 598)
@issue.invoices = [@invoice]
@fake = install_fake_quickbooks
Role.find(1).remove_permission!(:view_customers, :bill_issues, :share_issues_with_customers, :write_estimates)
end
def login(*permissions)
permissions.each { |p| Role.find(1).add_permission!(p) }
reset!
log_user('jsmith', 'jsmith')
end
# ---- issue page ----
def test_issue_shows_customer_estimate_and_invoices
login
get '/issues/1'
assert_response :success
assert_select '.customer_id .value a[href=?]', '/customers/9101', text: 'Jane Customer'
assert_select '.estimate_id .value a[href=?]', '/estimates/598', text: '1068'
assert_select '.invoice_id .value a[href=?]', '/invoices/601', text: '1234'
end
def test_estimate_actions_need_write_estimates
login
get '/issues/1'
assert_select '.qbo-estimate-edit-link', 0
login(:write_estimates)
get '/issues/1'
assert_select 'a.qbo-estimate-edit-link[href=?]', '/qbo_estimates/598/edit'
end
def test_bill_and_share_links_follow_permissions
login
get '/issues/1'
assert_select 'a[href=?]', '/bill/1', 0
assert_select 'a[href=?]', '/customers/share/1', 0
login(:bill_issues, :share_issues_with_customers)
get '/issues/1'
assert_select 'a[href=?][data-method=post]', '/bill/1'
assert_select 'a[href=?]', '/customers/share/1'
end
def test_issue_form_has_the_customer_and_their_estimates
login
get '/issues/1/edit'
assert_response :success
assert_select 'input.customer-name[data-autocomplete-url=?]', '/customers/autocomplete'
assert_select 'input#customer_id[type=hidden][value=?]', '9101'
assert_select 'select[name=?] option[value=?][selected]', 'issue[estimate_id]', '598'
end
def test_setting_the_customer_on_an_issue
login
patch '/issues/2', params: { issue: { customer_id: '9102' } }
assert_redirected_to '/issues/2'
assert_equal 9102, Issue.find(2).customer_id
end
# ---- issue history ----
def test_history_names_the_customer_and_estimate
journal = Journal.create!(journalized: @issue, user: User.find(2), notes: '')
JournalDetail.create!(journal: journal, property: 'attr', prop_key: 'customer_id', old_value: '9102', value: '9101')
JournalDetail.create!(journal: journal, property: 'attr', prop_key: 'estimate_id', old_value: '777', value: '598')
JournalDetail.create!(journal: journal, property: 'invoice', prop_key: '601', value: '1234')
login
get '/issues/1'
assert_select '.journal ul.journal-details li', text: /Bob Builder.*Jane Customer/
# An estimate that's gone shows its id
assert_select '.journal ul.journal-details li', text: /777.*1068/
assert_select '.journal ul.journal-details li a[href$=?]', '/invoices/601', text: '1234'
end
def test_invoice_history_without_the_invoice
journal = Journal.create!(journalized: @issue, user: User.anonymous, notes: '')
JournalDetail.create!(journal: journal, property: 'invoice', prop_key: '999', value: '9999')
login
get '/issues/1'
assert_select '.journal ul.journal-details li i', text: '9999'
end
def test_subjects_are_title_cased
@issue.update!(subject: 'install LED light bar on JL')
assert_equal 'Install LED Light Bar On JL', @issue.reload.subject
end
# ---- closing an issue bills it ----
def test_closing_a_billable_issue_queues_billing
User.find(3).update_column(:employee_id, 31)
@issue.update_columns(assigned_to_id: 3)
BillIssueTimeJob.expects(:perform_later).with(1)
@issue.reload.update!(status: IssueStatus.where(is_closed: true).first)
end
def test_closing_without_an_employee_does_not_bill
User.find(3).update_column(:employee_id, nil)
@issue.update_columns(assigned_to_id: 3)
BillIssueTimeJob.expects(:perform_later).never
@issue.reload.update!(status: IssueStatus.where(is_closed: true).first)
end
# ---- issue list ----
def test_customer_column_links_for_view_customers
login
get '/projects/ecookbook/issues', params: { set_filter: 1, c: %w[subject customer] }
assert_response :success
assert_select 'td.customer', text: 'Jane Customer'
assert_select 'td.customer a', 0
login(:view_customers)
get '/projects/ecookbook/issues', params: { set_filter: 1, c: %w[subject customer] }
assert_select 'td.customer a[href=?]', '/customers/9101'
end
def test_customer_name_filter
login
get '/projects/ecookbook/issues', params: { set_filter: 1, f: ['customer_name'], op: { customer_name: '~' },
v: { customer_name: ['jane'] }, c: %w[subject] }
assert_response :success
assert_select 'tr#issue-1'
assert_select 'tr#issue-2', 0
get '/projects/ecookbook/issues', params: { set_filter: 1, f: ['customer_name'], op: { customer_name: '!~' },
v: { customer_name: ['jane'] }, c: %w[subject] }
assert_select 'tr#issue-1', 0
end
def test_customer_name_filter_sql_is_escaped
query = IssueQuery.new(name: '_')
sql = query.sql_for_customer_name_field('customer_name', '~', ["x' OR 1=1 --"])
assert_match "LIKE '%x'' OR 1=1 --%'", sql.gsub('\\\'', "''")
assert_nil query.sql_for_customer_name_field('customer_name', '=', ['x'])
end
def test_billed_column_and_filter_on_spent_time
TimeEntry.where(id: 1).update_all(billed: true)
login
get '/projects/ecookbook/time_entries', params: { set_filter: 1, f: ['billed'], op: { billed: '=' }, v: { billed: ['1'] },
c: %w[hours billed] }
assert_response :success
assert_select 'tr#time-entry-1'
assert_select 'th', text: I18n.t(:field_billed)
end
# ---- users ----
def test_user_form_picks_the_employee
Employee.where(id: [31, 32]).delete_all
Employee.create!(id: 31, name: 'Tech One')
User.find(3).update_column(:employee_id, 31)
reset!
log_user('admin', 'admin')
get '/users/3/edit'
assert_select 'select[name=?] option[value="31"][selected]', 'user[employee_id]', text: 'Tech One'
patch '/users/3', params: { user: { employee_id: '' } }
assert_nil User.find(3).employee_id
end
# ---- issue PDF ----
def test_issue_pdf_includes_the_estimate
# A plain one-page PDF, like QuickBooks' (Redmine's own PDFs have optional content, which the merge refuses)
estimate_pdf = CombinePDF.new.tap { |p| p << CombinePDF.create_page }.to_pdf
PdfService.any_instance.expects(:fetch_pdf).with(doc_ids: [598]).returns([estimate_pdf, '1068'])
login
get '/issues/1.pdf'
assert_response :success
assert_equal 'application/pdf', response.media_type
assert_operator CombinePDF.parse(response.body).pages.size, :>=, 2
end
def test_issue_pdf_without_an_estimate
@issue.update_column(:estimate_id, nil)
PdfService.any_instance.expects(:fetch_pdf).never
login
get '/issues/1.pdf'
assert_response :success
end
# ---- activity ----
def test_activity_shows_quickbooks_documents_only_to_permitted_users
login
get '/activity'
assert_select 'input[name=show_qbo_estimates]', 0
login(:view_customers)
get '/activity'
assert_select 'input[name=show_qbo_estimates]'
# Never on a project's activity
get '/projects/ecookbook/activity'
assert_select 'input[name=show_qbo_estimates]', 0
end
end
+133
View File
@@ -0,0 +1,133 @@
#The MIT License (MIT)
#
#Copyright (c) 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.
require File.expand_path('../test_helper', __dir__)
class BillIssueTimeJobTest < ActiveSupport::TestCase
include QboFakeServiceHelper
fixtures :projects, :users, :members, :member_roles, :roles, :issues, :trackers, :projects_trackers,
:issue_statuses, :enabled_modules, :enumerations, :time_entries
# Stands in for QuickBooks' time activity and item services
class FakeTimeService
attr_reader :created
attr_accessor :fail_on
def initialize
@created = []
end
def create(activity)
raise Quickbooks::IntuitRequestException, 'QuickBooks is down' if fail_on && activity.hours.to_i == fail_on
created << activity
activity
end
end
class FakeItemService
attr_reader :queries
def initialize(items)
@items = items
@queries = []
end
def query(sql)
queries << sql
name = sql[/Name = '(.*)'\z/, 1].to_s.gsub("\\'", "'")
Array(@items[name])
end
end
def setup
local_customer
@issue = Issue.find(1)
@issue.update_columns(customer_id: 9101, assigned_to_id: 3, done_ratio: 40)
User.find(3).update_column(:employee_id, 31)
TimeEntry.delete_all
@design = TimeEntryActivity.find(9) # Design
@dev = TimeEntryActivity.find(10) # Development
@times = FakeTimeService.new
@items = FakeItemService.new('Design' => [Quickbooks::Model::Item.new(id: '5', unit_price: BigDecimal('90'))],
'Development' => [Quickbooks::Model::Item.new(id: '6', unit_price: BigDecimal('120'))])
Quickbooks::Service::TimeActivity.stubs(:new).returns(@times)
Quickbooks::Service::Item.stubs(:new).returns(@items)
qbo = Qbo.new(realm_id: '1')
qbo.define_singleton_method(:perform_authenticated_request) { |&block| block.call('token') }
QboConnectionService.stubs(:current!).returns(qbo)
Qbo.stubs(:update_time_stamp)
end
def spend(activity, hours, billed: false)
TimeEntry.create!(issue: @issue, project: @issue.project, user: User.find(2), activity: activity, hours: hours,
spent_on: Date.new(2026, 11, 18), billed: billed)
end
def test_sums_hours_by_activity_and_marks_them_billed
first = spend(@design, 1.25)
second = spend(@design, 0.5)
third = spend(@dev, 2)
spend(@dev, 3, billed: true)
BillIssueTimeJob.perform_now(@issue.id)
by_item = @times.created.to_h { |a| [a.item_ref.value, [a.hours, a.minutes]] }
assert_equal({ '5' => [1, 45], '6' => [2, 0] }, by_item)
activity = @times.created.first
assert_equal ['31', '9101', 'Billable', 'Employee'], [activity.employee_ref.value.to_s, activity.customer_ref.value.to_s,
activity.billable_status, activity.name_of]
assert_equal "#{@issue.tracker} ##{@issue.id}: #{@issue.subject} (Partial @ 40%)", activity.description
assert [first, second, third].all? { |e| e.reload.billed }
end
def test_closed_issue_description_has_no_partial_note
@issue.update_column(:status_id, IssueStatus.where(is_closed: true).first.id)
spend(@design, 1)
BillIssueTimeJob.perform_now(@issue.id)
assert_equal "#{@issue.tracker} ##{@issue.id}: #{@issue.subject}", @times.created.first.description
end
def test_nothing_unbilled_does_nothing
spend(@design, 1, billed: true)
BillIssueTimeJob.perform_now(@issue.id)
assert_empty @times.created
end
def test_activity_without_a_quickbooks_item_is_skipped_but_marked_billed
@items = FakeItemService.new({})
Quickbooks::Service::Item.stubs(:new).returns(@items)
entry = spend(@design, 1)
BillIssueTimeJob.perform_now(@issue.id)
assert_empty @times.created
assert entry.reload.billed
end
def test_a_failure_keeps_the_rest_for_a_retry
design = spend(@design, 1)
dev = spend(@dev, 2)
@times.fail_on = 2
assert_raises(Quickbooks::IntuitRequestException) { BillIssueTimeJob.new.perform(@issue.id) }
assert design.reload.billed
assert_not dev.reload.billed
# The retry only sends what's left
@times.fail_on = nil
BillIssueTimeJob.new.perform(@issue.id)
assert_equal [1, 2], @times.created.map(&:hours)
assert dev.reload.billed
end
def test_item_names_are_quoted
quoted = TimeEntryActivity.create!(name: "Tech's time", active: true)
spend(quoted, 1)
BillIssueTimeJob.perform_now(@issue.id)
assert_equal "SELECT * FROM Item WHERE Name = 'Tech\\'s time'", @items.queries.last
end
end
+152
View File
@@ -0,0 +1,152 @@
#The MIT License (MIT)
#
#Copyright (c) 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.
require File.expand_path('../test_helper', __dir__)
# BusinessReport's periods, chart points, hours and loading its figures from the database
class BusinessReportPeriodsTest < ActiveSupport::TestCase
fixtures :projects, :users, :issues, :trackers, :issue_statuses, :enumerations, :time_entries
Report = RedmineQboBilling::BusinessReport
TODAY = Date.new(2026, 11, 20) # a Friday
def range(period, **options)
Report.range_for(period, today: TODAY, **options)
end
def test_periods
assert_equal [Date.new(2026, 11, 16), Date.new(2026, 11, 22)], range('this_week')
assert_equal [Date.new(2026, 11, 15), Date.new(2026, 11, 21)], range('this_week', week_start: :sunday)
assert_equal [Date.new(2026, 11, 9), Date.new(2026, 11, 15)], range('last_week')
assert_equal [Date.new(2026, 11, 1), Date.new(2026, 11, 30)], range('this_month')
assert_equal [Date.new(2026, 10, 1), Date.new(2026, 10, 31)], range('last_month')
assert_equal [Date.new(2026, 10, 1), Date.new(2026, 12, 31)], range('this_quarter')
assert_equal [Date.new(2026, 7, 1), Date.new(2026, 9, 30)], range('last_quarter')
assert_equal [Date.new(2025, 1, 1), Date.new(2025, 12, 31)], range('last_year')
assert_equal [Date.new(2026, 1, 1), Date.new(2026, 12, 31)], range('this_year')
assert_equal [Date.new(2026, 1, 1), Date.new(2026, 12, 31)], range('bogus')
end
def test_custom_period
assert_equal [Date.new(2026, 3, 1), Date.new(2026, 4, 1)], range('custom', from: '2026-04-01', to: '2026-03-01')
assert_equal [Date.new(2026, 1, 1), TODAY], range('custom', from: 'nope')
assert_nil Report.parse_date('2026-13-01')
assert_equal TODAY, Report.parse_date(TODAY)
end
def test_unknown_period_is_this_year
assert_equal 'this_year', Report.new(period: 'forever', today: TODAY, data: {}).period
end
def test_week_start_setting
assert_equal :sunday, Report.week_start_from_setting('7')
assert_equal :saturday, Report.week_start_from_setting(6)
assert_equal :monday, Report.week_start_from_setting('')
end
def report(period, **options)
Report.new(period: period, today: TODAY, data: empty, previous_data: empty, **options)
end
def empty
{ estimates: [], invoices: [], paid: [], payments: [], issues: [], time_entries: [] }
end
def test_buckets_by_day_week_and_month
week = report('this_week')
assert_equal :day, week.granularity
assert_equal 7, week.buckets.size
month = report('this_month')
assert_equal :week, month.granularity
assert_equal [Date.new(2026, 11, 1), Date.new(2026, 11, 1)], month.buckets.first
assert_equal [Date.new(2026, 11, 30), Date.new(2026, 11, 30)], month.buckets.last
assert_equal [Date.new(2026, 11, 2) - 364, Date.new(2026, 11, 8) - 364], month.previous_buckets[1]
year = report('this_year')
assert_equal :month, year.granularity
assert_equal 12, year.buckets.size
assert_equal [Date.new(2025, 1, 1), Date.new(2025, 1, 31)], year.previous_buckets.first
end
def test_chart_stops_at_today
r = Report.new(period: 'this_week', today: TODAY, data: empty.merge(payments: [[TODAY, '100']]), previous_data: empty)
chart = r.chart
assert_equal '2026-11-16', chart[:points].first
assert_equal [0.0, 0.0, 0.0, 0.0, 100.0, nil, nil], chart[:current][:payments]
assert_equal [0.0] * 7, chart[:previous][:payments]
end
def test_hours_cpi_and_ratios
r = Report.new(period: 'this_month', today: TODAY, previous_data: empty,
data: empty.merge(estimates: [[TODAY, '0', 10]], invoices: [[TODAY, '0', 6, '0']],
issues: [[TODAY, 8]], time_entries: [[TODAY, 7.5], [TODAY, 0.5]]))
assert_equal({ estimate_hours: 10.0, issue_hours: 8.0, invoice_hours: 6.0, spent_hours: 8.0 }, r.hours)
assert_equal 0.75, r.cpi
assert_equal 75, r.ratios[:invoiced_of_spent]
assert_equal 100, r.ratios[:spent_of_estimated]
assert_nil r.ratios[:invoiced_of_estimated]
november = r.months.last
assert_equal [10.0, 8.0], november.values_at(:estimate_hours, :spent_hours)
end
def test_cpi_levels
assert_nil Report.cpi(5, 0)
assert_nil Report.cpi_level(nil)
assert_equal :poor, Report.cpi_level(0.79)
assert_equal :under, Report.cpi_level(0.95)
assert_equal :good, Report.cpi_level(1.2)
end
def test_months_stop_at_the_current_month
assert_equal (1..11).to_a, report('this_year').months.map { |m| m[:month].month }
assert_equal [1], Report.new(period: 'custom', from: '2027-01-01', to: '2027-02-01', today: TODAY, data: empty)
.months.map { |m| m[:month].month }
end
def test_project_ids
assert_not report('this_year').projects_filtered?
filtered = report('this_year', project_ids: ['1', '0', 1, 'x'])
assert_equal [1], filtered.project_ids
assert filtered.projects_filtered?
end
def test_loads_figures_from_the_database
Estimate.where(id: 9401).delete_all
Invoice.where(id: [9501, 9502]).delete_all
Payment.where(id: 9601).delete_all
TimeEntry.delete_all
Estimate.create!(id: 9401, doc_number: 'E1', customer_id: 1, txn_date: TODAY - 1, total_amount: 540, hours: 4, tax_amount: 40)
Invoice.create!(id: 9501, doc_number: '1', customer_id: 1, txn_date: TODAY - 2, total_amount: 535, balance: 0,
hours: 3, tax_amount: 35, paid_on: TODAY - 1)
Invoice.create!(id: 9502, doc_number: '2', customer_id: 1, txn_date: Date.new(2025, 11, 2), total_amount: 100, balance: 100)
Payment.create!(id: 9601, customer_id: 1, txn_date: TODAY - 1, total_amount: 535)
Issue.find(1).update_columns(created_on: TODAY.in_time_zone.change(hour: 9), estimated_hours: 5)
Issue.find(5).update_columns(created_on: TODAY.in_time_zone.change(hour: 9), estimated_hours: 2)
TimeEntry.new(issue_id: 1, project_id: 1, user_id: 2, author_id: 2, activity_id: 9, hours: 3.5, spent_on: TODAY).save!(validate: false)
TimeEntry.new(issue_id: 5, project_id: 3, user_id: 2, author_id: 2, activity_id: 9, hours: 1, spent_on: TODAY).save!(validate: false)
r = Report.new(period: 'this_month', today: TODAY)
assert_equal({ total: BigDecimal('500'), count: 1 }, r.money[:estimates])
assert_equal({ total: BigDecimal('500'), count: 1 }, r.money[:paid])
assert_equal BigDecimal('535'), r.money[:payments][:total]
assert_equal 1, r.money[:invoices][:count]
assert_equal 7.0, r.hours[:issue_hours]
assert_equal 4.5, r.hours[:spent_hours]
assert_equal 0, r.unsynced_count
only_one = Report.new(period: 'this_month', today: TODAY, project_ids: [1])
assert_equal [5.0, 3.5], only_one.hours.values_at(:issue_hours, :spent_hours)
# QuickBooks figures have no project
assert_equal BigDecimal('535'), only_one.money[:payments][:total]
# Last year's invoice is on the comparison line
assert_equal 100.0, Report.new(period: 'this_month', today: TODAY).chart[:previous][:invoices].sum
end
end
+114
View File
@@ -0,0 +1,114 @@
#The MIT License (MIT)
#
#Copyright (c) 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.
require File.expand_path('../test_helper', __dir__)
# The QuickBooks connection (Qbo), its OAuth token handling (QuickbooksOauth) and QboConnectionService
class QboConnectionTest < ActiveSupport::TestCase
def setup
Qbo.delete_all
end
def connection
Qbo.create!(oauth2_access_token: 'access', oauth2_refresh_token: 'refresh', realm_id: '123')
end
def test_only_one_connection
connection
assert_not Qbo.new(realm_id: '456').valid?
end
def test_current_needs_a_connection
assert_raises(RuntimeError) { QboConnectionService.current! }
record = connection
assert_equal record, QboConnectionService.current!
end
def test_with_qbo_service_needs_an_entity
connection
assert_raises(RuntimeError) { QboConnectionService.with_qbo_service { |_s| nil } }
end
def test_with_qbo_service_builds_the_service
record = connection
record.class.any_instance.stubs(:perform_authenticated_request).yields(record.oauth_access_token)
service = nil
QboConnectionService.with_qbo_service(entity: 'Invoice') { |s| service = s }
assert_kind_of Quickbooks::Service::Invoice, service
assert_equal '123', service.company_id
end
def test_last_sync_and_expiry_without_a_connection
assert_equal I18n.t(:label_qbo_never_synced), Qbo.last_sync
assert_nil Qbo.oauth2_access_token_expires_at
assert_nil Qbo.oauth2_refresh_token_expires_at
end
def test_update_time_stamp
record = connection
Qbo.update_time_stamp
assert_in_delta Time.now.to_i, record.reload.last_sync.to_i, 5
assert_not_equal I18n.t(:label_qbo_never_synced), Qbo.last_sync
end
def test_authenticated_request_refreshes_and_retries
record = connection
record.expects(:refresh_token!).twice
attempts = 0
result = record.perform_authenticated_request do |token|
attempts += 1
raise Quickbooks::AuthorizationFailure if attempts < 3
token.token
end
assert_equal 'access', result
end
def test_authenticated_request_gives_up
record = connection
record.stubs(:refresh_token!)
error = assert_raises(RuntimeError) do
record.perform_authenticated_request { |_token| raise Quickbooks::AuthorizationFailure }
end
assert_equal 'QuickbooksOauth:ExceededAuthAttempts', error.message
end
def test_refresh_token_saves_the_new_tokens
record = connection
refreshed = OAuth2::AccessToken.new(record.oauth_client, 'new-access', refresh_token: 'new-refresh',
expires_at: 1.hour.from_now.to_i, 'x_refresh_token_expires_in' => 8_640_000)
OAuth2::AccessToken.any_instance.stubs(:refresh!).returns(refreshed)
record.refresh_token!
record.reload
assert_equal %w[new-access new-refresh], [record.oauth2_access_token, record.oauth2_refresh_token]
assert_in_delta 100.days.from_now.to_i, record.oauth2_refresh_token_expires_at.to_i, 5
end
def test_oauth_client_follows_the_settings
Setting.stubs(:plugin_redmine_qbo).returns({ 'oauth_consumer_key' => 'key', 'oauth_consumer_secret' => 'secret',
'sandbox' => '1' }.with_indifferent_access)
client = Qbo.construct_oauth2_client
assert_equal 'key', client.id
assert Quickbooks.sandbox_mode
url = QboOauthService.authorization_url(callback_url: 'https://redmine.example/qbo/oauth_callback', state: 'abc')
assert_match 'state=abc', url
assert_match 'scope=com.intuit.quickbooks.accounting', url
ensure
Quickbooks.sandbox_mode = false
end
def test_replace_swaps_the_connection
connection
Qbo.any_instance.stubs(:refresh_token!)
replaced = QboConnectionService.replace!(token: 't', refresh_token: 'r', realm_id: '999')
assert_equal [replaced.id], Qbo.pluck(:id)
assert_equal '999', replaced.realm_id
end
end
+190
View File
@@ -0,0 +1,190 @@
#The MIT License (MIT)
#
#Copyright (c) 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.
require File.expand_path('../test_helper', __dir__)
# RefundGateway's QuickBooks calls, the refund email, and the smaller QuickBooks helpers: the services' query
# string and emailing, invoice lines' LinkedTxn, combined PDFs and attaching invoices to issues
class QboHelpersTest < ActiveSupport::TestCase
include QboFakeServiceHelper
fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations, :journals, :journal_details
def setup
@customer = local_customer
@fake = install_fake_quickbooks
stub_local_syncs
@gateway = RedmineQboBilling::RefundGateway.new
end
def payment(id, unapplied, date, lines: [])
doc = Quickbooks::Model::Payment.new(txn_date: date, total: BigDecimal('500'), unapplied_amount: BigDecimal(unapplied.to_s),
customer_ref: qbo_ref(9101))
doc.id = id.to_s
doc.sync_token = 1
doc.line_items = lines
doc
end
# ---- RefundGateway ----
def test_unapplied_payments_oldest_first
@fake.query_results = { 'FROM Payment' => [payment(52, 100, Date.new(2026, 11, 5)), payment(50, 0, Date.new(2026, 11, 1)),
payment(51, 200, Date.new(2026, 11, 2))] }
assert_equal %w[51 52], @gateway.unapplied_payments(9101).map(&:id)
end
def test_apply_payment_keeps_existing_lines
existing = RedmineQboBilling::RefundGateway.linked_line(BigDecimal('100'), 601, 'Invoice')
doc = payment(50, 400, Date.new(2026, 11, 1), lines: [existing])
saved = @gateway.apply_payment(doc, BigDecimal('50'), 601, 'Invoice')
assert_equal [[BigDecimal('150'), '601']], saved.line_items.map { |l| [l.amount, l.linked_transactions.first.txn_id] }
saved = @gateway.apply_payment(doc, BigDecimal('25'), 800, 'Expense')
assert_equal [%w[601 Invoice], %w[800 Expense]], saved.line_items.map { |l| [l.linked_transactions.first.txn_id, l.linked_transactions.first.txn_type] }
assert_equal BigDecimal('500'), saved.total
end
def test_payment_method_ids
RedmineQboBilling::PaymentWriter.stubs(:payment_methods).returns([%w[Cash 1], ['Cheque', '2'], ['Visa', '3']])
assert_equal '2', @gateway.payment_method_id(:check)
assert_equal '3', @gateway.payment_method_id(:card)
end
def test_account_and_balance
@fake.query_results = { "AccountType = 'Bank'" => [Quickbooks::Model::Account.new(id: 35)] }
assert_equal '35', @gateway.account_id('Bank')
assert_nil @gateway.account_id('Accounts Receivable')
@fake.customers['9101'] = Quickbooks::Model::Customer.new(balance: BigDecimal('-120'))
assert_equal BigDecimal('-120'), @gateway.customer_balance(9101)
end
def test_reject_estimate_and_documents
estimate = @fake.add(qbo_estimate(status: 'Pending', lines: [qbo_sales_line(1, 10, 'Labor', 1, 100)]))
assert_equal estimate, @gateway.estimate(598)
@gateway.reject_estimate(estimate)
assert_equal 'Rejected', @fake.updated.last.txn_status
invoice = @gateway.create_invoice(qbo_invoice(id: nil))
assert_equal invoice, @gateway.invoice(invoice.id)
end
def test_syncs_never_raise
InvoiceSyncService.any_instance.stubs(:sync_by_id).raises(StandardError)
PaymentSyncService.any_instance.stubs(:sync_by_id).raises(StandardError)
EstimateSyncService.any_instance.stubs(:sync_by_id).raises(StandardError)
assert_nothing_raised do
@gateway.sync_invoice(1)
@gateway.sync_payment(1)
@gateway.sync_estimate(1)
end
end
# ---- refund email ----
def refund
QboRefund.create!(customer_id: 9101, method: 'check', check_number: '5001', status: 'done', refund_amount: 407.6,
txn_date: Date.new(2026, 11, 16), reason: 'Canceled', kind: 'credit')
end
def test_refund_email
with_settings app_title: 'Test Shop', mail_from: 'shop@example.com' do
mail = QboRefundMailer.refund_summary(refund, 'jane@example.com')
assert_equal ['jane@example.com'], mail.to
assert_equal ['shop@example.com'], mail.from
assert_match '$407.60', mail.subject
assert_match 'Test Shop', mail.subject
end
end
def test_refund_email_when_delivery_is_off
ActionMailer::Base.stubs(:perform_deliveries).returns(false)
assert_raises(QboRefundMailer::DeliveryOff) { QboRefundMailer.refund_summary(refund, 'jane@example.com').message }
end
def test_refund_pdf
record = refund
pdf = RedmineQboBilling::RefundPdf.new(record)
assert pdf.render.start_with?('%PDF')
assert_equal 'refund-2026-11-16-jane-customer.pdf', pdf.filename
assert_match 'Jane Customer', pdf.title
end
# ---- QuickBooks service helpers ----
def access_token
OAuth2::AccessToken.new(OAuth2::Client.new('key', 'secret', site: 'https://appcenter.intuit.com'), 'token')
end
def test_services_ask_for_every_custom_field
service = RedmineQboBilling::QboEstimateService.new(company_id: '1', access_token: access_token)
url = service.send(:add_query_string_to_url, 'https://quickbooks.example/v3/estimate', { 'query' => 'x' })
assert_match 'minorversion=75', url
assert_match 'include=enhancedAllCustomFields', url
assert_match 'query=x', url
assert_match '&include', service.send(:add_query_string_to_url, 'https://quickbooks.example/v3/estimate?a=1')
end
def test_send_document
service = RedmineQboBilling::QboInvoiceService.new(company_id: '1', access_token: access_token)
sent_url = nil
response = Struct.new(:code, :plain_body).new(200, '<IntuitResponse><Invoice><Id>601</Id></Invoice></IntuitResponse>')
service.define_singleton_method(:do_http_post) { |url, *_args| sent_url = url; response }
service.define_singleton_method(:parse_singular_entity_response) { |_model, body| body[/<Invoice>.*<\/Invoice>/m] }
invoice = service.send_invoice(601, 'jane+x@example.com')
assert_equal '601', invoice.id
assert_match '/invoice/601/send?sendTo=jane%2Bx%40example.com', sent_url
service.define_singleton_method(:do_http_post) { |*_args| Struct.new(:code).new(400) }
assert_nil service.send_invoice(601)
end
def test_invoice_lines_carry_linked_transactions_after_the_amount
line = Quickbooks::Model::InvoiceLineItem.new
line.amount = BigDecimal('120')
line.linked_transactions = [qbo_link('TimeActivity', 77)]
line.sales_item! { |d| d.quantity = 1 }
xml = line.to_xml.to_s
assert_operator xml.index('<Amount>'), :<, xml.index('<LinkedTxn>')
assert_operator xml.index('<LinkedTxn>'), :<, xml.index('<SalesItemLineDetail>')
# Applying again changes nothing
RedmineQboBilling::Patches::InvoiceLineItemLinkedTxn.apply!
assert_equal xml, line.to_xml.to_s
end
def test_combined_pdf
page = CombinePDF.new.tap { |p| p << CombinePDF.create_page }.to_pdf
@fake.add(qbo_invoice(id: 601, doc_number: '1234'))
@fake.add(qbo_invoice(id: 602, doc_number: '1235'))
@fake.pdf_body = page
pdf, ref = PdfService.new(entity: Invoice).fetch_pdf(doc_ids: %w[601 602])
assert_equal '1234 1235', ref
assert_equal 2, CombinePDF.parse(pdf).pages.size
assert_raises(RuntimeError) { PdfService.new(entity: nil) }
end
# ---- invoices attached to issues ----
def test_invoice_attaches_to_its_customers_issues_once
Invoice.where(id: 601).delete_all
invoice = Invoice.create!(id: 601, doc_number: '1234', customer_id: 9101, txn_date: Date.new(2026, 11, 12))
Issue.find(1).update_column(:customer_id, 9101)
Issue.find(2).update_column(:customer_id, 424_242)
remote = qbo_invoice(lines: [qbo_note_line(1, 'Install #1: lift, see #2 and #99999')])
remote.private_note = 'Work order #1'
InvoiceAttachmentService.new(invoice, remote).attach
assert_equal [invoice], Issue.find(1).invoices.to_a
assert_empty Issue.find(2).invoices
journal = Issue.find(1).journals.last
assert_equal User.anonymous, journal.user
assert_equal [%w[invoice 601 1234]], journal.details.map { |d| [d.property, d.prop_key, d.value] }
assert_no_difference('Journal.count') { InvoiceAttachmentService.new(invoice, remote).attach }
end
end