Compare commits

...
44 Commits
Author SHA1 Message Date
rickyandClaude Opus 5.5 8ce702cb44 2026.11.28
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:47:15 -05:00
rickyandClaude Opus 5.5 ae0ffc7c1c Leave other plugins' features to hooks
Refund emails and PDFs take the shop name and mail settings from
:qbo_mail_settings instead of reading redmine_qbo_reminders' settings; the
customer page's ticked boxes use generic data-ticked-field/data-ticked-params
instead of knowing redmine_qbo_calendar's Add appointment link; and Create
issues carries the params plugins name in :qbo_billing_issue_carry_params
instead of appointment_id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:37:57 -05:00
rickyandClaude Opus 5.5 0552e2f1a3 2026.11.27
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 22:26:56 -05:00
rickyandClaude Opus 5.5 bc822ddc22 Leave vehicles to redmine_qbo_vehicles' hooks
Create issues no longer copies a parent issue's vehicle itself: the parent
is passed to :qbo_billing_issue_defaults (parent_issue:) and
:qbo_billing_build_issue (parent:), and every plugin's defaults are merged
rather than only the first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 22:17:58 -05:00
rickyandClaude Opus 5.5 62d767b695 Estimates QuickBooks can't read raise an ordinary error
EstimateService had no build_qbo_remote, so a failed read fell back to
ServiceBase's NotImplementedError, which rescue StandardError misses (e.g.
saving an appointment with an estimate while QuickBooks was down gave a 500).
Tests keep refund emails off redmine_qbo_reminders' SMTP server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:50:22 -05:00
rickyandClaude Opus 5.5 7029aa70dc New screenshots
Replaced the old screenshots (outdated, with real names) with current
pages from a test instance with made-up data, and shown them in the
README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:02:32 -05:00
rickyandClaude Opus 5.5 ff9556e728 Show the customer's addresses again; blank missing phones
The customer page's Billing and Shipping Address were always empty: the
controller stopped setting them in March and the view still read them.
The page now formats the QuickBooks addresses itself. A missing phone
number showed as "0", and the balance as "$125.0"; they're now blank
and "$125.00".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:02:32 -05:00
rickyandClaude Opus 5.5 761722bbb1 2026.11.26
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:41:13 -05:00
rickyandClaude Opus 5.5 6ea5610b51 README: unlocking linked estimates, PDF permissions, running the tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:41:13 -05:00
rickyandClaude Opus 5.5 b829593bc2 Limit estimate and invoice PDFs by permission; clean up
Any logged-in user could open any estimate or invoice PDF by id. Now:
- estimates: View customers or Write estimates, or an estimate attached
  to an issue the user can see (the issue page links to it); users
  without the permission don't trigger a sync of uncached estimates
- invoices: View customers, Write invoices, View/Receive payments or
  Issue refunds, or invoices attached to issues the user can see
- share-link customers are unchanged (their own issue's documents)
- the sidebar's estimate search only shows to those who can use it

The issue PDF merges an estimate PDF with optional content, as it
already did for the issue's own PDF, instead of failing.

Removed dead code: the JSON branches of CustomersController#create
(Redmine refuses JSON there) and the scaffold views for
qbo#authenticate, #oauth_callback and #webhook, which those actions
never render. An invalid customer now shows the form with a 422.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:36:20 -05:00
rickyandClaude Opus 5.5 17f24f9641 Add tests for billing time, OAuth, patches and helpers
BillIssueTimeJob (hours by activity, partial failure and retry, quoted
item names), the QuickBooks connection and token refresh, the business
report's periods and database figures, the Redmine page patches and
hooks (issue page, form, history, issue list column and filter, billed
time, user employee, bill/share links, issue PDF with its estimate,
activity), RefundGateway, the refund email and PDF, the services' query
string and emailing, invoice lines' LinkedTxn, combined PDFs, invoice
attachment, and the plugin settings page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:41:58 -05:00
rickyandClaude Opus 5.5 da82f7e12c Add controller and job tests
Integration tests for every controller: permissions, the estimate and
invoice editors (drafts, save and send, conflicts, the linked-estimate
and paid-invoice unlocks), payments, drafts, customers and share
links, estimate/invoice PDFs for share-link customers, items, accounts,
the business report, and QboController (OAuth state check, webhook
signature, manual billing). Unit tests for the webhook job, the sync
dispatcher and QboSyncJob.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:36:02 -05:00
rickyandClaude Opus 5.5 9ed3ef23fb Add tests for the QuickBooks writers and services
A fake QuickBooks service (test/qbo_fake_service.rb) stands in for the
estimate, invoice and connection services, so the writers are tested
end to end without QuickBooks.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:28:38 -05:00
rickyandClaude Opus 5.5 00400c21dc Add tests for forms, billing helpers and models
Unit tests for EstimateForm, PaymentForm, RefundForm, InvoiceRefundForm,
InvoiceStatus, LaborItems/ManHours, IssueValues, TitleCase, the
RedmineQboBilling permission helpers and field hooks, and the models:
Customer, Estimate, Invoice, Payment (with their activity events), Item,
Account, QboDraft, QboRefund, QboSyncStatus and QboBaseModel's push and
sync behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:22:03 -05:00
rickyandClaude Opus 5.5 48f92f241f Allow unlocking estimates linked to issues
An estimate attached to an issue was read-only, so changing it after a
customer asked for tweaks meant taking it off the work order first.

A new global permission, "Edit estimates linked to issues" (on top of
Write estimates), shows an "Unlock to edit" button on a linked
estimate. After a confirmation the estimate opens for editing, and the
issues stay linked when it's saved. EstimateWriter.save still refuses a
linked estimate unless it was unlocked by a user with the permission.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:08:52 -05:00
rickyandClaude Opus 5.5 22af08cee7 2026.11.25
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:44:30 -05:00
rickyandClaude Opus 5.5 7c87f4f9c5 Fix attachments on customer share links
The attachments patch skipped the login redirect for share-link holders
but left Redmine's read_authorize, find_container and
find_downloadable_attachments in place, which deny the anonymous user.
It relied on an Attachment#visible? patch that never existed, so every
file on a shared issue sent the customer to the login page.

Those checks now pass when the session holds an active share token for
the file's issue (show, download, thumbnail, Download all), and defer
to Redmine otherwise. Files on private notes stay hidden, matching the
share page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:44:30 -05:00
rickyandClaude Opus 5.5 cf5328cb21 2026.11.24
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:23:10 -05:00
rickyandClaude Opus 5.5 c851929e02 Refunds of paid invoices: refund receipt with optional restocking fee
Completed work that's billed and paid in full can be refunded from its
invoice (Refund on the invoice, or Paid invoice on the customer's Refund
page). It makes a QuickBooks Refund Receipt: the invoice lines refunded
(all or part, by quantity or amount) with their products/services and
tax codes, the invoice discount's share, and the restocking fee as a
negative line when it's ticked: the fee rate of the parts refunded, so
labor-only work has none. Paid out of the refund check or card account,
with the check number.

Each refund records the lines it refunded, so a line can't be refunded
for more than it was billed across refunds. Optionally notes the refund
on the invoice's work orders and emails the customer. The refund page,
PDF and email show the lines, tax and fee. Migration 056 adds the
columns to qbo_refunds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:23:10 -05:00
rickyandClaude Opus 5.5 56859d1794 2026.11.23
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:25:23 -05:00
rickyandClaude Opus 5.5 671afa2436 README: sharing an issue with the customer; ticked estimates
Documents share links (what they show, a month's validity, the
purge_customer_tokens task), the Share issues with customers
permission, and ticked estimates filling in New issue and Add
appointment on the customer page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:22:49 -05:00
rickyandClaude Opus 5.5 30c1f5181e Clear out expired customer share links
CustomerToken.purge_expired deletes share links that have expired or
whose issue was deleted. It runs whenever a new link is made, so they
don't pile up, and from rake redmine_qbo:purge_customer_tokens for a
manual or scheduled run. Expired links were only ignored before.

Also drops Issue's belongs_to :customer_token: issues have no such
column, so the association could only raise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:51:25 -05:00
rickyandClaude Opus 5.5 0d143e6eb1 Remove orphaned code
* customers#filter_estimates_by_customer and #filter_invoices_by_customer,
  their routes, permission entries and template: they filled an estimate
  dropdown on the old issue form, which is gone.
* Routes with no action: accounts new/create/show/edit/update/destroy
  (only index, Set default and Sync exist) and customers#destroy.
* Unused methods: AuthHelper#require_user, #allowed_to?, #check_permission;
  CustomersController#address_to_s; CustomerToken#expired? and
  .remove_expired_tokens; QboBaseModel#skip_qbo_push?;
  QboDraft.writable_document?; SyncServiceBase#extract_value.
* CustomersController's before_action helpers are private.
* The unused .autocomplete-meta style and 28 unused translation keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:48:17 -05:00
rickyandClaude Opus 5.5 92f9eb1bc7 Customer page lists: short paid badge, aligned icons, appointment link
* The invoice list's paid badge is short so each invoice stays on one
  line: "Paid", or "Paid +3d" when it was paid in full 3 days after
  its date, with the day on hover. The invoice page keeps the date.
* The estimate and invoice lists are laid out in columns (checkbox,
  number, date, status, actions), so the edit/view icons line up.
* Ticked estimates (and redmine_qbo_vehicles' vehicles) fill in
  redmine_qbo_calendar's Add appointment link (estimate_id,
  vehicle_id) as well as New issue. Estimate checkboxes are only on
  the customer page, where they're used.
* application.js is gone: it only carried the old Google Calendar
  link code, which threw an error when a box was ticked on a vehicle
  page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:39:08 -05:00
rickyandClaude Opus 5.5 40eb6205c4 2026.11.22
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:09:07 -05:00
rickyandClaude Opus 5.5 0c5bac855e Business report: Sales tax section at the bottom
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:09:07 -05:00
rickyandClaude Opus 5.5 663639b8fd 2026.11.21
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:45:29 -05:00
rickyandClaude Opus 5.5 ec4e5f681d Business report: sales tax invoiced and collected
A Sales tax section: tax invoiced (on invoices dated in the period,
accrual) and tax collected (on invoices paid in full in the period,
counted on the day each was paid in full, cash), with counts, a line
chart and a month-by-month table. Only invoices are counted; sales tax
is filed from QuickBooks' Sales Tax Liability report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:45:29 -05:00
rickyandClaude Opus 5.5 a72b0fa73b Business report without sales tax; invoices paid in full; paid dates
Estimates and invoices written are reported without sales tax (new
estimates.tax_amount, filled in by the estimate sync), and a new
Invoices paid in full figure counts invoices on the day they were paid
in full. Payments stay as received, so collected vs. invoiced compares
them with the invoices' totals with tax.

Paid invoices show the day they were paid in full on the customer's
invoice list and the invoice page ("Paid 11/03/2026").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:34:21 -05:00
rickyandClaude Opus 5.5 5b6c1ed2c2 Cache invoices' sales tax and the day they were paid in full
New invoices columns tax_amount and paid_on, filled in by the invoice
sync. An invoice is paid in full on the later of its date and the
dates of the payments and credit memos applied to it (local payments
first; QuickBooks only for ones not synced yet and credit memos), so
reports such as the monthly sales commission don't have to read
invoices from QuickBooks. A full sync fills them in for older
invoices; it now syncs payments before invoices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:34:21 -05:00
rickyandClaude Opus 5.5 4f6f81c87a 2026.11.20
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:43:36 -05:00
rickyandClaude Opus 5.5 9fa199aa98 Refunds for canceled orders and returned parts (SOP-OPS-014)
A Refund page on the customer: the canceled order's estimate fills in
the parts the 30% restocking fee is worked out on. Refunding makes the
fee invoice, pays it from the customer's credit, records the rest as a
Check (company check) or Expense (card refund on the terminal) with the
category Accounts Receivable, applies the credit to it so the balance
comes back to $0.00, and optionally marks the estimate Rejected,
cancels its work orders with the reason as a note and emails the
customer. Each refund has a page with a PDF of it.

New permission: Issue refunds. New settings under Billing » Refunds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:43:36 -05:00
rickyandClaude Opus 5.5 16f9441568 2026.11.19
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:42:08 -05:00
rickyandClaude Opus 5.5 5c48646041 Invoice page hook for plugin actions
:view_qbo_invoice_contextual, { invoice_id:, customer_id:, doc_number: }
in the invoice page's top-right actions, like the estimate page's hook
(used by redmine_qbo_labels' Print label).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:42:08 -05:00
rickyandClaude Opus 5.5 90adb96d54 2026.11.18
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:17:38 -05:00
rickyandClaude Opus 5.5 8a947483db Estimate/invoice numbers on issue PDF; create estimate issues as subtasks
- Issue PDF: show the issue's estimate number and invoice number(s)
- Create issues from estimate: optional parent task. The issues are created as
  its subtasks, take its customer, and start from its project, vehicle and
  custom field values (subtask_field_copier's rules when installed)
- Issue page: shortcut to create the estimate's issues as subtasks of the issue
- Create issues page: editable start and due dates, pre-filled from the
  appointment or the parent task
- Always show plugins' fields (e.g. the vehicle) on the Create issues page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:17:38 -05:00
rickyandClaude Opus 5.5 42461e7899 2026.11.17
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 10:44:25 -05:00
rickyandClaude Opus 5.5 461fa79bc5 Show a saving indicator on estimates and invoices
Clicking Save, Save and send or Save draft shows a spinner in the action bar and locks the buttons until the page reloads, so a second click can't save or send twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 10:44:25 -05:00
ricky 2fb21c34bb 2026.11.16 2026-11-04 15:04:19 -05:00
rickyandClaude Opus 5.5 1c71e3a4c9 Add discounts, unlocking paid invoices and editing payments
- Estimates and invoices take a discount, as a percent of the subtotal or an
  amount, saved as QuickBooks' discount line and taken off before sales tax.
  Duplicated estimates and invoices made from an estimate keep it. The box is
  hidden when discounts are off in QuickBooks.
- A paid invoice can be unlocked for editing after a confirmation. The
  payments stay linked, and the total can't go below what's been paid.
  Unlocking needs the new "Edit partially paid invoices" or "Edit paid
  invoices" permission, checked again when saving.
- Saved payments can be edited: date, method, reference, memo, amount and the
  invoices they pay. Each invoice keeps its amount unless the amount or the
  invoices change. Payments that also apply credit memos stay read-only.
- Locked estimates and invoices are readable again (disabled boxes had faint
  or invisible text, especially in Safari).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:04:19 -05:00
ricky 89f4797bbe 2026.11.15 2026-11-04 12:41:32 -05:00
rickyandClaude Opus 5.5 3bbceacda4 Don't take the sales person from a retired custom field
When an estimate didn't have the company's sales person field, the plugin fell back to
any field named like "Sales Rep", e.g. a retired "Sales Rep old" dropdown, which
QuickBooks returns as its option number. Invoices made from those estimates got "4"
as their sales person. Only the company's field is read now; an estimate without it
has no sales person, so the invoice gets the user who creates it. Matching by name is
left for when QuickBooks' settings can't be read, and never picks a hidden field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:41:32 -05:00
ricky d75dee2866 2026.11.14 2026-11-04 10:33:03 -05:00
rickyandClaude Opus 5.5 c8e2d2d92e Save new estimates and invoices as drafts
A draft is kept in Redmine only, however incomplete, so nothing is in QuickBooks
until it's saved from the editor. QuickBooks can't apply a deposit to an invoice
that's still being written, which made it read-only. Saving to QuickBooks deletes
the draft.

Drafts are listed on the customer's page, on a Drafts page linked from Customers,
and on a new invoice or estimate for a customer who already has one. Anyone with
Write invoices (or Write estimates) can continue or delete invoice (or estimate)
drafts. Adds the qbo_drafts table (migration 052).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:33:03 -05:00
149 changed files with 10184 additions and 494 deletions

No files matched your search

+82 -9
View File
@@ -76,9 +76,21 @@ The plugin provides basic Customer management:
* View and edit Customer information * 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. 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 ## Webhook Support
@@ -97,7 +109,7 @@ Customer records are automatically updated in the local database when changes oc
### Estimates, Invoices and Payments ### 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. * **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. * **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. * **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. * **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. * **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. * **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. * 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. * **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. * **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. * 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 ### 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. * 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. * **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 (with the shop name and mail settings another plugin gives through `:qbo_mail_settings`, e.g. redmine_qbo_reminders', 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
**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): **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. * **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. * **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). * **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 ### QuickBooks custom fields
@@ -185,6 +222,7 @@ Administration → Items lists the QuickBooks product/service list (synced from
1. Navigate to Administration -> Roles and permissions. 1. Navigate to Administration -> Roles and permissions.
2. Assign these global permissions as needed: 2. Assign these global permissions as needed:
* **Write estimates**: create and edit estimates * **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) * **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") * **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 * **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 * **View business reports**: the Business report
* **Write invoices**: create and edit invoices, and import time and estimates into them * **Write invoices**: create and edit invoices, and import time and estimates into them
* **Email invoices**: email invoices to customers * **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) 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. * **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. * **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. * **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. * Item and account counts, the default income account and their syncs are under Synchronization.
3. Writing an estimate 3. Writing an estimate
@@ -226,20 +270,39 @@ Hook| :qbo_additional_entities | Used to add additional entites to be processed
Hook| :qbo_full_sync | Used to add a Class to be called by the QboSyncDispatcher Hook| :qbo_full_sync | Used to add a Class to be called by the QboSyncDispatcher
Hook|:qbo_billing_issue_values, { issues: } | Return `{ field_id => { issue_id => value } }` (QuickBooks custom field id; find yours with `RedmineQboBilling::Company.custom_field_matching(/name/)`) for the work orders behind an invoice, e.g. redmine_qbo_vehicles' VIN and mileage. They're given to the editor with imported time and estimates (the `qbo:imported` event) and put on redmine_qbo_lineitems' estimates Hook|:qbo_billing_issue_values, { issues: } | Return `{ field_id => { issue_id => value } }` (QuickBooks custom field id; find yours with `RedmineQboBilling::Company.custom_field_matching(/name/)`) for the work orders behind an invoice, e.g. redmine_qbo_vehicles' VIN and mileage. They're given to the editor with imported time and estimates (the `qbo:imported` event) and put on redmine_qbo_lineitems' estimates
Hook|:qbo_billing_validate, { document:, form:, issues: } | Return an error message (or several) to stop an estimate or invoice from saving, e.g. redmine_qbo_vehicles: one vehicle per invoice Hook|:qbo_billing_validate, { document:, form:, issues: } | Return an error message (or several) to stop an estimate or invoice from saving, e.g. redmine_qbo_vehicles: one vehicle per invoice
Hook|:qbo_billing_issue_defaults, { estimate:, params: } | Return `start_date`, `due_date`, `assignee`, `project`, `description`, `return_path`, `return_label`, plus any values your own fields need (e.g. redmine_qbo_calendar's `vehicle_id`), for issues created from an estimate (redmine_qbo_calendar, when opened from an appointment) Hook|:qbo_billing_issue_defaults, { estimate:, params:, parent_issue: } | Return `start_date`, `due_date`, `assignee`, `project`, `description`, `return_path`, `return_label`, plus any values your own fields need, for issues created from an estimate (redmine_qbo_calendar, when opened from an appointment; redmine_qbo_vehicles: the parent's or appointment's vehicle). Every plugin's hash is merged
Hook|:qbo_billing_build_issue, { issue:, estimate:, defaults: } | Set your plugin's own fields on each issue created from an estimate, before it's saved (redmine_qbo_vehicles sets the vehicle: the one in `defaults`, or the customer's vehicle whose VIN is on the estimate) Hook|:qbo_billing_build_issue, { issue:, estimate:, defaults:, parent: } | Set your plugin's own fields on each issue created from an estimate, before it's saved; `parent` is the parent issue, if any (redmine_qbo_vehicles sets the vehicle: the one in `defaults`, the customer's vehicle whose VIN is on the estimate, or the parent's)
View|:view_qbo_estimate_issues_form, { estimate:, defaults:, project: } | Draw your plugin's fields on the Create issues from estimate page, applied to every issue. Name them `issue_plugin_fields[name]`; the posted values reach `:qbo_billing_build_issue` in `defaults` (redmine_qbo_vehicles: the Vehicle, preselected from the estimate's VIN) View|:view_qbo_estimate_issues_form, { estimate:, defaults:, project: } | Draw your plugin's fields on the Create issues from estimate page, applied to every issue. Name them `issue_plugin_fields[name]`; the posted values reach `:qbo_billing_build_issue` in `defaults` (redmine_qbo_vehicles: the Vehicle, preselected from the estimate's VIN)
Hook|:qbo_billing_issues_created, { estimate:, issues:, params: } | Called after issues are created from an estimate Hook|:qbo_billing_issues_created, { estimate:, issues:, params: } | Called after issues are created from an estimate
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_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) 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|: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-ticked-field="field"`, links with `data-ticked-params` on the customer page | Ticking a box adds its value to every link with `data-ticked-params`, named by that format: `issue[%s]` for the New issue link, `%s` for a plain param (e.g. redmine_qbo_calendar's Add appointment link). One box per field (redmine_qbo's estimates: `estimate_id`, redmine_qbo_vehicles' vehicles: `vehicle_id`)
Hook|:qbo_billing_issue_carry_params | Return names of request params the Create issues from estimate page keeps through its form (redmine_qbo_calendar: `appointment_id`)
Hook|:qbo_mail_settings | Return any of `shop_name`, `from`, `reply_to` and `delivery` (options for ActionMailer's `mail()`, e.g. an SMTP server) for customer emails such as refund summaries (redmine_qbo_reminders: its shop name and email settings). Blank ones fall back to Redmine's settings
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_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)
Other plugins create estimates with `RedmineQboBilling::EstimateWriter.create_estimate(customer:, lines:, private_note:, custom_fields:, user:)`; `custom_fields` is `{ field_id => value }`, and each line is a hash of `description`, `item_id`, `quantity`, `rate` and `taxable`. Other plugins create estimates with `RedmineQboBilling::EstimateWriter.create_estimate(customer:, lines:, private_note:, custom_fields:, user:)`; `custom_fields` is `{ field_id => value }`, and each line is a hash of `description`, `item_id`, `quantity`, `rate` and `taxable`.
--- ---
# Screenshots
All names and figures are made up.
<table>
<tr><td width="50%"><img src="Screenshots/issue.png" alt="An issue with its customer, estimate and invoice, and Bill Time / Share"><br><sub>An issue with its customer, estimate and invoice, and Bill Time / Share</sub></td><td width="50%"><img src="Screenshots/issue_form.png" alt="The customer and estimate on the issue form"><br><sub>The customer and estimate on the issue form</sub></td></tr>
<tr><td width="50%"><img src="Screenshots/issue_list.png" alt="The Customer column in issue lists"><br><sub>The Customer column in issue lists</sub></td><td width="50%"><img src="Screenshots/customers.png" alt="Customers, searchable by name or phone"><br><sub>Customers, searchable by name or phone</sub></td></tr>
<tr><td width="50%"><img src="Screenshots/customer.png" alt="A customer: QuickBooks details, estimates and invoices"><br><sub>A customer: QuickBooks details, estimates and invoices</sub></td><td width="50%"><img src="Screenshots/estimate_editor.png" alt="Writing an estimate"><br><sub>Writing an estimate</sub></td></tr>
<tr><td width="50%"><img src="Screenshots/estimate_linked_unlock.png" alt="An estimate linked to an issue, with Unlock to edit"><br><sub>An estimate linked to an issue, with Unlock to edit</sub></td><td width="50%"><img src="Screenshots/issues_from_estimate.png" alt="Creating issues from an estimate"><br><sub>Creating issues from an estimate</sub></td></tr>
<tr><td width="50%"><img src="Screenshots/invoice_editor.png" alt="Writing an invoice"><br><sub>Writing an invoice</sub></td><td width="50%"><img src="Screenshots/receive_payment.png" alt="Receiving a payment"><br><sub>Receiving a payment</sub></td></tr>
<tr><td width="50%"><img src="Screenshots/payment.png" alt="A payment and the invoices it paid"><br><sub>A payment and the invoices it paid</sub></td><td width="50%"><img src="Screenshots/business_report.png" alt="The business report"><br><sub>The business report</sub></td></tr>
<tr><td width="50%"><img src="Screenshots/plugin_config.png" alt="Plugin settings"><br><sub>Plugin settings</sub></td><td width="50%"><img src="Screenshots/user_edit.png" alt="Linking a user to a QuickBooks employee"><br><sub>Linking a user to a QuickBooks employee</sub></td></tr>
</table>
---
# Prerequisites # Prerequisites
Before installing the plugin: Before installing the plugin:
@@ -358,6 +421,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 # Troubleshooting
### Time Activities Not Created ### Time Activities Not Created
Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 724 KiB

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 520 KiB

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 269 KiB

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 539 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

@@ -0,0 +1,75 @@
#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.
# Drafts on the new estimate and new invoice editors (see QboDraft). "Save draft" keeps what's filled in, even
# if it isn't complete, and reopens it (new?draft_id=). Saving to QuickBooks deletes the draft.
module QboDraftHandling
extend ActiveSupport::Concern
private
# The draft named by draft_id (in the URL, or the editor's hidden field), if the user may open it
def find_draft(document)
@draft = (QboDraft.visible.for_document(document).find_by(id: params[:draft_id]) if params[:draft_id].present?)
end
# The editor form filled in from a draft, with the details the editor shows but doesn't post
def form_from_draft(draft)
form = draft.form
customer = Customer.find_by(id: form.customer_id) if form.customer_id.present?
if customer
form.billing_address = RedmineQboBilling::EstimateWriter.customer_address(customer)
form.customer_name = customer.name if form.customer_name.blank?
end
# Invoices keep the sales person shown on the editor (e.g. from an estimate); estimates are always the user's
form.sales_person = (draft.invoice? && draft.fields['sales_person'].presence) || User.current.name
form.lines = form.lines.reject(&:blank?)
form.lines += Array.new([2 - form.lines.size, 1].max) { RedmineQboBilling::EstimateForm::Line.new(quantity: '', taxable: true) }
form
end
# Saves what's on the editor as a draft (no checks: a draft can be missing anything) and reopens it
def save_draft(document, fields)
draft = @draft || QboDraft.new(document: document)
fields = fields.to_h.stringify_keys
draft.fields = fields
draft.customer_id = (Customer.where(id: fields['customer_id']).pick(:id) if fields['customer_id'].present?)
draft.user = User.current
draft.save!
flash[:notice] = l(:notice_qbo_draft_saved)
redirect_to draft_editor_path(draft)
end
# Saved to QuickBooks: the draft isn't needed any more
def discard_draft
@draft&.destroy
@draft = nil
end
# A new document for a customer who already has drafts of it: the editor points them out
def load_customer_drafts(document, customer_id)
@customer_drafts =
if @draft.nil? && customer_id.present?
QboDraft.visible.for_document(document).where(customer_id: customer_id).newest_first.to_a
else
[]
end
end
# A draft_id that's gone (e.g. finished or deleted by someone else): say so and list the drafts
def draft_missing
flash[:error] = l(:error_qbo_draft_not_found)
redirect_to qbo_drafts_path
end
def draft_editor_path(draft)
draft.invoice? ? new_qbo_invoice_path(draft_id: draft.id) : new_qbo_estimate_path(draft_id: draft.id)
end
end
+40 -79
View File
@@ -33,36 +33,6 @@ class CustomersController < ApplicationController
before_action :require_admin, only: :sync before_action :require_admin, only: :sync
skip_before_action :verify_authenticity_token, :check_if_login_required, only: [:view] 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 # Used for autocomplete forms. Fuzzy matching (nicknames, typos, word order, phone digits) helps
# staff spot an existing customer before creating a duplicate. See CustomerSearchService. # staff spot an existing customer before creating a duplicate. See CustomerSearchService.
def autocomplete def autocomplete
@@ -77,27 +47,16 @@ class CustomersController < ApplicationController
def create def create
@customer = Customer.new(allowed_params) @customer = Customer.new(allowed_params)
respond_to do |format| if @customer.save
if @customer.save log "Customer ##{@customer.id} created successfully."
log "Customer ##{@customer.id} created successfully." redirect_to @customer, notice: l(:notice_successful_create)
format.html { redirect_to @customer, notice: l(:notice_successful_create) } else
format.json { render json: { id: @customer.id, name: @customer.name }, status: :created } render :new, status: :unprocessable_entity
else
format.html { render :new }
format.json { render json: { errors: @customer.errors.full_messages }, status: :unprocessable_entity }
end
end end
rescue => e rescue => e
log "Failed to create customer: #{e.message}" log "Failed to create customer: #{e.message}"
respond_to do |format| flash[:error] = e.message
format.html { redirect_to new_customer_path
flash[:error] = e.message
redirect_to new_customer_path
}
format.json {
render json: { errors: [e.message] }, status: :internal_server_error
}
end
end end
def edit def edit
@@ -109,14 +68,6 @@ class CustomersController < ApplicationController
render_404 render_404
end 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) # Most matches a search lists (best first)
SEARCH_LIMIT = 200 SEARCH_LIMIT = 200
@@ -146,29 +97,6 @@ class CustomersController < ApplicationController
@issue_counts = Issue.where(customer_id: @customers.map(&:id)).group(:customer_id).count @issue_counts = Issue.where(customer_id: @customers.map(&:id)).group(:customer_id).count
end 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 def new
@customer = Customer.new @customer = Customer.new
@@ -253,6 +181,39 @@ class CustomersController < ApplicationController
render_403 render_403
end 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 def view_customer
global_check_permission(:view_customers) global_check_permission(:view_customers)
end end
+12 -1
View File
@@ -10,7 +10,8 @@
class EstimatesController < ApplicationController class EstimatesController < ApplicationController
include AuthHelper 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. # 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] skip_before_action :check_if_login_required, only: [:show, :doc]
before_action :require_login_or_customer_token, 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) # 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_customer_estimate if customer_token_only?
return load_issue_estimate unless RedmineQboBilling.estimate_viewer?
@estimate = find_estimate || sync_and_find_estimate @estimate = find_estimate || sync_and_find_estimate
@@ -65,6 +67,15 @@ class EstimatesController < ApplicationController
@estimate = estimate @estimate = estimate
end 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. # Attempts to find the estimate locally by ID or doc number.
def find_estimate def find_estimate
return Estimate.find_by(doc_number: params[:search]) if params[:search].present? return Estimate.find_by(doc_number: params[:search]) if params[:search].present?
+10 -1
View File
@@ -10,11 +10,13 @@
class InvoicesController < ApplicationController class InvoicesController < ApplicationController
include AuthHelper 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. # 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 skip_before_action :check_if_login_required, only: :show
before_action :require_login_or_customer_token, only: :show before_action :require_login_or_customer_token, only: :show
before_action :authorize_customer_invoices, only: :show before_action :authorize_customer_invoices, only: :show
before_action :authorize_user_invoices, only: :show
# Syncing is admin-only # Syncing is admin-only
before_action :require_admin, only: :sync before_action :require_admin, only: :sync
@@ -51,6 +53,13 @@ class InvoicesController < ApplicationController
render_403 if invoice_ids.empty? || (invoice_ids - allowed).any? render_403 if invoice_ids.empty? || (invoice_ids - allowed).any?
end 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. # Logs messages with a consistent prefix for easier debugging.
def log(msg) def log(msg)
Rails.logger.info "[InvoiceController] #{msg}" Rails.logger.info "[InvoiceController] #{msg}"
+31
View File
@@ -0,0 +1,31 @@
#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.
# Estimate and invoice drafts (QboDraft): all of them, and deleting one. Drafts are continued on the new
# estimate/invoice editor (new?draft_id=). Users see the drafts of the documents they may write.
class QboDraftsController < ApplicationController
before_action :authorize_global
def index
@drafts = QboDraft.visible.includes(:customer, :user).newest_first.to_a
end
def destroy
draft = QboDraft.visible.find_by(id: params[:id])
if draft
draft.destroy
flash[:notice] = l(:notice_qbo_draft_deleted)
else
flash[:error] = l(:error_qbo_draft_not_found)
end
redirect_back_or_default qbo_drafts_path
end
end
+104 -17
View File
@@ -10,6 +10,7 @@
# Writes, edits and emails QuickBooks estimates from Redmine, on a page laid out like QuickBooks' estimate screen. # Writes, edits and emails QuickBooks estimates from Redmine, on a page laid out like QuickBooks' estimate screen.
class QboEstimatesController < ApplicationController class QboEstimatesController < ApplicationController
include QboDraftHandling
before_action :require_admin, only: :refresh_company before_action :require_admin, only: :refresh_company
before_action :authorize_global, except: :refresh_company before_action :authorize_global, except: :refresh_company
@@ -25,34 +26,44 @@ class QboEstimatesController < ApplicationController
# redmine_qbo raises plain errors when QuickBooks isn't connected or the token can't be refreshed # redmine_qbo raises plain errors when QuickBooks isn't connected or the token can't be refreshed
RuntimeError].freeze RuntimeError].freeze
# A blank estimate, or a copy of another one (?duplicate=<estimate id>) # A blank estimate, a copy of another one (?duplicate=<estimate id>), or a draft (?draft_id=, see QboDraft)
def new def new
if params[:duplicate].present? if params[:draft_id].present?
return draft_missing unless find_draft('estimate')
@form = form_from_draft(@draft)
elsif params[:duplicate].present?
@form = RedmineQboBilling::EstimateWriter.duplicate_form(params[:duplicate], user: User.current) @form = RedmineQboBilling::EstimateWriter.duplicate_form(params[:duplicate], user: User.current)
else else
customer = Customer.find_by(id: params[:customer_id]) if params[:customer_id].present? customer = Customer.find_by(id: params[:customer_id]) if params[:customer_id].present?
@form = RedmineQboBilling::EstimateWriter.new_form(customer: customer, user: User.current) @form = RedmineQboBilling::EstimateWriter.new_form(customer: customer, user: User.current)
end end
load_customer_drafts('estimate', @form.customer_id)
rescue *QBO_ERRORS => e rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e) flash[:error] = qbo_message(e)
redirect_back_or_default home_path redirect_back_or_default home_path
end end
def create def create
find_draft('estimate')
return save_draft('estimate', estimate_params) if params[:save_draft].present?
@form = RedmineQboBilling::EstimateForm.from_params(estimate_params) @form = RedmineQboBilling::EstimateForm.from_params(estimate_params)
# Shown again if the save fails; the sales person is always the user creating the estimate # Shown again if the save fails; the sales person is always the user creating the estimate
@form.sales_person = User.current.name @form.sales_person = User.current.name
return show_invalid(:new) unless @form.valid? return show_invalid(:new) unless @form.valid?
saved = RedmineQboBilling::EstimateWriter.save(@form, user: User.current) saved = RedmineQboBilling::EstimateWriter.save(@form, user: User.current)
discard_draft
finish_save(saved, l(:notice_estimate_saved_in_quickbooks, number: saved.doc_number)) finish_save(saved, l(:notice_estimate_saved_in_quickbooks, number: saved.doc_number))
rescue *QBO_ERRORS => e rescue *QBO_ERRORS => e
show_error(e, :new) show_error(e, :new)
end end
# ?unlock=1 opens an estimate linked to an issue for editing anyway (after the editor's confirmation)
def edit def edit
@form = RedmineQboBilling::EstimateWriter.load(params[:id]) @form = RedmineQboBilling::EstimateWriter.load(params[:id])
@linked_issues = RedmineQboBilling::EstimateWriter.linked_issues(@form.id).visible.to_a @linked_issues = RedmineQboBilling::EstimateWriter.linked_issues(@form.id).visible.to_a
unlock_form if unlock?
rescue *QBO_ERRORS => e rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e) flash[:error] = qbo_message(e)
redirect_back_or_default home_path redirect_back_or_default home_path
@@ -61,9 +72,10 @@ class QboEstimatesController < ApplicationController
def update def update
@form = RedmineQboBilling::EstimateForm.from_params(estimate_params, id: params[:id]) @form = RedmineQboBilling::EstimateForm.from_params(estimate_params, id: params[:id])
@form.sales_person = params.dig(:estimate, :sales_person).to_s @form.sales_person = params.dig(:estimate, :sales_person).to_s
unlock_form if unlock?
return show_invalid(:edit) unless @form.valid? 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)) finish_save(saved, l(:notice_estimate_saved_in_quickbooks, number: saved.doc_number))
rescue RedmineQboBilling::EstimateWriter::Conflict => e rescue RedmineQboBilling::EstimateWriter::Conflict => e
@conflict = true @conflict = true
@@ -83,8 +95,8 @@ class QboEstimatesController < ApplicationController
end end
# Preview of the issues that can be created from the estimate's labor lines. Each line gets a tracker and # Preview of the issues that can be created from the estimate's labor lines. Each line gets a tracker and
# (optionally) a template before anything is created. Opened from an appointment, the appointment's dates, # (optionally) a template before anything is created. Plugins fill in defaults through
# technician and vehicle are used (redmine_qbo_calendar's :qbo_billing_issue_defaults). # :qbo_billing_issue_defaults (e.g. redmine_qbo_calendar: the appointment's dates and technician).
def issues_preview def issues_preview
end end
@@ -92,7 +104,8 @@ class QboEstimatesController < ApplicationController
def create_issues def create_issues
@rows = params[:lines].respond_to?(:to_unsafe_h) ? params[:lines].to_unsafe_h : {} @rows = params[:lines].respond_to?(:to_unsafe_h) ? params[:lines].to_unsafe_h : {}
@custom_field_values = submitted_custom_field_values @custom_field_values = submitted_custom_field_values
created = @builder.create_issues(project: @target_project, rows: @rows, custom_field_values: @custom_field_values) # A parent was entered but can't be used: create nothing rather than top-level issues
created = @parent_issue_error ? [] : @builder.create_issues(project: @target_project, rows: @rows, custom_field_values: @custom_field_values)
if created.any? if created.any?
Redmine::Hook.call_hook(:qbo_billing_issues_created, { estimate: @estimate, issues: created, params: params }) Redmine::Hook.call_hook(:qbo_billing_issues_created, { estimate: @estimate, issues: created, params: params })
@@ -165,39 +178,98 @@ class QboEstimatesController < ApplicationController
end end
return render_404 unless @estimate return render_404 unless @estimate
# Values plugins' fields posted with the form (e.g. redmine_qbo_vehicles' vehicle) override their defaults load_parent_issue
@defaults = issue_defaults.merge(submitted_plugin_fields)
@builder = RedmineQboBilling::EstimateIssueBuilder.new(@estimate, defaults: @defaults) @defaults = build_defaults
@return_path = @defaults[:return_path].presence || edit_qbo_estimate_path(@estimate.id) @return_path = @defaults[:return_path].presence || edit_qbo_estimate_path(@estimate.id)
@return_label = @defaults[:return_label].presence || "#{l(:label_estimate)} ##{@estimate.doc_number}" @return_label = @defaults[:return_label].presence || "#{l(:label_estimate)} ##{@estimate.doc_number}"
@available_projects = Project.allowed_to(User.current, :add_issues).sorted.to_a @available_projects = Project.allowed_to(User.current, :add_issues).sorted.to_a
# A project chosen on the page wins, then the one from another plugin (e.g. the appointment's), then the # A project chosen on the page wins, then the parent issue's, then the one from another plugin (e.g. the
# default project from the settings, then the first project the user can add issues to # appointment's), then the default project from the settings, then the first project the user can add issues to
chosen = @available_projects.detect { |p| p.id == params[:project_id].to_i } if params[:project_id].present? chosen = @available_projects.detect { |p| p.id == params[:project_id].to_i } if params[:project_id].present?
from_parent = @parent_issue.project if @parent_issue && @available_projects.include?(@parent_issue.project)
from_hook = @defaults[:project] if @available_projects.include?(@defaults[:project]) from_hook = @defaults[:project] if @available_projects.include?(@defaults[:project])
default_project = @available_projects.detect { |p| p.id == RedmineQboBilling::EstimateIssueBuilder.default_project_id } default_project = @available_projects.detect { |p| p.id == RedmineQboBilling::EstimateIssueBuilder.default_project_id }
@target_project = chosen || from_hook || default_project || @available_projects.first @target_project = chosen || from_parent || from_hook || default_project || @available_projects.first
return deny_access unless @target_project return deny_access unless @target_project
# Subtasks need the "Manage subtasks" permission in the project they're created in
@can_add_subtasks = User.current.allowed_to?(:manage_subtasks, @target_project)
if @parent_issue && !@can_add_subtasks
@parent_issue_error = l(:error_estimate_parent_not_allowed, project: @target_project.name)
@parent_issue = nil
@defaults = build_defaults
end
@builder = RedmineQboBilling::EstimateIssueBuilder.new(@estimate, defaults: @defaults, parent: @parent_issue)
@trackers = Issue.allowed_target_trackers(@target_project, User.current).to_a @trackers = Issue.allowed_target_trackers(@target_project, User.current).to_a
@default_tracker = @trackers.detect { |t| t.id == RedmineQboBilling::EstimateIssueBuilder.default_tracker_id } || @trackers.first @default_tracker = @trackers.detect { |t| t.id == RedmineQboBilling::EstimateIssueBuilder.default_tracker_id } || @trackers.first
@templates = RedmineQboBilling::IssueTemplateSupport.templates_for(@target_project) @templates = RedmineQboBilling::IssueTemplateSupport.templates_for(@target_project)
@field_set = RedmineQboBilling::IssueFieldSet.new(project: @target_project, trackers: @trackers) # With a parent issue, the shared fields start out with the parent's values
@field_set = RedmineQboBilling::IssueFieldSet.new(project: @target_project, trackers: @trackers,
values: parent_custom_field_values)
@rows ||= {} @rows ||= {}
rescue *QBO_ERRORS => e rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e) flash[:error] = qbo_message(e)
redirect_back_or_default home_path redirect_back_or_default home_path
end end
# The first non-empty hash a plugin returns for :qbo_billing_issue_defaults # The optional parent issue (parent_issue_id, "#123" or "123"): the new issues become its subtasks.
# Only an issue the user can see; an unknown one is reported and nothing is created.
def load_parent_issue
@parent_issue_id = params[:parent_issue_id].to_s.delete('#').strip
return if @parent_issue_id.blank?
@parent_issue = Issue.visible.find_by(id: @parent_issue_id.to_i) if @parent_issue_id.match?(/\A\d+\z/)
@parent_issue_error = l(:error_estimate_parent_not_found, id: @parent_issue_id) unless @parent_issue
end
# What the new issues start from:
# - dates: another plugin's (e.g. the appointment's), else the parent issue's
# - plugins' own fields: what they return for :qbo_billing_issue_defaults (they're given the parent issue)
# Values posted with the form (the dates, plugins' fields) win.
def build_defaults
parent_dates = @parent_issue ? { start_date: @parent_issue.start_date, due_date: @parent_issue.due_date }.compact : {}
parent_dates.merge(issue_defaults.compact).merge(submitted_plugin_fields).merge(submitted_dates)
end
# The Start date / Due date entered on the page, only when the form was posted. A blank one means no date.
def submitted_dates
return {} unless request.post? && params[:issue_dates].respond_to?(:to_unsafe_h)
values = params[:issue_dates].to_unsafe_h
%w[start_date due_date].each_with_object({}) do |key, dates|
dates[key.to_sym] = parse_date(values[key]) if values.key?(key)
end
end
def parse_date(value)
Date.iso8601(value.to_s.strip) if value.present?
rescue ArgumentError
nil
end
# The parent issue's custom field values the user can see, to start the shared fields from: { id => value }
def parent_custom_field_values
return {} unless @parent_issue
@parent_issue.visible_custom_field_values.each_with_object({}) do |custom_value, values|
next if Array(custom_value.value).all?(&:blank?)
values[custom_value.custom_field_id.to_s] = custom_value.value
end
end
# What plugins return for :qbo_billing_issue_defaults, merged (each fills in its own keys)
def issue_defaults def issue_defaults
results = Redmine::Hook.call_hook(:qbo_billing_issue_defaults, { estimate: @estimate, params: params }) results = Redmine::Hook.call_hook(:qbo_billing_issue_defaults,
(results.detect { |r| r.is_a?(Hash) && r.any? } || {}).symbolize_keys { estimate: @estimate, params: params, parent_issue: @parent_issue })
results.select { |r| r.is_a?(Hash) }.reduce({}) { |merged, r| merged.merge(r.symbolize_keys) }
end end
# Plugins' own fields on the preview form (issue_plugin_fields[...], drawn by :view_qbo_estimate_issues_form), # Plugins' own fields on the preview form (issue_plugin_fields[...], drawn by :view_qbo_estimate_issues_form),
# only when the form was posted: { vehicle_id: "5" } # only when the form was posted, e.g. { some_plugin_field: "5" }
def submitted_plugin_fields def submitted_plugin_fields
return {} unless request.post? return {} unless request.post?
@@ -220,6 +292,21 @@ class QboEstimatesController < ApplicationController
) )
end 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? def save_and_send?
params[:save_and_send].present? params[:save_and_send].present?
end end
+34 -2
View File
@@ -11,6 +11,7 @@
# Writes, edits and emails QuickBooks invoices from Redmine, with the same editor as estimates, plus importing # Writes, edits and emails QuickBooks invoices from Redmine, with the same editor as estimates, plus importing
# billable time and open estimates. The customer and product searches are QboEstimatesController's. # billable time and open estimates. The customer and product searches are QboEstimatesController's.
class QboInvoicesController < ApplicationController class QboInvoicesController < ApplicationController
include QboDraftHandling
before_action :authorize_global before_action :authorize_global
before_action :require_sender_for_save_and_send, only: [:create, :update] before_action :require_sender_for_save_and_send, only: [:create, :update]
@@ -18,8 +19,15 @@ class QboInvoicesController < ApplicationController
QBO_ERRORS = QboEstimatesController::QBO_ERRORS QBO_ERRORS = QboEstimatesController::QBO_ERRORS
# A blank invoice, or one made from an estimate (?estimate_id=<estimate id>) # A blank invoice, one made from an estimate (?estimate_id=<estimate id>), or a draft (?draft_id=, see
# QboDraft). A draft stays in Redmine, so QuickBooks can't apply a deposit to it while it's being written.
def new def new
if params[:draft_id].present?
return draft_missing unless find_draft('invoice')
@form = form_from_draft(@draft)
return
end
@form = @form =
if params[:estimate_id].present? if params[:estimate_id].present?
RedmineQboBilling::InvoiceWriter.from_estimate(params[:estimate_id], user: User.current) RedmineQboBilling::InvoiceWriter.from_estimate(params[:estimate_id], user: User.current)
@@ -27,25 +35,33 @@ class QboInvoicesController < ApplicationController
customer = Customer.find_by(id: params[:customer_id]) if params[:customer_id].present? customer = Customer.find_by(id: params[:customer_id]) if params[:customer_id].present?
RedmineQboBilling::InvoiceWriter.new_form(customer: customer, user: User.current) RedmineQboBilling::InvoiceWriter.new_form(customer: customer, user: User.current)
end end
load_customer_drafts('invoice', @form.customer_id)
rescue *QBO_ERRORS => e rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e) flash[:error] = qbo_message(e)
redirect_back_or_default home_path redirect_back_or_default home_path
end end
def create def create
find_draft('invoice')
# The sales person shown on the editor is kept with the draft
return save_draft('invoice', invoice_params.to_h.merge('sales_person' => params.dig(:estimate, :sales_person).to_s)) if params[:save_draft].present?
@form = RedmineQboBilling::EstimateForm.from_params(invoice_params, document: 'invoice') @form = RedmineQboBilling::EstimateForm.from_params(invoice_params, document: 'invoice')
# Display only (e.g. the estimate's sales person); InvoiceWriter.save works out what's saved # Display only (e.g. the estimate's sales person); InvoiceWriter.save works out what's saved
@form.sales_person = params.dig(:estimate, :sales_person).presence || User.current.name @form.sales_person = params.dig(:estimate, :sales_person).presence || User.current.name
return show_invalid(:new) unless @form.valid? return show_invalid(:new) unless @form.valid?
saved = RedmineQboBilling::InvoiceWriter.save(@form, user: User.current) saved = RedmineQboBilling::InvoiceWriter.save(@form, user: User.current)
discard_draft
finish_save(saved, l(:notice_invoice_saved_in_quickbooks, number: saved.doc_number)) finish_save(saved, l(:notice_invoice_saved_in_quickbooks, number: saved.doc_number))
rescue *QBO_ERRORS => e rescue *QBO_ERRORS => e
show_error(e, :new) show_error(e, :new)
end end
# ?unlock=1 opens a paid invoice for editing anyway (after the editor's confirmation)
def edit def edit
@form = RedmineQboBilling::InvoiceWriter.load(params[:id]) @form = RedmineQboBilling::InvoiceWriter.load(params[:id])
unlock_form if unlock?
rescue *QBO_ERRORS => e rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e) flash[:error] = qbo_message(e)
redirect_back_or_default home_path redirect_back_or_default home_path
@@ -54,9 +70,10 @@ class QboInvoicesController < ApplicationController
def update def update
@form = RedmineQboBilling::EstimateForm.from_params(invoice_params, id: params[:id], document: 'invoice') @form = RedmineQboBilling::EstimateForm.from_params(invoice_params, id: params[:id], document: 'invoice')
@form.sales_person = params.dig(:estimate, :sales_person).to_s @form.sales_person = params.dig(:estimate, :sales_person).to_s
unlock_form if unlock?
return show_invalid(:edit) unless @form.valid? return show_invalid(:edit) unless @form.valid?
saved = RedmineQboBilling::InvoiceWriter.save(@form, user: User.current) saved = RedmineQboBilling::InvoiceWriter.save(@form, user: User.current, unlock: unlock?)
finish_save(saved, l(:notice_invoice_saved_in_quickbooks, number: saved.doc_number)) finish_save(saved, l(:notice_invoice_saved_in_quickbooks, number: saved.doc_number))
rescue RedmineQboBilling::InvoiceWriter::Conflict => e rescue RedmineQboBilling::InvoiceWriter::Conflict => e
@conflict = true @conflict = true
@@ -99,6 +116,21 @@ class QboInvoicesController < ApplicationController
) )
end end
def unlock?
params[:unlock].to_s == '1'
end
# Shows a paid invoice editable, with the amount paid on it (posted back with the form when saving), for
# users allowed to edit it (paid off or partly paid). InvoiceWriter.save checks again against QuickBooks.
def unlock_form
@form.amount_paid ||= RedmineQboBilling::EstimateForm.decimal(params.dig(:estimate, :amount_paid))
return unless @form.locked == :paid || @form.locked.nil?
return unless RedmineQboBilling.paid_invoice_editor?(@form.fully_paid?)
@form.locked = nil
@form.unlocked = true
end
def save_and_send? def save_and_send?
params[:save_and_send].present? params[:save_and_send].present?
end end
+32 -5
View File
@@ -9,8 +9,8 @@
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Receives customer payments in QuickBooks: payment type and amount, applied to open invoices oldest first, or # Receives customer payments in QuickBooks: payment type and amount, applied to open invoices oldest first, or
# saved as a deposit. A saved payment can be printed (QuickBooks' payment PDF). A customer's payments are # saved as a deposit. A saved payment can be edited and printed (QuickBooks' payment PDF). A customer's
# listed on their payments page. # payments are listed on their payments page.
class QboPaymentsController < ApplicationController class QboPaymentsController < ApplicationController
before_action :authorize_global, except: :sync before_action :authorize_global, except: :sync
@@ -56,6 +56,31 @@ class QboPaymentsController < ApplicationController
show_form show_form
end end
def edit
@form = RedmineQboBilling::PaymentWriter.load_form(params[:id])
load_choices
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
end
def update
@form = RedmineQboBilling::PaymentForm.from_params(payment_params, id: params[:id])
return show_form unless @form.valid?
payment = RedmineQboBilling::PaymentWriter.save(@form)
flash[:notice] = l(:notice_payment_updated, amount: view_context.number_to_currency(payment.total))
redirect_to qbo_payment_path(payment.id)
rescue RedmineQboBilling::PaymentWriter::Conflict => e
@conflict = true
@form.errors.add(:base, qbo_message(e))
show_form
rescue *QBO_ERRORS => e
logger.warn "[RedmineQboBilling] #{e.class}: #{qbo_message(e)}"
@form.errors.add(:base, qbo_message(e))
show_form
end
def show def show
@payment = RedmineQboBilling::PaymentWriter.load(params[:id]) @payment = RedmineQboBilling::PaymentWriter.load(params[:id])
@customer = Customer.find_by(id: @payment.customer_ref&.value) @customer = Customer.find_by(id: @payment.customer_ref&.value)
@@ -86,13 +111,15 @@ class QboPaymentsController < ApplicationController
private private
def payment_params def payment_params
params.require(:payment).permit(*RedmineQboBilling::PaymentForm::ATTRIBUTES, invoice_ids: []) params.require(:payment).permit(*RedmineQboBilling::PaymentForm::ATTRIBUTES, :sync_token, invoice_ids: [])
end end
def load_choices def load_choices
@payment_methods = RedmineQboBilling::PaymentWriter.payment_methods @payment_methods = RedmineQboBilling::PaymentWriter.payment_methods
customer = Customer.find_by(id: @form.customer_id) if @form.customer_id.present? customer = Customer.find_by(id: @form.customer_id) if @form.customer_id.present?
@open_invoices = customer ? RedmineQboBilling::PaymentWriter.open_invoices(customer) : [] # Editing: the invoices this payment pays count as open (by what it paid on them)
payment = RedmineQboBilling::PaymentWriter.load(@form.id) if @form.persisted?
@open_invoices = customer ? RedmineQboBilling::PaymentWriter.open_invoices(customer, payment: payment) : []
rescue *QBO_ERRORS => e rescue *QBO_ERRORS => e
@open_invoices = [] @open_invoices = []
flash.now[:error] = qbo_message(e) flash.now[:error] = qbo_message(e)
@@ -100,7 +127,7 @@ class QboPaymentsController < ApplicationController
def show_form def show_form
load_choices load_choices
render :new, status: :unprocessable_entity render(@form.persisted? ? :edit : :new, status: :unprocessable_entity)
end end
def qbo_message(error) def qbo_message(error)
+178
View File
@@ -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
View File
@@ -31,26 +31,19 @@ module AuthHelper
require_login require_login
end end
# Kept for plugins that still call it (e.g. redmine_qbo_vehicles): requires a logged-in user. # A logged-in user may open the estimate's PDF with a billing permission (RedmineQboBilling.estimate_viewer?),
# The old version effectively never ran; share-link customers use require_login_or_customer_token. # or when it's attached to an issue they can see (the issue page links to it)
def require_user def estimate_pdf_allowed?(estimate)
return true if User.current.logged? RedmineQboBilling.estimate_viewer? || Issue.visible.where(estimate_id: estimate.id).exists?
require_login
end end
def allowed_to?(action) # The same for invoices: every one of them must be attached to an issue the user can see
return false if User.current.nil? def invoice_pdfs_allowed?(invoice_ids)
project = Project.find_by(id: params[:project_id]) return true if RedmineQboBilling.invoice_viewer?
return false if project.nil?
User.current.allowed_to?(action, project)
end
def check_permission(permission) ids = Array(invoice_ids).map(&:to_s).uniq
if !allowed_to?(permission) visible = Invoice.joins(:issues).merge(Issue.visible).where(id: ids).distinct.pluck(:id).map(&:to_s)
flash[:error] = t :notice_forbidden ids.any? && (ids - visible).empty?
render_403
end
end end
def global_check_permission(permission) def global_check_permission(permission)
+3 -2
View File
@@ -10,12 +10,13 @@
class QboSyncDispatcher class QboSyncDispatcher
# Payments before invoices: an invoice's paid-in-full day is worked out from the local payments' dates
SYNC_JOBS = [ SYNC_JOBS = [
Customer, Customer,
Estimate, Estimate,
Payment,
Invoice, Invoice,
Employee, Employee
Payment
].freeze ].freeze
# Dispatches all synchronization jobs to perform a full sync of QuickBooks entities with the local database. # Dispatches all synchronization jobs to perform a full sync of QuickBooks entities with the local database.
+40
View File
@@ -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
settings = RedmineQboBilling.mail_settings
@shop_name = settings[:shop_name].presence || Setting.app_title
delivery = settings[:delivery] || {}
if delivery.empty? && !ActionMailer::Base.perform_deliveries
raise DeliveryOff, I18n.t(:text_refund_email_off)
end
options = { to: email, from: settings[: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] = settings[:reply_to] if settings[:reply_to]
message = mail(options.merge(delivery)) do |format|
format.text
end
message.perform_deliveries = true unless delivery.empty?
message
end
end
+10 -11
View File
@@ -21,17 +21,8 @@ class CustomerToken < ApplicationRecord
TOKEN_EXPIRATION = 1.month TOKEN_EXPIRATION = 1.month
# Check if the token has expired # Get or create a token for the given issue. Making a new one also clears out the share links that have expired
def expired? # or whose issue was deleted, so they don't pile up.
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
def self.get_token(issue) def self.get_token(issue)
return unless issue return unless issue
return unless User.current.allowed_to?(:view_issues, issue.project) return unless User.current.allowed_to?(:view_issues, issue.project)
@@ -39,9 +30,17 @@ class CustomerToken < ApplicationRecord
token = active.find_by(issue_id: issue.id) token = active.find_by(issue_id: issue.id)
return token if token return token if token
purge_expired
create!(issue: issue) create!(issue: issue)
end 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 private
# Generate a unique token for the customer # Generate a unique token for the customer
-6
View File
@@ -79,12 +79,6 @@ class QboBaseModel < ActiveRecord::Base
QboSyncJob.perform_later(entity: model_name.name, id: id) QboSyncJob.perform_later(entity: model_name.name, id: id)
end 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) def self.qbo_sync(push: true)
self.qbo_push_enabled = push self.qbo_push_enabled = push
end end
+66
View File
@@ -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.
# A new estimate or invoice saved part way, in Redmine only. Nothing is in QuickBooks until it's saved from
# the editor, so QuickBooks can't apply a deposit to an invoice that's still being written. Drafts are shared:
# anyone with Write estimates (or Write invoices) can continue or delete any estimate (or invoice) draft.
class QboDraft < ApplicationRecord
DOCUMENTS = %w[estimate invoice].freeze
belongs_to :customer, optional: true
# Who saved it last
belongs_to :user, optional: true
validates :document, inclusion: { in: DOCUMENTS }
scope :newest_first, -> { order(updated_at: :desc, id: :desc) }
scope :for_document, ->(document) { where(document: document.to_s) }
# The drafts a user may open: estimate drafts need Write estimates, invoice drafts Write invoices
scope :visible, lambda { |user = User.current|
documents = []
documents << 'estimate' if RedmineQboBilling.writer?(user)
documents << 'invoice' if RedmineQboBilling.invoice_writer?(user)
where(document: documents)
}
# The editor's fields as posted (estimate[...])
def fields
parsed = JSON.parse(data.presence || '{}')
parsed.is_a?(Hash) ? parsed : {}
rescue JSON::ParserError
{}
end
def fields=(hash)
self.data = hash.to_h.to_json
end
# The editor form, filled in as it was saved
def form
RedmineQboBilling::EstimateForm.from_params(fields, document: document)
end
def invoice?
document == 'invoice'
end
def customer_name
customer&.name.presence || fields['customer_name'].presence
end
def subtotal
form.subtotal
end
def line_count
form.filled_lines.count { |line| !line.subtotal? }
end
end
+103
View File
@@ -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
+10
View File
@@ -9,5 +9,15 @@
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class EstimateService < ServiceBase class EstimateService < ServiceBase
# Raised when an estimate can't be read from QuickBooks (e.g. QuickBooks is down or disconnected)
class FetchError < StandardError; end
private
# Estimates are only read here (EstimateWriter saves them). When the read fails, raise an ordinary error
# rather than ServiceBase's NotImplementedError, which callers' `rescue StandardError` would miss; nothing
# is cached, so the next read tries QuickBooks again.
def build_qbo_remote
raise FetchError, "Could not read estimate ##{@local.id} from QuickBooks"
end
end end
+2
View File
@@ -30,6 +30,8 @@ class EstimateSyncService < SyncServiceBase
map_attribute :txn_status map_attribute :txn_status
# Man-hours: quantities of the labor products/services (plugin settings) # Man-hours: quantities of the labor products/services (plugin settings)
map_attribute(:hours) { |remote| RedmineQboBilling::ManHours.hours(remote) } 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 map_belongs_to :customer
end end
+3
View File
@@ -27,6 +27,9 @@ class InvoiceSyncService < SyncServiceBase
# Man-hours: quantities of the labor products/services (plugin settings) # Man-hours: quantities of the labor products/services (plugin settings)
map_attribute(:hours) { |remote| RedmineQboBilling::ManHours.hours(remote) } map_attribute(:hours) { |remote| RedmineQboBilling::ManHours.hours(remote) }
map_attribute :qbo_updated_at, "meta_data.last_updated_time" 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 map_belongs_to :customer
end end
-10
View File
@@ -80,15 +80,6 @@ class SyncServiceBase
false false
end 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 # Attribute Mapping DSL
# #
# This DSL defines how attributes from a QuickBooks Online (QBO) entity # This DSL defines how attributes from a QuickBooks Online (QBO) entity
@@ -157,7 +148,6 @@ class SyncServiceBase
end end
end end
def map_attribute(local_attr, remote_attr = nil, &block) def map_attribute(local_attr, remote_attr = nil, &block)
attribute_map[local_attr] = attribute_map[local_attr] =
if block_given? if block_given?
+7 -5
View File
@@ -1,3 +1,5 @@
<%# Phone numbers as (401) 555-0101, left blank when the customer has none %>
<% phone = ->(number) { digits = number.to_s.gsub(/\D/, ''); digits.present? ? number_to_phone(digits.to_i, area_code: true) : '' } %>
<table> <table>
<tbody> <tbody>
@@ -13,27 +15,27 @@
<tr> <tr>
<th><%= t(:label_primary_phone) %></th> <th><%= t(:label_primary_phone) %></th>
<td><%= number_to_phone(customer&.primary_phone&.gsub(/[^\d]/, '').to_i, area_code: true) %></td> <td><%= phone.call(customer&.primary_phone) %></td>
</tr> </tr>
<tr> <tr>
<th><%= t(:label_mobile_phone) %></th> <th><%= t(:label_mobile_phone) %></th>
<td><%= number_to_phone(customer&.mobile_phone&.gsub(/[^\d]/, '').to_i, area_code: true) %></td> <td><%= phone.call(customer&.mobile_phone) %></td>
</tr> </tr>
<tr> <tr>
<th><%= t(:label_billing_address) %></th> <th><%= t(:label_billing_address) %></th>
<td><pre><%= @billing_address %></pre></td> <td><pre><%= RedmineQboBilling::EstimateWriter.format_address(customer.billing_address) %></pre></td>
</tr> </tr>
<tr> <tr>
<th><%= t(:label_shipping_address) %></th> <th><%= t(:label_shipping_address) %></th>
<td><pre><%= @shipping_address %></pre></td> <td><pre><%= RedmineQboBilling::EstimateWriter.format_address(customer.shipping_address) %></pre></td>
</tr> </tr>
<tr> <tr>
<th><%= t(:label_account_balance) %></th> <th><%= t(:label_account_balance) %></th>
<td>$<%= customer.balance %></td> <td><%= number_to_currency(customer.balance || 0) %></td>
</tr> </tr>
<% if customer.notes.present? %> <% if customer.notes.present? %>
@@ -1,45 +1,51 @@
<%# <%#
Adds what's ticked on the customer page to the "New issue" link (#dynamic-new-issue-link in the contextual Adds what's ticked on the customer page to its links. A checkbox takes part with data-ticked-field="field"
area). Any checkbox with data-new-issue-param="issue[field]" takes part, one ticked per field: this plugin's (one is ticked per field), e.g. this plugin's estimates (estimate_id) and other plugins' lists. A link takes
estimates (issue[estimate_id]), and other plugins' lists (e.g. redmine_qbo_vehicles' issue[vehicle_id]). part with data-ticked-params, how each field is named in its URL: "issue[%s]" for New issue
(#dynamic-new-issue-link), "%s" for a plain param. Other plugins' links on the page work the same way.
%> %>
<script> <script>
function newIssueParamBoxes(param) { (function () {
return Array.prototype.filter.call(document.querySelectorAll('input[data-new-issue-param]'), function (cb) { var BOX = 'input[data-ticked-field]';
return !param || cb.getAttribute('data-new-issue-param') === param;
});
}
// One box per field: ticking one unticks the others for the same field function boxes(field) {
document.addEventListener('change', function (event) { return Array.prototype.filter.call(document.querySelectorAll(BOX), function (cb) {
var box = event.target; return !field || cb.getAttribute('data-ticked-field') === field;
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;
}); });
} }
updateLink();
});
function updateLink() { function fields() {
var link = document.getElementById('dynamic-new-issue-link'); return boxes().map(function (cb) { return cb.getAttribute('data-ticked-field'); })
if (!link) return; .filter(function (field, i, all) { return all.indexOf(field) === i; });
}
// Cache the pristine base URL on first run function updateLinks() {
if (!link.dataset.baseUrl) link.dataset.baseUrl = link.getAttribute('href'); Array.prototype.forEach.call(document.querySelectorAll('a[data-ticked-params]'), function (link) {
var url = new URL(link.dataset.baseUrl, window.location.origin); // 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);
var format = link.getAttribute('data-ticked-params');
fields().forEach(function (field) {
var param = format.replace('%s', field);
var ticked = boxes(field).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());
});
}
newIssueParamBoxes().forEach(function (cb) { // One box per field: ticking one unticks the others for the same field
var param = cb.getAttribute('data-new-issue-param'); document.addEventListener('change', function (event) {
var ticked = newIssueParamBoxes(param).filter(function (b) { return b.checked; })[0]; var box = event.target;
if (ticked) { if (!box.matches || !box.matches(BOX)) return;
url.searchParams.set(param, ticked.value); if (box.checked) {
} else { boxes(box.getAttribute('data-ticked-field')).forEach(function (cb) { if (cb !== box) cb.checked = false; });
url.searchParams.delete(param);
} }
updateLinks();
}); });
})();
link.setAttribute('href', url.toString());
}
</script> </script>
@@ -1 +0,0 @@
$('select#issue_estimate_id').html('<%= j content_tag(:option,'',value:"")+options_from_collection_for_select(@filtered_estimates, :id, :doc_number) %>');
+5
View File
@@ -5,6 +5,11 @@
<% if User.current.allowed_to?(:add_customers, nil, global: true) %> <% if User.current.allowed_to?(:add_customers, nil, global: true) %>
<%= link_to sprite_icon('add', l(:label_new_customer)), new_customer_path, class: 'icon icon-add' %> <%= link_to sprite_icon('add', l(:label_new_customer)), new_customer_path, class: 'icon icon-add' %>
<% end %> <% end %>
<%# Estimate and invoice drafts, for users who may write either %>
<% if RedmineQboBilling.writer? || RedmineQboBilling.invoice_writer? %>
<% draft_count = QboDraft.visible.count %>
<%= link_to sprite_icon('document', "#{l(:label_qbo_drafts)} (#{draft_count})"), qbo_drafts_path, class: 'icon icon-document' %>
<% end %>
<% if User.current.admin? %> <% if User.current.admin? %>
<%= link_to sprite_icon('reload', l(:label_sync)), qbo_sync_path, class: 'icon icon-reload' %> <%= link_to sprite_icon('reload', l(:label_sync)), qbo_sync_path, class: 'icon icon-reload' %>
<% end %> <% end %>
+39 -2
View File
@@ -6,7 +6,7 @@
<div class="contextual qbo-under-title"> <div class="contextual qbo-under-title">
<%# New issue for this customer; picks up what's ticked on this page (an estimate, other plugins' items) %> <%# New issue for this customer; picks up what's ticked on this page (an estimate, other plugins' items) %>
<%= link_to sprite_icon('add', l(:label_new_issue)), new_issue_path(issue: { customer_id: @customer.id }), <%= link_to sprite_icon('add', l(:label_new_issue)), new_issue_path(issue: { customer_id: @customer.id }),
id: 'dynamic-new-issue-link', class: 'icon icon-add', target: :_blank %> id: 'dynamic-new-issue-link', class: 'icon icon-add', target: :_blank, data: { ticked_params: 'issue[%s]' } %>
<%# Plugins add their customer actions here (e.g. redmine_qbo_calendar's Add appointment) %> <%# Plugins add their customer actions here (e.g. redmine_qbo_calendar's Add appointment) %>
<%= call_hook :view_customers_show_contextual, { customer: @customer } %> <%= call_hook :view_customers_show_contextual, { customer: @customer } %>
<%# Estimates, invoices and payments are handled here, each shown to users with its permission; Open in <%# Estimates, invoices and payments are handled here, each shown to users with its permission; Open in
@@ -23,6 +23,9 @@
<% if RedmineQboBilling.payment_receiver? %> <% 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' %> <%= link_to sprite_icon('add', l(:button_receive_payment)), new_qbo_payment_path(customer_id: @customer.id), class: 'icon icon-add' %>
<% end %> <% 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) %> <% if User.current.allowed_to?(:edit_customers, nil, global: true) %>
<%= link_to sprite_icon('edit', l(:button_edit)), edit_customer_path(@customer), <%= link_to sprite_icon('edit', l(:button_edit)), edit_customer_path(@customer),
class: 'icon icon-edit', accesskey: accesskey(:edit) %> class: 'icon icon-edit', accesskey: accesskey(:edit) %>
@@ -49,7 +52,7 @@
<div class="splitcontent"> <div class="splitcontent">
<div class="splitcontentleft"> <div class="splitcontentleft">
<h4><%=t(:estimates)%>:</h4> <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>
<div class="splitcontentleft"> <div class="splitcontentleft">
@@ -58,6 +61,40 @@
</div> </div>
</div> </div>
<%# Estimate and invoice drafts, kept in Redmine until they're saved to QuickBooks %>
<% customer_drafts = QboDraft.visible.where(customer_id: @customer.id).includes(:user).newest_first.to_a %>
<% if customer_drafts.any? %>
<h4><%= l(:label_qbo_drafts) %>:</h4>
<%= 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>
<div class="splitcontentleft"> <div class="splitcontentleft">
+11 -6
View File
@@ -3,14 +3,19 @@
<%= render partial: 'qbo_estimates/status_styles' %> <%= render partial: 'qbo_estimates/status_styles' %>
<div class="qbo-estimate-list"> <div class="qbo-estimate-list">
<% estimates.sort.reverse.each do |estimate| %> <% 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"> <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" %> <%# Ticking an estimate adds it to the customer page's links (customers/_new_issue_link_script) %>
<b><%= link_to "##{estimate.doc_number}", estimate_path(estimate), target: :_blank %></b> <%= estimate.txn_date %> <span class="qbo-list-check"><%= check_box_tag "estimate_ids[]", estimate.id, false, data: { ticked_field: '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) %> <%# QuickBooks status, cached by the estimate sync (kept current by the webhook) %>
<% if estimate.txn_status.present? %> <span class="qbo-list-status">
<span class="qbo-estimate-status qbo-estimate-status-<%= estimate.txn_status.downcase %>"><%= estimate.txn_status %></span> <% if estimate.txn_status.present? %>
<% end %> <span class="qbo-estimate-status qbo-estimate-status-<%= estimate.txn_status.downcase %>"><%= estimate.txn_status %></span>
<%= render partial: 'qbo_estimates/estimate_actions', locals: { estimate: estimate } if RedmineQboBilling.writer? %> <% end %>
</span>
<span class="qbo-list-actions"><%= render partial: 'qbo_estimates/estimate_actions', locals: { estimate: estimate } if RedmineQboBilling.writer? %></span>
</div> </div>
<% end %> <% end %>
</div> </div>
+12 -7
View File
@@ -13,14 +13,19 @@
<div class="qbo-invoice-list"> <div class="qbo-invoice-list">
<% invoices.sort.reverse.each do |invoice| %> <% 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"> <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 %> <span class="qbo-list-check"><%= check_box_tag "invoice_ids[]", invoice.id, false, class: "invoice-checkbox" if invoices.count > 1 %></span>
<b><%= link_to "##{invoice.doc_number}", invoice_path(invoice), target: :_blank %></b> <%= invoice.txn_date %> <b class="qbo-list-number"><%= link_to "##{invoice.doc_number}", invoice_path(invoice), target: :_blank %></b>
<%# Paid / partially paid / overdue / open / voided, from the cached balance and due date %> <span class="qbo-list-date"><%= invoice.txn_date %></span>
<% if (status = invoice.status) %> <%# Paid / partially paid / overdue / open / voided, from the cached balance and due date; short so the list
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status) %></span> stays narrow: "Paid", or "Paid +3d" when paid in full days after its date (the date on hover) %>
<% end %> <span class="qbo-list-status">
<%= render partial: 'qbo_invoices/invoice_actions', locals: { invoice: invoice } if RedmineQboBilling.invoice_writer? %> <% 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> </div>
<% end %> <% end %>
</div> </div>
+6
View File
@@ -10,6 +10,12 @@
<div class="value"> <div class="value">
<%= estimate_link %> <%= estimate_link %>
<%= render partial: 'qbo_estimates/estimate_actions', locals: { estimate: issue.estimate } if issue.estimate && RedmineQboBilling.writer? %> <%= render partial: 'qbo_estimates/estimate_actions', locals: { estimate: issue.estimate } if issue.estimate && RedmineQboBilling.writer? %>
<%# Create the estimate's remaining labor lines as subtasks of this issue %>
<% if issue.estimate && User.current.allowed_to?(:create_estimate_issues, nil, global: true) && User.current.allowed_to?(:manage_subtasks, issue.project) %>
<%= link_to sprite_icon('add', l(:button_create_estimate_subtasks)),
issues_preview_qbo_estimate_path(issue.estimate.id, parent_issue_id: issue.id),
class: 'icon-only icon-add', title: l(:button_create_estimate_subtasks) %>
<% end %>
</div> </div>
</div> </div>
+37
View File
@@ -66,3 +66,40 @@
<em class="info"><%= l(:text_default_tracker_info) %></em> <em class="info"><%= l(:text_default_tracker_info) %></em>
</p> </p>
</fieldset> </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>
+2 -1
View File
@@ -4,6 +4,7 @@
<%= render partial: 'customers/sidebar' %> <%= render partial: 'customers/sidebar' %>
<% end %> <% 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 %> <% end %>
-32
View File
@@ -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>
-13
View File
@@ -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>
-13
View File
@@ -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>
@@ -0,0 +1,18 @@
<%# On the new estimate/invoice editor: the draft being continued, or the customer's other drafts of this
document so a second one isn't started by accident %>
<% draft = local_assigns[:draft] %>
<% drafts = local_assigns[:drafts] || [] %>
<% if draft %>
<div class="flash notice qbo-draft-notice">
<%= l(:text_qbo_editing_draft, user: h(draft.user&.name || l(:label_user_anonymous)), age: time_tag(draft.updated_at)).html_safe %>
</div>
<% elsif drafts.any? %>
<div class="warning qbo-estimate-notice qbo-draft-notice">
<%= l(drafts.first.invoice? ? :text_qbo_customer_has_invoice_drafts : :text_qbo_customer_has_estimate_drafts, count: drafts.size) %>
<% drafts.each do |other| %>
<%= link_to l(:text_qbo_draft_link, user: other.user&.name || l(:label_user_anonymous),
subtotal: number_to_currency(other.subtotal), date: format_time(other.updated_at)),
other.invoice? ? new_qbo_invoice_path(draft_id: other.id) : new_qbo_estimate_path(draft_id: other.id) %>
<% end %>
</div>
<% end %>
+40
View File
@@ -0,0 +1,40 @@
<%# Estimate and invoice drafts (QboDraft) with Continue and Delete. show_customer: false on a customer's page. %>
<% show_customer = local_assigns.fetch(:show_customer, true) %>
<table class="list qbo-drafts">
<thead>
<tr>
<th><%= l(:label_qbo_draft_document) %></th>
<% if show_customer %><th><%= l(:field_customer) %></th><% end %>
<th class="qbo-draft-number"><%= l(:label_qbo_draft_lines) %></th>
<th class="qbo-draft-number"><%= l(:label_subtotal) %></th>
<th><%= l(:label_qbo_draft_saved_by) %></th>
<th></th>
</tr>
</thead>
<tbody>
<% drafts.each do |draft| %>
<tr>
<td><%= link_to l(draft.invoice? ? :label_qbo_invoice_draft : :label_qbo_estimate_draft),
draft.invoice? ? new_qbo_invoice_path(draft_id: draft.id) : new_qbo_estimate_path(draft_id: draft.id) %></td>
<% if show_customer %>
<td><%= draft.customer ? link_to(draft.customer.name, customer_path(draft.customer)) : (draft.customer_name || '–') %></td>
<% end %>
<td class="qbo-draft-number"><%= draft.line_count %></td>
<td class="qbo-draft-number"><%= number_to_currency(draft.subtotal) %></td>
<td><%= l(:text_qbo_draft_saved_by, user: h(draft.user&.name || l(:label_user_anonymous)), age: time_tag(draft.updated_at)).html_safe %></td>
<td class="buttons">
<%= link_to sprite_icon('edit', l(:button_qbo_continue_draft)),
draft.invoice? ? new_qbo_invoice_path(draft_id: draft.id) : new_qbo_estimate_path(draft_id: draft.id),
class: 'icon icon-edit' %>
<%= link_to sprite_icon('del', l(:button_delete)), qbo_draft_path(draft), method: :delete,
data: { confirm: l(:text_are_you_sure) }, class: 'icon icon-del' %>
</td>
</tr>
<% end %>
</tbody>
</table>
<style>
table.qbo-drafts td, table.qbo-drafts th { text-align: left; }
table.qbo-drafts .qbo-draft-number { text-align: right; white-space: nowrap; }
table.qbo-drafts td.buttons { white-space: nowrap; }
</style>
+11
View File
@@ -0,0 +1,11 @@
<% html_title l(:label_qbo_drafts) %>
<h2><%= link_to l(:label_customers), customers_path %> &#187; <%= l(:label_qbo_drafts) %></h2>
<p class="info"><%= l(:text_qbo_drafts_info) %></p>
<% if @drafts.any? %>
<%= render partial: 'qbo_drafts/list', locals: { drafts: @drafts } %>
<% else %>
<p class="nodata"><%= l(:label_no_data) %></p>
<% end %>
+39 -6
View File
@@ -10,6 +10,11 @@
settings_read = company.settings.present? settings_read = company.settings.present?
# The same editor writes estimates and invoices # The same editor writes estimates and invoices
invoice = form.invoice? invoice = form.invoice?
# The discount box, unless QuickBooks has discounts turned off or the document is read-only (shown anyway
# for a document that has one)
show_discount = form.discount? || (company.discounts_allowed? && !form.locked)
# The draft being continued (QboDraft), if any; new documents can be saved as drafts
draft = local_assigns[:draft]
sender = invoice ? RedmineQboBilling.invoice_sender? : RedmineQboBilling.sender? sender = invoice ? RedmineQboBilling.invoice_sender? : RedmineQboBilling.sender?
cancel_path = customer ? customer_path(customer) : home_path cancel_path = customer ? customer_path(customer) : home_path
form_url = form_url =
@@ -38,14 +43,22 @@
warn_unsaved: User.current.pref.warn_on_leaving_unsaved != '0' warn_unsaved: User.current.pref.warn_on_leaving_unsaved != '0'
}) do %> }) do %>
<%= hidden_field_tag 'estimate[sync_token]', form.sync_token, id: nil %> <%= hidden_field_tag 'estimate[sync_token]', form.sync_token, id: nil %>
<%= hidden_field_tag 'draft_id', draft.id, id: nil if draft %>
<%= hidden_field_tag 'estimate[total_tax]', form.total_tax, id: nil %> <%= hidden_field_tag 'estimate[total_tax]', form.total_tax, id: nil %>
<%= hidden_field_tag 'estimate[discount]', form.discount, id: nil %> <%= hidden_field_tag 'estimate[discount]', form.discount, id: nil %>
<%= hidden_field_tag 'estimate[email_status]', form.email_status, id: nil %> <%= hidden_field_tag 'estimate[email_status]', form.email_status, id: nil %>
<%= hidden_field_tag 'estimate[txn_status]', form.txn_status, id: nil %> <%= 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 %> <%# 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? %> <%= 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 %> <% if invoice %>
<%= hidden_field_tag 'estimate[balance]', form.balance, id: nil %> <%= hidden_field_tag 'estimate[balance]', form.balance, id: nil %>
<%# A paid invoice opened for editing (Unlock) stays unlocked if the page is shown again %>
<% if form.unlocked %>
<%= hidden_field_tag 'unlock', '1', id: nil %>
<%= hidden_field_tag 'estimate[amount_paid]', form.amount_paid, id: nil %>
<% end %>
<%# Estimates whose lines are on this invoice; the Import panel adds more %> <%# Estimates whose lines are on this invoice; the Import panel adds more %>
<span id="qbo-linked-estimates"> <span id="qbo-linked-estimates">
<% form.linked_estimate_ids.each do |estimate_id| %> <% form.linked_estimate_ids.each do |estimate_id| %>
@@ -259,10 +272,18 @@
<th><%= l(:label_taxable_subtotal) %></th> <th><%= l(:label_taxable_subtotal) %></th>
<td id="qbo-estimate-taxable-subtotal"></td> <td id="qbo-estimate-taxable-subtotal"></td>
</tr> </tr>
<% if form.discount.to_f != 0 %> <% if show_discount %>
<tr> <%# A percent of the subtotal or a dollar amount; QuickBooks' discount line %>
<th><%= l(:label_discount_from_quickbooks) %></th> <tr class="qbo-estimate-discount">
<td>-<%= number_to_currency(form.discount) %></td> <th>
<label for="qbo_estimate_discount_value"><%= l(:label_discount_from_quickbooks) %></label>
<%= text_field_tag 'estimate[discount_value]', form.discount_value, id: 'qbo_estimate_discount_value',
size: 6, inputmode: 'decimal', autocomplete: 'off', placeholder: '0' %>
<%= select_tag 'estimate[discount_type]',
options_for_select([[l(:label_discount_percent), 'percent'], [l(:label_discount_amount), 'amount']], form.discount_type),
id: 'qbo_estimate_discount_type', 'aria-label': l(:label_discount_type) %>
</th>
<td id="qbo-estimate-discount"><%= "-#{number_to_currency(form.discount_amount)}" if form.discount? %></td>
</tr> </tr>
<% end %> <% end %>
<tr> <tr>
@@ -279,14 +300,26 @@
</fieldset> </fieldset>
<%# Action bar, like the bar along the bottom of QuickBooks' estimate screen %> <%# Action bar, like the bar along the bottom of QuickBooks' estimate screen %>
<div class="qbo-estimate-actions"> <div class="qbo-estimate-actions" data-saving-text="<%= l(:text_qbo_saving) %>">
<%= link_to l(:button_cancel), cancel_path, class: 'qbo-button qbo-button-dark', id: 'qbo-estimate-cancel' %> <%= link_to l(:button_cancel), cancel_path, class: 'qbo-button qbo-button-dark', id: 'qbo-estimate-cancel' %>
<% unless form.locked %> <% unless form.locked %>
<span class="qbo-estimate-actions-save"> <span class="qbo-estimate-actions-save">
<%# Shown while a save is on its way to QuickBooks (qbo_estimates/_script) %>
<span class="qbo-saving-status" role="status" aria-live="polite" hidden></span>
<% unless form.persisted? %>
<%# Kept in Redmine only, however incomplete (QboDraftHandling) %>
<% if draft %>
<%= link_to l(:button_qbo_delete_draft), qbo_draft_path(draft), method: :delete,
data: { confirm: l(:text_are_you_sure) }, class: 'qbo-button qbo-button-dark', id: 'qbo-delete-draft' %>
<% end %>
<%= submit_tag l(:button_qbo_save_draft), name: 'save_draft', class: 'qbo-button qbo-button-dark',
id: 'qbo-save-draft', formnovalidate: true, data: { saving_text: l(:text_qbo_saving_draft) } %>
<% end %>
<%= submit_tag l(:button_save), name: 'save', class: 'qbo-button qbo-button-dark' %> <%= submit_tag l(:button_save), name: 'save', class: 'qbo-button qbo-button-dark' %>
<% if sender %> <% if sender %>
<%= submit_tag l(:button_save_and_send), name: 'save_and_send', class: 'qbo-button qbo-button-primary', <%= submit_tag l(:button_save_and_send), name: 'save_and_send', class: 'qbo-button qbo-button-primary',
id: 'qbo-estimate-save-and-send', data: { needs_email_text: l(:text_estimate_send_needs_email) } %> id: 'qbo-estimate-save-and-send',
data: { needs_email_text: l(:text_estimate_send_needs_email), saving_text: l(:text_qbo_saving_and_sending) } %>
<% end %> <% end %>
</span> </span>
<% end %> <% end %>
+28 -2
View File
@@ -20,7 +20,8 @@
due_date: RedmineQboBilling::EstimateForm.date(form.due_date), due_date: RedmineQboBilling::EstimateForm.date(form.due_date),
today: User.current.today) %> today: User.current.today) %>
<% if status %> <% 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 %> <% end %>
<% elsif !invoice && form.txn_status.present? %> <% elsif !invoice && form.txn_status.present? %>
<span class="qbo-estimate-status qbo-estimate-status-<%= form.txn_status.downcase %>"><%= form.txn_status %></span> <span class="qbo-estimate-status qbo-estimate-status-<%= form.txn_status.downcase %>"><%= form.txn_status %></span>
@@ -66,9 +67,34 @@
<li><%= link_to_issue(issue, truncate: 60) %></li> <li><%= link_to_issue(issue, truncate: 60) %></li>
<% end %> <% end %>
</ul> </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> </div>
<% elsif form.locked == :paid %> <% elsif form.locked == :paid %>
<p class="warning"><%= l(:error_invoice_paid) %></p> <p class="warning">
<%= l(:error_invoice_paid) %>
<%# Opened for editing anyway after a confirmation (e.g. a discount after a deposit) %>
<% if RedmineQboBilling.paid_invoice_editor?(form.fully_paid?) %>
<%= link_to sprite_icon('unlock', l(:button_unlock_invoice)), edit_qbo_invoice_path(form.id, unlock: 1),
class: 'icon icon-unlock', id: 'qbo-unlock-invoice',
data: { confirm: l(:text_unlock_invoice_confirmation) } %>
<% end %>
</p>
<% elsif form.unlocked && form.amount_paid.to_d > 0 %>
<p class="warning"><%= l(:text_invoice_unlocked, paid: number_to_currency(form.amount_paid)) %></p>
<% elsif form.locked == :bundles %> <% elsif form.locked == :bundles %>
<p class="warning"><%= l(invoice ? :error_invoice_has_bundles : :error_estimate_has_bundles) %></p> <p class="warning"><%= l(invoice ? :error_invoice_has_bundles : :error_estimate_has_bundles) %></p>
<% end %> <% end %>
+61 -3
View File
@@ -36,8 +36,10 @@ $(function () {
var money = new Intl.NumberFormat(<%= raw (current_language.to_s.presence || 'en').to_json %>, { style: 'currency', currency: 'USD' }); var money = new Intl.NumberFormat(<%= raw (current_language.to_s.presence || 'en').to_json %>, { style: 'currency', currency: 'USD' });
var savedSubtotal = $form.data('savedSubtotal') === '' ? null : parseFloat($form.data('savedSubtotal')); var savedSubtotal = $form.data('savedSubtotal') === '' ? null : parseFloat($form.data('savedSubtotal'));
var savedTax = $form.data('savedTax') === '' ? null : parseFloat($form.data('savedTax')); var savedTax = $form.data('savedTax') === '' ? null : parseFloat($form.data('savedTax'));
// Discounts are kept from QuickBooks as they are; QuickBooks works out a percent discount again on save // The discount QuickBooks took off when the document was last saved (the tax shown is for that discount)
var discount = $form.data('discount') === '' ? 0 : parseFloat($form.data('discount')); var savedDiscount = $form.data('discount') === '' ? 0 : parseFloat($form.data('discount'));
var $discountValue = $('#qbo_estimate_discount_value');
var $discountType = $('#qbo_estimate_discount_type');
var locked = $form.find('.qbo-estimate-sheet').prop('disabled'); var locked = $form.find('.qbo-estimate-sheet').prop('disabled');
// Row keys must be digits: Rails' strong parameters only keep a hash of rows when every key is a number // Row keys must be digits: Rails' strong parameters only keep a hash of rows when every key is a number
var nextKey = Date.now(); var nextKey = Date.now();
@@ -131,6 +133,13 @@ $(function () {
return round(qty * rate, 2); return round(qty * rate, 2);
} }
// The discount in dollars: a percent of the subtotal or an amount, like QuickBooks works it out
function discountAmount(subtotal) {
var value = parseNumber(String($discountValue.val() || '').replace(/%/g, ''));
if (!$discountValue.length || value === null || isNaN(value) || value <= 0) return 0;
return $discountType.val() === 'percent' ? round(subtotal * value / 100, 2) : round(value, 2);
}
function recalc() { function recalc() {
var subtotal = 0, taxable = 0, section = 0; var subtotal = 0, taxable = 0, section = 0;
rows().each(function () { rows().each(function () {
@@ -154,8 +163,11 @@ $(function () {
// QuickBooks works out the sales tax when the estimate is saved; show the saved tax until the lines change // QuickBooks works out the sales tax when the estimate is saved; show the saved tax until the lines change
var $tax = $('#qbo-estimate-tax'); var $tax = $('#qbo-estimate-tax');
var discount = discountAmount(subtotal);
$('#qbo-estimate-discount').text(discount > 0 ? '-' + money.format(discount) : '');
var total = round(subtotal - discount, 2); var total = round(subtotal - discount, 2);
if (savedTax !== null && savedSubtotal !== null && Math.abs(subtotal - savedSubtotal) < 0.005) { if (savedTax !== null && savedSubtotal !== null && Math.abs(subtotal - savedSubtotal) < 0.005 &&
Math.abs(discount - savedDiscount) < 0.005) {
$tax.text(money.format(savedTax)).removeClass('qbo-pending'); $tax.text(money.format(savedTax)).removeClass('qbo-pending');
total = round(total + savedTax, 2); total = round(total + savedTax, 2);
} else { } else {
@@ -743,6 +755,16 @@ $(function () {
}); });
} }
$discountValue.on('input', function () { dirty = true; recalc(); });
$discountType.on('change', function () { dirty = true; recalc(); });
// Math typed in the discount box (e.g. 1500-1250) is worked out, to the cent
function tidyDiscount() {
var text = String($discountValue.val() || '').replace(/[$,\s%]/g, '');
var value = parseNumber(text);
if (value !== null && !isNaN(value) && isMath(text)) $discountValue.val(plain(round(value, 2), 2));
}
$discountValue.on('blur', function () { tidyDiscount(); recalc(); });
// ---- saving ---- // ---- saving ----
$form.on('input change', '.qbo-estimate-top input, .qbo-estimate-details input, .qbo-estimate-notes textarea', function () { dirty = true; }); $form.on('input change', '.qbo-estimate-top input, .qbo-estimate-details input, .qbo-estimate-notes textarea', function () { dirty = true; });
@@ -751,7 +773,11 @@ $(function () {
if (event.key === 'Enter' && !$(this).closest('.ui-autocomplete').length) event.preventDefault(); if (event.key === 'Enter' && !$(this).closest('.ui-autocomplete').length) event.preventDefault();
}); });
// Set once a save is on its way, so more clicks don't save (or send) it twice
var saving = false;
$form.on('submit', function (event) { $form.on('submit', function (event) {
if (saving) { event.preventDefault(); return; }
var submitter = event.originalEvent && event.originalEvent.submitter; var submitter = event.originalEvent && event.originalEvent.submitter;
if (submitter && submitter.id === 'qbo-estimate-save-and-send' && !$email.val().trim()) { if (submitter && submitter.id === 'qbo-estimate-save-and-send' && !$email.val().trim()) {
event.preventDefault(); event.preventDefault();
@@ -761,7 +787,39 @@ $(function () {
} }
// Math still in a box is worked out before saving // Math still in a box is worked out before saving
rows().each(function () { tidyNumbers($(this)); }); rows().each(function () { tidyNumbers($(this)); });
tidyDiscount();
dirty = false; dirty = false;
// After every submit handler has run (and the form's values are already taken, so disabling the buttons
// doesn't drop which one was clicked): unless one stopped the save, show it's saving and lock the buttons
setTimeout(function () {
var stopped = event.originalEvent ? event.originalEvent.defaultPrevented : event.isDefaultPrevented();
if (stopped) return;
saving = true;
showSaving(submitter);
}, 0);
});
function showSaving(submitter) {
var $bar = $form.find('.qbo-estimate-actions');
var $clicked = submitter ? $(submitter) : $bar.find('input[type=submit][name=save]');
var text = $clicked.data('savingText') || $bar.data('savingText');
$bar.addClass('qbo-saving');
$bar.find('input[type=submit]').prop('disabled', true);
$bar.find('a.qbo-button').addClass('qbo-button-disabled').attr('aria-disabled', 'true');
$bar.find('.qbo-saving-status').text(text).prop('hidden', false);
}
// Coming back with the browser's Back button can show the page as it was left, still "saving"
window.addEventListener('pageshow', function (event) {
if (!event.persisted || !saving) return;
saving = false;
var $bar = $form.find('.qbo-estimate-actions');
$bar.removeClass('qbo-saving');
$bar.find('input[type=submit]').prop('disabled', false);
$bar.find('a.qbo-button').removeClass('qbo-button-disabled').removeAttr('aria-disabled');
$bar.find('.qbo-saving-status').prop('hidden', true);
}); });
window.addEventListener('beforeunload', function (event) { window.addEventListener('beforeunload', function (event) {
@@ -14,4 +14,11 @@
.qbo-invoice-status-open { background: #e8eefa; color: #0d47a1; } .qbo-invoice-status-open { background: #e8eefa; color: #0d47a1; }
.qbo-invoice-status-voided { background: #eceef1; color: #6b6c72; text-decoration: line-through; } .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; } .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> </style>
+20 -1
View File
@@ -2,7 +2,12 @@
<style> <style>
.qbo-estimate { --qbo-border: #babec5; --qbo-muted: #6b6c72; --qbo-green: #2ca01c; --qbo-green-dark: #108000; --qbo-bar: #393a3d; } .qbo-estimate { --qbo-border: #babec5; --qbo-muted: #6b6c72; --qbo-green: #2ca01c; --qbo-green-dark: #108000; --qbo-bar: #393a3d; }
.qbo-estimate-sheet { border: 1px solid #e3e5e8; border-radius: 4px; background: #fff; padding: 20px 24px 24px; margin: 0 0 0; min-width: 0; } .qbo-estimate-sheet { border: 1px solid #e3e5e8; border-radius: 4px; background: #fff; padding: 20px 24px 24px; margin: 0 0 0; min-width: 0; }
.qbo-estimate-sheet[disabled] { opacity: .75; } .qbo-estimate-sheet[disabled] { opacity: .85; }
/* A locked document is still read here: browsers grey out disabled boxes' text (Safari nearly to nothing,
through -webkit-text-fill-color), so it's drawn in the normal text color */
.qbo-estimate-sheet[disabled] :is(input, textarea, select) { color: #393a3d; -webkit-text-fill-color: #393a3d; opacity: 1; }
/* ...but not hints in empty boxes, which would read as if they were filled in */
.qbo-estimate-sheet[disabled] :is(input, textarea)::placeholder { color: transparent; -webkit-text-fill-color: transparent; }
.qbo-estimate-sheet[disabled] .qbo-estimate-line-buttons, .qbo-estimate-sheet[disabled] .qbo-line-handle svg, .qbo-estimate-sheet[disabled] .qbo-estimate-line-buttons, .qbo-estimate-sheet[disabled] .qbo-line-handle svg,
.qbo-estimate-sheet[disabled] .qbo-line-remove-button { display: none; } .qbo-estimate-sheet[disabled] .qbo-line-remove-button { display: none; }
.qbo-estimate-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 24px; } .qbo-estimate-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 24px; }
@@ -95,6 +100,9 @@
.qbo-estimate-totals { border-collapse: collapse; min-width: 300px; align-self: flex-start; font-variant-numeric: tabular-nums; } .qbo-estimate-totals { border-collapse: collapse; min-width: 300px; align-self: flex-start; font-variant-numeric: tabular-nums; }
.qbo-estimate-totals th { text-align: right; font-weight: normal; color: #393a3d; padding: 6px 16px 6px 0; } .qbo-estimate-totals th { text-align: right; font-weight: normal; color: #393a3d; padding: 6px 16px 6px 0; }
.qbo-estimate-totals td { text-align: right; padding: 6px 0; min-width: 110px; } .qbo-estimate-totals td { text-align: right; padding: 6px 0; min-width: 110px; }
.qbo-estimate-discount th { white-space: nowrap; }
.qbo-estimate-discount input { width: 5em; text-align: right; margin-left: 6px; }
.qbo-estimate-discount select { width: auto; }
.qbo-estimate-totals #qbo-estimate-tax.qbo-pending { color: var(--qbo-muted); font-style: italic; font-size: .9em; } .qbo-estimate-totals #qbo-estimate-tax.qbo-pending { color: var(--qbo-muted); font-style: italic; font-size: .9em; }
.qbo-estimate-totals .qbo-estimate-total th, .qbo-estimate-totals .qbo-estimate-total td { font-weight: 700; font-size: 1.15em; border-top: 1px solid #d4d7dc; padding-top: 10px; } .qbo-estimate-totals .qbo-estimate-total th, .qbo-estimate-totals .qbo-estimate-total td { font-weight: 700; font-size: 1.15em; border-top: 1px solid #d4d7dc; padding-top: 10px; }
@@ -111,6 +119,17 @@
.qbo-estimate .qbo-button-primary { background: var(--qbo-green); border-color: var(--qbo-green); color: #fff; } .qbo-estimate .qbo-button-primary { background: var(--qbo-green); border-color: var(--qbo-green); color: #fff; }
.qbo-estimate .qbo-button-primary:hover { background: var(--qbo-green-dark); border-color: var(--qbo-green-dark); color: #fff; } .qbo-estimate .qbo-button-primary:hover { background: var(--qbo-green-dark); border-color: var(--qbo-green-dark); color: #fff; }
/* While saving: the buttons are locked and a spinner says what's happening */
.qbo-estimate .qbo-saving .qbo-button[disabled],
.qbo-estimate .qbo-saving .qbo-button-disabled { opacity: .6; cursor: progress; pointer-events: none; }
.qbo-estimate .qbo-saving-status { display: inline-flex; align-items: center; gap: 8px; color: #fff; font-weight: 600; margin-right: 8px; }
.qbo-estimate .qbo-saving-status[hidden] { display: none; }
.qbo-estimate .qbo-saving-status::before { content: ""; width: 16px; height: 16px; border-radius: 50%; box-sizing: border-box;
border: 2px solid rgba(255,255,255,.35); border-top-color: #fff; animation: qbo-saving-spin .8s linear infinite; }
@keyframes qbo-saving-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .qbo-estimate .qbo-saving-status::before { animation-duration: 2.4s; } }
.qbo-estimate .qbo-saving { cursor: progress; }
/* Warnings with a list (linked issues, invoices): the text, then one item per line */ /* Warnings with a list (linked issues, invoices): the text, then one item per line */
div.warning.qbo-estimate-notice { text-align: left; } div.warning.qbo-estimate-notice { text-align: left; }
div.warning.qbo-estimate-notice ul { margin: 6px 0 0; padding-left: 22px; } div.warning.qbo-estimate-notice ul { margin: 6px 0 0; padding-left: 22px; }
+63 -13
View File
@@ -1,6 +1,6 @@
<% html_title l(:button_create_estimate_issues) %> <% html_title l(:button_create_estimate_issues) %>
<%# Extra params to carry through (e.g. appointment_id from redmine_qbo_calendar) %> <%# Params other plugins carry through the page (:qbo_billing_issue_carry_params, e.g. redmine_qbo_calendar's appointment) %>
<% carry = request.query_parameters.merge(request.request_parameters).slice('appointment_id') %> <% carry = request.query_parameters.merge(request.request_parameters).slice(*Redmine::Hook.call_hook(:qbo_billing_issue_carry_params, {}).flatten.compact.map(&:to_s)) %>
<div class="contextual"> <div class="contextual">
<%= link_to sprite_icon('angle-left', @return_label), @return_path, class: 'icon icon-angle-left' %> <%= link_to sprite_icon('angle-left', @return_label), @return_path, class: 'icon icon-angle-left' %>
@@ -14,26 +14,58 @@
</span> </span>
</h2> </h2>
<%# Target project: changing it reloads the page with that project's trackers and templates %> <%# Target project and parent task: changing either reloads the page (the project's trackers and templates;
<% if @available_projects.size > 1 %> the parent's project, custom field values and plugins' fields) %>
<%= form_tag issues_preview_qbo_estimate_path(@estimate.id), method: :get, id: 'estimate-issues-project-form' do %> <%= form_tag issues_preview_qbo_estimate_path(@estimate.id), method: :get, id: 'estimate-issues-project-form' do %>
<% carry.each do |key, value| %><%= hidden_field_tag key, value, id: nil %><% end %> <% carry.each do |key, value| %><%= hidden_field_tag key, value, id: nil %><% end %>
<p> <p>
<label for="project_id"><strong><%= l(:field_project) %>:</strong></label> <label for="project_id"><strong><%= l(:field_project) %>:</strong></label>
<% if @available_projects.size > 1 %>
<%= select_tag :project_id, <%= select_tag :project_id,
options_from_collection_for_select(@available_projects, :id, :name, @target_project.id), options_from_collection_for_select(@available_projects, :id, :name, @target_project.id),
onchange: 'this.form.submit();' %> onchange: 'this.form.submit();' %>
<noscript><%= submit_tag l(:button_apply), name: nil %></noscript> <% else %>
<%= link_to_project @target_project %>
<%= hidden_field_tag :project_id, @target_project.id, id: nil %>
<% end %>
</p>
<% if @can_add_subtasks || @parent_issue_id.present? %>
<p class="estimate-issues-parent">
<label for="parent_issue_id"><strong><%= l(:field_parent_issue) %>:</strong></label>
<%= text_field_tag :parent_issue_id, @parent_issue&.id || @parent_issue_id, size: 10,
placeholder: l(:label_estimate_parent_placeholder) %>
<% if @parent_issue %>
<%= link_to_issue(@parent_issue, truncate: 60) %>
<%= link_to sprite_icon('del', l(:button_clear)),
issues_preview_qbo_estimate_path(@estimate.id, carry.merge(project_id: @target_project.id)),
class: 'icon-only icon-del', title: l(:button_clear) %>
<br><em class="info"><%= l(:text_estimate_parent_info) %></em>
<% end %>
</p> </p>
<% end %> <% end %>
<% else %> <noscript><p><%= submit_tag l(:button_apply), name: nil %></p></noscript>
<p><strong><%= l(:field_project) %>:</strong> <%= link_to_project @target_project %></p>
<% end %> <% end %>
<% if @builder.errors.any? %> <% if @can_add_subtasks || @parent_issue_id.present? %>
<%= javascript_tag do %>
(function () {
var field = document.getElementById('parent_issue_id');
if (!field) return;
var submitted = false;
function reload() { if (!submitted) { submitted = true; field.form.submit(); } }
observeAutocompleteField('parent_issue_id',
<%= raw auto_complete_issues_path(project_id: @target_project, scope: Setting.cross_project_subtasks, status: 'o').to_json %>,
{ select: function (event, ui) { field.value = ui.item.value; reload(); } });
field.addEventListener('change', reload);
})();
<% end %>
<% end %>
<% errors = [@parent_issue_error, *@builder.errors].compact %>
<% if errors.any? %>
<div id="errorExplanation"> <div id="errorExplanation">
<ul> <ul>
<% @builder.errors.each do |message| %> <% errors.each do |message| %>
<li><%= message %></li> <li><%= message %></li>
<% end %> <% end %>
</ul> </ul>
@@ -63,6 +95,7 @@
id: 'estimate-issues-form', id: 'estimate-issues-form',
data: { templates: template_data.to_json } do %> data: { templates: template_data.to_json } do %>
<%= hidden_field_tag :project_id, @target_project.id %> <%= hidden_field_tag :project_id, @target_project.id %>
<%= hidden_field_tag :parent_issue_id, @parent_issue&.id || @parent_issue_id, id: nil %>
<% carry.each do |key, value| %><%= hidden_field_tag key, value, id: nil %><% end %> <% carry.each do |key, value| %><%= hidden_field_tag key, value, id: nil %><% end %>
<table class="list estimate-issues-preview"> <table class="list estimate-issues-preview">
@@ -136,6 +169,21 @@
</tbody> </tbody>
</table> </table>
<%# Dates for every issue: from the appointment the page was opened from, else the parent task; blank means none %>
<fieldset class="box tabular estimate-issue-dates">
<legend><%= l(:label_estimate_issue_dates) %></legend>
<p>
<label for="estimate_issue_start_date"><%= l(:field_start_date) %></label>
<%= date_field_tag 'issue_dates[start_date]', @defaults[:start_date], id: 'estimate_issue_start_date', size: 10 %>
<%= calendar_for('estimate_issue_start_date') %>
</p>
<p>
<label for="estimate_issue_due_date"><%= l(:field_due_date) %></label>
<%= date_field_tag 'issue_dates[due_date]', @defaults[:due_date], id: 'estimate_issue_due_date', size: 10 %>
<%= calendar_for('estimate_issue_due_date') %>
</p>
</fieldset>
<%# Fields entered once and applied to every issue: plugins' own (e.g. redmine_qbo_vehicles' vehicle, posted as <%# Fields entered once and applied to every issue: plugins' own (e.g. redmine_qbo_vehicles' vehicle, posted as
issue_plugin_fields[...]) and the custom fields for the chosen trackers %> issue_plugin_fields[...]) and the custom fields for the chosen trackers %>
<% plugin_fields = call_hook(:view_qbo_estimate_issues_form, { estimate: @estimate, defaults: @defaults, project: @target_project }) %> <% plugin_fields = call_hook(:view_qbo_estimate_issues_form, { estimate: @estimate, defaults: @defaults, project: @target_project }) %>
@@ -234,6 +282,8 @@
var visibleCount = 0; var visibleCount = 0;
fieldBox.querySelectorAll('.estimate-issue-field').forEach(function (field) { fieldBox.querySelectorAll('.estimate-issue-field').forEach(function (field) {
// Plugins' fields (e.g. the vehicle) apply to every tracker
if (!field.hasAttribute('data-tracker-ids')) { visibleCount++; return; }
var used = idList(field.dataset.trackerIds).some(function (id) { return trackerIds.indexOf(id) >= 0; }); var used = idList(field.dataset.trackerIds).some(function (id) { return trackerIds.indexOf(id) >= 0; });
var required = idList(field.dataset.requiredTrackerIds).some(function (id) { return trackerIds.indexOf(id) >= 0; }); var required = idList(field.dataset.requiredTrackerIds).some(function (id) { return trackerIds.indexOf(id) >= 0; });
field.style.display = used ? '' : 'none'; field.style.display = used ? '' : 'none';
+2 -1
View File
@@ -1,4 +1,5 @@
<% html_title l(:label_new_estimate) %> <% html_title l(:label_new_estimate) %>
<%= render partial: 'qbo_estimates/header', locals: { form: @form } %> <%= render partial: 'qbo_estimates/header', locals: { form: @form } %>
<%= render partial: 'qbo_estimates/form', locals: { form: @form } %> <%= render partial: 'qbo_drafts/editor_notice', locals: { draft: @draft, drafts: @customer_drafts } %>
<%= render partial: 'qbo_estimates/form', locals: { form: @form, draft: @draft } %>
+6
View File
@@ -1,9 +1,15 @@
<% html_title "#{l(:label_invoice)} ##{@form.doc_number}" %> <% html_title "#{l(:label_invoice)} ##{@form.doc_number}" %>
<div class="contextual"> <div class="contextual">
<%# Plugins add invoice actions here (e.g. redmine_qbo_labels' Print label) %>
<%= call_hook :view_qbo_invoice_contextual, { invoice_id: @form.id, customer_id: @form.customer_id, doc_number: @form.doc_number } %>
<% if RedmineQboBilling.payment_receiver? && @form.balance.to_d > 0 %> <% 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' %> <%= link_to sprite_icon('add', l(:button_receive_payment)), new_qbo_payment_path(customer_id: @form.customer_id), class: 'icon icon-add' %>
<% end %> <% 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 %> <%= 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? %> <% 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), <%= link_to sprite_icon('email', l(:button_email_estimate)), send_email_qbo_invoice_path(@form.id, email: @form.email),
+2 -1
View File
@@ -1,5 +1,6 @@
<% html_title l(:label_new_invoice) %> <% html_title l(:label_new_invoice) %>
<%= render partial: 'qbo_estimates/header', locals: { form: @form } %> <%= render partial: 'qbo_estimates/header', locals: { form: @form } %>
<%= render partial: 'qbo_drafts/editor_notice', locals: { draft: @draft, drafts: @customer_drafts } %>
<%= render partial: 'qbo_invoices/open_issues', locals: { customer: (Customer.find_by(id: @form.customer_id) if @form.customer_id.present?) } %> <%= render partial: 'qbo_invoices/open_issues', locals: { customer: (Customer.find_by(id: @form.customer_id) if @form.customer_id.present?) } %>
<%= render partial: 'qbo_estimates/form', locals: { form: @form } %> <%= render partial: 'qbo_estimates/form', locals: { form: @form, draft: @draft } %>
+2
View File
@@ -0,0 +1,2 @@
<%# A saved payment, on the same page as Receive payment %>
<%= render template: 'qbo_payments/new' %>
+3
View File
@@ -56,6 +56,9 @@
<td class="amount"><%= number_to_currency(payment.total) %></td> <td class="amount"><%= number_to_currency(payment.total) %></td>
<td class="amount"><%= unapplied > 0 ? number_to_currency(unapplied) : '' %></td> <td class="amount"><%= unapplied > 0 ? number_to_currency(unapplied) : '' %></td>
<td class="buttons"> <td class="buttons">
<% if RedmineQboBilling.payment_receiver? %>
<%= link_to sprite_icon('edit', l(:button_edit)), edit_qbo_payment_path(payment.id), class: 'icon icon-edit' %>
<% end %>
<%= link_to sprite_icon('application-pdf', l(:button_print_payment)), pdf_qbo_payment_path(payment.id), <%= link_to sprite_icon('application-pdf', l(:button_print_payment)), pdf_qbo_payment_path(payment.id),
class: 'icon icon-pdf', target: :_blank %> class: 'icon icon-pdf', target: :_blank %>
</td> </td>
+30 -8
View File
@@ -1,22 +1,44 @@
<% html_title l(:button_receive_payment) %> <%# Receive payment, and Edit payment (edit.html.erb) for a saved one %>
<% editing = @form.persisted? %>
<% title = editing ? l(:label_edit_payment) : l(:button_receive_payment) %>
<% html_title title %>
<% customer = Customer.find_by(id: @form.customer_id) if @form.customer_id.present? %> <% customer = Customer.find_by(id: @form.customer_id) if @form.customer_id.present? %>
<h2> <h2>
<%= link_to l(:label_customers), customers_path %> &#187; <%= link_to l(:label_customers), customers_path %> &#187;
<% if customer %><%= link_to customer.name, customer_path(customer) %> &#187;<% end %> <% if customer %><%= link_to customer.name, customer_path(customer) %> &#187;<% end %>
<%= l(:button_receive_payment) %> <% if editing %>
<%= link_to l(:label_payments), qbo_payments_path(customer_id: @form.customer_id) %> &#187;
<% end %>
<%= title %>
</h2> </h2>
<%= error_messages_for @form %> <%= error_messages_for @form %>
<%= form_tag qbo_payments_path, id: 'qbo-payment-form', <% if @conflict %>
<p class="warning">
<%= l(:text_payment_reload) %>
<%= link_to l(:button_reload_payment), edit_qbo_payment_path(@form.id) %>
</p>
<% end %>
<% if @form.locked %>
<p class="warning"><%= @form.locked %></p>
<% end %>
<%= form_tag (editing ? qbo_payment_path(@form.id) : qbo_payments_path), method: (editing ? :patch : :post), id: 'qbo-payment-form',
data: { open_invoices_url: open_invoices_qbo_payments_path, none_text: l(:label_no_open_invoices) } do %> data: { open_invoices_url: open_invoices_qbo_payments_path, none_text: l(:label_no_open_invoices) } do %>
<%= hidden_field_tag 'payment[sync_token]', @form.sync_token, id: nil if editing %>
<div class="box tabular"> <div class="box tabular">
<p> <p>
<label for="qbo_payment_customer_name"><%= l(:label_customer) %><span class="required"> *</span></label> <label for="qbo_payment_customer_name"><%= l(:label_customer) %><span class="required"> *</span></label>
<%= text_field_tag 'payment[customer_name]', @form.customer_name, id: 'qbo_payment_customer_name', class: 'customer-name', <%# A saved payment keeps its customer %>
autocomplete: 'off', size: 40, placeholder: l(:label_choose_a_customer), <% if editing %>
data: { autocomplete_url: '/customers/autocomplete' } %> <%= text_field_tag 'payment[customer_name]', @form.customer_name, id: 'qbo_payment_customer_name', size: 40, readonly: true, tabindex: -1 %>
<% else %>
<%= text_field_tag 'payment[customer_name]', @form.customer_name, id: 'qbo_payment_customer_name', class: 'customer-name',
autocomplete: 'off', size: 40, placeholder: l(:label_choose_a_customer),
data: { autocomplete_url: '/customers/autocomplete' } %>
<% end %>
<%= hidden_field_tag 'payment[customer_id]', @form.customer_id, id: 'customer_id' %> <%= hidden_field_tag 'payment[customer_id]', @form.customer_id, id: 'customer_id' %>
</p> </p>
<p> <p>
@@ -94,8 +116,8 @@
</fieldset> </fieldset>
<p> <p>
<%= submit_tag l(:button_save_payment) %> <%= submit_tag l(:button_save_payment) unless @form.locked %>
<%= link_to l(:button_cancel), customer ? customer_path(customer) : home_path %> <%= link_to l(:button_cancel), editing ? qbo_payment_path(@form.id) : (customer ? customer_path(customer) : home_path) %>
</p> </p>
<% end %> <% end %>
+3
View File
@@ -2,6 +2,9 @@
<% method_name = RedmineQboBilling::PaymentWriter.payment_method_name(@payment) %> <% method_name = RedmineQboBilling::PaymentWriter.payment_method_name(@payment) %>
<div class="contextual"> <div class="contextual">
<% if RedmineQboBilling.payment_receiver? %>
<%= link_to sprite_icon('edit', l(:button_edit)), edit_qbo_payment_path(@payment.id), class: 'icon icon-edit' %>
<% end %>
<%= link_to sprite_icon('application-pdf', l(:button_print_payment)), pdf_qbo_payment_path(@payment.id), class: 'icon icon-pdf', target: :_blank %> <%= link_to sprite_icon('application-pdf', l(:button_print_payment)), pdf_qbo_payment_path(@payment.id), class: 'icon icon-pdf', target: :_blank %>
<% if @customer && RedmineQboBilling.payment_receiver? %> <% if @customer && RedmineQboBilling.payment_receiver? %>
<%= link_to sprite_icon('add', l(:button_receive_payment)), new_qbo_payment_path(customer_id: @customer.id), class: 'icon icon-add' %> <%= link_to sprite_icon('add', l(:button_receive_payment)), new_qbo_payment_path(customer_id: @customer.id), class: 'icon icon-add' %>
@@ -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 %>
+137
View File
@@ -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 %> &#187;
<%= link_to @customer.name, customer_path(@customer) %> &#187;
<%= 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 %>
+195
View File
@@ -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 %> &#187;
<%= link_to @customer.name, customer_path(@customer) %> &#187;
<%= link_to l(:label_refund_invoice_number, number: number), edit_qbo_invoice_path(@invoice.id) %> &#187;
<%= 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 %>
+97
View File
@@ -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 %> &#187;
<% if @customer %><%= link_to @customer.name, customer_path(@customer) %> &#187;<% 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>
+61 -2
View File
@@ -2,7 +2,7 @@
<% money = @report.money %> <% money = @report.money %>
<% hours = @report.hours %> <% hours = @report.hours %>
<% ratios = @report.ratios %> <% 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 %> <% max_hours = hours.values.max.to_f %>
<% bar = ->(value, max) { max > 0 ? (value.to_f / max * 100).round(1) : 0 } %> <% bar = ->(value, max) { max > 0 ? (value.to_f / max * 100).round(1) : 0 } %>
<% fmt_hours = ->(h) { format('%.1f', h.to_f) } %> <% fmt_hours = ->(h) { format('%.1f', h.to_f) } %>
@@ -40,7 +40,12 @@
end %> end %>
<% sales_series = chart_series.call([[:estimates, l(:label_report_estimates_written), '#628db6'], <% sales_series = chart_series.call([[:estimates, l(:label_report_estimates_written), '#628db6'],
[:invoices, l(:label_report_invoices_written), '#e8a33d'], [:invoices, l(:label_report_invoices_written), '#e8a33d'],
[:paid, l(:label_report_invoices_paid), '#c0504d'],
[:payments, l(:label_report_payments_received), '#5aa05a']]) %> [: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'], <% hours_series = chart_series.call([[:estimate_hours, l(:label_report_estimate_hours), '#628db6'],
[:issue_hours, l(:label_report_issue_hours), '#9b7fc0'], [:issue_hours, l(:label_report_issue_hours), '#9b7fc0'],
[:invoice_hours, l(:label_report_invoice_hours), '#e8a33d'], [:invoice_hours, l(:label_report_invoice_hours), '#e8a33d'],
@@ -132,7 +137,7 @@
<table class="list qbo-report"> <table class="list qbo-report">
<tbody> <tbody>
<% [[:estimates, l(:label_report_estimates_written)], [:invoices, l(:label_report_invoices_written)], <% [[: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> <tr>
<td class="name"><%= label %> <span class="count">(<%= money[key][:count] %>)</span></td> <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> <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_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> <%= l(:label_report_open_balance) %>: <strong><%= number_to_currency(money[:invoices][:balance]) %></strong>
</p> </p>
<p><em class="info"><%= l(:text_report_without_tax) %></em></p>
</div> </div>
<div class="splitcontentright"> <div class="splitcontentright">
@@ -188,6 +194,7 @@
<th class="month"><%= l(:label_month) %></th> <th class="month"><%= l(:label_month) %></th>
<th><%= l(:label_report_estimates_written) %></th> <th><%= l(:label_report_estimates_written) %></th>
<th><%= l(:label_report_invoices_written) %></th> <th><%= l(:label_report_invoices_written) %></th>
<th><%= l(:label_report_invoices_paid) %></th>
<th><%= l(:label_report_payments_received) %></th> <th><%= l(:label_report_payments_received) %></th>
<th class="hours-start"><%= l(:label_report_estimate_hours) %></th> <th class="hours-start"><%= l(:label_report_estimate_hours) %></th>
<th><%= l(:label_report_issue_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 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[:estimates]) %></td>
<td><%= number_to_currency(row[:invoices]) %></td> <td><%= number_to_currency(row[:invoices]) %></td>
<td><%= number_to_currency(row[:paid]) %></td>
<td><%= number_to_currency(row[:payments]) %></td> <td><%= number_to_currency(row[:payments]) %></td>
<td class="hours-start"><%= fmt_hours.call(row[:estimate_hours]) %></td> <td class="hours-start"><%= fmt_hours.call(row[:estimate_hours]) %></td>
<td><%= fmt_hours.call(row[:issue_hours]) %></td> <td><%= fmt_hours.call(row[:issue_hours]) %></td>
@@ -216,6 +224,7 @@
<td class="month"><strong><%= l(:label_total) %></strong></td> <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[:estimates][:total]) %></strong></td>
<td><strong><%= number_to_currency(money[:invoices][: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><strong><%= number_to_currency(money[:payments][:total]) %></strong></td>
<td class="hours-start"><strong><%= fmt_hours.call(hours[:estimate_hours]) %></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> <td><strong><%= fmt_hours.call(hours[:issue_hours]) %></strong></td>
@@ -226,6 +235,54 @@
</tfoot> </tfoot>
</table> </table>
</div> </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> <p class="info"><%= l(:text_report_notes) %></p>
<style> <style>
@@ -237,6 +294,8 @@
.qbo-bar { height: 14px; border-radius: 2px; min-width: 1px; background: #628db6; } .qbo-bar { height: 14px; border-radius: 2px; min-width: 1px; background: #628db6; }
.qbo-bar-invoices, .qbo-bar-invoice_hours { background: #e8a33d; } .qbo-bar-invoices, .qbo-bar-invoice_hours { background: #e8a33d; }
.qbo-bar-payments, .qbo-bar-spent_hours { background: #5aa05a; } .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-bar-issue_hours { background: #9b7fc0; }
.qbo-report-ratios { margin: 8px 4px; line-height: 1.7; } .qbo-report-ratios { margin: 8px 4px; line-height: 1.7; }
.qbo-report-cpi { margin: 10px 4px 4px; } .qbo-report-cpi { margin: 10px 4px 4px; }
-20
View File
@@ -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;
}
-5
View File
@@ -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 /* 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 */ many links would otherwise crowd each other */
#content .contextual.qbo-under-title { #content .contextual.qbo-under-title {
+219 -28
View File
@@ -11,6 +11,11 @@
# English strings go here for Rails i18n # English strings go here for Rails i18n
# Usage I18n.t(:label) # Usage I18n.t(:label)
en: en:
button_create_estimate_subtasks: "Create subtasks from estimate"
error_estimate_parent_not_found: "Parent task #%{id} wasn't found, or you can't see it."
error_estimate_parent_not_allowed: "You aren't allowed to add subtasks in %{project}."
label_estimate_parent_placeholder: "Optional"
text_estimate_parent_info: "The issues are created as subtasks. They get the parent's customer, and the fields below start from the parent's; any left empty are filled from the parent."
notice_qbo_oauth_state_mismatch: "QuickBooks connection was not completed: the request could not be verified. Please try connecting again." notice_qbo_oauth_state_mismatch: "QuickBooks connection was not completed: the request could not be verified. Please try connecting again."
permission_bill_issues: "Bill issue time to QuickBooks" permission_bill_issues: "Bill issue time to QuickBooks"
permission_share_issues_with_customers: "Share issues with customers" permission_share_issues_with_customers: "Share issues with customers"
@@ -24,14 +29,11 @@ en:
field_invoice: "Invoice" field_invoice: "Invoice"
field_notes: "Notes" field_notes: "Notes"
label_account_balance: "Account Balance" label_account_balance: "Account Balance"
label_actions: "Actions"
label_amount: "Amount" label_amount: "Amount"
label_appointment: "Add Appointment" label_appointment: "Add Appointment"
label_balance_with_jobs: "Balance With Jobs"
label_bill_time: "Bill Time" label_bill_time: "Bill Time"
label_billing_address: "Billing Address" label_billing_address: "Billing Address"
label_billing_enqueued: "Billing has been enqueued for issue" label_billing_enqueued: "Billing has been enqueued for issue"
label_billed_success: "Successfully billed "
label_client_id: "Intuit QBO OAuth2 Client ID" label_client_id: "Intuit QBO OAuth2 Client ID"
label_client_secret: "Intuit QBO OAuth2 Client Secret" label_client_secret: "Intuit QBO OAuth2 Client Secret"
label_closed_issues: "Closed Issues" label_closed_issues: "Closed Issues"
@@ -40,23 +42,17 @@ en:
label_customer_link_expires: "This customer link expires in" label_customer_link_expires: "This customer link expires in"
label_customer: "Customer" label_customer: "Customer"
label_customers: "Customers" label_customers: "Customers"
label_delete: "Delete"
label_deposit_into: "Deposit to Account"
label_details: "Details" label_details: "Details"
label_display_name: "Display Name" label_display_name: "Display Name"
label_door: "Door" label_door: "Door"
label_edit: "Edit"
label_edit_customer: "Edit Customer" label_edit_customer: "Edit Customer"
label_email: "Email" label_email: "Email"
label_error: "Error" label_error: "Error"
label_estimate_404: "Estimate not found"
label_estimate: "Estimate" label_estimate: "Estimate"
label_estimates: "Estimates" label_estimates: "Estimates"
label_hours: "Hours" label_hours: "Hours"
label_invoice_404: "Invoice not found"
label_invoices: "Invoices" label_invoices: "Invoices"
label_last_sync: "Last Sync" label_last_sync: "Last Sync"
label_load_customer: "Load Customer"
label_make: "Make" label_make: "Make"
label_matching: "Matching" label_matching: "Matching"
label_mobile_phone: "Mobile Phone" label_mobile_phone: "Mobile Phone"
@@ -69,13 +65,9 @@ en:
text_customers_best_match: "%{count} best matches, closest first. Click a column to sort them by it instead." 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_estimates: "No Estimates"
label_no_invoices: "No Invoices" 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_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_open_issues: "Open Issues"
label_primary_phone: "Primary Phone" label_primary_phone: "Primary Phone"
label_qbo_sync_success: "Successfully synced to QuickBooks"
label_redmine_qbo: "Redmine QuickBooks"
label_sandbox: "Sandbox" label_sandbox: "Sandbox"
label_search: "Search" label_search: "Search"
label_search_customers: "Search Customers" label_search_customers: "Search Customers"
@@ -92,23 +84,11 @@ en:
notice_billing_error_no_customer: "Cannot bill without an assigned customer." 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_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_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_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_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_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_not_found: "Invoice not found"
notice_invoice_updated: "Invoice updated in QuickBooks"
notice_issue_not_found: "Issue not found" notice_issue_not_found: "Issue not found"
warn_ru_sure: "Are you sure?"
# ---- Billing: estimates, invoices, payments, items and accounts ---- # ---- Billing: estimates, invoices, payments, items and accounts ----
label_billing_settings: "Billing" label_billing_settings: "Billing"
@@ -117,6 +97,10 @@ en:
permission_send_estimates: "Email estimates" permission_send_estimates: "Email estimates"
permission_write_invoices: "Write invoices" permission_write_invoices: "Write invoices"
permission_send_invoices: "Email invoices" 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_create_estimate_issues: "Create issues from estimates"
permission_receive_payments: "Receive payments" permission_receive_payments: "Receive payments"
@@ -130,10 +114,38 @@ en:
button_open_in_quickbooks: "Open in QuickBooks" button_open_in_quickbooks: "Open in QuickBooks"
button_refresh_quickbooks_fields: "Refresh QuickBooks fields" button_refresh_quickbooks_fields: "Refresh QuickBooks fields"
label_qbo_hidden_custom_fields: "Hide QuickBooks custom fields" label_qbo_hidden_custom_fields: "Hide QuickBooks custom fields"
# Estimate and invoice drafts
label_qbo_drafts: "Drafts"
label_qbo_draft_document: "Draft"
label_qbo_draft_lines: "Lines"
label_qbo_draft_saved_by: "Last saved"
label_qbo_estimate_draft: "Estimate draft"
label_qbo_invoice_draft: "Invoice draft"
button_qbo_save_draft: "Save draft"
button_qbo_delete_draft: "Delete draft"
button_qbo_continue_draft: "Continue"
notice_qbo_draft_saved: "Draft saved. It's kept in Redmine only, until you save it to QuickBooks."
notice_qbo_draft_deleted: "Draft deleted."
error_qbo_draft_not_found: "That draft is gone. It may have been finished or deleted."
text_qbo_draft_saved_by: "%{user}, %{age} ago"
text_qbo_editing_draft: "Draft, not in QuickBooks yet. Last saved by %{user}, %{age} ago. Save it to send it to QuickBooks; that deletes the draft."
text_qbo_customer_has_estimate_drafts:
one: "This customer has an estimate draft:"
other: "This customer has %{count} estimate drafts:"
text_qbo_customer_has_invoice_drafts:
one: "This customer has an invoice draft:"
other: "This customer has %{count} invoice drafts:"
text_qbo_draft_link: "%{subtotal}, saved by %{user} %{date}"
text_qbo_drafts_info: "New estimates and invoices saved as drafts. They're kept in Redmine only, so nothing is in QuickBooks (and no deposit is applied to an invoice) until a draft is saved from the editor."
text_qbo_sales_person_field: "filled in with the sales person" text_qbo_sales_person_field: "filled in with the sales person"
text_qbo_hidden_custom_fields: "Ticked fields are left off estimates and invoices. QuickBooks doesn't tell apps which custom fields are inactive, and a field stays on its old estimates after it's turned off, so tick ones you no longer use (e.g. a renamed \"Sales Rep old\"). The sales person goes in the first field shown whose name has \"sales\" or \"rep\" in it." text_qbo_hidden_custom_fields: "Ticked fields are left off estimates and invoices. QuickBooks doesn't tell apps which custom fields are inactive, and a field stays on its old estimates after it's turned off, so tick ones you no longer use (e.g. a renamed \"Sales Rep old\"). The sales person goes in the first field shown whose name has \"sales\" or \"rep\" in it."
button_reload_estimate: "Reload the estimate" button_reload_estimate: "Reload the estimate"
button_save_and_send: "Save and send" button_save_and_send: "Save and send"
# Shown in the action bar while a save is on its way, with the buttons locked
text_qbo_saving: "Saving to QuickBooks…"
text_qbo_saving_and_sending: "Saving and sending…"
text_qbo_saving_draft: "Saving draft…"
error_estimate_changed_in_quickbooks: "This estimate was changed in QuickBooks after you opened it, so it wasn't saved." error_estimate_changed_in_quickbooks: "This estimate was changed in QuickBooks after you opened it, so it wasn't saved."
error_estimate_field_invalid: "%{field} is not valid" error_estimate_field_invalid: "%{field} is not valid"
@@ -152,6 +164,18 @@ en:
label_choose_a_customer: "Choose a customer" label_choose_a_customer: "Choose a customer"
label_customer_email: "Customer email" label_customer_email: "Customer email"
label_discount_from_quickbooks: "Discount" label_discount_from_quickbooks: "Discount"
label_discount_amount: "$"
label_discount_percent: "%"
label_discount_type: "Discount type"
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" label_drag_to_reorder: "Drag to reorder"
label_estimate_date: "Estimate date" label_estimate_date: "Estimate date"
label_estimate_expiration_days: "Estimates expire after (days)" label_estimate_expiration_days: "Estimates expire after (days)"
@@ -203,7 +227,6 @@ en:
label_default_account: "Default Item Income Account" label_default_account: "Default Item Income Account"
label_description: "Description" label_description: "Description"
label_edit_item: "Edit Item" label_edit_item: "Edit Item"
label_item: "Item"
label_item_new: "New Item" label_item_new: "New Item"
label_items: "Items" label_items: "Items"
label_management_and_sync: "Synchronization" label_management_and_sync: "Synchronization"
@@ -217,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_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." text_default_account_info: "New products/services go in this income account; set it on the Accounts page."
label_never_synced: "Never synced" label_never_synced: "Never synced"
label_no: "No"
label_type: "Type" label_type: "Type"
label_yes: "Yes"
error_default_account_not_selected: "Select an account to make it the default." error_default_account_not_selected: "Select an account to make it the default."
notice_default_account_updated: "Default account updated." notice_default_account_updated: "Default account updated."
@@ -245,6 +266,9 @@ en:
label_invoice_date: "Invoice date" label_invoice_date: "Invoice date"
label_invoice_no: "Invoice no." label_invoice_no: "Invoice no."
label_invoice_status_paid: "Paid" 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_partial: "Partially paid"
label_invoice_status_overdue: "Overdue" label_invoice_status_overdue: "Overdue"
label_invoice_status_open: "Open" label_invoice_status_open: "Open"
@@ -274,6 +298,7 @@ en:
label_default_project: "Default project" label_default_project: "Default project"
label_default_tracker: "Default tracker" label_default_tracker: "Default tracker"
label_estimate_issue_fields: "Issue fields" label_estimate_issue_fields: "Issue fields"
label_estimate_issue_dates: "Dates"
label_estimate_issue_settings: "Issues from estimates" label_estimate_issue_settings: "Issues from estimates"
label_estimate_item: "Item" label_estimate_item: "Item"
label_estimate_line_already_created: "Already created" label_estimate_line_already_created: "Already created"
@@ -295,6 +320,12 @@ en:
button_print_payment: "Print" button_print_payment: "Print"
button_receive_payment: "Receive payment" button_receive_payment: "Receive payment"
button_save_payment: "Save payment" button_save_payment: "Save payment"
button_reload_payment: "Reload the payment"
label_edit_payment: "Edit payment"
notice_payment_updated: "Payment of %{amount} updated in QuickBooks"
error_payment_changed_in_quickbooks: "This payment was changed in QuickBooks after this page was opened"
error_payment_not_editable: "This payment also applies %{types}, which can't be shown here. Edit it in QuickBooks."
text_payment_reload: "Reload it to see the changes, then make yours again."
error_payment_amount: "Enter the amount received" error_payment_amount: "Enter the amount received"
error_payment_needs_method: "Choose the payment method" error_payment_needs_method: "Choose the payment method"
error_payment_not_saved: "QuickBooks didn't save the payment" error_payment_not_saved: "QuickBooks didn't save the payment"
@@ -332,6 +363,15 @@ en:
label_report_last_year: "last year" label_report_last_year: "last year"
label_report_estimates_written: "Estimates written" label_report_estimates_written: "Estimates written"
label_report_invoices_written: "Invoices 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_payments_received: "Payments received"
label_report_estimate_hours: "Estimated (estimates)" label_report_estimate_hours: "Estimated (estimates)"
label_report_issue_hours: "Estimated (issues)" label_report_issue_hours: "Estimated (issues)"
@@ -371,3 +411,154 @@ en:
label_activity_payment: "Payment from %{customer}: %{amount}" label_activity_payment: "Payment from %{customer}: %{amount}"
text_activity_invoice_owed: "%{amount} owed" text_activity_invoice_owed: "%{amount} owed"
text_activity_payment_unapplied: "%{amount} not applied to an invoice" 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."
+18 -7
View File
@@ -33,11 +33,7 @@ post 'bill/:id', to: 'qbo#bill', as: :bill
get 'customers/view/:token', to: 'customers#view', as: :view get 'customers/view/:token', to: 'customers#view', as: :view
get 'customers/share/:id', to: 'customers#share', as: :share get 'customers/share/:id', to: 'customers#share', as: :share
#java script routes resources :customers, except: [:destroy] do
get 'filter_estimates_by_customer' => 'customers#filter_estimates_by_customer'
get 'filter_invoices_by_customer' => 'customers#filter_invoices_by_customer'
resources :customers do
collection do collection do
get :autocomplete get :autocomplete
get :sync get :sync
@@ -68,8 +64,23 @@ resources :qbo_invoices, only: [:new, :create, :edit, :update] do
end end
end 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=) # Receive payment pages, and a customer's payments (/qbo_payments?customer_id=)
resources :qbo_payments, only: [:index, :new, :create, :show] do resources :qbo_payments, only: [:index, :new, :create, :show, :edit, :update] do
member do member do
get :pdf get :pdf
end end
@@ -88,7 +99,7 @@ resources :items do
end end
# QuickBooks income accounts # QuickBooks income accounts
resources :accounts do resources :accounts, only: [:index] do
collection do collection do
patch :set_default patch :set_default
get :sync get :sync
+31
View File
@@ -0,0 +1,31 @@
#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.
# Estimate and invoice drafts: what's filled in on the editor, kept in Redmine until it's saved to QuickBooks
class CreateQboDrafts < ActiveRecord::Migration[7.0]
def up
return if table_exists?(:qbo_drafts)
create_table :qbo_drafts do |t|
t.string :document, null: false, limit: 20
t.bigint :customer_id
# Who saved it last
t.integer :user_id
# The editor's fields, as posted (JSON)
t.text :data, size: :medium
t.timestamps
end
add_index :qbo_drafts, [:document, :customer_id]
end
def down
drop_table :qbo_drafts if table_exists?(:qbo_drafts)
end
end
+55
View File
@@ -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
+17
View File
@@ -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
+39
View File
@@ -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
+16 -7
View File
@@ -14,7 +14,7 @@ Redmine::Plugin.register :redmine_qbo do
name 'Redmine QBO plugin' name 'Redmine QBO plugin'
author 'Rick Barrette' author 'Rick Barrette'
description 'A pluging for Redmine to connect with QuickBooks Online: customers, time activities for billable hours when an issue is closed, and estimates, invoices and payments written in Redmine' 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.13' version '2026.11.28'
url 'https://github.com/rickbarrette/redmine_qbo' url 'https://github.com/rickbarrette/redmine_qbo'
author_url 'https://barrettefabrication.com' author_url 'https://barrettefabrication.com'
settings default: {empty: true}, partial: 'qbo/settings' settings default: {empty: true}, partial: 'qbo/settings'
@@ -28,9 +28,8 @@ Redmine::Plugin.register :redmine_qbo do
TimeEntry.safe_attributes :billed TimeEntry.safe_attributes :billed
# Global Permissions # Global Permissions
# autocomplete and the filter_* actions feed the customer, estimate and invoice pickers on issue forms # autocomplete feeds the customer pickers (issue forms, estimates, invoices, payments)
permission :view_customers, { customers: [:index, :show, :autocomplete, permission :view_customers, { customers: [:index, :show, :autocomplete] }, global: true
:filter_estimates_by_customer, :filter_invoices_by_customer] }, global: true
permission :add_customers, { customers: [:new, :create] }, global: true permission :add_customers, { customers: [:new, :create] }, global: true
permission :edit_customers, { customers: [:edit, :update] }, global: true permission :edit_customers, { customers: [:edit, :update] }, global: true
permission :share_issues_with_customers, { customers: [:share] }, global: true permission :share_issues_with_customers, { customers: [:share] }, global: true
@@ -40,15 +39,25 @@ Redmine::Plugin.register :redmine_qbo do
# Billing (global): estimates, invoices, payments, issues from estimates # Billing (global): estimates, invoices, payments, issues from estimates
# customer_info and items feed the customer details and product/service search on the estimate/invoice editor # customer_info and items feed the customer details and product/service search on the estimate/invoice editor
permission :write_estimates, { qbo_estimates: [:new, :create, :edit, :update, :customer_info, :items] }, global: true # 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 :send_estimates, { qbo_estimates: [:send_email] }, global: true
permission :create_estimate_issues, { qbo_estimates: [:issues_preview, :create_issues] }, 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], permission :write_invoices, { qbo_invoices: [:new, :create, :edit, :update, :import_options],
qbo_estimates: [:customer_info, :items] }, global: true qbo_estimates: [:customer_info, :items], qbo_drafts: [:index, :destroy] }, global: true
permission :send_invoices, { qbo_invoices: [:send_email] }, global: true permission :send_invoices, { qbo_invoices: [:send_email] }, global: true
# Unlocking an invoice with a payment applied (on top of Write invoices); see RedmineQboBilling.paid_invoice_editor?
permission :edit_partially_paid_invoices, {}, global: true
permission :edit_paid_invoices, {}, global: true
permission :view_payments, { qbo_payments: [:index, :show, :pdf] }, global: true permission :view_payments, { qbo_payments: [:index, :show, :pdf] }, global: true
permission :receive_payments, { qbo_payments: [:index, :new, :create, :show, :pdf, :open_invoices], permission :receive_payments, { qbo_payments: [:index, :new, :create, :show, :edit, :update, :pdf, :open_invoices],
qbo_estimates: [:customer_info] }, global: true 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 permission :view_business_reports, { qbo_reports: [:index] }, global: true
# The product/service list, accounts and their syncs are admin-only (see ItemsController, AccountsController) # 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 # Load the javascript to support the autocomplete forms
def view_layouts_base_html_head(context = {}) def view_layouts_base_html_head(context = {})
safe_join([ safe_join([
javascript_include_tag( 'application.js', plugin: :redmine_qbo),
javascript_include_tag( 'autocomplete.js', plugin: :redmine_qbo), javascript_include_tag( 'autocomplete.js', plugin: :redmine_qbo),
javascript_include_tag( 'checkbox_controller.js', plugin: :redmine_qbo), javascript_include_tag( 'checkbox_controller.js', plugin: :redmine_qbo),
stylesheet_link_tag( 'autocomplete', plugin: :redmine_qbo) stylesheet_link_tag( 'autocomplete', plugin: :redmine_qbo)
@@ -11,17 +11,45 @@
module RedmineQbo module RedmineQbo
module Patches module Patches
module AttachmentsControllerPatch 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 def self.apply
AttachmentsController.prepend(CustomerTokenAccess)
AttachmentsController.class_eval do 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 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_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 private
@@ -31,30 +59,29 @@ module RedmineQbo
@customer_token = session[:token].present? ? CustomerToken.active.find_by(token: session[:token]) : nil @customer_token = session[:token].present? ? CustomerToken.active.find_by(token: session[:token]) : nil
end 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? def valid_customer_token?
token = @customer_token token = @customer_token
return false unless 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]) attachment = Attachment.find_by(id: params[:id])
return false unless attachment return false unless attachment
# Allow if attachment belongs directly to the Issue case attachment.container_type
if attachment.container_type == 'Issue' && attachment.container_id == token.issue_id when 'Issue'
return true 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 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
-1
View File
@@ -15,7 +15,6 @@ module RedmineQbo
prepended do prepended do
belongs_to :customer belongs_to :customer
belongs_to :customer_token
belongs_to :estimate belongs_to :estimate
has_and_belongs_to_many :invoices has_and_belongs_to_many :invoices
+5 -1
View File
@@ -103,6 +103,9 @@ module RedmineQbo
left << [l(:field_status), issue.status] left << [l(:field_status), issue.status]
left << [l(:field_priority), issue.priority] left << [l(:field_priority), issue.priority]
left << [l(:field_customer), issue.customer&.name] left << [l(:field_customer), issue.customer&.name]
left << [l(:field_estimate), issue.estimate.doc_number] if issue.estimate
invoice_numbers = issue.invoices.map(&:doc_number).compact_blank
left << [invoice_numbers.size > 1 ? l(:label_invoices) : l(:field_invoice), invoice_numbers.join(', ')] if invoice_numbers.any?
left << [l(:field_assigned_to), issue.assigned_to] unless issue.disabled_core_fields.include?(:assigned_to_id) left << [l(:field_assigned_to), issue.assigned_to] unless issue.disabled_core_fields.include?(:assigned_to_id)
log "Calling :pdf_left hook" log "Calling :pdf_left hook"
@@ -322,7 +325,8 @@ module RedmineQbo
if issue.estimate if issue.estimate
e_pdf, _ref = PdfService.new(entity: Estimate).fetch_pdf(doc_ids: [issue.estimate.id]) 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(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 combined.to_pdf
else else
pdf.output pdf.output
+43
View File
@@ -30,6 +30,18 @@ module RedmineQboBilling
# Suggestions for the editor's custom field boxes for a customer, from plugins answering # Suggestions for the editor's custom field boxes for a customer, from plugins answering
# :qbo_billing_field_options, { customer: } => { field_id => [{ value:, label: }, ...] } # :qbo_billing_field_options, { customer: } => { field_id => [{ value:, label: }, ...] }
# (e.g. redmine_qbo_vehicles: the customer's vehicles for its VIN field). Returns { "2" => [...] }. # (e.g. redmine_qbo_vehicles: the customer's vehicles for its VIN field). Returns { "2" => [...] }.
# The shop's name and how customer emails (refund summaries) are sent, from other plugins (e.g.
# redmine_qbo_reminders: its shop name and SMTP server) through :qbo_mail_settings. Each returns any of
# shop_name:, from:, reply_to:, delivery: (options for ActionMailer's mail(), e.g. an SMTP server); blank
# ones fall back to Redmine's own settings.
def self.mail_settings
Redmine::Hook.call_hook(:qbo_mail_settings, {}).select { |result| result.is_a?(Hash) }
.reduce({}) { |merged, result| merged.merge(result.symbolize_keys.compact_blank) }
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not read mail settings from plugins: #{e.message}"
{}
end
def self.field_options(customer) def self.field_options(customer)
return {} unless customer return {} unless customer
@@ -83,16 +95,47 @@ module RedmineQboBilling
user.allowed_to?(:receive_payments, nil, global: true) user.allowed_to?(:receive_payments, nil, global: true)
end 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) # True when the user may see customer payments (receiving them includes seeing them)
def self.payment_viewer?(user = User.current) def self.payment_viewer?(user = User.current)
user.allowed_to?(:view_payments, nil, global: true) || payment_receiver?(user) user.allowed_to?(:view_payments, nil, global: true) || payment_receiver?(user)
end 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 # True when the user may write invoices
def self.invoice_writer?(user = User.current) def self.invoice_writer?(user = User.current)
user.allowed_to?(:write_invoices, nil, global: true) user.allowed_to?(:write_invoices, nil, global: true)
end end
# True when the user may unlock and change an invoice with a payment applied: a paid-off one needs
# "Edit paid invoices", a partly paid one "Edit partially paid invoices" (both on top of "Write invoices")
def self.paid_invoice_editor?(fully_paid, user = User.current)
invoice_writer?(user) &&
user.allowed_to?(fully_paid ? :edit_paid_invoices : :edit_partially_paid_invoices, nil, global: true)
end
# True when the user may email invoices to customers # True when the user may email invoices to customers
def self.invoice_sender?(user = User.current) def self.invoice_sender?(user = User.current)
user.allowed_to?(:send_invoices, nil, global: true) user.allowed_to?(:send_invoices, nil, global: true)
+72 -25
View File
@@ -12,7 +12,9 @@
module RedmineQboBilling module RedmineQboBilling
# Business figures for a date range, from the estimates, invoices and payments cached from QuickBooks and from # Business figures for a date range, from the estimates, invoices and payments cached from QuickBooks and from
# Redmine's issues and spent time: # 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 # 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 # 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 # 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 # 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 DAILY_UP_TO = 14
WEEKLY_UP_TO = 93 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 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 attr_reader :from, :to, :period, :project_ids
@@ -54,8 +57,9 @@ module RedmineQboBilling
nil nil
end end
# data (for tests): { estimates: [[date, total, hours]], invoices: [[date, total, hours, balance]], # data (for tests): { estimates: [[date, total, hours, tax]], invoices: [[date, total, hours, balance, tax]],
# payments: [[date, total]], issues: [[date, estimated_hours]], time_entries: [[date, hours]] } # 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. # 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. # previous_data (for tests): last year's data, like data.
# project_ids: the projects whose issues and spent time count; blank for every project. # project_ids: the projects whose issues and spent time count; blank for every project.
@@ -150,13 +154,45 @@ module RedmineQboBilling
@data ||= load_data @data ||= load_data
end 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 def money
@money ||= { @money ||= MONEY_ROWS.to_h do |key, (source, value)|
estimates: { total: money_sum(data[:estimates], 1), count: data[:estimates].size }, rows = Array(data[source])
invoices: { total: money_sum(data[:invoices], 1), count: data[:invoices].size, balance: money_sum(data[:invoices], 3) }, [key, { total: rows.sum(BigDecimal('0')) { |r| value.call(r) }, count: rows.size }]
payments: { total: money_sum(data[:payments], 1), count: data[:payments].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 end
# { estimate_hours:, issue_hours:, invoice_hours:, spent_hours: } # { estimate_hours:, issue_hours:, invoice_hours:, spent_hours: }
@@ -193,7 +229,8 @@ module RedmineQboBilling
def ratios def ratios
{ {
invoiced_of_estimated: percent(money[:invoices][:total], money[:estimates][:total]), 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]), invoiced_of_spent: percent(hours[:invoice_hours], hours[:spent_hours]),
spent_of_estimated: percent(hours[:spent_hours], hours[:issue_hours]) spent_of_estimated: percent(hours[:spent_hours], hours[:issue_hours])
} }
@@ -208,7 +245,7 @@ module RedmineQboBilling
last = [to, @today].min last = [to, @today].min
last = from if last < from last = from if last < from
while month <= last 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 month = month.next_month
end end
index = rows.index_by { |r| [r[:month].year, r[:month].month] } 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 r[key] += kind == :money ? to_d(row[col]) : row[col].to_f
end end
end end
add.call(data[:estimates], :estimates, 1, :money) MONEY_ROWS.merge(TAX_ROWS).each do |key, (source, value)|
add.call(data[:invoices], :invoices, 1, :money) Array(data[source]).each do |row|
add.call(data[:payments], :payments, 1, :money) 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[:estimates], :estimate_hours, 2, :hours)
add.call(data[:issues], :issue_hours, 1, :hours) add.call(data[:issues], :issue_hours, 1, :hours)
add.call(data[:invoices], :invoice_hours, 2, :hours) add.call(data[:invoices], :invoice_hours, 2, :hours)
@@ -229,27 +269,33 @@ module RedmineQboBilling
end end
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 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 end
private private
# { money key or hours key => [sum per bucket] } for the data, in buckets ([first day, last day] pairs) # { 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) 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| find = lambda do |date|
bucket_list.index { |a, b| date >= a && date <= b } bucket_list.index { |a, b| date >= a && date <= b }
end end
columns = { MONEY_ROWS.merge(TAX_ROWS).each do |key, (source, value)|
estimates: [:estimates, 1], invoices: [:invoices, 1], payments: [:payments, 1], Array(rows[source]).each do |row|
estimate_hours: [:estimates, 2], issue_hours: [:issues, 1], invoice_hours: [:invoices, 2], spent_hours: [:time_entries, 1] 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)| columns.each do |key, (source, col)|
Array(rows[source]).each do |row| Array(rows[source]).each do |row|
i = find.call(row[0]) or next 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
end end
sums.transform_values { |values| values.map { |v| v.round(2) } } 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) time_entries = time_entries.where(project_id: project_ids)
end end
{ {
estimates: Estimate.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours), 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), 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), 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] }, 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) time_entries: time_entries.pluck(:spent_on, :hours)
+6
View File
@@ -75,6 +75,11 @@ module RedmineQboBilling
settings[:custom_txn_numbers] == true settings[:custom_txn_numbers] == true
end end
# Whether QuickBooks has discounts turned on for sales forms (true when its settings couldn't be read)
def discounts_allowed?
settings[:allow_discount] != false
end
# The "default message shown on estimates" from QuickBooks' sales settings # The "default message shown on estimates" from QuickBooks' sales settings
def estimate_message def estimate_message
settings[:estimate_message].to_s settings[:estimate_message].to_s
@@ -113,6 +118,7 @@ module RedmineQboBilling
{ {
custom_fields: merge_fields(parse_custom_fields(forms&.custom_fields), custom_fields_from_estimates), custom_fields: merge_fields(parse_custom_fields(forms&.custom_fields), custom_fields_from_estimates),
custom_txn_numbers: forms&.custom_txn_numbers? == 'true' || forms&.custom_txn_numbers? == true, custom_txn_numbers: forms&.custom_txn_numbers? == 'true' || forms&.custom_txn_numbers? == true,
allow_discount: forms.nil? || forms.allow_discount?.nil? ? nil : forms.allow_discount?.to_s == 'true',
estimate_message: forms&.estimate_message.to_s, estimate_message: forms&.estimate_message.to_s,
invoice_message: forms&.default_customer_message.to_s invoice_message: forms&.default_customer_message.to_s
} }
+51 -2
View File
@@ -92,8 +92,12 @@ module RedmineQboBilling
end end
end end
# due_date is an invoice's; expiration_date an estimate's # due_date is an invoice's; expiration_date an estimate's. The discount is a percent of the subtotal
HEADER_ATTRIBUTES = %i[customer_id customer_name email txn_date expiration_date due_date doc_number customer_memo private_note].freeze # (discount_type "percent") or a dollar amount ("amount"), saved as QuickBooks' discount line.
HEADER_ATTRIBUTES = %i[customer_id customer_name email txn_date expiration_date due_date doc_number customer_memo private_note
discount_type discount_value].freeze
DISCOUNT_TYPES = %w[percent amount].freeze
# "estimate" or "invoice" # "estimate" or "invoice"
attr_writer :document attr_writer :document
@@ -105,8 +109,12 @@ module RedmineQboBilling
# Invoices: estimates whose lines are on this invoice (they're linked and closed when saved) # Invoices: estimates whose lines are on this invoice (they're linked and closed when saved)
:linked_estimate_ids, :linked_estimate_ids,
# Read-only details shown on the editor # Read-only details shown on the editor
# (discount: the discount amount QuickBooks worked out when it was last saved)
:billing_address, :total, :total_tax, :discount, :email_status, :txn_status, :duplicated_from, :billing_address, :total, :total_tax, :discount, :email_status, :txn_status, :duplicated_from,
:balance, :converted_from, :balance, :converted_from,
# 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], ...]) # Estimates: the invoices it's billed on ([[id, number], ...])
:invoiced_on, :invoiced_on,
# nil, :bundles (has bundle lines), :linked (an issue is linked to the estimate) or # nil, :bundles (has bundle lines), :linked (an issue is linked to the estimate) or
@@ -117,6 +125,7 @@ module RedmineQboBilling
validate :validate_lines validate :validate_lines
validate :validate_dates validate :validate_dates
validate :validate_email validate :validate_email
validate :validate_discount
# Plugins can block a save (e.g. redmine_qbo_vehicles: one vehicle per invoice); see IssueValues # Plugins can block a save (e.g. redmine_qbo_vehicles: one vehicle per invoice); see IssueValues
validate :validate_with_plugins validate :validate_with_plugins
@@ -193,6 +202,35 @@ module RedmineQboBilling
filled_lines.sum(BigDecimal('0'), &:amount) filled_lines.sum(BigDecimal('0'), &:amount)
end end
def discount_type
DISCOUNT_TYPES.include?(@discount_type.to_s) ? @discount_type.to_s : 'percent'
end
def percent_discount?
discount_type == 'percent'
end
# "10%" reads as 10
def discount_value_number
self.class.decimal(discount_value.to_s.delete('%'))
end
# A discount is given when a value above zero is entered
def discount?
(discount_value_number || 0).positive?
end
# The discount in dollars, as QuickBooks works it out: a percent of the subtotal, rounded to the cent
def discount_amount
return BigDecimal('0') unless discount?
percent_discount? ? (subtotal * discount_value_number / 100).round(2) : discount_value_number.round(2)
end
# Invoices: nothing left owing (a payment covers it all)
def fully_paid?
balance.present? && self.class.decimal(balance).to_d <= 0
end
def sent? def sent?
email_status.to_s == 'EmailSent' email_status.to_s == 'EmailSent'
end end
@@ -240,6 +278,17 @@ module RedmineQboBilling
invalid(:label_due_date) if due_date.present? && due_date_value.nil? invalid(:label_due_date) if due_date.present? && due_date_value.nil?
end end
def validate_discount
return if discount_value.blank?
value = discount_value_number
if value.nil? || value.negative? || (percent_discount? && value > 100)
invalid(:label_discount_from_quickbooks)
elsif discount_amount > subtotal
errors.add(:base, I18n.t(:error_discount_too_large))
end
end
def validate_with_plugins def validate_with_plugins
IssueValues.plugin_errors(self).each { |message| errors.add(:base, message) } IssueValues.plugin_errors(self).each { |message| errors.add(:base, message) }
end end
@@ -17,13 +17,16 @@ module RedmineQboBilling
# - Lines already turned into issues are shown but can't be created again # - Lines already turned into issues are shown but can't be created again
# - Creation is all-or-nothing: if any issue fails validation, none are saved # - Creation is all-or-nothing: if any issue fails validation, none are saved
# - All issues created from the same estimate are related to each other, across batches # - All issues created from the same estimate are related to each other, across batches
# - With a parent issue, the issues are created as its subtasks and take its customer, plus its custom field
# values where the page left them empty (the same rules as the subtask_field_copier plugin, which is used
# when installed). Plugins copy their own fields from the parent in :qbo_billing_build_issue.
# #
# Other plugins fill in more through hooks: # Other plugins fill in more through hooks:
# :qbo_billing_issue_defaults, { estimate:, params: } => a hash of start_date, due_date, assignee, # :qbo_billing_issue_defaults, { estimate:, params:, parent_issue: } => a hash of start_date, due_date,
# description, project, return_path, return_label, plus anything a plugin's own fields need (e.g. # assignee, description, project, return_path, return_label, plus anything a plugin's own fields need.
# redmine_qbo_calendar's vehicle_id, when the page is opened from an appointment) # Every plugin's hash is merged.
# :qbo_billing_build_issue, { issue:, estimate:, defaults: } for each new issue before it's saved, to set # :qbo_billing_build_issue, { issue:, estimate:, defaults:, parent: } for each new issue before it's saved,
# plugins' own fields (e.g. redmine_qbo_vehicles sets the vehicle) # to set plugins' own fields (e.g. redmine_qbo_vehicles sets the vehicle, else the parent's)
# :view_qbo_estimate_issues_form, { estimate:, defaults:, project: } (view hook) draws plugins' fields on # :view_qbo_estimate_issues_form, { estimate:, defaults:, project: } (view hook) draws plugins' fields on
# the page, applied to every issue; posted as issue_plugin_fields[name], they reach :qbo_billing_build_issue # the page, applied to every issue; posted as issue_plugin_fields[name], they reach :qbo_billing_build_issue
# in defaults (e.g. redmine_qbo_vehicles' Vehicle, preselected from the estimate's VIN) # in defaults (e.g. redmine_qbo_vehicles' Vehicle, preselected from the estimate's VIN)
@@ -91,13 +94,15 @@ module RedmineQboBilling
end end
end end
attr_reader :estimate, :defaults, :errors attr_reader :estimate, :defaults, :parent, :errors
# estimate: redmine_qbo's local Estimate (its QuickBooks details give the lines) # estimate: redmine_qbo's local Estimate (its QuickBooks details give the lines)
# defaults: start_date, due_date, assignee, description and plugins' own values (from :qbo_billing_issue_defaults) # defaults: start_date, due_date, assignee, description and plugins' own values (from :qbo_billing_issue_defaults)
def initialize(estimate, defaults: {}) # parent: an issue to create the issues under as subtasks (optional; the caller checks the user may see it)
def initialize(estimate, defaults: {}, parent: nil)
@estimate = estimate @estimate = estimate
@defaults = (defaults || {}).to_h.symbolize_keys @defaults = (defaults || {}).to_h.symbolize_keys
@parent = parent
@errors = [] @errors = []
end end
@@ -190,10 +195,12 @@ module RedmineQboBilling
key.to_s key.to_s
end end
# Relates the new issues to each other and to every issue created earlier from the same estimate. # Relates the new issues to each other and to every issue created earlier from the same estimate,
# except their parent and its ancestors (Redmine doesn't allow relating a subtask to its parent)
def relate_issues(new_issues) def relate_issues(new_issues)
skip_ids = parent ? parent.self_and_ancestors.pluck(:id) : []
earlier = QboEstimateLineIssue.where(estimate_id: estimate.id) earlier = QboEstimateLineIssue.where(estimate_id: estimate.id)
.where.not(issue_id: new_issues.map(&:id)) .where.not(issue_id: new_issues.map(&:id) + skip_ids)
.includes(:issue) .includes(:issue)
.filter_map(&:issue) .filter_map(&:issue)
self.class.relate_all(earlier + new_issues) self.class.relate_all(earlier + new_issues)
@@ -223,15 +230,41 @@ module RedmineQboBilling
assignee = defaults[:assignee] assignee = defaults[:assignee]
issue.assigned_to = assignee if assignee && issue.assignable_users.include?(assignee) issue.assigned_to = assignee if assignee && issue.assignable_users.include?(assignee)
issue.customer_id = estimate.customer_id if issue.respond_to?(:customer_id=) # A subtask belongs to its parent's customer; otherwise the estimate's
if issue.respond_to?(:customer_id=)
issue.customer_id = parent&.customer_id.presence || estimate.customer_id
end
issue.estimate_id = estimate.id if issue.respond_to?(:estimate_id=) issue.estimate_id = estimate.id if issue.respond_to?(:estimate_id=)
# Plugins set their own fields (e.g. redmine_qbo_vehicles: the vehicle) # Plugins set their own fields (e.g. redmine_qbo_vehicles: the vehicle)
Redmine::Hook.call_hook(:qbo_billing_build_issue, { issue: issue, estimate: estimate, defaults: defaults }) Redmine::Hook.call_hook(:qbo_billing_build_issue, { issue: issue, estimate: estimate, defaults: defaults, parent: parent })
if parent
issue.parent_issue_id = parent.id
copy_from_parent(issue, author)
end
issue issue
end end
# Fills the subtask's empty fields from the parent: custom fields (those the author can see on the parent
# and edit on the subtask), and with subtask_field_copier its registered fields. Values entered on the page win.
def copy_from_parent(issue, author)
if defined?(::SubtaskFieldCopier)
::SubtaskFieldCopier.copy_from_parent(issue, parent, author, {})
return
end
parent_values = parent.visible_custom_field_values(author).index_by(&:custom_field_id)
copied = issue.editable_custom_field_values(author).each_with_object({}) do |custom_value, values|
value = parent_values[custom_value.custom_field_id]&.value
next if Array(value).all?(&:blank?) || Array(custom_value.value).any?(&:present?)
values[custom_value.custom_field_id.to_s] = value
end
issue.custom_field_values = copied if copied.any?
end
def default_description def default_description
defaults[:description].presence || defaults[:description].presence ||
"The purpose of this work is to bill the time spent on this issue for Estimate ##{estimate.doc_number}" "The purpose of this work is to bill the time spent on this issue for Estimate ##{estimate.doc_number}"
+71 -15
View File
@@ -13,8 +13,9 @@ module RedmineQboBilling
# #
# Subtotal rows are saved the way QuickBooks saves the subtotals added on its own estimate screen: a # Subtotal rows are saved the way QuickBooks saves the subtotals added on its own estimate screen: a
# description-only line reading "Subtotal: $342.60", which prints where it was placed. The subtotal # description-only line reading "Subtotal: $342.60", which prints where it was placed. The subtotal
# QuickBooks always adds after the last line isn't shown (QuickBooks adds it back). Discount lines are kept # QuickBooks always adds after the last line isn't shown (QuickBooks adds it back). The discount (a percent
# as they are, and estimates with bundle (group) lines are read-only so a bundle can't be broken up. # or an amount) is QuickBooks' discount line after the lines, and estimates with bundle (group) lines are
# read-only so a bundle can't be broken up.
# #
# Estimate numbers are never typed: QuickBooks numbers new estimates, or when its custom transaction # Estimate numbers are never typed: QuickBooks numbers new estimates, or when its custom transaction
# numbers are on, the next number is filled in when the estimate is created. # numbers are on, the next number is filled in when the estimate is created.
@@ -72,8 +73,8 @@ module RedmineQboBilling
save(form, user: user) save(form, user: user)
end end
# A new estimate copied from an existing one: same customer, lines, custom fields and messages, dated today, with a # A new estimate copied from an existing one: same customer, lines, discount, custom fields and messages, dated
# new number, the current user as sales person, and no discounts or bundles (those stay in QuickBooks) # today, with a new number and the current user as sales person (bundles aren't copied)
def duplicate_form(id, user: User.current) def duplicate_form(id, user: User.current)
source = load(id) source = load(id)
today = user.today today = user.today
@@ -88,6 +89,8 @@ module RedmineQboBilling
custom_fields: source.custom_fields.dup, custom_fields: source.custom_fields.dup,
customer_memo: source.customer_memo, customer_memo: source.customer_memo,
private_note: source.private_note, private_note: source.private_note,
discount_type: source.discount_type,
discount_value: source.discount_value,
lines: source.lines.map do |line| lines: source.lines.map do |line|
EstimateForm::Line.new(kind: line.kind, item_id: line.item_id, item_name: line.item_name, EstimateForm::Line.new(kind: line.kind, item_id: line.item_id, item_name: line.item_name,
description: line.description, quantity: line.quantity, rate: line.rate, description: line.description, quantity: line.quantity, rate: line.rate,
@@ -102,6 +105,13 @@ module RedmineQboBilling
Issue.where(estimate_id: estimate_id.to_s) Issue.where(estimate_id: estimate_id.to_s)
end 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 # Loads the estimate from QuickBooks for editing
def load(id) def load(id)
remote = QboEstimateService.with_service { |service| service.fetch_by_id(id) } remote = QboEstimateService.with_service { |service| service.fetch_by_id(id) }
@@ -111,7 +121,9 @@ module RedmineQboBilling
# Creates or updates the estimate in QuickBooks and returns the saved QuickBooks estimate. # 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. # 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) customer = Customer.find_by(id: form.customer_id)
raise Error, I18n.t(:error_estimate_needs_customer) unless customer raise Error, I18n.t(:error_estimate_needs_customer) unless customer
@@ -122,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 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_billed) if billed?(remote)
raise Error, I18n.t(:error_estimate_has_bundles) if group_lines?(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 = Quickbooks::Model::Estimate.new
estimate.id = remote.id estimate.id = remote.id
@@ -258,6 +270,7 @@ module RedmineQboBilling
total: remote.total, total: remote.total,
total_tax: remote.txn_tax_detail&.total_tax, total_tax: remote.txn_tax_detail&.total_tax,
discount: discount_total(remote), discount: discount_total(remote),
**discount_fields(remote),
email_status: remote.email_status.to_s, email_status: remote.email_status.to_s,
txn_status: remote.txn_status.to_s, txn_status: remote.txn_status.to_s,
invoiced_on: Array(remote.linked_transactions).select { |t| t.txn_type.to_s == 'Invoice' }.map { |t| invoiced_on: Array(remote.linked_transactions).select { |t| t.txn_type.to_s == 'Invoice' }.map { |t|
@@ -291,11 +304,17 @@ module RedmineQboBilling
# QuickBooks' own subtotal (always after the last line), discount and group lines aren't edited here # QuickBooks' own subtotal (always after the last line), discount and group lines aren't edited here
end end
# The custom field's value, found by the field QuickBooks' preferences name, or by name on the estimate # The custom field's value on a QuickBooks estimate or invoice ("" when it isn't there)
def custom_value(remote, field, name_pattern = nil) def custom_value(remote, field, name_pattern = nil)
fields = Array(remote.custom_fields) fields = Array(remote.custom_fields)
match = fields.detect { |f| field && f.id.to_i == field.id.to_i } || # The company's field, by id. A document without it has no value: falling back to a similarly named
(name_pattern && fields.detect { |f| f.name.to_s =~ name_pattern }) # field picked up retired ones, e.g. a "Sales Rep old" dropdown, which QuickBooks returns as its option
# number ("4"), and that number was copied onto invoices as the sales person.
return fields.detect { |f| f.id.to_i == field.id.to_i }&.string_value.to_s if field
# The field isn't known (QuickBooks' settings couldn't be read): found by name, never a hidden one
hidden = Company.hidden_field_ids
match = name_pattern && fields.detect { |f| f.name.to_s =~ name_pattern && !hidden.include?(f.id.to_i) }
match&.string_value.to_s match&.string_value.to_s
end end
@@ -319,9 +338,16 @@ module RedmineQboBilling
estimate.private_note = form.private_note.to_s estimate.private_note = form.private_note.to_s
estimate.custom_fields = build_custom_fields(form, remote, user) estimate.custom_fields = build_custom_fields(form, remote, user)
estimate.line_items = build_lines(form, remote) estimate.line_items = build_lines(form, remote)
discount_before_tax(estimate, form)
estimate estimate
end end
# A discount comes off before sales tax: QuickBooks takes the discount from the subtotal, then works out
# the tax on what's left (otherwise it taxes the full amount and discounts after)
def discount_before_tax(document, form)
document.apply_tax_after_discount = true if form.discount?
end
# Keeps every custom field already on the estimate, then sets the ones edited on the form, and the sales # Keeps every custom field already on the estimate, then sets the ones edited on the form, and the sales
# person on create # person on create
# (left empty for estimates made without a user, e.g. by a background job) # (left empty for estimates made without a user, e.g. by a background job)
@@ -365,14 +391,44 @@ module RedmineQboBilling
built built
end end
# Discounts keep their place after the lines # The discount goes after the lines, as on QuickBooks' own screen
Array(remote&.line_items).select(&:discount_item?).each do |discount| discount = discount_line(form, remote, lines.size + 1)
discount.line_num = lines.size + 1 lines << discount if discount
lines << discount
end
lines lines
end end
# QuickBooks' discount line for the form's discount, or nil (taken off before tax, see discount_before_tax). A percent discount is sent as a percent so
# QuickBooks works it out from its own subtotal; the discount account already on the document is kept
# (otherwise QuickBooks uses its default discount account).
def discount_line(form, remote, number)
return nil unless form.discount?
account = Array(remote&.line_items).detect(&:discount_item?)&.discount_line_detail&.discount_account_ref
line = Quickbooks::Model::InvoiceLineItem.new
line.line_num = number
line.amount = form.discount_amount
line.discount_item! do |detail|
detail.percent_based = form.percent_discount?
detail.discount_percent = form.discount_value_number if form.percent_discount?
detail.discount_account_ref = account if account
end
line
end
# The editor's discount fields from a document's discount lines: one percent line stays a percent;
# an amount, or several discount lines, become their total in dollars
def discount_fields(remote)
discounts = Array(remote.line_items).select(&:discount_item?)
return {} if discounts.empty?
detail = discounts.first.discount_line_detail
if discounts.size == 1 && detail&.percent_based?.to_s == 'true' && detail.discount_percent
{ discount_type: 'percent', discount_value: plain_number(detail.discount_percent) }
else
{ discount_type: 'amount', discount_value: plain_number(discount_total(remote)) }
end
end
def build_line(line, number, keep_id:, section_total: BigDecimal('0')) def build_line(line, number, keep_id:, section_total: BigDecimal('0'))
remote = Quickbooks::Model::InvoiceLineItem.new remote = Quickbooks::Model::InvoiceLineItem.new
remote.id = line.id if keep_id remote.id = line.id if keep_id
@@ -443,7 +499,7 @@ module RedmineQboBilling
"Subtotal: #{'-' if value.negative?}$#{whole.reverse.scan(/\d{1,3}/).join(',').reverse}.#{cents}" "Subtotal: #{'-' if value.negative?}$#{whole.reverse.scan(/\d{1,3}/).join(',').reverse}.#{cents}"
end end
# Discount lines aren't edited here but count toward the total shown # What the document's discount lines take off, in dollars
def discount_total(remote) def discount_total(remote)
discounts = Array(remote.line_items).select(&:discount_item?) discounts = Array(remote.line_items).select(&:discount_item?)
discounts.empty? ? nil : discounts.sum(BigDecimal('0')) { |l| l.amount || BigDecimal('0') } discounts.empty? ? nil : discounts.sum(BigDecimal('0')) { |l| l.amount || BigDecimal('0') }
@@ -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
+26 -2
View File
@@ -34,8 +34,32 @@ module RedmineQboBilling
balance < total ? :partial : :open balance < total ? :partial : :open
end end
def label(status) # "Paid", or with the day it was paid in full, "Paid 11/03/2026"
status ? I18n.t("label_invoice_status_#{status}") : '' 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 end
def to_d(value) def to_d(value)
+56 -6
View File
@@ -19,7 +19,9 @@ module RedmineQboBilling
# * billable QuickBooks time activities (the ones redmine_qbo makes from an issue's time entries). Each # * billable QuickBooks time activities (the ones redmine_qbo makes from an issue's time entries). Each
# becomes a line linked to its time activity, so QuickBooks marks the time as billed. # becomes a line linked to its time activity, so QuickBooks marks the time as billed.
# #
# An invoice with a payment applied to it is read-only, so a paid invoice can't be changed under the payment. # An invoice with a payment applied to it is read-only, so a paid invoice isn't changed under the payment by
# accident. It can be unlocked on purpose (e.g. to give a discount after a deposit); the payment stays
# applied, and the total can't go below what's been paid.
module InvoiceWriter module InvoiceWriter
Error = EstimateWriter::Error Error = EstimateWriter::Error
Conflict = EstimateWriter::Conflict Conflict = EstimateWriter::Conflict
@@ -77,6 +79,8 @@ module RedmineQboBilling
# The estimate's writer sells the job; with no one on the estimate, whoever writes the invoice # The estimate's writer sells the job; with no one on the estimate, whoever writes the invoice
form.sales_person = source.sales_person.presence || user.name form.sales_person = source.sales_person.presence || user.name
form.private_note = source.private_note form.private_note = source.private_note
form.discount_type = source.discount_type
form.discount_value = source.discount_value
form.lines = copy_lines(source.lines) form.lines = copy_lines(source.lines)
form.linked_estimate_ids = [source.id.to_s] form.linked_estimate_ids = [source.id.to_s]
form.converted_from = source.doc_number form.converted_from = source.doc_number
@@ -92,7 +96,8 @@ module RedmineQboBilling
# Creates or updates the invoice in QuickBooks, closes the estimates it was made from, and returns the # Creates or updates the invoice in QuickBooks, closes the estimates it was made from, and returns the
# saved QuickBooks invoice. The sales person is the one on the estimate it was made from (the first linked # saved QuickBooks invoice. The sales person is the one on the estimate it was made from (the first linked
# estimate that names one), or else the user who creates it; editing keeps the original one. # estimate that names one), or else the user who creates it; editing keeps the original one.
def save(form, user: User.current) # unlock: a paid invoice may be changed (the user unlocked it), as long as it still covers the payments
def save(form, user: User.current, unlock: false)
customer = Customer.find_by(id: form.customer_id) customer = Customer.find_by(id: form.customer_id)
raise Error, I18n.t(:error_estimate_needs_customer) unless customer raise Error, I18n.t(:error_estimate_needs_customer) unless customer
@@ -102,7 +107,7 @@ module RedmineQboBilling
raise Error, I18n.t(:notice_invoice_not_found) unless remote raise Error, I18n.t(:notice_invoice_not_found) unless remote
raise Conflict, I18n.t(:error_invoice_changed_in_quickbooks) if remote.sync_token.to_s != form.sync_token.to_s raise Conflict, I18n.t(:error_invoice_changed_in_quickbooks) if remote.sync_token.to_s != form.sync_token.to_s
raise Error, I18n.t(:error_invoice_has_bundles) if writer.group_lines?(remote) raise Error, I18n.t(:error_invoice_has_bundles) if writer.group_lines?(remote)
raise Error, I18n.t(:error_invoice_paid) if paid?(remote) check_paid(form, remote, unlock, user)
check_not_billed(form.linked_estimate_ids - linked_ids(remote, ESTIMATE)) check_not_billed(form.linked_estimate_ids - linked_ids(remote, ESTIMATE))
invoice = Quickbooks::Model::Invoice.new invoice = Quickbooks::Model::Invoice.new
@@ -154,7 +159,9 @@ module RedmineQboBilling
total: remote.total, total: remote.total,
total_tax: remote.txn_tax_detail&.total_tax, total_tax: remote.txn_tax_detail&.total_tax,
discount: writer.discount_total(remote), discount: writer.discount_total(remote),
**writer.discount_fields(remote),
balance: remote.balance, balance: remote.balance,
amount_paid: amount_paid(remote),
email_status: remote.email_status.to_s, email_status: remote.email_status.to_s,
locked: (:bundles if writer.group_lines?(remote)) || (:paid if paid?(remote)) locked: (:bundles if writer.group_lines?(remote)) || (:paid if paid?(remote))
) )
@@ -166,6 +173,46 @@ module RedmineQboBilling
BigDecimal(remote.balance.to_s) < BigDecimal(remote.total.to_s) BigDecimal(remote.balance.to_s) < BigDecimal(remote.total.to_s)
end end
# What's been paid on the invoice: its total less its balance
def amount_paid(remote)
return BigDecimal('0') unless paid?(remote)
BigDecimal(remote.total.to_s) - BigDecimal(remote.balance.to_s)
end
# Nothing left owing on it
def fully_paid?(remote)
paid?(remote) && BigDecimal(remote.balance.to_s) <= 0
end
# A paid invoice is only changed when unlocked by a user allowed to (see
# RedmineQboBilling.paid_invoice_editor?), and never to less than what's been paid on it
def check_paid(form, remote, unlock, user)
return unless paid?(remote)
raise Error, I18n.t(:error_invoice_paid) unless unlock
raise Error, I18n.t(:error_invoice_paid_not_allowed) unless RedmineQboBilling.paid_invoice_editor?(fully_paid?(remote), user)
paid = amount_paid(remote)
total = estimated_total(form, remote)
return if total >= paid - BigDecimal('0.005')
raise Error, I18n.t(:error_invoice_below_paid, total: money(total), paid: money(paid))
end
# The invoice's new total, before QuickBooks works out the tax: the lines less the discount, plus the tax
# it had, scaled to the new amount (the same lines give exactly the old total)
def estimated_total(form, remote)
before_tax = form.subtotal - form.discount_amount
old_tax = BigDecimal(remote.txn_tax_detail&.total_tax.to_s.presence || '0')
old_before_tax = BigDecimal(remote.total.to_s) - old_tax
return before_tax if old_tax.zero? || old_before_tax <= 0
(before_tax + old_tax * before_tax / old_before_tax).round(2)
end
def money(amount)
ActiveSupport::NumberHelper.number_to_currency(amount)
end
def linked_ids(remote, type) def linked_ids(remote, type)
Array(remote&.linked_transactions).select { |t| t.txn_type.to_s == type }.map { |t| t.txn_id.to_s }.uniq Array(remote&.linked_transactions).select { |t| t.txn_type.to_s == type }.map { |t| t.txn_id.to_s }.uniq
end end
@@ -188,16 +235,19 @@ module RedmineQboBilling
invoice.private_note = form.private_note.to_s invoice.private_note = form.private_note.to_s
invoice.custom_fields = writer.build_custom_fields(form, remote, user, sales_person: sales_person) invoice.custom_fields = writer.build_custom_fields(form, remote, user, sales_person: sales_person)
invoice.line_items = writer.build_lines(form, remote) invoice.line_items = writer.build_lines(form, remote)
writer.discount_before_tax(invoice, form)
invoice.linked_transactions = header_links(form, remote) invoice.linked_transactions = header_links(form, remote)
invoice invoice
end end
# The invoice-level links: the estimates it was made from, and every time activity a line bills # The invoice-level links: the estimates it was made from, every time activity a line bills (QuickBooks
# (QuickBooks wants time linked both on the line and on the invoice) # wants time linked both on the line and on the invoice), and whatever else QuickBooks linked to it, e.g.
# the payments applied to it (left out, QuickBooks would unlink them)
def header_links(form, remote) def header_links(form, remote)
estimates = (linked_ids(remote, ESTIMATE) + form.linked_estimate_ids).uniq estimates = (linked_ids(remote, ESTIMATE) + form.linked_estimate_ids).uniq
times = form.filled_lines.filter_map(&:time_activity_id).map(&:to_s).uniq times = form.filled_lines.filter_map(&:time_activity_id).map(&:to_s).uniq
estimates.map { |id| link(id, ESTIMATE) } + times.map { |id| link(id, TIME_ACTIVITY) } others = Array(remote&.linked_transactions).reject { |t| [ESTIMATE, TIME_ACTIVITY].include?(t.txn_type.to_s) }
estimates.map { |id| link(id, ESTIMATE) } + times.map { |id| link(id, TIME_ACTIVITY) } + others
end end
def link(id, type) def link(id, type)
+11 -3
View File
@@ -9,8 +9,8 @@
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module RedmineQboBilling module RedmineQboBilling
# What the Receive payment page posts: who paid, how, and how much. PaymentWriter turns it into a # What the Receive payment and Edit payment pages post: who paid, how, and how much. PaymentWriter turns it
# QuickBooks payment, applied to the customer's oldest open invoices first, or kept as a deposit. # into a QuickBooks payment, applied to the customer's oldest open invoices first, or kept as a deposit.
class PaymentForm class PaymentForm
include ActiveModel::Model include ActiveModel::Model
include ActiveModel::Validations include ActiveModel::Validations
@@ -20,16 +20,24 @@ module RedmineQboBilling
attr_accessor(*ATTRIBUTES) attr_accessor(*ATTRIBUTES)
# Invoices ticked on the page: the payment goes on these (oldest first). None ticked: all open invoices. # Invoices ticked on the page: the payment goes on these (oldest first). None ticked: all open invoices.
attr_accessor :invoice_ids attr_accessor :invoice_ids
# A saved payment being edited: its QuickBooks id and sync token, and why it can't be edited here (or nil)
attr_accessor :id, :sync_token, :locked
validate :validate_payment validate :validate_payment
def self.from_params(params) def self.from_params(params, id: nil)
params = params.to_h.stringify_keys params = params.to_h.stringify_keys
new(ATTRIBUTES.to_h { |attr| [attr, params[attr.to_s].to_s.strip] }).tap do |form| new(ATTRIBUTES.to_h { |attr| [attr, params[attr.to_s].to_s.strip] }).tap do |form|
form.invoice_ids = Array(params['invoice_ids']).map(&:to_s).reject(&:blank?).uniq form.invoice_ids = Array(params['invoice_ids']).map(&:to_s).reject(&:blank?).uniq
form.id = id.presence
form.sync_token = params['sync_token'].presence
end end
end end
def persisted?
id.present?
end
def initialize(attributes = {}) def initialize(attributes = {})
super super
self.invoice_ids ||= [] self.invoice_ids ||= []
+124 -28
View File
@@ -12,8 +12,13 @@ module RedmineQboBilling
# Receives customer payments in QuickBooks: payment type and amount, applied to the customer's open # Receives customer payments in QuickBooks: payment type and amount, applied to the customer's open
# invoices oldest first (the way QuickBooks applies them on its own screen), or only to the invoices ticked # invoices oldest first (the way QuickBooks applies them on its own screen), or only to the invoices ticked
# on the page, or saved unapplied as a deposit. Whatever doesn't fit stays unapplied as a credit. # on the page, or saved unapplied as a deposit. Whatever doesn't fit stays unapplied as a credit.
#
# A saved payment can be edited the same way (date, method, reference, memo, amount and the invoices it
# pays); its customer stays. Left as it was, it keeps the amounts it already applied to each invoice.
module PaymentWriter module PaymentWriter
Error = EstimateWriter::Error Error = EstimateWriter::Error
Conflict = EstimateWriter::Conflict
INVOICE = 'Invoice'.freeze
METHODS_CACHE_KEY = 'redmine_qbo_billing:payment_methods' METHODS_CACHE_KEY = 'redmine_qbo_billing:payment_methods'
@@ -39,17 +44,21 @@ module RedmineQboBilling
[] []
end end
# The customer's invoices with a balance, oldest first (by date, then number) # The customer's invoices with a balance, oldest first (by date, then number). For a payment being edited
def open_invoices(customer) # (payment:, the QuickBooks payment), what it paid on each invoice counts as still open, so the invoices it
# pays are listed even when it paid them off.
def open_invoices(customer, payment: nil)
invoices = with_service('Invoice') do |service| invoices = with_service('Invoice') do |service|
service.query("SELECT * FROM Invoice WHERE CustomerRef = '#{customer.id.to_i}' ORDERBY TxnDate", per_page: 1000).entries service.query("SELECT * FROM Invoice WHERE CustomerRef = '#{customer.id.to_i}' ORDERBY TxnDate", per_page: 1000).entries
end end
paid_here = payment ? applied_amounts(payment) : {}
Array(invoices).select { |i| BigDecimal(i.balance.to_s.presence || '0') > 0 } Array(invoices).map { |i| [i, BigDecimal(i.balance.to_s.presence || '0') + paid_here.fetch(i.id.to_s, 0)] }
.sort_by { |i| [i.txn_date || Date.new(1900), i.doc_number.to_s.rjust(12, '0')] } .select { |_, balance| balance > 0 }
.map do |i| .sort_by { |i, _| [i.txn_date || Date.new(1900), i.doc_number.to_s.rjust(12, '0')] }
.map do |i, balance|
{ id: i.id.to_s, doc_number: i.doc_number.to_s, date: i.txn_date.to_s, due_date: i.due_date.to_s, { id: i.id.to_s, doc_number: i.doc_number.to_s, date: i.txn_date.to_s, due_date: i.due_date.to_s,
total: i.total.to_s, balance: BigDecimal(i.balance.to_s).to_s('F') } total: i.total.to_s, balance: balance.to_s('F') }
end end
end end
@@ -67,45 +76,132 @@ module RedmineQboBilling
[applied, left] [applied, left]
end end
# Creates the payment in QuickBooks and returns it. Open invoices are read again here, so the payment # Creates the payment in QuickBooks (or updates the one being edited) and returns it. Open invoices are
# goes on what's open right now. # read again here, so the payment goes on what's open right now.
def save(form) def save(form)
return update(form) if form.persisted?
customer = Customer.find_by(id: form.customer_id) customer = Customer.find_by(id: form.customer_id)
raise Error, I18n.t(:error_estimate_needs_customer) unless customer raise Error, I18n.t(:error_estimate_needs_customer) unless customer
amount = form.amount_value.round(2) amount = form.amount_value.round(2)
applied = applied = allocation(form, customer, amount)
if form.deposit?
[]
else
invoices = open_invoices(customer)
invoices = invoices.select { |i| form.invoice_ids.include?(i[:id]) } if form.invoice_ids.any?
allocate(amount, invoices).first
end
payment = Quickbooks::Model::Payment.new payment = Quickbooks::Model::Payment.new
payment.customer_id = customer.id payment.customer_id = customer.id
payment.txn_date = form.txn_date_value fill(payment, form, amount, applied)
payment.payment_method_ref = Quickbooks::Model::BaseReference.new(form.payment_method_id) payment.payment_ref_number = nil if form.reference.blank?
payment.payment_ref_number = form.reference if form.reference.present? payment.private_note = nil if form.memo.blank?
payment.private_note = form.memo if form.memo.present?
payment.total = amount
payment.line_items = applied.map do |invoice, take|
line = Quickbooks::Model::Line.new
line.amount = take
line.invoice_id = invoice[:id]
line
end
saved = with_service('Payment') { |service| service.create(payment) } saved = with_service('Payment') { |service| service.create(payment) }
raise Error, I18n.t(:error_payment_not_saved) unless saved raise Error, I18n.t(:error_payment_not_saved) unless saved
# Invoice balances changed: update the local invoices, and cache the payment for reports # Invoice balances changed: update the local invoices, and cache the payment for reports
applied.each { |invoice, _| sync_invoice(invoice[:id]) } applied.each { |invoice_id, _| sync_invoice(invoice_id) }
sync_payment(saved.id) sync_payment(saved.id)
saved saved
end end
# A saved payment on the Edit payment page
def load_form(id)
payment = load(id)
applied = applied_amounts(payment)
PaymentForm.new(
id: payment.id.to_s,
sync_token: payment.sync_token.to_s,
customer_id: payment.customer_ref&.value.to_s,
customer_name: payment.customer_ref&.name.presence || Customer.find_by(id: payment.customer_ref&.value)&.name,
txn_date: payment.txn_date&.iso8601,
payment_method_id: payment.payment_method_ref&.value.to_s,
reference: payment.payment_ref_number.to_s,
amount: BigDecimal(payment.total.to_s).round(2).to_s('F'),
deposit: applied.empty? ? '1' : '0',
memo: payment.private_note.to_s,
invoice_ids: applied.keys,
locked: edit_blocked(payment)
)
end
# Saves the changes to a payment. Its customer stays. If the amount and the ticked invoices are the
# same as before, each invoice keeps the amount it had; otherwise the amount is spread again, oldest first.
def update(form)
applied = nil
previously = []
saved = with_service('Payment') do |service|
remote = service.fetch_by_id(form.id)
raise Error, I18n.t(:notice_payment_not_found) unless remote
raise Conflict, I18n.t(:error_payment_changed_in_quickbooks) if remote.sync_token.to_s != form.sync_token.to_s
blocked = edit_blocked(remote)
raise Error, blocked if blocked
customer = Customer.find_by(id: remote.customer_ref&.value)
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
amount = form.amount_value.round(2)
before = applied_amounts(remote)
applied =
if !form.deposit? && before.any? && amount == BigDecimal(remote.total.to_s) && form.invoice_ids.sort == before.keys.sort
before.to_a
else
allocation(form, customer, amount, payment: remote)
end
previously = before.keys
payment = Quickbooks::Model::Payment.new
payment.id = remote.id
payment.sync_token = remote.sync_token
payment.customer_ref = remote.customer_ref
fill(payment, form, amount, applied)
service.update(payment, sparse: true)
end
raise Error, I18n.t(:error_payment_not_saved) unless saved
# Balances changed on the invoices it paid before and the ones it pays now
(previously + applied.map(&:first)).uniq.each { |invoice_id| sync_invoice(invoice_id) }
sync_payment(saved.id)
saved
end
# Where the payment goes: [[invoice_id, amount], ...] (nothing for a deposit)
def allocation(form, customer, amount, payment: nil)
return [] if form.deposit?
invoices = open_invoices(customer, payment: payment)
invoices = invoices.select { |i| form.invoice_ids.include?(i[:id]) } if form.invoice_ids.any?
allocate(amount, invoices).first.map { |invoice, take| [invoice[:id], take] }
end
# The form's details on a QuickBooks payment, applied as given ([[invoice_id, amount], ...])
def fill(payment, form, amount, applied)
payment.txn_date = form.txn_date_value
payment.payment_method_ref = Quickbooks::Model::BaseReference.new(form.payment_method_id)
payment.payment_ref_number = form.reference.to_s
payment.private_note = form.memo.to_s
payment.total = amount
payment.line_items = applied.map do |invoice_id, take|
line = Quickbooks::Model::Line.new
line.amount = take
line.invoice_id = invoice_id
line
end
payment
end
# Why a payment can't be edited here, or nil: it also applies credit memos or other transactions, which
# this page doesn't show (saving would drop them)
def edit_blocked(payment)
others = Array(payment.line_items).flat_map { |line| Array(line.linked_transactions) }
.reject { |t| t.txn_type.to_s == INVOICE }
others.any? ? I18n.t(:error_payment_not_editable, types: others.map { |t| t.txn_type.to_s }.uniq.join(', ')) : nil
end
# What the payment pays on each invoice: { invoice_id => amount }
def applied_amounts(payment)
applied_invoices(payment).each_with_object(Hash.new(BigDecimal('0'))) do |(invoice_id, _, amount), sums|
sums[invoice_id] += BigDecimal(amount.to_s.presence || '0')
end.to_h
end
# Every payment the customer has made, newest first (by date, then QuickBooks id), read from QuickBooks # Every payment the customer has made, newest first (by date, then QuickBooks id), read from QuickBooks
def customer_payments(customer) def customer_payments(customer)
payments = with_service('Payment') do |service| payments = with_service('Payment') do |service|
+59
View File
@@ -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
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more