mirror of
https://github.com/rickbarrette/redmine_qbo.git
synced 2026-11-20 18:40:37 -05:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
761722bbb1 | ||
|
|
6ea5610b51 | ||
|
|
b829593bc2 | ||
|
|
17f24f9641 | ||
|
|
da82f7e12c | ||
|
|
9ed3ef23fb | ||
|
|
00400c21dc | ||
|
|
48f92f241f | ||
|
|
22af08cee7 | ||
|
|
7c87f4f9c5 | ||
|
|
cf5328cb21 | ||
|
|
c851929e02 | ||
|
|
56859d1794 | ||
|
|
671afa2436 | ||
|
|
30c1f5181e | ||
|
|
0d143e6eb1 | ||
|
|
92f9eb1bc7 | ||
|
|
40eb6205c4 | ||
|
|
0c5bac855e | ||
|
|
663639b8fd | ||
|
|
ec4e5f681d | ||
|
|
a72b0fa73b | ||
|
|
5b6c1ed2c2 | ||
|
|
4f6f81c87a | ||
|
|
9fa199aa98 |
No files matched your search
@@ -75,10 +75,22 @@ The plugin provides basic Customer management:
|
||||
* Search Customers by **name or phone number**: the best matches come first (click a column to sort them instead), and a single match opens that Customer
|
||||
|
||||
* View and edit Customer information
|
||||
|
||||
* On the customer page, ticking an estimate (or a redmine_qbo_vehicles vehicle) adds it to the **New issue** link and to redmine_qbo_calendar's **Add appointment** link, one of each at a time
|
||||
|
||||
|
||||
Customers are synchronized with QuickBooks.
|
||||
|
||||
### Sharing an issue with the customer
|
||||
|
||||
**Share** on an issue (permission **Share issues with customers**) opens a link the customer can open without logging in: the issue with its history, attachments, estimate and invoices. A link lasts a month; sharing the issue again while it's valid gives the same link.
|
||||
|
||||
Expired links, and links whose issue was deleted, are deleted whenever a new link is made. To delete them now (or on a schedule):
|
||||
|
||||
```
|
||||
bundle exec rake redmine_qbo:purge_customer_tokens RAILS_ENV=production
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Webhook Support
|
||||
@@ -97,7 +109,7 @@ Customer records are automatically updated in the local database when changes oc
|
||||
|
||||
### Estimates, Invoices and Payments
|
||||
|
||||
Estimates and invoices keep their number, date, customer, total and **man-hours** (the quantities of the labor products/services, including lines inside bundles). Payments keep their customer, date, amount and unapplied amount. These cached figures feed the business report.
|
||||
Estimates and invoices keep their number, date, customer, total, sales tax and **man-hours** (the quantities of the labor products/services, including lines inside bundles). Payments keep their customer, date, amount and unapplied amount. These cached figures feed the business report.
|
||||
|
||||
---
|
||||
|
||||
@@ -107,7 +119,7 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
|
||||
* **Edit** any estimate from the Edit link next to it on the customer page or the issue page.
|
||||
* **Keyboard entry**: in a line's product box, Tab picks the product the text points to (an exact name, the only match, or the only name starting with it, e.g. "lab" → Labor) and fills the line. Tabbing into the description, quantity or rate selects it, so typing replaces it. The quantity, rate and amount boxes take simple math (e.g. `33*1.3`, `(120+15)/2`; `+ - * /`, `x` for times, parentheses), worked out when you leave the box; math in the rate or amount is rounded to the nearest penny, and an amount sets the rate from the quantity. Typing `sub`, `subtotal` or `=` in a product box, then Tab or Enter, adds a subtotal there (an empty line becomes the subtotal; a line with a description keeps it and gets the subtotal after it) and moves on to the next line.
|
||||
* **Duplicate** an estimate to start a similar one: same customer, lines, subtotals, custom fields and messages, dated today, with the current user as sales person.
|
||||
* **Read-only once linked to an issue**: an estimate that an issue is linked to can be viewed, emailed and duplicated, but not changed, so the work doesn't drift from what was quoted. The list shows a View link for these instead of Edit.
|
||||
* **Read-only once linked to an issue**: an estimate that an issue is linked to can be viewed, emailed and duplicated, but not changed by accident, so the work doesn't drift from what was quoted. The list shows a View link for these instead of Edit. Users with **Edit estimates linked to issues** get **Unlock to edit** on the estimate's page (e.g. a customer asks for changes to the estimate on a diagnostic work order): after a confirmation it opens for editing, and the issues stay linked when it's saved.
|
||||
* **Read-only once billed**: an estimate that's Converted or Closed in QuickBooks, or linked to an invoice, can't be changed here either (including redmine_qbo_lineitems' estimates once they're invoiced). Its page lists the invoices it's on; it can still be viewed, emailed and duplicated, and it shows View instead of Edit in lists.
|
||||
* **Create issues** from an estimate's labor lines (moved here from redmine_qbo_calendar): each line with one of the **labor products/services** (e.g. Labor) becomes an issue with the line's description as subject and its quantity as estimated hours. Pick the project, trackers, templates and shared custom fields first. Lines already turned into issues can't be created twice, and issues from the same estimate are related to each other. Creating issues marks a pending estimate **Accepted** in QuickBooks (dated today), since the work is going ahead; estimates that are already accepted, closed, converted or rejected keep their status. Opened from an appointment, the issues get the appointment's dates, technician and vehicle.
|
||||
* **Email** the estimate with QuickBooks' own estimate email, with **Save and send** or the Email link.
|
||||
@@ -128,7 +140,7 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
|
||||
* Time lines are linked to their time activities, so QuickBooks marks the time as billed. Estimates the invoice was made from, or imported into it, are linked and closed when it's saved.
|
||||
* **Custom fields from the work orders**: the issues behind an invoice are the ones its time lines and lineitems estimates name. Plugins can fill custom fields from them when they're imported, and block a save (e.g. redmine_qbo_vehicles fills the VIN and mileage and allows one vehicle per invoice). On its own, redmine_qbo leaves the boxes as typed.
|
||||
* **Sales person**: an invoice credits the sales person on the estimate it was made from (the first linked estimate that names one); if none does, the user who writes the invoice.
|
||||
* Invoices show their status, worked out from the balance and due date like QuickBooks' invoice list: **Paid**, **Partially paid**, **Overdue**, **Open** or **Voided** (a zero total), on the customer page's invoice list and the invoice page.
|
||||
* Invoices show their status, worked out from the balance and due date like QuickBooks' invoice list: **Paid**, **Partially paid**, **Overdue**, **Open** or **Voided** (a zero total), on the customer page's invoice list and the invoice page. A paid invoice shows when it was paid in full (the later of its date and the last payment or credit memo applied to it): on the customer page's list, **Paid** when it was paid the day it was written, or **Paid +3d** when it was paid in full 3 days after its date, with the date when hovering over it; on the invoice page, the date (e.g. **Paid 11/03/2026**).
|
||||
* Invoices with a payment applied open read-only. The due date is left to QuickBooks (from the customer's terms) unless one is picked. The "default message shown on invoices" fills in the message.
|
||||
|
||||
### Payments
|
||||
@@ -140,17 +152,42 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
|
||||
* The saved payment's page shows where it was applied and has **Print**, QuickBooks' payment PDF.
|
||||
* **Payments** on the customer page lists all of the customer's payments from QuickBooks, newest first: date, method, reference no., the invoices each was applied to (or Deposit), memo, amount and what's still unapplied, with totals. Each date opens the payment's page and **Print** opens its PDF.
|
||||
|
||||
### Refunds
|
||||
|
||||
Refunds for canceled orders and returned parts, following SOP-OPS-014, so they don't have to be made in QuickBooks:
|
||||
|
||||
* **Refund** on the customer page. Pick the canceled order's estimate: its parts (the lines that aren't labor, including those in bundles, before tax) fill in the amount the restocking fee is worked out on, and can be changed (e.g. only some parts are returned). Labor carries no fee.
|
||||
* Choose how the money goes back: **Company check** (with its number) or **Card** (a partial refund on the terminal). There are no cash refunds. The page shows the customer's credit, the fee and the exact amount to refund.
|
||||
* **Refund** then, in QuickBooks:
|
||||
1. makes the restocking fee invoice, its line showing the math ("Restocking fee: 30% × $307.99 parts on E1068 = $92.40"), and pays it from the customer's credit, oldest first (unless QuickBooks already applied the credit to it on its own);
|
||||
2. records the rest of the credit as a refund with the category **Accounts Receivable**, from the bank account in the settings, described "Refund for deposit on E1068": a **Check** for a check, an **Expense** for a card refund;
|
||||
3. applies the customer's remaining credit to that check or expense, so the deposit, the fee invoice and the refund reconcile, and reads back the customer's balance (it should be $0.00).
|
||||
* As ticked on the page, it also marks the estimate **Rejected**, sets the order's work orders to the canceled status with the reason as a note, and emails the customer a summary (through redmine_qbo_reminders' mail settings when that plugin is set up, otherwise Redmine's).
|
||||
* Each refund has its own page, listed on the customer page: what was refunded and how, with the fee invoice (opened in Redmine), a **PDF** of the refund (QuickBooks has no PDF of a check or an expense), the fee invoice's PDF, and **Email the customer** to send the summary again. If a QuickBooks step fails, the refund stops there and its page says which step and what was already done, to finish in QuickBooks.
|
||||
* It refunds all of the customer's remaining credit held as unapplied payments. Credit held as credit memos isn't refunded here.
|
||||
|
||||
#### Refunding a paid invoice
|
||||
|
||||
Completed work that's billed and paid in full is refunded from its invoice, with a QuickBooks **Refund Receipt**, the way QuickBooks refunds a paid sale:
|
||||
|
||||
* **Refund** on a paid-in-full invoice (or pick it under **Paid invoice** on the customer's Refund page). The invoice's lines are listed (bundles opened up into their lines), each marked parts or labor, with what earlier refunds already took of it. Tick the lines to refund and change the **quantity** (e.g. 2 of 4 parts returned) or the **amount** (a partial refund, e.g. some of the labor). A line can't be refunded, over one or more refunds, for more than it was billed.
|
||||
* **Restocking fee** is optional: when ticked, it's the rate in the settings of the *parts* refunded. Labor carries no fee, so a refund of labor alone has none. Leave it off when the parts aren't coming back.
|
||||
* The page shows the lines, the invoice discount's share (if it had one), the estimated sales tax refunded, the fee and the refund. Choose **Company check** (with its number) or **Card**.
|
||||
* **Refund** records the refund receipt in QuickBooks: the refunded lines with their products/services and tax codes (so the income and sales tax come back off the books; QuickBooks works out the tax), the discount's share, the fee as a negative line with the restocking fee product/service, paid out of the refund check or card refund account in the settings, with the payment method (a QuickBooks payment method named Check, or one with Card/Visa/Mastercard/Amex/Discover in its name) and the check number. The invoice stays as it is, paid.
|
||||
* As ticked on the page, it also notes the refund on the invoice's work orders (their status is left alone) and emails the customer a summary. The refund's page, PDF and email list the lines refunded, and show the refund receipt's exact total: refund exactly that.
|
||||
|
||||
### Business report
|
||||
|
||||
**Business report** in the top menu compares, for a period (this or last week, month, quarter or year, or custom dates; weeks start on the day set in Redmine's *Start calendars on* setting, Monday when it follows the language):
|
||||
|
||||
* **Sales**: estimates written, invoices written and payments received (totals and counts), invoiced vs. estimated, collected vs. invoiced, and what's still owed on those invoices.
|
||||
* **Sales**: estimates written, invoices written, invoices paid in full (on the day each was paid in full) and payments received (totals and counts), invoiced vs. estimated, collected vs. invoiced, and what's still owed on those invoices. Estimates and invoices are without sales tax (QuickBooks' tax on each is cached with it); payments are as received, so collected vs. invoiced compares them with the invoices' totals with tax.
|
||||
* **Sales tax**: **tax invoiced**, the sales tax on invoices dated in the period, paid or not (accrual), and **tax collected**, the sales tax on invoices paid in full in the period, counted on the day each was paid in full (cash), each with how many invoices carried tax, a line chart and a month-by-month table. A partly paid invoice's tax counts as collected once it's paid in full. Only invoices are counted: sales receipts, refund receipts and credit memos aren't kept in Redmine, so file sales tax from QuickBooks' *Sales Tax Liability* report.
|
||||
* **Hours**: estimated hours on estimates, issues' estimated time, invoiced hours on invoices and time spent, with spent vs. estimated, and the **cost performance index** (CPI = invoiced hours ÷ spent hours): green at 1.00 or more, yellow below 1, red below 0.80. Each month shows its CPI too.
|
||||
* **Charts**: above each set of bars, a line chart of the same figures in the same colors (Chart.js 4.5.1, MIT licensed, bundled with the plugin in assets/javascripts so it doesn't clash with other plugins' copies such as redmine_indicator's Chart.js 2), with a point per day for a week, per week for up to about three months, and per month beyond. Hovering a point shows its figures. **Compare with last year** adds last year's lines, dashed and faded, without reloading: days and weeks go back 52 weeks so weekdays line up, months go back to the same month. Clicking a figure in the legend hides it (and its last-year line); clicking *last year* stops comparing. Today's line stops at today.
|
||||
* **By month**: every figure month by month, with totals.
|
||||
* **By month**: every sales and hours figure month by month, with totals (the sales tax has its own table).
|
||||
* **Projects**: pick one or more open projects (Ctrl/Cmd-click; closed and archived projects aren't listed) to count only their issues' estimated time and spent time, in the totals, charts and months; none picked counts every project. Estimates, invoices and payments have no project in QuickBooks, so they always cover the whole business (as do the CPI's invoiced hours). **Remember these projects** saves the choice in your Redmine preferences, and the report opens with it until you save another (saving none goes back to every project).
|
||||
|
||||
Estimates, invoices and payments count by their QuickBooks date. Issues' estimated time counts issues created in the period, leaving out parents so subtasks aren't counted twice. Spent time counts time logged in the period. While estimates, invoices or payments are syncing, the report says so (with how many have been read) and refreshes every 30 seconds; the settings page's Synchronization table shows the same per type. Estimates and invoices synced before these figures were added have no total or hours until a full sync (the report says how many); run one again after changing the labor products/services.
|
||||
Estimates, invoices and payments count by their QuickBooks date; invoices paid in full and tax collected by the day each invoice was paid in full. Issues' estimated time counts issues created in the period, leaving out parents so subtasks aren't counted twice. Spent time counts time logged in the period. While estimates, invoices or payments are syncing, the report says so (with how many have been read) and refreshes every 30 seconds; the settings page's Synchronization table shows the same per type. Estimates and invoices synced before these figures were added have no total, hours or sales tax, and paid invoices no paid-in-full day, until a full sync (the report says how many); run one again after changing the labor products/services.
|
||||
|
||||
### QuickBooks custom fields
|
||||
|
||||
@@ -185,6 +222,7 @@ Administration → Items lists the QuickBooks product/service list (synced from
|
||||
1. Navigate to Administration -> Roles and permissions.
|
||||
2. Assign these global permissions as needed:
|
||||
* **Write estimates**: create and edit estimates
|
||||
* **Edit estimates linked to issues**: unlock an estimate an issue is linked to and change it (on top of Write estimates)
|
||||
* **Email estimates**: email estimates to customers (Save and send, and the Email link)
|
||||
* **Create issues from estimates**: the Create issues page (was redmine_qbo_calendar's "Create issues from appointment estimates")
|
||||
* **View payments**: a customer's Payments list, the payment page and its PDF
|
||||
@@ -192,11 +230,17 @@ Administration → Items lists the QuickBooks product/service list (synced from
|
||||
* **View business reports**: the Business report
|
||||
* **Write invoices**: create and edit invoices, and import time and estimates into them
|
||||
* **Email invoices**: email invoices to customers
|
||||
* **Edit partially paid invoices** / **Edit paid invoices**: unlock an invoice with a payment applied and change it, never below what's been paid (on top of Write invoices)
|
||||
* **Issue refunds**: the Refund page (customer credit) and refunds of paid invoices, refunds and their PDFs
|
||||
* **Share issues with customers**: the Share link on issues (see Sharing an issue with the customer)
|
||||
|
||||
Estimate and invoice PDFs follow these permissions: any estimate with **View customers** or **Write estimates**; any invoice with **View customers**, **Write invoices**, **View payments**, **Receive payments** or **Issue refunds**. Other users open only the estimates and invoices attached to issues they can see (the issue page links to them), and a shared link opens only that issue's.
|
||||
|
||||
2. Settings (Administration -> Plugins -> Configure)
|
||||
* **Estimates expire after (days)**: new estimates get an expiration date this many days after the estimate date (e.g. 30). Leave blank for none.
|
||||
* **Labor products/services** (e.g. Labor): one list used three ways. An estimate's lines with them can become issues (their quantities are also the estimate's labor hours, which an appointment's hours can't be less than); an invoice's lines with them are offered under Replace these lines when time is imported; and their quantities are the hours on estimates and invoices in the business report. While none are chosen, products/services named Labor are used.
|
||||
* **Issues from estimates**: the default project and the default tracker.
|
||||
* **Refunds**: the restocking fee (SOP-OPS-014: 30%) and the product/service on its invoice or refund receipt line (e.g. a "Restocking Fee" service, which sets the income account), the bank accounts refund checks and card refunds come out of (blank: the first bank account), and the status canceled work orders are set to (blank: a closed status named Canceled).
|
||||
* Item and account counts, the default income account and their syncs are under Synchronization.
|
||||
|
||||
3. Writing an estimate
|
||||
@@ -233,7 +277,7 @@ Hook|:qbo_billing_issues_created, { estimate:, issues:, params: } | Called after
|
||||
Hook|:qbo_billing_field_defaults, { customer:, issues: } | Return `{ field_id => value }` for a document's work orders: used when an invoice is made from an estimate, for the fields it leaves blank. New estimates and invoices start blank (redmine_qbo_vehicles: the work orders' VIN and highest mileage)
|
||||
Hook|:qbo_billing_field_options, { customer: } | Return `{ field_id => [{ value:, label: }, ...] }` to suggest in the editor's custom field boxes for a customer (redmine_qbo_vehicles: the customer's vehicles for the VIN box)
|
||||
View|:view_qbo_estimate_form_bottom, { form:, document: } | Add your plugin's script to the estimate/invoice editor. It can use `window.qboEditor` (`field(id)`, `fieldNamed(/name/)`, `setFieldOptions(id, options)`) and listen for `qbo:customer-changed` and `qbo:imported` on the form (redmine_qbo_vehicles fills the VIN and mileage)
|
||||
View|checkboxes with `data-new-issue-param="issue[field]"` on the customer page | Ticking one adds `issue[field]=value` to the New issue link, one per field (redmine_qbo's estimates, redmine_qbo_vehicles' vehicles)
|
||||
View|checkboxes with `data-new-issue-param="issue[field]"` and `data-appointment-param="field"` on the customer page | Ticking one adds `issue[field]=value` to the New issue link and `field=value` to redmine_qbo_calendar's Add appointment link (`#appointment_link`), one per field (redmine_qbo's estimates: `estimate_id`, redmine_qbo_vehicles' vehicles: `vehicle_id`)
|
||||
View Hook|:view_qbo_estimate_contextual, { estimate_id:, customer_id:, custom_fields:, doc_number: } | Adds links to an estimate page's action area (e.g. redmine_qbo_calendar's Add appointment); `custom_fields` is `{ field_id => value }`
|
||||
View Hook|:view_qbo_invoice_contextual, { invoice_id:, customer_id:, doc_number: } | Adds links to an invoice page's action area (e.g. redmine_qbo_labels' Print label)
|
||||
|
||||
@@ -359,6 +403,16 @@ After the initial synchronization, the plugin receives updates through **Intuit
|
||||
|
||||
---
|
||||
|
||||
# Running the tests
|
||||
|
||||
The tests run with Redmine's own test setup on MySQL (the customer search index needs it), with QuickBooks replaced by a fake (`test/qbo_fake_service.rb`), so they never call QuickBooks:
|
||||
|
||||
```
|
||||
bundle exec rake redmine:plugins:test NAME=redmine_qbo RAILS_ENV=test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Troubleshooting
|
||||
|
||||
### Time Activities Not Created
|
||||
|
||||
@@ -33,36 +33,6 @@ class CustomersController < ApplicationController
|
||||
before_action :require_admin, only: :sync
|
||||
skip_before_action :verify_authenticity_token, :check_if_login_required, only: [:view]
|
||||
|
||||
def address_to_s(address)
|
||||
return if address.nil?
|
||||
|
||||
lines = [
|
||||
address.line1,
|
||||
address.line2,
|
||||
address.line3,
|
||||
address.line4,
|
||||
address.line5
|
||||
].compact_blank
|
||||
|
||||
city_line = [
|
||||
address.city,
|
||||
address.country_sub_division_code,
|
||||
address.postal_code
|
||||
].compact_blank.join(" ")
|
||||
|
||||
lines << city_line unless city_line.blank?
|
||||
|
||||
lines.join("\n")
|
||||
end
|
||||
|
||||
def add_customer
|
||||
global_check_permission(:add_customers)
|
||||
end
|
||||
|
||||
def allowed_params
|
||||
params.require(:customer).permit(:name, :email, :primary_phone, :mobile_phone, :phone_number, :notes)
|
||||
end
|
||||
|
||||
# Used for autocomplete forms. Fuzzy matching (nicknames, typos, word order, phone digits) helps
|
||||
# staff spot an existing customer before creating a duplicate. See CustomerSearchService.
|
||||
def autocomplete
|
||||
@@ -77,27 +47,16 @@ class CustomersController < ApplicationController
|
||||
def create
|
||||
@customer = Customer.new(allowed_params)
|
||||
|
||||
respond_to do |format|
|
||||
if @customer.save
|
||||
log "Customer ##{@customer.id} created successfully."
|
||||
format.html { redirect_to @customer, notice: l(:notice_successful_create) }
|
||||
format.json { render json: { id: @customer.id, name: @customer.name }, status: :created }
|
||||
else
|
||||
format.html { render :new }
|
||||
format.json { render json: { errors: @customer.errors.full_messages }, status: :unprocessable_entity }
|
||||
end
|
||||
if @customer.save
|
||||
log "Customer ##{@customer.id} created successfully."
|
||||
redirect_to @customer, notice: l(:notice_successful_create)
|
||||
else
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
rescue => e
|
||||
log "Failed to create customer: #{e.message}"
|
||||
respond_to do |format|
|
||||
format.html {
|
||||
flash[:error] = e.message
|
||||
redirect_to new_customer_path
|
||||
}
|
||||
format.json {
|
||||
render json: { errors: [e.message] }, status: :internal_server_error
|
||||
}
|
||||
end
|
||||
flash[:error] = e.message
|
||||
redirect_to new_customer_path
|
||||
end
|
||||
|
||||
def edit
|
||||
@@ -109,14 +68,6 @@ class CustomersController < ApplicationController
|
||||
render_404
|
||||
end
|
||||
|
||||
def filter_estimates_by_customer
|
||||
@filtered_estimates = Estimate.all.where(customer_id: params[:selected_customer])
|
||||
end
|
||||
|
||||
def filter_invoices_by_customer
|
||||
@filtered_invoices = Invoice.all.where(customer_id: params[:selected_customer])
|
||||
end
|
||||
|
||||
# Most matches a search lists (best first)
|
||||
SEARCH_LIMIT = 200
|
||||
|
||||
@@ -146,29 +97,6 @@ class CustomersController < ApplicationController
|
||||
@issue_counts = Issue.where(customer_id: @customers.map(&:id)).group(:customer_id).count
|
||||
end
|
||||
|
||||
def load_issue_data
|
||||
@journals = @issue.journals.preload(:details).preload(user: :email_address).reorder(:created_on, :id).to_a
|
||||
|
||||
@journals.each_with_index { |j, i| j.indice = i + 1 }
|
||||
@journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
|
||||
Journal.preload_journals_details_custom_fields(@journals)
|
||||
@journals.select! { |journal| journal.notes? || journal.visible_details.any? }
|
||||
@journals.reverse! if User.current.wants_comments_in_reverse_order?
|
||||
|
||||
@changesets = @issue.changesets.visible.preload(:repository, :user).to_a
|
||||
@changesets.reverse! if User.current.wants_comments_in_reverse_order?
|
||||
|
||||
@relations = @issue.relations.select { |r| r.other_issue(@issue)&.visible? }
|
||||
@allowed_statuses = @issue.new_statuses_allowed_to(User.current)
|
||||
@priorities = IssuePriority.active
|
||||
@time_entry = TimeEntry.new(issue: @issue, project: @issue.project)
|
||||
@relation = IssueRelation.new
|
||||
end
|
||||
|
||||
def log(msg)
|
||||
Rails.logger.info "[CustomersController] #{msg}"
|
||||
end
|
||||
|
||||
def new
|
||||
@customer = Customer.new
|
||||
|
||||
@@ -253,8 +181,41 @@ class CustomersController < ApplicationController
|
||||
render_403
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def add_customer
|
||||
global_check_permission(:add_customers)
|
||||
end
|
||||
|
||||
def allowed_params
|
||||
params.require(:customer).permit(:name, :email, :primary_phone, :mobile_phone, :phone_number, :notes)
|
||||
end
|
||||
|
||||
def load_issue_data
|
||||
@journals = @issue.journals.preload(:details).preload(user: :email_address).reorder(:created_on, :id).to_a
|
||||
|
||||
@journals.each_with_index { |j, i| j.indice = i + 1 }
|
||||
@journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
|
||||
Journal.preload_journals_details_custom_fields(@journals)
|
||||
@journals.select! { |journal| journal.notes? || journal.visible_details.any? }
|
||||
@journals.reverse! if User.current.wants_comments_in_reverse_order?
|
||||
|
||||
@changesets = @issue.changesets.visible.preload(:repository, :user).to_a
|
||||
@changesets.reverse! if User.current.wants_comments_in_reverse_order?
|
||||
|
||||
@relations = @issue.relations.select { |r| r.other_issue(@issue)&.visible? }
|
||||
@allowed_statuses = @issue.new_statuses_allowed_to(User.current)
|
||||
@priorities = IssuePriority.active
|
||||
@time_entry = TimeEntry.new(issue: @issue, project: @issue.project)
|
||||
@relation = IssueRelation.new
|
||||
end
|
||||
|
||||
def log(msg)
|
||||
Rails.logger.info "[CustomersController] #{msg}"
|
||||
end
|
||||
|
||||
def view_customer
|
||||
global_check_permission(:view_customers)
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
@@ -10,7 +10,8 @@
|
||||
class EstimatesController < ApplicationController
|
||||
include AuthHelper
|
||||
|
||||
# PDFs: logged-in users, or a customer with a share link (limited to their issue's estimate).
|
||||
# PDFs: logged-in users with View customers or Write estimates, other logged-in users for the estimates on
|
||||
# issues they can see, and share-link customers for their issue's estimate.
|
||||
# Redmine's own login check is replaced by require_login_or_customer_token for these actions.
|
||||
skip_before_action :check_if_login_required, only: [:show, :doc]
|
||||
before_action :require_login_or_customer_token, only: [:show, :doc]
|
||||
@@ -42,6 +43,7 @@ class EstimatesController < ApplicationController
|
||||
|
||||
# Share-link customers may only open the estimate attached to their issue (checked before any sync)
|
||||
return load_customer_estimate if customer_token_only?
|
||||
return load_issue_estimate unless RedmineQboBilling.estimate_viewer?
|
||||
|
||||
@estimate = find_estimate || sync_and_find_estimate
|
||||
|
||||
@@ -65,6 +67,15 @@ class EstimatesController < ApplicationController
|
||||
@estimate = estimate
|
||||
end
|
||||
|
||||
# For logged-in users without a billing permission: only an estimate attached to an issue they can see,
|
||||
# which is always cached locally (no sync from QuickBooks)
|
||||
def load_issue_estimate
|
||||
estimate = find_estimate
|
||||
return render_403 unless estimate && estimate_pdf_allowed?(estimate)
|
||||
|
||||
@estimate = estimate
|
||||
end
|
||||
|
||||
# Attempts to find the estimate locally by ID or doc number.
|
||||
def find_estimate
|
||||
return Estimate.find_by(doc_number: params[:search]) if params[:search].present?
|
||||
|
||||
@@ -10,11 +10,13 @@
|
||||
class InvoicesController < ApplicationController
|
||||
include AuthHelper
|
||||
|
||||
# PDFs: logged-in users, or a customer with a share link (limited to their issue's invoices).
|
||||
# PDFs: logged-in users with a billing permission (RedmineQboBilling.invoice_viewer?), other logged-in users for
|
||||
# the invoices on issues they can see, and share-link customers for their issue's invoices.
|
||||
# Redmine's own login check is replaced by require_login_or_customer_token for this action.
|
||||
skip_before_action :check_if_login_required, only: :show
|
||||
before_action :require_login_or_customer_token, only: :show
|
||||
before_action :authorize_customer_invoices, only: :show
|
||||
before_action :authorize_user_invoices, only: :show
|
||||
|
||||
# Syncing is admin-only
|
||||
before_action :require_admin, only: :sync
|
||||
@@ -51,6 +53,13 @@ class InvoicesController < ApplicationController
|
||||
render_403 if invoice_ids.empty? || (invoice_ids - allowed).any?
|
||||
end
|
||||
|
||||
# Logged-in users: a billing permission, or invoices attached to issues they can see
|
||||
def authorize_user_invoices
|
||||
return true unless User.current.logged?
|
||||
|
||||
render_403 unless invoice_pdfs_allowed?(invoice_ids)
|
||||
end
|
||||
|
||||
# Logs messages with a consistent prefix for easier debugging.
|
||||
def log(msg)
|
||||
Rails.logger.info "[InvoiceController] #{msg}"
|
||||
|
||||
@@ -59,9 +59,11 @@ class QboEstimatesController < ApplicationController
|
||||
show_error(e, :new)
|
||||
end
|
||||
|
||||
# ?unlock=1 opens an estimate linked to an issue for editing anyway (after the editor's confirmation)
|
||||
def edit
|
||||
@form = RedmineQboBilling::EstimateWriter.load(params[:id])
|
||||
@linked_issues = RedmineQboBilling::EstimateWriter.linked_issues(@form.id).visible.to_a
|
||||
unlock_form if unlock?
|
||||
rescue *QBO_ERRORS => e
|
||||
flash[:error] = qbo_message(e)
|
||||
redirect_back_or_default home_path
|
||||
@@ -70,9 +72,10 @@ class QboEstimatesController < ApplicationController
|
||||
def update
|
||||
@form = RedmineQboBilling::EstimateForm.from_params(estimate_params, id: params[:id])
|
||||
@form.sales_person = params.dig(:estimate, :sales_person).to_s
|
||||
unlock_form if unlock?
|
||||
return show_invalid(:edit) unless @form.valid?
|
||||
|
||||
saved = RedmineQboBilling::EstimateWriter.save(@form, user: User.current)
|
||||
saved = RedmineQboBilling::EstimateWriter.save(@form, user: User.current, unlock: unlock?)
|
||||
finish_save(saved, l(:notice_estimate_saved_in_quickbooks, number: saved.doc_number))
|
||||
rescue RedmineQboBilling::EstimateWriter::Conflict => e
|
||||
@conflict = true
|
||||
@@ -296,6 +299,21 @@ class QboEstimatesController < ApplicationController
|
||||
)
|
||||
end
|
||||
|
||||
def unlock?
|
||||
params[:unlock].to_s == '1'
|
||||
end
|
||||
|
||||
# Shows an estimate linked to an issue editable, for users allowed to. EstimateWriter.save checks again.
|
||||
def unlock_form
|
||||
return unless RedmineQboBilling.linked_estimate_editor?
|
||||
|
||||
@linked_issues ||= RedmineQboBilling::EstimateWriter.linked_issues(@form.id).visible.to_a
|
||||
return unless @form.locked == :linked || (@form.locked.nil? && @linked_issues.any?)
|
||||
|
||||
@form.locked = nil
|
||||
@form.unlocked = true
|
||||
end
|
||||
|
||||
def save_and_send?
|
||||
params[:save_and_send].present?
|
||||
end
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
#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.
|
||||
|
||||
# Customer refunds (SOP-OPS-014): the Refund page for a customer with credit (a canceled order's deposit), the
|
||||
# Refund invoice page for completed work on a paid invoice, and a refund once it's made
|
||||
class QboRefundsController < ApplicationController
|
||||
before_action :authorize_global
|
||||
|
||||
QBO_ERRORS = QboEstimatesController::QBO_ERRORS
|
||||
|
||||
def new
|
||||
@customer = Customer.find_by(id: params[:customer_id])
|
||||
return render_404 unless @customer
|
||||
|
||||
@form = RedmineQboBilling::RefundForm.new(customer_id: @customer.id.to_s, estimate_id: params[:estimate_id].to_s,
|
||||
txn_date: User.current.today.iso8601, method: 'check',
|
||||
close_estimate: '1', cancel_issues: '1', email_customer: '1')
|
||||
@form.parts_amount = estimate_parts(@form.estimate_id)
|
||||
load_page
|
||||
end
|
||||
|
||||
def create
|
||||
@form = RedmineQboBilling::RefundForm.from_params(params.require(:refund).permit(*RedmineQboBilling::RefundForm::ATTRIBUTES))
|
||||
@customer = Customer.find_by(id: @form.customer_id)
|
||||
return render_404 unless @customer
|
||||
return show_form unless @form.valid?
|
||||
|
||||
refund = RedmineQboBilling::RefundWriter.refund!(@form)
|
||||
if refund.done?
|
||||
flash[:notice] = l(:notice_refund_done, amount: RedmineQboBilling::RefundWriter.money(refund.refund_amount))
|
||||
else
|
||||
flash[:error] = refund.message
|
||||
end
|
||||
redirect_to qbo_refund_path(refund)
|
||||
rescue RedmineQboBilling::RefundWriter::Error, *QBO_ERRORS => e
|
||||
@form.errors.add(:base, qbo_message(e))
|
||||
show_form
|
||||
end
|
||||
|
||||
# Refund of a paid invoice: its lines to pick from, the optional restocking fee, how the money goes back
|
||||
def new_invoice
|
||||
@form = RedmineQboBilling::InvoiceRefundForm.new(invoice_id: params[:invoice_id].to_s, txn_date: User.current.today.iso8601,
|
||||
method: 'check', charge_fee: '1', note_issues: '1', email_customer: '1')
|
||||
return unless load_invoice_page
|
||||
|
||||
@form.customer_id = @customer.id.to_s
|
||||
# Every line with something left to refund is ticked, at what's left of it
|
||||
@lines.select(&:refundable?).each do |line|
|
||||
@form.lines[line.key] = RedmineQboBilling::InvoiceRefundForm::LineChoice.new(
|
||||
refund: '1', quantity: (quantity = RedmineQboBilling::InvoiceRefundWriter.default_quantity(line)) && RedmineQboBilling::RefundWriter.plain(quantity),
|
||||
amount: format('%.2f', line.remaining_amount)
|
||||
)
|
||||
end
|
||||
load_invoice_plan
|
||||
end
|
||||
|
||||
def create_invoice
|
||||
@form = RedmineQboBilling::InvoiceRefundForm.from_params(params.require(:refund).permit(*RedmineQboBilling::InvoiceRefundForm.permitted))
|
||||
return unless load_invoice_page
|
||||
return show_invoice_form unless @form.valid?
|
||||
|
||||
refund = RedmineQboBilling::InvoiceRefundWriter.refund!(@form)
|
||||
if refund.done?
|
||||
flash[:notice] = l(:notice_refund_done, amount: RedmineQboBilling::RefundWriter.money(refund.refund_amount))
|
||||
else
|
||||
flash[:error] = refund.message
|
||||
end
|
||||
redirect_to qbo_refund_path(refund)
|
||||
rescue RedmineQboBilling::RefundWriter::Error, *QBO_ERRORS => e
|
||||
@form.errors.add(:base, qbo_message(e))
|
||||
show_invoice_form
|
||||
end
|
||||
|
||||
def show
|
||||
@refund = QboRefund.find_by(id: params[:id])
|
||||
return render_404 unless @refund
|
||||
|
||||
@customer = @refund.customer
|
||||
end
|
||||
|
||||
# The refund as a PDF, shown in the browser to print or save
|
||||
def pdf
|
||||
refund = QboRefund.find_by(id: params[:id])
|
||||
return render_404 unless refund
|
||||
|
||||
document = RedmineQboBilling::RefundPdf.new(refund)
|
||||
send_data document.render, type: 'application/pdf', disposition: 'inline', filename: document.filename
|
||||
end
|
||||
|
||||
# Emails the customer the refund's summary (again, or after fixing their email in QuickBooks)
|
||||
def email
|
||||
refund = QboRefund.find_by(id: params[:id])
|
||||
return render_404 unless refund&.done?
|
||||
|
||||
warning = RedmineQboBilling::RefundWriter.email_customer(refund, refund.customer, QboRefundMailer)
|
||||
if warning
|
||||
flash[:error] = warning
|
||||
else
|
||||
flash[:notice] = l(:notice_refund_emailed, email: refund.emailed_to)
|
||||
end
|
||||
redirect_to qbo_refund_path(refund)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# The estimate's parts (its lines that aren't labor), before tax, for the restocking fee
|
||||
def estimate_parts(estimate_id)
|
||||
return '' if estimate_id.blank?
|
||||
|
||||
estimate = RedmineQboBilling::RefundGateway.new.estimate(estimate_id)
|
||||
estimate ? format('%.2f', RedmineQboBilling::RefundWriter.parts_amount(estimate)) : ''
|
||||
rescue *QBO_ERRORS => e
|
||||
flash.now[:error] = qbo_message(e)
|
||||
''
|
||||
end
|
||||
|
||||
def load_page
|
||||
@estimates = RedmineQboBilling::RefundWriter.estimate_choices(@customer)
|
||||
@invoices = RedmineQboBilling::InvoiceRefundWriter.invoice_choices(@customer)
|
||||
@preview = RedmineQboBilling::RefundWriter.preview(@customer, parts: @form.parts_value || BigDecimal('0'))
|
||||
@statuses = IssueStatus.sorted.to_a
|
||||
rescue *QBO_ERRORS => e
|
||||
@preview = nil
|
||||
flash.now[:error] = qbo_message(e)
|
||||
end
|
||||
|
||||
def show_form
|
||||
load_page
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
# The paid invoice from QuickBooks, its customer and its lines; renders the error and returns false when it
|
||||
# can't be refunded
|
||||
def load_invoice_page
|
||||
gateway = RedmineQboBilling::RefundGateway.new
|
||||
@invoice = gateway.invoice(@form.invoice_id) if @form.invoice_id.present?
|
||||
@customer = Customer.find_by(id: @invoice&.customer_ref&.value)
|
||||
if @invoice.nil? || @customer.nil?
|
||||
render_404
|
||||
return false
|
||||
end
|
||||
unless RedmineQboBilling::InvoiceRefundWriter.paid_in_full?(@invoice)
|
||||
flash[:error] = l(:error_refund_invoice_not_paid)
|
||||
redirect_to edit_qbo_invoice_path(@invoice.id)
|
||||
return false
|
||||
end
|
||||
|
||||
@lines = RedmineQboBilling::InvoiceRefundWriter.lines(@invoice)
|
||||
@refunds = QboRefund.of_invoice(@invoice.id).recent.to_a
|
||||
true
|
||||
rescue *QBO_ERRORS => e
|
||||
flash[:error] = qbo_message(e)
|
||||
redirect_to(@form.customer_id.present? ? customer_path(@form.customer_id) : customers_path)
|
||||
false
|
||||
end
|
||||
|
||||
def load_invoice_plan
|
||||
@plan, = RedmineQboBilling::InvoiceRefundWriter.plan(@invoice, @form, invoice_lines: @lines)
|
||||
end
|
||||
|
||||
def show_invoice_form
|
||||
load_invoice_plan
|
||||
render :new_invoice, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def qbo_message(error)
|
||||
detail = error.respond_to?(:detail) ? error.detail.to_s : ''
|
||||
message = error.message.to_s
|
||||
detail.present? && !message.include?(detail) ? "#{message}: #{detail}" : message
|
||||
end
|
||||
end
|
||||
+10
-17
@@ -31,26 +31,19 @@ module AuthHelper
|
||||
require_login
|
||||
end
|
||||
|
||||
# Kept for plugins that still call it (e.g. redmine_qbo_vehicles): requires a logged-in user.
|
||||
# The old version effectively never ran; share-link customers use require_login_or_customer_token.
|
||||
def require_user
|
||||
return true if User.current.logged?
|
||||
|
||||
require_login
|
||||
# A logged-in user may open the estimate's PDF with a billing permission (RedmineQboBilling.estimate_viewer?),
|
||||
# or when it's attached to an issue they can see (the issue page links to it)
|
||||
def estimate_pdf_allowed?(estimate)
|
||||
RedmineQboBilling.estimate_viewer? || Issue.visible.where(estimate_id: estimate.id).exists?
|
||||
end
|
||||
|
||||
def allowed_to?(action)
|
||||
return false if User.current.nil?
|
||||
project = Project.find_by(id: params[:project_id])
|
||||
return false if project.nil?
|
||||
User.current.allowed_to?(action, project)
|
||||
end
|
||||
# The same for invoices: every one of them must be attached to an issue the user can see
|
||||
def invoice_pdfs_allowed?(invoice_ids)
|
||||
return true if RedmineQboBilling.invoice_viewer?
|
||||
|
||||
def check_permission(permission)
|
||||
if !allowed_to?(permission)
|
||||
flash[:error] = t :notice_forbidden
|
||||
render_403
|
||||
end
|
||||
ids = Array(invoice_ids).map(&:to_s).uniq
|
||||
visible = Invoice.joins(:issues).merge(Issue.visible).where(id: ids).distinct.pluck(:id).map(&:to_s)
|
||||
ids.any? && (ids - visible).empty?
|
||||
end
|
||||
|
||||
def global_check_permission(permission)
|
||||
|
||||
@@ -10,12 +10,13 @@
|
||||
|
||||
class QboSyncDispatcher
|
||||
|
||||
# Payments before invoices: an invoice's paid-in-full day is worked out from the local payments' dates
|
||||
SYNC_JOBS = [
|
||||
Customer,
|
||||
Estimate,
|
||||
Payment,
|
||||
Invoice,
|
||||
Employee,
|
||||
Payment
|
||||
Employee
|
||||
].freeze
|
||||
|
||||
# Dispatches all synchronization jobs to perform a full sync of QuickBooks entities with the local database.
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
#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.
|
||||
|
||||
# Emails a customer the summary of their refund (SOP-OPS-014). It goes out like redmine_qbo_reminders' appointment
|
||||
# reminders when that plugin is installed (its From, Reply-To and SMTP server, e.g. the shop's sales mailbox);
|
||||
# otherwise through Redmine's own email settings, from Redmine's emission address. Not Redmine's Mailer, which only
|
||||
# writes to Redmine users and adds Redmine's headers and footer.
|
||||
class QboRefundMailer < ActionMailer::Base
|
||||
layout false
|
||||
self.raise_delivery_errors = true
|
||||
|
||||
class DeliveryOff < StandardError; end
|
||||
|
||||
def refund_summary(refund, email)
|
||||
@refund = refund
|
||||
@customer = refund.customer
|
||||
reminders = defined?(RedmineQboReminders::Settings) ? RedmineQboReminders::Settings.current : nil
|
||||
@shop_name = reminders&.[]('shop_name').to_s.presence || Setting.app_title
|
||||
delivery = reminders ? reminders.delivery_options : {}
|
||||
if delivery.empty? && !ActionMailer::Base.perform_deliveries
|
||||
raise DeliveryOff, I18n.t(:text_refund_email_off)
|
||||
end
|
||||
|
||||
options = { to: email, from: reminders&.from.presence || Setting.mail_from.to_s,
|
||||
subject: I18n.t(:text_refund_email_subject, shop: @shop_name, amount: RedmineQboBilling::RefundWriter.money(refund.refund_amount)) }
|
||||
options[:reply_to] = reminders.reply_to if reminders&.reply_to
|
||||
message = mail(options.merge(delivery)) do |format|
|
||||
format.text
|
||||
end
|
||||
message.perform_deliveries = true unless delivery.empty?
|
||||
message
|
||||
end
|
||||
end
|
||||
@@ -21,17 +21,8 @@ class CustomerToken < ApplicationRecord
|
||||
|
||||
TOKEN_EXPIRATION = 1.month
|
||||
|
||||
# Check if the token has expired
|
||||
def expired?
|
||||
expires_at.present? && expires_at <= Time.current
|
||||
end
|
||||
|
||||
# Remove expired tokens from the database
|
||||
def self.remove_expired_tokens
|
||||
where("expires_at <= ?", Time.current).delete_all
|
||||
end
|
||||
|
||||
# Get or create a token for the given issue
|
||||
# Get or create a token for the given issue. Making a new one also clears out the share links that have expired
|
||||
# or whose issue was deleted, so they don't pile up.
|
||||
def self.get_token(issue)
|
||||
return unless issue
|
||||
return unless User.current.allowed_to?(:view_issues, issue.project)
|
||||
@@ -39,9 +30,17 @@ class CustomerToken < ApplicationRecord
|
||||
token = active.find_by(issue_id: issue.id)
|
||||
return token if token
|
||||
|
||||
purge_expired
|
||||
create!(issue: issue)
|
||||
end
|
||||
|
||||
# Deletes the share links that have expired or whose issue no longer exists; returns how many
|
||||
def self.purge_expired
|
||||
where('expires_at <= ?', Time.current)
|
||||
.or(where.not(issue_id: Issue.select(:id)))
|
||||
.delete_all
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Generate a unique token for the customer
|
||||
|
||||
@@ -79,12 +79,6 @@ class QboBaseModel < ActiveRecord::Base
|
||||
QboSyncJob.perform_later(entity: model_name.name, id: id)
|
||||
end
|
||||
|
||||
# Flag used to update local without pushing to QBO.
|
||||
# This is used to prevent loops with the webhook
|
||||
def skip_qbo_push?
|
||||
!!skip_qbo_push
|
||||
end
|
||||
|
||||
def self.qbo_sync(push: true)
|
||||
self.qbo_push_enabled = push
|
||||
end
|
||||
|
||||
@@ -31,14 +31,6 @@ class QboDraft < ApplicationRecord
|
||||
where(document: documents)
|
||||
}
|
||||
|
||||
def self.writable_document?(document, user = User.current)
|
||||
case document.to_s
|
||||
when 'estimate' then RedmineQboBilling.writer?(user)
|
||||
when 'invoice' then RedmineQboBilling.invoice_writer?(user)
|
||||
else false
|
||||
end
|
||||
end
|
||||
|
||||
# The editor's fields as posted (estimate[...])
|
||||
def fields
|
||||
parsed = JSON.parse(data.presence || '{}')
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
#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.
|
||||
|
||||
# A customer refund (SOP-OPS-014), as it was made: the restocking fee, the refund, and each step's outcome.
|
||||
# Two kinds: credit, a canceled order's deposit (RefundWriter), and invoice, completed work on a paid invoice
|
||||
# (InvoiceRefundWriter).
|
||||
class QboRefund < ApplicationRecord
|
||||
METHODS = %w[check card].freeze
|
||||
STATUSES = %w[done incomplete].freeze
|
||||
KINDS = %w[credit invoice].freeze
|
||||
|
||||
# A refunded invoice line, as recorded: its key on the invoice (InvoiceRefundWriter.line_key)
|
||||
RefundedLine = Struct.new(:key, :description, :quantity, :amount, :parts, keyword_init: true)
|
||||
|
||||
belongs_to :customer
|
||||
belongs_to :user, optional: true
|
||||
|
||||
validates :customer_id, presence: true
|
||||
validates :method, inclusion: { in: METHODS }
|
||||
validates :status, inclusion: { in: STATUSES }
|
||||
validates :kind, inclusion: { in: KINDS }
|
||||
|
||||
scope :recent, -> { order(created_at: :desc, id: :desc) }
|
||||
# The invoice's refunds that made a refund receipt in QuickBooks
|
||||
scope :of_invoice, ->(id) { where(kind: 'invoice', invoice_id: id).where.not(purchase_id: [nil, '']) }
|
||||
|
||||
def invoice?
|
||||
kind == 'invoice'
|
||||
end
|
||||
|
||||
def done?
|
||||
status == 'done'
|
||||
end
|
||||
|
||||
def check?
|
||||
method == 'check'
|
||||
end
|
||||
|
||||
def method_name
|
||||
I18n.t("label_refund_method_#{method}")
|
||||
end
|
||||
|
||||
def canceled_issue_ids
|
||||
Array(JSON.parse(self[:canceled_issue_ids].presence || '[]')).map(&:to_i)
|
||||
rescue JSON::ParserError
|
||||
[]
|
||||
end
|
||||
|
||||
def canceled_issue_ids=(ids)
|
||||
self[:canceled_issue_ids] = Array(ids).map(&:to_i).uniq.to_json
|
||||
end
|
||||
|
||||
def noted_issue_ids
|
||||
Array(JSON.parse(self[:noted_issue_ids].presence || '[]')).map(&:to_i)
|
||||
rescue JSON::ParserError
|
||||
[]
|
||||
end
|
||||
|
||||
def noted_issue_ids=(ids)
|
||||
self[:noted_issue_ids] = Array(ids).map(&:to_i).uniq.to_json
|
||||
end
|
||||
|
||||
def refunded_lines
|
||||
Array(JSON.parse(self[:refunded_lines].presence || '[]')).map do |line|
|
||||
RefundedLine.new(key: line['key'].to_s, description: line['description'].to_s, quantity: line['quantity'],
|
||||
amount: BigDecimal(line['amount'].to_s.presence || '0'), parts: line['parts'] == true)
|
||||
end
|
||||
rescue JSON::ParserError
|
||||
[]
|
||||
end
|
||||
|
||||
def refunded_lines=(lines)
|
||||
self[:refunded_lines] = Array(lines).map do |line|
|
||||
{ key: line.key.to_s, description: line.description.to_s, quantity: line.quantity&.to_s,
|
||||
amount: line.amount.to_d.to_s('F'), parts: line.parts ? true : false }
|
||||
end.to_json
|
||||
end
|
||||
|
||||
# What the order or invoice is called: "E1068", "Invoice #1234", or nil
|
||||
def document_label
|
||||
if invoice? then I18n.t(:label_refund_invoice_number, number: invoice_number)
|
||||
elsif estimate_number.present? then "E#{estimate_number}"
|
||||
end
|
||||
end
|
||||
|
||||
# The QuickBooks screen for the refund receipt, check or expense
|
||||
def purchase_url
|
||||
return nil if purchase_id.blank?
|
||||
|
||||
page = if invoice? then 'refundreceipt'
|
||||
elsif check? then 'check'
|
||||
else 'expense'
|
||||
end
|
||||
"https://#{RedmineQbo.sandbox_mode? ? 'sandbox' : 'app'}.qbo.intuit.com/app/#{page}?txnId=#{purchase_id}"
|
||||
end
|
||||
end
|
||||
@@ -30,6 +30,8 @@ class EstimateSyncService < SyncServiceBase
|
||||
map_attribute :txn_status
|
||||
# Man-hours: quantities of the labor products/services (plugin settings)
|
||||
map_attribute(:hours) { |remote| RedmineQboBilling::ManHours.hours(remote) }
|
||||
# Sales tax, so the business report can compare estimates and invoices without it
|
||||
map_attribute(:tax_amount) { |remote| RedmineQboBilling::InvoicePaidOn.tax(remote) }
|
||||
map_belongs_to :customer
|
||||
|
||||
end
|
||||
@@ -27,6 +27,9 @@ class InvoiceSyncService < SyncServiceBase
|
||||
# Man-hours: quantities of the labor products/services (plugin settings)
|
||||
map_attribute(:hours) { |remote| RedmineQboBilling::ManHours.hours(remote) }
|
||||
map_attribute :qbo_updated_at, "meta_data.last_updated_time"
|
||||
# Sales tax, and the day it was paid in full (nil while open), for reports such as monthly paid sales
|
||||
map_attribute(:tax_amount) { |remote| RedmineQboBilling::InvoicePaidOn.tax(remote) }
|
||||
map_attribute(:paid_on) { |remote| RedmineQboBilling::InvoicePaidOn.paid_on(remote) }
|
||||
map_belongs_to :customer
|
||||
|
||||
end
|
||||
@@ -80,15 +80,6 @@ class SyncServiceBase
|
||||
false
|
||||
end
|
||||
|
||||
def extract_value(remote, remote_attr)
|
||||
case remote_attr
|
||||
when Proc
|
||||
remote_attr.call(remote)
|
||||
else
|
||||
remote.public_send(remote_attr)
|
||||
end
|
||||
end
|
||||
|
||||
# Attribute Mapping DSL
|
||||
#
|
||||
# This DSL defines how attributes from a QuickBooks Online (QBO) entity
|
||||
@@ -157,7 +148,6 @@ class SyncServiceBase
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
def map_attribute(local_attr, remote_attr = nil, &block)
|
||||
attribute_map[local_attr] =
|
||||
if block_given?
|
||||
|
||||
@@ -1,45 +1,58 @@
|
||||
<%#
|
||||
Adds what's ticked on the customer page to the "New issue" link (#dynamic-new-issue-link in the contextual
|
||||
area). Any checkbox with data-new-issue-param="issue[field]" takes part, one ticked per field: this plugin's
|
||||
estimates (issue[estimate_id]), and other plugins' lists (e.g. redmine_qbo_vehicles' issue[vehicle_id]).
|
||||
Adds what's ticked on the customer page to its links: "New issue" (#dynamic-new-issue-link in the contextual area)
|
||||
and redmine_qbo_calendar's "Add appointment" (#appointment_link). A checkbox takes part with
|
||||
data-new-issue-param="issue[field]" (New issue) and data-appointment-param="field" (Add appointment); one is
|
||||
ticked per field: this plugin's estimates (estimate_id), and other plugins' lists (e.g. redmine_qbo_vehicles'
|
||||
vehicle_id).
|
||||
%>
|
||||
<script>
|
||||
function newIssueParamBoxes(param) {
|
||||
return Array.prototype.filter.call(document.querySelectorAll('input[data-new-issue-param]'), function (cb) {
|
||||
return !param || cb.getAttribute('data-new-issue-param') === param;
|
||||
});
|
||||
}
|
||||
(function () {
|
||||
var LINKS = [['dynamic-new-issue-link', 'data-new-issue-param'], ['appointment_link', 'data-appointment-param']];
|
||||
var ANY = 'input[data-new-issue-param], input[data-appointment-param]';
|
||||
|
||||
// One box per field: ticking one unticks the others for the same field
|
||||
document.addEventListener('change', function (event) {
|
||||
var box = event.target;
|
||||
if (!box.matches || !box.matches('input[data-new-issue-param]')) return;
|
||||
if (box.checked) {
|
||||
newIssueParamBoxes(box.getAttribute('data-new-issue-param')).forEach(function (cb) {
|
||||
if (cb !== box) cb.checked = false;
|
||||
function boxes(attr, param) {
|
||||
return Array.prototype.filter.call(document.querySelectorAll('input[' + attr + ']'), function (cb) {
|
||||
return !param || cb.getAttribute(attr) === param;
|
||||
});
|
||||
}
|
||||
updateLink();
|
||||
});
|
||||
|
||||
function updateLink() {
|
||||
var link = document.getElementById('dynamic-new-issue-link');
|
||||
if (!link) return;
|
||||
|
||||
// Cache the pristine base URL on first run
|
||||
if (!link.dataset.baseUrl) link.dataset.baseUrl = link.getAttribute('href');
|
||||
var url = new URL(link.dataset.baseUrl, window.location.origin);
|
||||
|
||||
newIssueParamBoxes().forEach(function (cb) {
|
||||
var param = cb.getAttribute('data-new-issue-param');
|
||||
var ticked = newIssueParamBoxes(param).filter(function (b) { return b.checked; })[0];
|
||||
if (ticked) {
|
||||
url.searchParams.set(param, ticked.value);
|
||||
} else {
|
||||
url.searchParams.delete(param);
|
||||
// Boxes for the same field (the same estimate list, the same vehicle list)
|
||||
function sameField(box) {
|
||||
for (var i = 0; i < LINKS.length; i++) {
|
||||
var attr = LINKS[i][1], param = box.getAttribute(attr);
|
||||
if (param) return boxes(attr, param);
|
||||
}
|
||||
});
|
||||
return [box];
|
||||
}
|
||||
|
||||
link.setAttribute('href', url.toString());
|
||||
}
|
||||
function updateLinks() {
|
||||
LINKS.forEach(function (pair) {
|
||||
var link = document.getElementById(pair[0]);
|
||||
if (!link) return;
|
||||
// Cache the pristine base URL on first run
|
||||
if (!link.dataset.baseUrl) link.dataset.baseUrl = link.getAttribute('href');
|
||||
var url = new URL(link.dataset.baseUrl, window.location.origin);
|
||||
boxes(pair[1]).forEach(function (cb) {
|
||||
var param = cb.getAttribute(pair[1]);
|
||||
var ticked = boxes(pair[1], param).filter(function (b) { return b.checked; })[0];
|
||||
if (ticked) {
|
||||
url.searchParams.set(param, ticked.value);
|
||||
} else {
|
||||
url.searchParams.delete(param);
|
||||
}
|
||||
});
|
||||
link.setAttribute('href', url.toString());
|
||||
});
|
||||
}
|
||||
|
||||
// One box per field: ticking one unticks the others for the same field
|
||||
document.addEventListener('change', function (event) {
|
||||
var box = event.target;
|
||||
if (!box.matches || !box.matches(ANY)) return;
|
||||
if (box.checked) {
|
||||
sameField(box).forEach(function (cb) { if (cb !== box) cb.checked = false; });
|
||||
}
|
||||
updateLinks();
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
@@ -1 +0,0 @@
|
||||
$('select#issue_estimate_id').html('<%= j content_tag(:option,'',value:"")+options_from_collection_for_select(@filtered_estimates, :id, :doc_number) %>');
|
||||
@@ -23,6 +23,9 @@
|
||||
<% if RedmineQboBilling.payment_receiver? %>
|
||||
<%= link_to sprite_icon('add', l(:button_receive_payment)), new_qbo_payment_path(customer_id: @customer.id), class: 'icon icon-add' %>
|
||||
<% end %>
|
||||
<% if RedmineQboBilling.refunder? %>
|
||||
<%= link_to sprite_icon('arrow-narrow-left', l(:label_refund)), new_qbo_refund_path(customer_id: @customer.id), class: 'icon icon-arrow-narrow-left' %>
|
||||
<% end %>
|
||||
<% if User.current.allowed_to?(:edit_customers, nil, global: true) %>
|
||||
<%= link_to sprite_icon('edit', l(:button_edit)), edit_customer_path(@customer),
|
||||
class: 'icon icon-edit', accesskey: accesskey(:edit) %>
|
||||
@@ -49,7 +52,7 @@
|
||||
<div class="splitcontent">
|
||||
<div class="splitcontentleft">
|
||||
<h4><%=t(:estimates)%>:</h4>
|
||||
<%= render partial: 'estimates/list', locals: {estimates: @customer.estimates} %>
|
||||
<%= render partial: 'estimates/list', locals: {estimates: @customer.estimates, new_issue_checkboxes: true} %>
|
||||
</div>
|
||||
|
||||
<div class="splitcontentleft">
|
||||
@@ -65,6 +68,33 @@
|
||||
<%= render partial: 'qbo_drafts/list', locals: { drafts: customer_drafts, show_customer: false } %>
|
||||
<% end %>
|
||||
|
||||
<%# Refunds made from Redmine (SOP-OPS-014) %>
|
||||
<% if RedmineQboBilling.refunder? %>
|
||||
<% customer_refunds = QboRefund.where(customer_id: @customer.id).recent.limit(10).to_a %>
|
||||
<% if customer_refunds.any? %>
|
||||
<h4><%= l(:label_refunds) %>:</h4>
|
||||
<table class="list">
|
||||
<tbody>
|
||||
<% customer_refunds.each do |refund| %>
|
||||
<tr>
|
||||
<td><%= link_to format_date(refund.txn_date), qbo_refund_path(refund) %></td>
|
||||
<td>
|
||||
<% if refund.invoice? %>
|
||||
<%= link_to refund.document_label, RedmineQboBilling.invoice_writer? ? edit_qbo_invoice_path(refund.invoice_id) : invoice_path(refund.invoice_id) %>
|
||||
<% elsif refund.estimate_id.present? %>
|
||||
<%= link_to("E#{refund.estimate_number}", RedmineQboBilling.writer? ? edit_qbo_estimate_path(refund.estimate_id) : estimate_path(refund.estimate_id)) %>
|
||||
<% end %>
|
||||
</td>
|
||||
<td><%= refund.method_name %></td>
|
||||
<td style="text-align: right"><%= RedmineQboBilling::RefundWriter.money(refund.refund_amount) %></td>
|
||||
<td><%= refund.done? ? '' : l(:label_refund_incomplete) %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
<% end %>
|
||||
<% end %>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="splitcontentleft">
|
||||
|
||||
@@ -3,14 +3,19 @@
|
||||
<%= render partial: 'qbo_estimates/status_styles' %>
|
||||
<div class="qbo-estimate-list">
|
||||
<% estimates.sort.reverse.each do |estimate| %>
|
||||
<%# One cell each (qbo_estimates/_status_styles lines them up in columns, so the icons line up) %>
|
||||
<div class="row">
|
||||
<%= check_box_tag "estimate_ids[]", estimate.id, false, onchange: "updateLink()", data: { text: "Estimate ##{estimate.doc_number}", new_issue_param: 'issue[estimate_id]' }, class: "estimate-checkbox appointment" %>
|
||||
<b><%= link_to "##{estimate.doc_number}", estimate_path(estimate), target: :_blank %></b> <%= estimate.txn_date %>
|
||||
<%# Ticking an estimate adds it to the customer page's New issue and Add appointment links (customers/_new_issue_link_script) %>
|
||||
<span class="qbo-list-check"><%= check_box_tag "estimate_ids[]", estimate.id, false, data: { new_issue_param: 'issue[estimate_id]', appointment_param: 'estimate_id' }, class: "estimate-checkbox" if local_assigns[:new_issue_checkboxes] %></span>
|
||||
<b class="qbo-list-number"><%= link_to "##{estimate.doc_number}", estimate_path(estimate), target: :_blank %></b>
|
||||
<span class="qbo-list-date"><%= estimate.txn_date %></span>
|
||||
<%# QuickBooks status, cached by the estimate sync (kept current by the webhook) %>
|
||||
<% if estimate.txn_status.present? %>
|
||||
<span class="qbo-estimate-status qbo-estimate-status-<%= estimate.txn_status.downcase %>"><%= estimate.txn_status %></span>
|
||||
<% end %>
|
||||
<%= render partial: 'qbo_estimates/estimate_actions', locals: { estimate: estimate } if RedmineQboBilling.writer? %>
|
||||
<span class="qbo-list-status">
|
||||
<% if estimate.txn_status.present? %>
|
||||
<span class="qbo-estimate-status qbo-estimate-status-<%= estimate.txn_status.downcase %>"><%= estimate.txn_status %></span>
|
||||
<% end %>
|
||||
</span>
|
||||
<span class="qbo-list-actions"><%= render partial: 'qbo_estimates/estimate_actions', locals: { estimate: estimate } if RedmineQboBilling.writer? %></span>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
@@ -13,14 +13,19 @@
|
||||
|
||||
<div class="qbo-invoice-list">
|
||||
<% invoices.sort.reverse.each do |invoice| %>
|
||||
<%# One cell each (qbo_estimates/_status_styles lines them up in columns, so the icons line up) %>
|
||||
<div class="row">
|
||||
<%= check_box_tag "invoice_ids[]", invoice.id, false, onchange: "updateLink()", data: { url: invoice_path(invoice), text: "Invoice ##{invoice.to_s}" }, class: "invoice-checkbox appointment" if invoices.count > 1 %>
|
||||
<b><%= link_to "##{invoice.doc_number}", invoice_path(invoice), target: :_blank %></b> <%= invoice.txn_date %>
|
||||
<%# Paid / partially paid / overdue / open / voided, from the cached balance and due date %>
|
||||
<% if (status = invoice.status) %>
|
||||
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status) %></span>
|
||||
<% end %>
|
||||
<%= render partial: 'qbo_invoices/invoice_actions', locals: { invoice: invoice } if RedmineQboBilling.invoice_writer? %>
|
||||
<span class="qbo-list-check"><%= check_box_tag "invoice_ids[]", invoice.id, false, class: "invoice-checkbox" if invoices.count > 1 %></span>
|
||||
<b class="qbo-list-number"><%= link_to "##{invoice.doc_number}", invoice_path(invoice), target: :_blank %></b>
|
||||
<span class="qbo-list-date"><%= invoice.txn_date %></span>
|
||||
<%# Paid / partially paid / overdue / open / voided, from the cached balance and due date; short so the list
|
||||
stays narrow: "Paid", or "Paid +3d" when paid in full days after its date (the date on hover) %>
|
||||
<span class="qbo-list-status">
|
||||
<% if (status = invoice.status) %>
|
||||
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>" title="<%= RedmineQboBilling::InvoiceStatus.title(status, paid_on: invoice.paid_on) %>"><%= RedmineQboBilling::InvoiceStatus.short_label(status, paid_on: invoice.paid_on, invoice_date: invoice.txn_date) %></span>
|
||||
<% end %>
|
||||
</span>
|
||||
<span class="qbo-list-actions"><%= render partial: 'qbo_invoices/invoice_actions', locals: { invoice: invoice } if RedmineQboBilling.invoice_writer? %></span>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
@@ -66,3 +66,40 @@
|
||||
<em class="info"><%= l(:text_default_tracker_info) %></em>
|
||||
</p>
|
||||
</fieldset>
|
||||
|
||||
<%# Refunds (SOP-OPS-014): the restocking fee, and where the refund check or card refund is recorded %>
|
||||
<% refunds = RedmineQboBilling::RefundWriter %>
|
||||
<% accounts = Account.where(active: true).order(:name).pluck(:name, :id) %>
|
||||
<fieldset class="box tabular">
|
||||
<legend><%= l(:label_refund_settings) %></legend>
|
||||
<p>
|
||||
<label for="settings_restocking_fee_rate"><%= l(:label_restocking_fee_rate) %></label>
|
||||
<%= number_field_tag 'settings[restocking_fee_rate]', refunds.plain(refunds.fee_rate), id: 'settings_restocking_fee_rate',
|
||||
min: 0, max: 100, step: 0.01, style: 'width: 6em' %>%
|
||||
<em class="info"><%= l(:text_restocking_fee_rate) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label for="settings_restocking_item_id"><%= l(:label_restocking_item) %></label>
|
||||
<%= select_tag 'settings[restocking_item_id]', options_from_collection_for_select(Item.sellable.order(:name), :id, :name, @settings['restocking_item_id']),
|
||||
include_blank: true, id: 'settings_restocking_item_id' %>
|
||||
<em class="info"><%= l(:text_restocking_item) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label for="settings_refund_check_account_id"><%= l(:label_refund_check_account) %></label>
|
||||
<%= select_tag 'settings[refund_check_account_id]', options_for_select(accounts, @settings['refund_check_account_id'].to_s),
|
||||
include_blank: l(:label_refund_first_bank_account), id: 'settings_refund_check_account_id' %>
|
||||
<em class="info"><%= l(:text_refund_check_account) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label for="settings_refund_card_account_id"><%= l(:label_refund_card_account) %></label>
|
||||
<%= select_tag 'settings[refund_card_account_id]', options_for_select(accounts, @settings['refund_card_account_id'].to_s),
|
||||
include_blank: l(:label_refund_first_bank_account), id: 'settings_refund_card_account_id' %>
|
||||
<em class="info"><%= l(:text_refund_card_account) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label for="settings_refund_canceled_status_id"><%= l(:label_refund_canceled_status) %></label>
|
||||
<%= select_tag 'settings[refund_canceled_status_id]', options_from_collection_for_select(IssueStatus.sorted, :id, :name, @settings['refund_canceled_status_id'].to_s),
|
||||
include_blank: refunds.canceled_status ? "#{refunds.canceled_status.name} (#{l(:label_default)})" : true, id: 'settings_refund_canceled_status_id' %>
|
||||
<em class="info"><%= l(:text_refund_canceled_status) %></em>
|
||||
</p>
|
||||
</fieldset>
|
||||
@@ -4,6 +4,7 @@
|
||||
<%= render partial: 'customers/sidebar' %>
|
||||
<% end %>
|
||||
|
||||
<%= render partial: 'estimates/sidebar' %>
|
||||
<%# Finding an estimate by number needs View customers or Write estimates %>
|
||||
<%= render partial: 'estimates/sidebar' if RedmineQboBilling.estimate_viewer? %>
|
||||
|
||||
<% end %>
|
||||
@@ -1,32 +0,0 @@
|
||||
<!--
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 - 2026 rick barrette
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
-->
|
||||
|
||||
<h2>QboController#authenticate</h2>
|
||||
<body>
|
||||
<!-- REPLACE THE BODY of the default application.html.erb with this -->
|
||||
|
||||
<% unless session[:token] %>
|
||||
<ipp:connectToIntuit></ipp:connectToIntuit>
|
||||
<% end %>
|
||||
|
||||
<% if notice %>
|
||||
<div style="padding: 10px;background: gainsboro;font-weight: 900;width: 50%;"><%= notice %></div>
|
||||
<% end %>
|
||||
|
||||
<%= yield %>
|
||||
|
||||
<script type="text/javascript" src="https://appcenter.intuit.com/Content/IA/intuit.ipp.anywhere.js"></script>
|
||||
|
||||
<script>
|
||||
intuit.ipp.anywhere.setup({menuProxy: '/path/to/blue-dot', grantUrl: '<%= authenticate_vendors_url %>'});
|
||||
</script>
|
||||
</body>
|
||||
@@ -1,13 +0,0 @@
|
||||
<!--
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 - 2026 rick barrette
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
-->
|
||||
|
||||
<h2>QboController#oauth_callback</h2>
|
||||
@@ -1,13 +0,0 @@
|
||||
<!--
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 - 2026 rick barrette
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
-->
|
||||
|
||||
<h2>QboController#webhook</h2>
|
||||
@@ -50,6 +50,8 @@
|
||||
<%= hidden_field_tag 'estimate[txn_status]', form.txn_status, id: nil %>
|
||||
<%# Shown again if the page is redisplayed; the saved value is worked out when saving %>
|
||||
<%= hidden_field_tag 'estimate[sales_person]', form.sales_person, id: nil if form.persisted? || form.invoice? %>
|
||||
<%# An estimate linked to an issue opened for editing (Unlock) stays unlocked if the page is shown again %>
|
||||
<%= hidden_field_tag 'unlock', '1', id: nil if !invoice && form.unlocked %>
|
||||
<% if invoice %>
|
||||
<%= hidden_field_tag 'estimate[balance]', form.balance, id: nil %>
|
||||
<%# A paid invoice opened for editing (Unlock) stays unlocked if the page is shown again %>
|
||||
|
||||
@@ -20,7 +20,8 @@
|
||||
due_date: RedmineQboBilling::EstimateForm.date(form.due_date),
|
||||
today: User.current.today) %>
|
||||
<% if status %>
|
||||
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status) %></span>
|
||||
<% paid_on = Invoice.where(id: form.id).pick(:paid_on) if status == :paid && form.id.present? %>
|
||||
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status, paid_on: paid_on) %></span>
|
||||
<% end %>
|
||||
<% elsif !invoice && form.txn_status.present? %>
|
||||
<span class="qbo-estimate-status qbo-estimate-status-<%= form.txn_status.downcase %>"><%= form.txn_status %></span>
|
||||
@@ -66,6 +67,21 @@
|
||||
<li><%= link_to_issue(issue, truncate: 60) %></li>
|
||||
<% end %>
|
||||
</ul>
|
||||
<%# Opened for editing anyway after a confirmation (e.g. the customer asks for changes after the diagnosis) %>
|
||||
<% if RedmineQboBilling.linked_estimate_editor? %>
|
||||
<%= link_to sprite_icon('unlock', l(:button_unlock_estimate)), edit_qbo_estimate_path(form.id, unlock: 1),
|
||||
class: 'icon icon-unlock', id: 'qbo-unlock-estimate',
|
||||
data: { confirm: l(:text_unlock_estimate_confirmation) } %>
|
||||
<% end %>
|
||||
</div>
|
||||
<% elsif form.unlocked && !invoice %>
|
||||
<div class="warning qbo-estimate-notice">
|
||||
<%= l(:text_estimate_unlocked) %>
|
||||
<ul>
|
||||
<% Array(@linked_issues).each do |issue| %>
|
||||
<li><%= link_to_issue(issue, truncate: 60) %></li>
|
||||
<% end %>
|
||||
</ul>
|
||||
</div>
|
||||
<% elsif form.locked == :paid %>
|
||||
<p class="warning">
|
||||
|
||||
@@ -14,4 +14,11 @@
|
||||
.qbo-invoice-status-open { background: #e8eefa; color: #0d47a1; }
|
||||
.qbo-invoice-status-voided { background: #eceef1; color: #6b6c72; text-decoration: line-through; }
|
||||
.qbo-invoice-list .qbo-estimate-status { font-size: .8em; padding: 1px 7px; margin-left: 4px; }
|
||||
/* The estimate and invoice lists: checkbox, number, date, status and actions in columns, so the edit/view icons
|
||||
line up; a list wider than its column scrolls instead of wrapping */
|
||||
.qbo-estimate-list, .qbo-invoice-list { display: grid; grid-template-columns: repeat(5, max-content); column-gap: .35em;
|
||||
row-gap: 2px; align-items: center; overflow-x: auto; }
|
||||
.qbo-estimate-list .row, .qbo-invoice-list .row { display: contents; }
|
||||
.qbo-estimate-list .row > *, .qbo-invoice-list .row > * { white-space: nowrap; }
|
||||
.qbo-list-status .qbo-estimate-status { margin-left: 0; }
|
||||
</style>
|
||||
@@ -6,6 +6,10 @@
|
||||
<% if RedmineQboBilling.payment_receiver? && @form.balance.to_d > 0 %>
|
||||
<%= link_to sprite_icon('add', l(:button_receive_payment)), new_qbo_payment_path(customer_id: @form.customer_id), class: 'icon icon-add' %>
|
||||
<% end %>
|
||||
<%# Completed work that's paid in full is refunded with a refund receipt %>
|
||||
<% if RedmineQboBilling.refunder? && @form.total.to_d.positive? && @form.balance.to_d <= 0 %>
|
||||
<%= link_to sprite_icon('arrow-narrow-left', l(:label_refund)), new_invoice_qbo_refunds_path(invoice_id: @form.id), class: 'icon icon-arrow-narrow-left' %>
|
||||
<% end %>
|
||||
<%= link_to sprite_icon('application-pdf', l(:label_estimate_pdf)), invoice_path(@form.id), class: 'icon icon-pdf', target: :_blank %>
|
||||
<% if RedmineQboBilling.invoice_sender? && @form.email.present? %>
|
||||
<%= link_to sprite_icon('email', l(:button_email_estimate)), send_email_qbo_invoice_path(@form.id, email: @form.email),
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<% money = ->(amount) { RedmineQboBilling::RefundWriter.money(amount) } -%>
|
||||
<%= t(:text_refund_email_greeting, name: @customer&.name.to_s) %>
|
||||
|
||||
<%= t(:text_refund_email_intro, shop: @shop_name, order: @refund.document_label || t(:label_refund_your_order)) %>
|
||||
|
||||
<% if @refund.invoice? -%>
|
||||
<% @refund.refunded_lines.each do |line| -%>
|
||||
<%= line.description %>: <%= money.(line.amount) %>
|
||||
<% end -%>
|
||||
<%= t(:label_refund_lines_amount) %>: <%= money.(@refund.lines_amount) %>
|
||||
<% if @refund.discount_amount.to_d.positive? -%>
|
||||
<%= t(:label_refund_discount) %>: -<%= money.(@refund.discount_amount) %>
|
||||
<% end -%>
|
||||
<%= t(:label_refund_tax) %>: <%= money.(@refund.tax_amount) %>
|
||||
<% end -%>
|
||||
<% if @refund.fee_amount.to_d.positive? -%>
|
||||
<%= t(:label_refund_parts) %>: <%= money.(@refund.parts_amount) %>
|
||||
<%= t(:label_refund_fee_rate, rate: RedmineQboBilling::RefundWriter.plain(@refund.fee_rate)) %>: <%= money.(@refund.fee_amount) %>
|
||||
<% end -%>
|
||||
<%= t(:label_refund_amount) %>: <%= money.(@refund.refund_amount) %>
|
||||
<%= @refund.check? ? t(:text_refund_email_check, number: @refund.check_number) : t(:text_refund_email_card) %>
|
||||
|
||||
<% if !@refund.invoice? -%>
|
||||
<%= t(:text_refund_email_terms) %>
|
||||
<% elsif @refund.fee_amount.to_d.positive? -%>
|
||||
<%= t(:text_refund_email_terms_invoice) %>
|
||||
<% end -%>
|
||||
|
||||
<%= @shop_name %>
|
||||
@@ -0,0 +1,137 @@
|
||||
<%# Refund for a canceled order or returned parts (SOP-OPS-014) %>
|
||||
<% html_title l(:label_refund) %>
|
||||
<% money = ->(amount) { RedmineQboBilling::RefundWriter.money(amount) } %>
|
||||
<% preview = @preview %>
|
||||
|
||||
<h2>
|
||||
<%= link_to l(:label_customers), customers_path %> »
|
||||
<%= link_to @customer.name, customer_path(@customer) %> »
|
||||
<%= l(:label_refund) %>
|
||||
</h2>
|
||||
|
||||
<%= error_messages_for @form %>
|
||||
|
||||
<p class="warning"><%= l(:text_refund_final_sale) %></p>
|
||||
|
||||
<%# Completed work on a paid invoice is refunded from the invoice (a refund receipt), not from credit %>
|
||||
<% if @invoices.present? %>
|
||||
<%= form_tag new_invoice_qbo_refunds_path, method: :get, id: 'qbo-refund-invoice' do %>
|
||||
<div class="box tabular">
|
||||
<p>
|
||||
<label for="qbo_refund_invoice"><%= l(:label_refund_paid_invoice) %></label>
|
||||
<%= select_tag 'invoice_id', options_for_select(@invoices), include_blank: true, id: 'qbo_refund_invoice',
|
||||
onchange: 'if (this.value) this.form.submit()' %>
|
||||
<noscript><%= submit_tag l(:button_apply), name: nil %></noscript>
|
||||
<em class="info"><%= l(:text_refund_paid_invoice) %></em>
|
||||
</p>
|
||||
</div>
|
||||
<% end %>
|
||||
<% end %>
|
||||
|
||||
<% if preview && preview.credits.empty? %>
|
||||
<p class="nodata"><%= l(:text_refund_no_credit) %></p>
|
||||
<% end %>
|
||||
|
||||
<%# Picking the canceled order's estimate reloads the page with its parts filled in %>
|
||||
<%= form_tag new_qbo_refund_path, method: :get, id: 'qbo-refund-estimate' do %>
|
||||
<%= hidden_field_tag 'customer_id', @customer.id, id: nil %>
|
||||
<div class="box tabular">
|
||||
<p>
|
||||
<label for="qbo_refund_estimate"><%= l(:label_refund_estimate) %></label>
|
||||
<%= select_tag 'estimate_id', options_for_select(@estimates, @form.estimate_id), include_blank: l(:label_refund_no_estimate),
|
||||
id: 'qbo_refund_estimate', onchange: 'this.form.submit()' %>
|
||||
<noscript><%= submit_tag l(:button_apply), name: nil %></noscript>
|
||||
<em class="info"><%= l(:text_refund_estimate) %></em>
|
||||
</p>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<%= form_tag qbo_refunds_path, method: :post, id: 'qbo-refund-form' do %>
|
||||
<%= hidden_field_tag 'refund[customer_id]', @customer.id, id: nil %>
|
||||
<%= hidden_field_tag 'refund[estimate_id]', @form.estimate_id, id: nil %>
|
||||
<div class="box tabular">
|
||||
<p>
|
||||
<label for="qbo_refund_parts"><%= l(:label_refund_parts) %></label>
|
||||
$<%= text_field_tag 'refund[parts_amount]', @form.parts_amount, id: 'qbo_refund_parts', size: 12, inputmode: 'decimal',
|
||||
autocomplete: 'off', data: { rate: preview&.fee_rate.to_s } %>
|
||||
<em class="info"><%= l(:text_refund_parts, rate: RedmineQboBilling::RefundWriter.plain(preview&.fee_rate || RedmineQboBilling::RefundWriter.fee_rate)) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label><%= l(:label_refund_method) %><span class="required"> *</span></label>
|
||||
<label class="inline"><%= radio_button_tag 'refund[method]', 'check', @form.method == 'check', id: 'qbo_refund_method_check' %> <%= l(:label_refund_method_check) %></label>
|
||||
<label class="inline"><%= radio_button_tag 'refund[method]', 'card', @form.method == 'card', id: 'qbo_refund_method_card' %> <%= l(:label_refund_method_card) %></label>
|
||||
<em class="info"><%= l(:text_refund_method) %></em>
|
||||
</p>
|
||||
<p id="qbo-refund-check-number">
|
||||
<label for="qbo_refund_check_number"><%= l(:label_refund_check_number) %><span class="required"> *</span></label>
|
||||
<%= text_field_tag 'refund[check_number]', @form.check_number, id: 'qbo_refund_check_number', size: 12, maxlength: 21 %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_refund_date"><%= l(:label_refund_date) %><span class="required"> *</span></label>
|
||||
<%= date_field_tag 'refund[txn_date]', @form.txn_date, id: 'qbo_refund_date' %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_refund_reason"><%= l(:label_refund_reason) %><span class="required"> *</span></label>
|
||||
<%= text_area_tag 'refund[reason]', @form.reason, id: 'qbo_refund_reason', rows: 3, cols: 60, maxlength: 2000 %>
|
||||
<em class="info"><%= l(:text_refund_reason) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label><%= l(:label_refund_also) %></label>
|
||||
<% [[:close_estimate, :label_refund_close_estimate], [:cancel_issues, :label_refund_cancel_issues], [:email_customer, :label_refund_email_customer]].each do |flag, label| %>
|
||||
<% needs_estimate = flag != :email_customer %>
|
||||
<label class="block">
|
||||
<%= hidden_field_tag "refund[#{flag}]", '0', id: nil %>
|
||||
<%= check_box_tag "refund[#{flag}]", '1', @form.send(:"#{flag}?") && (!needs_estimate || @form.estimate_id.present?),
|
||||
id: "qbo_refund_#{flag}", disabled: needs_estimate && @form.estimate_id.blank? %>
|
||||
<%= l(label) %>
|
||||
</label>
|
||||
<% end %>
|
||||
<% if @customer.email.blank? %><em class="info"><%= l(:text_refund_no_email) %></em><% end %>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<% if preview %>
|
||||
<fieldset class="box" id="qbo-refund-preview">
|
||||
<legend><%= l(:label_refund_summary) %></legend>
|
||||
<table class="list">
|
||||
<thead><tr><th><%= l(:label_refund_credit_from) %></th><th><%= l(:label_payment_reference) %></th><th><%= l(:label_memo) %></th><th><%= l(:label_amount) %></th></tr></thead>
|
||||
<tbody>
|
||||
<% preview.credits.each do |credit| %>
|
||||
<tr>
|
||||
<td><%= link_to format_date(credit.date), qbo_payment_path(credit.payment_id) %></td>
|
||||
<td><%= credit.reference %></td>
|
||||
<td><%= credit.memo %></td>
|
||||
<td style="text-align: right"><%= money.(credit.amount) %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr><td colspan="3"><%= l(:label_refund_credit) %></td><td style="text-align: right" id="qbo-refund-credit" data-credit="<%= preview.credit_total.to_s('F') %>"><%= money.(preview.credit_total) %></td></tr>
|
||||
<tr><td colspan="3"><%= l(:label_refund_fee_rate, rate: RedmineQboBilling::RefundWriter.plain(preview.fee_rate)) %></td><td style="text-align: right" id="qbo-refund-fee">-<%= money.(preview.fee) %></td></tr>
|
||||
<tr><td colspan="3"><strong><%= l(:label_refund_amount) %></strong></td><td style="text-align: right"><strong id="qbo-refund-amount"><%= money.(preview.refund) %></strong></td></tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
<p><em class="info"><%= l(:text_refund_summary) %></em></p>
|
||||
</fieldset>
|
||||
<% end %>
|
||||
|
||||
<p><%= submit_tag l(:button_refund), data: { confirm: l(:text_refund_confirm) }, disabled: preview.nil? || preview.credits.empty? %></p>
|
||||
<% end %>
|
||||
|
||||
<%= javascript_tag do %>
|
||||
$(function() {
|
||||
var money = function(n) { return '$' + n.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ','); };
|
||||
function update() {
|
||||
var parts = parseFloat(($('#qbo_refund_parts').val() || '0').replace(/[$,\s]/g, '')) || 0;
|
||||
var rate = parseFloat($('#qbo_refund_parts').data('rate')) || 0;
|
||||
var credit = parseFloat($('#qbo-refund-credit').data('credit')) || 0;
|
||||
var fee = Math.round(parts * rate) / 100;
|
||||
$('#qbo-refund-fee').text('-' + money(fee));
|
||||
$('#qbo-refund-amount').text(money(Math.max(credit - fee, 0)));
|
||||
}
|
||||
function method() { $('#qbo-refund-check-number').toggle($('#qbo_refund_method_check').is(':checked')); }
|
||||
$('#qbo_refund_parts').on('input', update);
|
||||
$('input[name="refund[method]"]').on('change', method);
|
||||
update(); method();
|
||||
});
|
||||
<% end %>
|
||||
@@ -0,0 +1,195 @@
|
||||
<%# Refund of completed work on a paid invoice: a QuickBooks Refund Receipt (InvoiceRefundWriter) %>
|
||||
<% html_title "#{l(:label_refund)} #{l(:label_refund_invoice_number, number: @invoice.doc_number)}" %>
|
||||
<% writer = RedmineQboBilling::RefundWriter %>
|
||||
<% money = ->(amount) { writer.money(amount) } %>
|
||||
<% plan = @plan %>
|
||||
<% number = @invoice.doc_number.to_s %>
|
||||
|
||||
<h2>
|
||||
<%= link_to l(:label_customers), customers_path %> »
|
||||
<%= link_to @customer.name, customer_path(@customer) %> »
|
||||
<%= link_to l(:label_refund_invoice_number, number: number), edit_qbo_invoice_path(@invoice.id) %> »
|
||||
<%= l(:label_refund) %>
|
||||
</h2>
|
||||
|
||||
<%= error_messages_for @form %>
|
||||
|
||||
<p class="warning"><%= l(:text_refund_final_sale) %></p>
|
||||
|
||||
<% if @refunds.any? %>
|
||||
<div class="flash warning">
|
||||
<%= l(:text_refund_invoice_earlier) %>
|
||||
<%= safe_join(@refunds.map { |r| link_to("#{format_date(r.txn_date)} · #{money.(r.refund_amount)}", qbo_refund_path(r)) }, ', ') %>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<%= form_tag create_invoice_qbo_refunds_path, method: :post, id: 'qbo-refund-form' do %>
|
||||
<%= hidden_field_tag 'refund[customer_id]', @customer.id, id: nil %>
|
||||
<%= hidden_field_tag 'refund[invoice_id]', @invoice.id, id: nil %>
|
||||
|
||||
<fieldset class="box" id="qbo-refund-lines">
|
||||
<legend><%= l(:label_refund_invoice_lines, number: number, date: format_date(@invoice.txn_date)) %></legend>
|
||||
<table class="list" data-discount-rate="<%= plan.discount_rate.to_s('F') %>" data-tax-rate="<%= plan.tax_rate.to_s('F') %>"
|
||||
data-fee-rate="<%= plan.fee_rate.to_s('F') %>">
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th style="text-align: left"><%= l(:label_refund_line) %></th>
|
||||
<th></th>
|
||||
<th style="text-align: right"><%= l(:label_refund_line_billed) %></th>
|
||||
<th style="text-align: right"><%= l(:label_refund_line_refunded) %></th>
|
||||
<th><%= l(:label_refund_line_quantity) %></th>
|
||||
<th><%= l(:label_refund_line_amount) %></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% @lines.each do |line| %>
|
||||
<% choice = @form.line(line.key) %>
|
||||
<% field = "refund[lines][#{line.key}]" %>
|
||||
<% dom = "qbo_refund_line_#{line.key.parameterize(separator: '_')}" %>
|
||||
<tr class="qbo-refund-line<%= ' disabled' unless line.refundable? %>" data-rate="<%= line.rate&.to_s('F') %>"
|
||||
data-parts="<%= line.parts ? 1 : 0 %>" data-taxable="<%= line.taxable ? 1 : 0 %>">
|
||||
<td>
|
||||
<% if line.refundable? %>
|
||||
<%= hidden_field_tag "#{field}[refund]", '0', id: nil %>
|
||||
<%= check_box_tag "#{field}[refund]", '1', choice&.refund?, id: dom, class: 'qbo-refund-pick' %>
|
||||
<% end %>
|
||||
</td>
|
||||
<td style="text-align: left">
|
||||
<label for="<%= dom %>">
|
||||
<% if line.item_name.present? %><strong><%= line.item_name %></strong><br><% end %>
|
||||
<%= line.description %>
|
||||
</label>
|
||||
</td>
|
||||
<td><span class="badge <%= line.parts ? 'badge-status-open' : 'badge-status-closed' %>"><%= l(line.parts ? :label_refund_parts : :label_refund_labor) %></span>
|
||||
<% if line.taxable %><span class="badge"><%= l(:label_refund_taxable) %></span><% end %></td>
|
||||
<td style="text-align: right">
|
||||
<% if line.quantity && line.rate %><%= writer.plain(line.quantity) %> × <%= money.(line.rate) %><br><% end %>
|
||||
<%= money.(line.amount) %>
|
||||
</td>
|
||||
<td style="text-align: right"><%= line.refunded_amount.positive? ? money.(line.refunded_amount) : '' %></td>
|
||||
<% if line.refundable? %>
|
||||
<td style="white-space: nowrap">
|
||||
<% if line.quantity && line.rate %>
|
||||
<%= text_field_tag "#{field}[quantity]", choice&.quantity, size: 5, inputmode: 'decimal', autocomplete: 'off',
|
||||
class: 'qbo-refund-quantity', 'aria-label': l(:label_refund_line_quantity) %>
|
||||
<em class="info">/ <%= writer.plain(line.remaining_quantity) %></em>
|
||||
<% end %>
|
||||
</td>
|
||||
<td style="white-space: nowrap">
|
||||
$<%= text_field_tag "#{field}[amount]", choice&.amount, size: 9, inputmode: 'decimal', autocomplete: 'off',
|
||||
class: 'qbo-refund-line-amount', 'aria-label': l(:label_refund_line_amount),
|
||||
data: { max: line.remaining_amount.to_s('F') } %>
|
||||
</td>
|
||||
<% else %>
|
||||
<td colspan="2"><em class="info"><%= l(:text_refund_line_done) %></em></td>
|
||||
<% end %>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
<p><em class="info"><%= l(:text_refund_invoice_lines) %></em></p>
|
||||
</fieldset>
|
||||
|
||||
<div class="box tabular">
|
||||
<p>
|
||||
<label for="qbo_refund_charge_fee"><%= l(:label_refund_charge_fee) %></label>
|
||||
<%= hidden_field_tag 'refund[charge_fee]', '0', id: nil %>
|
||||
<%= check_box_tag 'refund[charge_fee]', '1', @form.charge_fee?, id: 'qbo_refund_charge_fee' %>
|
||||
<%= l(:label_refund_fee_rate, rate: writer.plain(plan.fee_rate)) %>
|
||||
<em class="info"><%= l(:text_refund_charge_fee) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label><%= l(:label_refund_method) %><span class="required"> *</span></label>
|
||||
<label class="inline"><%= radio_button_tag 'refund[method]', 'check', @form.method == 'check', id: 'qbo_refund_method_check' %> <%= l(:label_refund_method_check) %></label>
|
||||
<label class="inline"><%= radio_button_tag 'refund[method]', 'card', @form.method == 'card', id: 'qbo_refund_method_card' %> <%= l(:label_refund_method_card) %></label>
|
||||
<em class="info"><%= l(:text_refund_method) %></em>
|
||||
</p>
|
||||
<p id="qbo-refund-check-number">
|
||||
<label for="qbo_refund_check_number"><%= l(:label_refund_check_number) %><span class="required"> *</span></label>
|
||||
<%= text_field_tag 'refund[check_number]', @form.check_number, id: 'qbo_refund_check_number', size: 12, maxlength: 21 %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_refund_date"><%= l(:label_refund_date) %><span class="required"> *</span></label>
|
||||
<%= date_field_tag 'refund[txn_date]', @form.txn_date, id: 'qbo_refund_date' %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_refund_reason"><%= l(:label_refund_reason) %><span class="required"> *</span></label>
|
||||
<%= text_area_tag 'refund[reason]', @form.reason, id: 'qbo_refund_reason', rows: 3, cols: 60, maxlength: 2000 %>
|
||||
<em class="info"><%= l(:text_refund_invoice_reason) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label><%= l(:label_refund_also) %></label>
|
||||
<% [[:note_issues, :label_refund_note_issues], [:email_customer, :label_refund_email_customer]].each do |flag, label| %>
|
||||
<label class="block">
|
||||
<%= hidden_field_tag "refund[#{flag}]", '0', id: nil %>
|
||||
<%= check_box_tag "refund[#{flag}]", '1', @form.send(:"#{flag}?"), id: "qbo_refund_#{flag}" %>
|
||||
<%= l(label) %>
|
||||
</label>
|
||||
<% end %>
|
||||
<% if @customer.email.blank? %><em class="info"><%= l(:text_refund_no_email) %></em><% end %>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<fieldset class="box" id="qbo-refund-preview">
|
||||
<legend><%= l(:label_refund_summary) %></legend>
|
||||
<table class="list">
|
||||
<tbody>
|
||||
<tr><td><%= l(:label_refund_lines_amount) %></td><td style="text-align: right" id="qbo-refund-lines-amount"><%= money.(plan.lines_amount) %></td></tr>
|
||||
<tr id="qbo-refund-discount-row"<%= ' style="display: none"'.html_safe unless plan.discount_rate.positive? %>>
|
||||
<td><%= l(:label_refund_discount) %></td><td style="text-align: right" id="qbo-refund-discount">-<%= money.(plan.discount) %></td>
|
||||
</tr>
|
||||
<tr><td><%= l(:label_refund_tax_estimate) %></td><td style="text-align: right" id="qbo-refund-tax"><%= money.(plan.tax) %></td></tr>
|
||||
<tr><td><%= l(:label_refund_fee_on_parts) %> (<span id="qbo-refund-parts"><%= money.(plan.parts_amount) %></span>)</td>
|
||||
<td style="text-align: right" id="qbo-refund-fee">-<%= money.(plan.fee) %></td></tr>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr><td><strong><%= l(:label_refund_amount) %></strong></td><td style="text-align: right"><strong id="qbo-refund-amount"><%= money.(plan.refund) %></strong></td></tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
<p><em class="info"><%= l(:text_refund_invoice_summary) %></em></p>
|
||||
</fieldset>
|
||||
|
||||
<p><%= submit_tag l(:button_refund), data: { confirm: l(:text_refund_invoice_confirm) }, disabled: @lines.none?(&:refundable?) %></p>
|
||||
<% end %>
|
||||
|
||||
<%= javascript_tag do %>
|
||||
$(function() {
|
||||
var table = $('#qbo-refund-lines table');
|
||||
var money = function(n) { return '$' + n.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ','); };
|
||||
var num = function(v) { return parseFloat(String(v || '').replace(/[$,\s]/g, '')) || 0; };
|
||||
var round = function(n) { return Math.round(n * 100) / 100; };
|
||||
function update() {
|
||||
var lines = 0, parts = 0, taxable = 0;
|
||||
$('tr.qbo-refund-line').each(function() {
|
||||
var row = $(this);
|
||||
if (!row.find('.qbo-refund-pick').is(':checked')) return;
|
||||
var amount = num(row.find('.qbo-refund-line-amount').val());
|
||||
lines += amount;
|
||||
if (row.data('parts') == 1) parts += amount;
|
||||
if (row.data('taxable') == 1) taxable += amount;
|
||||
});
|
||||
var discountRate = num(table.data('discount-rate')), taxRate = num(table.data('tax-rate'));
|
||||
var discount = round(lines * discountRate);
|
||||
var tax = round(taxable * (1 - discountRate) * taxRate);
|
||||
var fee = $('#qbo_refund_charge_fee').is(':checked') ? Math.round(parts * num(table.data('fee-rate'))) / 100 : 0;
|
||||
$('#qbo-refund-lines-amount').text(money(lines));
|
||||
$('#qbo-refund-discount').text('-' + money(discount));
|
||||
$('#qbo-refund-tax').text(money(tax));
|
||||
$('#qbo-refund-parts').text(money(parts));
|
||||
$('#qbo-refund-fee').text('-' + money(fee));
|
||||
$('#qbo-refund-amount').text(money(Math.max(lines - discount + tax - fee, 0)));
|
||||
}
|
||||
// A quantity refunds that many at the line's rate (the amount can still be changed after)
|
||||
$('.qbo-refund-quantity').on('input', function() {
|
||||
var row = $(this).closest('tr'), rate = num(row.data('rate'));
|
||||
if (rate) row.find('.qbo-refund-line-amount').val(round(num($(this).val()) * rate).toFixed(2));
|
||||
row.find('.qbo-refund-pick').prop('checked', num($(this).val()) > 0);
|
||||
update();
|
||||
});
|
||||
$('.qbo-refund-line-amount, #qbo_refund_charge_fee, .qbo-refund-pick').on('input change', update);
|
||||
function method() { $('#qbo-refund-check-number').toggle($('#qbo_refund_method_check').is(':checked')); }
|
||||
$('input[name="refund[method]"]').on('change', method);
|
||||
update(); method();
|
||||
});
|
||||
<% end %>
|
||||
@@ -0,0 +1,97 @@
|
||||
<%# A refund as it was made (SOP-OPS-014) %>
|
||||
<% html_title l(:label_refund) %>
|
||||
<% money = ->(amount) { RedmineQboBilling::RefundWriter.money(amount) } %>
|
||||
|
||||
<h2>
|
||||
<%= link_to l(:label_customers), customers_path %> »
|
||||
<% if @customer %><%= link_to @customer.name, customer_path(@customer) %> »<% end %>
|
||||
<%= l(:label_refund) %> <%= format_date(@refund.txn_date) %>
|
||||
</h2>
|
||||
|
||||
<div class="contextual">
|
||||
<%= link_to sprite_icon('application-pdf', 'PDF'), pdf_qbo_refund_path(@refund), class: 'icon icon-pdf', target: :_blank %>
|
||||
<% if @refund.fee_invoice_id.present? %>
|
||||
<%= link_to sprite_icon('application-pdf', l(:label_refund_fee_invoice_pdf)), invoice_path(@refund.fee_invoice_id), class: 'icon icon-pdf', target: :_blank %>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
<% if @refund.done? && @refund.invoice? %>
|
||||
<p class="notice flash"><%= l(:text_refund_receipt_made, number: @refund.receipt_number.presence || @refund.purchase_id) %></p>
|
||||
<% elsif @refund.done? %>
|
||||
<p class="<%= @refund.balance_after.to_d.zero? ? 'notice flash' : 'warning' %>">
|
||||
<%= @refund.balance_after.nil? ? l(:text_refund_balance_unknown) : l(:text_refund_balance, balance: money.(@refund.balance_after)) %>
|
||||
</p>
|
||||
<% else %>
|
||||
<p class="conflict"><%= l(:text_refund_incomplete) %></p>
|
||||
<% end %>
|
||||
<% if @refund.message.present? %>
|
||||
<div class="warning"><%= simple_format(h(@refund.message)) %></div>
|
||||
<% end %>
|
||||
|
||||
<div class="box tabular">
|
||||
<% if @refund.invoice? %>
|
||||
<p><label><%= l(:label_refund_invoice) %></label>
|
||||
<%= link_to @refund.document_label, RedmineQboBilling.invoice_writer? ? edit_qbo_invoice_path(@refund.invoice_id) : invoice_path(@refund.invoice_id) %>
|
||||
· <%= l(:label_refund_paid_on_invoice) %> <%= money.(@refund.credit_amount) %></p>
|
||||
<p><label><%= l(:label_refund_reason) %></label> <%= @refund.reason %></p>
|
||||
<p><label><%= l(:label_refund_lines_amount) %></label> <%= money.(@refund.lines_amount) %></p>
|
||||
<% if @refund.refunded_lines.any? %>
|
||||
<table class="list" style="max-width: 50em">
|
||||
<tbody>
|
||||
<% @refund.refunded_lines.each do |line| %>
|
||||
<tr>
|
||||
<td style="text-align: left"><%= line.description %></td>
|
||||
<td><%= l(line.parts ? :label_refund_parts : :label_refund_labor) %></td>
|
||||
<td style="text-align: right"><%= RedmineQboBilling::RefundWriter.plain(BigDecimal(line.quantity.to_s)) if line.quantity.present? %></td>
|
||||
<td style="text-align: right"><%= money.(line.amount) %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
<% end %>
|
||||
<% if @refund.discount_amount.to_d.positive? %>
|
||||
<p><label><%= l(:label_refund_discount) %></label> -<%= money.(@refund.discount_amount) %></p>
|
||||
<% end %>
|
||||
<p><label><%= l(:label_refund_tax) %></label> <%= money.(@refund.tax_amount) %></p>
|
||||
<% else %>
|
||||
<p><label><%= l(:label_refund_estimate) %></label> <%= @refund.estimate_id.present? ? link_to("E#{@refund.estimate_number}", RedmineQboBilling.writer? ? edit_qbo_estimate_path(@refund.estimate_id) : estimate_path(@refund.estimate_id)) : l(:label_refund_no_estimate) %></p>
|
||||
<p><label><%= l(:label_refund_reason) %></label> <%= @refund.reason %></p>
|
||||
<p><label><%= l(:label_refund_credit) %></label> <%= money.(@refund.credit_amount) %></p>
|
||||
<% end %>
|
||||
<p><label><%= l(:label_refund_parts) %></label> <%= money.(@refund.parts_amount) %></p>
|
||||
<p>
|
||||
<label><%= l(:label_refund_fee_rate, rate: RedmineQboBilling::RefundWriter.plain(@refund.fee_rate)) %></label>
|
||||
<%= @refund.fee_amount.to_d.positive? ? money.(@refund.fee_amount) : l(:label_refund_no_fee) %>
|
||||
<% if @refund.fee_invoice_id.present? %>
|
||||
· <%= link_to l(:label_refund_fee_invoice, number: @refund.fee_invoice_number), RedmineQboBilling.invoice_writer? ? edit_qbo_invoice_path(@refund.fee_invoice_id) : invoice_path(@refund.fee_invoice_id) %>
|
||||
<% end %>
|
||||
</p>
|
||||
<p>
|
||||
<label><%= l(:label_refund_amount) %></label>
|
||||
<%= money.(@refund.refund_amount) %> · <%= @refund.method_name %><%= " ##{@refund.check_number}" if @refund.check? %>
|
||||
<% if @refund.purchase_url %>
|
||||
· <%= link_to l(@refund.invoice? ? :label_refund_open_receipt : (@refund.check? ? :label_refund_open_check : :label_refund_open_expense)),
|
||||
@refund.purchase_url, target: '_blank', rel: 'noopener' %>
|
||||
<% end %>
|
||||
</p>
|
||||
<% if @refund.estimate_number.present? %>
|
||||
<p><label><%= l(:label_refund_close_estimate) %></label> <%= checked_image @refund.estimate_closed? %></p>
|
||||
<% end %>
|
||||
<% if @refund.noted_issue_ids.any? %>
|
||||
<p><label><%= l(:label_refund_note_issues) %></label>
|
||||
<%= safe_join(Issue.where(id: @refund.noted_issue_ids).map { |issue| link_to_issue(issue, project: false) }, ', ') %></p>
|
||||
<% end %>
|
||||
<% if @refund.canceled_issue_ids.any? %>
|
||||
<p><label><%= l(:label_refund_cancel_issues) %></label>
|
||||
<%= safe_join(Issue.where(id: @refund.canceled_issue_ids).map { |issue| link_to_issue(issue, project: false) }, ', ') %></p>
|
||||
<% end %>
|
||||
<p>
|
||||
<label><%= l(:label_refund_email_customer) %></label> <%= @refund.emailed_to.presence || '—' %>
|
||||
<% if @refund.done? %>
|
||||
· <%= link_to sprite_icon('email', l(@refund.emailed_to.present? ? :button_refund_email_again : :button_refund_email)),
|
||||
email_qbo_refund_path(@refund), method: :post, class: 'icon icon-email',
|
||||
data: { confirm: l(:text_refund_email_confirm) } %>
|
||||
<% end %>
|
||||
</p>
|
||||
<p><label><%= l(:field_author) %></label> <%= @refund.user ? link_to_user(@refund.user) : '' %> <%= format_time(@refund.created_at) %></p>
|
||||
</div>
|
||||
@@ -2,7 +2,7 @@
|
||||
<% money = @report.money %>
|
||||
<% hours = @report.hours %>
|
||||
<% ratios = @report.ratios %>
|
||||
<% max_money = [money[:estimates][:total], money[:invoices][:total], money[:payments][:total]].max.to_f %>
|
||||
<% max_money = [money[:estimates][:total], money[:invoices][:total], money[:paid][:total], money[:payments][:total]].max.to_f %>
|
||||
<% max_hours = hours.values.max.to_f %>
|
||||
<% bar = ->(value, max) { max > 0 ? (value.to_f / max * 100).round(1) : 0 } %>
|
||||
<% fmt_hours = ->(h) { format('%.1f', h.to_f) } %>
|
||||
@@ -40,7 +40,12 @@
|
||||
end %>
|
||||
<% sales_series = chart_series.call([[:estimates, l(:label_report_estimates_written), '#628db6'],
|
||||
[:invoices, l(:label_report_invoices_written), '#e8a33d'],
|
||||
[:paid, l(:label_report_invoices_paid), '#c0504d'],
|
||||
[:payments, l(:label_report_payments_received), '#5aa05a']]) %>
|
||||
<% taxes = @report.taxes %>
|
||||
<% max_tax = taxes.values.map { |t| t[:total] }.max.to_f %>
|
||||
<% tax_series = chart_series.call([[:tax_invoiced, l(:label_report_tax_invoiced), '#e8a33d'],
|
||||
[:tax_collected, l(:label_report_tax_collected), '#c0504d']]) %>
|
||||
<% hours_series = chart_series.call([[:estimate_hours, l(:label_report_estimate_hours), '#628db6'],
|
||||
[:issue_hours, l(:label_report_issue_hours), '#9b7fc0'],
|
||||
[:invoice_hours, l(:label_report_invoice_hours), '#e8a33d'],
|
||||
@@ -132,7 +137,7 @@
|
||||
<table class="list qbo-report">
|
||||
<tbody>
|
||||
<% [[:estimates, l(:label_report_estimates_written)], [:invoices, l(:label_report_invoices_written)],
|
||||
[:payments, l(:label_report_payments_received)]].each do |key, label| %>
|
||||
[:paid, l(:label_report_invoices_paid)], [:payments, l(:label_report_payments_received)]].each do |key, label| %>
|
||||
<tr>
|
||||
<td class="name"><%= label %> <span class="count">(<%= money[key][:count] %>)</span></td>
|
||||
<td class="bar"><div class="qbo-bar qbo-bar-<%= key %>" style="width: <%= bar.call(money[key][:total], max_money) %>%"></div></td>
|
||||
@@ -146,6 +151,7 @@
|
||||
<%= l(:label_report_collected_of_invoiced) %>: <strong><%= pct.call(ratios[:collected_of_invoiced]) %></strong><br />
|
||||
<%= l(:label_report_open_balance) %>: <strong><%= number_to_currency(money[:invoices][:balance]) %></strong>
|
||||
</p>
|
||||
<p><em class="info"><%= l(:text_report_without_tax) %></em></p>
|
||||
</div>
|
||||
|
||||
<div class="splitcontentright">
|
||||
@@ -188,6 +194,7 @@
|
||||
<th class="month"><%= l(:label_month) %></th>
|
||||
<th><%= l(:label_report_estimates_written) %></th>
|
||||
<th><%= l(:label_report_invoices_written) %></th>
|
||||
<th><%= l(:label_report_invoices_paid) %></th>
|
||||
<th><%= l(:label_report_payments_received) %></th>
|
||||
<th class="hours-start"><%= l(:label_report_estimate_hours) %></th>
|
||||
<th><%= l(:label_report_issue_hours) %></th>
|
||||
@@ -202,6 +209,7 @@
|
||||
<td class="month"><%= ::I18n.t('date.abbr_month_names')[row[:month].month] %> <%= row[:month].year %></td>
|
||||
<td><%= number_to_currency(row[:estimates]) %></td>
|
||||
<td><%= number_to_currency(row[:invoices]) %></td>
|
||||
<td><%= number_to_currency(row[:paid]) %></td>
|
||||
<td><%= number_to_currency(row[:payments]) %></td>
|
||||
<td class="hours-start"><%= fmt_hours.call(row[:estimate_hours]) %></td>
|
||||
<td><%= fmt_hours.call(row[:issue_hours]) %></td>
|
||||
@@ -216,6 +224,7 @@
|
||||
<td class="month"><strong><%= l(:label_total) %></strong></td>
|
||||
<td><strong><%= number_to_currency(money[:estimates][:total]) %></strong></td>
|
||||
<td><strong><%= number_to_currency(money[:invoices][:total]) %></strong></td>
|
||||
<td><strong><%= number_to_currency(money[:paid][:total]) %></strong></td>
|
||||
<td><strong><%= number_to_currency(money[:payments][:total]) %></strong></td>
|
||||
<td class="hours-start"><strong><%= fmt_hours.call(hours[:estimate_hours]) %></strong></td>
|
||||
<td><strong><%= fmt_hours.call(hours[:issue_hours]) %></strong></td>
|
||||
@@ -226,6 +235,54 @@
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<h3><%= l(:label_report_taxes) %></h3>
|
||||
<div class="splitcontent">
|
||||
<div class="splitcontentleft">
|
||||
<div class="qbo-report-chart">
|
||||
<canvas id="qbo-chart-taxes" data-kind="money" data-series="<%= tax_series.to_json %>"></canvas>
|
||||
</div>
|
||||
<table class="list qbo-report">
|
||||
<tbody>
|
||||
<% [[:tax_invoiced, l(:label_report_tax_invoiced)], [:tax_collected, l(:label_report_tax_collected)]].each do |key, label| %>
|
||||
<tr>
|
||||
<td class="name"><%= label %> <span class="count">(<%= l(:label_report_taxed_invoices, count: taxes[key][:count]) %>)</span></td>
|
||||
<td class="bar"><div class="qbo-bar qbo-bar-<%= key %>" style="width: <%= bar.call(taxes[key][:total], max_tax) %>%"></div></td>
|
||||
<td class="value"><%= number_to_currency(taxes[key][:total]) %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
<p><em class="info"><%= l(:text_report_taxes) %></em></p>
|
||||
</div>
|
||||
<div class="splitcontentright">
|
||||
<table class="list qbo-report-months qbo-report-tax-months">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="month"><%= l(:label_month) %></th>
|
||||
<th><%= l(:label_report_tax_invoiced) %></th>
|
||||
<th><%= l(:label_report_tax_collected) %></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% @report.months.each do |row| %>
|
||||
<tr>
|
||||
<td class="month"><%= ::I18n.t('date.abbr_month_names')[row[:month].month] %> <%= row[:month].year %></td>
|
||||
<td><%= number_to_currency(row[:tax_invoiced]) %></td>
|
||||
<td><%= number_to_currency(row[:tax_collected]) %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr class="total">
|
||||
<td class="month"><strong><%= l(:label_total) %></strong></td>
|
||||
<td><strong><%= number_to_currency(taxes[:tax_invoiced][:total]) %></strong></td>
|
||||
<td><strong><%= number_to_currency(taxes[:tax_collected][:total]) %></strong></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="info"><%= l(:text_report_notes) %></p>
|
||||
|
||||
<style>
|
||||
@@ -237,6 +294,8 @@
|
||||
.qbo-bar { height: 14px; border-radius: 2px; min-width: 1px; background: #628db6; }
|
||||
.qbo-bar-invoices, .qbo-bar-invoice_hours { background: #e8a33d; }
|
||||
.qbo-bar-payments, .qbo-bar-spent_hours { background: #5aa05a; }
|
||||
.qbo-bar-paid, .qbo-bar-tax_collected { background: #c0504d; }
|
||||
.qbo-bar-tax_invoiced { background: #e8a33d; }
|
||||
.qbo-bar-issue_hours { background: #9b7fc0; }
|
||||
.qbo-report-ratios { margin: 8px 4px; line-height: 1.7; }
|
||||
.qbo-report-cpi { margin: 10px 4px 4px; }
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
function updateLink() {
|
||||
console.log("updateLink called");
|
||||
const linkElement = document.getElementById("appointment_link");
|
||||
const regex = /((?:<br\/>|%3Cbr\/?%3E))([\s\S]*?)(&dates)/gi;
|
||||
linkElement.href = linkElement.href.replace(regex, `$1${getSelectedDocs()}$3`);
|
||||
}
|
||||
|
||||
function getSelectedDocs() {
|
||||
const appointent_extras = document.querySelectorAll('.appointment');
|
||||
|
||||
let output = '';
|
||||
for (const item of appointent_extras) {
|
||||
if (item.checked) {
|
||||
console.log(`Checked item: ${item.dataset.text} with URL: ${item.dataset.url}`);
|
||||
output += `%0A`+ encodeURIComponent(`<a href="${window.location.origin}${item.dataset.url}">${item.dataset.text}</a>`) +`%0A`;
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
@@ -1,8 +1,3 @@
|
||||
/* Keep Redmine default look, just enhance metadata */
|
||||
.ui-autocomplete .autocomplete-meta {
|
||||
color: #888;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
/* Contextual links on their own line under the page title (customer and vehicle pages), where a long title and
|
||||
many links would otherwise crowd each other */
|
||||
#content .contextual.qbo-under-title {
|
||||
|
||||
+168
-28
@@ -29,14 +29,11 @@ en:
|
||||
field_invoice: "Invoice"
|
||||
field_notes: "Notes"
|
||||
label_account_balance: "Account Balance"
|
||||
label_actions: "Actions"
|
||||
label_amount: "Amount"
|
||||
label_appointment: "Add Appointment"
|
||||
label_balance_with_jobs: "Balance With Jobs"
|
||||
label_bill_time: "Bill Time"
|
||||
label_billing_address: "Billing Address"
|
||||
label_billing_enqueued: "Billing has been enqueued for issue"
|
||||
label_billed_success: "Successfully billed "
|
||||
label_client_id: "Intuit QBO OAuth2 Client ID"
|
||||
label_client_secret: "Intuit QBO OAuth2 Client Secret"
|
||||
label_closed_issues: "Closed Issues"
|
||||
@@ -45,23 +42,17 @@ en:
|
||||
label_customer_link_expires: "This customer link expires in"
|
||||
label_customer: "Customer"
|
||||
label_customers: "Customers"
|
||||
label_delete: "Delete"
|
||||
label_deposit_into: "Deposit to Account"
|
||||
label_details: "Details"
|
||||
label_display_name: "Display Name"
|
||||
label_door: "Door"
|
||||
label_edit: "Edit"
|
||||
label_edit_customer: "Edit Customer"
|
||||
label_email: "Email"
|
||||
label_error: "Error"
|
||||
label_estimate_404: "Estimate not found"
|
||||
label_estimate: "Estimate"
|
||||
label_estimates: "Estimates"
|
||||
label_hours: "Hours"
|
||||
label_invoice_404: "Invoice not found"
|
||||
label_invoices: "Invoices"
|
||||
label_last_sync: "Last Sync"
|
||||
label_load_customer: "Load Customer"
|
||||
label_make: "Make"
|
||||
label_matching: "Matching"
|
||||
label_mobile_phone: "Mobile Phone"
|
||||
@@ -74,13 +65,9 @@ en:
|
||||
text_customers_best_match: "%{count} best matches, closest first. Click a column to sort them by it instead."
|
||||
label_no_estimates: "No Estimates"
|
||||
label_no_invoices: "No Invoices"
|
||||
label_oauth2_refresh_token_expires_at: "Refresh Token Expires At"
|
||||
label_oauth_expires: "OAuth2 Access Token Expires At"
|
||||
label_oauth_note: "Note: You need to authenticate with QuickBooks after saving your key and secret above."
|
||||
label_open_issues: "Open Issues"
|
||||
label_primary_phone: "Primary Phone"
|
||||
label_qbo_sync_success: "Successfully synced to QuickBooks"
|
||||
label_redmine_qbo: "Redmine QuickBooks"
|
||||
label_sandbox: "Sandbox"
|
||||
label_search: "Search"
|
||||
label_search_customers: "Search Customers"
|
||||
@@ -97,23 +84,11 @@ en:
|
||||
notice_billing_error_no_customer: "Cannot bill without an assigned customer."
|
||||
notice_billing_error_no_employee: "Cannot bill without an assigned employee."
|
||||
notice_billing_error_no_qbo: "Cannot bill without a QuickBooks connection. Please connect to QuickBooks and try again."
|
||||
notice_customer_created: "Customer created in QuickBooks"
|
||||
notice_customer_deleted: "Customer deleted in QuickBooks"
|
||||
notice_customer_not_deleted: "Customer could not be deleted in QuickBooks"
|
||||
notice_customer_not_found: "Customer not found in QuickBooks"
|
||||
notice_customer_updated: "Customer updated in QuickBooks"
|
||||
notice_error_issue_not_found: "The issue could not be found. Please check the issue and try again."
|
||||
notice_error_project_nil: "The issue's project is nil. Set project to:"
|
||||
notice_error_tracker_nil: "The issue's tracker is nil. Set tracker to:"
|
||||
notice_estimate_created: "Estimate created in QuickBooks"
|
||||
notice_estimate_not_found: "Estimate not found, we are syncing with QuickBooks to find it. Please check back shortly."
|
||||
notice_estimate_updated: "Estimate updated in QuickBooks"
|
||||
notice_forbidden: "You do not have permission to access this resource."
|
||||
notice_invoice_created: "Invoice created in QuickBooks"
|
||||
notice_invoice_not_found: "Invoice not found"
|
||||
notice_invoice_updated: "Invoice updated in QuickBooks"
|
||||
notice_issue_not_found: "Issue not found"
|
||||
warn_ru_sure: "Are you sure?"
|
||||
|
||||
# ---- Billing: estimates, invoices, payments, items and accounts ----
|
||||
label_billing_settings: "Billing"
|
||||
@@ -124,6 +99,7 @@ en:
|
||||
permission_send_invoices: "Email invoices"
|
||||
permission_edit_partially_paid_invoices: "Edit partially paid invoices"
|
||||
permission_edit_paid_invoices: "Edit paid invoices"
|
||||
permission_edit_linked_estimates: "Edit estimates linked to issues"
|
||||
error_invoice_paid_not_allowed: "You're not allowed to change invoices with this much paid on them"
|
||||
permission_create_estimate_issues: "Create issues from estimates"
|
||||
permission_receive_payments: "Receive payments"
|
||||
@@ -194,6 +170,10 @@ en:
|
||||
error_discount_too_large: "The discount can't be more than the subtotal"
|
||||
error_invoice_below_paid: "The invoice total (about %{total} with tax) can't be less than the %{paid} already paid on it"
|
||||
button_unlock_invoice: "Unlock to edit"
|
||||
button_unlock_estimate: "Unlock to edit"
|
||||
text_unlock_estimate_confirmation: "This estimate is linked to an issue. Unlock it to make changes? The issues stay linked to it."
|
||||
text_estimate_unlocked: "Unlocked: this estimate is linked to these issues, and they stay linked when you save:"
|
||||
error_estimate_linked_not_allowed: "You're not allowed to change an estimate linked to an issue."
|
||||
text_unlock_invoice_confirmation: "A payment has been applied to this invoice. Unlock it to make changes, such as a discount? The payment stays applied, and the total can't go below what's been paid."
|
||||
text_invoice_unlocked: "Unlocked: %{paid} has been paid on this invoice. The payment stays applied when you save, and the total can't go below it."
|
||||
label_drag_to_reorder: "Drag to reorder"
|
||||
@@ -247,7 +227,6 @@ en:
|
||||
label_default_account: "Default Item Income Account"
|
||||
label_description: "Description"
|
||||
label_edit_item: "Edit Item"
|
||||
label_item: "Item"
|
||||
label_item_new: "New Item"
|
||||
label_items: "Items"
|
||||
label_management_and_sync: "Synchronization"
|
||||
@@ -261,9 +240,7 @@ en:
|
||||
text_qbo_sync_info: "Sync changes reads what changed in QuickBooks since the last sync; Full sync and each type's Sync re-read every record (e.g. after changing the labor products/services, sync estimates and invoices). Webhooks keep things current in between."
|
||||
text_default_account_info: "New products/services go in this income account; set it on the Accounts page."
|
||||
label_never_synced: "Never synced"
|
||||
label_no: "No"
|
||||
label_type: "Type"
|
||||
label_yes: "Yes"
|
||||
error_default_account_not_selected: "Select an account to make it the default."
|
||||
notice_default_account_updated: "Default account updated."
|
||||
|
||||
@@ -289,6 +266,9 @@ en:
|
||||
label_invoice_date: "Invoice date"
|
||||
label_invoice_no: "Invoice no."
|
||||
label_invoice_status_paid: "Paid"
|
||||
label_invoice_status_paid_on: "Paid %{date}"
|
||||
label_invoice_status_paid_days: "Paid +%{days}d"
|
||||
text_invoice_paid_in_full: "Paid in full %{date}"
|
||||
label_invoice_status_partial: "Partially paid"
|
||||
label_invoice_status_overdue: "Overdue"
|
||||
label_invoice_status_open: "Open"
|
||||
@@ -383,6 +363,15 @@ en:
|
||||
label_report_last_year: "last year"
|
||||
label_report_estimates_written: "Estimates written"
|
||||
label_report_invoices_written: "Invoices written"
|
||||
label_report_invoices_paid: "Invoices paid in full"
|
||||
label_report_taxes: "Sales tax"
|
||||
label_report_tax_invoiced: "Tax invoiced"
|
||||
label_report_tax_collected: "Tax collected"
|
||||
label_report_taxed_invoices:
|
||||
one: "1 invoice"
|
||||
other: "%{count} invoices"
|
||||
text_report_taxes: "Tax invoiced is the sales tax on invoices dated in the period (accrual); tax collected is the sales tax on invoices paid in full in the period (cash), counted on the day each was paid in full. Sales receipts and refunds aren't included: file from QuickBooks' Sales Tax Liability report."
|
||||
text_report_without_tax: "Estimates and invoices are without sales tax; invoices paid in full count on the day they were paid in full. Payments are as received, so collected vs. invoiced compares them with the invoices' totals with tax."
|
||||
label_report_payments_received: "Payments received"
|
||||
label_report_estimate_hours: "Estimated (estimates)"
|
||||
label_report_issue_hours: "Estimated (issues)"
|
||||
@@ -422,3 +411,154 @@ en:
|
||||
label_activity_payment: "Payment from %{customer}: %{amount}"
|
||||
text_activity_invoice_owed: "%{amount} owed"
|
||||
text_activity_payment_unapplied: "%{amount} not applied to an invoice"
|
||||
|
||||
# ---- Refunds (SOP-OPS-014) ----
|
||||
permission_issue_refunds: "Issue refunds"
|
||||
label_refund: "Refund"
|
||||
label_refunds: "Refunds"
|
||||
label_refund_incomplete: "Incomplete"
|
||||
label_refund_estimate: "Canceled order"
|
||||
label_refund_no_estimate: "None (customer credit only)"
|
||||
label_refund_your_order: "your order"
|
||||
label_refund_parts: "Parts"
|
||||
label_refund_method: "Refund by"
|
||||
label_refund_method_check: "Company check"
|
||||
label_refund_method_card: "Card (on the terminal)"
|
||||
label_refund_check_number: "Check no."
|
||||
label_refund_date: "Refund date"
|
||||
label_refund_reason: "Reason"
|
||||
label_refund_also: "Also"
|
||||
label_refund_close_estimate: "Mark the estimate Rejected in QuickBooks"
|
||||
label_refund_cancel_issues: "Cancel the order's work orders"
|
||||
label_refund_email_customer: "Email the customer a summary"
|
||||
label_refund_summary: "Refund"
|
||||
label_refund_credit_from: "Credit from payment"
|
||||
label_refund_credit: "Customer credit"
|
||||
label_refund_fee_rate: "Restocking fee (%{rate}% of parts)"
|
||||
label_refund_amount: "Refund"
|
||||
label_refund_fee_invoice: "Invoice #%{number}"
|
||||
label_refund_open_check: "Check in QuickBooks"
|
||||
label_refund_open_expense: "Expense in QuickBooks"
|
||||
label_refund_settings: "Refunds"
|
||||
label_refund_balance_after: "Customer balance afterwards"
|
||||
label_refund_recorded_by: "Recorded by"
|
||||
label_refund_received_by: "Received by (customer signature)"
|
||||
label_refund_fee_invoice_pdf: "Fee invoice PDF"
|
||||
label_refund_pdf_fee: "Restocking fee: %{rate}% × %{parts} parts"
|
||||
label_refund_pdf_work_orders: "Work orders canceled"
|
||||
label_refund_pdf_estimate: "Estimate"
|
||||
text_refund_pdf_estimate_rejected: "E%{number} marked Rejected in QuickBooks"
|
||||
label_restocking_fee_rate: "Restocking fee"
|
||||
label_restocking_item: "Restocking fee product/service"
|
||||
label_refund_check_account: "Refund checks from"
|
||||
label_refund_card_account: "Card refunds from"
|
||||
label_refund_first_bank_account: "The first bank account"
|
||||
label_refund_canceled_status: "Canceled work order status"
|
||||
button_refund: "Refund"
|
||||
button_refund_email: "Email the customer"
|
||||
button_refund_email_again: "Email again"
|
||||
|
||||
notice_refund_emailed: "Refund summary emailed to %{email}."
|
||||
notice_refund_done: "Refund of %{amount} recorded in QuickBooks."
|
||||
|
||||
error_refund_method: "Choose how the refund is paid: company check or card."
|
||||
error_refund_check_number: "Enter the check number."
|
||||
error_refund_reason: "Enter the reason for the refund."
|
||||
error_refund_parts_amount: "Parts must be an amount of $0.00 or more."
|
||||
error_refund_estimate_customer: "That estimate is for another customer."
|
||||
error_refund_no_fee_item: "Pick the restocking fee product/service in the QuickBooks plugin settings (Billing » Refunds)."
|
||||
error_refund_no_credit: "This customer has no credit (unapplied payments) to refund."
|
||||
error_refund_fee_over_credit: "The restocking fee (%{fee}) isn't less than the customer's credit (%{credit}), so there's nothing to refund."
|
||||
error_refund_no_ar_account: "QuickBooks has no Accounts Receivable account."
|
||||
error_refund_no_bank_account: "QuickBooks has no bank account to record the refund from. Pick one in the plugin settings."
|
||||
error_refund_fee_not_saved: "QuickBooks didn't save the restocking fee invoice."
|
||||
error_refund_fee_unpaid: "The customer's credit didn't cover the restocking fee invoice (%{amount} still open)."
|
||||
error_refund_nothing_left: "No credit is left to refund after the restocking fee."
|
||||
error_refund_not_saved: "QuickBooks didn't save the refund."
|
||||
error_refund_step_fee: "The restocking fee invoice couldn't be made or paid from the customer's credit: %{error}. Nothing was refunded. Finish or undo it in QuickBooks."
|
||||
error_refund_step_refund: "The refund couldn't be recorded in QuickBooks: %{error}. The restocking fee invoice (if any) is made. Record the refund in QuickBooks (Check or Expense, category Accounts Receivable) and apply the customer's credit to it."
|
||||
|
||||
text_refund_final_sale: "Custom fabricated assemblies and discontinued or closeout items are final sale. Don't refund them without Shop Manager approval (SOP-OPS-014). No cash refunds: card payments are refunded on the terminal, everything else by company check."
|
||||
text_refund_no_credit: "This customer has no credit (unapplied payments) to refund."
|
||||
text_refund_estimate: "The order being canceled. Its parts fill in the restocking fee, and the refund refers to it."
|
||||
text_refund_parts: "The parts returned or canceled, before tax. The restocking fee is %{rate}% of this; labor carries no fee. Enter 0 to refund without a fee."
|
||||
text_refund_method: "The way the order was paid: card payments are refunded on the card terminal (a partial refund, of the amount below); cash and check payments by company check."
|
||||
text_refund_reason: "Goes on the refund in QuickBooks and on the canceled work orders."
|
||||
text_refund_summary: "The restocking fee invoice is paid from the customer's credit, and the rest is refunded. Refund exactly this amount on the terminal or check."
|
||||
text_refund_email_confirm: "Email the customer this refund's summary?"
|
||||
text_refund_confirm: "Make the restocking fee invoice and record the refund in QuickBooks?"
|
||||
text_refund_no_email: "The customer has no email in QuickBooks."
|
||||
text_refund_balance: "Done. The customer's QuickBooks balance is now %{balance}."
|
||||
text_refund_balance_unknown: "Done, but the customer's QuickBooks balance couldn't be read. Check it's $0.00 in QuickBooks."
|
||||
text_refund_incomplete: "This refund is incomplete. See below which step failed, and finish it in QuickBooks."
|
||||
text_refund_fee_line: "Restocking fee: %{rate}% × %{parts} parts%{on} = %{fee}"
|
||||
text_refund_line: "Refund for deposit on E%{number}"
|
||||
text_refund_line_credit: "Refund of customer credit"
|
||||
text_refund_line_card: "(card refund on the terminal)"
|
||||
text_refund_private_note: "Refund made in Redmine (SOP-OPS-014). Reason: %{reason}"
|
||||
text_refund_issue_note: "Order canceled and refunded: %{reason}. Restocking fee %{fee}, refunded %{refund} by %{method}."
|
||||
text_refund_issues_not_canceled: "Some work orders couldn't be set to canceled: %{issues}"
|
||||
text_refund_no_canceled_status: "The work orders weren't canceled: pick the canceled status in the plugin settings."
|
||||
text_refund_estimate_not_closed: "The estimate couldn't be marked Rejected in QuickBooks: %{error}"
|
||||
text_refund_email_failed: "The customer wasn't emailed: %{error}"
|
||||
text_refund_email_off: "Redmine's email delivery is turned off."
|
||||
text_refund_email_subject: "Your refund from %{shop}: %{amount}"
|
||||
text_refund_email_greeting: "Hello %{name},"
|
||||
text_refund_email_intro: "We've processed the refund for %{order}."
|
||||
text_refund_email_check: "It's being paid by company check (no. %{number})."
|
||||
text_refund_email_card: "It's been refunded to the card you paid with. It can take a few business days to show on your statement."
|
||||
text_refund_email_terms: "As in our posted terms, returned and canceled parts carry a restocking fee. Labor that wasn't done isn't charged."
|
||||
text_restocking_fee_rate: "Of the parts returned or canceled (SOP-OPS-014: 30%)."
|
||||
text_restocking_item: "The QuickBooks product/service on the restocking fee invoice (e.g. \"Restocking Fee\"). It sets the income account the fee is booked to."
|
||||
text_refund_check_account: "The bank account refund checks are written from."
|
||||
text_refund_card_account: "The account card refunds come out of (where card payments are deposited)."
|
||||
text_refund_canceled_status: "Work orders of a canceled order are set to this status, with the reason as a note."
|
||||
|
||||
# Refunds of paid invoices: completed work, billed and paid in full (a QuickBooks Refund Receipt)
|
||||
label_refund_invoice: "Invoice"
|
||||
label_refund_invoice_number: "Invoice #%{number}"
|
||||
label_refund_paid_invoice: "Paid invoice"
|
||||
label_refund_invoice_lines: "Invoice #%{number} · %{date}"
|
||||
label_refund_line: "Line"
|
||||
label_refund_line_billed: "Billed"
|
||||
label_refund_line_refunded: "Refunded before"
|
||||
label_refund_line_quantity: "Qty to refund"
|
||||
label_refund_line_amount: "Amount to refund"
|
||||
label_refund_labor: "Labor"
|
||||
label_refund_taxable: "Taxable"
|
||||
label_refund_charge_fee: "Restocking fee"
|
||||
label_refund_note_issues: "Note the refund on the invoice's work orders"
|
||||
label_refund_lines_amount: "Lines refunded"
|
||||
label_refund_discount: "Invoice discount (its share)"
|
||||
label_refund_tax_estimate: "Sales tax (estimated)"
|
||||
label_refund_tax: "Sales tax"
|
||||
label_refund_fee_on_parts: "Restocking fee on parts"
|
||||
label_refund_paid_on_invoice: "paid"
|
||||
label_refund_no_fee: "None"
|
||||
label_refund_open_receipt: "Refund receipt in QuickBooks"
|
||||
label_refund_receipt: "Refund receipt"
|
||||
text_refund_paid_invoice: "Completed work that's billed and paid in full: open its invoice to refund some or all of it (a refund receipt in QuickBooks). The rest of this page refunds customer credit, e.g. a canceled order's deposit."
|
||||
text_refund_invoice_lines: "Tick the lines to refund. Change the quantity (parts returned) or the amount (a partial refund) as needed; a line can't be refunded for more than was billed, less what earlier refunds took."
|
||||
text_refund_line_done: "Already refunded"
|
||||
text_refund_charge_fee: "Charged on the parts refunded only; labor carries no fee. Leave it off when the parts aren't coming back, or there are none."
|
||||
text_refund_invoice_reason: "Goes on the refund receipt in QuickBooks and on the invoice's work orders."
|
||||
text_refund_invoice_summary: "QuickBooks works out the sales tax on the refund receipt, so the refund can differ from this estimate by a few cents. The refund's page shows the exact amount to refund on the terminal or check."
|
||||
text_refund_invoice_confirm: "Record this refund receipt in QuickBooks?"
|
||||
text_refund_invoice_earlier: "This invoice has been refunded before:"
|
||||
text_refund_receipt_made: "Done. Refund receipt %{number} is recorded in QuickBooks. Refund exactly the amount below."
|
||||
text_refund_receipt_number: "No. %{number}"
|
||||
text_refund_receipt_memo: "Refund for invoice #%{number}"
|
||||
text_refund_invoice_private_note: "Refund of invoice #%{number} made in Redmine (SOP-OPS-014). Reason: %{reason}"
|
||||
text_refund_invoice_issue_note: "Refunded %{amount} on invoice #%{number} by %{method}: %{reason}"
|
||||
text_refund_issues_not_noted: "The refund couldn't be noted on some work orders: %{issues}"
|
||||
text_refund_email_terms_invoice: "As in our posted terms, returned parts carry a restocking fee."
|
||||
error_refund_no_invoice: "Pick the invoice to refund."
|
||||
error_refund_no_lines: "Tick at least one line to refund."
|
||||
error_refund_line_gone: "A line to refund isn't on the invoice any more. Reload the page."
|
||||
error_refund_line_quantity: "%{line}: the quantity must be more than 0 and no more than %{quantity}."
|
||||
error_refund_line_amount: "%{line}: enter an amount to refund of more than $0.00."
|
||||
error_refund_line_over: "%{line}: no more than %{amount} is left to refund."
|
||||
error_refund_fee_over_lines: "The restocking fee (%{fee}) isn't less than what's refunded (%{amount})."
|
||||
error_refund_invoice_customer: "That invoice is for another customer."
|
||||
error_refund_invoice_not_paid: "Only an invoice that's paid in full can be refunded here. Take or refund the payment in QuickBooks."
|
||||
error_refund_step_receipt: "The refund receipt couldn't be recorded in QuickBooks: %{error}. Nothing was refunded."
|
||||
+14
-6
@@ -33,11 +33,7 @@ post 'bill/:id', to: 'qbo#bill', as: :bill
|
||||
get 'customers/view/:token', to: 'customers#view', as: :view
|
||||
get 'customers/share/:id', to: 'customers#share', as: :share
|
||||
|
||||
#java script routes
|
||||
get 'filter_estimates_by_customer' => 'customers#filter_estimates_by_customer'
|
||||
get 'filter_invoices_by_customer' => 'customers#filter_invoices_by_customer'
|
||||
|
||||
resources :customers do
|
||||
resources :customers, except: [:destroy] do
|
||||
collection do
|
||||
get :autocomplete
|
||||
get :sync
|
||||
@@ -71,6 +67,18 @@ end
|
||||
# Estimate and invoice drafts, kept in Redmine until they're saved to QuickBooks (continued on the editors)
|
||||
resources :qbo_drafts, only: [:index, :destroy]
|
||||
|
||||
# Customer refunds (SOP-OPS-014): /qbo_refunds/new?customer_id=
|
||||
resources :qbo_refunds, only: [:new, :create, :show] do
|
||||
member do
|
||||
get :pdf
|
||||
post :email
|
||||
end
|
||||
collection do
|
||||
get :new_invoice
|
||||
post :create_invoice
|
||||
end
|
||||
end
|
||||
|
||||
# Receive payment pages, and a customer's payments (/qbo_payments?customer_id=)
|
||||
resources :qbo_payments, only: [:index, :new, :create, :show, :edit, :update] do
|
||||
member do
|
||||
@@ -91,7 +99,7 @@ resources :items do
|
||||
end
|
||||
|
||||
# QuickBooks income accounts
|
||||
resources :accounts do
|
||||
resources :accounts, only: [:index] do
|
||||
collection do
|
||||
patch :set_default
|
||||
get :sync
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
#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.
|
||||
|
||||
# Customer refunds (SOP-OPS-014): the restocking fee invoice, the refund check or card refund, and what was
|
||||
# done in QuickBooks and Redmine, so a refund can be looked up (and finished by hand if a step failed)
|
||||
class CreateQboRefunds < ActiveRecord::Migration[7.0]
|
||||
def up
|
||||
return if table_exists?(:qbo_refunds)
|
||||
|
||||
create_table :qbo_refunds do |t|
|
||||
t.bigint :customer_id, null: false
|
||||
# The canceled order's estimate, if any
|
||||
t.bigint :estimate_id
|
||||
t.string :estimate_number
|
||||
t.integer :user_id
|
||||
t.date :txn_date
|
||||
# check or card
|
||||
t.string :method, null: false, limit: 10
|
||||
t.string :check_number
|
||||
t.text :reason
|
||||
t.decimal :parts_amount, precision: 15, scale: 2, null: false, default: 0
|
||||
t.decimal :fee_rate, precision: 6, scale: 2, null: false, default: 0
|
||||
t.decimal :fee_amount, precision: 15, scale: 2, null: false, default: 0
|
||||
# The customer's credit before the refund, and what was refunded
|
||||
t.decimal :credit_amount, precision: 15, scale: 2, null: false, default: 0
|
||||
t.decimal :refund_amount, precision: 15, scale: 2, null: false, default: 0
|
||||
# The QuickBooks fee invoice and the refund check or expense
|
||||
t.string :fee_invoice_id
|
||||
t.string :fee_invoice_number
|
||||
t.string :purchase_id
|
||||
# The customer's QuickBooks balance afterwards
|
||||
t.decimal :balance_after, precision: 15, scale: 2
|
||||
t.boolean :estimate_closed, null: false, default: false
|
||||
# The work orders set to canceled (JSON list of issue ids)
|
||||
t.text :canceled_issue_ids
|
||||
t.string :emailed_to
|
||||
# done, or incomplete (a step failed: message says which)
|
||||
t.string :status, null: false, default: 'incomplete', limit: 20
|
||||
t.text :message
|
||||
t.timestamps
|
||||
end
|
||||
add_index :qbo_refunds, :customer_id
|
||||
end
|
||||
|
||||
def down
|
||||
drop_table :qbo_refunds if table_exists?(:qbo_refunds)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,20 @@
|
||||
#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.
|
||||
|
||||
# An invoice's sales tax and the day it was paid in full, cached like its total and balance, so reports (e.g.
|
||||
# redmine_qbo_commission's monthly paid sales) don't have to read invoices from QuickBooks. A full invoice sync
|
||||
# fills them in for invoices synced before.
|
||||
class AddInvoiceTaxAndPaidOn < ActiveRecord::Migration[7.0]
|
||||
def change
|
||||
add_column :invoices, :tax_amount, :decimal, precision: 15, scale: 2 unless column_exists?(:invoices, :tax_amount)
|
||||
add_column :invoices, :paid_on, :date unless column_exists?(:invoices, :paid_on)
|
||||
add_index :invoices, :paid_on unless index_exists?(:invoices, :paid_on)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,17 @@
|
||||
#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.
|
||||
|
||||
# An estimate's sales tax, cached like its total, so the business report can compare estimates and invoices
|
||||
# without tax. A full estimate sync fills it in for estimates synced before.
|
||||
class AddEstimateTax < ActiveRecord::Migration[7.0]
|
||||
def change
|
||||
add_column :estimates, :tax_amount, :decimal, precision: 15, scale: 2 unless column_exists?(:estimates, :tax_amount)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,39 @@
|
||||
#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.
|
||||
|
||||
# Refunds of paid invoices (completed, billed and paid-in-full work): a QuickBooks Refund Receipt for the lines
|
||||
# refunded, with an optional restocking fee, alongside the refunds of customer credit (canceled orders)
|
||||
class AddInvoiceRefunds < ActiveRecord::Migration[7.0]
|
||||
def up
|
||||
# credit: a canceled order's deposit (fee invoice + check/expense); invoice: a paid invoice (refund receipt)
|
||||
add_column :qbo_refunds, :kind, :string, null: false, default: 'credit', limit: 10 unless column_exists?(:qbo_refunds, :kind)
|
||||
add_column :qbo_refunds, :invoice_id, :bigint unless column_exists?(:qbo_refunds, :invoice_id)
|
||||
add_column :qbo_refunds, :invoice_number, :string unless column_exists?(:qbo_refunds, :invoice_number)
|
||||
# The Refund Receipt's number (its id is purchase_id)
|
||||
add_column :qbo_refunds, :receipt_number, :string unless column_exists?(:qbo_refunds, :receipt_number)
|
||||
# The refunded lines before the discount, fee and tax; the invoice discount's share; the tax refunded
|
||||
add_column :qbo_refunds, :lines_amount, :decimal, precision: 15, scale: 2, null: false, default: 0 unless column_exists?(:qbo_refunds, :lines_amount)
|
||||
add_column :qbo_refunds, :discount_amount, :decimal, precision: 15, scale: 2, null: false, default: 0 unless column_exists?(:qbo_refunds, :discount_amount)
|
||||
add_column :qbo_refunds, :tax_amount, :decimal, precision: 15, scale: 2, null: false, default: 0 unless column_exists?(:qbo_refunds, :tax_amount)
|
||||
# The lines refunded (JSON: key, description, quantity, amount, parts), so a line isn't refunded twice
|
||||
add_column :qbo_refunds, :refunded_lines, :text unless column_exists?(:qbo_refunds, :refunded_lines)
|
||||
# The work orders the refund was noted on (JSON list of issue ids)
|
||||
add_column :qbo_refunds, :noted_issue_ids, :text unless column_exists?(:qbo_refunds, :noted_issue_ids)
|
||||
add_index :qbo_refunds, :invoice_id unless index_exists?(:qbo_refunds, :invoice_id)
|
||||
end
|
||||
|
||||
def down
|
||||
remove_index :qbo_refunds, :invoice_id if index_exists?(:qbo_refunds, :invoice_id)
|
||||
%i[kind invoice_id invoice_number receipt_number lines_amount discount_amount tax_amount refunded_lines
|
||||
noted_issue_ids].each do |column|
|
||||
remove_column :qbo_refunds, column if column_exists?(:qbo_refunds, column)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -14,7 +14,7 @@ Redmine::Plugin.register :redmine_qbo do
|
||||
name 'Redmine QBO plugin'
|
||||
author 'Rick Barrette'
|
||||
description 'A pluging for Redmine to connect with QuickBooks Online: customers, time activities for billable hours when an issue is closed, and estimates, invoices and payments written in Redmine'
|
||||
version '2026.11.19'
|
||||
version '2026.11.26'
|
||||
url 'https://github.com/rickbarrette/redmine_qbo'
|
||||
author_url 'https://barrettefabrication.com'
|
||||
settings default: {empty: true}, partial: 'qbo/settings'
|
||||
@@ -28,9 +28,8 @@ Redmine::Plugin.register :redmine_qbo do
|
||||
TimeEntry.safe_attributes :billed
|
||||
|
||||
# Global Permissions
|
||||
# autocomplete and the filter_* actions feed the customer, estimate and invoice pickers on issue forms
|
||||
permission :view_customers, { customers: [:index, :show, :autocomplete,
|
||||
:filter_estimates_by_customer, :filter_invoices_by_customer] }, global: true
|
||||
# autocomplete feeds the customer pickers (issue forms, estimates, invoices, payments)
|
||||
permission :view_customers, { customers: [:index, :show, :autocomplete] }, global: true
|
||||
permission :add_customers, { customers: [:new, :create] }, global: true
|
||||
permission :edit_customers, { customers: [:edit, :update] }, global: true
|
||||
permission :share_issues_with_customers, { customers: [:share] }, global: true
|
||||
@@ -43,6 +42,8 @@ Redmine::Plugin.register :redmine_qbo do
|
||||
# Drafts (QboDraft): each user sees the drafts of the documents they may write
|
||||
permission :write_estimates, { qbo_estimates: [:new, :create, :edit, :update, :customer_info, :items],
|
||||
qbo_drafts: [:index, :destroy] }, global: true
|
||||
# Unlocking an estimate linked to an issue (on top of Write estimates); see RedmineQboBilling.linked_estimate_editor?
|
||||
permission :edit_linked_estimates, {}, global: true
|
||||
permission :send_estimates, { qbo_estimates: [:send_email] }, global: true
|
||||
permission :create_estimate_issues, { qbo_estimates: [:issues_preview, :create_issues] }, global: true
|
||||
permission :write_invoices, { qbo_invoices: [:new, :create, :edit, :update, :import_options],
|
||||
@@ -54,6 +55,9 @@ Redmine::Plugin.register :redmine_qbo do
|
||||
permission :view_payments, { qbo_payments: [:index, :show, :pdf] }, global: true
|
||||
permission :receive_payments, { qbo_payments: [:index, :new, :create, :show, :edit, :update, :pdf, :open_invoices],
|
||||
qbo_estimates: [:customer_info] }, global: true
|
||||
# Refunds for canceled orders, returned parts and paid invoices (SOP-OPS-014): restocking fee, refund check
|
||||
# or card refund
|
||||
permission :issue_refunds, { qbo_refunds: [:new, :create, :new_invoice, :create_invoice, :show, :pdf, :email] }, global: true
|
||||
permission :view_business_reports, { qbo_reports: [:index] }, global: true
|
||||
# The product/service list, accounts and their syncs are admin-only (see ItemsController, AccountsController)
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@ module RedmineQbo
|
||||
# Load the javascript to support the autocomplete forms
|
||||
def view_layouts_base_html_head(context = {})
|
||||
safe_join([
|
||||
javascript_include_tag( 'application.js', plugin: :redmine_qbo),
|
||||
javascript_include_tag( 'autocomplete.js', plugin: :redmine_qbo),
|
||||
javascript_include_tag( 'checkbox_controller.js', plugin: :redmine_qbo),
|
||||
stylesheet_link_tag( 'autocomplete', plugin: :redmine_qbo)
|
||||
|
||||
@@ -11,17 +11,45 @@
|
||||
module RedmineQbo
|
||||
module Patches
|
||||
module AttachmentsControllerPatch
|
||||
# Redmine's own access checks, which deny the anonymous viewer of a share link. Each one defers
|
||||
# to Redmine unless the session holds a customer share token for the issue the file belongs to.
|
||||
module CustomerTokenAccess
|
||||
private
|
||||
|
||||
def read_authorize
|
||||
valid_customer_token? || super
|
||||
end
|
||||
|
||||
def find_container
|
||||
return super unless customer_token_for_download_all?
|
||||
|
||||
@container = Issue.find(params[:object_id])
|
||||
@project = @container.project
|
||||
rescue ActiveRecord::RecordNotFound
|
||||
render_404
|
||||
end
|
||||
|
||||
def find_downloadable_attachments
|
||||
return super unless customer_token_for_download_all?
|
||||
|
||||
@attachments = @container.attachments.select(&:readable?)
|
||||
bulk_download_max_size = Setting.bulk_download_max_size.to_i.kilobytes
|
||||
if @attachments.sum(&:filesize) > bulk_download_max_size
|
||||
flash[:error] = l(:error_bulk_download_size_too_big, max_size: number_to_human_size(bulk_download_max_size.to_i))
|
||||
redirect_back_or_default(container_url, referer: true)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def self.apply
|
||||
AttachmentsController.prepend(CustomerTokenAccess)
|
||||
|
||||
AttachmentsController.class_eval do
|
||||
# 1. PREPEND: Must run before ANY of Redmine's ApplicationController filters
|
||||
# Must run before any of Redmine's ApplicationController filters
|
||||
prepend_before_action :load_customer_token
|
||||
|
||||
# 2. Skip global login redirects if the user holds a valid token for this file
|
||||
# Skip the login redirect if the session holds a valid token for this file
|
||||
skip_before_action :check_if_login_required, if: :valid_customer_token?
|
||||
skip_before_action :check_project_privacy, raise: false, if: :valid_customer_token?
|
||||
|
||||
# Note: We do NOT need to skip :read_authorize anymore.
|
||||
# Because we patched Attachment#visible?, read_authorize will pass naturally!
|
||||
|
||||
private
|
||||
|
||||
@@ -31,33 +59,32 @@ module RedmineQbo
|
||||
@customer_token = session[:token].present? ? CustomerToken.active.find_by(token: session[:token]) : nil
|
||||
end
|
||||
|
||||
def customer_token_for_download_all?
|
||||
@customer_token.present? && params[:action] == 'download_all' &&
|
||||
params[:object_type] == 'issues' && params[:object_id].to_i == @customer_token.issue_id
|
||||
end
|
||||
|
||||
def valid_customer_token?
|
||||
token = @customer_token
|
||||
return false unless token
|
||||
return customer_token_for_download_all? if params[:action] == 'download_all'
|
||||
return false unless %w[show download thumbnail].include?(params[:action])
|
||||
|
||||
# Handle "Download All" zip requests (object_type=issues, object_id=ID)
|
||||
if params[:action] == 'download_all'
|
||||
return params[:object_type] == 'issues' && params[:object_id].to_i == token.issue_id
|
||||
end
|
||||
|
||||
# Handle normal single attachment requests (show, download, thumbnail)
|
||||
attachment = Attachment.find_by(id: params[:id])
|
||||
return false unless attachment
|
||||
|
||||
# Allow if attachment belongs directly to the Issue
|
||||
if attachment.container_type == 'Issue' && attachment.container_id == token.issue_id
|
||||
return true
|
||||
case attachment.container_type
|
||||
when 'Issue'
|
||||
attachment.container_id == token.issue_id
|
||||
when 'Journal'
|
||||
journal = attachment.container
|
||||
journal&.journalized_type == 'Issue' && journal.journalized_id == token.issue_id && !journal.private_notes?
|
||||
else
|
||||
false
|
||||
end
|
||||
|
||||
# Allow if attachment belongs to a Journal (comment) on the Issue
|
||||
if attachment.container_type == 'Journal' && attachment.container.journalized_type == 'Issue' && attachment.container.journalized_id == token.issue_id
|
||||
return true
|
||||
end
|
||||
|
||||
false
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -15,7 +15,6 @@ module RedmineQbo
|
||||
|
||||
prepended do
|
||||
belongs_to :customer
|
||||
belongs_to :customer_token
|
||||
belongs_to :estimate
|
||||
has_and_belongs_to_many :invoices
|
||||
|
||||
|
||||
@@ -325,7 +325,8 @@ module RedmineQbo
|
||||
if issue.estimate
|
||||
e_pdf, _ref = PdfService.new(entity: Estimate).fetch_pdf(doc_ids: [issue.estimate.id])
|
||||
combined = CombinePDF.parse(pdf.output, allow_optional_content: true)
|
||||
combined << CombinePDF.parse(e_pdf)
|
||||
# The estimate may have optional content too (layers); merged the same way as the issue's PDF
|
||||
combined << CombinePDF.parse(e_pdf, allow_optional_content: true)
|
||||
combined.to_pdf
|
||||
else
|
||||
pdf.output
|
||||
|
||||
@@ -83,11 +83,35 @@ module RedmineQboBilling
|
||||
user.allowed_to?(:receive_payments, nil, global: true)
|
||||
end
|
||||
|
||||
# True when the user may refund customers' credit (SOP-OPS-014)
|
||||
def self.refunder?(user = User.current)
|
||||
user.allowed_to?(:issue_refunds, nil, global: true)
|
||||
end
|
||||
|
||||
# True when the user may see customer payments (receiving them includes seeing them)
|
||||
def self.payment_viewer?(user = User.current)
|
||||
user.allowed_to?(:view_payments, nil, global: true) || payment_receiver?(user)
|
||||
end
|
||||
|
||||
# True when the user may unlock and change an estimate linked to an issue (e.g. a customer asks for changes to
|
||||
# an estimate already on the diagnostic work order): "Edit estimates linked to issues" on top of "Write estimates"
|
||||
def self.linked_estimate_editor?(user = User.current)
|
||||
writer?(user) && user.allowed_to?(:edit_linked_estimates, nil, global: true)
|
||||
end
|
||||
|
||||
# True when the user may open any estimate's PDF: View customers or Write estimates. Others open only the
|
||||
# estimates attached to issues they can see (see AuthHelper#estimate_pdf_allowed?).
|
||||
def self.estimate_viewer?(user = User.current)
|
||||
user.allowed_to?(:view_customers, nil, global: true) || writer?(user)
|
||||
end
|
||||
|
||||
# True when the user may open any invoice's PDF: View customers, Write invoices, View or Receive payments, or
|
||||
# Issue refunds (those pages link to invoices). Others open only the invoices attached to issues they can see.
|
||||
def self.invoice_viewer?(user = User.current)
|
||||
user.allowed_to?(:view_customers, nil, global: true) || invoice_writer?(user) || payment_viewer?(user) ||
|
||||
refunder?(user)
|
||||
end
|
||||
|
||||
# True when the user may write invoices
|
||||
def self.invoice_writer?(user = User.current)
|
||||
user.allowed_to?(:write_invoices, nil, global: true)
|
||||
|
||||
@@ -12,7 +12,9 @@
|
||||
module RedmineQboBilling
|
||||
# Business figures for a date range, from the estimates, invoices and payments cached from QuickBooks and from
|
||||
# Redmine's issues and spent time:
|
||||
# money: estimates written, invoices written, payments received (totals and counts)
|
||||
# money: estimates written, invoices written, invoices paid in full, payments received (totals and counts);
|
||||
# estimates and invoices without sales tax (it isn't the shop's revenue), payments as received
|
||||
# taxes: sales tax on invoices written (by their date) and on invoices paid in full (by that day)
|
||||
# hours: man-hours on estimates, issues' estimated time, man-hours invoiced, time spent
|
||||
# with a month-by-month breakdown. Estimates, invoices and payments count by their QuickBooks date, issues by
|
||||
# the day they were created (only issues without subtasks, so parents' totals aren't counted twice), and
|
||||
@@ -24,8 +26,9 @@ module RedmineQboBilling
|
||||
# Chart points: a day each for up to two weeks, a week each up to about three months, else a month each
|
||||
DAILY_UP_TO = 14
|
||||
WEEKLY_UP_TO = 93
|
||||
MONEY = %i[estimates invoices payments].freeze
|
||||
MONEY = %i[estimates invoices paid payments].freeze
|
||||
HOURS = %i[estimate_hours issue_hours invoice_hours spent_hours].freeze
|
||||
TAXES = %i[tax_invoiced tax_collected].freeze
|
||||
|
||||
attr_reader :from, :to, :period, :project_ids
|
||||
|
||||
@@ -54,8 +57,9 @@ module RedmineQboBilling
|
||||
nil
|
||||
end
|
||||
|
||||
# data (for tests): { estimates: [[date, total, hours]], invoices: [[date, total, hours, balance]],
|
||||
# payments: [[date, total]], issues: [[date, estimated_hours]], time_entries: [[date, hours]] }
|
||||
# data (for tests): { estimates: [[date, total, hours, tax]], invoices: [[date, total, hours, balance, tax]],
|
||||
# paid: [[paid_on, total, tax]], payments: [[date, total]], issues: [[date, estimated_hours]],
|
||||
# time_entries: [[date, hours]] }. Tax may be left off (none).
|
||||
# week_start: the first day of a week (:monday, :saturday or :sunday); see week_start_from_setting.
|
||||
# previous_data (for tests): last year's data, like data.
|
||||
# project_ids: the projects whose issues and spent time count; blank for every project.
|
||||
@@ -150,13 +154,45 @@ module RedmineQboBilling
|
||||
@data ||= load_data
|
||||
end
|
||||
|
||||
# { estimates: { total:, count: }, invoices: { total:, count:, balance: }, payments: { total:, count: } }
|
||||
# Where each money figure's rows are and how much each row counts: estimates, invoices and invoices paid in
|
||||
# full without their sales tax, payments as received
|
||||
MONEY_ROWS = {
|
||||
estimates: [:estimates, ->(r) { to_money(r[1]) - to_money(r[3]) }],
|
||||
invoices: [:invoices, ->(r) { to_money(r[1]) - to_money(r[4]) }],
|
||||
paid: [:paid, ->(r) { to_money(r[1]) - to_money(r[2]) }],
|
||||
payments: [:payments, ->(r) { to_money(r[1]) }]
|
||||
}.freeze
|
||||
|
||||
# Sales tax on invoices written (by their date) and on invoices paid in full (by that day)
|
||||
TAX_ROWS = {
|
||||
tax_invoiced: [:invoices, ->(r) { to_money(r[4]) }],
|
||||
tax_collected: [:paid, ->(r) { to_money(r[2]) }]
|
||||
}.freeze
|
||||
|
||||
def self.to_money(value)
|
||||
BigDecimal(value.to_s.presence || '0')
|
||||
rescue ArgumentError
|
||||
BigDecimal('0')
|
||||
end
|
||||
|
||||
# { estimates: { total:, count: }, invoices: { total:, count:, balance:, with_tax: }, paid: { total:, count: },
|
||||
# payments: { total:, count: } }. Invoices' balance (still owed) and with_tax are what the customers pay.
|
||||
def money
|
||||
@money ||= {
|
||||
estimates: { total: money_sum(data[:estimates], 1), count: data[:estimates].size },
|
||||
invoices: { total: money_sum(data[:invoices], 1), count: data[:invoices].size, balance: money_sum(data[:invoices], 3) },
|
||||
payments: { total: money_sum(data[:payments], 1), count: data[:payments].size }
|
||||
}
|
||||
@money ||= MONEY_ROWS.to_h do |key, (source, value)|
|
||||
rows = Array(data[source])
|
||||
[key, { total: rows.sum(BigDecimal('0')) { |r| value.call(r) }, count: rows.size }]
|
||||
end.tap do |figures|
|
||||
figures[:invoices][:balance] = money_sum(data[:invoices], 3)
|
||||
figures[:invoices][:with_tax] = money_sum(data[:invoices], 1)
|
||||
end
|
||||
end
|
||||
|
||||
# { tax_invoiced: { total:, count: }, tax_collected: { total:, count: } }: count is the invoices that had tax
|
||||
def taxes
|
||||
@taxes ||= TAX_ROWS.to_h do |key, (source, value)|
|
||||
amounts = Array(data[source]).map { |r| value.call(r) }
|
||||
[key, { total: amounts.sum(BigDecimal('0')), count: amounts.count(&:positive?) }]
|
||||
end
|
||||
end
|
||||
|
||||
# { estimate_hours:, issue_hours:, invoice_hours:, spent_hours: }
|
||||
@@ -193,7 +229,8 @@ module RedmineQboBilling
|
||||
def ratios
|
||||
{
|
||||
invoiced_of_estimated: percent(money[:invoices][:total], money[:estimates][:total]),
|
||||
collected_of_invoiced: percent(money[:payments][:total], money[:invoices][:total]),
|
||||
# Payments include sales tax, so they're compared with the invoices' totals with tax
|
||||
collected_of_invoiced: percent(money[:payments][:total], money[:invoices][:with_tax]),
|
||||
invoiced_of_spent: percent(hours[:invoice_hours], hours[:spent_hours]),
|
||||
spent_of_estimated: percent(hours[:spent_hours], hours[:issue_hours])
|
||||
}
|
||||
@@ -208,7 +245,7 @@ module RedmineQboBilling
|
||||
last = [to, @today].min
|
||||
last = from if last < from
|
||||
while month <= last
|
||||
rows << { month: month }.merge((MONEY + HOURS).index_with { |_| 0 })
|
||||
rows << { month: month }.merge((MONEY + HOURS + TAXES).index_with { |_| 0 })
|
||||
month = month.next_month
|
||||
end
|
||||
index = rows.index_by { |r| [r[:month].year, r[:month].month] }
|
||||
@@ -218,9 +255,12 @@ module RedmineQboBilling
|
||||
r[key] += kind == :money ? to_d(row[col]) : row[col].to_f
|
||||
end
|
||||
end
|
||||
add.call(data[:estimates], :estimates, 1, :money)
|
||||
add.call(data[:invoices], :invoices, 1, :money)
|
||||
add.call(data[:payments], :payments, 1, :money)
|
||||
MONEY_ROWS.merge(TAX_ROWS).each do |key, (source, value)|
|
||||
Array(data[source]).each do |row|
|
||||
r = index[[row[0].year, row[0].month]] or next
|
||||
r[key] += value.call(row)
|
||||
end
|
||||
end
|
||||
add.call(data[:estimates], :estimate_hours, 2, :hours)
|
||||
add.call(data[:issues], :issue_hours, 1, :hours)
|
||||
add.call(data[:invoices], :invoice_hours, 2, :hours)
|
||||
@@ -229,27 +269,33 @@ module RedmineQboBilling
|
||||
end
|
||||
end
|
||||
|
||||
# Estimates and invoices in the range that synced before totals and hours were cached (a full sync fills them)
|
||||
# Estimates and invoices in the range that synced before totals, hours and sales tax were cached (a full sync
|
||||
# fills them)
|
||||
def unsynced_count
|
||||
data[:estimates].count { |r| r[1].nil? || r[2].nil? } + data[:invoices].count { |r| r[1].nil? || r[2].nil? }
|
||||
data[:estimates].count { |r| r[1].nil? || r[2].nil? || (r.size > 3 && r[3].nil?) } +
|
||||
data[:invoices].count { |r| r[1].nil? || r[2].nil? || (r.size > 4 && r[4].nil?) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# { money key or hours key => [sum per bucket] } for the data, in buckets ([first day, last day] pairs)
|
||||
def sums_by_bucket(rows, bucket_list)
|
||||
sums = (MONEY + HOURS).index_with { |_| Array.new(bucket_list.size, 0.0) }
|
||||
sums = (MONEY + HOURS + TAXES).index_with { |_| Array.new(bucket_list.size, 0.0) }
|
||||
find = lambda do |date|
|
||||
bucket_list.index { |a, b| date >= a && date <= b }
|
||||
end
|
||||
columns = {
|
||||
estimates: [:estimates, 1], invoices: [:invoices, 1], payments: [:payments, 1],
|
||||
estimate_hours: [:estimates, 2], issue_hours: [:issues, 1], invoice_hours: [:invoices, 2], spent_hours: [:time_entries, 1]
|
||||
}
|
||||
MONEY_ROWS.merge(TAX_ROWS).each do |key, (source, value)|
|
||||
Array(rows[source]).each do |row|
|
||||
i = find.call(row[0]) or next
|
||||
sums[key][i] += value.call(row).to_f
|
||||
end
|
||||
end
|
||||
columns = { estimate_hours: [:estimates, 2], issue_hours: [:issues, 1], invoice_hours: [:invoices, 2],
|
||||
spent_hours: [:time_entries, 1] }
|
||||
columns.each do |key, (source, col)|
|
||||
Array(rows[source]).each do |row|
|
||||
i = find.call(row[0]) or next
|
||||
sums[key][i] += MONEY.include?(key) ? to_d(row[col]).to_f : row[col].to_f
|
||||
sums[key][i] += row[col].to_f
|
||||
end
|
||||
end
|
||||
sums.transform_values { |values| values.map { |v| v.round(2) } }
|
||||
@@ -266,8 +312,9 @@ module RedmineQboBilling
|
||||
time_entries = time_entries.where(project_id: project_ids)
|
||||
end
|
||||
{
|
||||
estimates: Estimate.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours),
|
||||
invoices: Invoice.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours, :balance),
|
||||
estimates: Estimate.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours, :tax_amount),
|
||||
invoices: Invoice.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours, :balance, :tax_amount),
|
||||
paid: Invoice.where(paid_on: dates).where('total_amount > 0').pluck(:paid_on, :total_amount, :tax_amount),
|
||||
payments: Payment.where(txn_date: dates).pluck(:txn_date, :total_amount),
|
||||
issues: issues.pluck(:created_on, :estimated_hours).map { |t, h| [t.in_time_zone.to_date, h] },
|
||||
time_entries: time_entries.pluck(:spent_on, :hours)
|
||||
|
||||
@@ -112,7 +112,8 @@ module RedmineQboBilling
|
||||
# (discount: the discount amount QuickBooks worked out when it was last saved)
|
||||
:billing_address, :total, :total_tax, :discount, :email_status, :txn_status, :duplicated_from,
|
||||
:balance, :converted_from,
|
||||
# Invoices: a paid invoice opened for editing anyway (Unlock), and the amount paid on it
|
||||
# Invoices: a paid invoice opened for editing anyway (Unlock), and the amount paid on it.
|
||||
# Estimates: an estimate linked to an issue opened for editing anyway (Unlock).
|
||||
:unlocked, :amount_paid,
|
||||
# Estimates: the invoices it's billed on ([[id, number], ...])
|
||||
:invoiced_on,
|
||||
|
||||
@@ -105,6 +105,13 @@ module RedmineQboBilling
|
||||
Issue.where(estimate_id: estimate_id.to_s)
|
||||
end
|
||||
|
||||
# An estimate linked to an issue is only changed when unlocked by a user allowed to
|
||||
def check_linked(form, unlock, user)
|
||||
return unless linked_issues(form.id).exists?
|
||||
raise Error, I18n.t(:error_estimate_linked_to_issues) unless unlock
|
||||
raise Error, I18n.t(:error_estimate_linked_not_allowed) unless RedmineQboBilling.linked_estimate_editor?(user)
|
||||
end
|
||||
|
||||
# Loads the estimate from QuickBooks for editing
|
||||
def load(id)
|
||||
remote = QboEstimateService.with_service { |service| service.fetch_by_id(id) }
|
||||
@@ -114,7 +121,9 @@ module RedmineQboBilling
|
||||
|
||||
# Creates or updates the estimate in QuickBooks and returns the saved QuickBooks estimate.
|
||||
# The sales person is the user who creates the estimate; editing keeps the original one.
|
||||
def save(form, user: User.current)
|
||||
# unlock: an estimate linked to an issue may be changed (the user unlocked it, see
|
||||
# RedmineQboBilling.linked_estimate_editor?)
|
||||
def save(form, user: User.current, unlock: false)
|
||||
customer = Customer.find_by(id: form.customer_id)
|
||||
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
|
||||
|
||||
@@ -125,7 +134,7 @@ module RedmineQboBilling
|
||||
raise Conflict, I18n.t(:error_estimate_changed_in_quickbooks) if remote.sync_token.to_s != form.sync_token.to_s
|
||||
raise Error, I18n.t(:error_estimate_billed) if billed?(remote)
|
||||
raise Error, I18n.t(:error_estimate_has_bundles) if group_lines?(remote)
|
||||
raise Error, I18n.t(:error_estimate_linked_to_issues) if linked_issues(form.id).any?
|
||||
check_linked(form, unlock, user)
|
||||
|
||||
estimate = Quickbooks::Model::Estimate.new
|
||||
estimate.id = remote.id
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboBilling
|
||||
# An invoice's sales tax and the day it was paid in full, worked out from the QuickBooks invoice when it's synced
|
||||
# (InvoiceSyncService).
|
||||
#
|
||||
# An invoice is paid in full on the later of its own date and the dates of the payments and credit memos applied
|
||||
# to it, so a deposit taken before the work counts on the day the job was invoiced. The payments' dates come from
|
||||
# the local payments (synced from QuickBooks); QuickBooks is only asked for the ones not synced yet and for credit
|
||||
# memos.
|
||||
module InvoicePaidOn
|
||||
APPLIED_TYPES = %w[Payment CreditMemo].freeze
|
||||
IDS_PER_QUERY = 100
|
||||
|
||||
module_function
|
||||
|
||||
def tax(remote)
|
||||
tax = remote.respond_to?(:txn_tax_detail) ? remote.txn_tax_detail&.total_tax : nil
|
||||
tax.nil? ? BigDecimal('0') : BigDecimal(tax.to_s)
|
||||
end
|
||||
|
||||
# The day the invoice was paid in full, or nil while it's open (or voided: a $0 total)
|
||||
def paid_on(remote, dates: nil)
|
||||
return nil unless remote.txn_date
|
||||
return nil unless BigDecimal(remote.balance.to_s.presence || '1').zero?
|
||||
return nil unless BigDecimal(remote.total.to_s.presence || '0').positive?
|
||||
|
||||
dates ||= applied_dates(applied(remote))
|
||||
[remote.txn_date, *applied(remote).map { |type, id| dates[[type, id]] }.compact].max
|
||||
end
|
||||
|
||||
# [["Payment", "123"], ...] applied to the invoice
|
||||
def applied(remote)
|
||||
Array(remote.linked_transactions).select { |link| APPLIED_TYPES.include?(link.txn_type.to_s) }
|
||||
.map { |link| [link.txn_type.to_s, link.txn_id.to_s] }
|
||||
end
|
||||
|
||||
# { ["Payment", "123"] => Date }: local payments first, the rest read from QuickBooks
|
||||
def applied_dates(links)
|
||||
dates = {}
|
||||
payment_ids = links.select { |type, _| type == 'Payment' }.map(&:last)
|
||||
Payment.where(id: payment_ids).pluck(:id, :txn_date).each { |id, date| dates[['Payment', id.to_s]] = date if date }
|
||||
missing = links.reject { |link| dates.key?(link) }
|
||||
missing.group_by(&:first).each do |type, list|
|
||||
list.map(&:last).uniq.each_slice(IDS_PER_QUERY) do |ids|
|
||||
query = "SELECT * FROM #{type} WHERE Id IN (#{ids.map { |id| "'#{id.gsub(/\D/, '')}'" }.join(',')})"
|
||||
records = QboConnectionService.with_qbo_service(entity: type) { |service| service.query(query).entries }
|
||||
Array(records).each { |record| dates[[type, record.id.to_s]] = record.txn_date }
|
||||
end
|
||||
end
|
||||
dates
|
||||
rescue StandardError => e
|
||||
Rails.logger.warn "[RedmineQboBilling] Could not read the dates of what was applied to an invoice: #{e.message}"
|
||||
dates
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,97 @@
|
||||
#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.
|
||||
|
||||
|
||||
module RedmineQboBilling
|
||||
# What the Refund invoice page posts: the paid invoice, the lines refunded (each with its quantity and
|
||||
# amount), whether a restocking fee is charged on the parts among them, how the money goes back (card terminal
|
||||
# or company check), and what else to do.
|
||||
class InvoiceRefundForm
|
||||
include ActiveModel::Model
|
||||
include ActiveModel::Validations
|
||||
|
||||
ATTRIBUTES = %i[customer_id invoice_id txn_date method check_number reason charge_fee note_issues
|
||||
email_customer].freeze
|
||||
FLAGS = %i[charge_fee note_issues email_customer].freeze
|
||||
|
||||
# One invoice line as posted: refund ticked, the quantity and the amount refunded
|
||||
LineChoice = Struct.new(:refund, :quantity, :amount, keyword_init: true) do
|
||||
def refund?
|
||||
refund.to_s == '1' || refund == true
|
||||
end
|
||||
|
||||
def quantity_value
|
||||
quantity.blank? ? nil : EstimateForm.decimal(quantity)
|
||||
end
|
||||
|
||||
def amount_value
|
||||
amount.blank? ? nil : EstimateForm.decimal(amount)
|
||||
end
|
||||
end
|
||||
|
||||
attr_accessor(*ATTRIBUTES)
|
||||
# { line key => LineChoice }
|
||||
attr_writer :lines
|
||||
|
||||
validate :validate_refund
|
||||
|
||||
# params: the refund's permitted params, lines as { key => { refund:, quantity:, amount: } }
|
||||
def self.from_params(params)
|
||||
params = params.to_h.stringify_keys
|
||||
form = new(ATTRIBUTES.to_h { |attr| [attr, params[attr.to_s].to_s.strip] })
|
||||
form.lines = (params['lines'] || {}).to_h.to_h do |key, line|
|
||||
line = line.to_h.stringify_keys
|
||||
[key.to_s, LineChoice.new(refund: line['refund'].to_s, quantity: line['quantity'].to_s.strip,
|
||||
amount: line['amount'].to_s.strip.delete('$,'))]
|
||||
end
|
||||
form
|
||||
end
|
||||
|
||||
def self.permitted
|
||||
ATTRIBUTES + [{ lines: {} }]
|
||||
end
|
||||
|
||||
def lines
|
||||
@lines ||= {}
|
||||
end
|
||||
|
||||
def line(key)
|
||||
lines[key.to_s]
|
||||
end
|
||||
|
||||
def chosen
|
||||
lines.select { |_, line| line.refund? }
|
||||
end
|
||||
|
||||
def txn_date_value
|
||||
EstimateForm.date(txn_date)
|
||||
end
|
||||
|
||||
def check?
|
||||
method == 'check'
|
||||
end
|
||||
|
||||
FLAGS.each do |flag|
|
||||
define_method(:"#{flag}?") { send(flag).to_s == '1' || send(flag) == true }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def validate_refund
|
||||
errors.add(:base, I18n.t(:error_estimate_needs_customer)) if customer_id.blank?
|
||||
errors.add(:base, I18n.t(:error_refund_no_invoice)) if invoice_id.blank?
|
||||
errors.add(:base, I18n.t(:error_refund_method)) unless QboRefund::METHODS.include?(method)
|
||||
errors.add(:base, I18n.t(:error_refund_check_number)) if check? && check_number.blank?
|
||||
errors.add(:base, I18n.t(:error_refund_reason)) if reason.blank?
|
||||
errors.add(:base, I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_refund_date))) if txn_date_value.nil?
|
||||
errors.add(:base, I18n.t(:error_refund_no_lines)) if chosen.empty?
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,348 @@
|
||||
#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.
|
||||
|
||||
|
||||
module RedmineQboBilling
|
||||
# Refunds of completed work: an invoice that's billed and paid in full (SOP-OPS-014 for the restocking fee).
|
||||
# QuickBooks' way to refund a paid sale is a Refund Receipt, which this makes:
|
||||
#
|
||||
# * the invoice lines refunded (all or part of each), with their product/service and tax code, so the income
|
||||
# and the sales tax come back off the books the way they went on (QuickBooks works out the tax);
|
||||
# * the invoice's discount, if it had one, in proportion to what's refunded;
|
||||
# * the restocking fee, when it's charged, as a negative line with the restocking fee product/service:
|
||||
# its rate (plugin setting) of the parts refunded. Labor carries no fee, and work with no parts has none;
|
||||
# * paid out of the refund check or card refund bank account in the settings, by company check (its number)
|
||||
# or a refund on the card terminal.
|
||||
#
|
||||
# The invoice itself stays as it is, paid. Each refund is recorded (QboRefund, kind invoice) with the lines it
|
||||
# refunded, so a line can't be refunded for more than it was billed across several refunds. Then, as asked on
|
||||
# the page, the refund is noted on the invoice's work orders and the customer is emailed a summary.
|
||||
module InvoiceRefundWriter
|
||||
Error = RefundWriter::Error
|
||||
|
||||
# An invoice line that can be refunded, with what earlier refunds already took of it
|
||||
Line = Struct.new(:key, :item_id, :item_name, :description, :quantity, :rate, :amount, :taxable, :parts,
|
||||
:refunded_quantity, :refunded_amount, keyword_init: true) do
|
||||
def remaining_amount
|
||||
[amount - refunded_amount, BigDecimal('0')].max
|
||||
end
|
||||
|
||||
def remaining_quantity
|
||||
quantity && [quantity - refunded_quantity, BigDecimal('0')].max
|
||||
end
|
||||
|
||||
def refundable?
|
||||
remaining_amount.positive?
|
||||
end
|
||||
|
||||
def label
|
||||
[item_name.presence, description.presence].compact.uniq.join(' · ')
|
||||
end
|
||||
end
|
||||
|
||||
# A line being refunded: the invoice line, the quantity (nil when only an amount is refunded) and the amount
|
||||
Refunding = Struct.new(:line, :quantity, :amount, keyword_init: true)
|
||||
|
||||
# What a refund comes to: the lines, the invoice discount's share, the fee, the tax (estimated before
|
||||
# QuickBooks works it out) and the refund
|
||||
Plan = Struct.new(:refunding, :lines_amount, :parts_amount, :discount_rate, :discount, :fee_rate, :fee,
|
||||
:tax_rate, :tax, :refund, keyword_init: true)
|
||||
|
||||
module_function
|
||||
|
||||
def settings
|
||||
RefundWriter.settings
|
||||
end
|
||||
|
||||
# Billed and paid in full: a total, and nothing left owing
|
||||
def paid_in_full?(remote)
|
||||
total = BigDecimal(remote&.total.to_s.presence || '0')
|
||||
balance = BigDecimal(remote&.balance.to_s.presence || '0')
|
||||
total.positive? && balance <= 0
|
||||
end
|
||||
|
||||
# The customer's paid invoices to pick from on the Refund page, newest first: [[label, id], ...]
|
||||
def invoice_choices(customer)
|
||||
Invoice.where(customer_id: customer.id).where('balance <= 0 AND total_amount > 0')
|
||||
.order(txn_date: :desc, id: :desc).limit(50).map do |invoice|
|
||||
["##{invoice.doc_number} · #{invoice.txn_date} · #{RefundWriter.money(invoice.total_amount)}", invoice.id.to_s]
|
||||
end
|
||||
end
|
||||
|
||||
# The invoice's lines that can be refunded (bundles opened up into their lines), with what this invoice's
|
||||
# earlier refunds took of each
|
||||
def lines(remote, refunds: QboRefund.of_invoice(remote.id))
|
||||
taken = Hash.new { |hash, key| hash[key] = [BigDecimal('0'), BigDecimal('0')] }
|
||||
refunds.each do |refund|
|
||||
refund.refunded_lines.each do |line|
|
||||
taken[line.key][0] += BigDecimal(line.quantity.to_s.presence || '0')
|
||||
taken[line.key][1] += line.amount.to_d
|
||||
end
|
||||
end
|
||||
|
||||
labor_ids = LaborItems.ids
|
||||
sales_lines(Array(remote.line_items)).filter_map do |line, key|
|
||||
detail = RefundWriter.sales_detail(line)
|
||||
amount = BigDecimal(line.amount.to_s.presence || '0')
|
||||
next unless amount.positive?
|
||||
|
||||
ref = detail&.item_ref
|
||||
quantity = detail&.quantity.nil? ? nil : BigDecimal(detail.quantity.to_s)
|
||||
quantity = nil unless quantity&.positive?
|
||||
Line.new(key: key, item_id: ref&.value.to_s.presence, item_name: ref&.name.to_s, description: line.description.to_s,
|
||||
quantity: quantity, rate: detail&.unit_price.nil? ? nil : BigDecimal(detail.unit_price.to_s),
|
||||
amount: amount, taxable: detail&.tax_code_ref&.value.to_s == 'TAX',
|
||||
parts: ref.present? && ref.value.present? && !LaborItems.match?(ref, ids: labor_ids),
|
||||
refunded_quantity: taken[key][0], refunded_amount: taken[key][1])
|
||||
end
|
||||
end
|
||||
|
||||
# The sales lines with a key for each: its QuickBooks line id, or for a line in a bundle the bundle's id and
|
||||
# its place in it
|
||||
def sales_lines(lines, prefix = nil)
|
||||
lines.each_with_index.flat_map do |line, index|
|
||||
key = "#{prefix}#{line.id.presence || index + 1}"
|
||||
if line.respond_to?(:group_line_detail) && line.group_line_detail
|
||||
sales_lines(Array(line.group_line_detail.line_items), "#{key}.")
|
||||
elsif RefundWriter.sales_detail(line)
|
||||
[[line, key]]
|
||||
else
|
||||
[]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# The invoice's discount, as a share of its lines (0.1 for 10% off)
|
||||
def discount_rate(remote)
|
||||
discount = EstimateWriter.discount_total(remote).to_d
|
||||
subtotal = sales_lines(Array(remote.line_items)).sum(BigDecimal('0')) { |line, _| BigDecimal(line.amount.to_s.presence || '0') }
|
||||
return BigDecimal('0') unless discount.positive? && subtotal.positive?
|
||||
|
||||
[discount / subtotal, BigDecimal('1')].min
|
||||
end
|
||||
|
||||
# The invoice's sales tax, as a share of its taxable lines after the discount, to estimate the tax refunded
|
||||
def tax_rate(remote, invoice_lines = lines(remote, refunds: []))
|
||||
tax = BigDecimal(remote.txn_tax_detail&.total_tax.to_s.presence || '0')
|
||||
taxable = invoice_lines.select(&:taxable).sum(BigDecimal('0'), &:amount) * (1 - discount_rate(remote))
|
||||
tax.positive? && taxable.positive? ? tax / taxable : BigDecimal('0')
|
||||
end
|
||||
|
||||
# Works out the refund from the form's lines: [plan, errors]
|
||||
def plan(remote, form, invoice_lines: lines(remote))
|
||||
errors = []
|
||||
by_key = invoice_lines.index_by(&:key)
|
||||
refunding = form.chosen.filter_map do |key, choice|
|
||||
line = by_key[key]
|
||||
if line.nil?
|
||||
errors << I18n.t(:error_refund_line_gone)
|
||||
next
|
||||
end
|
||||
|
||||
refunding_line(line, choice, errors)
|
||||
end
|
||||
|
||||
lines_amount = refunding.sum(BigDecimal('0'), &:amount)
|
||||
parts = refunding.select { |r| r.line.parts }.sum(BigDecimal('0'), &:amount)
|
||||
rate = discount_rate(remote)
|
||||
discount = (lines_amount * rate).round(2, BigDecimal::ROUND_HALF_UP)
|
||||
fee_rate = RefundWriter.fee_rate
|
||||
fee = form.charge_fee? ? RefundWriter.fee(parts, fee_rate) : BigDecimal('0')
|
||||
tax_rate = tax_rate(remote, invoice_lines)
|
||||
taxable = refunding.select { |r| r.line.taxable }.sum(BigDecimal('0'), &:amount) * (1 - rate)
|
||||
tax = (taxable * tax_rate).round(2, BigDecimal::ROUND_HALF_UP)
|
||||
refund = lines_amount - discount + tax - fee
|
||||
if refunding.any? && fee >= lines_amount - discount
|
||||
errors << I18n.t(:error_refund_fee_over_lines, fee: RefundWriter.money(fee), amount: RefundWriter.money(lines_amount - discount))
|
||||
end
|
||||
|
||||
plan = Plan.new(refunding: refunding, lines_amount: lines_amount, parts_amount: parts, discount_rate: rate,
|
||||
discount: discount, fee_rate: fee_rate, fee: fee, tax_rate: tax_rate, tax: tax,
|
||||
refund: [refund, BigDecimal('0')].max)
|
||||
[plan, errors.uniq]
|
||||
end
|
||||
|
||||
# A line being refunded, from what was posted for it: the quantity and the amount (by default the quantity
|
||||
# at the line's rate, or what's left of the line). Adds to errors when it can't be refunded.
|
||||
def refunding_line(line, choice, errors)
|
||||
name = line.label.presence || line.key
|
||||
quantity = choice.quantity_value
|
||||
quantity = nil if line.quantity.nil? || line.rate.nil?
|
||||
amount = choice.amount_value
|
||||
amount ||= quantity ? (quantity * line.rate).round(2) : line.remaining_amount
|
||||
|
||||
if quantity && (quantity <= 0 || quantity > line.remaining_quantity)
|
||||
errors << I18n.t(:error_refund_line_quantity, line: name, quantity: RefundWriter.plain(line.remaining_quantity))
|
||||
return nil
|
||||
end
|
||||
if amount.nil? || amount <= 0
|
||||
errors << I18n.t(:error_refund_line_amount, line: name)
|
||||
return nil
|
||||
end
|
||||
if amount > line.remaining_amount
|
||||
errors << I18n.t(:error_refund_line_over, line: name, amount: RefundWriter.money(line.remaining_amount))
|
||||
return nil
|
||||
end
|
||||
|
||||
# A partial amount (not the quantity at the line's rate) is refunded as an amount alone, so it doesn't
|
||||
# use up the line's quantity
|
||||
quantity = nil if quantity && (quantity * line.rate).round(2) != amount
|
||||
Refunding.new(line: line, quantity: quantity, amount: amount)
|
||||
end
|
||||
|
||||
# The quantity to offer for a line: what's left of it, when that's what's left of its amount at its rate
|
||||
def default_quantity(line)
|
||||
quantity = line.remaining_quantity
|
||||
return nil unless quantity&.positive? && line.rate
|
||||
|
||||
(quantity * line.rate).round(2) == line.remaining_amount ? quantity : nil
|
||||
end
|
||||
|
||||
# Makes the refund receipt; returns the QboRefund (done, or incomplete with why in its message). Raises
|
||||
# Error, before anything is made in QuickBooks, when the refund can't be made as asked.
|
||||
def refund!(form, user: User.current, gateway: RefundGateway.new, mailer: QboRefundMailer)
|
||||
customer = Customer.find_by(id: form.customer_id)
|
||||
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
|
||||
|
||||
remote = gateway.invoice(form.invoice_id)
|
||||
raise Error, I18n.t(:notice_invoice_not_found) unless remote
|
||||
raise Error, I18n.t(:error_refund_invoice_customer) unless remote.customer_ref&.value.to_s == customer.id.to_s
|
||||
raise Error, I18n.t(:error_refund_invoice_not_paid) unless paid_in_full?(remote)
|
||||
|
||||
plan, errors = plan(remote, form)
|
||||
raise Error, errors.join(' ') if errors.any?
|
||||
raise Error, I18n.t(:error_refund_no_lines) if plan.refunding.empty?
|
||||
|
||||
item = RefundWriter.fee_item
|
||||
raise Error, I18n.t(:error_refund_no_fee_item) if plan.fee.positive? && item.nil?
|
||||
|
||||
bank_account = settings[form.check? ? 'refund_check_account_id' : 'refund_card_account_id'].presence || gateway.account_id('Bank')
|
||||
raise Error, I18n.t(:error_refund_no_bank_account) unless bank_account
|
||||
|
||||
paid = BigDecimal(remote.total.to_s) - BigDecimal(remote.balance.to_s.presence || '0')
|
||||
record = QboRefund.create!(kind: 'invoice', customer_id: customer.id, invoice_id: remote.id,
|
||||
invoice_number: remote.doc_number.to_s, user: user, txn_date: form.txn_date_value,
|
||||
method: form.method, check_number: form.check? ? form.check_number : nil,
|
||||
reason: form.reason, lines_amount: plan.lines_amount, discount_amount: plan.discount,
|
||||
parts_amount: plan.parts_amount, fee_rate: plan.fee_rate, fee_amount: plan.fee,
|
||||
tax_amount: plan.tax, credit_amount: paid, refund_amount: plan.refund,
|
||||
refunded_lines: refunded_lines(plan), status: 'incomplete')
|
||||
|
||||
made = RefundWriter.step(record, :receipt) do
|
||||
receipt = build_receipt(record, remote, plan, form, item, bank_account, gateway)
|
||||
saved = gateway.create_refund_receipt(receipt)
|
||||
raise Error, I18n.t(:error_refund_not_saved) unless saved&.id
|
||||
|
||||
tax = saved.txn_tax_detail&.total_tax
|
||||
record.update!(purchase_id: saved.id.to_s, receipt_number: saved.doc_number.to_s,
|
||||
refund_amount: saved.total.nil? ? plan.refund : BigDecimal(saved.total.to_s),
|
||||
tax_amount: tax.nil? ? plan.tax : BigDecimal(tax.to_s))
|
||||
end
|
||||
return record unless made
|
||||
|
||||
warnings = []
|
||||
warnings << note_issues(record, user) if form.note_issues?
|
||||
warnings << RefundWriter.email_customer(record, customer, mailer) if form.email_customer?
|
||||
record.update!(status: 'done', message: warnings.compact.join("\n").presence)
|
||||
record
|
||||
end
|
||||
|
||||
def refunded_lines(plan)
|
||||
plan.refunding.map do |r|
|
||||
QboRefund::RefundedLine.new(key: r.line.key, description: r.line.label, quantity: r.quantity,
|
||||
amount: r.amount, parts: r.line.parts)
|
||||
end
|
||||
end
|
||||
|
||||
# The QuickBooks Refund Receipt: the lines refunded, the discount's share, the restocking fee
|
||||
def build_receipt(record, remote, plan, form, fee_item, bank_account, gateway)
|
||||
receipt = Quickbooks::Model::RefundReceipt.new
|
||||
receipt.customer_ref = Quickbooks::Model::BaseReference.new(record.customer_id.to_s)
|
||||
receipt.txn_date = record.txn_date
|
||||
receipt.deposit_to_account_ref = Quickbooks::Model::BaseReference.new(bank_account.to_s)
|
||||
method_id = gateway.payment_method_id(form.check? ? :check : :card)
|
||||
receipt.payment_method_ref = Quickbooks::Model::BaseReference.new(method_id) if method_id
|
||||
receipt.payment_ref_number = record.check_number if form.check?
|
||||
receipt.bill_email = remote.bill_email if remote.bill_email&.address.present?
|
||||
receipt.customer_memo = I18n.t(:text_refund_receipt_memo, number: record.invoice_number)
|
||||
receipt.private_note = I18n.t(:text_refund_invoice_private_note, number: record.invoice_number, reason: record.reason)
|
||||
receipt.apply_tax_after_discount = true if plan.discount.positive?
|
||||
|
||||
lines = plan.refunding.map { |r| receipt_line(r) }
|
||||
lines << discount_line(plan) if plan.discount.positive?
|
||||
lines << fee_line(record, fee_item) if plan.fee.positive?
|
||||
lines.each_with_index { |line, index| line.line_num = index + 1 }
|
||||
receipt.line_items = lines
|
||||
receipt
|
||||
end
|
||||
|
||||
# A refunded line: the invoice line's product/service and tax code. Its quantity and rate go with it when
|
||||
# the amount is that quantity at the line's rate (refunding_line); a partial amount goes as an amount alone.
|
||||
def receipt_line(refunding)
|
||||
line = refunding.line
|
||||
remote = Quickbooks::Model::Line.new
|
||||
remote.description = line.description
|
||||
remote.amount = refunding.amount
|
||||
remote.sales_item! do |detail|
|
||||
detail.item_ref = Quickbooks::Model::BaseReference.new(line.item_id) if line.item_id
|
||||
if refunding.quantity
|
||||
detail.quantity = refunding.quantity
|
||||
detail.unit_price = line.rate
|
||||
end
|
||||
detail.tax_code_ref = Quickbooks::Model::BaseReference.new(line.taxable ? 'TAX' : 'NON')
|
||||
end
|
||||
remote
|
||||
end
|
||||
|
||||
def discount_line(plan)
|
||||
remote = Quickbooks::Model::Line.new
|
||||
remote.amount = plan.discount
|
||||
remote.discount! { |detail| detail.percent_based = false }
|
||||
remote
|
||||
end
|
||||
|
||||
# The restocking fee, kept back: a negative line, so the fee is income and the refund is less by it
|
||||
def fee_line(record, item)
|
||||
remote = Quickbooks::Model::Line.new
|
||||
remote.amount = -record.fee_amount
|
||||
remote.description = RefundWriter.fee_description(record.parts_amount, record.fee_rate, record.fee_amount,
|
||||
nil, on: record.document_label)
|
||||
remote.sales_item! do |detail|
|
||||
detail.item_id = item.id
|
||||
detail.quantity = 1
|
||||
detail.unit_price = -record.fee_amount
|
||||
detail.tax_code_ref = Quickbooks::Model::BaseReference.new('NON')
|
||||
end
|
||||
remote
|
||||
end
|
||||
|
||||
# Notes the refund on the invoice's work orders (their status is left alone); returns a warning, or nil
|
||||
def note_issues(record, user)
|
||||
issues = Invoice.find_by(id: record.invoice_id)&.issues.to_a
|
||||
return nil if issues.empty?
|
||||
|
||||
note = I18n.t(:text_refund_invoice_issue_note, amount: RefundWriter.money(record.refund_amount),
|
||||
number: record.invoice_number, method: record.method_name,
|
||||
reason: record.reason)
|
||||
failed = []
|
||||
noted = issues.filter_map do |issue|
|
||||
issue.init_journal(user, note)
|
||||
if issue.save
|
||||
issue.id
|
||||
else
|
||||
failed << "##{issue.id} (#{issue.errors.full_messages.join(', ')})"
|
||||
nil
|
||||
end
|
||||
end
|
||||
record.update!(noted_issue_ids: noted)
|
||||
failed.any? ? I18n.t(:text_refund_issues_not_noted, issues: failed.join('; ')) : nil
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -34,8 +34,32 @@ module RedmineQboBilling
|
||||
balance < total ? :partial : :open
|
||||
end
|
||||
|
||||
def label(status)
|
||||
status ? I18n.t("label_invoice_status_#{status}") : ''
|
||||
# "Paid", or with the day it was paid in full, "Paid 11/03/2026"
|
||||
def label(status, paid_on: nil)
|
||||
return '' unless status
|
||||
return I18n.t(:label_invoice_status_paid_on, date: I18n.l(paid_on)) if status == :paid && paid_on
|
||||
|
||||
I18n.t("label_invoice_status_#{status}")
|
||||
end
|
||||
|
||||
# The invoice list's short badge: "Paid", or "Paid +3d" when it was paid in full 3 days after its date
|
||||
def short_label(status, paid_on: nil, invoice_date: nil)
|
||||
days = days_to_pay(invoice_date, paid_on) if status == :paid
|
||||
return I18n.t(:label_invoice_status_paid_days, days: days) if days&.positive?
|
||||
|
||||
label(status)
|
||||
end
|
||||
|
||||
# The badge's tooltip: "Paid in full 11/19/2025" (nil unless it's paid with a known day)
|
||||
def title(status, paid_on: nil)
|
||||
I18n.t(:text_invoice_paid_in_full, date: I18n.l(paid_on)) if status == :paid && paid_on
|
||||
end
|
||||
|
||||
# Days from the invoice's date to the day it was paid in full
|
||||
def days_to_pay(invoice_date, paid_on)
|
||||
return nil unless invoice_date && paid_on
|
||||
|
||||
(paid_on.to_date - invoice_date.to_date).to_i
|
||||
end
|
||||
|
||||
def to_d(value)
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboBilling
|
||||
# What the Refund page posts (SOP-OPS-014): the canceled order's estimate, the parts the restocking fee is
|
||||
# worked out on, how the money goes back (card terminal or company check), and what else to do in
|
||||
# QuickBooks and Redmine.
|
||||
class RefundForm
|
||||
include ActiveModel::Model
|
||||
include ActiveModel::Validations
|
||||
|
||||
ATTRIBUTES = %i[customer_id estimate_id txn_date parts_amount method check_number reason
|
||||
close_estimate cancel_issues email_customer].freeze
|
||||
|
||||
attr_accessor(*ATTRIBUTES)
|
||||
|
||||
validate :validate_refund
|
||||
|
||||
def self.from_params(params)
|
||||
params = params.to_h.stringify_keys
|
||||
new(ATTRIBUTES.to_h { |attr| [attr, params[attr.to_s].to_s.strip] })
|
||||
end
|
||||
|
||||
def parts_value
|
||||
parts_amount.blank? ? BigDecimal('0') : EstimateForm.decimal(parts_amount)
|
||||
end
|
||||
|
||||
def txn_date_value
|
||||
EstimateForm.date(txn_date)
|
||||
end
|
||||
|
||||
def check?
|
||||
method == 'check'
|
||||
end
|
||||
|
||||
%i[close_estimate cancel_issues email_customer].each do |flag|
|
||||
define_method(:"#{flag}?") { send(flag).to_s == '1' || send(flag) == true }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def validate_refund
|
||||
errors.add(:base, I18n.t(:error_estimate_needs_customer)) if customer_id.blank?
|
||||
errors.add(:base, I18n.t(:error_refund_method)) unless QboRefund::METHODS.include?(method)
|
||||
errors.add(:base, I18n.t(:error_refund_check_number)) if check? && check_number.blank?
|
||||
errors.add(:base, I18n.t(:error_refund_reason)) if reason.blank?
|
||||
value = parts_value
|
||||
errors.add(:base, I18n.t(:error_refund_parts_amount)) if value.nil? || value.negative?
|
||||
errors.add(:base, I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_refund_date))) if txn_date_value.nil?
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -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.
|
||||
|
||||
module RedmineQboBilling
|
||||
# The QuickBooks calls a refund makes (RefundWriter), kept apart so the steps can be tested without QuickBooks.
|
||||
class RefundGateway
|
||||
# The customer's payments with money not yet applied (deposits and other credit), oldest first
|
||||
def unapplied_payments(customer_id)
|
||||
payments = with_service('Payment') do |service|
|
||||
service.all("SELECT * FROM Payment WHERE CustomerRef = '#{customer_id.to_i}'")
|
||||
end
|
||||
Array(payments).select { |p| BigDecimal(p.unapplied_amount.to_s.presence || '0').positive? }
|
||||
.sort_by { |p| [p.txn_date || Date.new(1900), p.id.to_i] }
|
||||
end
|
||||
|
||||
def estimate(id)
|
||||
QboEstimateService.with_service { |service| service.fetch_by_id(id) }
|
||||
end
|
||||
|
||||
def create_invoice(invoice)
|
||||
with_service('Invoice') { |service| service.create(invoice) }
|
||||
end
|
||||
|
||||
def invoice(id)
|
||||
with_service('Invoice') { |service| service.fetch_by_id(id) }
|
||||
end
|
||||
|
||||
# Applies amount of the payment's unapplied money to a transaction (an invoice, or the refund check or
|
||||
# expense). QuickBooks replaces a payment's lines on a sparse update, so its lines are sent back with
|
||||
# the new one (added to the line already linked to that transaction, if any). Returns the saved payment.
|
||||
def apply_payment(payment, amount, txn_id, txn_type)
|
||||
lines = Array(payment.line_items).map { |line| copy_line(line) }
|
||||
same = lines.find do |line|
|
||||
Array(line.linked_transactions).any? { |t| t.txn_id.to_s == txn_id.to_s && t.txn_type.to_s == txn_type }
|
||||
end
|
||||
if same
|
||||
same.amount = BigDecimal(same.amount.to_s) + amount
|
||||
else
|
||||
lines << self.class.linked_line(amount, txn_id, txn_type)
|
||||
end
|
||||
|
||||
update = Quickbooks::Model::Payment.new
|
||||
update.id = payment.id
|
||||
update.sync_token = payment.sync_token
|
||||
update.customer_ref = payment.customer_ref
|
||||
update.total = payment.total
|
||||
update.line_items = lines
|
||||
with_service('Payment') { |service| service.update(update, sparse: true) }
|
||||
end
|
||||
|
||||
def create_purchase(purchase)
|
||||
with_service('Purchase') { |service| service.create(purchase) }
|
||||
end
|
||||
|
||||
# A paid invoice's refund (InvoiceRefundWriter)
|
||||
def create_refund_receipt(receipt)
|
||||
with_service('RefundReceipt') { |service| service.create(receipt) }
|
||||
end
|
||||
|
||||
PAYMENT_METHOD_NAMES = { check: /\b(check|cheque)\b/i, card: /card|visa|mastercard|amex|discover/i }.freeze
|
||||
|
||||
# QuickBooks' payment method for a refund by :check or :card (the first whose name fits), or nil
|
||||
def payment_method_id(kind)
|
||||
pattern = PAYMENT_METHOD_NAMES[kind]
|
||||
PaymentWriter.payment_methods.detect { |name, _| name.match?(pattern) }&.last
|
||||
end
|
||||
|
||||
# The first active account of a QuickBooks account type ('Accounts Receivable', 'Bank')
|
||||
def account_id(type)
|
||||
account = with_service('Account') do |service|
|
||||
service.query("SELECT * FROM Account WHERE AccountType = '#{type}' AND Active = true").entries.first
|
||||
end
|
||||
account&.id&.to_s
|
||||
end
|
||||
|
||||
def customer_balance(customer_id)
|
||||
customer = with_service('Customer') { |service| service.fetch_by_id(customer_id) }
|
||||
BigDecimal(customer&.balance.to_s.presence || '0')
|
||||
end
|
||||
|
||||
# Marks the canceled order's estimate Rejected, so it can't be invoiced later
|
||||
def reject_estimate(estimate)
|
||||
update = EstimateWriter.status_update(estimate, 'Rejected')
|
||||
QboEstimateService.with_service { |service| service.update(update, sparse: true) }
|
||||
end
|
||||
|
||||
def sync_invoice(id)
|
||||
InvoiceSyncService.new.sync_by_id(id)
|
||||
rescue StandardError => e
|
||||
Rails.logger.warn "[RedmineQboBilling] Could not cache invoice #{id} after a refund: #{e.message}"
|
||||
end
|
||||
|
||||
def sync_payment(id)
|
||||
PaymentSyncService.new.sync_by_id(id)
|
||||
rescue StandardError => e
|
||||
Rails.logger.warn "[RedmineQboBilling] Could not cache payment #{id} after a refund: #{e.message}"
|
||||
end
|
||||
|
||||
def sync_estimate(id)
|
||||
EstimateSyncService.new.sync_by_id(id)
|
||||
rescue StandardError => e
|
||||
Rails.logger.warn "[RedmineQboBilling] Could not cache estimate #{id} after a refund: #{e.message}"
|
||||
end
|
||||
|
||||
def self.linked_line(amount, txn_id, txn_type)
|
||||
line = Quickbooks::Model::Line.new
|
||||
line.amount = amount
|
||||
link = Quickbooks::Model::LinkedTransaction.new
|
||||
link.txn_id = txn_id.to_s
|
||||
link.txn_type = txn_type
|
||||
line.linked_transactions = [link]
|
||||
line
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def copy_line(line)
|
||||
copy = Quickbooks::Model::Line.new
|
||||
copy.amount = BigDecimal(line.amount.to_s)
|
||||
copy.linked_transactions = Array(line.linked_transactions).map do |t|
|
||||
link = Quickbooks::Model::LinkedTransaction.new
|
||||
link.txn_id = t.txn_id
|
||||
link.txn_type = t.txn_type
|
||||
link
|
||||
end
|
||||
copy
|
||||
end
|
||||
|
||||
def with_service(entity, &block)
|
||||
QboConnectionService.with_qbo_service(entity: entity, &block)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,141 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboBilling
|
||||
# A refund as a PDF (SOP-OPS-014): what was refunded and how, from what Redmine recorded when it was made, so it
|
||||
# can be printed or filed without opening QuickBooks (QuickBooks has no PDF of a check or an expense).
|
||||
class RefundPdf
|
||||
include Redmine::I18n
|
||||
|
||||
WIDTH = 190
|
||||
|
||||
def initialize(refund)
|
||||
@refund = refund
|
||||
end
|
||||
|
||||
def render
|
||||
pdf = ::Redmine::Export::PDF::ITCPDF.new(current_language)
|
||||
pdf.set_title(title)
|
||||
pdf.alias_nb_pages
|
||||
pdf.footer_date = format_date(User.current.today)
|
||||
pdf.add_page
|
||||
|
||||
pdf.SetFontStyle('B', 14)
|
||||
pdf.RDMMultiCell(WIDTH, 7, shop_name)
|
||||
pdf.SetFontStyle('B', 12)
|
||||
pdf.RDMMultiCell(WIDTH, 7, title)
|
||||
pdf.ln(3)
|
||||
|
||||
details(pdf)
|
||||
pdf.ln(4)
|
||||
amounts(pdf)
|
||||
pdf.ln(4)
|
||||
notes(pdf)
|
||||
signature(pdf) if @refund.check?
|
||||
pdf.output
|
||||
end
|
||||
|
||||
def title
|
||||
"#{l(:label_refund)} · #{@refund.customer&.name} · #{format_date(@refund.txn_date)}"
|
||||
end
|
||||
|
||||
def filename
|
||||
"refund-#{@refund.txn_date}-#{@refund.customer&.name.to_s.parameterize.presence || @refund.customer_id}.pdf"
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def details(pdf)
|
||||
rows = [[l(:label_customer), @refund.customer&.name.to_s],
|
||||
[l(:label_refund_date), format_date(@refund.txn_date)],
|
||||
@refund.invoice? ? [l(:label_refund_invoice), @refund.document_label] :
|
||||
[l(:label_refund_estimate), @refund.estimate_number.present? ? "E#{@refund.estimate_number}" : l(:label_refund_no_estimate)],
|
||||
[l(:label_refund_reason), @refund.reason.to_s]]
|
||||
rows.each { |label, value| row(pdf, label, value) }
|
||||
end
|
||||
|
||||
def amounts(pdf)
|
||||
pdf.SetFontStyle('B', 10)
|
||||
pdf.RDMCell(WIDTH, 6, l(:label_refund_summary), 'B', 1)
|
||||
pdf.SetFontStyle('', 10)
|
||||
fee = @refund.fee_amount.to_d
|
||||
if @refund.invoice?
|
||||
invoice_lines(pdf)
|
||||
else
|
||||
money_row(pdf, l(:label_refund_credit), @refund.credit_amount)
|
||||
end
|
||||
if fee.positive?
|
||||
label = l(:label_refund_pdf_fee, rate: RefundWriter.plain(@refund.fee_rate), parts: RefundWriter.money(@refund.parts_amount))
|
||||
label += " · #{l(:label_refund_fee_invoice, number: @refund.fee_invoice_number)}" if @refund.fee_invoice_number.present?
|
||||
money_row(pdf, label, -fee)
|
||||
end
|
||||
pdf.SetFontStyle('B', 11)
|
||||
money_row(pdf, "#{l(:label_refund_amount)} · #{method_text}", @refund.refund_amount, border: 'T')
|
||||
pdf.SetFontStyle('', 10)
|
||||
unless @refund.balance_after.nil?
|
||||
money_row(pdf, l(:label_refund_balance_after), @refund.balance_after)
|
||||
end
|
||||
end
|
||||
|
||||
# A paid invoice's refund: each line refunded, the discount's share and the sales tax
|
||||
def invoice_lines(pdf)
|
||||
@refund.refunded_lines.each do |line|
|
||||
quantity = line.quantity.present? ? " (#{RefundWriter.plain(BigDecimal(line.quantity.to_s))})" : ''
|
||||
money_row(pdf, "#{line.description.truncate(90)}#{quantity}", line.amount)
|
||||
end
|
||||
money_row(pdf, l(:label_refund_discount), -@refund.discount_amount.to_d) if @refund.discount_amount.to_d.positive?
|
||||
money_row(pdf, l(:label_refund_tax), @refund.tax_amount)
|
||||
end
|
||||
|
||||
def notes(pdf)
|
||||
pdf.SetFontStyle('', 9)
|
||||
issues = Issue.where(id: @refund.canceled_issue_ids).to_a
|
||||
row(pdf, l(:label_refund_pdf_work_orders), issues.map { |i| "#{i.tracker} ##{i.id}: #{i.subject}" }.join("\n")) if issues.any?
|
||||
row(pdf, l(:label_refund_pdf_estimate), l(:text_refund_pdf_estimate_rejected, number: @refund.estimate_number)) if @refund.estimate_closed?
|
||||
if @refund.invoice? && @refund.receipt_number.present?
|
||||
row(pdf, l(:label_refund_receipt), l(:text_refund_receipt_number, number: @refund.receipt_number))
|
||||
end
|
||||
row(pdf, l(:label_refund_recorded_by), "#{@refund.user&.name} · #{format_time(@refund.created_at)}")
|
||||
row(pdf, l(:label_refund_incomplete), @refund.message.to_s) unless @refund.done?
|
||||
end
|
||||
|
||||
# For a refund check: the customer signs for it
|
||||
def signature(pdf)
|
||||
pdf.ln(14)
|
||||
pdf.SetFontStyle('', 10)
|
||||
pdf.RDMCell(110, 6, l(:label_refund_received_by), 'T', 0)
|
||||
pdf.RDMCell(10, 6, '', 0, 0)
|
||||
pdf.RDMCell(70, 6, l(:label_date), 'T', 1)
|
||||
end
|
||||
|
||||
def method_text
|
||||
@refund.check? ? "#{@refund.method_name} ##{@refund.check_number}" : @refund.method_name
|
||||
end
|
||||
|
||||
def row(pdf, label, value)
|
||||
pdf.SetFontStyle('B', 10)
|
||||
pdf.RDMCell(50, 6, label.to_s, 0, 0)
|
||||
pdf.SetFontStyle('', 10)
|
||||
pdf.RDMMultiCell(WIDTH - 50, 6, value.to_s)
|
||||
end
|
||||
|
||||
def money_row(pdf, label, amount, border: 0)
|
||||
pdf.RDMCell(WIDTH - 40, 7, label.to_s, border, 0)
|
||||
pdf.RDMCell(40, 7, RefundWriter.money(amount), border, 1, 'R')
|
||||
end
|
||||
|
||||
def shop_name
|
||||
reminders = defined?(RedmineQboReminders::Settings) ? RedmineQboReminders::Settings.current : nil
|
||||
reminders&.[]('shop_name').to_s.presence || Setting.app_title
|
||||
rescue StandardError
|
||||
Setting.app_title
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,329 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboBilling
|
||||
# Customer refunds for canceled orders and returned parts (SOP-OPS-014), the way the SOP does them in QuickBooks:
|
||||
#
|
||||
# 1. A restocking fee invoice for 30% of the parts (labor carries no fee), its line showing the math, paid
|
||||
# from the customer's credit (their deposit), oldest first.
|
||||
# 2. The rest of the customer's credit is refunded: a company check, or a partial refund on the card terminal.
|
||||
# 3. The refund is recorded in QuickBooks with the category Accounts Receivable, from the bank account in the
|
||||
# settings, described "Refund for deposit on E1234": a Check for a check, an Expense for a card refund.
|
||||
# 4. The credit left on the customer's payments is applied to that check or expense, so the deposit, the fee
|
||||
# invoice and the refund reconcile and the customer's balance comes back to $0.00.
|
||||
#
|
||||
# Then, as asked on the page: the canceled order's estimate is marked Rejected in QuickBooks, its work orders are
|
||||
# set to the canceled status with the reason as a note, and the customer is emailed a summary.
|
||||
#
|
||||
# Each refund is recorded (QboRefund). Steps 1 to 4 stop at the first failure, and the record says which step
|
||||
# failed and what was already done, so it can be finished in QuickBooks. The later steps only add warnings.
|
||||
module RefundWriter
|
||||
class Error < StandardError; end
|
||||
|
||||
Credit = Struct.new(:payment_id, :date, :reference, :memo, :amount, keyword_init: true)
|
||||
Preview = Struct.new(:credits, :credit_total, :parts_amount, :fee_rate, :fee, :refund, keyword_init: true)
|
||||
|
||||
CLOSED_ESTIMATE_STATUSES = %w[Closed Converted Rejected].freeze
|
||||
CANCELED_STATUS_NAMES = %w[Canceled Cancelled].freeze
|
||||
|
||||
module_function
|
||||
|
||||
def settings
|
||||
Setting.plugin_redmine_qbo || {}
|
||||
rescue StandardError
|
||||
{}
|
||||
end
|
||||
|
||||
# The restocking fee rate in percent (plugin setting, SOP-OPS-014: 30)
|
||||
def fee_rate
|
||||
rate = BigDecimal(settings['restocking_fee_rate'].to_s.strip, exception: false)
|
||||
rate.nil? || rate.negative? ? BigDecimal('30') : rate
|
||||
end
|
||||
|
||||
# The product/service on the restocking fee invoice (plugin setting)
|
||||
def fee_item
|
||||
Item.find_by(id: settings['restocking_item_id']) if settings['restocking_item_id'].present?
|
||||
end
|
||||
|
||||
def fee(parts, rate = fee_rate)
|
||||
(parts.to_d * rate.to_d / 100).round(2, BigDecimal::ROUND_HALF_UP)
|
||||
end
|
||||
|
||||
# The parts on an estimate: its lines that aren't labor (with the lines inside bundles), before tax
|
||||
def parts_amount(estimate)
|
||||
labor_ids = LaborItems.ids
|
||||
parts_lines(Array(estimate&.line_items), labor_ids).sum(BigDecimal('0')) { |line| BigDecimal(line.amount.to_s.presence || '0') }
|
||||
end
|
||||
|
||||
def parts_lines(lines, labor_ids)
|
||||
lines.flat_map do |line|
|
||||
if line.respond_to?(:group_line_detail) && line.group_line_detail
|
||||
parts_lines(Array(line.group_line_detail.line_items), labor_ids)
|
||||
elsif (ref = sales_detail(line)&.item_ref) && ref.value.present?
|
||||
LaborItems.match?(ref, ids: labor_ids) ? [] : [line]
|
||||
else
|
||||
[]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# A sales line's detail: estimates and invoices name it SalesLineItemDetail (InvoiceLineItem), other
|
||||
# transactions SalesItemLineDetail (Line)
|
||||
def sales_detail(line)
|
||||
if line.respond_to?(:sales_line_item_detail) then line.sales_line_item_detail
|
||||
elsif line.respond_to?(:sales_item_line_detail) then line.sales_item_line_detail
|
||||
end
|
||||
end
|
||||
|
||||
# The customer's credit: their payments' unapplied money, oldest first
|
||||
def credits(customer, gateway: RefundGateway.new)
|
||||
gateway.unapplied_payments(customer.id).map do |payment|
|
||||
Credit.new(payment_id: payment.id.to_s, date: payment.txn_date, reference: payment.payment_ref_number.to_s,
|
||||
memo: payment.private_note.to_s, amount: BigDecimal(payment.unapplied_amount.to_s))
|
||||
end
|
||||
end
|
||||
|
||||
# The customer's estimates to pick the canceled order from, newest first: [[label, id], ...]
|
||||
def estimate_choices(customer)
|
||||
Estimate.where(customer_id: customer.id).order(txn_date: :desc, id: :desc).limit(50).map do |estimate|
|
||||
total = estimate.respond_to?(:total_amount) && estimate.total_amount ? " · $#{format('%.2f', estimate.total_amount)}" : ''
|
||||
["E#{estimate.doc_number} · #{estimate.txn_date}#{total}", estimate.id.to_s]
|
||||
end
|
||||
end
|
||||
|
||||
# What the page shows before the refund is made: the credit, the fee and what will be refunded
|
||||
def preview(customer, parts:, gateway: RefundGateway.new)
|
||||
list = credits(customer, gateway: gateway)
|
||||
total = list.sum(BigDecimal('0'), &:amount)
|
||||
rate = fee_rate
|
||||
amount = fee(parts, rate)
|
||||
Preview.new(credits: list, credit_total: total, parts_amount: parts.to_d, fee_rate: rate, fee: amount,
|
||||
refund: [total - amount, BigDecimal('0')].max)
|
||||
end
|
||||
|
||||
# "Restocking fee: 30% × $1,026.63 parts on E1068 = $308.00" (on: what the parts are on instead, e.g. "Invoice #1234")
|
||||
def fee_description(parts, rate, amount, estimate_number, on: nil)
|
||||
on = on.present? ? " on #{on}" : (estimate_number.present? ? " on E#{estimate_number}" : '')
|
||||
I18n.t(:text_refund_fee_line, rate: plain(rate), parts: money(parts), on: on, fee: money(amount))
|
||||
end
|
||||
|
||||
# "Refund for deposit on E1068" (SOP-OPS-014 step 3)
|
||||
def refund_description(estimate_number, card:)
|
||||
text = estimate_number.present? ? I18n.t(:text_refund_line, number: estimate_number) : I18n.t(:text_refund_line_credit)
|
||||
card ? "#{text} #{I18n.t(:text_refund_line_card)}" : text
|
||||
end
|
||||
|
||||
# Makes the refund; returns the QboRefund (done, or incomplete with the step that failed in its message).
|
||||
# Raises Error, before anything is made in QuickBooks, when the refund can't be made as asked.
|
||||
def refund!(form, user: User.current, gateway: RefundGateway.new, mailer: QboRefundMailer)
|
||||
customer = Customer.find_by(id: form.customer_id)
|
||||
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
|
||||
|
||||
estimate = load_estimate(form, customer, gateway)
|
||||
rate = fee_rate
|
||||
parts = form.parts_value
|
||||
fee_amount = fee(parts, rate)
|
||||
item = fee_item
|
||||
raise Error, I18n.t(:error_refund_no_fee_item) if fee_amount.positive? && item.nil?
|
||||
|
||||
payments = gateway.unapplied_payments(customer.id)
|
||||
credit = payments.sum(BigDecimal('0')) { |p| BigDecimal(p.unapplied_amount.to_s) }
|
||||
raise Error, I18n.t(:error_refund_no_credit) unless credit.positive?
|
||||
raise Error, I18n.t(:error_refund_fee_over_credit, fee: money(fee_amount), credit: money(credit)) if fee_amount >= credit
|
||||
|
||||
ar_account = gateway.account_id('Accounts Receivable')
|
||||
raise Error, I18n.t(:error_refund_no_ar_account) unless ar_account
|
||||
bank_account = settings[form.check? ? 'refund_check_account_id' : 'refund_card_account_id'].presence || gateway.account_id('Bank')
|
||||
raise Error, I18n.t(:error_refund_no_bank_account) unless bank_account
|
||||
|
||||
record = QboRefund.create!(customer_id: customer.id, estimate_id: estimate&.id, estimate_number: estimate&.doc_number,
|
||||
user: user, txn_date: form.txn_date_value, method: form.method,
|
||||
check_number: form.check? ? form.check_number : nil, reason: form.reason,
|
||||
parts_amount: parts, fee_rate: rate, fee_amount: fee_amount, credit_amount: credit,
|
||||
status: 'incomplete')
|
||||
warnings = []
|
||||
|
||||
if fee_amount.positive?
|
||||
fee_paid = step(record, :fee) { charge_fee(record, customer, item, gateway) }
|
||||
return record unless fee_paid
|
||||
end
|
||||
refunded = step(record, :refund) { record_refund(record, customer, form, ar_account, bank_account, gateway) }
|
||||
return record unless refunded
|
||||
|
||||
begin
|
||||
record.update!(balance_after: gateway.customer_balance(customer.id))
|
||||
rescue StandardError
|
||||
warnings << I18n.t(:text_refund_balance_unknown)
|
||||
end
|
||||
warnings << close_estimate(record, estimate, gateway) if form.close_estimate? && estimate
|
||||
warnings << cancel_issues(record, estimate, form, user) if form.cancel_issues? && estimate
|
||||
warnings << email_customer(record, customer, mailer) if form.email_customer?
|
||||
record.update!(status: 'done', message: warnings.compact.join("\n").presence)
|
||||
record
|
||||
end
|
||||
|
||||
# The canceled order's estimate, which must be the customer's
|
||||
def load_estimate(form, customer, gateway)
|
||||
return nil if form.estimate_id.blank?
|
||||
|
||||
estimate = gateway.estimate(form.estimate_id)
|
||||
raise Error, I18n.t(:notice_estimate_not_found) unless estimate
|
||||
raise Error, I18n.t(:error_refund_estimate_customer) unless estimate.customer_ref&.value.to_s == customer.id.to_s
|
||||
|
||||
estimate
|
||||
end
|
||||
|
||||
# Runs one of the steps that must all succeed; on failure records which step and why
|
||||
def step(record, name)
|
||||
yield
|
||||
true
|
||||
rescue StandardError => e
|
||||
detail = e.respond_to?(:detail) && e.detail.present? ? "#{e.message}: #{e.detail}" : e.message
|
||||
Rails.logger.error "[RedmineQboBilling] Refund #{record.id}, #{name}: #{detail}"
|
||||
record.update!(message: I18n.t(:"error_refund_step_#{name}", error: detail))
|
||||
false
|
||||
end
|
||||
|
||||
# Step 1: the restocking fee invoice, paid from the customer's credit
|
||||
def charge_fee(record, customer, item, gateway)
|
||||
invoice = Quickbooks::Model::Invoice.new
|
||||
invoice.customer_id = customer.id
|
||||
invoice.txn_date = record.txn_date
|
||||
invoice.private_note = I18n.t(:text_refund_private_note, reason: record.reason)
|
||||
line = Quickbooks::Model::InvoiceLineItem.new
|
||||
line.amount = record.fee_amount
|
||||
line.description = fee_description(record.parts_amount, record.fee_rate, record.fee_amount, record.estimate_number)
|
||||
line.sales_item! do |detail|
|
||||
detail.item_id = item.id
|
||||
detail.quantity = 1
|
||||
detail.unit_price = record.fee_amount
|
||||
end
|
||||
invoice.line_items = [line]
|
||||
saved = gateway.create_invoice(invoice)
|
||||
raise Error, I18n.t(:error_refund_fee_not_saved) unless saved&.id
|
||||
|
||||
record.update!(fee_invoice_id: saved.id.to_s, fee_invoice_number: saved.doc_number.to_s)
|
||||
# QuickBooks may already have applied the customer's credit to the new invoice ("Automatically apply credits")
|
||||
owed = BigDecimal(gateway.invoice(saved.id).balance.to_s.presence || '0')
|
||||
gateway.unapplied_payments(customer.id).each do |payment|
|
||||
break unless owed.positive?
|
||||
|
||||
take = [owed, BigDecimal(payment.unapplied_amount.to_s)].min
|
||||
next unless take.positive?
|
||||
|
||||
gateway.apply_payment(payment, take, saved.id, 'Invoice')
|
||||
gateway.sync_payment(payment.id)
|
||||
owed -= take
|
||||
end
|
||||
raise Error, I18n.t(:error_refund_fee_unpaid, amount: money(owed)) if owed.positive?
|
||||
|
||||
gateway.sync_invoice(saved.id)
|
||||
end
|
||||
|
||||
# Steps 2 to 4: the refund check or expense for the rest of the credit, and the credit applied to it
|
||||
def record_refund(record, customer, form, ar_account, bank_account, gateway)
|
||||
payments = gateway.unapplied_payments(customer.id)
|
||||
amount = payments.sum(BigDecimal('0')) { |p| BigDecimal(p.unapplied_amount.to_s) }
|
||||
raise Error, I18n.t(:error_refund_nothing_left) unless amount.positive?
|
||||
|
||||
card = !form.check?
|
||||
purchase = Quickbooks::Model::Purchase.new
|
||||
purchase.payment_type = card ? 'Cash' : 'Check'
|
||||
purchase.doc_number = record.check_number unless card
|
||||
purchase.txn_date = record.txn_date
|
||||
purchase.account_ref = Quickbooks::Model::BaseReference.new(bank_account.to_s)
|
||||
payee = Quickbooks::Model::BaseReference.new(customer.id.to_s)
|
||||
payee.type = 'Customer'
|
||||
purchase.entity_ref = payee
|
||||
purchase.private_note = I18n.t(:text_refund_private_note, reason: record.reason)
|
||||
line = Quickbooks::Model::PurchaseLineItem.new
|
||||
line.amount = amount
|
||||
line.description = refund_description(record.estimate_number, card: card)
|
||||
line.account_based_expense! do |detail|
|
||||
detail.account_ref = Quickbooks::Model::BaseReference.new(ar_account.to_s)
|
||||
detail.customer_ref = Quickbooks::Model::BaseReference.new(customer.id.to_s)
|
||||
end
|
||||
purchase.line_items = [line]
|
||||
saved = gateway.create_purchase(purchase)
|
||||
raise Error, I18n.t(:error_refund_not_saved) unless saved&.id
|
||||
|
||||
record.update!(purchase_id: saved.id.to_s, refund_amount: amount)
|
||||
# The credit is applied to the check ("Check") or the expense ("Expense")
|
||||
payments.each do |payment|
|
||||
gateway.apply_payment(payment, BigDecimal(payment.unapplied_amount.to_s), saved.id, card ? 'Expense' : 'Check')
|
||||
gateway.sync_payment(payment.id)
|
||||
end
|
||||
end
|
||||
|
||||
# Marks the canceled order's estimate Rejected; returns a warning, or nil
|
||||
def close_estimate(record, estimate, gateway)
|
||||
return nil if CLOSED_ESTIMATE_STATUSES.include?(estimate.txn_status.to_s)
|
||||
|
||||
gateway.reject_estimate(estimate)
|
||||
gateway.sync_estimate(estimate.id)
|
||||
record.update!(estimate_closed: true)
|
||||
nil
|
||||
rescue StandardError => e
|
||||
I18n.t(:text_refund_estimate_not_closed, error: e.message)
|
||||
end
|
||||
|
||||
# Sets the estimate's open work orders to the canceled status, with the reason as a note (Work Orders §5)
|
||||
def cancel_issues(record, estimate, form, user)
|
||||
status = canceled_status
|
||||
return I18n.t(:text_refund_no_canceled_status) unless status
|
||||
|
||||
ids = Issue.where(estimate_id: estimate.id).pluck(:id) + QboEstimateLineIssue.where(estimate_id: estimate.id).pluck(:issue_id)
|
||||
note = I18n.t(:text_refund_issue_note, reason: form.reason, fee: money(record.fee_amount),
|
||||
refund: money(record.refund_amount), method: record.method_name)
|
||||
failed = []
|
||||
canceled = Issue.where(id: ids.uniq).includes(:status).reject(&:closed?).filter_map do |issue|
|
||||
issue.init_journal(user, note)
|
||||
issue.status = status
|
||||
if issue.save
|
||||
issue.id
|
||||
else
|
||||
failed << "##{issue.id} (#{issue.errors.full_messages.join(', ')})"
|
||||
nil
|
||||
end
|
||||
end
|
||||
record.update!(canceled_issue_ids: canceled)
|
||||
failed.any? ? I18n.t(:text_refund_issues_not_canceled, issues: failed.join('; ')) : nil
|
||||
end
|
||||
|
||||
# The work order status for canceled orders (plugin setting, else a closed status named Canceled)
|
||||
def canceled_status
|
||||
id = settings['refund_canceled_status_id']
|
||||
(IssueStatus.find_by(id: id) if id.present?) ||
|
||||
IssueStatus.where(is_closed: true).detect { |s| CANCELED_STATUS_NAMES.include?(s.name.to_s.strip) }
|
||||
end
|
||||
|
||||
# Emails the customer a summary; returns a warning, or nil
|
||||
def email_customer(record, customer, mailer)
|
||||
email = customer.email.to_s.strip
|
||||
return I18n.t(:text_refund_no_email) if email.blank?
|
||||
|
||||
mailer.refund_summary(record, email).deliver_now
|
||||
record.update!(emailed_to: email)
|
||||
nil
|
||||
rescue StandardError => e
|
||||
I18n.t(:text_refund_email_failed, error: e.message)
|
||||
end
|
||||
|
||||
def money(amount)
|
||||
whole, cents = format('%.2f', amount.to_d.abs).split('.')
|
||||
"#{'-' if amount.to_d.negative?}$#{whole.reverse.scan(/\d{1,3}/).join(',').reverse}.#{cents}"
|
||||
end
|
||||
|
||||
def plain(number)
|
||||
number = number.to_d
|
||||
number == number.to_i ? number.to_i.to_s : number.to_s('F')
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -21,4 +21,9 @@ namespace :redmine_qbo do
|
||||
|
||||
puts "Checked #{estimates.size} estimate(s), created #{total} relation(s)."
|
||||
end
|
||||
|
||||
desc "Delete customer share links that have expired or whose issue was deleted (also done whenever a link is made)"
|
||||
task purge_customer_tokens: :environment do
|
||||
puts "Deleted #{CustomerToken.purge_expired} customer share link(s)."
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,87 @@
|
||||
#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__)
|
||||
|
||||
# Files on an issue shared through a customer link (customers/view/:token) open for the anonymous
|
||||
# visitor holding the link, and nothing else does.
|
||||
class CustomerShareAttachmentsTest < Redmine::IntegrationTest
|
||||
fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
|
||||
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations, :attachments, :journals
|
||||
|
||||
# Issue 4 is in a private project; attachment 7 is on it, attachment 1 is on issue 3.
|
||||
def setup
|
||||
set_fixtures_attachments_directory
|
||||
CustomerToken.delete_all
|
||||
User.current = User.find(1)
|
||||
@token = CustomerToken.create!(issue_id: 4, expires_at: 1.week.from_now)
|
||||
User.current = nil
|
||||
end
|
||||
|
||||
def teardown
|
||||
set_tmp_attachments_directory
|
||||
end
|
||||
|
||||
def open_share_link
|
||||
get "/customers/view/#{@token.token}"
|
||||
assert_response :success
|
||||
end
|
||||
|
||||
def test_without_the_link_files_need_a_login
|
||||
with_settings login_required: '1' do
|
||||
get '/attachments/download/7/archive.zip'
|
||||
assert_redirected_to %r{/login}
|
||||
end
|
||||
end
|
||||
|
||||
def test_share_link_opens_the_issues_files
|
||||
with_settings login_required: '1' do
|
||||
open_share_link
|
||||
assert_select 'a[href=?]', '/attachments/7'
|
||||
|
||||
get '/attachments/7'
|
||||
assert_response :success
|
||||
get '/attachments/download/7/archive.zip'
|
||||
assert_response :success
|
||||
assert_equal 'application/zip', response.media_type
|
||||
get '/attachments/issues/4/download'
|
||||
assert_response :success
|
||||
end
|
||||
end
|
||||
|
||||
def test_share_link_does_not_open_other_files
|
||||
with_settings login_required: '1' do
|
||||
open_share_link
|
||||
get '/attachments/download/1/error281.txt'
|
||||
assert_redirected_to %r{/login}
|
||||
get '/attachments/issues/3/download'
|
||||
assert_redirected_to %r{/login}
|
||||
end
|
||||
end
|
||||
|
||||
def test_files_on_private_notes_stay_hidden
|
||||
journal = Journal.create!(journalized: Issue.find(4), user: User.find(1), notes: 'internal', private_notes: true)
|
||||
Attachment.find(1).update_columns(container_type: 'Journal', container_id: journal.id)
|
||||
with_settings login_required: '1' do
|
||||
open_share_link
|
||||
get '/attachments/download/1/error281.txt'
|
||||
assert_redirected_to %r{/login}
|
||||
end
|
||||
end
|
||||
|
||||
def test_expired_link_opens_nothing
|
||||
with_settings login_required: '1' do
|
||||
open_share_link
|
||||
@token.update_columns(expires_at: 1.minute.ago)
|
||||
get '/attachments/download/7/archive.zip'
|
||||
assert_redirected_to %r{/login}
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,194 @@
|
||||
#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 CustomersControllerTest < 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
|
||||
|
||||
def setup
|
||||
# The search keeps its rows in memory, keyed by customer count and newest change (to the second); tests
|
||||
# roll back, so two tests can make the same key with different customers
|
||||
CustomerSearchService.instance_variable_set(:@candidates, nil)
|
||||
Customer.where(id: [9101, 9102]).delete_all
|
||||
@customer = local_customer(9101, 'Jane Customer')
|
||||
@customer.update_columns(phone_number: '4015550101')
|
||||
local_customer(9102, 'Bob Builder')
|
||||
Issue.find(1).update_column(:customer_id, 9101)
|
||||
Issue.find(8).update_column(:customer_id, 9101)
|
||||
CustomerToken.delete_all
|
||||
@fake = install_fake_quickbooks
|
||||
end
|
||||
|
||||
# Gives jsmith's Manager role the permissions and logs jsmith in (again, if someone was logged in)
|
||||
def grant(*permissions)
|
||||
permissions.each { |p| Role.find(1).add_permission!(p) }
|
||||
reset!
|
||||
log_user('jsmith', 'jsmith')
|
||||
end
|
||||
|
||||
def test_pages_need_view_customers
|
||||
log_user('jsmith', 'jsmith')
|
||||
Role.find(1).remove_permission!(:view_customers)
|
||||
get '/customers'
|
||||
assert_response :forbidden
|
||||
get '/customers/9101'
|
||||
assert_response :forbidden
|
||||
get '/customers/autocomplete', params: { q: 'jane' }
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_index_lists_and_sorts
|
||||
grant(:view_customers)
|
||||
get '/customers', params: { sort: 'name' }
|
||||
assert_response :success
|
||||
assert_select 'a[href=?]', '/customers/9101'
|
||||
assert_select 'a[href=?]', '/customers/9102'
|
||||
end
|
||||
|
||||
def test_a_single_search_match_opens_the_customer
|
||||
grant(:view_customers)
|
||||
get '/customers', params: { search: 'Jane Customer' }
|
||||
assert_redirected_to '/customers/9101'
|
||||
end
|
||||
|
||||
def test_show_lists_open_and_closed_issues
|
||||
grant(:view_customers)
|
||||
get '/customers/9101'
|
||||
assert_response :success
|
||||
assert_select 'a[href=?]', '/issues/1'
|
||||
assert_select 'a[href=?]', '/issues/8'
|
||||
get '/customers/424242'
|
||||
assert_response :not_found
|
||||
end
|
||||
|
||||
def test_autocomplete
|
||||
grant(:view_customers)
|
||||
get '/customers/autocomplete', params: { q: 'jane custmer' }
|
||||
assert_response :success
|
||||
assert_equal [9101], JSON.parse(response.body).map { |c| c['id'] }
|
||||
get '/customers/autocomplete', params: { phone: '0101' }
|
||||
assert_equal ['Jane Customer'], JSON.parse(response.body).map { |c| c['name'] }
|
||||
end
|
||||
|
||||
def test_create_needs_add_customers
|
||||
grant(:view_customers)
|
||||
Role.find(1).remove_permission!(:add_customers)
|
||||
get '/customers/new'
|
||||
assert_response :forbidden
|
||||
post '/customers', params: { customer: { name: 'New Person' } }
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_create_pushes_to_quickbooks
|
||||
grant(:view_customers, :add_customers)
|
||||
post '/customers', params: { customer: { name: 'new person', phone_number: '(401) 555-0123', email: 'new@example.com' } }
|
||||
customer = Customer.find_by(name: 'New Person')
|
||||
assert customer, 'customer created'
|
||||
assert_redirected_to "/customers/#{customer.id}"
|
||||
assert_equal '4015550123', customer.phone_number
|
||||
assert_equal 'new@example.com', @fake.created.last.email_address.address
|
||||
end
|
||||
|
||||
# Customers are created from the page only; JSON requests are refused
|
||||
def test_json_create_is_refused
|
||||
Role.find(1).add_permission!(:view_customers)
|
||||
Role.find(1).add_permission!(:add_customers)
|
||||
with_settings rest_api_enabled: '1' do
|
||||
post '/customers.json', params: { customer: { name: 'Json Person' } },
|
||||
headers: { 'X-Redmine-API-Key' => User.find(2).api_key }
|
||||
end
|
||||
assert_includes [401, 403, 406], response.status
|
||||
assert_not Customer.exists?(name: 'Json Person')
|
||||
end
|
||||
|
||||
def test_invalid_customer_shows_the_form_again
|
||||
grant(:view_customers, :add_customers)
|
||||
post '/customers', params: { customer: { name: '' } }
|
||||
assert_response :unprocessable_entity
|
||||
assert_select '#errorExplanation'
|
||||
end
|
||||
|
||||
def test_quickbooks_error_on_create_is_shown
|
||||
grant(:view_customers, :add_customers)
|
||||
@fake.define_singleton_method(:create) { |_doc| raise Quickbooks::IntuitRequestException, 'Duplicate Name Exists' }
|
||||
post '/customers', params: { customer: { name: 'Jane Customer' } }
|
||||
assert_redirected_to '/customers/new'
|
||||
assert_match 'Duplicate Name Exists', flash[:error]
|
||||
end
|
||||
|
||||
def test_update_needs_edit_customers
|
||||
grant(:view_customers)
|
||||
Role.find(1).remove_permission!(:edit_customers)
|
||||
patch '/customers/9101', params: { customer: { name: 'Changed' } }
|
||||
assert_response :forbidden
|
||||
|
||||
grant(:edit_customers)
|
||||
get '/customers/9101/edit'
|
||||
assert_response :success
|
||||
patch '/customers/9101', params: { customer: { name: 'jane changed' } }
|
||||
assert_redirected_to '/customers/9101'
|
||||
assert_equal 'Jane Changed', @customer.reload.name
|
||||
assert_equal 'Jane Changed', @fake.updated.last.display_name
|
||||
end
|
||||
|
||||
def test_sync_is_admin_only
|
||||
grant(:view_customers)
|
||||
get '/customers/sync'
|
||||
assert_response :forbidden
|
||||
reset!
|
||||
log_user('admin', 'admin')
|
||||
Customer.expects(:sync)
|
||||
get '/customers/sync'
|
||||
assert_response :redirect
|
||||
end
|
||||
|
||||
# ---- share links ----
|
||||
|
||||
def test_share_needs_the_permission_and_a_visible_issue
|
||||
grant(:view_customers)
|
||||
Role.find(1).remove_permission!(:share_issues_with_customers)
|
||||
get '/customers/share/1'
|
||||
assert_response :forbidden
|
||||
|
||||
grant(:share_issues_with_customers)
|
||||
get '/customers/share/1'
|
||||
token = CustomerToken.find_by(issue_id: 1)
|
||||
assert_redirected_to "/customers/view/#{token.token}"
|
||||
Project.find(2).update_column(:is_public, false)
|
||||
Member.where(user_id: 2, project_id: 2).destroy_all
|
||||
hidden = Issue.find(4)
|
||||
assert_not hidden.visible?(User.find(2))
|
||||
get "/customers/share/#{hidden.id}"
|
||||
assert_response :not_found
|
||||
assert_not CustomerToken.exists?(issue_id: hidden.id)
|
||||
end
|
||||
|
||||
def test_share_link_shows_the_issue_to_anyone
|
||||
token = CustomerToken.create!(issue_id: 1, expires_at: 1.week.from_now)
|
||||
with_settings login_required: '1' do
|
||||
get "/customers/view/#{token.token}"
|
||||
end
|
||||
assert_response :success
|
||||
assert_select 'h3, h2, div.subject', text: /#{Regexp.escape(Issue.find(1).subject)}/
|
||||
end
|
||||
|
||||
def test_expired_or_unknown_share_links_are_refused
|
||||
expired = CustomerToken.create!(issue_id: 1, expires_at: 1.week.from_now)
|
||||
expired.update_column(:expires_at, 1.day.ago)
|
||||
get "/customers/view/#{expired.token}"
|
||||
assert_response :forbidden
|
||||
get '/customers/view/not-a-token'
|
||||
assert_response :forbidden
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,188 @@
|
||||
#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__)
|
||||
|
||||
# Estimate and invoice PDFs: users with a billing permission open any of them; other logged-in users only the
|
||||
# documents attached to issues they can see; share-link customers only their own issue's documents
|
||||
class DocumentPdfsTest < Redmine::IntegrationTest
|
||||
include QboFakeServiceHelper
|
||||
fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
|
||||
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations
|
||||
|
||||
def setup
|
||||
local_customer
|
||||
Estimate.where(id: [598, 599]).delete_all
|
||||
Invoice.where(id: [601, 602]).delete_all
|
||||
Estimate.create!(id: 598, doc_number: '1068', customer_id: 9101)
|
||||
Estimate.create!(id: 599, doc_number: '1069', customer_id: 9101)
|
||||
@invoice = Invoice.create!(id: 601, doc_number: '1234', customer_id: 9101, txn_date: Date.new(2026, 11, 12))
|
||||
Invoice.create!(id: 602, doc_number: '1235', customer_id: 9101, txn_date: Date.new(2026, 11, 12))
|
||||
issue = Issue.find(1)
|
||||
issue.update_column(:estimate_id, 598)
|
||||
issue.invoices = [@invoice]
|
||||
CustomerToken.delete_all
|
||||
@token = CustomerToken.create!(issue_id: 1, expires_at: 1.week.from_now)
|
||||
@fake = install_fake_quickbooks
|
||||
[qbo_estimate(id: 598, doc_number: '1068'), qbo_estimate(id: 599, doc_number: '1069'),
|
||||
qbo_invoice(id: 601, doc_number: '1234'), qbo_invoice(id: 602, doc_number: '1235')].each { |d| @fake.add(d) }
|
||||
@fake.pdf_body = CombinePDF.new.tap { |pdf| pdf << CombinePDF.create_page }.to_pdf
|
||||
Role.find(1).remove_permission!(:view_customers, :write_estimates, :write_invoices, :view_payments,
|
||||
:receive_payments, :issue_refunds)
|
||||
end
|
||||
|
||||
def login(*permissions)
|
||||
permissions.each { |p| Role.find(1).add_permission!(p) }
|
||||
reset!
|
||||
log_user('jsmith', 'jsmith')
|
||||
end
|
||||
|
||||
def open_share_link
|
||||
get "/customers/view/#{@token.token}"
|
||||
assert_response :success
|
||||
end
|
||||
|
||||
def test_billing_users_open_any_estimate
|
||||
%i[view_customers write_estimates].each do |permission|
|
||||
Role.find(1).remove_permission!(:view_customers, :write_estimates)
|
||||
login(permission)
|
||||
get '/estimates/599'
|
||||
assert_response :success, permission
|
||||
assert_equal 'application/pdf', response.media_type
|
||||
assert_match 'estimate 1069.pdf', response.headers['Content-Disposition']
|
||||
get '/estimates/doc', params: { search: '1069' }
|
||||
assert_response :success, permission
|
||||
end
|
||||
end
|
||||
|
||||
def test_other_users_open_only_estimates_on_issues_they_can_see
|
||||
login
|
||||
get '/estimates/598'
|
||||
assert_response :success
|
||||
get '/estimates/doc', params: { search: '1068' }
|
||||
assert_response :success
|
||||
get '/estimates/599'
|
||||
assert_response :forbidden
|
||||
get '/estimates/doc', params: { search: '1069' }
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_estimate_on_a_hidden_issue_is_refused
|
||||
Issue.find(1).update_column(:estimate_id, nil)
|
||||
Issue.find(4).update_column(:estimate_id, 598)
|
||||
Project.find(2).update_column(:is_public, false)
|
||||
Member.where(user_id: 2, project_id: 2).destroy_all
|
||||
login
|
||||
get '/estimates/598'
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_only_billing_users_sync_missing_estimates
|
||||
login
|
||||
Estimate.expects(:sync_by_id).never
|
||||
get '/estimates/777'
|
||||
assert_response :forbidden
|
||||
|
||||
login(:view_customers)
|
||||
Estimate.expects(:sync_by_id).with('777')
|
||||
get '/estimates/777'
|
||||
assert_response :redirect
|
||||
assert_equal I18n.t(:notice_estimate_not_found), flash[:error]
|
||||
end
|
||||
|
||||
def test_billing_users_open_any_invoice
|
||||
%i[view_customers write_invoices view_payments receive_payments issue_refunds].each do |permission|
|
||||
Role.find(1).remove_permission!(:view_customers, :write_invoices, :view_payments, :receive_payments, :issue_refunds)
|
||||
login(permission)
|
||||
get '/invoices/602'
|
||||
assert_response :success, permission
|
||||
get '/invoices/601', params: { invoice_ids: %w[601 602] }
|
||||
assert_response :success, permission
|
||||
end
|
||||
end
|
||||
|
||||
def test_other_users_open_only_invoices_on_issues_they_can_see
|
||||
login
|
||||
get '/invoices/601'
|
||||
assert_response :success
|
||||
assert_match 'invoice 1234.pdf', response.headers['Content-Disposition']
|
||||
get '/invoices/602'
|
||||
assert_response :forbidden
|
||||
get '/invoices/601', params: { invoice_ids: %w[601 602] }
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_estimate_search_shows_only_to_billing_users
|
||||
login
|
||||
get '/projects/ecookbook/issues'
|
||||
assert_select '#estimate-search-form', 0
|
||||
login(:write_estimates)
|
||||
get '/projects/ecookbook/issues'
|
||||
assert_select '#estimate-search-form'
|
||||
end
|
||||
|
||||
def test_anonymous_visitors_must_log_in
|
||||
get '/estimates/598'
|
||||
assert_redirected_to %r{/login}
|
||||
get '/invoices/601'
|
||||
assert_redirected_to %r{/login}
|
||||
end
|
||||
|
||||
def test_share_link_customer_sees_only_their_estimate
|
||||
open_share_link
|
||||
get '/estimates/598'
|
||||
assert_response :success
|
||||
get '/estimates/doc', params: { search: '1068' }
|
||||
assert_response :success
|
||||
get '/estimates/599'
|
||||
assert_response :forbidden
|
||||
get '/estimates/doc', params: { search: '1069' }
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_share_link_customer_sees_only_their_invoices
|
||||
open_share_link
|
||||
get '/invoices/601'
|
||||
assert_response :success
|
||||
assert_match 'invoice 1234.pdf', response.headers['Content-Disposition']
|
||||
get '/invoices/602'
|
||||
assert_response :forbidden
|
||||
get '/invoices/601', params: { invoice_ids: %w[601 602] }
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_expired_share_link_stops_working
|
||||
open_share_link
|
||||
@token.update_column(:expires_at, 1.minute.ago)
|
||||
get '/invoices/601'
|
||||
assert_redirected_to %r{/login}
|
||||
end
|
||||
|
||||
def test_invoice_pdf_failure_redirects
|
||||
login(:write_invoices)
|
||||
get '/invoices/999'
|
||||
assert_response :redirect
|
||||
assert_equal I18n.t(:notice_invoice_not_found), flash[:error]
|
||||
end
|
||||
|
||||
def test_syncs_are_admin_only
|
||||
login
|
||||
get '/estimates/sync'
|
||||
assert_response :forbidden
|
||||
get '/invoices/sync'
|
||||
assert_response :forbidden
|
||||
reset!
|
||||
log_user('admin', 'admin')
|
||||
Estimate.expects(:sync)
|
||||
Invoice.expects(:sync)
|
||||
get '/estimates/sync'
|
||||
get '/invoices/sync'
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,164 @@
|
||||
#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__)
|
||||
|
||||
# Items, accounts and employee syncs (admin), and the business report
|
||||
class QboAdminPagesTest < Redmine::IntegrationTest
|
||||
include QboFakeServiceHelper
|
||||
fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
|
||||
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations, :workflows
|
||||
|
||||
def setup
|
||||
Item.where(id: [9701, 9702]).delete_all
|
||||
Account.where(id: [9801, 9802]).delete_all
|
||||
@fake = install_fake_quickbooks
|
||||
end
|
||||
|
||||
def item(id, name, attrs = {})
|
||||
Item.new({ id: id, name: name, description: '', unit_price: 10, active: true, type: 'Service' }.merge(attrs))
|
||||
.tap { |i| i.skip_qbo_push = true }.tap(&:save!)
|
||||
end
|
||||
|
||||
def admin
|
||||
reset!
|
||||
log_user('admin', 'admin')
|
||||
end
|
||||
|
||||
def jsmith
|
||||
reset!
|
||||
log_user('jsmith', 'jsmith')
|
||||
end
|
||||
|
||||
def test_items_are_admin_only
|
||||
item(9701, 'Labor')
|
||||
jsmith
|
||||
%w[/items /items/new /items/9701 /items/9701/edit /items/sync /accounts /accounts/sync /employees/sync].each do |path|
|
||||
get path
|
||||
assert_response :forbidden, path
|
||||
end
|
||||
post '/items', params: { item: { name: 'Sneaky' } }
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_item_pages
|
||||
item(9701, 'Labor')
|
||||
admin
|
||||
get '/items'
|
||||
assert_response :success
|
||||
assert_select 'body', text: /Labor/
|
||||
get '/items/9701'
|
||||
assert_response :success
|
||||
get '/items/9701/edit'
|
||||
assert_response :success
|
||||
get '/items/424242'
|
||||
assert_response :not_found
|
||||
end
|
||||
|
||||
def test_create_item_in_quickbooks
|
||||
admin
|
||||
post '/items', params: { item: { name: 'Brake Pads', description: 'Front pads', unit_price: '45', type: 'NonInventory', taxable: '1' } }
|
||||
created = @fake.created.last
|
||||
assert_equal 'Brake Pads', created.name
|
||||
assert_redirected_to "/items/#{created.id}"
|
||||
assert Item.exists?(created.id.to_i)
|
||||
end
|
||||
|
||||
def test_duplicate_name_opens_the_existing_item
|
||||
admin
|
||||
@fake.define_singleton_method(:create) do |_doc|
|
||||
raise Quickbooks::IntuitRequestException, "Duplicate Name Exists Error:\nThe name supplied already exists. : Id=9702"
|
||||
end
|
||||
post '/items', params: { item: { name: 'Labor', description: '', unit_price: '1' } }
|
||||
assert_redirected_to '/items/9702'
|
||||
end
|
||||
|
||||
def test_update_and_destroy_item
|
||||
item(9701, 'Labor')
|
||||
admin
|
||||
patch '/items/9701', params: { item: { name: 'Shop Labor', unit_price: '125' } }
|
||||
assert_redirected_to '/items/9701'
|
||||
assert_equal 'Shop Labor', Item.find(9701).name
|
||||
assert_equal 'Shop Labor', @fake.updated.last.name
|
||||
|
||||
patch '/items/9701', params: { item: { unit_price: '-1' } }
|
||||
assert_response :unprocessable_entity
|
||||
|
||||
delete '/items/9701'
|
||||
assert_redirected_to '/items'
|
||||
assert_not Item.exists?(9701)
|
||||
assert_equal false, @fake.updated.last.active?
|
||||
end
|
||||
|
||||
def test_item_autocomplete_lists_sellable_items
|
||||
item(9701, 'Labor', description: 'Shop labor')
|
||||
item(9702, 'Labor old', active: false)
|
||||
admin
|
||||
get '/items/autocomplete', params: { q: 'lab' }
|
||||
assert_equal [9701], JSON.parse(response.body).map { |i| i['id'] }
|
||||
end
|
||||
|
||||
def test_accounts
|
||||
Account.create!(id: 9801, name: 'Sales', classification: 'Revenue')
|
||||
Account.create!(id: 9802, name: 'Rent', classification: 'Expense')
|
||||
admin
|
||||
get '/accounts'
|
||||
assert_response :success
|
||||
assert_select 'body', text: /Sales/
|
||||
patch '/accounts/set_default', params: { default_account_id: 9801 }
|
||||
assert_redirected_to '/accounts'
|
||||
assert Account.find(9801).default
|
||||
patch '/accounts/set_default', params: { default_account_id: 424_242 }
|
||||
assert_equal I18n.t(:error_default_account_not_selected), flash[:error]
|
||||
end
|
||||
|
||||
def test_admin_syncs
|
||||
admin
|
||||
Item.expects(:sync)
|
||||
Account.expects(:sync)
|
||||
Employee.expects(:sync)
|
||||
Payment.expects(:sync)
|
||||
%w[/items/sync /accounts/sync /employees/sync /qbo_payments/sync].each do |path|
|
||||
get path
|
||||
assert_response :redirect, path
|
||||
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
|
||||
Role.find(1).remove_permission!(:view_business_reports)
|
||||
jsmith
|
||||
get '/qbo_reports'
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_report_remembers_projects
|
||||
Role.find(1).add_permission!(:view_business_reports)
|
||||
jsmith
|
||||
get '/qbo_reports', params: { period: 'last_month' }
|
||||
assert_response :success
|
||||
get '/qbo_reports', params: { project_ids: ['1', '999'], save_projects: '1' }
|
||||
assert_response :success
|
||||
assert_equal [1], User.find(2).pref[:qbo_report_project_ids]
|
||||
get '/qbo_reports'
|
||||
assert_response :success
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,182 @@
|
||||
#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__)
|
||||
|
||||
# Connecting to QuickBooks, manual syncs and billing, and Intuit's webhook
|
||||
class QboControllerTest < Redmine::IntegrationTest
|
||||
fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
|
||||
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations, :workflows
|
||||
|
||||
SECRET = 'webhook-secret'.freeze
|
||||
|
||||
def setup
|
||||
Qbo.delete_all
|
||||
Customer.where(id: 9101).delete_all
|
||||
end
|
||||
|
||||
# Redmine keeps plugin settings with indifferent access (RedmineQbo.settings reads symbol keys)
|
||||
def settings(token)
|
||||
{ 'webhook_token' => token }.with_indifferent_access
|
||||
end
|
||||
|
||||
def signed(body, secret = SECRET)
|
||||
Base64.strict_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), secret, body))
|
||||
end
|
||||
|
||||
def post_webhook(body, signature)
|
||||
post '/qbo/webhook', params: body, headers: { 'CONTENT_TYPE' => 'application/json', 'intuit-signature' => signature }
|
||||
end
|
||||
|
||||
# ---- webhook ----
|
||||
|
||||
def test_webhook_with_a_valid_signature_queues_the_job
|
||||
body = '{"eventNotifications":[]}'
|
||||
WebhookProcessJob.expects(:perform_later).with(body)
|
||||
with_settings plugin_redmine_qbo: settings(SECRET) do
|
||||
post_webhook(body, signed(body))
|
||||
end
|
||||
assert_response :ok
|
||||
end
|
||||
|
||||
def test_webhook_refuses_bad_or_missing_signatures
|
||||
body = '{"eventNotifications":[]}'
|
||||
WebhookProcessJob.expects(:perform_later).never
|
||||
with_settings plugin_redmine_qbo: settings(SECRET) do
|
||||
post_webhook(body, signed(body, 'wrong'))
|
||||
assert_response :unauthorized
|
||||
post_webhook(body, '')
|
||||
assert_response :unauthorized
|
||||
end
|
||||
with_settings plugin_redmine_qbo: settings('') do
|
||||
post_webhook(body, signed(body, ''))
|
||||
assert_response :unauthorized
|
||||
end
|
||||
end
|
||||
|
||||
def test_webhook_needs_no_login
|
||||
body = '{}'
|
||||
WebhookProcessJob.stubs(:perform_later)
|
||||
with_settings login_required: '1', plugin_redmine_qbo: settings(SECRET) do
|
||||
post_webhook(body, signed(body))
|
||||
end
|
||||
assert_response :ok
|
||||
end
|
||||
|
||||
# ---- admin pages ----
|
||||
|
||||
def test_connecting_and_syncing_are_admin_only
|
||||
log_user('jsmith', 'jsmith')
|
||||
get '/qbo/authenticate'
|
||||
assert_response :forbidden
|
||||
get '/qbo/sync'
|
||||
assert_response :forbidden
|
||||
get '/qbo/oauth_callback', params: { code: 'x', state: 'y', realmId: '1' }
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_authenticate_redirects_to_intuit_with_a_state
|
||||
log_user('admin', 'admin')
|
||||
QboOauthService.expects(:authorization_url).with { |args| args[:state].present? && args[:callback_url].end_with?('/qbo/oauth_callback') }
|
||||
.returns('https://appcenter.intuit.com/connect/oauth2?x=1')
|
||||
get '/qbo/authenticate'
|
||||
assert_redirected_to 'https://appcenter.intuit.com/connect/oauth2?x=1'
|
||||
end
|
||||
|
||||
def test_oauth_callback_checks_the_state
|
||||
log_user('admin', 'admin')
|
||||
QboOauthService.expects(:exchange!).never
|
||||
get '/qbo/oauth_callback', params: { code: 'abc', state: 'forged', realmId: '123' }
|
||||
assert_redirected_to '/settings/plugin/redmine_qbo'
|
||||
assert_equal I18n.t(:notice_qbo_oauth_state_mismatch), flash[:error]
|
||||
end
|
||||
|
||||
def test_oauth_callback_connects
|
||||
log_user('admin', 'admin')
|
||||
state = nil
|
||||
QboOauthService.stubs(:authorization_url).with { |args| state = args[:state] }.returns('https://intuit.example/')
|
||||
get '/qbo/authenticate'
|
||||
QboOauthService.expects(:exchange!).with(code: 'abc', callback_url: anything, realm_id: '123')
|
||||
get '/qbo/oauth_callback', params: { code: 'abc', state: state, realmId: '123' }
|
||||
assert_redirected_to '/qbo/sync'
|
||||
assert_equal I18n.t(:label_connected), flash[:notice]
|
||||
|
||||
# The state is used once
|
||||
get '/qbo/oauth_callback', params: { code: 'abc', state: state, realmId: '123' }
|
||||
assert_equal I18n.t(:notice_qbo_oauth_state_mismatch), flash[:error]
|
||||
end
|
||||
|
||||
def test_oauth_failure_is_reported
|
||||
log_user('admin', 'admin')
|
||||
state = nil
|
||||
QboOauthService.stubs(:authorization_url).with { |args| state = args[:state] }.returns('https://intuit.example/')
|
||||
get '/qbo/authenticate'
|
||||
QboOauthService.stubs(:exchange!).raises(OAuth2::Error.new(Struct.new(:parsed, :body, :status).new({}, 'bad', 400)))
|
||||
get '/qbo/oauth_callback', params: { code: 'abc', state: state, realmId: '123' }
|
||||
assert_redirected_to '/settings/plugin/redmine_qbo'
|
||||
assert_equal I18n.t(:label_error), flash[:error]
|
||||
end
|
||||
|
||||
def test_sync
|
||||
log_user('admin', 'admin')
|
||||
QboSyncDispatcher.expects(:sync!).with(full_sync: true)
|
||||
get '/qbo/sync', params: { full_sync: 'true' }
|
||||
assert_response :redirect
|
||||
assert_equal I18n.t(:label_syncing), flash[:notice]
|
||||
end
|
||||
|
||||
# ---- billing ----
|
||||
|
||||
def billable_issue
|
||||
customer = Customer.new(id: 9101, name: 'Jane Customer')
|
||||
customer.skip_qbo_push = true
|
||||
customer.save!
|
||||
User.find(3).update_column(:employee_id, 31)
|
||||
Issue.find(1).tap { |i| i.update_columns(customer_id: 9101, assigned_to_id: 3) }
|
||||
end
|
||||
|
||||
def test_bill_needs_the_permission
|
||||
billable_issue
|
||||
log_user('jsmith', 'jsmith')
|
||||
Role.find(1).remove_permission!(:bill_issues)
|
||||
post '/bill/1'
|
||||
assert_response :forbidden
|
||||
post '/bill/99999'
|
||||
assert_response :not_found
|
||||
end
|
||||
|
||||
def test_bill_queues_the_job
|
||||
issue = billable_issue
|
||||
Qbo.new(realm_id: '1').save!(validate: false)
|
||||
Role.find(1).add_permission!(:bill_issues)
|
||||
log_user('jsmith', 'jsmith')
|
||||
BillIssueTimeJob.expects(:perform_later).with(issue.id)
|
||||
post "/bill/#{issue.id}"
|
||||
assert_redirected_to "/issues/#{issue.id}"
|
||||
assert_match 'Jane Customer', flash[:notice]
|
||||
end
|
||||
|
||||
def test_bill_explains_what_is_missing
|
||||
Role.find(1).add_permission!(:bill_issues)
|
||||
log_user('jsmith', 'jsmith')
|
||||
BillIssueTimeJob.expects(:perform_later).never
|
||||
Issue.find(1).update_columns(customer_id: nil)
|
||||
post '/bill/1'
|
||||
assert_equal I18n.t(:notice_billing_error_no_customer), flash[:error]
|
||||
|
||||
billable_issue
|
||||
post '/bill/1'
|
||||
assert_equal I18n.t(:notice_billing_error_no_qbo), flash[:error]
|
||||
|
||||
User.find(3).update_column(:employee_id, nil)
|
||||
post '/bill/1'
|
||||
assert_equal I18n.t(:notice_billing_error_no_employee), flash[:error]
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,250 @@
|
||||
#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 QboEstimatesControllerTest < Redmine::IntegrationTest
|
||||
include QboEditorTestHelper
|
||||
|
||||
def estimate_params(extra = {})
|
||||
{ customer_id: '9101', txn_date: '2026-11-20', email: 'jane@example.com', lines: line_params }.merge(extra)
|
||||
end
|
||||
|
||||
def test_editor_needs_write_estimates
|
||||
login_with(:view_customers)
|
||||
get '/qbo_estimates/new'
|
||||
assert_response :forbidden
|
||||
post '/qbo_estimates', params: { estimate: estimate_params }
|
||||
assert_response :forbidden
|
||||
assert_empty @fake.created
|
||||
end
|
||||
|
||||
def test_new_estimate
|
||||
login_with(:write_estimates)
|
||||
get '/qbo_estimates/new', params: { customer_id: 9101 }
|
||||
assert_response :success
|
||||
assert_select 'input[name=?][value=?]', 'estimate[customer_id]', '9101'
|
||||
end
|
||||
|
||||
def test_create
|
||||
login_with(:write_estimates)
|
||||
post '/qbo_estimates', params: { estimate: estimate_params }
|
||||
saved = @fake.created.first
|
||||
assert saved
|
||||
assert_redirected_to "/qbo_estimates/#{saved.id}/edit"
|
||||
assert_equal BigDecimal('240'), saved.line_items.first.amount
|
||||
end
|
||||
|
||||
def test_invalid_form_is_shown_again
|
||||
login_with(:write_estimates)
|
||||
post '/qbo_estimates', params: { estimate: estimate_params(customer_id: '', lines: {}) }
|
||||
assert_response :unprocessable_entity
|
||||
assert_select '#errorExplanation', text: /#{Regexp.escape(I18n.t(:error_estimate_needs_customer))}/
|
||||
assert_empty @fake.created
|
||||
end
|
||||
|
||||
def test_save_and_send_needs_send_estimates
|
||||
login_with(:write_estimates)
|
||||
post '/qbo_estimates', params: { estimate: estimate_params, save_and_send: '1' }
|
||||
assert_response :forbidden
|
||||
|
||||
login_with(:send_estimates)
|
||||
post '/qbo_estimates', params: { estimate: estimate_params, save_and_send: '1' }
|
||||
assert_equal [[@fake.created.first.id, 'jane@example.com']], @fake.sent
|
||||
end
|
||||
|
||||
def test_quickbooks_error_is_shown
|
||||
login_with(:write_estimates)
|
||||
@fake.define_singleton_method(:create) { |_doc| raise Quickbooks::IntuitRequestException, 'Business Validation Error' }
|
||||
post '/qbo_estimates', params: { estimate: estimate_params }
|
||||
assert_response :unprocessable_entity
|
||||
assert_select '#errorExplanation', text: /Business Validation Error/
|
||||
end
|
||||
|
||||
def test_edit_and_update
|
||||
login_with(:write_estimates)
|
||||
@fake.add(estimate_doc)
|
||||
get '/qbo_estimates/598/edit'
|
||||
assert_response :success
|
||||
assert_select 'fieldset.qbo-estimate-sheet[disabled]', 0
|
||||
|
||||
patch '/qbo_estimates/598', params: { estimate: estimate_params(sync_token: '3', lines: line_params(rate: '150')) }
|
||||
assert_redirected_to '/qbo_estimates/598/edit'
|
||||
assert_equal BigDecimal('300'), @fake.updated.first.line_items.first.amount
|
||||
end
|
||||
|
||||
def test_stale_update_is_a_conflict
|
||||
login_with(:write_estimates)
|
||||
@fake.add(estimate_doc)
|
||||
patch '/qbo_estimates/598', params: { estimate: estimate_params(sync_token: '1') }
|
||||
assert_response :unprocessable_entity
|
||||
assert_select '#errorExplanation', text: /#{Regexp.escape(I18n.t(:error_estimate_changed_in_quickbooks))}/
|
||||
end
|
||||
|
||||
def test_missing_estimate_redirects
|
||||
login_with(:write_estimates)
|
||||
get '/qbo_estimates/999/edit'
|
||||
assert_response :redirect
|
||||
assert_equal I18n.t(:notice_estimate_not_found), flash[:error]
|
||||
end
|
||||
|
||||
# ---- estimates linked to an issue ----
|
||||
|
||||
def test_linked_estimate_is_read_only_without_the_permission
|
||||
login_with(:write_estimates)
|
||||
@fake.add(estimate_doc)
|
||||
Issue.find(1).update_column(:estimate_id, 598)
|
||||
get '/qbo_estimates/598/edit'
|
||||
assert_select 'fieldset.qbo-estimate-sheet[disabled]'
|
||||
assert_select '#qbo-unlock-estimate', 0
|
||||
# Asking to unlock without the permission changes nothing
|
||||
get '/qbo_estimates/598/edit', params: { unlock: 1 }
|
||||
assert_select 'fieldset.qbo-estimate-sheet[disabled]'
|
||||
patch '/qbo_estimates/598', params: { estimate: estimate_params(sync_token: '3'), unlock: '1' }
|
||||
assert_response :unprocessable_entity
|
||||
assert_empty @fake.updated
|
||||
end
|
||||
|
||||
def test_unlock_a_linked_estimate
|
||||
login_with(:write_estimates, :edit_linked_estimates)
|
||||
@fake.add(estimate_doc)
|
||||
Issue.find(1).update_column(:estimate_id, 598)
|
||||
get '/qbo_estimates/598/edit'
|
||||
assert_select 'a#qbo-unlock-estimate[href=?][data-confirm=?]', '/qbo_estimates/598/edit?unlock=1',
|
||||
I18n.t(:text_unlock_estimate_confirmation)
|
||||
|
||||
get '/qbo_estimates/598/edit', params: { unlock: 1 }
|
||||
assert_select 'fieldset.qbo-estimate-sheet[disabled]', 0
|
||||
assert_select 'input[type=hidden][name=unlock][value="1"]'
|
||||
assert_select '.qbo-estimate-notice', text: /#{Regexp.escape(I18n.t(:text_estimate_unlocked))}/
|
||||
|
||||
patch '/qbo_estimates/598', params: { estimate: estimate_params(sync_token: '3', lines: line_params(rate: '150')), unlock: '1' }
|
||||
assert_redirected_to '/qbo_estimates/598/edit'
|
||||
assert_equal BigDecimal('300'), @fake.updated.first.line_items.first.amount
|
||||
assert_equal 598, Issue.find(1).estimate_id
|
||||
end
|
||||
|
||||
def test_billed_estimate_cannot_be_unlocked
|
||||
login_with(:write_estimates, :edit_linked_estimates)
|
||||
@fake.add(estimate_doc(status: 'Closed'))
|
||||
Issue.find(1).update_column(:estimate_id, 598)
|
||||
get '/qbo_estimates/598/edit', params: { unlock: 1 }
|
||||
assert_select 'fieldset.qbo-estimate-sheet[disabled]'
|
||||
patch '/qbo_estimates/598', params: { estimate: estimate_params(sync_token: '3'), unlock: '1' }
|
||||
assert_response :unprocessable_entity
|
||||
assert_empty @fake.updated
|
||||
end
|
||||
|
||||
# ---- duplicates, drafts, emails ----
|
||||
|
||||
def test_duplicate
|
||||
login_with(:write_estimates)
|
||||
@fake.add(estimate_doc)
|
||||
get '/qbo_estimates/new', params: { duplicate: 598 }
|
||||
assert_response :success
|
||||
assert_select '.flash.notice', text: /1068/
|
||||
end
|
||||
|
||||
def test_drafts
|
||||
login_with(:write_estimates)
|
||||
post '/qbo_estimates', params: { estimate: estimate_params(customer_id: '9101', lines: line_params), save_draft: '1' }
|
||||
draft = QboDraft.last
|
||||
assert_redirected_to "/qbo_estimates/new?draft_id=#{draft.id}"
|
||||
assert_equal [9101, 2], [draft.customer_id, draft.user_id]
|
||||
get "/qbo_estimates/new?draft_id=#{draft.id}"
|
||||
assert_response :success
|
||||
|
||||
# Saving to QuickBooks deletes the draft
|
||||
post '/qbo_estimates', params: { estimate: estimate_params, draft_id: draft.id }
|
||||
assert_not QboDraft.exists?(draft.id)
|
||||
|
||||
get '/qbo_estimates/new', params: { draft_id: draft.id }
|
||||
assert_redirected_to '/qbo_drafts'
|
||||
end
|
||||
|
||||
def test_send_email
|
||||
login_with(:write_estimates)
|
||||
@fake.add(estimate_doc)
|
||||
post '/qbo_estimates/598/send_email', params: { email: 'jane@example.com' }
|
||||
assert_response :forbidden
|
||||
login_with(:send_estimates)
|
||||
post '/qbo_estimates/598/send_email', params: { email: 'jane@example.com' }
|
||||
assert_redirected_to '/qbo_estimates/598/edit'
|
||||
assert_equal [%w[598 jane@example.com]], @fake.sent
|
||||
end
|
||||
|
||||
# ---- editor lookups ----
|
||||
|
||||
def test_customer_info
|
||||
login_with(:write_estimates)
|
||||
get '/qbo_estimates/customer_info', params: { customer_id: 9101 }
|
||||
assert_equal 'Jane Customer', JSON.parse(response.body)['name']
|
||||
get '/qbo_estimates/customer_info', params: { customer_id: 424_242 }
|
||||
assert_response :not_found
|
||||
get '/qbo_estimates/customer_info', params: { customer_id: 9101, document: 'invoice' }
|
||||
assert JSON.parse(response.body).key?('open_issues_html')
|
||||
end
|
||||
|
||||
def test_items_search
|
||||
Item.where(id: [9701, 9702]).delete_all
|
||||
[[9701, 'Labor', true], [9702, 'Lab coat', false]].each do |id, name, active|
|
||||
Item.new(id: id, name: name, description: '', unit_price: 120, active: active, type: 'Service')
|
||||
.tap { |i| i.skip_qbo_push = true }.save!
|
||||
end
|
||||
login_with(:write_invoices)
|
||||
get '/qbo_estimates/items', params: { q: 'lab' }
|
||||
assert_equal [9701], JSON.parse(response.body).map { |i| i['id'] }
|
||||
end
|
||||
|
||||
def test_refresh_company_is_admin_only
|
||||
login_with(:write_estimates)
|
||||
post '/qbo_estimates/refresh_company'
|
||||
assert_response :forbidden
|
||||
reset!
|
||||
log_user('admin', 'admin')
|
||||
RedmineQboBilling::Company.expects(:refresh!)
|
||||
post '/qbo_estimates/refresh_company'
|
||||
assert_response :redirect
|
||||
end
|
||||
|
||||
# ---- issues from an estimate ----
|
||||
|
||||
def test_issues_from_an_estimate
|
||||
Estimate.where(id: 598).delete_all
|
||||
Estimate.create!(id: 598, doc_number: '1068', customer_id: 9101)
|
||||
Estimate.any_instance.stubs(:line_items).returns([qbo_sales_line(2, 10, 'Labor', 2, 120, description: 'Install lift kit')])
|
||||
Setting.stubs(:plugin_redmine_qbo).returns('issue_default_project_id' => '1')
|
||||
@fake.add(estimate_doc)
|
||||
|
||||
login_with(:write_estimates)
|
||||
get '/qbo_estimates/598/issues_preview'
|
||||
assert_response :forbidden
|
||||
|
||||
login_with(:create_estimate_issues, :add_issues)
|
||||
get '/qbo_estimates/598/issues_preview'
|
||||
assert_response :success
|
||||
|
||||
post '/qbo_estimates/598/create_issues', params: { project_id: 1, lines: { '2' => { selected: '1', tracker_id: '1' } } }
|
||||
assert_redirected_to '/qbo_estimates/598/edit'
|
||||
issue = Issue.where(estimate_id: 598).last
|
||||
assert_equal 'Install Lift Kit', issue.subject
|
||||
# The work is going ahead: the estimate is accepted
|
||||
assert_equal 'Accepted', @fake.updated.last.txn_status
|
||||
end
|
||||
|
||||
def test_create_issues_with_nothing_selected
|
||||
Estimate.where(id: 598).delete_all
|
||||
Estimate.create!(id: 598, doc_number: '1068', customer_id: 9101)
|
||||
Estimate.any_instance.stubs(:line_items).returns([qbo_sales_line(2, 10, 'Labor', 2, 120, description: 'Install')])
|
||||
login_with(:create_estimate_issues, :add_issues)
|
||||
post '/qbo_estimates/598/create_issues', params: { project_id: 1, lines: {} }
|
||||
assert_response :unprocessable_entity
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,137 @@
|
||||
#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 QboInvoicesControllerTest < Redmine::IntegrationTest
|
||||
include QboEditorTestHelper
|
||||
|
||||
def invoice_params(extra = {})
|
||||
{ customer_id: '9101', txn_date: '2026-11-20', email: 'jane@example.com', lines: line_params }.merge(extra)
|
||||
end
|
||||
|
||||
def test_editor_needs_write_invoices
|
||||
login_with(:write_estimates)
|
||||
get '/qbo_invoices/new'
|
||||
assert_response :forbidden
|
||||
post '/qbo_invoices', params: { estimate: invoice_params }
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_new_and_create
|
||||
login_with(:write_invoices)
|
||||
get '/qbo_invoices/new', params: { customer_id: 9101 }
|
||||
assert_response :success
|
||||
post '/qbo_invoices', params: { estimate: invoice_params }
|
||||
saved = @fake.created.first
|
||||
assert_redirected_to "/qbo_invoices/#{saved.id}/edit"
|
||||
assert_kind_of Quickbooks::Model::Invoice, saved
|
||||
end
|
||||
|
||||
def test_new_from_an_estimate
|
||||
login_with(:write_invoices)
|
||||
@fake.add(estimate_doc)
|
||||
get '/qbo_invoices/new', params: { estimate_id: 598 }
|
||||
assert_response :success
|
||||
assert_select 'input[name=?][value=?]', 'estimate[linked_estimate_ids][]', '598'
|
||||
|
||||
post '/qbo_invoices', params: { estimate: invoice_params(linked_estimate_ids: ['598']) }
|
||||
assert_equal 'Closed', @fake.records['598'].txn_status
|
||||
end
|
||||
|
||||
def test_new_from_a_billed_estimate_explains_why
|
||||
login_with(:write_invoices)
|
||||
@fake.add(estimate_doc(status: 'Closed'))
|
||||
get '/qbo_invoices/new', params: { estimate_id: 598 }
|
||||
assert_not_equal 500, response.status
|
||||
assert_equal I18n.t(:error_estimate_closed_billed, number: '1068', status: 'Closed'), flash[:error]
|
||||
end
|
||||
|
||||
def test_save_and_send_needs_send_invoices
|
||||
login_with(:write_invoices)
|
||||
post '/qbo_invoices', params: { estimate: invoice_params, save_and_send: '1' }
|
||||
assert_response :forbidden
|
||||
login_with(:send_invoices)
|
||||
post '/qbo_invoices', params: { estimate: invoice_params, save_and_send: '1' }
|
||||
assert_equal 1, @fake.sent.size
|
||||
end
|
||||
|
||||
def test_edit_and_update
|
||||
login_with(:write_invoices)
|
||||
@fake.add(invoice_doc)
|
||||
get '/qbo_invoices/601/edit'
|
||||
assert_response :success
|
||||
patch '/qbo_invoices/601', params: { estimate: invoice_params(sync_token: '3', lines: line_params(rate: '150')) }
|
||||
assert_redirected_to '/qbo_invoices/601/edit'
|
||||
assert_equal BigDecimal('300'), @fake.updated.first.line_items.first.amount
|
||||
end
|
||||
|
||||
def test_paid_invoice_is_locked
|
||||
login_with(:write_invoices)
|
||||
@fake.add(invoice_doc(balance: '0'))
|
||||
get '/qbo_invoices/601/edit'
|
||||
assert_select 'fieldset.qbo-estimate-sheet[disabled]'
|
||||
assert_select '#qbo-unlock-invoice', 0
|
||||
patch '/qbo_invoices/601', params: { estimate: invoice_params(sync_token: '3'), unlock: '1' }
|
||||
assert_response :unprocessable_entity
|
||||
assert_empty @fake.updated
|
||||
end
|
||||
|
||||
def test_unlock_a_paid_invoice
|
||||
login_with(:write_invoices, :edit_paid_invoices)
|
||||
@fake.add(invoice_doc(balance: '0'))
|
||||
get '/qbo_invoices/601/edit'
|
||||
assert_select 'a#qbo-unlock-invoice[href=?]', '/qbo_invoices/601/edit?unlock=1'
|
||||
get '/qbo_invoices/601/edit', params: { unlock: 1 }
|
||||
assert_select 'fieldset.qbo-estimate-sheet[disabled]', 0
|
||||
patch '/qbo_invoices/601', params: { estimate: invoice_params(sync_token: '3', balance: '0'), unlock: '1' }
|
||||
assert_redirected_to '/qbo_invoices/601/edit'
|
||||
end
|
||||
|
||||
def test_partly_paid_invoice_needs_its_own_permission
|
||||
login_with(:write_invoices, :edit_paid_invoices)
|
||||
@fake.add(invoice_doc(balance: '100'))
|
||||
get '/qbo_invoices/601/edit'
|
||||
assert_select '#qbo-unlock-invoice', 0
|
||||
login_with(:edit_partially_paid_invoices)
|
||||
get '/qbo_invoices/601/edit'
|
||||
assert_select '#qbo-unlock-invoice'
|
||||
end
|
||||
|
||||
def test_import_options
|
||||
login_with(:write_invoices)
|
||||
@fake.query_results = { 'FROM Estimate' => [estimate_doc] }
|
||||
get '/qbo_invoices/import_options', params: { customer_id: 9101 }
|
||||
assert_response :success
|
||||
data = JSON.parse(response.body)
|
||||
assert_equal ['598'], data['estimates'].map { |e| e['id'] }
|
||||
get '/qbo_invoices/import_options', params: { customer_id: 424_242 }
|
||||
assert_response :not_found
|
||||
end
|
||||
|
||||
def test_send_email
|
||||
login_with(:write_invoices, :send_invoices)
|
||||
@fake.add(invoice_doc)
|
||||
post '/qbo_invoices/601/send_email', params: { email: 'jane@example.com' }
|
||||
assert_redirected_to '/qbo_invoices/601/edit'
|
||||
assert_equal [%w[601 jane@example.com]], @fake.sent
|
||||
end
|
||||
|
||||
def test_drafts
|
||||
login_with(:write_invoices)
|
||||
post '/qbo_invoices', params: { estimate: invoice_params(sales_person: 'Ricky'), save_draft: '1' }
|
||||
draft = QboDraft.last
|
||||
assert draft.invoice?
|
||||
assert_equal 'Ricky', draft.fields['sales_person']
|
||||
assert_redirected_to "/qbo_invoices/new?draft_id=#{draft.id}"
|
||||
get "/qbo_invoices/new?draft_id=#{draft.id}"
|
||||
assert_response :success
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,129 @@
|
||||
#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 QboPaymentsAndDraftsControllerTest < Redmine::IntegrationTest
|
||||
include QboEditorTestHelper
|
||||
|
||||
def setup
|
||||
Invoice.where(id: 601).delete_all
|
||||
@fake.query_results = { 'FROM Invoice' => [invoice_doc(balance: '240')], 'PaymentMethod' => [
|
||||
Quickbooks::Model::PaymentMethod.new(id: 2, name: 'Check', active: true)
|
||||
] }
|
||||
end
|
||||
|
||||
def payment_params(extra = {})
|
||||
{ customer_id: '9101', txn_date: '2026-11-20', payment_method_id: '2', amount: '100' }.merge(extra)
|
||||
end
|
||||
|
||||
def saved_payment
|
||||
doc = Quickbooks::Model::Payment.new(customer_ref: qbo_ref(9101, 'Jane Customer'), txn_date: Date.new(2026, 11, 20),
|
||||
total: BigDecimal('100'), payment_method_ref: qbo_ref(2, 'Check'))
|
||||
doc.id = '801'
|
||||
doc.sync_token = 1
|
||||
doc.line_items = [Quickbooks::Model::Line.new.tap { |l| l.amount = BigDecimal('100'); l.invoice_id = '601' }]
|
||||
@fake.add(doc)
|
||||
end
|
||||
|
||||
def test_receiving_needs_receive_payments
|
||||
login_with(:view_payments)
|
||||
get '/qbo_payments/new'
|
||||
assert_response :forbidden
|
||||
post '/qbo_payments', params: { payment: payment_params }
|
||||
assert_response :forbidden
|
||||
get '/qbo_payments', params: { customer_id: 9101 }
|
||||
assert_response :success
|
||||
end
|
||||
|
||||
def test_receive_a_payment
|
||||
login_with(:receive_payments)
|
||||
get '/qbo_payments/new', params: { customer_id: 9101 }
|
||||
assert_response :success
|
||||
post '/qbo_payments', params: { payment: payment_params }
|
||||
payment = @fake.created.first
|
||||
assert_redirected_to "/qbo_payments/#{payment.id}"
|
||||
assert_equal BigDecimal('100'), payment.line_items.first.amount
|
||||
end
|
||||
|
||||
def test_invalid_payment
|
||||
login_with(:receive_payments)
|
||||
post '/qbo_payments', params: { payment: payment_params(amount: '0') }
|
||||
assert_response :unprocessable_entity
|
||||
assert_empty @fake.created
|
||||
end
|
||||
|
||||
def test_show_edit_update_pdf
|
||||
login_with(:receive_payments)
|
||||
saved_payment
|
||||
get '/qbo_payments/801'
|
||||
assert_response :success
|
||||
get '/qbo_payments/801/edit'
|
||||
assert_response :success
|
||||
patch '/qbo_payments/801', params: { payment: payment_params(sync_token: '1', invoice_ids: ['601'], memo: 'Edited') }
|
||||
assert_redirected_to '/qbo_payments/801'
|
||||
assert_equal 'Edited', @fake.updated.first.private_note
|
||||
@fake.pdf_body = '%PDF-1.4'
|
||||
get '/qbo_payments/801/pdf'
|
||||
assert_equal 'application/pdf', response.media_type
|
||||
end
|
||||
|
||||
def test_stale_payment_update
|
||||
login_with(:receive_payments)
|
||||
saved_payment
|
||||
patch '/qbo_payments/801', params: { payment: payment_params(sync_token: '0') }
|
||||
assert_response :unprocessable_entity
|
||||
end
|
||||
|
||||
def test_missing_payment
|
||||
login_with(:view_payments)
|
||||
get '/qbo_payments/999'
|
||||
assert_response :redirect
|
||||
assert_equal I18n.t(:notice_payment_not_found), flash[:error]
|
||||
end
|
||||
|
||||
def test_open_invoices
|
||||
login_with(:receive_payments)
|
||||
get '/qbo_payments/open_invoices', params: { customer_id: 9101 }
|
||||
assert_equal ['601'], JSON.parse(response.body).map { |i| i['id'] }
|
||||
get '/qbo_payments/open_invoices', params: { customer_id: 424_242 }
|
||||
assert_response :not_found
|
||||
end
|
||||
|
||||
def test_payment_sync_is_admin_only
|
||||
login_with(:receive_payments)
|
||||
get '/qbo_payments/sync'
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
# ---- drafts ----
|
||||
|
||||
def test_drafts_by_permission
|
||||
estimate = QboDraft.create!(document: 'estimate', fields: { 'customer_name' => 'Est Draft' })
|
||||
invoice = QboDraft.create!(document: 'invoice', fields: { 'customer_name' => 'Inv Draft' })
|
||||
login_with(:view_customers)
|
||||
get '/qbo_drafts'
|
||||
assert_response :forbidden
|
||||
|
||||
login_with(:write_estimates)
|
||||
get '/qbo_drafts'
|
||||
assert_response :success
|
||||
assert_select 'body', text: /Est Draft/
|
||||
assert_select 'body', text: /Inv Draft/, count: 0
|
||||
|
||||
# Not allowed to delete an invoice draft
|
||||
delete "/qbo_drafts/#{invoice.id}"
|
||||
assert QboDraft.exists?(invoice.id)
|
||||
assert_equal I18n.t(:error_qbo_draft_not_found), flash[:error]
|
||||
|
||||
delete "/qbo_drafts/#{estimate.id}"
|
||||
assert_not QboDraft.exists?(estimate.id)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,194 @@
|
||||
#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 QboRefundsTest < Redmine::IntegrationTest
|
||||
include QboRefundTestHelper
|
||||
|
||||
def setup
|
||||
@customer = create_customer
|
||||
Customer.any_instance.stubs(:email).returns('jane@example.com')
|
||||
RedmineQboBilling::RefundWriter.stubs(:fee_item).returns(fee_item)
|
||||
@gateway = FakeGateway.new(payments: [deposit(50, 500)], estimate: estimate)
|
||||
RedmineQboBilling::RefundGateway.stubs(:new).returns(@gateway)
|
||||
RedmineQboBilling::RefundWriter.stubs(:estimate_choices).returns([['E1068 · 2026-10-06', '598']])
|
||||
QboRefundMailer.stubs(:refund_summary).returns(stub(deliver_now: true))
|
||||
end
|
||||
|
||||
def test_needs_the_permission
|
||||
log_user('jsmith', 'jsmith')
|
||||
get "/qbo_refunds/new?customer_id=#{CUSTOMER_ID}"
|
||||
assert_response :forbidden
|
||||
|
||||
Role.find(1).add_permission!(:issue_refunds)
|
||||
get "/qbo_refunds/new?customer_id=#{CUSTOMER_ID}"
|
||||
assert_response :success
|
||||
end
|
||||
|
||||
def test_refund_page_fills_in_the_estimates_parts
|
||||
log_user('admin', 'admin')
|
||||
get "/qbo_refunds/new?customer_id=#{CUSTOMER_ID}&estimate_id=598"
|
||||
assert_response :success
|
||||
assert_select 'input[name=?][value=?]', 'refund[parts_amount]', '307.99'
|
||||
assert_select '#qbo-refund-credit', text: '$500.00'
|
||||
assert_select '#qbo-refund-fee', text: '-$92.40'
|
||||
assert_select '#qbo-refund-amount', text: '$407.60'
|
||||
assert_select 'input[name=?][value=check][checked]', 'refund[method]'
|
||||
end
|
||||
|
||||
def test_refund
|
||||
log_user('admin', 'admin')
|
||||
post '/qbo_refunds', params: { refund: { customer_id: CUSTOMER_ID, estimate_id: '598', parts_amount: '307.99',
|
||||
method: 'check', check_number: '5001', txn_date: '2026-11-16',
|
||||
reason: 'Canceled', close_estimate: '1', cancel_issues: '0', email_customer: '1' } }
|
||||
refund = QboRefund.last
|
||||
assert_redirected_to "/qbo_refunds/#{refund.id}"
|
||||
assert refund.done?, refund.message
|
||||
assert_equal BigDecimal('407.60'), refund.refund_amount
|
||||
follow_redirect!
|
||||
assert_select 'p', text: /\$407\.60 · Company check #5001/
|
||||
assert_select 'a[href*="app/check?txnId="]'
|
||||
assert_select 'a[href=?]', "/qbo_invoices/#{refund.fee_invoice_id}/edit"
|
||||
assert_select 'a[href=?]', '/qbo_estimates/598/edit'
|
||||
assert_select 'a[href*="app/invoice?txnId="]', count: 0
|
||||
|
||||
get "/customers/#{CUSTOMER_ID}"
|
||||
assert_select 'a[href=?]', "/qbo_refunds/#{refund.id}"
|
||||
end
|
||||
|
||||
def test_form_errors
|
||||
log_user('admin', 'admin')
|
||||
post '/qbo_refunds', params: { refund: { customer_id: CUSTOMER_ID, parts_amount: '10', method: 'check',
|
||||
check_number: '', txn_date: '2026-11-16', reason: '' } }
|
||||
assert_response :unprocessable_entity
|
||||
assert_select '#errorExplanation', text: /check number/
|
||||
assert_select '#errorExplanation', text: /reason/
|
||||
assert_equal 0, QboRefund.count
|
||||
end
|
||||
|
||||
def test_email_again
|
||||
log_user('admin', 'admin')
|
||||
refund = QboRefund.create!(customer_id: CUSTOMER_ID, method: 'check', check_number: '5001', status: 'done',
|
||||
refund_amount: 100, txn_date: Date.new(2026, 11, 16))
|
||||
post "/qbo_refunds/#{refund.id}/email"
|
||||
assert_redirected_to "/qbo_refunds/#{refund.id}"
|
||||
assert_equal 'jane@example.com', refund.reload.emailed_to
|
||||
end
|
||||
|
||||
def test_pdf
|
||||
log_user('admin', 'admin')
|
||||
refund = QboRefund.create!(customer_id: CUSTOMER_ID, method: 'check', check_number: '5001', status: 'done',
|
||||
estimate_number: '1068', reason: 'Canceled', parts_amount: 307.99, fee_rate: 30,
|
||||
fee_amount: 92.40, fee_invoice_number: '1502', credit_amount: 500, refund_amount: 407.60,
|
||||
balance_after: 0, txn_date: Date.new(2026, 11, 16), user_id: 1)
|
||||
get "/qbo_refunds/#{refund.id}/pdf"
|
||||
assert_response :success
|
||||
assert_equal 'application/pdf', response.media_type
|
||||
assert response.body.start_with?('%PDF')
|
||||
assert_match(/refund-2026-11-16-jane-customer\.pdf/, response.headers['Content-Disposition'])
|
||||
|
||||
get "/qbo_refunds/#{refund.id}"
|
||||
assert_select 'a[href=?]', "/qbo_refunds/#{refund.id}/pdf"
|
||||
end
|
||||
|
||||
# ---- Paid invoices ----
|
||||
|
||||
def invoice_setup
|
||||
RedmineQboBilling::LaborItems.stubs(:ids).returns([])
|
||||
@gateway.invoices << paid_invoice
|
||||
end
|
||||
|
||||
def test_invoice_refund_page
|
||||
invoice_setup
|
||||
log_user('admin', 'admin')
|
||||
get '/qbo_refunds/new_invoice?invoice_id=950'
|
||||
assert_response :success
|
||||
assert_select 'h2', text: /Invoice #1234/
|
||||
assert_select 'input[type=checkbox][name=?][checked]', 'refund[lines][2][refund]'
|
||||
assert_select 'input[name=?][value=?]', 'refund[lines][2][quantity]', '4'
|
||||
assert_select 'input[name=?][value=?]', 'refund[lines][3][amount]', '80.00'
|
||||
assert_select 'input[name=?][checked]', 'refund[charge_fee]'
|
||||
# Everything ticked: $440.00 of lines, $14.00 tax, 30% of $200.00 parts
|
||||
assert_select '#qbo-refund-lines-amount', text: '$440.00'
|
||||
assert_select '#qbo-refund-tax', text: '$14.00'
|
||||
assert_select '#qbo-refund-fee', text: '-$60.00'
|
||||
assert_select '#qbo-refund-amount', text: '$394.00'
|
||||
end
|
||||
|
||||
def test_unpaid_invoice_isnt_refunded
|
||||
RedmineQboBilling::LaborItems.stubs(:ids).returns([])
|
||||
@gateway.invoices << paid_invoice(balance: 50)
|
||||
log_user('admin', 'admin')
|
||||
get '/qbo_refunds/new_invoice?invoice_id=950'
|
||||
assert_redirected_to '/qbo_invoices/950/edit'
|
||||
end
|
||||
|
||||
def test_invoice_refund
|
||||
invoice_setup
|
||||
log_user('admin', 'admin')
|
||||
post '/qbo_refunds/create_invoice', params: { refund: {
|
||||
customer_id: CUSTOMER_ID, invoice_id: '950', method: 'card', txn_date: '2026-11-18', reason: 'Returned pads',
|
||||
charge_fee: '0', note_issues: '1', email_customer: '0',
|
||||
lines: { '1' => { refund: '0', quantity: '2', amount: '240.00' }, '2' => { refund: '1', quantity: '2', amount: '60.00' },
|
||||
'3' => { refund: '0', quantity: '1', amount: '80.00' } }
|
||||
} }
|
||||
refund = QboRefund.last
|
||||
assert_redirected_to "/qbo_refunds/#{refund.id}"
|
||||
assert refund.done?, refund.message
|
||||
assert_equal BigDecimal('64.20'), refund.refund_amount
|
||||
follow_redirect!
|
||||
assert_select 'p', text: /Refund receipt 3000 is recorded/
|
||||
assert_select 'a[href*="app/refundreceipt?txnId=900"]'
|
||||
assert_select 'a[href=?]', '/qbo_invoices/950/edit'
|
||||
|
||||
get '/qbo_refunds/new_invoice?invoice_id=950'
|
||||
assert_select 'input[name=?][value=?]', 'refund[lines][2][quantity]', '2'
|
||||
assert_select '.flash.warning a[href=?]', "/qbo_refunds/#{refund.id}"
|
||||
|
||||
get "/qbo_refunds/#{refund.id}/pdf"
|
||||
assert_response :success
|
||||
|
||||
get "/customers/#{CUSTOMER_ID}"
|
||||
assert_select 'a[href=?]', '/qbo_invoices/950/edit', text: 'Invoice #1234'
|
||||
end
|
||||
|
||||
def test_invoice_refund_form_errors
|
||||
invoice_setup
|
||||
log_user('admin', 'admin')
|
||||
post '/qbo_refunds/create_invoice', params: { refund: {
|
||||
customer_id: CUSTOMER_ID, invoice_id: '950', method: 'check', check_number: '', txn_date: '2026-11-18', reason: '',
|
||||
lines: { '2' => { refund: '1', quantity: '9' } }
|
||||
} }
|
||||
assert_response :unprocessable_entity
|
||||
assert_select '#errorExplanation', text: /check number/
|
||||
assert_select '#errorExplanation', text: /reason/
|
||||
|
||||
post '/qbo_refunds/create_invoice', params: { refund: {
|
||||
customer_id: CUSTOMER_ID, invoice_id: '950', method: 'check', check_number: '1', txn_date: '2026-11-18', reason: 'x',
|
||||
lines: { '2' => { refund: '1', quantity: '9' } }
|
||||
} }
|
||||
assert_response :unprocessable_entity
|
||||
assert_select '#errorExplanation', text: /no more than 4/
|
||||
assert_equal 0, QboRefund.count
|
||||
assert_empty @gateway.receipts
|
||||
end
|
||||
|
||||
def test_credit_refund_page_offers_paid_invoices
|
||||
Invoice.where(id: 950).delete_all
|
||||
Invoice.new(id: 950, doc_number: '1234', txn_date: Date.new(2026, 11, 2), customer_id: CUSTOMER_ID,
|
||||
total_amount: 454, balance: 0).save!(validate: false)
|
||||
log_user('admin', 'admin')
|
||||
get "/qbo_refunds/new?customer_id=#{CUSTOMER_ID}"
|
||||
assert_select '#qbo_refund_invoice option[value="950"]', text: /#1234/
|
||||
ensure
|
||||
Invoice.where(id: 950).delete_all
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
# Made by Redmine's own PDF writer, which adds optional content: merged like the issue's PDF
|
||||
estimate_pdf = Redmine::Export::PDF::ITCPDF.new('en').tap { |p| p.add_page; p.write(5, 'ESTIMATE') }.output
|
||||
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
|
||||
@@ -0,0 +1,52 @@
|
||||
#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.
|
||||
|
||||
# Shared setup for the estimate, invoice and payment editor tests: jsmith with chosen billing permissions,
|
||||
# QuickBooks replaced by QboFakeServiceHelper's fake
|
||||
module QboEditorTestHelper
|
||||
def self.included(base)
|
||||
base.include QboFakeServiceHelper
|
||||
base.fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
|
||||
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations, :workflows
|
||||
base.setup do
|
||||
@customer = local_customer
|
||||
@fake = install_fake_quickbooks
|
||||
stub_company
|
||||
stub_local_syncs
|
||||
Issue.where(estimate_id: [598, 599]).update_all(estimate_id: nil)
|
||||
QboDraft.delete_all
|
||||
Role.find(1).remove_permission!(*BILLING_PERMISSIONS)
|
||||
end
|
||||
end
|
||||
|
||||
BILLING_PERMISSIONS = %i[write_estimates send_estimates create_estimate_issues write_invoices send_invoices
|
||||
edit_partially_paid_invoices edit_paid_invoices edit_linked_estimates view_payments
|
||||
receive_payments view_customers].freeze
|
||||
|
||||
def login_with(*permissions)
|
||||
permissions.each { |p| Role.find(1).add_permission!(p) }
|
||||
reset!
|
||||
log_user('jsmith', 'jsmith')
|
||||
end
|
||||
|
||||
def estimate_doc(**options)
|
||||
qbo_estimate(customer_name: 'Jane Customer', doc_number: '1068', status: 'Pending',
|
||||
lines: [qbo_sales_line(2, 10, 'Labor', 2, 120, description: 'Install lift kit')], **options)
|
||||
end
|
||||
|
||||
def invoice_doc(total: '240', balance: '240', **options)
|
||||
qbo_invoice(customer_name: 'Jane Customer', doc_number: '1234', total: total, balance: balance,
|
||||
lines: [qbo_sales_line(1, 10, 'Labor', 2, 120)], **options)
|
||||
end
|
||||
|
||||
def line_params(rate: '120')
|
||||
{ '0' => { item_id: '10', item_name: 'Labor', quantity: '2', rate: rate, taxable: '0', description: 'Install' } }
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -0,0 +1,244 @@
|
||||
#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/test_helper', __dir__)
|
||||
require File.expand_path('qbo_fake_service', __dir__)
|
||||
require File.expand_path('qbo_editor_test_helper', __dir__)
|
||||
|
||||
module QboRefundTestHelper
|
||||
CUSTOMER_ID = 9101
|
||||
|
||||
# Stands in for QuickBooks: the customer's payments, and what the refund made
|
||||
class FakeGateway
|
||||
attr_reader :payments, :invoices, :purchases, :applied, :rejected, :receipts
|
||||
attr_accessor :auto_apply, :fail_on, :estimate_record, :balance
|
||||
|
||||
def initialize(payments: [], estimate: nil)
|
||||
@payments = payments
|
||||
@estimate_record = estimate
|
||||
@invoices = []
|
||||
@purchases = []
|
||||
@applied = []
|
||||
@rejected = []
|
||||
@receipts = []
|
||||
@auto_apply = false
|
||||
@balance = BigDecimal('0')
|
||||
end
|
||||
|
||||
def unapplied_payments(_customer_id)
|
||||
payments.select { |p| p.unapplied_amount.to_d.positive? }.sort_by { |p| [p.txn_date, p.id.to_i] }
|
||||
end
|
||||
|
||||
def estimate(id)
|
||||
estimate_record if estimate_record && estimate_record.id.to_s == id.to_s
|
||||
end
|
||||
|
||||
def create_invoice(invoice)
|
||||
raise Quickbooks::IntuitRequestException, 'QuickBooks is down' if fail_on == :invoice
|
||||
|
||||
invoice.id = (700 + invoices.size).to_s
|
||||
invoice.doc_number = (1500 + invoices.size).to_s
|
||||
invoice.total = invoice.line_items.sum(BigDecimal('0')) { |l| l.amount.to_d }
|
||||
invoice.balance = invoice.total
|
||||
invoices << invoice
|
||||
# QuickBooks' "Automatically apply credits"
|
||||
if auto_apply
|
||||
unapplied_payments(nil).each do |p|
|
||||
take = [invoice.balance, p.unapplied_amount.to_d].min
|
||||
next unless take.positive?
|
||||
|
||||
apply_payment(p, take, invoice.id, 'Invoice')
|
||||
end
|
||||
end
|
||||
invoice
|
||||
end
|
||||
|
||||
def invoice(id)
|
||||
invoices.find { |i| i.id.to_s == id.to_s }
|
||||
end
|
||||
|
||||
def apply_payment(payment, amount, txn_id, txn_type)
|
||||
raise Quickbooks::IntuitRequestException, 'Link refused' if fail_on == :link
|
||||
|
||||
payment.unapplied_amount = payment.unapplied_amount.to_d - amount
|
||||
invoice(txn_id).balance = invoice(txn_id).balance.to_d - amount if txn_type == 'Invoice'
|
||||
applied << [payment.id, amount, txn_id.to_s, txn_type]
|
||||
payment
|
||||
end
|
||||
|
||||
def create_purchase(purchase)
|
||||
raise Quickbooks::IntuitRequestException, 'QuickBooks is down' if fail_on == :purchase
|
||||
|
||||
purchase.id = (800 + purchases.size).to_s
|
||||
purchases << purchase
|
||||
purchase
|
||||
end
|
||||
|
||||
# QuickBooks' refund receipt: tax at 7% on the taxable lines, after the discount's share
|
||||
def create_refund_receipt(receipt)
|
||||
raise Quickbooks::IntuitRequestException, 'QuickBooks is down' if fail_on == :receipt
|
||||
|
||||
sales = receipt.line_items.select { |l| l.detail_type.to_s == 'SalesItemLineDetail' }
|
||||
discount = receipt.line_items.select { |l| l.detail_type.to_s == 'DiscountLineDetail' }.sum(BigDecimal('0')) { |l| l.amount.to_d }
|
||||
lines = sales.sum(BigDecimal('0')) { |l| l.amount.to_d.positive? ? l.amount.to_d : 0 }
|
||||
taxable = sales.select { |l| l.sales_item_line_detail.tax_code_ref&.value == 'TAX' }.sum(BigDecimal('0')) { |l| l.amount.to_d }
|
||||
tax = (taxable * (lines.positive? ? 1 - discount / lines : 1) * BigDecimal('0.07')).round(2)
|
||||
receipt.id = (900 + receipts.size).to_s
|
||||
receipt.doc_number = (3000 + receipts.size).to_s
|
||||
receipt.txn_tax_detail = Quickbooks::Model::TransactionTaxDetail.new
|
||||
receipt.txn_tax_detail.total_tax = tax
|
||||
receipt.total = sales.sum(BigDecimal('0')) { |l| l.amount.to_d } - discount + tax
|
||||
receipts << receipt
|
||||
receipt
|
||||
end
|
||||
|
||||
def payment_method_id(kind)
|
||||
{ check: '2', card: '3' }[kind]
|
||||
end
|
||||
|
||||
def account_id(type)
|
||||
{ 'Accounts Receivable' => '84', 'Bank' => '35' }[type]
|
||||
end
|
||||
|
||||
def customer_balance(_customer_id)
|
||||
balance
|
||||
end
|
||||
|
||||
def reject_estimate(estimate)
|
||||
rejected << estimate.id.to_s
|
||||
end
|
||||
|
||||
def sync_invoice(_id); end
|
||||
def sync_payment(_id); end
|
||||
def sync_estimate(_id); end
|
||||
end
|
||||
|
||||
class FakeMailer
|
||||
Delivery = Struct.new(:refund, :email) do
|
||||
def deliver_now
|
||||
FakeMailer.sent << [refund.id, email]
|
||||
end
|
||||
end
|
||||
|
||||
def self.sent
|
||||
@sent ||= []
|
||||
end
|
||||
|
||||
def self.refund_summary(refund, email)
|
||||
Delivery.new(refund, email)
|
||||
end
|
||||
end
|
||||
|
||||
def self.included(base)
|
||||
base.fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
|
||||
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations, :workflows
|
||||
base.setup do
|
||||
QboRefund.delete_all
|
||||
Customer.where(id: CUSTOMER_ID).delete_all
|
||||
FakeMailer.sent.clear
|
||||
end
|
||||
end
|
||||
|
||||
def create_customer
|
||||
customer = Customer.new(id: CUSTOMER_ID, name: 'Jane Customer')
|
||||
customer.skip_qbo_push = true
|
||||
customer.save!
|
||||
customer
|
||||
end
|
||||
|
||||
def deposit(id, amount, date: Date.new(2026, 11, 2))
|
||||
payment = Quickbooks::Model::Payment.new
|
||||
payment.id = id.to_s
|
||||
payment.txn_date = date
|
||||
payment.total = BigDecimal(amount.to_s)
|
||||
payment.unapplied_amount = BigDecimal(amount.to_s)
|
||||
payment.customer_ref = Quickbooks::Model::BaseReference.new(CUSTOMER_ID.to_s)
|
||||
payment
|
||||
end
|
||||
|
||||
def item_line(item_id, name, amount)
|
||||
line = Quickbooks::Model::InvoiceLineItem.new
|
||||
line.amount = BigDecimal(amount.to_s)
|
||||
line.sales_item! { |d| d.item_ref = Quickbooks::Model::BaseReference.new(item_id.to_s, name: name) }
|
||||
line
|
||||
end
|
||||
|
||||
# E1068: $1,900 labor and $307.99 of parts
|
||||
def estimate(id: 598, status: 'Accepted', customer_id: CUSTOMER_ID)
|
||||
estimate = Quickbooks::Model::Estimate.new
|
||||
estimate.id = id.to_s
|
||||
estimate.doc_number = '1068'
|
||||
estimate.txn_status = status
|
||||
estimate.customer_ref = Quickbooks::Model::BaseReference.new(customer_id.to_s)
|
||||
estimate.line_items = [item_line(1, 'Labor', 1900), item_line(2, 'TF HD JK Ball Joints', '307.99')]
|
||||
estimate
|
||||
end
|
||||
|
||||
def fee_item
|
||||
Struct.new(:id, :name).new('55', 'Restocking Fee')
|
||||
end
|
||||
|
||||
def 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 = Quickbooks::Model::BaseReference.new(item_id.to_s, name: name)
|
||||
d.quantity = BigDecimal(quantity.to_s)
|
||||
d.unit_price = BigDecimal(rate.to_s)
|
||||
d.tax_code_ref = Quickbooks::Model::BaseReference.new(taxable ? 'TAX' : 'NON')
|
||||
end
|
||||
line
|
||||
end
|
||||
|
||||
# Invoice #1234, paid in full: 2 h labor at $120 (not taxed), 4 brake pads at $30 and a $80 rotor (taxed at
|
||||
# 7%: $14.00), $454.00 in all
|
||||
def paid_invoice(id: 950, balance: 0, customer_id: CUSTOMER_ID, discount: nil)
|
||||
invoice = Quickbooks::Model::Invoice.new
|
||||
invoice.id = id.to_s
|
||||
invoice.doc_number = '1234'
|
||||
invoice.txn_date = Date.new(2026, 11, 2)
|
||||
invoice.customer_ref = Quickbooks::Model::BaseReference.new(customer_id.to_s)
|
||||
invoice.line_items = [sales_line(1, 1, 'Labor', 2, 120, taxable: false, description: 'Brake job'),
|
||||
sales_line(2, 3, 'Brake Pads', 4, 30, description: 'Ceramic pads'),
|
||||
sales_line(3, 4, 'Rotor', 1, 80, description: 'Front rotor')]
|
||||
tax = BigDecimal('14')
|
||||
if discount
|
||||
line = Quickbooks::Model::InvoiceLineItem.new
|
||||
line.amount = BigDecimal(discount.to_s)
|
||||
line.discount_item! { |d| d.percent_based = false }
|
||||
invoice.line_items = invoice.line_items + [line]
|
||||
tax = (BigDecimal('200') * (1 - BigDecimal(discount.to_s) / 440) * BigDecimal('0.07')).round(2)
|
||||
end
|
||||
invoice.txn_tax_detail = Quickbooks::Model::TransactionTaxDetail.new
|
||||
invoice.txn_tax_detail.total_tax = tax
|
||||
invoice.total = BigDecimal('440') - BigDecimal((discount || 0).to_s) + tax
|
||||
invoice.balance = BigDecimal(balance.to_s)
|
||||
invoice
|
||||
end
|
||||
|
||||
def invoice_refund_form(attributes = {})
|
||||
form = RedmineQboBilling::InvoiceRefundForm.from_params(
|
||||
{ customer_id: CUSTOMER_ID.to_s, invoice_id: '950', txn_date: '2026-11-18', method: 'check',
|
||||
check_number: '5002', reason: 'Parts returned unused', charge_fee: '1', note_issues: '1',
|
||||
email_customer: '1', lines: { '2' => { refund: '1', quantity: '4' }, '3' => { refund: '1', quantity: '1' } } }
|
||||
.merge(attributes)
|
||||
)
|
||||
form
|
||||
end
|
||||
|
||||
def refund_form(attributes = {})
|
||||
RedmineQboBilling::RefundForm.new({ customer_id: CUSTOMER_ID.to_s, estimate_id: '598', txn_date: '2026-11-16',
|
||||
parts_amount: '307.99', method: 'check', check_number: '5001',
|
||||
reason: 'Customer canceled the order', close_estimate: '1',
|
||||
cancel_issues: '1', email_customer: '1' }.merge(attributes))
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -0,0 +1,101 @@
|
||||
#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__)
|
||||
|
||||
# PaymentForm, RefundForm and InvoiceRefundForm
|
||||
class BillingFormsTest < ActiveSupport::TestCase
|
||||
def payment(attrs = {})
|
||||
RedmineQboBilling::PaymentForm.from_params({ 'customer_id' => '9101', 'txn_date' => '2026-11-20',
|
||||
'payment_method_id' => '2', 'amount' => '$1,000' }.merge(attrs))
|
||||
end
|
||||
|
||||
def test_payment_form_from_params
|
||||
form = payment('invoice_ids' => ['7', '', '7', '8'], 'sync_token' => '3', 'deposit' => '1')
|
||||
assert_equal %w[7 8], form.invoice_ids
|
||||
assert_equal '3', form.sync_token
|
||||
assert_equal BigDecimal('1000'), form.amount_value
|
||||
assert_equal Date.new(2026, 11, 20), form.txn_date_value
|
||||
assert form.deposit?
|
||||
assert_not form.persisted?
|
||||
assert RedmineQboBilling::PaymentForm.from_params({}, id: '12').persisted?
|
||||
assert_equal [], RedmineQboBilling::PaymentForm.new.invoice_ids
|
||||
end
|
||||
|
||||
def test_payment_form_validation
|
||||
assert payment.valid?
|
||||
form = RedmineQboBilling::PaymentForm.from_params({ 'amount' => '0', 'txn_date' => 'x' })
|
||||
assert_not form.valid?
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_needs_customer)
|
||||
assert_includes form.errors[:base], I18n.t(:error_payment_needs_method)
|
||||
assert_includes form.errors[:base], I18n.t(:error_payment_amount)
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_payment_date))
|
||||
assert_not payment('amount' => 'abc').valid?
|
||||
assert_not payment('amount' => '-5').valid?
|
||||
end
|
||||
|
||||
def refund(attrs = {})
|
||||
RedmineQboBilling::RefundForm.from_params({ 'customer_id' => '9101', 'txn_date' => '2026-11-20',
|
||||
'method' => 'card', 'reason' => 'Canceled order' }.merge(attrs))
|
||||
end
|
||||
|
||||
def test_refund_form
|
||||
form = refund('parts_amount' => '307.99', 'close_estimate' => '1', 'cancel_issues' => '0')
|
||||
assert form.valid?, form.errors.full_messages.inspect
|
||||
assert_equal BigDecimal('307.99'), form.parts_value
|
||||
assert form.close_estimate?
|
||||
assert_not form.cancel_issues?
|
||||
assert_not form.email_customer?
|
||||
assert_not form.check?
|
||||
assert_equal BigDecimal('0'), refund.parts_value
|
||||
end
|
||||
|
||||
def test_refund_form_validation
|
||||
form = RedmineQboBilling::RefundForm.from_params('method' => 'check', 'parts_amount' => '-1')
|
||||
assert_not form.valid?
|
||||
%i[error_estimate_needs_customer error_refund_check_number error_refund_reason error_refund_parts_amount].each do |key|
|
||||
assert_includes form.errors[:base], I18n.t(key)
|
||||
end
|
||||
assert_includes refund('method' => 'cash').tap(&:valid?).errors[:base], I18n.t(:error_refund_method)
|
||||
assert_includes refund('parts_amount' => 'lots').tap(&:valid?).errors[:base], I18n.t(:error_refund_parts_amount)
|
||||
assert refund('method' => 'check', 'check_number' => '1042').valid?
|
||||
end
|
||||
|
||||
def invoice_refund(attrs = {})
|
||||
RedmineQboBilling::InvoiceRefundForm.from_params(
|
||||
{ 'customer_id' => '9101', 'invoice_id' => '601', 'txn_date' => '2026-11-20', 'method' => 'card',
|
||||
'reason' => 'Returned part', 'lines' => { '3' => { 'refund' => '1', 'quantity' => '2', 'amount' => '$1,060.00' },
|
||||
'4' => { 'refund' => '0', 'quantity' => '', 'amount' => '' } } }.merge(attrs)
|
||||
)
|
||||
end
|
||||
|
||||
def test_invoice_refund_form_lines
|
||||
form = invoice_refund('charge_fee' => '1')
|
||||
assert form.valid?, form.errors.full_messages.inspect
|
||||
assert_equal ['3'], form.chosen.keys
|
||||
assert_equal BigDecimal('2'), form.line(3).quantity_value
|
||||
assert_equal BigDecimal('1060'), form.line('3').amount_value
|
||||
assert_nil form.line('4').quantity_value
|
||||
assert_nil form.line('4').amount_value
|
||||
assert_nil form.line('9')
|
||||
assert form.charge_fee?
|
||||
assert_not form.note_issues?
|
||||
assert_includes RedmineQboBilling::InvoiceRefundForm.permitted, { lines: {} }
|
||||
end
|
||||
|
||||
def test_invoice_refund_form_validation
|
||||
form = RedmineQboBilling::InvoiceRefundForm.from_params('method' => 'check')
|
||||
assert_not form.valid?
|
||||
%i[error_estimate_needs_customer error_refund_no_invoice error_refund_check_number error_refund_reason
|
||||
error_refund_no_lines].each { |key| assert_includes form.errors[:base], I18n.t(key) }
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_refund_date))
|
||||
assert_equal({}, form.lines)
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -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 BusinessReportTest < ActiveSupport::TestCase
|
||||
Report = RedmineQboBilling::BusinessReport
|
||||
NOV = Date.new(2026, 11, 1)
|
||||
|
||||
def report(data)
|
||||
full = { estimates: [], invoices: [], paid: [], payments: [], issues: [], time_entries: [] }.merge(data)
|
||||
Report.new(period: 'custom', from: NOV, to: NOV.end_of_month, today: Date.new(2026, 11, 20), data: full,
|
||||
previous_data: full.transform_values { [] })
|
||||
end
|
||||
|
||||
def test_estimates_and_invoices_without_tax
|
||||
r = report(estimates: [[NOV + 1, '1080', 10, '80'], [NOV + 2, '500', 2]],
|
||||
invoices: [[NOV + 3, '1070', 5, '0', '70'], [NOV + 4, '200', 1, '200', '0']],
|
||||
payments: [[NOV + 5, '1070']])
|
||||
assert_equal BigDecimal('1500'), r.money[:estimates][:total]
|
||||
assert_equal BigDecimal('1200'), r.money[:invoices][:total]
|
||||
assert_equal BigDecimal('1270'), r.money[:invoices][:with_tax]
|
||||
assert_equal BigDecimal('200'), r.money[:invoices][:balance]
|
||||
assert_equal BigDecimal('1070'), r.money[:payments][:total]
|
||||
# $1,070 collected of $1,270 invoiced with tax
|
||||
assert_equal 84, r.ratios[:collected_of_invoiced]
|
||||
assert_equal 80, r.ratios[:invoiced_of_estimated]
|
||||
end
|
||||
|
||||
def test_invoices_paid_in_full
|
||||
r = report(paid: [[NOV + 3, '1070', '70'], [NOV + 9, '500', nil]])
|
||||
assert_equal BigDecimal('1500'), r.money[:paid][:total]
|
||||
assert_equal 2, r.money[:paid][:count]
|
||||
november = r.months.find { |m| m[:month] == NOV }
|
||||
assert_equal BigDecimal('1500'), november[:paid]
|
||||
assert_equal 1500.0, r.chart[:current][:paid].compact.sum
|
||||
end
|
||||
|
||||
def test_rows_missing_tax_are_unsynced
|
||||
r = report(estimates: [[NOV + 1, '100', 1, nil]], invoices: [[NOV + 1, '100', 1, '0', '0']])
|
||||
assert_equal 1, r.unsynced_count
|
||||
end
|
||||
|
||||
def test_paid_badge_shows_the_day
|
||||
assert_equal 'Paid', RedmineQboBilling::InvoiceStatus.label(:paid)
|
||||
assert_match(/\APaid \S+/, RedmineQboBilling::InvoiceStatus.label(:paid, paid_on: Date.new(2026, 11, 3)))
|
||||
assert_equal 'Open', RedmineQboBilling::InvoiceStatus.label(:open, paid_on: Date.new(2026, 11, 3))
|
||||
end
|
||||
|
||||
def test_taxes
|
||||
r = report(invoices: [[NOV + 3, '1070', 5, '0', '70'], [NOV + 4, '200', 1, '200', '0'], [NOV + 6, '535', 2, '0', '35']],
|
||||
paid: [[NOV + 9, '1070', '70'], [Date.new(2026, 11, 10), '500', nil]])
|
||||
assert_equal({ total: BigDecimal('105'), count: 2 }, r.taxes[:tax_invoiced])
|
||||
assert_equal({ total: BigDecimal('70'), count: 1 }, r.taxes[:tax_collected])
|
||||
november = r.months.find { |m| m[:month] == NOV }
|
||||
assert_equal BigDecimal('105'), november[:tax_invoiced]
|
||||
assert_equal BigDecimal('70'), november[:tax_collected]
|
||||
assert_equal 105.0, r.chart[:current][:tax_invoiced].compact.sum
|
||||
assert_equal 70.0, r.chart[:current][:tax_collected].compact.sum
|
||||
end
|
||||
|
||||
def test_short_paid_badge
|
||||
status = RedmineQboBilling::InvoiceStatus
|
||||
nov18 = Date.new(2026, 11, 18)
|
||||
assert_equal 'Paid', status.short_label(:paid, paid_on: nov18, invoice_date: nov18)
|
||||
assert_equal 'Paid +1d', status.short_label(:paid, paid_on: nov18 + 1, invoice_date: nov18)
|
||||
assert_equal 'Paid +34d', status.short_label(:paid, paid_on: nov18 + 34, invoice_date: nov18)
|
||||
assert_equal 'Paid', status.short_label(:paid, paid_on: nil, invoice_date: nov18)
|
||||
# A deposit taken before the invoice: paid in full on its date
|
||||
assert_equal 'Paid', status.short_label(:paid, paid_on: nov18, invoice_date: nov18 + 2)
|
||||
assert_equal 'Open', status.short_label(:open, paid_on: nov18 + 3, invoice_date: nov18)
|
||||
assert_match(/\APaid in full \S+/, status.title(:paid, paid_on: nov18))
|
||||
assert_nil status.title(:open, paid_on: nov18)
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -0,0 +1,83 @@
|
||||
#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
|
||||
CustomerSearchService.instance_variable_set(:@candidates, nil)
|
||||
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
|
||||
@@ -0,0 +1,86 @@
|
||||
#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 CustomerTest < ActiveSupport::TestCase
|
||||
def setup
|
||||
Customer.where(id: [9201, 9202, 9203]).delete_all
|
||||
end
|
||||
|
||||
def customer(id, name, phone: nil, mobile: nil)
|
||||
record = Customer.new(id: id, name: name, phone_number: phone, mobile_phone_number: mobile)
|
||||
record.skip_qbo_push = true
|
||||
record.save!
|
||||
record
|
||||
end
|
||||
|
||||
def test_name_is_title_cased_locally_and_in_quickbooks
|
||||
record = Customer.new(id: 9201, name: ' jane DOE llc ')
|
||||
assert_equal 'Jane DOE Llc', record.name
|
||||
assert_equal 'Jane DOE Llc', record.details.display_name
|
||||
end
|
||||
|
||||
def test_phone_numbers_keep_digits_only
|
||||
record = customer(9201, 'Jane', phone: '(401) 555-0101', mobile: '+1 401.555.0102')
|
||||
assert_equal '4015550101', record.phone_number
|
||||
assert_equal '14015550102', record.mobile_phone_number
|
||||
end
|
||||
|
||||
def test_to_s_adds_the_last_four_digits
|
||||
assert_equal 'Jane - 0101', customer(9201, 'Jane', phone: '4015550101').to_s
|
||||
assert_equal 'Bob', customer(9202, 'Bob').to_s
|
||||
end
|
||||
|
||||
def test_needs_a_name_and_a_unique_id
|
||||
assert_not Customer.new(id: 9201, name: '').tap { |c| c.skip_qbo_push = true }.valid?
|
||||
customer(9201, 'Jane')
|
||||
duplicate = Customer.new(id: 9201, name: 'Other')
|
||||
duplicate.skip_qbo_push = true
|
||||
assert_not duplicate.valid?
|
||||
end
|
||||
|
||||
def test_search_by_name_or_phone
|
||||
customer(9201, 'Jane Customer', phone: '4015550101')
|
||||
customer(9202, 'Bob Builder', mobile: '4015550199')
|
||||
customer(9203, '100% Jeep')
|
||||
assert_equal [9201], Customer.search('jane').pluck(:id)
|
||||
assert_equal [9202], Customer.search('0199').pluck(:id)
|
||||
# LIKE wildcards are matched literally
|
||||
assert_equal [9203], Customer.search('100%').pluck(:id)
|
||||
end
|
||||
|
||||
def test_redmine_search_needs_every_token
|
||||
customer(9201, 'Jane Customer', phone: '4015550101')
|
||||
customer(9202, 'Jane Other')
|
||||
assert_equal({ 9201 => 9201 }, Customer.search_result_ranks_and_ids(%w[jane 0101], User.find(1)))
|
||||
assert_equal({}, Customer.search_result_ranks_and_ids([], User.find(1)))
|
||||
end
|
||||
|
||||
def test_quickbooks_details_setters
|
||||
record = Customer.new(id: 9201, name: 'Jane')
|
||||
record.primary_phone = '401-555-0101'
|
||||
record.mobile_phone = '401-555-0102'
|
||||
record.email = 'jane@example.com'
|
||||
record.notes = 'Prefers texts'
|
||||
assert_equal '401-555-0101', record.primary_phone
|
||||
assert_equal '401-555-0102', record.mobile_phone
|
||||
assert_equal 'jane@example.com', record.email
|
||||
assert_equal 'Prefers texts', record.details.notes
|
||||
assert_nil record.project
|
||||
end
|
||||
|
||||
def test_saving_pushes_to_quickbooks_unless_skipped
|
||||
CustomerService.any_instance.expects(:push).once.returns(true)
|
||||
Customer.create!(id: 9201, name: 'Jane')
|
||||
CustomerService.any_instance.expects(:push).never
|
||||
customer(9202, 'Bob')
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,48 @@
|
||||
#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 CustomerTokenTest < ActiveSupport::TestCase
|
||||
fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
|
||||
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations
|
||||
|
||||
def setup
|
||||
CustomerToken.delete_all
|
||||
User.current = User.find(1)
|
||||
end
|
||||
|
||||
def token(issue_id, expires_at)
|
||||
CustomerToken.create!(issue_id: issue_id, expires_at: expires_at)
|
||||
end
|
||||
|
||||
def test_purge_expired
|
||||
active = token(1, 1.week.from_now)
|
||||
token(2, 1.day.ago)
|
||||
token(3, 1.month.ago)
|
||||
token(99_999, 1.week.from_now) # its issue was deleted
|
||||
assert_equal 3, CustomerToken.purge_expired
|
||||
assert_equal [active.id], CustomerToken.pluck(:id)
|
||||
end
|
||||
|
||||
def test_a_new_share_link_clears_out_old_ones
|
||||
token(2, 1.day.ago)
|
||||
link = CustomerToken.get_token(Issue.find(1))
|
||||
assert link.expires_at > Time.current
|
||||
assert_equal [link.id], CustomerToken.pluck(:id)
|
||||
end
|
||||
|
||||
def test_an_active_link_is_reused
|
||||
active = token(1, 1.week.from_now)
|
||||
token(2, 1.day.ago)
|
||||
assert_equal active, CustomerToken.get_token(Issue.find(1))
|
||||
assert_equal 2, CustomerToken.count # nothing new made, nothing cleared
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,216 @@
|
||||
#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 EstimateFormTest < ActiveSupport::TestCase
|
||||
Form = RedmineQboBilling::EstimateForm
|
||||
Line = Form::Line
|
||||
|
||||
def line(attrs = {})
|
||||
Line.from_params(attrs)
|
||||
end
|
||||
|
||||
def valid_form(attrs = {})
|
||||
Form.new({ customer_id: '9101', txn_date: '2026-11-20',
|
||||
lines: [line(item_id: '1', item_name: 'Labor', quantity: '2', rate: '120')] }.merge(attrs))
|
||||
end
|
||||
|
||||
# Line
|
||||
|
||||
def test_line_from_params_cleans_up_the_row
|
||||
row = line('id' => '', 'kind' => 'other', 'item_id' => '5', 'item_name' => ' Labor ', 'description' => ' Brakes ',
|
||||
'quantity' => ' 2 ', 'rate' => '$1,200.50', 'taxable' => '1', 'time_activity_id' => '')
|
||||
assert_nil row.id
|
||||
assert_nil row.kind
|
||||
assert_equal 'Labor', row.item_name
|
||||
assert_equal 'Brakes', row.description
|
||||
assert_equal BigDecimal('1200.50'), row.rate_value
|
||||
assert row.taxable?
|
||||
assert_nil row.time_activity_id
|
||||
assert_not line('taxable' => '0').taxable?
|
||||
end
|
||||
|
||||
def test_line_amount_defaults_quantity_to_one_and_rounds
|
||||
assert_equal BigDecimal('45.50'), line(rate: '45.50').amount
|
||||
assert_equal BigDecimal('3.33'), line(quantity: '0.333', rate: '10').amount
|
||||
assert_equal BigDecimal('0'), line(description: 'note').amount
|
||||
assert_equal BigDecimal('0'), line(kind: 'subtotal', rate: '10').amount
|
||||
end
|
||||
|
||||
def test_line_kinds
|
||||
assert line(kind: 'subtotal').subtotal?
|
||||
assert line(item_id: '1').item?
|
||||
assert_not line(kind: 'subtotal', item_id: '1').item?
|
||||
assert line(description: 'Notes').description_only?
|
||||
assert_not line(description: 'Notes', rate: '5').description_only?
|
||||
assert line.blank?
|
||||
assert_not line(kind: 'subtotal').blank?
|
||||
assert line(item_name: 'Typed only').unmatched_item?
|
||||
assert_not line(item_id: '1', item_name: 'Labor').unmatched_item?
|
||||
end
|
||||
|
||||
def test_line_number_invalid
|
||||
assert line(quantity: 'two').number_invalid?
|
||||
assert line(rate: 'abc').number_invalid?
|
||||
assert_not line(quantity: '2', rate: '1,000').number_invalid?
|
||||
assert_not line(kind: 'subtotal', rate: 'abc').number_invalid?
|
||||
end
|
||||
|
||||
# Parsing helpers
|
||||
|
||||
def test_decimal
|
||||
assert_equal BigDecimal('1234.5'), Form.decimal('$1,234.50')
|
||||
assert_nil Form.decimal('')
|
||||
assert_nil Form.decimal('abc')
|
||||
end
|
||||
|
||||
def test_date
|
||||
assert_equal Date.new(2026, 11, 20), Form.date('2026-11-20')
|
||||
assert_equal Date.new(2026, 1, 2), Form.date(Date.new(2026, 1, 2))
|
||||
assert_nil Form.date('')
|
||||
assert_nil Form.date('11/20/2026')
|
||||
end
|
||||
|
||||
def test_custom_field_hash_keeps_numeric_ids_only
|
||||
field = Struct.new(:id).new(3)
|
||||
assert_equal({ '2' => 'VIN1', '3' => 'x' }, Form.custom_field_hash(2 => ' VIN1 ', 'name' => 'no', field => 'x'))
|
||||
assert_equal({}, Form.custom_field_hash(nil))
|
||||
form = Form.new(custom_fields: { 2 => 'VIN1' })
|
||||
assert_equal 'VIN1', form.custom_field(2)
|
||||
assert_equal 'VIN1', form.custom_field(Struct.new(:id).new('2'))
|
||||
assert_equal '', form.custom_field(9)
|
||||
end
|
||||
|
||||
def test_from_params
|
||||
form = Form.from_params({ 'customer_id' => ' 9101 ', 'txn_date' => '2026-11-20', 'sync_token' => '',
|
||||
'total_tax' => '4.20', 'linked_estimate_ids' => ['5', '', '5', '6'],
|
||||
'custom_fields' => { '2' => 'VIN' },
|
||||
'lines' => { '0' => { 'item_id' => '1', 'rate' => '10' }, '1' => { 'description' => 'Note' } } },
|
||||
id: '42', document: 'invoice')
|
||||
assert_equal '42', form.id
|
||||
assert form.persisted?
|
||||
assert form.invoice?
|
||||
assert_nil form.sync_token
|
||||
assert_equal '9101', form.customer_id
|
||||
assert_equal '4.20', form.total_tax
|
||||
assert_equal %w[5 6], form.linked_estimate_ids
|
||||
assert_equal({ '2' => 'VIN' }, form.custom_fields)
|
||||
assert_equal 2, form.lines.size
|
||||
assert_equal 'Note', form.lines.last.description
|
||||
end
|
||||
|
||||
def test_defaults
|
||||
form = Form.new
|
||||
assert_equal 'estimate', form.document
|
||||
assert_not form.invoice?
|
||||
assert_not form.persisted?
|
||||
assert_equal [], form.lines
|
||||
assert_equal [], form.linked_estimate_ids
|
||||
end
|
||||
|
||||
# Totals and discounts
|
||||
|
||||
def test_subtotal_skips_blank_rows
|
||||
form = Form.new(lines: [line(quantity: '2', rate: '10', item_id: '1'), line, line(rate: '5.25', item_id: '2')])
|
||||
assert_equal 2, form.filled_lines.size
|
||||
assert_equal BigDecimal('25.25'), form.subtotal
|
||||
end
|
||||
|
||||
def test_percent_discount
|
||||
form = valid_form(discount_value: '10%')
|
||||
assert form.percent_discount?
|
||||
assert form.discount?
|
||||
assert_equal BigDecimal('24'), form.discount_amount
|
||||
end
|
||||
|
||||
def test_amount_discount_and_unknown_type
|
||||
assert_equal BigDecimal('15.56'), valid_form(discount_type: 'amount', discount_value: '15.555').discount_amount
|
||||
assert_equal 'percent', valid_form(discount_type: 'bogus').discount_type
|
||||
assert_not valid_form(discount_value: '0').discount?
|
||||
assert_equal BigDecimal('0'), valid_form.discount_amount
|
||||
end
|
||||
|
||||
def test_fully_paid_and_sent
|
||||
assert Form.new(balance: '0').fully_paid?
|
||||
assert Form.new(balance: '-1').fully_paid?
|
||||
assert_not Form.new(balance: '10').fully_paid?
|
||||
assert_not Form.new.fully_paid?
|
||||
assert Form.new(email_status: 'EmailSent').sent?
|
||||
assert_not Form.new(email_status: 'NeedToSend').sent?
|
||||
end
|
||||
|
||||
# Validation
|
||||
|
||||
def test_valid_form
|
||||
assert valid_form.valid?, valid_form.errors.full_messages.inspect
|
||||
end
|
||||
|
||||
def test_needs_customer_line_and_date
|
||||
form = Form.new(txn_date: '')
|
||||
assert_not form.valid?
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_needs_customer)
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_needs_a_line)
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_estimate_date))
|
||||
end
|
||||
|
||||
def test_invoice_date_label
|
||||
form = valid_form(txn_date: 'nope', document: 'invoice')
|
||||
assert_not form.valid?
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_invoice_date))
|
||||
end
|
||||
|
||||
def test_bad_expiration_and_due_dates
|
||||
form = valid_form(expiration_date: 'soon', due_date: '13/45/2026')
|
||||
assert_not form.valid?
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_expiration_date))
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_due_date))
|
||||
end
|
||||
|
||||
def test_line_errors_are_numbered_by_filled_row
|
||||
form = valid_form(lines: [line, line(item_name: 'Ghost'), line(item_id: '1', rate: 'x')])
|
||||
assert_not form.valid?
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_line_unmatched_item, line: 1, name: 'Ghost')
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_line_number, line: 2)
|
||||
end
|
||||
|
||||
# A row with an unreadable price and no product or description: kept, so it needs a description
|
||||
def test_description_line_needs_text
|
||||
form = valid_form
|
||||
form.lines << line(rate: 'abc')
|
||||
assert_not form.valid?
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_line_description, line: 2)
|
||||
end
|
||||
|
||||
def test_email_addresses
|
||||
assert valid_form(email: 'a@example.com, b@example.com').valid?
|
||||
form = valid_form(email: 'a@example.com, not-an-address')
|
||||
assert_not form.valid?
|
||||
assert_includes form.errors[:base], I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_customer_email))
|
||||
end
|
||||
|
||||
def test_discount_validation
|
||||
invalid = I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_discount_from_quickbooks))
|
||||
assert_includes valid_form(discount_value: '101').tap(&:valid?).errors[:base], invalid
|
||||
assert_includes valid_form(discount_value: '-5').tap(&:valid?).errors[:base], invalid
|
||||
assert_includes valid_form(discount_value: 'ten').tap(&:valid?).errors[:base], invalid
|
||||
assert_includes valid_form(discount_type: 'amount', discount_value: '241').tap(&:valid?).errors[:base],
|
||||
I18n.t(:error_discount_too_large)
|
||||
assert valid_form(discount_type: 'amount', discount_value: '240').valid?
|
||||
assert valid_form(discount_value: '100').valid?
|
||||
end
|
||||
|
||||
def test_plugin_errors_block_the_save
|
||||
RedmineQboBilling::IssueValues.stubs(:plugin_errors).returns(['One vehicle per invoice'])
|
||||
form = valid_form
|
||||
assert_not form.valid?
|
||||
assert_includes form.errors[:base], 'One vehicle per invoice'
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,79 @@
|
||||
#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 InvoicePaidOnTest < ActiveSupport::TestCase
|
||||
PaidOn = RedmineQboBilling::InvoicePaidOn
|
||||
|
||||
def setup
|
||||
Payment.where(id: [9301, 9302]).delete_all
|
||||
end
|
||||
|
||||
def link(type, id)
|
||||
link = Quickbooks::Model::LinkedTransaction.new
|
||||
link.txn_type = type
|
||||
link.txn_id = id.to_s
|
||||
link
|
||||
end
|
||||
|
||||
def invoice(date: Date.new(2026, 10, 30), total: 2207.99, balance: 0, links: [], tax: nil)
|
||||
invoice = Quickbooks::Model::Invoice.new
|
||||
invoice.id = '601'
|
||||
invoice.txn_date = date
|
||||
invoice.total = BigDecimal(total.to_s)
|
||||
invoice.balance = BigDecimal(balance.to_s)
|
||||
invoice.linked_transactions = links
|
||||
if tax
|
||||
invoice.txn_tax_detail = Quickbooks::Model::TransactionTaxDetail.new
|
||||
invoice.txn_tax_detail.total_tax = BigDecimal(tax.to_s)
|
||||
end
|
||||
invoice
|
||||
end
|
||||
|
||||
def local_payment(id, date)
|
||||
payment = Payment.new(id: id, txn_date: date, total_amount: 100)
|
||||
payment.skip_qbo_push = true
|
||||
payment.save!(validate: false)
|
||||
end
|
||||
|
||||
def test_tax
|
||||
assert_equal BigDecimal('80.30'), PaidOn.tax(invoice(tax: '80.30'))
|
||||
assert_equal BigDecimal('0'), PaidOn.tax(invoice)
|
||||
end
|
||||
|
||||
def test_paid_in_full_on_the_last_payment
|
||||
local_payment(9301, Date.new(2026, 10, 8)) # deposit before the invoice
|
||||
local_payment(9302, Date.new(2026, 11, 3)) # final payment
|
||||
remote = invoice(links: [link('Payment', 9301), link('Payment', 9302), link('Estimate', 598)])
|
||||
QboConnectionService.expects(:with_qbo_service).never
|
||||
assert_equal Date.new(2026, 11, 3), PaidOn.paid_on(remote)
|
||||
end
|
||||
|
||||
def test_deposit_before_the_invoice_counts_on_the_invoice_date
|
||||
local_payment(9301, Date.new(2026, 10, 8))
|
||||
assert_equal Date.new(2026, 10, 30), PaidOn.paid_on(invoice(links: [link('Payment', 9301)]))
|
||||
end
|
||||
|
||||
def test_payments_not_synced_and_credit_memos_are_read_from_quickbooks
|
||||
memo = Quickbooks::Model::CreditMemo.new
|
||||
memo.id = '70'
|
||||
memo.txn_date = Date.new(2026, 11, 9)
|
||||
service = mock('service')
|
||||
service.stubs(:query).returns(stub(entries: [memo]))
|
||||
QboConnectionService.expects(:with_qbo_service).with(entity: 'CreditMemo').yields(service).returns([memo])
|
||||
assert_equal Date.new(2026, 11, 9), PaidOn.paid_on(invoice(links: [link('CreditMemo', 70)]))
|
||||
end
|
||||
|
||||
def test_open_and_voided_invoices_arent_paid
|
||||
assert_nil PaidOn.paid_on(invoice(balance: 10))
|
||||
assert_nil PaidOn.paid_on(invoice(total: 0))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,227 @@
|
||||
#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 InvoiceRefundWriterTest < ActiveSupport::TestCase
|
||||
include QboRefundTestHelper
|
||||
Writer = RedmineQboBilling::InvoiceRefundWriter
|
||||
|
||||
def setup
|
||||
User.current = User.find(1)
|
||||
@customer = create_customer
|
||||
Customer.any_instance.stubs(:email).returns('jane@example.com')
|
||||
RedmineQboBilling::RefundWriter.stubs(:fee_item).returns(fee_item)
|
||||
RedmineQboBilling::LaborItems.stubs(:ids).returns([])
|
||||
@gateway = FakeGateway.new
|
||||
@gateway.invoices << paid_invoice
|
||||
end
|
||||
|
||||
def refund(form = invoice_refund_form, gateway: @gateway)
|
||||
Writer.refund!(form, user: User.find(1), gateway: gateway, mailer: FakeMailer)
|
||||
end
|
||||
|
||||
def receipt
|
||||
@gateway.receipts.last
|
||||
end
|
||||
|
||||
def test_lines
|
||||
lines = Writer.lines(paid_invoice, refunds: [])
|
||||
assert_equal %w[1 2 3], lines.map(&:key)
|
||||
assert_equal [false, true, true], lines.map(&:parts)
|
||||
assert_equal [false, true, true], lines.map(&:taxable)
|
||||
assert_equal BigDecimal('120'), lines[1].amount
|
||||
assert_equal BigDecimal('4'), lines[1].quantity
|
||||
assert_equal 'Brake Pads · Ceramic pads', lines[1].label
|
||||
end
|
||||
|
||||
def test_lines_inside_bundles
|
||||
invoice = paid_invoice
|
||||
bundle = Quickbooks::Model::InvoiceLineItem.new
|
||||
bundle.id = '7'
|
||||
bundle.amount = BigDecimal('150')
|
||||
bundle.group_line_detail!
|
||||
bundle.group_line_detail.line_items = [sales_line(nil, 1, 'Labor', 1, 100, taxable: false), sales_line(nil, 5, 'Shim Kit', 1, 50)]
|
||||
invoice.line_items = invoice.line_items + [bundle]
|
||||
lines = Writer.lines(invoice, refunds: [])
|
||||
assert_equal %w[1 2 3 7.1 7.2], lines.map(&:key)
|
||||
assert_equal [false, true], lines.last(2).map(&:parts)
|
||||
end
|
||||
|
||||
def test_paid_in_full_only
|
||||
assert Writer.paid_in_full?(paid_invoice)
|
||||
assert_not Writer.paid_in_full?(paid_invoice(balance: 10))
|
||||
end
|
||||
|
||||
# Returned parts by check: $200.00 of parts, a $60.00 fee (30%), $14.00 tax back: $154.00
|
||||
def test_refund_parts_with_fee
|
||||
record = refund
|
||||
assert record.done?, record.message
|
||||
assert record.invoice?
|
||||
assert_equal '1234', record.invoice_number
|
||||
assert_equal BigDecimal('200'), record.lines_amount
|
||||
assert_equal BigDecimal('200'), record.parts_amount
|
||||
assert_equal BigDecimal('60'), record.fee_amount
|
||||
assert_equal BigDecimal('14'), record.tax_amount
|
||||
assert_equal BigDecimal('154'), record.refund_amount
|
||||
assert_equal BigDecimal('454'), record.credit_amount
|
||||
assert_equal '900', record.purchase_id
|
||||
assert_equal '3000', record.receipt_number
|
||||
assert_equal %w[2 3], record.refunded_lines.map(&:key)
|
||||
|
||||
assert_equal '35', receipt.deposit_to_account_ref.value
|
||||
assert_equal '2', receipt.payment_method_ref.value
|
||||
assert_equal '5002', receipt.payment_ref_number
|
||||
assert_equal CUSTOMER_ID.to_s, receipt.customer_ref.value
|
||||
pads, rotor, fee = receipt.line_items
|
||||
assert_equal '3', pads.sales_item_line_detail.item_ref.value
|
||||
assert_equal BigDecimal('4'), pads.sales_item_line_detail.quantity
|
||||
assert_equal BigDecimal('30'), pads.sales_item_line_detail.unit_price
|
||||
assert_equal 'TAX', pads.sales_item_line_detail.tax_code_ref.value
|
||||
assert_equal BigDecimal('80'), rotor.amount
|
||||
assert_equal BigDecimal('-60'), fee.amount
|
||||
assert_equal '55', fee.sales_item_line_detail.item_ref.value
|
||||
assert_equal 'NON', fee.sales_item_line_detail.tax_code_ref.value
|
||||
assert_equal 'Restocking fee: 30% × $200.00 parts on Invoice #1234 = $60.00', fee.description
|
||||
assert_equal [[record.id, 'jane@example.com']], FakeMailer.sent
|
||||
end
|
||||
|
||||
def test_fee_is_optional
|
||||
record = refund(invoice_refund_form(charge_fee: '0'))
|
||||
assert record.done?, record.message
|
||||
assert_equal BigDecimal('0'), record.fee_amount
|
||||
assert_equal BigDecimal('214'), record.refund_amount
|
||||
assert_equal 2, receipt.line_items.size
|
||||
end
|
||||
|
||||
# Work with no parts: no fee, even when it's ticked, and no fee product/service needed
|
||||
def test_labor_only_has_no_fee
|
||||
RedmineQboBilling::RefundWriter.stubs(:fee_item).returns(nil)
|
||||
record = refund(invoice_refund_form(lines: { '1' => { refund: '1', quantity: '2' } }, method: 'card', check_number: ''))
|
||||
assert record.done?, record.message
|
||||
assert_equal BigDecimal('0'), record.parts_amount
|
||||
assert_equal BigDecimal('0'), record.fee_amount
|
||||
assert_equal BigDecimal('240'), record.refund_amount
|
||||
assert_equal 1, receipt.line_items.size
|
||||
assert_equal 'NON', receipt.line_items.first.sales_item_line_detail.tax_code_ref.value
|
||||
assert_equal '3', receipt.payment_method_ref.value
|
||||
assert_nil receipt.payment_ref_number
|
||||
assert_nil record.check_number
|
||||
end
|
||||
|
||||
# A goodwill refund of part of the labor: an amount alone, no quantity or rate
|
||||
def test_partial_amount
|
||||
record = refund(invoice_refund_form(lines: { '1' => { refund: '1', quantity: '2', amount: '100' } }))
|
||||
assert record.done?, record.message
|
||||
detail = receipt.line_items.first.sales_item_line_detail
|
||||
assert_equal BigDecimal('100'), receipt.line_items.first.amount
|
||||
assert_nil detail.quantity
|
||||
assert_nil detail.unit_price
|
||||
assert_equal '1', detail.item_ref.value
|
||||
# It doesn't use up the 2 hours: what's left is $140.00, offered without a quantity
|
||||
assert_nil record.refunded_lines.first.quantity
|
||||
labor = Writer.lines(paid_invoice).first
|
||||
assert_equal BigDecimal('2'), labor.remaining_quantity
|
||||
assert_equal BigDecimal('140'), labor.remaining_amount
|
||||
assert_nil Writer.default_quantity(labor)
|
||||
assert_equal BigDecimal('4'), Writer.default_quantity(Writer.lines(paid_invoice)[1])
|
||||
end
|
||||
|
||||
def test_a_line_isnt_refunded_twice
|
||||
first = refund(invoice_refund_form(lines: { '2' => { refund: '1', quantity: '2' } }))
|
||||
assert first.done?, first.message
|
||||
assert_equal BigDecimal('60'), first.lines_amount
|
||||
assert_equal BigDecimal('2'), receipt.line_items.first.sales_item_line_detail.quantity
|
||||
|
||||
lines = Writer.lines(paid_invoice)
|
||||
assert_equal BigDecimal('2'), lines[1].remaining_quantity
|
||||
assert_equal BigDecimal('60'), lines[1].remaining_amount
|
||||
|
||||
error = assert_raises(Writer::Error) { refund(invoice_refund_form(lines: { '2' => { refund: '1', quantity: '3' } })) }
|
||||
assert_match(/no more than 2/, error.message)
|
||||
error = assert_raises(Writer::Error) { refund(invoice_refund_form(lines: { '2' => { refund: '1', amount: '61' } })) }
|
||||
assert_match(/\$60\.00 is left/, error.message)
|
||||
assert refund(invoice_refund_form(lines: { '2' => { refund: '1', quantity: '2' } })).done?
|
||||
end
|
||||
|
||||
def test_discount_share
|
||||
@gateway.invoices.replace([paid_invoice(discount: 44)])
|
||||
record = refund(invoice_refund_form(charge_fee: '0'))
|
||||
assert record.done?, record.message
|
||||
# 10% off the invoice: $20.00 of the $200.00 refunded
|
||||
assert_equal BigDecimal('20'), record.discount_amount
|
||||
discount = receipt.line_items.detect { |l| l.detail_type.to_s == 'DiscountLineDetail' }
|
||||
assert_equal BigDecimal('20'), discount.amount
|
||||
assert receipt.apply_tax_after_discount?
|
||||
assert_equal BigDecimal('192.60'), record.refund_amount
|
||||
end
|
||||
|
||||
def test_checks_before_making_anything
|
||||
@gateway.invoices.replace([paid_invoice(balance: 100)])
|
||||
assert_raises(Writer::Error) { refund }
|
||||
@gateway.invoices.replace([paid_invoice(customer_id: 1)])
|
||||
assert_raises(Writer::Error) { refund }
|
||||
@gateway.invoices.replace([paid_invoice])
|
||||
assert_raises(Writer::Error) { refund(invoice_refund_form(lines: { '9' => { refund: '1' } })) }
|
||||
RedmineQboBilling::RefundWriter.stubs(:fee_item).returns(nil)
|
||||
assert_raises(Writer::Error) { refund }
|
||||
assert_equal 0, QboRefund.count
|
||||
assert_empty @gateway.receipts
|
||||
end
|
||||
|
||||
def test_records_when_quickbooks_fails
|
||||
@gateway.fail_on = :receipt
|
||||
record = refund
|
||||
assert_not record.done?
|
||||
assert_match(/refund receipt couldn't be recorded/i, record.message)
|
||||
assert_nil record.purchase_id
|
||||
assert_empty FakeMailer.sent
|
||||
# A refund that made nothing doesn't use up the lines
|
||||
assert_equal BigDecimal('120'), Writer.lines(paid_invoice)[1].remaining_amount
|
||||
end
|
||||
|
||||
def test_notes_the_work_orders
|
||||
Invoice.where(id: 950).delete_all
|
||||
invoice = Invoice.new(id: 950, doc_number: '1234', txn_date: Date.new(2026, 11, 2), customer_id: CUSTOMER_ID,
|
||||
total_amount: 454, balance: 0)
|
||||
invoice.save!(validate: false)
|
||||
invoice.issues << Issue.find(1)
|
||||
status = Issue.find(1).status_id
|
||||
record = refund
|
||||
assert record.done?, record.message
|
||||
assert_equal [1], record.noted_issue_ids
|
||||
issue = Issue.find(1)
|
||||
assert_equal status, issue.status_id
|
||||
assert_equal 'Refunded $154.00 on invoice #1234 by Company check: Parts returned unused', issue.journals.last.notes
|
||||
ensure
|
||||
Invoice.where(id: 950).delete_all
|
||||
end
|
||||
|
||||
def test_the_email
|
||||
record = refund
|
||||
message = QboRefundMailer.refund_summary(record, 'jane@example.com')
|
||||
body = message.body.to_s
|
||||
assert_includes body, "We've processed the refund for Invoice #1234."
|
||||
assert_includes body, 'Brake Pads · Ceramic pads: $120.00'
|
||||
assert_includes body, 'Lines refunded: $200.00'
|
||||
assert_includes body, 'Sales tax: $14.00'
|
||||
assert_includes body, 'Restocking fee (30% of parts): $60.00'
|
||||
assert_includes body, 'Refund: $154.00'
|
||||
assert_includes body, 'returned parts carry a restocking fee'
|
||||
assert_not_includes body, "Labor that wasn't done"
|
||||
end
|
||||
|
||||
def test_the_pdf
|
||||
record = refund
|
||||
document = RedmineQboBilling::RefundPdf.new(record)
|
||||
assert document.render.start_with?('%PDF')
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,63 @@
|
||||
#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 InvoiceStatusTest < ActiveSupport::TestCase
|
||||
Status = RedmineQboBilling::InvoiceStatus
|
||||
TODAY = Date.new(2026, 11, 20)
|
||||
|
||||
def status(total, balance, due: nil)
|
||||
Status.status(total: total, balance: balance, due_date: due, today: TODAY)
|
||||
end
|
||||
|
||||
def test_statuses
|
||||
assert_nil status(100, nil)
|
||||
assert_nil status(100, ' ')
|
||||
assert_equal :voided, status(0, 0)
|
||||
assert_equal :paid, status(100, 0)
|
||||
assert_equal :paid, status(100, -5)
|
||||
assert_equal :overdue, status(100, 40, due: TODAY - 1)
|
||||
assert_equal :partial, status(100, 40, due: TODAY)
|
||||
assert_equal :open, status(100, 100)
|
||||
assert_equal :open, status('100.00', '100')
|
||||
end
|
||||
|
||||
def test_bad_numbers_count_as_zero
|
||||
assert_equal :voided, status('junk', '0')
|
||||
assert_equal BigDecimal('0'), Status.to_d('abc')
|
||||
assert_equal BigDecimal('0'), Status.to_d(nil)
|
||||
end
|
||||
|
||||
def test_labels
|
||||
paid_on = Date.new(2026, 11, 3)
|
||||
assert_equal '', Status.label(nil)
|
||||
assert_equal I18n.t(:label_invoice_status_open), Status.label(:open)
|
||||
assert_equal I18n.t(:label_invoice_status_paid_on, date: I18n.l(paid_on)), Status.label(:paid, paid_on: paid_on)
|
||||
assert_equal I18n.t(:label_invoice_status_paid), Status.label(:paid)
|
||||
end
|
||||
|
||||
def test_short_label_counts_days_to_pay
|
||||
assert_equal I18n.t(:label_invoice_status_paid_days, days: 3),
|
||||
Status.short_label(:paid, paid_on: Date.new(2026, 11, 4), invoice_date: Date.new(2026, 11, 1))
|
||||
# Paid the same day (or before the invoice): just "Paid"
|
||||
assert_equal I18n.t(:label_invoice_status_paid),
|
||||
Status.short_label(:paid, paid_on: Date.new(2026, 11, 1), invoice_date: Date.new(2026, 11, 1))
|
||||
assert_equal I18n.t(:label_invoice_status_open), Status.short_label(:open, paid_on: Date.new(2026, 11, 4), invoice_date: Date.new(2026, 11, 1))
|
||||
end
|
||||
|
||||
def test_title_and_days
|
||||
assert_nil Status.title(:open, paid_on: TODAY)
|
||||
assert_nil Status.title(:paid)
|
||||
assert_equal I18n.t(:text_invoice_paid_in_full, date: I18n.l(TODAY)), Status.title(:paid, paid_on: TODAY)
|
||||
assert_nil Status.days_to_pay(nil, TODAY)
|
||||
assert_equal(-2, Status.days_to_pay(TODAY, TODAY - 2))
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -0,0 +1,66 @@
|
||||
#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 IssueValuesTest < ActiveSupport::TestCase
|
||||
fixtures :projects, :users, :issues, :trackers, :issue_statuses, :enumerations
|
||||
|
||||
Values = RedmineQboBilling::IssueValues
|
||||
Form = RedmineQboBilling::EstimateForm
|
||||
|
||||
def form(lines, attrs = {})
|
||||
Form.new({ lines: lines.map { |l| Form::Line.new(l) } }.merge(attrs))
|
||||
end
|
||||
|
||||
def test_issue_reference_reads_the_first_line
|
||||
assert_equal '116', Values.issue_reference("Install #116: lift kit\nmore #200: text")
|
||||
assert_nil Values.issue_reference('no reference')
|
||||
assert_nil Values.issue_reference(nil)
|
||||
end
|
||||
|
||||
def test_issue_ids_from_time_lines_added_from_notes_and_linked_estimates
|
||||
Issue.find(3).update_column(:estimate_id, 777)
|
||||
doc = form([{ description: 'Install #1: lift', time_activity_id: '55', rate: '1' },
|
||||
{ description: 'Added from: Repair #2: brakes' },
|
||||
{ description: 'Mentions #5: but not imported', rate: '1' },
|
||||
{ description: 'Subtotal #6: x', kind: 'subtotal', time_activity_id: '9' }],
|
||||
document: 'invoice', linked_estimate_ids: ['777'])
|
||||
assert_equal %w[1 2 3], Values.issue_ids(doc).sort
|
||||
assert_equal [1, 2, 3], Values.issues(doc).map(&:id).sort
|
||||
end
|
||||
|
||||
def test_saved_estimate_counts_its_own_issues
|
||||
Issue.find(4).update_column(:estimate_id, 888)
|
||||
assert_equal ['4'], Values.issue_ids(form([], id: '888'))
|
||||
assert_equal [], Values.issue_ids(form([]))
|
||||
assert_equal [], Values.issues(form([]))
|
||||
end
|
||||
|
||||
def test_values_merge_plugins_and_drop_blanks
|
||||
Redmine::Hook.stubs(:call_hook).with(:qbo_billing_issue_values, anything)
|
||||
.returns([{ 2 => { 1 => 'VIN1', 2 => ' ' } }, 'junk', { '2' => { 3 => 'VIN3' }, '4' => 'not a hash' }])
|
||||
issues = Issue.where(id: [1, 2, 3]).to_a
|
||||
assert_equal({ '2' => { '1' => 'VIN1', '3' => 'VIN3' } }, Values.values_for(issues))
|
||||
assert_equal({ '1' => { '2' => 'VIN1' }, '3' => { '2' => 'VIN3' } }, Values.by_issue(issues))
|
||||
assert_equal({}, Values.values_for([]))
|
||||
end
|
||||
|
||||
def test_plugin_errors
|
||||
Redmine::Hook.stubs(:call_hook).with(:qbo_billing_validate, has_entries(document: 'invoice'))
|
||||
.returns([['Two vehicles', nil], '', 'Other'])
|
||||
assert_equal ['Two vehicles', 'Other'], Values.plugin_errors(form([], document: 'invoice'))
|
||||
end
|
||||
|
||||
def test_a_failing_plugin_does_not_stop_the_save
|
||||
Redmine::Hook.stubs(:call_hook).raises(StandardError, 'boom')
|
||||
assert_equal [], Values.plugin_errors(form([]))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,56 @@
|
||||
#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__)
|
||||
|
||||
# Estimates linked to an issue are read-only unless unlocked by a user with "Edit estimates linked to issues"
|
||||
class LinkedEstimateUnlockTest < ActiveSupport::TestCase
|
||||
Writer = RedmineQboBilling::EstimateWriter
|
||||
|
||||
def user(*permissions)
|
||||
user = User.new
|
||||
user.stubs(:allowed_to?).returns(false)
|
||||
permissions.each { |p| user.stubs(:allowed_to?).with(p, nil, global: true).returns(true) }
|
||||
user
|
||||
end
|
||||
|
||||
def form(linked:)
|
||||
Writer.stubs(:linked_issues).with('701').returns(stub(exists?: linked))
|
||||
RedmineQboBilling::EstimateForm.new.tap { |f| f.id = '701' }
|
||||
end
|
||||
|
||||
def test_editor_needs_write_estimates_and_edit_linked_estimates
|
||||
assert RedmineQboBilling.linked_estimate_editor?(user(:write_estimates, :edit_linked_estimates))
|
||||
assert_not RedmineQboBilling.linked_estimate_editor?(user(:write_estimates))
|
||||
assert_not RedmineQboBilling.linked_estimate_editor?(user(:edit_linked_estimates))
|
||||
end
|
||||
|
||||
def test_unlinked_estimate_saves_without_unlocking
|
||||
assert_nothing_raised { Writer.check_linked(form(linked: false), false, user(:write_estimates)) }
|
||||
end
|
||||
|
||||
def test_linked_estimate_is_locked_without_unlock
|
||||
error = assert_raises(Writer::Error) do
|
||||
Writer.check_linked(form(linked: true), false, user(:write_estimates, :edit_linked_estimates))
|
||||
end
|
||||
assert_equal I18n.t(:error_estimate_linked_to_issues), error.message
|
||||
end
|
||||
|
||||
def test_unlock_needs_the_permission
|
||||
error = assert_raises(Writer::Error) { Writer.check_linked(form(linked: true), true, user(:write_estimates)) }
|
||||
assert_equal I18n.t(:error_estimate_linked_not_allowed), error.message
|
||||
end
|
||||
|
||||
def test_unlocked_by_an_editor_saves
|
||||
assert_nothing_raised do
|
||||
Writer.check_linked(form(linked: true), true, user(:write_estimates, :edit_linked_estimates))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,81 @@
|
||||
#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__)
|
||||
|
||||
# LaborItems and ManHours
|
||||
class ManHoursTest < ActiveSupport::TestCase
|
||||
def ref(id, name)
|
||||
Quickbooks::Model::BaseReference.new(id.to_s, name: name)
|
||||
end
|
||||
|
||||
def sales_line(item_id, name, quantity)
|
||||
line = Quickbooks::Model::InvoiceLineItem.new
|
||||
line.sales_item! do |d|
|
||||
d.item_ref = ref(item_id, name)
|
||||
d.quantity = BigDecimal(quantity.to_s)
|
||||
end
|
||||
line
|
||||
end
|
||||
|
||||
def invoice(*lines)
|
||||
Quickbooks::Model::Invoice.new.tap { |i| i.line_items = lines }
|
||||
end
|
||||
|
||||
def test_ids_from_settings
|
||||
assert_equal %w[1 2], RedmineQboBilling::LaborItems.ids('labor_item_ids' => [1, '2', '', '1'])
|
||||
assert_equal [], RedmineQboBilling::LaborItems.ids({})
|
||||
end
|
||||
|
||||
def test_match_by_id_or_name
|
||||
labor = RedmineQboBilling::LaborItems
|
||||
assert labor.match?(ref(5, 'Anything'), ids: ['5'])
|
||||
assert_not labor.match?(ref(6, 'Labor'), ids: ['5'])
|
||||
assert labor.match?(ref(6, 'Labor'), ids: [])
|
||||
assert labor.match?(ref(6, 'Services:labor'), ids: [])
|
||||
assert_not labor.match?(ref(6, 'Laborious part'), ids: [])
|
||||
assert_not labor.match?(nil, ids: [])
|
||||
assert_not labor.name_matches?(' ', ['Labor'])
|
||||
assert labor.name_matches?('Shop Labor', ['shop labor'])
|
||||
end
|
||||
|
||||
def test_item_ids_and_names_fall_back_to_matching_names
|
||||
Setting.stubs(:plugin_redmine_qbo).returns({})
|
||||
Item.stubs(:sellable).returns(stub(pluck: [[11, 'Labor'], [12, 'Brake pads'], [13, 'Shop:Labor']]))
|
||||
assert_equal %w[11 13], RedmineQboBilling::LaborItems.item_ids
|
||||
assert_equal ['Labor'], RedmineQboBilling::LaborItems.names
|
||||
end
|
||||
|
||||
def test_chosen_item_ids_and_names
|
||||
Setting.stubs(:plugin_redmine_qbo).returns('labor_item_ids' => ['21'])
|
||||
assert_equal ['21'], RedmineQboBilling::LaborItems.item_ids
|
||||
Item.stubs(:where).with(id: ['21']).returns(stub(pluck: []))
|
||||
assert_equal ['21'], RedmineQboBilling::LaborItems.names
|
||||
end
|
||||
|
||||
def test_hours_by_name
|
||||
Setting.stubs(:plugin_redmine_qbo).returns({})
|
||||
doc = invoice(sales_line(1, 'Labor', 2.5), sales_line(2, 'Brake pads', 4), sales_line(1, 'Labor', '1.25'))
|
||||
assert_equal 3.75, RedmineQboBilling::ManHours.hours(doc)
|
||||
end
|
||||
|
||||
def test_hours_by_id_include_bundles
|
||||
bundle = Quickbooks::Model::InvoiceLineItem.new
|
||||
bundle.group_line_detail!
|
||||
bundle.group_line_detail.line_items = [sales_line(9, 'Install', 3), sales_line(2, 'Part', 1)]
|
||||
doc = invoice(bundle, sales_line(9, 'Install', 1))
|
||||
assert_equal 4.0, RedmineQboBilling::ManHours.hours(doc, item_ids: ['9'])
|
||||
end
|
||||
|
||||
def test_hours_of_nothing
|
||||
assert_equal 0.0, RedmineQboBilling::ManHours.hours(nil)
|
||||
assert_equal 0.0, RedmineQboBilling::ManHours.hours(invoice, item_ids: ['9'])
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,112 @@
|
||||
#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__)
|
||||
|
||||
# Estimate, Invoice and Payment: the local QuickBooks caches, and their events on the activity page (QboActivity)
|
||||
class QboDocumentsTest < ActiveSupport::TestCase
|
||||
fixtures :users
|
||||
|
||||
CUSTOMER_ID = 9301
|
||||
|
||||
def setup
|
||||
Estimate.where(id: [9401, 9402]).delete_all
|
||||
Invoice.where(id: [9501, 9502, 9503]).delete_all
|
||||
Payment.where(id: [9601]).delete_all
|
||||
Customer.where(id: CUSTOMER_ID).delete_all
|
||||
customer = Customer.new(id: CUSTOMER_ID, name: 'Jane Customer')
|
||||
customer.skip_qbo_push = true
|
||||
customer.save!
|
||||
end
|
||||
|
||||
def estimate(id, attrs = {})
|
||||
Estimate.create!({ id: id, doc_number: "E#{id}", customer_id: CUSTOMER_ID, txn_date: Date.new(2026, 11, 10),
|
||||
total_amount: 1250, txn_status: 'Pending' }.merge(attrs))
|
||||
end
|
||||
|
||||
def invoice(id, attrs = {})
|
||||
Invoice.create!({ id: id, doc_number: id.to_s, customer_id: CUSTOMER_ID, txn_date: Date.new(2026, 11, 10),
|
||||
total_amount: 1250, balance: 1250, due_date: Date.new(2026, 12, 10) }.merge(attrs))
|
||||
end
|
||||
|
||||
def user(*permissions)
|
||||
user = User.find(2)
|
||||
user.stubs(:allowed_to?).returns(false)
|
||||
permissions.each { |p| user.stubs(:allowed_to?).with(p, nil, global: true).returns(true) }
|
||||
user
|
||||
end
|
||||
|
||||
def test_estimate
|
||||
record = estimate(9401)
|
||||
assert_equal 'E9401', record.to_s
|
||||
assert_equal 'E9401', record.name
|
||||
assert_not record.billed?
|
||||
RedmineQboBilling::EstimateWriter::BILLED_STATUSES.each do |status|
|
||||
assert estimate(9402, txn_status: status).billed?, status
|
||||
Estimate.where(id: 9402).delete_all
|
||||
end
|
||||
assert_not Estimate.new(id: 9402).valid?
|
||||
end
|
||||
|
||||
def test_invoice_status_and_activity_description
|
||||
today = Date.new(2026, 11, 20)
|
||||
assert_equal :open, invoice(9501).status(today: today)
|
||||
partial = invoice(9502, balance: 400)
|
||||
assert_equal :partial, partial.status(today: today)
|
||||
User.current.stubs(:today).returns(today)
|
||||
assert_equal "$1,250.00 · #{I18n.t(:label_invoice_status_partial)} · #{I18n.t(:text_activity_invoice_owed, amount: '$400.00')}",
|
||||
partial.activity_description
|
||||
assert_equal "$1,250.00 · #{I18n.t(:label_invoice_status_open)}", Invoice.find(9501).activity_description
|
||||
unknown = invoice(9503, balance: nil)
|
||||
assert_nil unknown.status
|
||||
assert_equal '$1,250.00', unknown.activity_description
|
||||
assert_equal '9503', unknown.to_s
|
||||
end
|
||||
|
||||
def test_payment_activity_description
|
||||
payment = Payment.create!(id: 9601, customer_id: CUSTOMER_ID, txn_date: Date.new(2026, 11, 2),
|
||||
total_amount: 500, unapplied_amount: 0)
|
||||
assert_equal '', payment.activity_description
|
||||
payment.unapplied_amount = 150
|
||||
assert_equal I18n.t(:text_activity_payment_unapplied, amount: '$150.00'), payment.activity_description
|
||||
assert_equal '2026-11-02 500.0', payment.to_s
|
||||
end
|
||||
|
||||
def test_activity_needs_a_permission_and_no_project
|
||||
estimate(9401)
|
||||
assert_equal [], Estimate.find_events('qbo_estimates', user, nil, nil, {})
|
||||
viewer = user(:view_customers)
|
||||
assert_equal [9401], Estimate.find_events('qbo_estimates', viewer, nil, nil, {}).map(&:id)
|
||||
assert_equal [], Estimate.find_events('qbo_estimates', viewer, nil, nil, project: Project.new)
|
||||
assert_equal [], Estimate.find_events('qbo_estimates', viewer, nil, nil, author: viewer)
|
||||
assert_equal({ 'qbo_estimates' => { permission: :view_customers } }, Estimate.activity_provider_options)
|
||||
assert Payment.qbo_activity_visible_to?(user(:receive_payments))
|
||||
end
|
||||
|
||||
def test_activity_by_quickbooks_date
|
||||
estimate(9401, txn_date: Date.new(2026, 11, 10))
|
||||
estimate(9402, txn_date: Date.new(2026, 11, 12))
|
||||
viewer = user(:write_estimates)
|
||||
found = Estimate.find_events('qbo_estimates', viewer, Date.new(2026, 11, 11), Date.new(2026, 11, 13), {})
|
||||
assert_equal [9402], found.map(&:id)
|
||||
assert_equal [9402], Estimate.find_events('qbo_estimates', viewer, nil, nil, limit: 1).map(&:id)
|
||||
end
|
||||
|
||||
def test_activity_datetime
|
||||
record = estimate(9401, txn_date: Date.new(2026, 11, 10))
|
||||
assert_equal Time.local(2026, 11, 10, 12), record.activity_datetime
|
||||
record.txn_date = record.created_at.getlocal.to_date
|
||||
assert_equal record.created_at, record.activity_datetime
|
||||
assert_equal 'Jane Customer', record.activity_customer
|
||||
assert_nil record.project
|
||||
assert_nil record.activity_money(nil)
|
||||
assert_equal I18n.t(:label_none), Estimate.new.activity_customer
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,67 @@
|
||||
#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 QboDraftTest < ActiveSupport::TestCase
|
||||
fixtures :users
|
||||
|
||||
def setup
|
||||
QboDraft.delete_all
|
||||
end
|
||||
|
||||
def draft(document, fields = {})
|
||||
QboDraft.create!(document: document, fields: fields)
|
||||
end
|
||||
|
||||
def test_document_must_be_known
|
||||
assert_not QboDraft.new(document: 'payment').valid?
|
||||
assert QboDraft.new(document: 'invoice').valid?
|
||||
end
|
||||
|
||||
def test_fields_round_trip_and_bad_data
|
||||
record = draft('estimate', 'customer_name' => 'Jane', 'lines' => { '0' => { 'rate' => '10', 'item_id' => '1' } })
|
||||
assert_equal 'Jane', record.reload.fields['customer_name']
|
||||
record.data = 'not json'
|
||||
assert_equal({}, record.fields)
|
||||
record.data = '[1, 2]'
|
||||
assert_equal({}, record.fields)
|
||||
record.data = nil
|
||||
assert_equal({}, record.fields)
|
||||
end
|
||||
|
||||
def test_form_subtotal_and_line_count
|
||||
record = draft('invoice', 'lines' => { '0' => { 'item_id' => '1', 'quantity' => '2', 'rate' => '10' },
|
||||
'1' => { 'kind' => 'subtotal' }, '2' => { 'description' => 'Note' },
|
||||
'3' => {} })
|
||||
assert record.invoice?
|
||||
assert record.form.invoice?
|
||||
assert_equal BigDecimal('20'), record.subtotal
|
||||
assert_equal 2, record.line_count
|
||||
end
|
||||
|
||||
def test_customer_name_falls_back_to_the_typed_name
|
||||
assert_equal 'Typed Name', draft('estimate', 'customer_name' => 'Typed Name').customer_name
|
||||
assert_nil draft('estimate').customer_name
|
||||
end
|
||||
|
||||
def test_visible_by_permission
|
||||
estimate = draft('estimate')
|
||||
invoice = draft('invoice')
|
||||
user = User.find(2)
|
||||
user.stubs(:allowed_to?).returns(false)
|
||||
assert_empty QboDraft.visible(user)
|
||||
user.stubs(:allowed_to?).with(:write_estimates, nil, global: true).returns(true)
|
||||
assert_equal [estimate], QboDraft.visible(user).to_a
|
||||
user.stubs(:allowed_to?).with(:write_invoices, nil, global: true).returns(true)
|
||||
assert_equal [estimate, invoice], QboDraft.visible(user).order(:id).to_a
|
||||
assert_equal [invoice], QboDraft.for_document(:invoice).to_a
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -0,0 +1,122 @@
|
||||
#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__)
|
||||
|
||||
# Item, Account and what every QuickBooks-backed model shares (QboBaseModel)
|
||||
class QboItemsAndAccountsTest < ActiveSupport::TestCase
|
||||
def setup
|
||||
Item.where(id: [9701, 9702, 9703, 9704]).delete_all
|
||||
Account.where(id: [9801, 9802]).delete_all
|
||||
end
|
||||
|
||||
def item(id, attrs = {})
|
||||
record = Item.new({ id: id, name: "Item #{id}", description: '', unit_price: 10, active: true, type: 'Service' }.merge(attrs))
|
||||
record.skip_qbo_push = true
|
||||
record.save!
|
||||
record
|
||||
end
|
||||
|
||||
def account(id, attrs = {})
|
||||
Account.create!({ id: id, name: "Account #{id}" }.merge(attrs))
|
||||
end
|
||||
|
||||
def test_item_setters_write_through_to_quickbooks
|
||||
income = account(9801, name: 'Sales')
|
||||
record = Item.new(id: 9701, name: 'Labor', description: 'Shop labor', sku: 'LAB', unit_price: 120, type: 'Service',
|
||||
account_id: income.id)
|
||||
assert_equal 'Labor', record.details.name
|
||||
assert_equal 'Shop labor', record.details.description
|
||||
assert_equal 'LAB', record.details.sku
|
||||
assert_equal BigDecimal('120'), record.details.unit_price
|
||||
assert_equal 'Service', record.details.type
|
||||
assert_equal '9801', record.details.income_account_ref.value.to_s
|
||||
assert record.taxable
|
||||
end
|
||||
|
||||
def test_unknown_account_leaves_the_quickbooks_ref_alone
|
||||
record = Item.new(id: 9701, name: 'Labor', account_id: 12_345)
|
||||
assert_nil record.details.income_account_ref
|
||||
assert_equal 12_345, record.account_id
|
||||
end
|
||||
|
||||
def test_item_validation
|
||||
assert_not Item.new(id: 9701, name: '').tap { |i| i.skip_qbo_push = true }.valid?
|
||||
assert_not Item.new(id: 9701, name: 'Part', unit_price: -1).tap { |i| i.skip_qbo_push = true }.valid?
|
||||
end
|
||||
|
||||
def test_sellable
|
||||
item(9701)
|
||||
item(9702, type: 'Category')
|
||||
item(9703, active: false)
|
||||
item(9704, type: nil)
|
||||
assert_equal [9701, 9704], Item.sellable.where(id: [9701, 9702, 9703, 9704]).order(:id).pluck(:id)
|
||||
end
|
||||
|
||||
def test_destroying_an_item_makes_it_inactive_in_quickbooks
|
||||
record = item(9701)
|
||||
record.expects(:push_to_qbo).once
|
||||
record.destroy
|
||||
assert_equal false, record.details.active?
|
||||
end
|
||||
|
||||
def test_one_default_account
|
||||
first = account(9801, default: true)
|
||||
second = account(9802, default: true)
|
||||
assert_not first.reload.default
|
||||
assert_equal second, Account.get_default
|
||||
ref = second.ref
|
||||
assert_equal 9802, ref.value
|
||||
assert_equal 'Account 9802', ref.name
|
||||
assert_equal 'Account 9802', second.to_s
|
||||
end
|
||||
|
||||
def test_push_toggle
|
||||
assert Item.qbo_push_enabled
|
||||
assert_not Estimate.qbo_push_enabled
|
||||
record = Item.new(id: 9701, name: 'Part')
|
||||
assert record.push_to_qbo?
|
||||
record.skip_qbo_push = true
|
||||
assert_not record.push_to_qbo?
|
||||
assert_not Estimate.new.push_to_qbo?
|
||||
end
|
||||
|
||||
def test_method_missing_reaches_the_quickbooks_entity
|
||||
record = Item.new(id: 9701, name: 'Part')
|
||||
assert record.respond_to?(:purchase_desc)
|
||||
record.purchase_desc = 'Bought in bulk'
|
||||
assert_equal 'Bought in bulk', record.purchase_desc
|
||||
assert_raises(NoMethodError) { record.not_a_quickbooks_field }
|
||||
end
|
||||
|
||||
def test_sync_queues_jobs
|
||||
QboSyncStatus.delete_all
|
||||
QboSyncJob.expects(:perform_later).with(entity: 'Item', full_sync: true)
|
||||
Item.sync
|
||||
assert_equal 'queued', QboSyncStatus.find_by(entity: 'Item').state
|
||||
QboSyncJob.expects(:perform_later).with(entity: 'Item', id: 5)
|
||||
Item.sync_by_id(5)
|
||||
QboSyncJob.expects(:perform_later).with(entity: 'Estimate', doc_number: '1068')
|
||||
Estimate.sync_by_doc_number('1068')
|
||||
end
|
||||
|
||||
def test_last_sync
|
||||
Employee.delete_all
|
||||
assert_equal I18n.t(:label_qbo_never_synced), Employee.last_sync
|
||||
end
|
||||
|
||||
def test_estimate_line_issue_link
|
||||
QboEstimateLineIssue.delete_all
|
||||
link = QboEstimateLineIssue.create!(estimate_id: 1, line_id: '3', issue_id: 1)
|
||||
assert link.created_on
|
||||
assert_not QboEstimateLineIssue.new(estimate_id: 1, line_id: '3', issue_id: 2).valid?
|
||||
assert_not QboEstimateLineIssue.new(line_id: '4').valid?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,87 @@
|
||||
#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 QboRefundTest < ActiveSupport::TestCase
|
||||
def refund(attrs = {})
|
||||
QboRefund.new({ customer_id: 9101, method: 'card', status: 'done', kind: 'credit' }.merge(attrs))
|
||||
end
|
||||
|
||||
def test_validations
|
||||
assert refund.valid?
|
||||
assert_not refund(method: 'cash').valid?
|
||||
assert_not refund(status: 'maybe').valid?
|
||||
assert_not refund(kind: 'other').valid?
|
||||
assert_not refund(customer_id: nil).valid?
|
||||
end
|
||||
|
||||
def test_flags_and_method_name
|
||||
record = refund(method: 'check', kind: 'invoice', status: 'incomplete')
|
||||
assert record.check?
|
||||
assert record.invoice?
|
||||
assert_not record.done?
|
||||
assert_equal I18n.t(:label_refund_method_check), record.method_name
|
||||
end
|
||||
|
||||
def test_issue_id_lists
|
||||
record = refund
|
||||
record.canceled_issue_ids = ['3', 3, 4]
|
||||
record.noted_issue_ids = [7]
|
||||
assert_equal [3, 4], record.canceled_issue_ids
|
||||
assert_equal [7], record.noted_issue_ids
|
||||
record[:canceled_issue_ids] = 'garbage'
|
||||
record[:noted_issue_ids] = nil
|
||||
assert_equal [], record.canceled_issue_ids
|
||||
assert_equal [], record.noted_issue_ids
|
||||
end
|
||||
|
||||
def test_refunded_lines_round_trip
|
||||
record = refund
|
||||
record.refunded_lines = [QboRefund::RefundedLine.new(key: 3, description: 'Brake pads', quantity: 2,
|
||||
amount: BigDecimal('60'), parts: true),
|
||||
QboRefund::RefundedLine.new(key: 'L1', description: 'Labor', quantity: nil,
|
||||
amount: 120, parts: nil)]
|
||||
lines = record.refunded_lines
|
||||
assert_equal %w[3 L1], lines.map(&:key)
|
||||
assert_equal '2', lines.first.quantity
|
||||
assert_equal BigDecimal('60'), lines.first.amount
|
||||
assert lines.first.parts
|
||||
assert_not lines.last.parts
|
||||
assert_nil lines.last.quantity
|
||||
record[:refunded_lines] = '{bad'
|
||||
assert_equal [], record.refunded_lines
|
||||
end
|
||||
|
||||
def test_document_label
|
||||
assert_equal 'E1068', refund(estimate_number: '1068').document_label
|
||||
assert_nil refund.document_label
|
||||
assert_equal I18n.t(:label_refund_invoice_number, number: '1234'),
|
||||
refund(kind: 'invoice', invoice_number: '1234').document_label
|
||||
end
|
||||
|
||||
def test_purchase_url
|
||||
RedmineQbo.stubs(:sandbox_mode?).returns(false)
|
||||
assert_nil refund.purchase_url
|
||||
assert_equal 'https://app.qbo.intuit.com/app/expense?txnId=5', refund(purchase_id: '5').purchase_url
|
||||
assert_equal 'https://app.qbo.intuit.com/app/check?txnId=5', refund(purchase_id: '5', method: 'check').purchase_url
|
||||
assert_equal 'https://app.qbo.intuit.com/app/refundreceipt?txnId=5', refund(purchase_id: '5', kind: 'invoice').purchase_url
|
||||
RedmineQbo.stubs(:sandbox_mode?).returns(true)
|
||||
assert_equal 'https://sandbox.qbo.intuit.com/app/expense?txnId=5', refund(purchase_id: '5').purchase_url
|
||||
end
|
||||
|
||||
def test_of_invoice_needs_a_receipt
|
||||
QboRefund.delete_all
|
||||
with_receipt = refund(kind: 'invoice', invoice_id: 601, purchase_id: '900').tap { |r| r.save!(validate: false) }
|
||||
refund(kind: 'invoice', invoice_id: 601, purchase_id: '').save!(validate: false)
|
||||
refund(kind: 'invoice', invoice_id: 602, purchase_id: '901').save!(validate: false)
|
||||
assert_equal [with_receipt.id], QboRefund.of_invoice(601).pluck(:id)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,106 @@
|
||||
#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__)
|
||||
|
||||
# WebhookProcessJob, QboSyncDispatcher and QboSyncJob
|
||||
class QboSyncJobsTest < ActiveSupport::TestCase
|
||||
def setup
|
||||
QboSyncStatus.delete_all
|
||||
Qbo.stubs(:update_time_stamp)
|
||||
end
|
||||
|
||||
def notification(*entities)
|
||||
{ eventNotifications: [{ realmId: '1', dataChangeEvent: { entities: entities } }] }.to_json
|
||||
end
|
||||
|
||||
# Items and accounts come from the plugin's own hook (QboHookListener); anything else is ignored
|
||||
def test_webhook_syncs_allowed_entities
|
||||
Invoice.expects(:sync_by_id).with(601)
|
||||
Customer.expects(:sync_by_id).with(9101)
|
||||
Item.expects(:sync_by_id).with(5)
|
||||
Account.expects(:sync_by_id).with(84)
|
||||
Kernel.expects(:sync_by_id).never
|
||||
WebhookProcessJob.perform_now(notification({ name: 'Invoice', id: '601', operation: 'Update' },
|
||||
{ name: 'Customer', id: '9101', operation: 'Create' },
|
||||
{ name: 'Item', id: '5', operation: 'Update' },
|
||||
{ name: 'Account', id: '84', operation: 'Update' },
|
||||
{ name: 'Kernel', id: '1', operation: 'Update' },
|
||||
{ name: 'Vendor', id: '2', operation: 'Update' }))
|
||||
end
|
||||
|
||||
def test_webhook_deletes
|
||||
Estimate.expects(:delete).with(598)
|
||||
Payment.expects(:delete).with('801')
|
||||
WebhookProcessJob.perform_now(notification({ name: 'Estimate', id: '598', operation: 'Delete' },
|
||||
{ name: 'Payment', id: '802', operation: 'Merge', deletedId: '801' }))
|
||||
end
|
||||
|
||||
def test_plugins_add_webhook_entities
|
||||
Redmine::Hook.stubs(:call_hook).with(:qbo_additional_entities).returns([['Vehicle'], nil])
|
||||
vehicle = Class.new { def self.sync_by_id(_id); end }
|
||||
Object.const_set(:Vehicle, vehicle) unless defined?(::Vehicle)
|
||||
::Vehicle.expects(:sync_by_id).with(5)
|
||||
WebhookProcessJob.perform_now(notification({ name: 'Vehicle', id: '5', operation: 'Update' }))
|
||||
ensure
|
||||
Object.send(:remove_const, :Vehicle) if defined?(::Vehicle) && ::Vehicle == vehicle
|
||||
end
|
||||
|
||||
def test_plugin_hook_adds_items_and_accounts
|
||||
listener = RedmineQboBilling::Hooks::QboHookListener.instance
|
||||
assert_equal %w[Item Account], listener.qbo_additional_entities
|
||||
assert_equal [Account, Item], listener.qbo_full_sync
|
||||
end
|
||||
|
||||
def test_one_bad_entity_does_not_stop_the_rest
|
||||
Invoice.stubs(:sync_by_id).raises(StandardError, 'boom')
|
||||
Customer.expects(:sync_by_id).with(9101)
|
||||
WebhookProcessJob.perform_now(notification({ name: 'Invoice', id: '601' }, { name: 'Customer', id: '9101' }))
|
||||
end
|
||||
|
||||
def test_webhook_updates_the_time_stamp
|
||||
Qbo.expects(:update_time_stamp)
|
||||
WebhookProcessJob.perform_now('{}')
|
||||
end
|
||||
|
||||
def test_dispatcher_queues_every_entity_payments_before_invoices
|
||||
queued = []
|
||||
QboSyncJob.stubs(:perform_later).with { |args| queued << [args[:entity].to_s, args[:full_sync]] }
|
||||
Redmine::Hook.stubs(:call_hook).with(:qbo_full_sync).returns([[Item], nil])
|
||||
QboSyncDispatcher.sync!(full_sync: true)
|
||||
assert_equal %w[Customer Estimate Payment Invoice Employee Item], queued.map(&:first)
|
||||
assert queued.all?(&:last)
|
||||
assert_equal 6, QboSyncStatus.where(state: 'queued').count
|
||||
end
|
||||
|
||||
def test_sync_job_by_id_doc_number_or_all
|
||||
CustomerSyncService.any_instance.expects(:sync_by_id).with(9101)
|
||||
QboSyncJob.perform_now(entity: 'Customer', id: 9101)
|
||||
|
||||
EstimateSyncService.any_instance.expects(:sync_by_doc_number).with('1068')
|
||||
QboSyncJob.perform_now(entity: 'Estimate', doc_number: '1068')
|
||||
|
||||
InvoiceSyncService.any_instance.expects(:sync).with(full_sync: true)
|
||||
QboSyncStatus.queued('Invoice')
|
||||
QboSyncJob.perform_now(entity: 'Invoice', full_sync: true)
|
||||
assert_not QboSyncStatus.exists?(entity: 'Invoice')
|
||||
end
|
||||
|
||||
def test_sync_status_is_cleared_when_the_sync_fails
|
||||
InvoiceSyncService.any_instance.stubs(:sync).raises(StandardError, 'QuickBooks down')
|
||||
job = QboSyncJob.new(entity: 'Invoice')
|
||||
assert_raises(StandardError) { job.perform(entity: 'Invoice') }
|
||||
assert_not QboSyncStatus.exists?(entity: 'Invoice')
|
||||
end
|
||||
|
||||
def test_sync_job_needs_an_entity
|
||||
assert_raises(RuntimeError) { QboSyncJob.new.perform }
|
||||
end
|
||||
end
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user