Add tests for the QuickBooks writers and services

A fake QuickBooks service (test/qbo_fake_service.rb) stands in for the
estimate, invoice and connection services, so the writers are tested
end to end without QuickBooks.

Covers EstimateWriter (reading, saving, subtotals, discounts, custom
fields, locks, accepting, emailing), InvoiceWriter (from estimates,
paid-invoice unlock, closing estimates, imports of time and
estimates), PaymentWriter (oldest-first allocation, deposits, edits),
EstimateIssueBuilder, Company, the sync services and
CustomerSearchService.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-20 16:28:38 -05:00
1 parent 00400c21dc
commit 9ed3ef23fb
9 files changed
+1521

No files matched your search

+222
View File
@@ -0,0 +1,222 @@
#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.
# Stands in for QuickBooks in the estimate, invoice and payment writer tests: one in-memory service answers
# QboEstimateService.with_service, QboInvoiceService.with_service and QboConnectionService.with_qbo_service.
module QboFakeServiceHelper
class FakeService
attr_reader :records, :created, :updated, :sent, :queries, :entities, :customers
# query_results: { "SQL fragment" or entity name => [records] }; fail_query: a regexp of queries to refuse
attr_accessor :query_results, :fail_query, :pdf_body
def initialize(*records)
@records = {}
records.each { |record| add(record) }
@created = []
@updated = []
@sent = []
@queries = []
@entities = []
@query_results = {}
@customers = {}
end
def add(record)
@records[record.id.to_s] = record
record
end
# Local models' details (Customer#details, Item#details...) are looked up through with_qbo_service; they
# get a blank QuickBooks record unless one was added to customers
DETAIL_ENTITIES = %w[Customer Item Account Employee].freeze
def fetch_by_id(id)
return records[id.to_s] if records.key?(id.to_s)
entity = entities.last.to_s
return customers[id.to_s] ||= Quickbooks::Model::Customer.new if entity == 'Customer'
return "Quickbooks::Model::#{entity}".constantize.new if DETAIL_ENTITIES.include?(entity)
nil
end
def create(doc)
doc.id ||= (5000 + created.size).to_s
doc.sync_token = 0
doc.doc_number ||= "N#{doc.id}" if doc.respond_to?(:doc_number=)
created << doc
add(doc)
end
def update(doc, sparse: false)
doc.sync_token = doc.sync_token.to_i + 1
updated << doc
add(doc)
end
def send_document(id, email)
sent << [id.to_s, email]
records[id.to_s]
end
alias send_estimate send_document
alias send_invoice send_document
def query(sql = nil, per_page: nil)
queries << sql
raise StandardError, 'query refused' if fail_query && sql.to_s.match?(fail_query)
key = sql ? query_results.keys.detect { |k| sql.include?(k) } : entities.last
Struct.new(:entries).new(Array(query_results[key]))
end
# SyncServiceBase#sync: query_results[entity name] in pages
def query_in_batches(sql, per_page: 1000)
queries << sql
Array(query_results[entities.last.to_s]).each_slice(per_page) { |batch| yield batch }
end
def find_by(field, value)
records.values.select { |r| r.respond_to?(field) && r.public_send(field).to_s == value.to_s }
end
def all(sql)
query(sql).entries
end
def pdf(doc)
pdf_body || "PDF #{doc.id}"
end
end
def install_fake_quickbooks(fake = FakeService.new)
@restore_quickbooks ||= []
[RedmineQboBilling::QboEstimateService, RedmineQboBilling::QboInvoiceService].each do |klass|
replace_class_method(klass, :with_service) do |&block|
fake.entities << klass.name.demodulize.gsub(/\AQbo|Service\z/, '')
block.call(fake)
end
end
replace_class_method(QboConnectionService, :with_qbo_service) do |entity: nil, &block|
fake.entities << entity
block.call(fake)
end
fake
end
def replace_class_method(klass, name, &body)
original = klass.method(name)
klass.define_singleton_method(name, &body)
@restore_quickbooks << -> { klass.define_singleton_method(name, original) }
end
def self.included(base)
base.teardown { Array(@restore_quickbooks).reverse_each(&:call) }
end
# The QuickBooks company's sales form settings (RedmineQboBilling::Company.settings)
def stub_company(custom_fields: [{ id: 1, name: 'Sales Rep' }, { id: 2, name: 'VIN' }], custom_txn_numbers: false,
estimate_message: 'Thank you for your business', invoice_message: 'Payment due on receipt')
RedmineQboBilling::Company.stubs(:settings).returns(
custom_fields: custom_fields, custom_txn_numbers: custom_txn_numbers, allow_discount: true,
estimate_message: estimate_message, invoice_message: invoice_message
)
end
def stub_local_syncs
EstimateSyncService.any_instance.stubs(:sync_by_id)
InvoiceSyncService.any_instance.stubs(:sync_by_id)
PaymentSyncService.any_instance.stubs(:sync_by_id)
end
# ---- QuickBooks documents ----
def qbo_ref(value, name = nil)
Quickbooks::Model::BaseReference.new(value.to_s, name: name)
end
def qbo_link(type, id)
Quickbooks::Model::LinkedTransaction.new(txn_id: id.to_s, txn_type: type)
end
def qbo_sales_line(id, item_id, name, quantity, rate, taxable: true, description: '')
line = Quickbooks::Model::InvoiceLineItem.new
line.id = id.to_s
line.description = description
line.amount = (BigDecimal(quantity.to_s) * BigDecimal(rate.to_s)).round(2)
line.sales_item! do |d|
d.item_ref = qbo_ref(item_id, name)
d.quantity = BigDecimal(quantity.to_s)
d.unit_price = BigDecimal(rate.to_s)
d.tax_code_ref = qbo_ref(taxable ? 'TAX' : 'NON')
end
line
end
def qbo_note_line(id, text)
line = Quickbooks::Model::InvoiceLineItem.new
line.id = id.to_s
line.description = text
line.description_only!
line
end
def qbo_discount_line(amount, percent: nil, account: nil)
line = Quickbooks::Model::InvoiceLineItem.new
line.amount = BigDecimal(amount.to_s)
line.discount_item! do |d|
d.percent_based = !percent.nil?
d.discount_percent = BigDecimal(percent.to_s) if percent
d.discount_account_ref = qbo_ref(account) if account
end
line
end
def qbo_custom_field(id, name, value)
field = Quickbooks::Model::CustomField.new
field.id = id
field.name = name
field.type = 'StringType'
field.string_value = value
field
end
def qbo_document(klass, id:, customer_id:, customer_name: nil, lines: [], status: nil, links: [], doc_number: nil,
total: nil, balance: nil, custom_fields: [], sync_token: 3, txn_date: Date.new(2026, 11, 10))
doc = klass.new
doc.id = id.to_s
doc.sync_token = sync_token
doc.doc_number = doc_number || id.to_s
doc.txn_date = txn_date
doc.customer_ref = qbo_ref(customer_id, customer_name)
doc.line_items = lines
doc.txn_status = status if doc.respond_to?(:txn_status=)
doc.linked_transactions = links
doc.total = BigDecimal(total.to_s) if total
doc.balance = BigDecimal(balance.to_s) if balance && doc.respond_to?(:balance=)
doc.custom_fields = custom_fields
doc
end
def qbo_estimate(id: 598, customer_id: 9101, **options)
qbo_document(Quickbooks::Model::Estimate, id: id, customer_id: customer_id, **options)
end
def qbo_invoice(id: 601, customer_id: 9101, **options)
qbo_document(Quickbooks::Model::Invoice, id: id, customer_id: customer_id, **options)
end
def local_customer(id = 9101, name = 'Jane Customer')
Customer.where(id: id).delete_all
customer = Customer.new(id: id, name: name)
customer.skip_qbo_push = true
customer.save!
customer
end
end
+1
View File
@@ -9,6 +9,7 @@
#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/test_helper', __dir__)
require File.expand_path('qbo_fake_service', __dir__)
module QboRefundTestHelper
CUSTOMER_ID = 9101
+84
View File
@@ -0,0 +1,84 @@
#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 CompanyTest < ActiveSupport::TestCase
include QboFakeServiceHelper
Company = RedmineQboBilling::Company
def name_value(name, string: nil, boolean: nil)
Struct.new(:name, :string_value, :boolean_value).new(name, string, boolean)
end
def settings(fields, extra = {})
Company.stubs(:settings).returns({ custom_fields: fields }.merge(extra))
end
def test_parse_custom_fields
entries = [name_value('SalesFormsPrefs.UseSalesCustom1', boolean: 'true'),
name_value('SalesFormsPrefs.SalesCustomName1', string: ' Sales Rep '),
name_value('SalesFormsPrefs.UseSalesCustom2', boolean: 'false'),
name_value('SalesFormsPrefs.SalesCustomName2', string: 'Old'),
name_value('SalesFormsPrefs.SalesCustomName3', string: 'VIN'),
name_value('SalesFormsPrefs.SalesCustomName4', string: '')]
assert_equal [{ id: 1, name: 'Sales Rep' }, { id: 3, name: 'VIN' }], Company.parse_custom_fields(entries)
end
def test_merge_fields_prefers_newer_custom_fields
legacy = [{ id: 1, name: 'Sales Rep old' }]
assert_equal [{ id: 5_000_001, name: 'Sales Person' }],
Company.merge_fields(legacy, [{ id: 1, name: 'x' }, { id: 5_000_001, name: 'Sales Person' }])
assert_equal [{ id: 1, name: 'Sales Rep old' }, { id: 2, name: 'VIN' }],
Company.merge_fields(legacy, [{ id: 1, name: 'Sales' }, { id: 2, name: 'VIN' }])
end
def test_fields_hidden_in_settings_are_left_out
settings([{ id: 1, name: 'Sales Rep' }, { id: 2, name: 'VIN' }, { id: 3, name: 'Mileage' }])
Setting.stubs(:plugin_redmine_qbo).returns('hidden_custom_field_ids' => ['3', ''])
assert_equal [1, 2], Company.custom_fields.map(&:id)
assert_equal [1, 2, 3], Company.all_custom_fields.map(&:id)
assert_equal 1, Company.sales_person_field.id
assert_equal [2], Company.editable_custom_fields.map(&:id)
assert_equal 2, Company.custom_field_matching(/\bvin\b/i).id
assert_nil Company.custom_field_matching(/mileage/i)
end
def test_flags_and_messages
settings([], custom_txn_numbers: true, allow_discount: false, estimate_message: 'Thanks', invoice_message: nil)
assert Company.custom_txn_numbers?
assert_not Company.discounts_allowed?
assert_equal 'Thanks', Company.estimate_message
assert_equal '', Company.invoice_message
settings([])
assert Company.discounts_allowed?
assert_not Company.custom_txn_numbers?
end
def test_fetch_settings_from_preferences_and_recent_estimates
fake = install_fake_quickbooks
prefs = Struct.new(:sales_forms).new(
Struct.new(:custom_fields, :custom_txn_numbers?, :allow_discount?, :estimate_message, :default_customer_message)
.new([name_value('SalesFormsPrefs.SalesCustomName1', string: 'Sales Rep')], 'true', 'false', 'Thanks', 'Pay up')
)
fake.query_results = { 'Preferences' => [prefs],
'FROM Estimate' => [qbo_estimate(custom_fields: [qbo_custom_field(2, 'VIN', 'x')])] }
result = Company.fetch_settings
assert_equal [{ id: 1, name: 'Sales Rep' }, { id: 2, name: 'VIN' }], result[:custom_fields]
assert_equal [true, false, 'Thanks', 'Pay up'], result.values_at(:custom_txn_numbers, :allow_discount, :estimate_message, :invoice_message)
end
def test_settings_are_empty_when_quickbooks_is_unreachable
QboConnectionService.stubs(:with_qbo_service).raises(StandardError, 'QBO not connected')
assert_nil Company.fetch_settings
assert_equal({}, Company.settings)
assert_equal({}, Company.refresh!)
end
end
+82
View File
@@ -0,0 +1,82 @@
#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 CustomerSearchServiceTest < ActiveSupport::TestCase
Search = CustomerSearchService
ROWS = [
[1, 'William Smith', '4015550101', nil],
[2, 'Robert Jones', nil, '4015550199'],
[3, 'Kathy McDonald', '5085551234', nil],
[4, "Sean O'Brien LLC", nil, nil],
[5, 'José Alvarez', nil, nil],
[6, 'Jon Smyth', nil, nil]
].freeze
def rank(**query)
Search.rank(Search.prepare(ROWS), **query).map(&:first)
end
def test_tokens
assert_equal %w[obrien smith jose], Search.tokens("O'Brien-Smith, José")
assert_equal %w[sean obrien], Search.tokens("Sean O'Brien LLC")
assert_equal %w[the company], Search.tokens('The Company')
end
def test_nicknames_sound_alikes_typos_and_order
assert_equal 1, rank(name: 'Bill Smith').first
assert_equal 2, rank(name: 'Bob Jones').first
assert_equal 1, rank(name: 'Smith, William').first
assert_equal 1, rank(name: 'Willaim Smtih').first
assert_includes rank(name: 'John Smith'), 6
assert_equal 3, rank(name: 'Cathy Mc Donald').first
assert_equal 5, rank(name: 'jose alvarez').first
end
def test_partial_names_while_typing
assert_equal 1, rank(name: 'will smi').first
assert_equal 1, rank(name: 'bil smith').first
end
def test_unrelated_names_do_not_match
assert_empty rank(name: 'Bill Jones') & [1]
assert_empty rank(name: 'Zebulon')
assert_empty rank(name: '')
end
def test_phone_numbers
assert_equal [2], rank(phone: '0199')
assert_equal [1], rank(name: '(401) 555-0101')
assert_equal [], rank(phone: '12')
assert_equal 1.0, Search.phone_score('5550101', ['4015550101'])
assert_equal 0.9, Search.phone_score('5550', ['4015550101'])
end
def test_limit
assert_equal 1, Search.rank(Search.prepare(ROWS), phone: '401555', limit: 1).size
end
def test_nicknames_need_a_shared_longer_name
assert Search.nicknames?('bill', 'will')
assert_not Search.nicknames?('william', 'robert')
assert Search.nicknames?('liam', 'william')
end
def test_call_returns_customers_best_first
Customer.where(id: [9101, 9102]).delete_all
[[9101, 'William Smith'], [9102, 'Bill Smithers']].each do |id, name|
Customer.new(id: id, name: name).tap { |c| c.skip_qbo_push = true }.save!
end
assert_equal 9101, Search.call(name: 'William Smith').first.id
assert_empty Search.call(name: 'zzzz')
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 EstimateIssueBuilderTest < ActiveSupport::TestCase
include QboFakeServiceHelper
fixtures :projects, :users, :email_addresses, :roles, :members, :member_roles, :issues, :issue_statuses, :trackers,
:projects_trackers, :enabled_modules, :enumerations, :workflows, :custom_fields, :custom_values,
:custom_fields_projects, :custom_fields_trackers, :issue_relations
Builder = RedmineQboBilling::EstimateIssueBuilder
def setup
Setting.stubs(:plugin_redmine_qbo).returns('issue_default_tracker_id' => '2', 'issue_default_project_id' => '1')
QboEstimateLineIssue.delete_all
Estimate.where(id: 598).delete_all
local_customer
@estimate = Estimate.create!(id: 598, doc_number: '1068', customer_id: 9101)
@estimate.stubs(:line_items).returns([
qbo_sales_line(1, 10, 'Labor', 2, 120, description: 'Install lift kit'),
qbo_sales_line(2, 11, 'Brake pads', 4, 30, description: 'Pads'),
qbo_sales_line(3, 10, 'Labor', 0, 120, description: 'Diagnose noise'),
qbo_sales_line(4, 10, 'Labor', 1, 120, description: ' ')
])
@project = Project.find(1)
@author = User.find(1)
User.current = @author
end
def rows(*line_ids, **extra)
line_ids.to_h { |id| [id.to_s, { 'selected' => '1', 'tracker_id' => '1' }.merge(extra.transform_keys(&:to_s))] }
end
def test_settings
assert_equal 2, Builder.default_tracker_id
assert_equal 1, Builder.default_project_id
end
def test_labor_hours
assert_equal 3.0, Builder.labor_hours(@estimate)
assert_equal 0.0, Builder.labor_hours(nil)
end
def test_proposals_are_labor_lines_with_a_description
proposals = Builder.new(@estimate).proposals
assert_equal %w[1 3], proposals.map(&:line_id)
assert_equal ['Install lift kit', 2.0], [proposals.first.description, proposals.first.hours]
assert_nil proposals.last.hours
assert_not proposals.first.created?
assert_equal [], Builder.new(nil).proposals
end
def test_create_issues
builder = Builder.new(@estimate, defaults: { start_date: Date.new(2026, 11, 23), assignee: User.find(3) })
created = builder.create_issues(project: @project, rows: rows(1, 3, estimated_hours: '1.5'), author: @author)
assert_empty builder.errors
# Subjects are title-cased by the issue patch
assert_equal ['Install Lift Kit', 'Diagnose Noise'], created.map(&:subject)
issue = created.first.reload
assert_equal [598, 9101, 1.5, Date.new(2026, 11, 23)], [issue.estimate_id, issue.customer_id, issue.estimated_hours, issue.start_date]
assert_match 'Estimate #1068', issue.description
assert_equal 2, QboEstimateLineIssue.where(estimate_id: 598).count
assert issue.relations.any? { |r| r.other_issue(issue) == created.last }
# Shown as created; can't be made again
again = Builder.new(@estimate)
assert again.proposals.all?(&:created?)
assert_equal [], again.create_issues(project: @project, rows: rows(1), author: @author)
assert_equal [I18n.t(:error_no_estimate_lines_selected)], again.errors
end
def test_later_batches_are_related_to_earlier_ones
first = Builder.new(@estimate).create_issues(project: @project, rows: rows(1), author: @author)
second = Builder.new(@estimate).create_issues(project: @project, rows: rows(3), author: @author)
assert IssueRelation.where(issue_from_id: [first.first.id, second.first.id], issue_to_id: [first.first.id, second.first.id]).exists?
end
def test_nothing_is_created_when_one_issue_fails
builder = Builder.new(@estimate)
count = Issue.count
created = builder.create_issues(project: @project, rows: rows(1).merge(rows(3, tracker_id: '999')), author: @author)
assert_equal [], created
assert_equal count, Issue.count
assert_match 'Diagnose noise', builder.errors.first
assert_equal 0, QboEstimateLineIssue.count
end
def test_subject_and_default_description_overrides
builder = Builder.new(@estimate, defaults: { description: 'From the appointment' })
created = builder.create_issues(project: @project, rows: rows(1, subject: 'Custom subject'), author: @author)
assert_equal 'Custom Subject', created.first.subject
assert_equal 'From the appointment', created.first.description
end
def test_unassignable_user_is_left_off
outsider = User.find(7)
created = Builder.new(@estimate, defaults: { assignee: outsider }).create_issues(project: @project, rows: rows(1), author: @author)
assert_nil created.first.assigned_to
end
def test_subtasks_take_the_parents_customer
parent = Issue.find(1)
parent.update_column(:customer_id, 9102)
created = Builder.new(@estimate, parent: parent).create_issues(project: @project, rows: rows(1), author: @author)
issue = created.first.reload
assert_equal parent.id, issue.parent_id
assert_equal 9102, issue.customer_id
# Not related to its own parent
assert_not issue.relations.any? { |r| r.other_issue(issue) == parent }
end
def test_plugins_set_their_fields
Redmine::Hook.expects(:call_hook).with(:qbo_billing_build_issue, has_key(:issue)).once
Builder.new(@estimate).create_issues(project: @project, rows: rows(1), author: @author)
end
def test_relate_all_skips_existing_relations
issues = Issue.where(id: [1, 2, 3]).order(:id).to_a
IssueRelation.where(issue_from_id: [1, 2, 3]).or(IssueRelation.where(issue_to_id: [1, 2, 3])).delete_all
IssueRelation.create!(issue_from: issues[0], issue_to: issues[1], relation_type: 'relates')
assert_equal 2, Builder.relate_all(issues + [nil, issues[0]])
assert_equal 0, Builder.relate_all(issues)
assert_equal 0, Builder.relate_all([issues.first])
end
end
+372
View File
@@ -0,0 +1,372 @@
#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 EstimateWriterTest < ActiveSupport::TestCase
include QboFakeServiceHelper
fixtures :projects, :users, :issues, :trackers, :issue_statuses, :enumerations
Writer = RedmineQboBilling::EstimateWriter
Form = RedmineQboBilling::EstimateForm
def setup
@customer = local_customer
@fake = install_fake_quickbooks
stub_company
stub_local_syncs
Setting.stubs(:plugin_redmine_qbo).returns('expiration_days' => '30')
Issue.where(estimate_id: [598, 599]).update_all(estimate_id: nil)
@user = User.find(2)
end
def remote_estimate(**options)
qbo_estimate(customer_name: 'Jane Customer', doc_number: '1068', status: 'Pending',
custom_fields: [qbo_custom_field(1, 'Sales Rep', 'Ricky'), qbo_custom_field(2, 'VIN', '1C4HJXDG5JW123456')],
lines: [qbo_note_line(1, 'Lift kit install'),
qbo_sales_line(2, 10, 'Labor', 2, 120, taxable: false, description: 'Install'),
qbo_note_line(3, 'Subtotal: $240.00'),
qbo_sales_line(4, 11, 'Brake pads', 4, '30.5')],
**options)
end
def form(attrs = {})
Form.new({ customer_id: @customer.id.to_s, txn_date: '2026-11-20', email: 'jane@example.com',
lines: [Form::Line.new(item_id: '10', quantity: '2', rate: '120', taxable: false, description: 'Install'),
Form::Line.new(kind: 'subtotal'),
Form::Line.new(item_id: '11', quantity: '4', rate: '30.50', taxable: true)] }.merge(attrs))
end
# ---- reading ----
def test_form_from_remote
result = Writer.form_from_remote(remote_estimate)
assert_equal '598', result.id
assert_equal '3', result.sync_token
assert_equal '9101', result.customer_id
assert_equal 'Jane Customer', result.customer_name
assert_equal '1068', result.doc_number
assert_equal 'Ricky', result.sales_person
assert_equal({ '1' => 'Ricky', '2' => '1C4HJXDG5JW123456' }, result.custom_fields)
assert_equal [nil, nil, 'subtotal', nil], result.lines.map(&:kind)
labor = result.lines[1]
assert_equal %w[10 Labor 2 120], [labor.item_id, labor.item_name, labor.quantity, labor.rate]
assert_not labor.taxable?
assert result.lines[3].taxable?
assert_equal '30.5', result.lines[3].rate
assert_nil result.locked
end
def test_locked_states
assert_equal :billed, Writer.form_from_remote(remote_estimate(status: 'Converted')).locked
assert_equal :billed, Writer.form_from_remote(remote_estimate(links: [qbo_link('Invoice', 601)])).locked
bundle = Quickbooks::Model::InvoiceLineItem.new
bundle.group_line_detail!
assert_equal :bundles, Writer.form_from_remote(remote_estimate(lines: [bundle])).locked
Issue.find(1).update_column(:estimate_id, 598)
assert_equal :linked, Writer.form_from_remote(remote_estimate).locked
end
def test_invoiced_on_lists_the_invoices
Invoice.where(id: 601).delete_all
Invoice.create!(id: 601, doc_number: '1234', customer_id: 9101, txn_date: Date.new(2026, 11, 12))
result = Writer.form_from_remote(remote_estimate(links: [qbo_link('Invoice', 601), qbo_link('Invoice', 601), qbo_link('Payment', 7)]))
assert_equal [%w[601 1234]], result.invoiced_on
end
def test_discount_fields
percent = remote_estimate(lines: [qbo_sales_line(1, 10, 'Labor', 1, 100), qbo_discount_line(10, percent: 10)])
assert_equal({ discount_type: 'percent', discount_value: '10' }, Writer.discount_fields(percent))
amount = remote_estimate(lines: [qbo_discount_line('12.5'), qbo_discount_line('2.5', percent: 1)])
assert_equal({ discount_type: 'amount', discount_value: '15' }, Writer.discount_fields(amount))
assert_equal({}, Writer.discount_fields(remote_estimate))
assert_equal BigDecimal('15'), Writer.discount_total(amount)
assert_nil Writer.discount_total(remote_estimate)
end
def test_line_from_remote_skips_quickbooks_own_lines
subtotal = Quickbooks::Model::InvoiceLineItem.new
subtotal.detail_type = 'SubTotalLineDetail'
assert_nil Writer.line_from_remote(subtotal)
assert_nil Writer.line_from_remote(qbo_discount_line(5))
assert Writer.line_from_remote(qbo_note_line(1, 'subtotal: -$1,000.25')).subtotal?
assert_equal 'Subtotal for brakes', Writer.line_from_remote(qbo_note_line(1, 'Subtotal for brakes')).description
end
def test_custom_value
remote = remote_estimate
assert_equal 'Ricky', Writer.custom_value(remote, RedmineQboBilling::Company::Field.new(1, 'Sales Rep'))
assert_equal '', Writer.custom_value(remote, RedmineQboBilling::Company::Field.new(3, 'Other'))
# Unknown field: found by name, but never a hidden one
assert_equal 'Ricky', Writer.custom_value(remote, nil, /sales/i)
RedmineQboBilling::Company.stubs(:hidden_field_ids).returns([1])
assert_equal '', Writer.custom_value(remote, nil, /sales/i)
end
def test_load
@fake.add(remote_estimate)
assert_equal '1068', Writer.load(598).doc_number
error = assert_raises(Writer::Error) { Writer.load(999) }
assert_equal I18n.t(:notice_estimate_not_found), error.message
end
# ---- new, duplicate, create for plugins ----
def test_new_form
@user.stubs(:today).returns(Date.new(2026, 11, 20))
result = Writer.new_form(customer: @customer, user: @user)
assert_equal '2026-11-20', result.txn_date
assert_equal '2026-12-20', result.expiration_date
assert_equal @user.name, result.sales_person
assert_equal 'Thank you for your business', result.customer_memo
assert_equal 2, result.lines.size
assert result.lines.all?(&:taxable?)
assert_equal 'Jane Customer', result.customer_name
end
def test_no_expiration_without_the_setting
Setting.stubs(:plugin_redmine_qbo).returns({})
assert_nil Writer.new_form(user: @user).expiration_date
end
def test_duplicate_form
@fake.add(remote_estimate(lines: [qbo_sales_line(2, 10, 'Labor', 2, 120), qbo_discount_line(24, percent: 10)]))
@user.stubs(:today).returns(Date.new(2026, 11, 20))
copy = Writer.duplicate_form(598, user: @user)
assert_not copy.persisted?
assert_equal '1068', copy.duplicated_from
assert_equal '2026-11-20', copy.txn_date
assert_equal @user.name, copy.sales_person
assert_equal 'percent', copy.discount_type
assert_equal '10', copy.discount_value
assert_equal [nil], copy.lines.map(&:id)
assert_equal '1C4HJXDG5JW123456', copy.custom_field(2)
end
def test_create_estimate_for_another_plugin
saved = Writer.create_estimate(customer: @customer, private_note: 'From #116',
lines: [{ description: 'Added from: Install #116: lift' },
{ item_id: 11, quantity: 2.0, rate: '45.50', taxable: false }],
custom_fields: { 2 => 'VIN9' }, txn_date: Date.new(2026, 11, 20))
assert_equal 1, @fake.created.size
assert_equal 'From #116', saved.private_note
assert_equal 'Thank you for your business', saved.customer_memo
sales = saved.line_items.find(&:sales_item?)
assert_equal BigDecimal('91'), sales.amount
assert_equal 'NON', sales.sales_line_item_detail.tax_code_ref.value
assert_equal Date.new(2026, 12, 20), saved.expiration_date
# Made without a user: no sales person
assert_equal({ 2 => 'VIN9' }, saved.custom_fields.to_h { |f| [f.id, f.string_value] })
end
# ---- saving ----
def test_create
saved = Writer.save(form, user: @user)
estimate = @fake.created.first
assert_equal saved, estimate
assert_equal 9101, estimate.customer_ref.value.to_i
assert_equal 'jane@example.com', estimate.bill_email.address
assert_equal Date.new(2026, 11, 20), estimate.txn_date
assert_equal ['Install', 'Subtotal: $240.00', nil], estimate.line_items.map(&:description)
assert_equal [1, 2, 3], estimate.line_items.map(&:line_num)
assert_equal BigDecimal('122'), estimate.line_items.last.amount
# Sales person on create
assert_equal({ 1 => @user.name }, estimate.custom_fields.to_h { |f| [f.id, f.string_value] })
assert_nil estimate.doc_number.to_s[/\A\d+\z/]
end
def test_create_numbers_estimates_with_custom_transaction_numbers
stub_company(custom_txn_numbers: true)
Estimate.where(id: [9401, 9402]).delete_all
Estimate.create!(id: 9401, doc_number: '1068', customer_id: 9101)
Estimate.create!(id: 9402, doc_number: 'X-1', customer_id: 9101)
Writer.save(form, user: @user)
assert_equal '1069', @fake.created.first.doc_number
end
def test_create_with_discount
Writer.save(form(discount_value: '10'), user: @user)
estimate = @fake.created.first
discount = estimate.line_items.last
assert discount.discount_item?
assert_equal BigDecimal('36.2'), discount.amount
assert_equal BigDecimal('10'), discount.discount_line_detail.discount_percent
assert estimate.apply_tax_after_discount?
end
def test_needs_a_local_customer
error = assert_raises(Writer::Error) { Writer.save(form(customer_id: '424242'), user: @user) }
assert_equal I18n.t(:error_estimate_needs_customer), error.message
end
def test_update_keeps_line_ids_custom_fields_and_discount_account
remote = @fake.add(remote_estimate(lines: [qbo_sales_line(2, 10, 'Labor', 2, 120), qbo_discount_line(5, account: '86')]))
edited = Writer.form_from_remote(remote)
edited.lines.first.quantity = '3'
edited.lines << Form::Line.new(description: 'New note')
edited.custom_fields['2'] = 'NEWVIN'
edited.discount_type = 'amount'
edited.discount_value = '20'
Writer.save(edited, user: @user)
update = @fake.updated.first
assert_equal '598', update.id
assert_equal ['2', nil, nil], update.line_items.map(&:id)
assert_equal BigDecimal('360'), update.line_items.first.amount
assert_equal '86', update.line_items.last.discount_line_detail.discount_account_ref.value
fields = update.custom_fields.to_h { |f| [f.id, f.string_value] }
# The sales person isn't replaced by whoever edits it
assert_equal({ 1 => 'Ricky', 2 => 'NEWVIN' }, fields)
assert_nil update.billing_address
end
def test_changing_customer_copies_the_billing_address
other = local_customer(9102, 'Bob Builder')
remote = @fake.add(remote_estimate)
address = Quickbooks::Model::PhysicalAddress.new
address.line1 = '1 Main St'
@fake.customers['9102'] = Quickbooks::Model::Customer.new(billing_address: address)
edited = Writer.form_from_remote(remote)
edited.customer_id = other.id.to_s
Writer.save(edited, user: @user)
assert_equal '1 Main St', @fake.updated.first.billing_address.line1
end
def test_update_refuses_stale_billed_and_bundled_estimates
remote = @fake.add(remote_estimate)
stale = Writer.form_from_remote(remote)
stale.sync_token = '2'
assert_raises(Writer::Conflict) { Writer.save(stale, user: @user) }
remote.txn_status = 'Closed'
error = assert_raises(Writer::Error) { Writer.save(Writer.form_from_remote(remote), user: @user) }
assert_equal I18n.t(:error_estimate_billed), error.message
bundle = Quickbooks::Model::InvoiceLineItem.new
bundle.group_line_detail!
remote.txn_status = 'Pending'
remote.line_items = [qbo_sales_line(2, 10, 'Labor', 1, 1), bundle]
error = assert_raises(Writer::Error) { Writer.save(Writer.form_from_remote(remote).tap { |f| f.locked = nil }, user: @user) }
assert_equal I18n.t(:error_estimate_has_bundles), error.message
assert_raises(Writer::Error) { Writer.save(form.tap { |f| f.id = '999' }, user: @user) }
assert_empty @fake.updated
end
def test_rate_falls_back_to_the_item_price
Item.where(id: 11).delete_all
item = Item.new(id: 11, name: 'Brake pads', description: '', unit_price: 42)
item.skip_qbo_push = true
item.save!
Writer.save(form(lines: [Form::Line.new(item_id: '11', quantity: '2')]), user: @user)
assert_equal BigDecimal('84'), @fake.created.first.line_items.first.amount
end
def test_unsaved_answer_is_an_error
@fake.define_singleton_method(:create) { |_doc| nil }
error = assert_raises(Writer::Error) { Writer.save(form, user: @user) }
assert_equal I18n.t(:error_estimate_not_saved), error.message
end
# ---- accepting, emailing, custom fields ----
def test_accept_a_pending_estimate
@fake.add(remote_estimate)
@user.stubs(:today).returns(Date.new(2026, 11, 20))
result = Writer.accept(598, user: @user)
assert result.accepted?
update = @fake.updated.first
assert_equal 'Accepted', update.txn_status
assert_equal 'Jane Customer', update.accepted_by
assert_equal Date.new(2026, 11, 20), update.accepted_date
assert_equal 4, update.line_items.size
end
def test_accept_leaves_other_statuses_and_reports_failures
@fake.add(remote_estimate(status: 'Rejected'))
result = Writer.accept(598, user: @user)
assert_equal :unchanged, result.outcome
assert_equal 'Rejected', result.message
assert_empty @fake.updated
assert Writer.accept(999, user: @user).failed?
@fake.add(remote_estimate)
@fake.define_singleton_method(:update) { |_doc, sparse: false| raise Quickbooks::IntuitRequestException, 'Stale' }
result = Writer.accept(598, user: @user)
assert result.failed?
assert_equal 'Stale', result.message
end
def test_send_email
@fake.add(remote_estimate)
assert_equal '598', Writer.send_email(598, 'jane@example.com').id
assert_equal [%w[598 jane@example.com]], @fake.sent
assert_raises(Writer::Error) { Writer.send_email(999, 'jane@example.com') }
end
def test_custom_field_value
@fake.add(remote_estimate)
assert_equal '1C4HJXDG5JW123456', Writer.custom_field_value(598, 2)
assert_nil Writer.custom_field_value(598, 9)
assert_nil Writer.custom_field_value('', 2)
assert_nil Writer.custom_field_value(999, 2)
end
# ---- helpers ----
def test_subtotal_text
assert_equal 'Subtotal: $1,342.60', Writer.subtotal_text('1342.6')
assert_equal 'Subtotal: -$5.00', Writer.subtotal_text(-5)
assert_equal 'Subtotal: $1,000,000.00', Writer.subtotal_text(1_000_000)
end
def test_tidy_subtotals
lines = [Form::Line.new(kind: 'subtotal'), Form::Line.new(rate: '1'), Form::Line.new(kind: 'subtotal'),
Form::Line.new(kind: 'subtotal'), Form::Line.new(rate: '2')]
assert_equal [nil, 'subtotal', nil], Writer.tidy_subtotals(lines).map(&:kind)
end
def test_subtotals_total_their_own_section
Writer.save(form(lines: [Form::Line.new(item_id: '1', rate: '10'), Form::Line.new(description: 'Note'),
Form::Line.new(kind: 'subtotal'), Form::Line.new(item_id: '1', rate: '5'),
Form::Line.new(kind: 'subtotal')]), user: @user)
assert_equal ['Subtotal: $10.00', 'Subtotal: $5.00'],
@fake.created.first.line_items.map(&:description).grep(/Subtotal/)
end
def test_plain_number_and_format_address
assert_equal '2', Writer.plain_number(BigDecimal('2.0'))
assert_equal '12.5', Writer.plain_number('12.50')
assert_equal '', Writer.plain_number(nil)
address = Quickbooks::Model::PhysicalAddress.new
address.line1 = '1 Main St'
address.line2 = ' '
address.city = 'Providence'
address.country_sub_division_code = 'RI'
address.postal_code = '02903'
assert_equal "1 Main St\nProvidence, RI 02903", Writer.format_address(address)
assert_equal '', Writer.format_address(nil)
end
def test_time_activity_links
line = Quickbooks::Model::InvoiceLineItem.new
Writer.link_time_activity(line, '77')
assert_equal '77', Writer.linked_time_activity_id(line)
Writer.link_time_activity(line, '')
assert_equal '77', Writer.linked_time_activity_id(line)
end
def test_next_doc_number
Invoice.delete_all
assert_nil Writer.next_doc_number(Invoice)
end
end
+285
View File
@@ -0,0 +1,285 @@
#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 InvoiceWriterTest < ActiveSupport::TestCase
include QboFakeServiceHelper
fixtures :projects, :users, :issues, :trackers, :issue_statuses, :enumerations
Writer = RedmineQboBilling::InvoiceWriter
Form = RedmineQboBilling::EstimateForm
def setup
@customer = local_customer
@fake = install_fake_quickbooks
stub_company
stub_local_syncs
Issue.where(estimate_id: [598, 599]).update_all(estimate_id: nil)
Invoice.where(id: [601, 602]).delete_all
@user = User.find(2)
@user.stubs(:today).returns(Date.new(2026, 11, 20))
end
def estimate(**options)
qbo_estimate(customer_name: 'Jane Customer', doc_number: '1068', status: 'Accepted',
custom_fields: [qbo_custom_field(1, 'Sales Rep', 'Ricky'), qbo_custom_field(2, 'VIN', '')],
lines: [qbo_sales_line(2, 10, 'Labor', 2, 120, taxable: false, description: 'Install #1: lift'),
qbo_sales_line(4, 11, 'Brake pads', 4, 30)], **options)
end
# Invoice #1234: $360 of lines plus $8.40 tax
def invoice(total: '368.40', balance: '368.40', **options)
doc = qbo_invoice(customer_name: 'Jane Customer', doc_number: '1234', total: total, balance: balance,
lines: [qbo_sales_line(1, 10, 'Labor', 2, 120, taxable: false), qbo_sales_line(2, 11, 'Brake pads', 4, 30)],
**options)
doc.txn_tax_detail = Quickbooks::Model::TransactionTaxDetail.new
doc.txn_tax_detail.total_tax = BigDecimal('8.40')
doc
end
def form(attrs = {})
Form.new({ document: 'invoice', customer_id: '9101', txn_date: '2026-11-20',
lines: [Form::Line.new(item_id: '10', quantity: '2', rate: '120')] }.merge(attrs))
end
def allow(*permissions)
@user.stubs(:allowed_to?).returns(false)
permissions.each { |p| @user.stubs(:allowed_to?).with(p, nil, global: true).returns(true) }
end
# ---- new invoices ----
def test_new_form
result = Writer.new_form(customer: @customer, user: @user)
assert result.invoice?
assert_equal '2026-11-20', result.txn_date
assert_equal 'Payment due on receipt', result.customer_memo
assert_equal @user.name, result.sales_person
end
def test_from_estimate
@fake.add(estimate(lines: [qbo_sales_line(2, 10, 'Labor', 2, 120), qbo_discount_line(24, percent: 10)]))
Issue.find(1).update_column(:estimate_id, 598)
RedmineQboBilling.expects(:field_defaults).with(@customer, issues: [Issue.find(1)]).returns('2' => 'VINFROMISSUE')
result = Writer.from_estimate(598, user: @user)
assert_equal '1068', result.converted_from
assert_equal ['598'], result.linked_estimate_ids
assert_equal 'Ricky', result.sales_person
assert_equal({ '2' => 'VINFROMISSUE', '1' => 'Ricky' }, result.custom_fields)
assert_equal '10', result.discount_value
assert_equal [nil], result.lines.map(&:id)
end
def test_from_estimate_refuses_billed_estimates
assert_raises(Writer::Error) { Writer.from_estimate(999, user: @user) }
Invoice.create!(id: 601, doc_number: '1234', customer_id: 9101, txn_date: Date.new(2026, 11, 12))
@fake.add(estimate(links: [qbo_link('Invoice', 601)]))
error = assert_raises(Writer::Error) { Writer.from_estimate(598, user: @user) }
assert_equal I18n.t(:error_estimate_already_invoiced, number: '1068', invoice: '1234'), error.message
end
def test_billing_error
assert_nil Writer.billing_error(estimate)
assert_equal I18n.t(:error_estimate_closed_billed, number: '1068', status: 'Closed'),
Writer.billing_error(estimate(status: 'Closed'))
assert_equal I18n.t(:error_estimate_rejected, number: '1068'), Writer.billing_error(estimate(status: 'Rejected'))
assert_equal I18n.t(:error_estimate_already_invoiced, number: '1068', invoice: '777'),
Writer.billing_error(estimate(links: [qbo_link('Invoice', 777)]))
end
# ---- reading ----
def test_form_from_remote
result = Writer.form_from_remote(invoice(balance: '100', links: [qbo_link('Estimate', 598), qbo_link('Payment', 9)]))
assert result.invoice?
assert_equal '1234', result.doc_number
assert_equal ['598'], result.linked_estimate_ids
assert_equal BigDecimal('268.40'), result.amount_paid
assert_equal :paid, result.locked
assert_nil Writer.form_from_remote(invoice).locked
end
def test_paid_helpers
assert_not Writer.paid?(invoice)
assert_not Writer.paid?(qbo_invoice)
assert Writer.paid?(invoice(balance: '100'))
assert_not Writer.fully_paid?(invoice(balance: '100'))
assert Writer.fully_paid?(invoice(balance: '0'))
assert_equal BigDecimal('0'), Writer.amount_paid(invoice)
end
def test_estimated_total_scales_the_tax
remote = invoice
assert_equal BigDecimal('368.40'), Writer.estimated_total(form(lines: [Form::Line.new(item_id: '1', rate: '360')]), remote)
assert_equal BigDecimal('184.20'), Writer.estimated_total(form(lines: [Form::Line.new(item_id: '1', rate: '180')]), remote)
remote.txn_tax_detail.total_tax = 0
assert_equal BigDecimal('180'), Writer.estimated_total(form(lines: [Form::Line.new(item_id: '1', rate: '180')]), remote)
end
# ---- saving ----
def test_create_closes_its_estimates_and_credits_their_sales_person
@fake.add(estimate)
Writer.save(form(linked_estimate_ids: ['598']), user: @user)
created = @fake.created.first
assert_equal({ 1 => 'Ricky' }, created.custom_fields.to_h { |f| [f.id, f.string_value] })
assert_equal [%w[Estimate 598]], created.linked_transactions.map { |t| [t.txn_type, t.txn_id] }
closed = @fake.updated.first
assert_equal ['598', 'Closed'], [closed.id, closed.txn_status]
end
def test_create_refuses_an_estimate_billed_meanwhile
@fake.add(estimate(status: 'Converted'))
assert_raises(Writer::Error) { Writer.save(form(linked_estimate_ids: ['598']), user: @user) }
assert_empty @fake.created
assert_raises(Writer::Error) { Writer.save(form(linked_estimate_ids: ['999']), user: @user) }
end
def test_create_with_time_and_due_date
Writer.save(form(due_date: '2026-12-20', lines: [Form::Line.new(item_id: '10', quantity: '1.5', rate: '120',
time_activity_id: '77', description: 'Install #1: lift')]),
user: @user)
created = @fake.created.first
assert_equal Date.new(2026, 12, 20), created.due_date
assert_equal [%w[TimeActivity 77]], created.linked_transactions.map { |t| [t.txn_type, t.txn_id] }
assert_equal '77', created.line_items.first.linked_transactions.first.txn_id
assert_equal @user.name, created.custom_fields.first.string_value
end
def test_update_keeps_payment_links
remote = @fake.add(invoice(links: [qbo_link('Estimate', 598), qbo_link('Payment', 9), qbo_link('TimeActivity', 5)]))
@fake.add(estimate(status: 'Closed'))
edited = Writer.form_from_remote(remote)
Writer.save(edited, user: @user)
update = @fake.updated.first
assert_equal [%w[Estimate 598], %w[Payment 9]], update.linked_transactions.map { |t| [t.txn_type, t.txn_id] }
# Already closed: left alone
assert_equal 1, @fake.updated.size
end
def test_paid_invoice_needs_unlocking_and_permission
remote = @fake.add(invoice(balance: '0'))
edited = Writer.form_from_remote(remote)
error = assert_raises(Writer::Error) { Writer.save(edited, user: @user) }
assert_equal I18n.t(:error_invoice_paid), error.message
allow(:write_invoices, :edit_partially_paid_invoices)
error = assert_raises(Writer::Error) { Writer.save(edited, user: @user, unlock: true) }
assert_equal I18n.t(:error_invoice_paid_not_allowed), error.message
allow(:write_invoices, :edit_paid_invoices)
Writer.save(edited, user: @user, unlock: true)
assert_equal 1, @fake.updated.size
end
def test_unlocked_invoice_cannot_drop_below_what_was_paid
allow(:write_invoices, :edit_paid_invoices)
remote = @fake.add(invoice(balance: '0'))
edited = Writer.form_from_remote(remote)
edited.discount_type = 'amount'
edited.discount_value = '50'
error = assert_raises(Writer::Error) { Writer.save(edited, user: @user, unlock: true) }
assert_match '$368.40', error.message
end
def test_update_refuses_stale_and_bundled_invoices
remote = @fake.add(invoice)
stale = Writer.form_from_remote(remote)
stale.sync_token = '1'
assert_raises(Writer::Conflict) { Writer.save(stale, user: @user) }
bundle = Quickbooks::Model::InvoiceLineItem.new
bundle.group_line_detail!
remote.line_items = [bundle]
assert_raises(Writer::Error) { Writer.save(Writer.form_from_remote(remote).tap { |f| f.lines = form.lines }, user: @user) }
assert_raises(Writer::Error) { Writer.save(form(id: '999'), user: @user) }
assert_raises(Writer::Error) { Writer.save(form(customer_id: '424242'), user: @user) }
end
def test_close_estimates_survives_errors
@fake.add(estimate)
@fake.define_singleton_method(:update) { |_doc, sparse: false| raise StandardError, 'down' }
assert_nothing_raised { Writer.close_estimates(%w[598 598 999]) }
end
def test_send_email
@fake.add(invoice)
Writer.send_email(601, 'jane@example.com')
assert_equal [%w[601 jane@example.com]], @fake.sent
assert_raises(Writer::Error) { Writer.send_email(999, 'x@example.com') }
end
def test_estimate_sales_person
@fake.add(estimate(id: 598, custom_fields: []))
@fake.add(estimate(id: 599))
assert_equal 'Ricky', Writer.estimate_sales_person(%w[598 599])
assert_nil Writer.estimate_sales_person([])
stub_company(custom_fields: [{ id: 2, name: 'VIN' }])
assert_nil Writer.estimate_sales_person(%w[599])
end
def test_invoice_number
assert_equal '601', Writer.invoice_number(601)
Invoice.create!(id: 601, doc_number: '1234', customer_id: 9101, txn_date: Date.new(2026, 11, 12))
assert_equal '1234', Writer.invoice_number('601')
end
# ---- importing ----
def time_activity(id, hours: nil, minutes: nil, status: 'Billable', customer_id: 9101, start: nil, finish: nil)
activity = Quickbooks::Model::TimeActivity.new
activity.id = id.to_s
activity.txn_date = '2026-11-18'
activity.customer_ref = qbo_ref(customer_id)
activity.employee_ref = qbo_ref(3, 'Tech One')
activity.item_ref = qbo_ref(10, 'Labor')
activity.hourly_rate = '120'
activity.hours = hours
activity.minutes = minutes
activity.start_time = start
activity.end_time = finish
activity.billable_status = status
activity.description = 'Install #1: lift kit'
activity
end
def test_activity_hours
assert_equal BigDecimal('1.5'), Writer.activity_hours(time_activity(1, hours: 1, minutes: 30))
timed = time_activity(2, start: DateTime.new(2026, 11, 18, 8), finish: DateTime.new(2026, 11, 18, 10, 30))
timed.break_minutes = 30
assert_equal BigDecimal('2'), Writer.activity_hours(timed)
assert_equal BigDecimal('0'), Writer.activity_hours(time_activity(3))
end
def test_import_options
@fake.query_results = {
'FROM TimeActivity' => [time_activity(71, hours: 2), time_activity(72, hours: 1, status: 'HasBeenBilled'),
time_activity(73, hours: 1, customer_id: 9999)],
'FROM Estimate' => [estimate(id: 598, status: 'Pending'), estimate(id: 599, status: 'Closed')]
}
Issue.find(2).update_column(:estimate_id, 598)
result = Writer.import_options(@customer, issue_ids: [3])
assert_equal ['71'], result[:time_activities].map { |t| t[:id] }
time = result[:time_activities].first
assert_equal ['1', '2', '120', '240.0', 'Tech One', false], time.values_at(:issue_id, :quantity, :rate, :amount, :employee, :taxable)
assert_equal ['598'], result[:estimates].map { |e| e[:id] }
open = result[:estimates].first
assert_equal '1', open[:issue_id]
assert_match '#2:', open[:issue]
assert_equal 2, open[:lines].size
assert_kind_of Hash, result[:issue_values]
end
def test_time_falls_back_to_recent_time
@fake.fail_query = /CustomerRef/
@fake.query_results = { 'TxnDate >=' => [time_activity(71, hours: 2)] }
assert_equal ['71'], Writer.open_time_activities(@customer).map { |t| t[:id] }
end
end
+202
View File
@@ -0,0 +1,202 @@
#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 PaymentWriterTest < ActiveSupport::TestCase
include QboFakeServiceHelper
fixtures :users
Writer = RedmineQboBilling::PaymentWriter
Form = RedmineQboBilling::PaymentForm
def setup
@customer = local_customer
@fake = install_fake_quickbooks
stub_local_syncs
Invoice.where(id: [601, 602, 603]).delete_all
@fake.query_results = { 'FROM Invoice' => [open_invoice(603, '1236', '2026-11-12', 50),
open_invoice(601, '1234', '2026-11-01', 100),
open_invoice(602, '1235', '2026-11-01', 200),
open_invoice(604, '1237', '2026-11-02', 0)] }
end
def open_invoice(id, number, date, balance)
qbo_invoice(id: id, doc_number: number, txn_date: Date.parse(date), total: 300, balance: balance)
end
def form(attrs = {})
Form.from_params({ 'customer_id' => '9101', 'txn_date' => '2026-11-20', 'payment_method_id' => '2',
'amount' => '250' }.merge(attrs))
end
def payment(id: 801, total: 250, applied: { '601' => 100, '602' => 150 }, others: [])
doc = Quickbooks::Model::Payment.new
doc.id = id.to_s
doc.sync_token = 2
doc.customer_ref = qbo_ref(9101, 'Jane Customer')
doc.txn_date = Date.new(2026, 11, 15)
doc.total = BigDecimal(total.to_s)
doc.payment_method_ref = qbo_ref(2, 'Check')
doc.payment_ref_number = '1042'
lines = applied.map do |invoice_id, amount|
Quickbooks::Model::Line.new.tap do |line|
line.amount = BigDecimal(amount.to_s)
line.invoice_id = invoice_id
end
end
others.each do |type|
lines << Quickbooks::Model::Line.new.tap do |line|
line.amount = 5
line.linked_transactions = [qbo_link(type, 9)]
end
end
doc.line_items = lines
@fake.add(doc)
end
def applied(doc)
doc.line_items.map { |l| [l.linked_transactions.first.txn_id, l.amount] }
end
def test_new_form
user = User.find(2)
user.stubs(:today).returns(Date.new(2026, 11, 20))
result = Writer.new_form(customer: @customer, user: user)
assert_equal ['9101', 'Jane Customer', '2026-11-20'], [result.customer_id.to_s, result.customer_name, result.txn_date]
end
def test_open_invoices_oldest_first
list = Writer.open_invoices(@customer)
assert_equal %w[1234 1235 1236], list.map { |i| i[:doc_number] }
assert_equal '100.0', list.first[:balance]
end
def test_allocate
invoices = [{ id: 'a', balance: '100' }, { id: 'b', balance: '0' }, { id: 'c', balance: '200' }]
result, left = Writer.allocate(BigDecimal('150'), invoices)
assert_equal [['a', BigDecimal('100')], ['c', BigDecimal('50')]], result.map { |i, take| [i[:id], take] }
assert_equal BigDecimal('0'), left
assert_equal BigDecimal('100'), Writer.allocate(400, invoices).last
end
def test_save_applies_oldest_first
saved = Writer.save(form)
assert_equal [['601', BigDecimal('100')], ['602', BigDecimal('150')]], applied(saved)
assert_equal BigDecimal('250'), saved.total
assert_equal '2', saved.payment_method_ref.value
assert_nil saved.payment_ref_number
assert_nil saved.private_note
end
def test_save_to_ticked_invoices_with_credit_left_over
saved = Writer.save(form('invoice_ids' => ['603'], 'amount' => '80', 'reference' => '1042', 'memo' => 'Deposit'))
assert_equal [['603', BigDecimal('50')]], applied(saved)
assert_equal '1042', saved.payment_ref_number
assert_equal 'Deposit', saved.private_note
end
def test_deposit_stays_unapplied
saved = Writer.save(form('deposit' => '1'))
assert_empty saved.line_items
end
def test_save_needs_a_customer_and_an_answer
assert_raises(Writer::Error) { Writer.save(form('customer_id' => '424242')) }
@fake.define_singleton_method(:create) { |_doc| nil }
error = assert_raises(Writer::Error) { Writer.save(form) }
assert_equal I18n.t(:error_payment_not_saved), error.message
end
def test_load_form
payment
result = Writer.load_form(801)
assert result.persisted?
assert_equal %w[601 602], result.invoice_ids
assert_equal '250.0', result.amount
assert_equal '0', result.deposit
assert_equal '1042', result.reference
assert_nil result.locked
assert_raises(Writer::Error) { Writer.load_form(999) }
end
def test_update_unchanged_keeps_amounts
payment
edited = Writer.load_form(801)
edited.memo = 'Edited'
saved = Writer.save(edited)
assert_equal [['601', BigDecimal('100')], ['602', BigDecimal('150')]], applied(saved)
assert_equal 'Edited', saved.private_note
end
def test_update_with_a_new_amount_spreads_it_again
payment(applied: { '602' => 200 }, total: 200)
edited = Writer.load_form(801)
edited.amount = '120'
edited.invoice_ids = []
saved = Writer.save(edited)
# What this payment paid on 602 counts as open again
assert_equal [['601', BigDecimal('100')], ['602', BigDecimal('20')]], applied(saved)
end
def test_update_refusals
payment
stale = Writer.load_form(801)
stale.sync_token = '1'
assert_raises(Writer::Conflict) { Writer.save(stale) }
payment(others: ['CreditMemo'])
error = assert_raises(Writer::Error) { Writer.save(Writer.load_form(801)) }
assert_equal I18n.t(:error_payment_not_editable, types: 'CreditMemo'), error.message
assert_raises(Writer::Error) { Writer.save(form.tap { |f| f.id = '999' }) }
end
def test_payment_methods
@fake.query_results = { 'PaymentMethod' => [
Quickbooks::Model::PaymentMethod.new(id: 2, name: 'Check', active: true),
Quickbooks::Model::PaymentMethod.new(id: 1, name: 'cash', active: true),
Quickbooks::Model::PaymentMethod.new(id: 3, name: 'Old card', active: false)
] }
assert_equal [%w[cash 1], %w[Check 2]], Writer.payment_methods
end
def test_payment_methods_survive_errors
QboConnectionService.stubs(:with_qbo_service).raises(StandardError, 'down')
assert_equal [], Writer.payment_methods
end
def test_customer_payments_and_totals
old = payment(id: 801)
old.txn_date = Date.new(2026, 10, 1)
old.unapplied_amount = 0
recent = payment(id: 802, total: 100, applied: {})
recent.unapplied_amount = 100
@fake.query_results = { 'FROM Payment' => [old, recent] }
list = Writer.customer_payments(@customer)
assert_equal %w[802 801], list.map(&:id)
assert_equal({ received: BigDecimal('350'), unapplied: BigDecimal('100') }, Writer.payment_totals(list))
end
def test_payment_method_name
doc = payment
assert_equal 'Check', Writer.payment_method_name(doc)
doc.payment_method_ref = qbo_ref(7)
Writer.stubs(:payment_methods).returns([%w[Visa 7]])
assert_equal 'Visa', Writer.payment_method_name(doc)
doc.payment_method_ref = nil
assert_equal '', Writer.payment_method_name(doc)
end
def test_pdf
@fake.pdf_body = '%PDF-1.4'
assert_equal '%PDF-1.4', Writer.pdf(801)
end
end
+140
View File
@@ -0,0 +1,140 @@
#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__)
# SyncServiceBase and the entity sync services: QuickBooks records cached locally
class SyncServicesTest < ActiveSupport::TestCase
include QboFakeServiceHelper
fixtures :projects, :users, :issues, :trackers, :issue_statuses, :enumerations
def setup
Customer.where(id: [9101, 9102]).delete_all
Estimate.where(id: 598).delete_all
Invoice.where(id: 601).delete_all
Payment.where(id: 801).delete_all
Employee.where(id: 31).delete_all
Account.where(id: 84).delete_all
QboSyncStatus.delete_all
@fake = install_fake_quickbooks
end
def remote_customer(id, name, active: true, phone: nil)
customer = Quickbooks::Model::Customer.new(id: id.to_s, display_name: name, active: active)
if phone
customer.primary_phone = Quickbooks::Model::TelephoneNumber.new
customer.primary_phone.free_form_number = phone
end
customer
end
def test_customer_sync_by_id
@fake.add(remote_customer(9101, 'jane customer', phone: '(401) 555-0101'))
CustomerSyncService.new.sync_by_id(9101)
customer = Customer.find(9101)
assert_equal ['Jane Customer', '4015550101'], [customer.name, customer.phone_number]
end
def test_inactive_customer_is_removed
local_customer(9101)
@fake.add(remote_customer(9101, 'Jane Customer', active: false))
CustomerSyncService.new.sync_by_id(9101)
assert_not Customer.exists?(9101)
end
def test_full_sync_in_pages_reports_progress
QboSyncStatus.running('Customer')
@fake.query_results = { 'Customer' => [remote_customer(9101, 'Jane'), remote_customer(9102, 'Bob')] }
CustomerSyncService.new.sync(full_sync: true)
assert_equal %w[Bob Jane], Customer.where(id: [9101, 9102]).order(:name).pluck(:name)
assert_equal 'SELECT * FROM Customer ORDER BY Id', @fake.queries.last
assert_equal 2, QboSyncStatus.find_by(entity: 'Customer').processed
end
def test_incremental_sync_asks_for_changes_since_the_last_update
local_customer(9101)
CustomerSyncService.new.sync
assert_match(/WHERE MetaData.LastUpdatedTime > '\d{4}-\d\d-\d\dT/, @fake.queries.last)
end
def test_estimate_sync
local_customer(9101)
remote = qbo_estimate(doc_number: '1068', status: 'Pending', total: '368.40',
lines: [qbo_sales_line(1, 10, 'Labor', 2, 120)])
remote.txn_tax_detail = Quickbooks::Model::TransactionTaxDetail.new(total_tax: BigDecimal('8.40'))
@fake.add(remote)
Setting.stubs(:plugin_redmine_qbo).returns({})
EstimateSyncService.new.sync_by_id(598)
estimate = Estimate.find(598)
assert_equal ['1068', 'Pending', BigDecimal('368.40'), 2.0, BigDecimal('8.40'), 9101],
[estimate.doc_number, estimate.txn_status, estimate.total_amount, estimate.hours, estimate.tax_amount, estimate.customer_id]
end
def test_estimate_sync_by_doc_number
local_customer(9101)
@fake.add(qbo_estimate(doc_number: '1068'))
EstimateSyncService.new.sync_by_doc_number('1068')
assert Estimate.exists?(598)
end
def test_invoice_sync_attaches_issues
local_customer(9101)
Issue.find(1).update_columns(customer_id: 9101)
remote = qbo_invoice(doc_number: '1234', total: 100, balance: 100,
lines: [qbo_sales_line(1, 10, 'Labor', 1, 100, description: 'Install #1: lift')])
@fake.add(remote)
InvoiceSyncService.new.sync_by_id(601)
invoice = Invoice.find(601)
assert_equal ['1234', BigDecimal('100'), nil], [invoice.doc_number, invoice.balance, invoice.paid_on]
assert_includes Issue.find(1).invoices, invoice
end
def test_unchanged_record_is_not_saved_again
local_customer(9101, 'Jane Customer')
@fake.add(remote_customer(9101, 'Jane Customer'))
Customer.any_instance.expects(:save!).never
CustomerSyncService.new.sync_by_id(9101)
end
def test_payment_waits_for_its_customer
@fake.add(Quickbooks::Model::Payment.new(id: '801', total: BigDecimal('50'), unapplied_amount: BigDecimal('0'),
txn_date: Date.new(2026, 11, 2), customer_ref: qbo_ref(424_242)))
PaymentSyncService.new.sync_by_id(801)
payment = Payment.find(801)
assert_nil payment.customer_id
assert_equal BigDecimal('50'), payment.total_amount
end
def test_employee_and_account_sync
@fake.add(Quickbooks::Model::Employee.new(id: '31', display_name: 'Tech One', active: true))
EmployeeSyncService.new.sync_by_id(31)
assert_equal 'Tech One', Employee.find(31).name
@fake.add(Quickbooks::Model::Account.new(id: '84', name: 'Sales', classification: 'Revenue', active: true))
AccountSyncService.new.sync_by_id(84)
assert_equal ['Sales', 'Revenue', true], Account.find(84).values_at(:name, :classification, :active)
end
def test_a_bad_record_is_logged_not_raised
@fake.add(remote_customer(9101, ''))
assert_nothing_raised { CustomerSyncService.new.sync_by_id(9101) }
assert_not Customer.exists?(9101)
end
def test_a_record_inserted_meanwhile_is_updated
local_customer(9101, 'Old Name')
@fake.add(remote_customer(9101, 'New Name'))
service = CustomerSyncService.new
calls = 0
Customer.stubs(:find_or_initialize_by).with { calls += 1 }.returns(Customer.new(id: 9101), Customer.find(9101))
Customer.any_instance.stubs(:save!).raises(ActiveRecord::RecordNotUnique).then.returns(true)
service.sync_by_id(9101)
assert_equal 2, calls
end
end