Compare commits

..
72 Commits
Author SHA1 Message Date
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
ricky a1fb88e77c 2026.11.13 2026-11-04 10:07:54 -05:00
rickyandClaude Opus 5.5 0a7b2e34b8 Fix the settings page before QuickBooks is connected
The token expiry came back as "never synced" text, which the page treated as a
time, so it failed. It's now empty, shown as N/A.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:07:54 -05:00
rickyandClaude Opus 5.5 895733f534 Let admins hide QuickBooks custom fields from 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 an inactive "Sales Rep old" kept showing
and was filled in with the sales person. The billing settings now list the fields
found, with a box to hide each; hidden fields are left out of the editor, the sales
person and other plugins' field lookups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:07:54 -05:00
ricky fa1b4eed06 2026.11.12 2026-11-04 09:47:36 -05:00
rickyandClaude Opus 5.5 95e76a41fd Use QuickBooks' newer custom fields once estimates show them
QuickBooks keeps listing the legacy sales form fields (DefinitionIds 1-3) in the
preferences after a company moves to its newer custom fields, often renamed or inactive
(e.g. "Sales Rep old"). Once estimates show any newer field, only those are used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:47:36 -05:00
ricky 92b2a18eb6 2026.11.11 2026-11-03 22:12:47 -05:00
rickyandClaude Opus 5.5 084df36061 Link the Customer column in issue lists to the customer
Only for users with View customers, who can open the customer page; others see
the name as plain text. CSV and PDF exports are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 22:12:47 -05:00
rickyandClaude Opus 5.5 3b51625df4 Fix sorting and grouping time entries by Billed
The time entry Billed column sorted by time_entries.name, which doesn't exist, so
sorting or grouping by it failed. The issue list's Billed column is removed: issues
have no billed value, so showing or sorting it always failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 22:12:47 -05:00
ricky 7cfc8a370e 2026.11.10 2026-11-03 21:53:13 -05:00
rickyandClaude Opus 5.5 d2cdd798cd Show names in issue history, and record invoices the webhook attaches
The history showed the customer and estimate as id numbers. It now shows their names,
for existing entries too. When the QuickBooks webhook attaches an invoice to an issue,
the issue's history gets "Invoice 1042 added", linking to the invoice PDF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 21:53:13 -05:00
rickyandClaude Opus 5.5 159420fac1 Show estimate, invoice and payment activity on the activity page
Each type appears only on the overall activity page, and only for users who may see it:
estimates need View customers or Write estimates, invoices View customers or Write invoices,
and payments View or Receive payments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 21:53:13 -05:00
rickyandClaude Opus 5.5 dbee228cdf 2026.11.9
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:22:51 -05:00
rickyandClaude Opus 5.5 ec00684edd Clear all lines asks in redmine_dark_mode's dialog when it's installed
On dark pages the confirmation is dark instead of the browser's bright box; without redmine_dark_mode
it's the browser's box as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:22:51 -05:00
rickyandClaude Opus 5.5 839ac976e6 2026.11.8
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 21:52:41 -05:00
rickyandClaude Opus 5.5 dc72b11766 Business report charts take their colours from the page
The grid lines and labels read --qbo-chart-grid and --qbo-chart-text (Chart.js' own colours when
unset), and recolour on redmine_dark_mode's redmine:color-scheme event, so the charts get lighter
grid lines in dark mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 21:52:41 -05:00
rickyandClaude Opus 5.5 778111825b 2026.11.7
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:56:49 -05:00
rickyandClaude Opus 5.5 4ba96e2dfd Warn about the customer's open issues on a new invoice
A new invoice lists the customer's open issues (any project, those the user can see) in a warning under
the title, so work orders aren't left open once the work is billed. It's there when the page opens with a
customer (from the customer page or an estimate) and follows the customer when it's changed: customer_info
returns open_issues_html for invoices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:55:14 -05:00
ricky 88160a985d 2026.11.6 2026-11-01 17:47:43 -05:00
rickyandClaude Opus 5.5 e2a871b1e8 Customer page: Customers » name trail, actions under it, Open in QuickBooks
- The title is a trail back to the customer list, like Redmine's pages, instead of "Customer #id - name"
- The action links sit on their own line under the title (qbo-under-title, also used by
  redmine_qbo_vehicles), so a long name and the many actions don't crowd each other
- Open in QuickBooks joins the action links, as on the payments, invoice and estimate pages, in place of
  the name linking to QuickBooks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:47:19 -05:00
rickyandClaude Opus 5.5 489edd97fa Customers page lists every customer, paged by Redmine instead of will_paginate
- The Customers page shows all customers without a search: a Redmine list with name, phone, mobile,
  issue count and last update, sortable by column, with Redmine's pagination and per-page choices
- Search works as before (best matches first, a single match opens the customer); clicking a column
  sorts the matches by it instead, and Clear goes back to everyone
- New Customer and Sync move to the page's action links
- will_paginate removed from the Gemfile and init.rb; redmine_qbo_vehicles 2026.11.3 no longer needs it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:47:19 -05:00
rickyandClaude Opus 5.5 64e4a149ab Business report: only open projects in the project filter
Closed and archived projects aren't listed. A saved project that has since closed is dropped from the
filter (and from "Opens with"), so the report never filters by a project the picker can't show.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:02:24 -05:00
ricky 6a638fe7bb 2026.11.5 2026-11-01 16:45:52 -05:00
rickyandClaude Opus 5.5 51159d5034 Business report: project filter, remembered per user
- Projects picker (project tree, visible projects only) limits issues' estimated time and spent time
  to the chosen projects, in the totals, charts, last-year lines and months; none picked is every project
- Estimates, invoices and payments have no project in QuickBooks, so they stay whole-business; the page
  says so while filtered (the CPI's invoiced hours included)
- "Remember these projects" saves the choice in the user's Redmine preferences; the report opens with it
  when the address has no projects, and saving none goes back to every project

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:44:03 -05:00
Claude 8f2cef2bc8 Business report: week periods and line charts with last-year comparison
- This week and last week periods; weeks start on Redmine's "Start calendars on" day
- Sales and Hours line charts above the bars, same figures and colors, drawn with
  Redmine's bundled Chart.js: a point per day (a week), week (up to ~3 months) or month
- "Compare with last year" toggle adds dashed, faded last-year lines instantly and is
  kept in the URL; days/weeks go back 52 weeks so weekdays line up, months to the same month
- Legend: one entry per figure (hides both years' lines) plus a single "last year" entry

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 21:58:58 -04:00
Claude bd29ec2978 Imported time replaces its own line, not one block at the first
Importing time with "Replace these lines" put all the time where the first ticked line was and removed the
others, so ticking several lines jumbled the invoice (time out of order, subtotals over the wrong lines).
Each time entry now takes the place of one ticked line: the one whose description is its issue's subject
(issues created from an estimate are named after the line: "Install #134: Install Lift Kit" replaces
"Install Lift Kit"), then any others in order. Extra time goes after the last replaced line; extra ticked
lines are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 18:05:01 -04:00
rickyandClaude Opus 5.5 b1ad2d5b40 2026.11.4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 14:17:15 -04:00
Claude 03af3457ab Show invoice statuses
Invoices get a status badge on the customer page's invoice list and the invoice page: Paid, Partially
paid, Overdue, Open or Voided (zero total), worked out from the total, balance and due date like
QuickBooks' invoice list (RedmineQboBilling::InvoiceStatus; QuickBooks keeps no status on invoices).
The list uses the cached balance and due date; the invoice page uses QuickBooks' current figures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 14:10:11 -04:00
Claude 0d35cffb83 Cost performance index on the business report
CPI = invoiced hours / spent hours, for the period and for each month, colour-coded: green at 1.00 or
more, yellow below 1, red below 0.80. It replaces the invoiced-vs-spent percentage (the same figure).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 13:51:19 -04:00
rickyandClaude Opus 5.5 e348042fef 2026.11.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 13:17:51 -04:00
Claude 846fcad292 Keep the description selected after Tab in every browser
Browsers like Safari and Firefox place the cursor in a textarea after its focus event, undoing the
selection, so Tab from the product into the description left the cursor at the start. The box is now
selected on focus, once more after the browser has placed its cursor, and again on the Tab key's release,
each only while nothing has been typed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 13:11:01 -04:00
Claude d91e80199e Subtotal from the keyboard: sub, subtotal or = in a product box
Typing sub, subtotal or = in a line's product box, then Tab or Enter, adds a subtotal there: an otherwise
empty line becomes the subtotal; a line with a description, quantity or rate keeps them and gets the
subtotal after it. The next line's product box gets the focus. Lines with a product are left alone.
Tabbing into a box now selects its text right away, so the first key typed already replaces it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 13:06:03 -04:00
Claude d054b0d872 Math in the amount box
Arithmetic typed into a line's amount (e.g. 300*1.1) is rounded to the nearest penny and sets the rate from
the quantity, as a typed amount already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:59:11 -04:00
Claude 632d81b98b Math in the rate and quantity boxes
Typing arithmetic into a line's rate or quantity (33*1.3, (120+15)/2; + - * /, x for times, parentheses)
works it out when leaving the box, and before saving; the amount updates while typing. Math in the rate is
rounded to the nearest penny, half up and exactly (1.005 -> 1.01). It's parsed, never run as code; broken
math is left as typed. A click right after a Tab no longer selects the box's text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:58:30 -04:00
Claude 331a2d1da7 Keyboard estimate entry: Tab picks the product; Tab selects the text
- In a line's product box, Tab picks the product the typed text points to: an exact name, else the only
  match, else the only name starting with it ("lab" -> Labor). Tabbing before the search comes back
  fills the line when it does; ambiguous text is left as typed; an item highlighted in the list still wins.
- Tabbing into a line's description, quantity or rate selects its text so typing replaces it (a click
  still places the cursor).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:56:49 -04:00
Claude 66d96c9e4c Send an estimate's lines with status changes
QuickBooks refused the Accepted update with "At least 1 line item is required": a sparse estimate update
still needs its lines. Status changes (Accepted when issues are created, Closed when an invoice is saved)
now go through EstimateWriter.status_update, which sends the estimate's lines back exactly as QuickBooks
returned them, so nothing else changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:47:09 -04:00
Claude 6ac0e27cb2 Report when an estimate can't be marked Accepted; show every status on the estimate page
- Accepting sends Accepted by (the customer) with the accepted date, as QuickBooks' own Accept does, and
  checks what QuickBooks returns. If it keeps the old status or refuses, the Create issues page shows a
  warning with QuickBooks' message instead of only logging it.
- The estimate page's header shows the status badge for every status, Pending included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:43:17 -04:00
Claude 338b4db237 Mark an estimate Accepted when issues are created from it
Creating issues from an estimate means the work is going ahead, so a pending estimate becomes Accepted in
QuickBooks (sparse update with today's accepted date, like closing an estimate) and the local estimate is
synced, so its status badge updates. Accepted, Closed, Converted and Rejected estimates are left alone. A
failure is logged and doesn't affect the created issues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:36:05 -04:00
rickyandClaude Opus 5.5 ec6fecbd85 Show each estimate's status on the customer page
The estimate lists (customer page, and redmine_qbo_vehicles' vehicle page) show the QuickBooks status
badge (Pending, Accepted, Closed, Converted, Rejected) after the date. It's the status the estimate
sync already caches, kept current by the webhook. The badge styles are shared with the estimate
page's header (qbo_estimates/_status_styles).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:32:31 -04:00
rickyandClaude Opus 5.5 09e88232b0 2026.11.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:11:36 -04:00
Claude 6f40308029 Fix migration 050 on MySQL; add the estimate status column
- 050 wrote the kept rows' times back with their zone offset ('2026-10-31 10:06:08 -0400'), which MySQL
  refuses; dates and times are now written with Rails' quoted_date. Each record's delete and re-insert
  run in one transaction, so a failure can't leave it deleted.
- 051 adds estimates.txn_status for databases that ran migration 047 before that column was added to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 11:52:32 -04:00
Claude b739b84917 Fix duplicate estimates: make QuickBooks ids unique
The customers, employees, estimates and invoices tables were created with
t.integer :id, options: 'PRIMARY KEY', which Rails ignores, so the QuickBooks id was never unique. Two
syncs of the same record at once (saving an estimate in Redmine, then QuickBooks' webhook) inserted it
twice, so it showed twice on the customer page and counted twice on the business report.

- Migration 050 keeps one row per id (the most recently updated) and adds a unique index on id.
- A sync that collides with another one's insert retries once as an update.
- Estimates, customers and employees validate a unique id, like invoices already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 11:48:23 -04:00
Claude 388ac915d7 Handle QuickBooks custom fields generically; no vehicle code left
redmine_qbo now works the same for any business; vehicle behaviour lives in redmine_qbo_vehicles.

- Every enabled QuickBooks text custom field gets a box on the estimate/invoice editor (the sales person
  is still filled in automatically). Forms keep custom_fields { field_id => value } instead of vin and
  mileage; Duplicate and Create invoice copy them all.
- Company: custom_field_matching(pattern) and editable_custom_fields; the VIN and Mileage name patterns
  are gone.
- Hooks are keyed by custom field id: qbo_billing_field_options (box suggestions) and
  qbo_billing_field_defaults (values for a document's work orders) replace the VIN hooks;
  qbo_billing_issue_values returns { field_id => { issue_id => value } }.
- Editor script API for plugins: window.qboEditor, the qbo:customer-changed and qbo:imported events, and
  the view_qbo_estimate_form_bottom hook to add a script. The VIN/mileage filling and the several-vehicle
  warning moved to redmine_qbo_vehicles.
- EstimateWriter.create_estimate(custom_fields:), custom_field_value and custom_field_values replace
  the vin/mileage arguments and vin_for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 11:34:10 -04:00
Claude cb705d9525 Blank VIN on new documents; VIN from attached estimates; read estimate VINs with newer custom fields
- New estimates and invoices start with a blank VIN; picking a customer only fills the VIN box's
  suggestions.
- Importing an estimate whose work orders give no VIN fills the invoice's VIN box with the estimate's
  own VIN (open estimates now carry it).
- EstimateWriter.vin_for reads an estimate's VIN with QuickBooks' newer custom fields (cached a minute).
  The local Estimate's details leave those out, so plugins matching the estimate's VIN to a vehicle
  never found one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 10:52:39 -04:00
Claude abeb0fe0f5 Let plugins add fields to the Create issues from estimate page
View hook view_qbo_estimate_issues_form draws plugins' fields in the shared Issue fields box; values
posted as issue_plugin_fields[name] override the plugin defaults and reach qbo_billing_build_issue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 10:25:03 -04:00
Claude b84f39afce Fill the VIN on new estimates and invoices through a hook
New hook qbo_billing_default_vin, { customer:, issues: }: a blank estimate or invoice starts with the VIN
a plugin gives for the customer, and an invoice made from an estimate without a VIN gets the one for the
estimate's work orders. The editor only filled the VIN when the customer was changed or work orders were
imported, so pages opened with the customer already set started blank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 10:17:25 -04:00
Claude 28538d4c7f Show when a QuickBooks sync is running
Syncs record their state in a new qbo_sync_statuses table: queued when asked for, running with how
many records have been read, removed when finished (stale rows are ignored after 6 hours). The
business report says when estimates, invoices or payments are still syncing and refreshes every 30
seconds until they finish; the settings page's Synchronization table shows the same per type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 10:03:12 -04:00
Claude bf7c7b0905 Sync services and other items without a description or rate
QuickBooks only requires an item's name, but the local Item required a description and a rate, so
services such as Labor (often with neither) failed validation and were silently skipped by the sync.
Name is now the only requirement; a missing description syncs as blank and a missing rate as 0.
Product/service pickers and the labor setting list sellable items only (no Categories or Bundles).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 09:34:22 -04:00
Claude 06a78ebccb Move vehicle code out to redmine_qbo_vehicles
- IssueMileageListener removed: redmine_qbo_vehicles answers qbo_billing_issue_values with mileage.
- New hook qbo_billing_build_issue sets plugins' fields on issues created from an estimate; the vehicle
  lookup by VIN moved to redmine_qbo_vehicles.
- New hook qbo_billing_vin_options gives the VIN box's suggestions (RedmineQboBilling.vin_options)
  instead of reading customer.vehicles.
- The customer page's New issue link script is generic: any checkbox with
  data-new-issue-param="issue[field]" fills that field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 09:12:52 -04:00
Claude 3304fce92f Make billed estimates read-only
An estimate that's Converted or Closed in QuickBooks, or linked to an invoice, opens read-only and is
refused on save (this includes redmine_qbo_lineitems' estimates once invoiced). Its page lists the
invoices it's on. Estimates cache their status so lists show View instead of Edit for them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 08:34:41 -04:00
Claude 4732c32409 Combine the labor settings into Labor products/services
The estimate item codes and "Replaced by imported time" become one list of products/services
(RedmineQboBilling::LaborItems), used to create issues from an estimate's labor lines (and an
appointment's minimum hours), to offer an invoice's labor lines to be replaced by imported time, and
to total the hours on estimates and invoices for the business report. While none are chosen,
products/services named Labor are used. The old settings and redmine_qbo_calendar's fallbacks are no
longer read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 08:22:32 -04:00
Claude 616ee13725 Tidy the plugin settings page
- Three sections: QuickBooks connection, Synchronization and Billing.
- Synchronization is one table of every synced type (customers, employees, estimates, invoices,
  payments, items, accounts) with its count, last sync and a Sync link, plus Sync changes and Full sync.
  The separate billing stats and management boxes are folded into it.
- New payments sync (admin only).
- Sync links return to the page they were clicked on instead of the home page.
- Remove locale strings nothing uses any more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 08:11:27 -04:00
Claude 062ef9b8b3 Cache totals, man-hours and payments; add a business report
- Estimates now keep their total; estimates and invoices keep their man-hours: the quantities of the
  products/services set as "Replaced by imported time" (bundles included; the estimate item codes
  while that setting is blank). Filled in by the webhook and the sync.
- Payment model (QboBaseModel) caching each payment's customer, date, amount and unapplied amount,
  kept current by the webhook, the sync and the Receive payment page.
- Business report (View business reports permission, top menu): estimates written vs. invoices written
  vs. payments received, and estimated hours on estimates and issues vs. invoiced and spent hours, for
  a period, with a month-by-month breakdown.
- Fix two keyword arguments that defaulted to themselves (QboSyncDispatcher.enque_jobs, PdfService),
  which newer Ruby refuses to parse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 07:54:28 -04:00
116 changed files with 5895 additions and 612 deletions

No files matched your search

-1
View File
@@ -3,7 +3,6 @@ source 'https://rubygems.org'
gem 'quickbooks-ruby' gem 'quickbooks-ruby'
gem 'oauth2' gem 'oauth2'
gem 'roxml' gem 'roxml'
gem 'will_paginate'
gem 'rexml' gem 'rexml'
gem 'combine_pdf' gem 'combine_pdf'
+70 -18
View File
@@ -70,7 +70,9 @@ The plugin provides basic Customer management:
* Create Customers directly from Redmine * Create Customers directly from Redmine
* Search Customers by **name or phone number** * Browse every Customer on the **Customers** page: a Redmine list with phone numbers, issue counts and last update, sortable by column and paged with Redmine's own pagination (and its per-page choices)
* Search Customers by **name or phone number**: the best matches come first (click a column to sort them instead), and a single match opens that Customer
* View and edit Customer information * View and edit Customer information
@@ -93,15 +95,21 @@ Invoices containing an Issue reference (e.g. `#123`) automatically attach to the
Customer records are automatically updated in the local database when changes occur in QuickBooks. Customer records are automatically updated in the local database when changes occur in QuickBooks.
### Estimates, Invoices and Payments
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.
--- ---
## Billing: Estimates, Invoices and Payments ## Billing: Estimates, Invoices and Payments
* **New estimate** from the customer page: Create Estimate opens the Redmine editor. The customer page no longer links to QuickBooks' estimate or payment screens; the customer's name still opens their QuickBooks account page as a fallback. * **New estimate** from the customer page: Create Estimate opens the Redmine editor. The customer page no longer links to QuickBooks' estimate or payment screens; **Open in QuickBooks** opens their QuickBooks account page as a fallback.
* **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.
* **Duplicate** an estimate to start a similar one: same customer, lines, subtotals, VIN and messages, dated today, with the current user as sales person. * **Keyboard entry**: in a line's product box, Tab picks the product the text points to (an exact name, the only match, or the only name starting with it, e.g. "lab" → Labor) and fills the line. Tabbing into the description, quantity or rate selects it, so typing replaces it. The quantity, rate and amount boxes take simple math (e.g. `33*1.3`, `(120+15)/2`; `+ - * /`, `x` for times, parentheses), worked out when you leave the box; math in the rate or amount is rounded to the nearest penny, and an amount sets the rate from the quantity. Typing `sub`, `subtotal` or `=` in a product box, then Tab or Enter, adds a subtotal there (an empty line becomes the subtotal; a line with a description keeps it and gets the subtotal after it) and moves on to the next line.
* **Duplicate** an estimate to start a similar one: same customer, lines, subtotals, custom fields and messages, dated today, with the current user as sales person.
* **Read-only once linked to an issue**: an estimate that an issue is linked to can be viewed, emailed and duplicated, but not changed, so the work doesn't drift from what was quoted. The list shows a View link for these instead of Edit. * **Read-only once linked to an issue**: an estimate that an issue is linked to can be viewed, emailed and duplicated, but not changed, so the work doesn't drift from what was quoted. The list shows a View link for these instead of Edit.
* **Create issues** from an estimate's labor lines (moved here from redmine_qbo_calendar): each line whose item matches an **estimate item code** (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. Opened from an appointment, the issues get the appointment's dates, technician and vehicle. * **Read-only once billed**: an estimate that's Converted or Closed in QuickBooks, or linked to an invoice, can't be changed here either (including redmine_qbo_lineitems' estimates once they're invoiced). Its page lists the invoices it's on; it can still be viewed, emailed and duplicated, and it shows View instead of Edit in lists.
* **Create issues** from an estimate's labor lines (moved here from redmine_qbo_calendar): each line with one of the **labor products/services** (e.g. Labor) becomes an issue with the line's description as subject and its quantity as estimated hours. Pick the project, trackers, templates and shared custom fields first. Lines already turned into issues can't be created twice, and issues from the same estimate are related to each other. Creating issues marks a pending estimate **Accepted** in QuickBooks (dated today), since the work is going ahead; estimates that are already accepted, closed, converted or rejected keep their status. Opened from an appointment, the issues get the appointment's dates, technician and vehicle.
* **Email** the estimate with QuickBooks' own estimate email, with **Save and send** or the Email link. * **Email** the estimate with QuickBooks' own estimate email, with **Save and send** or the Email link.
* The page follows QuickBooks' estimate screen: customer, customer email, billing address, estimate date, expiration date, estimate number, then the product/service lines (#, product/service, description, qty, rate, amount, tax), the message displayed on the estimate, the memo, and the totals. * The page follows QuickBooks' estimate screen: customer, customer email, billing address, estimate date, expiration date, estimate number, then the product/service lines (#, product/service, description, qty, rate, amount, tax), the message displayed on the estimate, the memo, and the totals.
* Lines work like QuickBooks: the product list opens when the box is clicked, picking a product fills in its description, rate and tax, typing an amount works out the rate, a spare empty line is always at the bottom, and lines are reordered by dragging them by the handle. * Lines work like QuickBooks: the product list opens when the box is clicked, picking a product fills in its description, rate and tax, typing an amount works out the rate, a spare empty line is always at the bottom, and lines are reordered by dragging them by the handle.
@@ -111,15 +119,16 @@ Customer records are automatically updated in the local database when changes oc
### Invoices ### Invoices
* **Create invoice** on an estimate's page makes an invoice from it (customer, lines, subtotals, VIN), like QuickBooks' "Create invoice". **Create invoice** on the customer page starts a blank one, and the Edit link next to each invoice on the customer page opens it. * **Create invoice** on an estimate's page makes an invoice from it (customer, lines, subtotals, custom fields), like QuickBooks' "Create invoice". **Create invoice** on the customer page starts a blank one, and the Edit link next to each invoice on the customer page opens it.
* **Import time & estimates** lists the customer's billable QuickBooks time (the time activities redmine_qbo makes from an issue's time entries) and their open estimates (e.g. the ones redmine_qbo_lineitems makes for parts that weren't quoted). * **Import time & estimates** lists the customer's billable QuickBooks time (the time activities redmine_qbo makes from an issue's time entries) and their open estimates (e.g. the ones redmine_qbo_lineitems makes for parts that weren't quoted).
* Tick the time to bill and, under **Replace these lines**, the lines it replaces (e.g. the estimate's labor lines). When products/services are set as **Replaced by imported time** in the plugin settings, only lines with one of them are offered there; with none set, every line is. The time goes where the first ticked line was and the ticked lines are removed, so the invoice reads in the same order. * Tick the time to bill and, under **Replace these lines**, the lines it replaces (e.g. the estimate's labor lines). Only lines with one of the **labor products/services** from the plugin settings are offered there. Each time entry takes the place of one ticked line: the one whose description is its issue's subject (issues created from an estimate are named after the line, so "Install #134: Install Lift Kit" replaces the "Install Lift Kit" line), then any others in order. Extra time goes after the last replaced line and extra ticked lines are removed, so the invoice keeps the estimate's order and subtotals.
* Ticked estimates go right after the time for the same issue: a redmine_qbo_lineitems estimate starting "Added from: Install #116: …" lands after the time for #116, without that note line, since the time line already names the issue. Estimates with no matching time keep the note and go at the end. * Ticked estimates go right after the time for the same issue: a redmine_qbo_lineitems estimate starting "Added from: Install #116: …" lands after the time for #116, without that note line, since the time line already names the issue. Estimates with no matching time keep the note and go at the end.
* **Undo import** puts the lines back until the invoice is saved. * **Undo import** puts the lines back until the invoice is saved.
* **An estimate is billed once**: an estimate that's on an invoice (linked to one, or closed) or was rejected can't be made into an invoice or imported, and its page shows the invoice it's billed on. This is checked against QuickBooks again when the invoice is saved, so an estimate invoiced meanwhile (in another tab, by someone else, or in QuickBooks) stops the save. * **An estimate is billed once**: an estimate that's on an invoice (linked to one, or closed) or was rejected can't be made into an invoice or imported, and its page shows the invoice it's billed on. This is checked against QuickBooks again when the invoice is saved, so an estimate invoiced meanwhile (in another tab, by someone else, or in QuickBooks) stops the save.
* 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.
* **VIN and mileage from the work orders**: the issues behind an invoice are the ones its time lines and lineitems estimates name. When they're imported, the VIN box takes their vehicle's VIN (with redmine_qbo_vehicles) and a **Mileage** box (shown when QuickBooks has a text custom field named like "Mileage") takes the highest value of the issues' Mileage custom field. With redmine_qbo_vehicles, an invoice whose work orders are for more than one vehicle isn't saved. * **Custom fields from the work orders**: the issues behind an invoice are the ones its time lines and lineitems estimates name. Plugins can fill custom fields from them when they're imported, and block a save (e.g. redmine_qbo_vehicles fills the VIN and mileage and allows one vehicle per invoice). On its own, redmine_qbo leaves the boxes as typed.
* **Sales person**: an invoice credits the sales person on the estimate it was made from (the first linked estimate that names one); if none does, the user who writes the invoice. * **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. A paid invoice shows the day it was paid in full (e.g. **Paid 11/03/2026**): the later of its date and the last payment or credit memo applied to it.
* 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
@@ -131,18 +140,45 @@ Customer records are automatically updated in the local database when changes oc
* 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 (through redmine_qbo_reminders' mail settings when that plugin is set up, otherwise Redmine's).
* Each refund has its own page, listed on the customer page: what was refunded and how, with the fee invoice (opened in Redmine), a **PDF** of the refund (QuickBooks has no PDF of a check or an expense), the fee invoice's PDF, and **Email the customer** to send the summary again. If a QuickBooks step fails, the refund stops there and its page says which step and what was already done, to finish in QuickBooks.
* It refunds all of the customer's remaining credit held as unapplied payments. Credit held as credit memos isn't refunded here.
### Business report
**Business report** in the top menu compares, for a period (this or last week, month, quarter or year, or custom dates; weeks start on the day set in Redmine's *Start calendars on* setting, Monday when it follows the language):
* **Sales**: estimates written, invoices written, invoices paid in full (on the day each was paid in full) and payments received (totals and counts), invoiced vs. estimated, collected vs. invoiced, and what's still owed on those invoices. Estimates and invoices are without sales tax (QuickBooks' tax on each is cached with it); payments are as received, so collected vs. invoiced compares them with the invoices' totals with tax.
* **Sales tax**: **tax invoiced**, the sales tax on invoices dated in the period, paid or not (accrual), and **tax collected**, the sales tax on invoices paid in full in the period, counted on the day each was paid in full (cash), each with how many invoices carried tax, a line chart and a month-by-month table. A partly paid invoice's tax counts as collected once it's paid in full. Only invoices are counted: sales receipts, refund receipts and credit memos aren't kept in Redmine, so file sales tax from QuickBooks' *Sales Tax Liability* report.
* **Hours**: estimated hours on estimates, issues' estimated time, invoiced hours on invoices and time spent, with spent vs. estimated, and the **cost performance index** (CPI = invoiced hours ÷ spent hours): green at 1.00 or more, yellow below 1, red below 0.80. Each month shows its CPI too.
* **Charts**: above each set of bars, a line chart of the same figures in the same colors (Chart.js 4.5.1, MIT licensed, bundled with the plugin in assets/javascripts so it doesn't clash with other plugins' copies such as redmine_indicator's Chart.js 2), with a point per day for a week, per week for up to about three months, and per month beyond. Hovering a point shows its figures. **Compare with last year** adds last year's lines, dashed and faded, without reloading: days and weeks go back 52 weeks so weekdays line up, months go back to the same month. Clicking a figure in the legend hides it (and its last-year line); clicking *last year* stops comparing. Today's line stops at today.
* **By month**: every sales and hours figure month by month, with totals (the sales tax has its own table).
* **Projects**: pick one or more open projects (Ctrl/Cmd-click; closed and archived projects aren't listed) to count only their issues' estimated time and spent time, in the totals, charts and months; none picked counts every project. Estimates, invoices and payments have no project in QuickBooks, so they always cover the whole business (as do the CPI's invoiced hours). **Remember these projects** saves the choice in your Redmine preferences, and the report opens with it until you save another (saving none goes back to every project).
Estimates, invoices and payments count by their QuickBooks date; 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
Nothing is configured in Redmine. The plugin reads QuickBooks' sales form settings, and the custom fields on the 20 most recently changed estimates, and finds the fields by name: Nothing is configured in Redmine. The plugin reads QuickBooks' sales form settings, and the custom fields on the 20 most recently changed estimates, and shows them on the estimate/invoice editor:
* A text field whose name contains **VIN** gets the VIN box. The customer's vehicles (from redmine_qbo_vehicles) are offered as choices. * Every enabled **text** custom field gets a box in the editor's header (e.g. "Crew #"), saved to that field. Plugins can suggest values and fill them in (e.g. redmine_qbo_vehicles: the VIN and Mileage fields).
* A text field whose name contains **Sales** or **Rep** (e.g. "Sales Person", "Salesperson", "Sales Rep") gets the name of the Redmine user who creates the estimate. Editing an estimate keeps its sales person. * A text field whose name contains **Sales** or **Rep** (e.g. "Sales Person", "Salesperson", "Sales Rep") gets the name of the Redmine user who creates the estimate. Editing an estimate keeps its sales person.
QuickBooks only shares its first three **text** custom fields with apps; dropdown custom fields can't be read or filled in. If your sales person field is a dropdown, change it to a text field in QuickBooks (Settings → Custom fields). QuickBooks only shares its first three **text** custom fields with apps; dropdown custom fields can't be read or filled in. If your sales person field is a dropdown, change it to a text field in QuickBooks (Settings → Custom fields).
Newer QuickBooks custom fields (made under Settings → Custom fields) aren't listed in QuickBooks' settings, so the plugin asks QuickBooks for all custom fields on estimates and finds them on the most recently changed ones. If a new field isn't found, fill it in on one estimate in QuickBooks, then refresh. Newer QuickBooks custom fields (made under Settings → Custom fields) aren't listed in QuickBooks' settings, so the plugin asks QuickBooks for all custom fields on estimates and finds them on the most recently changed ones. If a new field isn't found, fill it in on one estimate in QuickBooks, then refresh.
The settings are read once an hour (every five minutes while the VIN or sales person field is missing). After adding or renaming a custom field in QuickBooks, an administrator can use **Refresh QuickBooks fields** on the estimate page, which also lists the fields QuickBooks shares. Newer QuickBooks custom fields (e.g. on Advanced and sandbox companies) may not be listed in its settings; they're found once they're filled in on at least one estimate. The settings are read once an hour (every five minutes while no custom fields are found). After adding or renaming a custom field in QuickBooks, an administrator can use **Refresh QuickBooks fields** on the estimate page, which also lists the fields QuickBooks shares. Newer QuickBooks custom fields (e.g. on Advanced and sandbox companies) may not be listed in its settings; they're found once they're filled in on at least one estimate.
Estimate numbers can't be typed. QuickBooks numbers new estimates; when its "Custom transaction numbers" setting is on, the next number is filled in when the estimate is created. The "default message shown on estimates" fills in the message on new estimates. Estimate numbers can't be typed. QuickBooks numbers new estimates; when its "Custom transaction numbers" setting is on, the next number is filled in when the estimate is created. The "default message shown on estimates" fills in the message on new estimates.
@@ -168,14 +204,17 @@ Administration → Items lists the QuickBooks product/service list (synced from
* **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
* **Receive payments**: the Receive payment page, plus everything View payments allows * **Receive payments**: the Receive payment page, plus everything View payments allows
* **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
* **Issue refunds**: the Refund page, refunds and their PDFs
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.
* **Issues from estimates**: the estimate item codes (also an estimate's labor hours, which an appointment's hours can't be less than), the default project and the default tracker. Until saved here, redmine_qbo_calendar's old values 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.
* **Replaced by imported time**: the products/services (e.g. Labor) whose invoice lines time can replace. Only those lines are offered under Replace these lines; leave empty to offer every line. * **Issues from estimates**: the default project and the default tracker.
* Item and account counts, the default income account, and Sync Items / Sync Accounts. * **Refunds**: the restocking fee (SOP-OPS-014: 30%) and the product/service on its invoice (e.g. a "Restocking Fee" service, which sets the income account), the bank accounts refund checks and card refunds come out of (blank: the first bank account), and the status canceled work orders are set to (blank: a closed status named Canceled).
* Item and account counts, the default income account and their syncs are under Synchronization.
3. Writing an estimate 3. Writing an estimate
@@ -196,19 +235,26 @@ Available hooks:
|Type|Hook|Note |Type|Hook|Note
|--|--|--| |--|--|--|
View Hook|:view_customers_show_contextual, { customer: @customer } | Used to add action links to the customer page's top-right action area (return links styled like Redmine's, e.g. `link_to sprite_icon('add', 'Label'), path, class: 'icon icon-add'`). Replaces `customer_actions_top` / `customer_actions_bottom` View Hook|:view_customers_show_contextual, { customer: @customer } | Used to add action links to the customer page's action area, under the title (return links styled like Redmine's, e.g. `link_to sprite_icon('add', 'Label'), path, class: 'icon icon-add'`). Replaces `customer_actions_top` / `customer_actions_bottom`
View Hook|:pdf_left, { issue: issue } | Used to add text to left side of PDF View Hook|:pdf_left, { issue: issue } | Used to add text to left side of PDF
View Hook|:pdf_right, { issue: issue } | Used to add text to right side of PDF View Hook|:pdf_right, { issue: issue } | Used to add text to right side of PDF
View Hook|:show_customer_view_right, { customer: customer } | Used to show partials on right side of customer view View Hook|:show_customer_view_right, { customer: customer } | Used to show partials on right side of customer view
Hook| :qbo_additional_entities | Used to add additional entites to be processed by the WebhookProcessJob Hook| :qbo_additional_entities | Used to add additional entites to be processed by the WebhookProcessJob
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 => { issue_id => value } }` for the work orders behind an invoice, e.g. `{ vin: { 116 => "1C4..." } }` (redmine_qbo_vehicles). Importing time or estimates fills the VIN box when the work orders share one VIN, and the mileage box with the highest mileage (read from the issue custom field named "Mileage") 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`, `vehicle_id`, `project`, `description`, `return_path`, `return_label` for issues created from an estimate (redmine_qbo_calendar, when opened from an appointment) 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_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)
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
View Hook|:view_qbo_estimate_contextual, { estimate_id:, customer_id:, vin:, doc_number: } | Adds links to an estimate page's action area (e.g. redmine_qbo_calendar's Add appointment) Hook|:qbo_billing_field_defaults, { customer:, issues: } | Return `{ field_id => value }` for a document's work orders: used when an invoice is made from an estimate, for the fields it leaves blank. New estimates and invoices start blank (redmine_qbo_vehicles: the work orders' VIN and highest mileage)
Hook|:qbo_billing_field_options, { customer: } | Return `{ field_id => [{ value:, label: }, ...] }` to suggest in the editor's custom field boxes for a customer (redmine_qbo_vehicles: the customer's vehicles for the VIN box)
View|:view_qbo_estimate_form_bottom, { form:, document: } | Add your plugin's script to the estimate/invoice editor. It can use `window.qboEditor` (`field(id)`, `fieldNamed(/name/)`, `setFieldOptions(id, options)`) and listen for `qbo:customer-changed` and `qbo:imported` on the form (redmine_qbo_vehicles fills the VIN and mileage)
View|checkboxes with `data-new-issue-param="issue[field]"` on the customer page | Ticking one adds `issue[field]=value` to the New issue link, one per field (redmine_qbo's estimates, redmine_qbo_vehicles' vehicles)
View 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:, vin:, mileage:, user:)`; 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`.
--- ---
@@ -293,6 +339,12 @@ Administration → Plugins → Configure
Once authentication succeeds, the plugin performs an **initial synchronization**. Once authentication succeeds, the plugin performs an **initial synchronization**.
The settings page has three sections:
* **QuickBooks connection**: client ID and secret, webhook token, sandbox, when the access token expires, and Connect to QuickBooks.
* **Synchronization**: customers, employees, estimates, invoices, payments, products/services (items) and accounts, with how many of each are stored, when each last synced and a **Sync** link for each (it re-reads every record of that type). **Sync changes** reads only what changed since the last sync; **Full sync** re-reads everything. The default income account for new products/services is shown here too.
* **Billing**: estimate expiration, the labor products/services and the issues-from-estimates defaults.
--- ---
# User Mapping # User Mapping
+1 -1
View File
@@ -32,6 +32,6 @@ class AccountsController < ApplicationController
def sync def sync
Account.sync Account.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
end end
@@ -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
+26 -17
View File
@@ -117,13 +117,33 @@ class CustomersController < ApplicationController
@filtered_invoices = Invoice.all.where(customer_id: params[:selected_customer]) @filtered_invoices = Invoice.all.where(customer_id: params[:selected_customer])
end end
# Most matches a search lists (best first)
SEARCH_LIMIT = 200
# Every customer, sortable and paged like Redmine's lists; a search narrows it to the best matches (a single
# match opens that customer). Sorting a search's results by a column replaces the best-first order.
def index def index
if params[:search] sort_init 'name', 'asc'
@customers = CustomerSearchService.call(name: params[:search], limit: 200).paginate(page: params[:page]) sort_update 'name' => "#{Customer.table_name}.name",
if only_one_non_zero?(@customers) 'phone' => "#{Customer.table_name}.phone_number",
redirect_to @customers.first 'mobile' => "#{Customer.table_name}.mobile_phone_number",
end 'updated' => "#{Customer.table_name}.updated_at"
@search = params[:search].to_s.strip
if @search.present?
scope = CustomerSearchService.call(name: @search, limit: SEARCH_LIMIT)
@best_first = params[:sort].blank?
else
scope = Customer.all
end end
scope = scope.reorder(sort_clause).order(:id) unless @best_first
@customer_count = scope.count
return redirect_to(scope.first) if @search.present? && @customer_count == 1
@customer_pages = Paginator.new @customer_count, per_page_option, params['page']
@customers = scope.limit(@customer_pages.per_page).offset(@customer_pages.offset).to_a
@issue_counts = Issue.where(customer_id: @customers.map(&:id)).group(:customer_id).count
end end
def load_issue_data def load_issue_data
@@ -157,17 +177,6 @@ class CustomersController < ApplicationController
end end
end end
def only_one_non_zero?(array)
found_non_zero = false
array.each do |val|
if val != 0
return false if found_non_zero
found_non_zero = true
end
end
found_non_zero
end
def share def share
issue = Issue.visible.find(params[:id]) issue = Issue.visible.find(params[:id])
token = issue.share_token token = issue.share_token
@@ -213,7 +222,7 @@ class CustomersController < ApplicationController
def sync def sync
Customer.sync Customer.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
def update def update
+1 -1
View File
@@ -15,7 +15,7 @@ class EmployeesController < ApplicationController
def sync def sync
Employee.sync Employee.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
private private
+1 -1
View File
@@ -31,7 +31,7 @@ class EstimatesController < ApplicationController
def sync def sync
Estimate.sync Estimate.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
private private
+1 -1
View File
@@ -34,7 +34,7 @@ class InvoicesController < ApplicationController
def sync def sync
Invoice.sync Invoice.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
private private
+2 -2
View File
@@ -23,7 +23,7 @@ class ItemsController < ApplicationController
term = ActiveRecord::Base.sanitize_sql_like(params[:q].to_s) term = ActiveRecord::Base.sanitize_sql_like(params[:q].to_s)
items = Item.where("description LIKE :t OR name LIKE :t OR sku LIKE :t", t: "%#{term}%") items = Item.where("description LIKE :t OR name LIKE :t OR sku LIKE :t", t: "%#{term}%")
.where(active: true) .merge(Item.sellable)
.order(:description) .order(:description)
.limit(20) .limit(20)
@@ -76,7 +76,7 @@ class ItemsController < ApplicationController
def sync def sync
Item.sync Item.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
def update def update
+1 -1
View File
@@ -70,7 +70,7 @@ class QboController < ApplicationController
full_sync = ActiveModel::Type::Boolean.new.cast(params[:full_sync]) full_sync = ActiveModel::Type::Boolean.new.cast(params[:full_sync])
QboSyncDispatcher.sync!(full_sync: full_sync) QboSyncDispatcher.sync!(full_sync: full_sync)
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
# Endpoint to receive QuickBooks webhook notifications. Validates the request and processes the payload to sync relevant data to Redmine. Responds with appropriate HTTP status codes based on success or failure of processing. # Endpoint to receive QuickBooks webhook notifications. Validates the request and processes the payload to sync relevant data to Redmine. Responds with appropriate HTTP status codes based on success or failure of processing.
+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
+111 -14
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,26 +26,34 @@ 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)
@@ -92,11 +101,16 @@ 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 })
# The work is going ahead: a pending estimate becomes Accepted in QuickBooks
accepted = RedmineQboBilling::EstimateWriter.accept(@estimate.id, user: User.current)
flash[:notice] = l(:notice_estimate_issues_created, count: created.size) flash[:notice] = l(:notice_estimate_issues_created, count: created.size)
flash[:notice] += " #{l(:notice_estimate_accepted, number: @estimate.doc_number)}" if accepted.accepted?
flash[:warning] = l(:warning_estimate_not_accepted, number: @estimate.doc_number, message: accepted.message) if accepted.failed?
redirect_to @return_path redirect_to @return_path
else else
# Rebuild the fields so the form keeps what was entered # Rebuild the fields so the form keeps what was entered
@@ -106,26 +120,32 @@ class QboEstimatesController < ApplicationController
end end
end end
# Customer details for the editor when a customer is picked: email, billing address and vehicles (VINs) # Customer details for the editor when a customer is picked: email, billing address and the suggestions
# plugins give for the custom field boxes (RedmineQboBilling.field_options)
def customer_info def customer_info
customer = Customer.find_by(id: params[:customer_id]) customer = Customer.find_by(id: params[:customer_id])
return render(json: {}, status: :not_found) unless customer return render(json: {}, status: :not_found) unless customer
vehicles = customer.respond_to?(:vehicles) ? customer.vehicles.to_a : [] info = {
render json: {
id: customer.id, id: customer.id,
name: customer.name, name: customer.name,
email: RedmineQboBilling::EstimateWriter.customer_email(customer), email: RedmineQboBilling::EstimateWriter.customer_email(customer),
billing_address: RedmineQboBilling::EstimateWriter.customer_address(customer), billing_address: RedmineQboBilling::EstimateWriter.customer_address(customer),
vehicles: vehicles.select { |v| v.vin.present? }.map { |v| { vin: v.vin, name: v.to_s } } field_options: RedmineQboBilling.field_options(customer)
} }
# A new invoice warns about the customer's open issues
if params[:document] == 'invoice'
info[:open_issues_html] = render_to_string(partial: 'qbo_invoices/open_issues', formats: [:html],
locals: { customer: customer })
end
render json: info
end end
# Product/service search for the line table (the QuickBooks item list) # Product/service search for the line table (the QuickBooks item list)
def items def items
term = "%#{ActiveRecord::Base.sanitize_sql_like(params[:q].to_s.strip)}%" term = "%#{ActiveRecord::Base.sanitize_sql_like(params[:q].to_s.strip)}%"
items = Item.where(active: true) items = Item.sellable
.where("name LIKE :t OR sku LIKE :t OR description LIKE :t", t: term) .where("name LIKE :t OR sku LIKE :t OR description LIKE :t", t: term)
.order(:name) .order(:name)
.limit(25) .limit(25)
@@ -155,36 +175,112 @@ class QboEstimatesController < ApplicationController
end end
return render_404 unless @estimate return render_404 unless @estimate
@defaults = issue_defaults load_parent_issue
@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 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
# - vehicle: the parent issue's, else another plugin's (e.g. the appointment's)
# Values posted with the form (the dates, plugins' fields such as redmine_qbo_vehicles' vehicle) win.
def build_defaults
parent_dates = {}
parent_vehicle = {}
if @parent_issue
parent_dates = { start_date: @parent_issue.start_date, due_date: @parent_issue.due_date }.compact
if @parent_issue.respond_to?(:vehicle_id) && @parent_issue.vehicle_id.present?
parent_vehicle = { vehicle_id: @parent_issue.vehicle_id.to_s }
end
end
parent_dates.merge(issue_defaults.compact).merge(parent_vehicle).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
# The first non-empty hash a plugin returns for :qbo_billing_issue_defaults # The first non-empty hash a plugin returns for :qbo_billing_issue_defaults
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, { estimate: @estimate, params: params })
(results.detect { |r| r.is_a?(Hash) && r.any? } || {}).symbolize_keys (results.detect { |r| r.is_a?(Hash) && r.any? } || {}).symbolize_keys
end end
# 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" }
def submitted_plugin_fields
return {} unless request.post?
values = params[:issue_plugin_fields]
values.respond_to?(:to_unsafe_h) ? values.to_unsafe_h.to_h.transform_keys(&:to_sym).transform_values(&:to_s) : {}
end
# The shared custom field values from the preview form: { custom_field_id => value } # The shared custom field values from the preview form: { custom_field_id => value }
def submitted_custom_field_values def submitted_custom_field_values
values = params.dig(:issue, :custom_field_values) values = params.dig(:issue, :custom_field_values)
@@ -195,6 +291,7 @@ class QboEstimatesController < ApplicationController
params.require(:estimate).permit( params.require(:estimate).permit(
:sync_token, :total_tax, :discount, :email_status, :txn_status, :sync_token, :total_tax, :discount, :email_status, :txn_status,
*RedmineQboBilling::EstimateForm::HEADER_ATTRIBUTES, *RedmineQboBilling::EstimateForm::HEADER_ATTRIBUTES,
custom_fields: {},
lines: RedmineQboBilling::EstimateForm::Line::PARAMS lines: RedmineQboBilling::EstimateForm::Line::PARAMS
) )
end end
+35 -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
@@ -94,10 +111,26 @@ class QboInvoicesController < ApplicationController
:sync_token, :total_tax, :discount, :email_status, :txn_status, :balance, :sync_token, :total_tax, :discount, :email_status, :txn_status, :balance,
*RedmineQboBilling::EstimateForm::HEADER_ATTRIBUTES, *RedmineQboBilling::EstimateForm::HEADER_ATTRIBUTES,
linked_estimate_ids: [], linked_estimate_ids: [],
custom_fields: {},
lines: RedmineQboBilling::EstimateForm::Line::PARAMS lines: RedmineQboBilling::EstimateForm::Line::PARAMS
) )
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
+40 -6
View File
@@ -9,14 +9,21 @@
#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 before_action :authorize_global, except: :sync
before_action :require_admin, only: :sync
QBO_ERRORS = QboEstimatesController::QBO_ERRORS QBO_ERRORS = QboEstimatesController::QBO_ERRORS
# Re-reads every payment from QuickBooks into the local cache (admin, from the plugin settings)
def sync
Payment.sync
redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end
# The customer's payments, newest first, read from QuickBooks # The customer's payments, newest first, read from QuickBooks
def index def index
@customer = Customer.find_by(id: params[:customer_id]) @customer = Customer.find_by(id: params[:customer_id])
@@ -49,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)
@@ -79,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)
@@ -93,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)
+108
View File
@@ -0,0 +1,108 @@
#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, 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
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)
@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
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
+62
View File
@@ -0,0 +1,62 @@
#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.
# Business report: estimates and invoices written and payments received, and estimated, invoiced and spent
# hours, for a period (RedmineQboBilling::BusinessReport)
class QboReportsController < ApplicationController
before_action :authorize_global
# The user's preference holding the projects the report opens with
PROJECTS_PREF = :qbo_report_project_ids
def index
# Projects for the issues and spent time: the projects picker can choose some of the open ones
@projects = Project.visible.active.to_a
@project_ids = report_project_ids
@report = RedmineQboBilling::BusinessReport.new(period: params[:period].presence || 'this_year',
from: params[:from], to: params[:to], today: User.current.today,
week_start: RedmineQboBilling::BusinessReport.week_start_from_setting(Setting.start_of_week),
project_ids: @project_ids)
# Last year's lines on the charts
@compare = params[:compare] == '1'
# Syncs still running for what the report counts: its figures are incomplete until they finish
@syncing = QboSyncStatus.by_entity(%w[Estimate Invoice Payment]).values.sort_by(&:entity)
end
private
# The form's projects (none picked is every project), or the user's saved ones when the address has none.
# "Remember these projects" saves the form's choice. Only open projects the user can see are kept.
def report_project_ids
visible = @projects.map(&:id)
if params.key?(:project_ids)
ids = Array(params[:project_ids]).map(&:to_i) & visible
save_project_ids(ids) if params[:save_projects] == '1'
else
ids = saved_project_ids & visible
end
@saved_project_ids = saved_project_ids & visible
ids
end
def saved_project_ids
return [] unless User.current.logged?
Array(User.current.pref[PROJECTS_PREF]).map(&:to_i)
end
def save_project_ids(ids)
return unless User.current.logged?
pref = User.current.pref
pref[PROJECTS_PREF] = ids
pref.save
end
end
+7 -2
View File
@@ -10,9 +10,11 @@
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
].freeze ].freeze
@@ -27,7 +29,7 @@ class QboSyncDispatcher
private private
# Dynamically enques all sync jobs # Dynamically enques all sync jobs
def self.enque_jobs(full_sync: full_sync) def self.enque_jobs(full_sync: false)
jobs = SYNC_JOBS.dup jobs = SYNC_JOBS.dup
# Allow other plugins to add addtional sync jobs via Hooks # Allow other plugins to add addtional sync jobs via Hooks
@@ -39,7 +41,10 @@ class QboSyncDispatcher
end end
end end
jobs.each { |job| QboSyncJob.perform_later(entity: job, full_sync: full_sync) } jobs.each do |job|
QboSyncStatus.queued(job.to_s)
QboSyncJob.perform_later(entity: job, full_sync: full_sync)
end
end end
def self.log(msg) def self.log(msg)
+7 -1
View File
@@ -25,7 +25,13 @@ class QboSyncJob < ApplicationJob
elsif doc_number.present? elsif doc_number.present?
service.sync_by_doc_number(doc_number) service.sync_by_doc_number(doc_number)
else else
service.sync(full_sync: full_sync) # Shown on the business report and the settings page while it runs
QboSyncStatus.running(entity)
begin
service.sync(full_sync: full_sync)
ensure
QboSyncStatus.finished(entity)
end
end end
end end
+1
View File
@@ -17,6 +17,7 @@ class WebhookProcessJob < ActiveJob::Base
Invoice Invoice
Estimate Estimate
Employee Employee
Payment
].freeze ].freeze
# Process incoming QBO webhook notifications and sync relevant data to Redmine # Process incoming QBO webhook notifications and sync relevant data to Redmine
+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
reminders = defined?(RedmineQboReminders::Settings) ? RedmineQboReminders::Settings.current : nil
@shop_name = reminders&.[]('shop_name').to_s.presence || Setting.app_title
delivery = reminders ? reminders.delivery_options : {}
if delivery.empty? && !ActionMailer::Base.perform_deliveries
raise DeliveryOff, I18n.t(:text_refund_email_off)
end
options = { to: email, from: reminders&.from.presence || Setting.mail_from.to_s,
subject: I18n.t(:text_refund_email_subject, shop: @shop_name, amount: RedmineQboBilling::RefundWriter.money(refund.refund_amount)) }
options[:reply_to] = reminders.reply_to if reminders&.reply_to
message = mail(options.merge(delivery)) do |format|
format.text
end
message.perform_deliveries = true unless delivery.empty?
message
end
end
+71
View File
@@ -0,0 +1,71 @@
#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.
# Estimates, invoices and payments on Redmine's activity page. They come from QuickBooks and belong to no
# project, so they show on the overall activity page only (not a project's, nor a user's), and each kind only to
# users with one of its global permissions.
module QboActivity
extend ActiveSupport::Concern
class_methods do
# event_type: the activity type registered in init.rb (e.g. 'qbo_estimates'); icon: the event's CSS class
# and icon in this plugin's sprite (assets/images/icons.svg); permissions: any one of these shows it
def qbo_activity(event_type, icon:, permissions:, title:, description:, url:)
# These models can load before Redmine adds acts_as_event to every model
include Redmine::Acts::Event unless respond_to?(:acts_as_event)
acts_as_event title: title, description: description, url: url, type: icon,
datetime: :activity_datetime, author: nil
class_attribute :qbo_activity_permissions, instance_writer: false, default: permissions
class_attribute :qbo_activity_event_type, instance_writer: false, default: event_type
end
def qbo_activity_visible_to?(user)
qbo_activity_permissions.any? { |permission| user.allowed_to?(permission, nil, global: true) }
end
# What Redmine::Activity::Fetcher reads for a project's activity page; these never show there
def activity_provider_options
{ qbo_activity_event_type => { permission: qbo_activity_permissions.first } }
end
# Documents dated from..to (the page's days, to not included), newest first. From the QuickBooks date, so
# a sync bringing in old documents doesn't pile them onto the day it ran.
def find_events(event_type, user, from, to, options)
return [] if options[:project] || options[:author] || !qbo_activity_visible_to?(user)
scope = includes(:customer).where.not(txn_date: nil)
scope = scope.where('txn_date >= ?', from.to_date) if from
scope = scope.where('txn_date < ?', to.to_date) if to
scope = scope.order(txn_date: :desc, id: :desc).limit(options[:limit]) if options[:limit]
scope.to_a
end
end
# When it happened: the time it reached Redmine when that was its QuickBooks date (created or changed in
# QuickBooks and sent by the webhook moments later), else midday on its QuickBooks date (e.g. a full sync)
def activity_datetime
return created_at if created_at && created_at.getlocal.to_date == txn_date
Time.local(txn_date.year, txn_date.month, txn_date.day, 12)
end
# Activity events have a project; these don't
def project
nil
end
def activity_money(amount)
ActiveSupport::NumberHelper.number_to_currency(amount) if amount
end
def activity_customer
customer&.name.presence || I18n.t(:label_none)
end
end
+2
View File
@@ -16,7 +16,9 @@ class Customer < QboBaseModel
has_many :issues has_many :issues
has_many :invoices has_many :invoices
has_many :estimates has_many :estimates
has_many :payments
validates_presence_of :name validates_presence_of :name
validates :id, uniqueness: true, allow_nil: true
before_validation :normalize_phone_numbers before_validation :normalize_phone_numbers
self.primary_key = :id self.primary_key = :id
qbo_sync push: true qbo_sync push: true
+1
View File
@@ -12,6 +12,7 @@ class Employee < QboBaseModel
has_many :users has_many :users
validates_presence_of :id, :name validates_presence_of :id, :name
validates :id, uniqueness: true
self.primary_key = :id self.primary_key = :id
qbo_sync push: false qbo_sync push: false
+13
View File
@@ -13,13 +13,26 @@ class Estimate < QboBaseModel
has_many :issues has_many :issues
belongs_to :customer belongs_to :customer
validates_presence_of :doc_number, :id validates_presence_of :doc_number, :id
validates :id, uniqueness: true
self.primary_key = :id self.primary_key = :id
qbo_sync push: false qbo_sync push: false
include QboActivity
qbo_activity 'qbo_estimates', icon: 'qbo-estimate', permissions: %i[view_customers write_estimates],
title: ->(e) { I18n.t(:label_activity_estimate, number: e.doc_number, customer: e.activity_customer) },
description: ->(e) { [e.activity_money(e[:total_amount]), e[:txn_status]].compact.join(' · ') },
url: ->(e) { { controller: 'estimates', action: 'show', id: e.id } }
def name def name
to_s to_s
end end
# True once QuickBooks has turned it into an invoice (status cached by the sync). The estimate page also
# checks for a linked invoice; either way a billed estimate can't be changed in Redmine.
def billed?
RedmineQboBilling::EstimateWriter::BILLED_STATUSES.include?(self[:txn_status].to_s)
end
# returns a human readable string # returns a human readable string
def to_s def to_s
return self[:doc_number] return self[:doc_number]
+22
View File
@@ -17,9 +17,31 @@ class Invoice < QboBaseModel
self.primary_key = :id self.primary_key = :id
qbo_sync push: false qbo_sync push: false
include QboActivity
qbo_activity 'qbo_invoices', icon: 'qbo-invoice', permissions: %i[view_customers write_invoices],
title: ->(i) { I18n.t(:label_activity_invoice, number: i.doc_number, customer: i.activity_customer) },
description: ->(i) { i.activity_description },
url: ->(i) { { controller: 'invoices', action: 'show', id: i.id } }
# Return the invoice's document number as its string representation # Return the invoice's document number as its string representation
def to_s def to_s
doc_number doc_number
end end
# Amount and where it stands, e.g. "$1,250.00 · Partially paid ($400.00 owed)"
def activity_description
state = status
owed = activity_money(self[:balance]) if state && self[:balance].to_d.positive?
[activity_money(self[:total_amount]),
(I18n.t(:"label_invoice_status_#{state}", default: state.to_s.humanize) if state),
(I18n.t(:text_activity_invoice_owed, amount: owed) if owed && state != :open && state != :overdue)].compact.join(' · ')
end
# Paid, partially paid, overdue, open or voided, from the cached total, balance and due date
# (RedmineQboBilling::InvoiceStatus); nil when the balance isn't cached
def status(today: User.current.today)
RedmineQboBilling::InvoiceStatus.status(total: self[:total_amount], balance: self[:balance],
due_date: self[:due_date], today: today)
end
end end
+9 -1
View File
@@ -11,8 +11,16 @@
class Item < QboBaseModel class Item < QboBaseModel
belongs_to :account, optional: true belongs_to :account, optional: true
validates_presence_of :id, :description # QuickBooks only requires a name: services such as Labor often have no description or rate
validates_presence_of :id, :name
validates :unit_price, numericality: { greater_than_or_equal_to: 0 } validates :unit_price, numericality: { greater_than_or_equal_to: 0 }
# QuickBooks item types that can't go on an estimate or invoice line themselves
UNSELLABLE_TYPES = %w[Category Group].freeze
# Active products/services that can go on a line (services, non-inventory and inventory items), for the
# pickers and the labor products/services setting
scope :sellable, -> { where(active: true).where.not(type: UNSELLABLE_TYPES).or(where(active: true, type: nil)) }
self.primary_key = :id self.primary_key = :id
self.inheritance_column = :_type_disabled self.inheritance_column = :_type_disabled
qbo_sync push: true qbo_sync push: true
+38
View File
@@ -0,0 +1,38 @@
#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 payment, cached from QuickBooks for reporting: id, customer, date and amount. Kept current by the
# webhook and the sync; payments are received through the Receive payment page (RedmineQboBilling::PaymentWriter).
class Payment < QboBaseModel
belongs_to :customer, optional: true
validates :id, presence: true, uniqueness: true
self.primary_key = :id
qbo_sync push: false
include QboActivity
qbo_activity 'qbo_payments', icon: 'qbo-payment', permissions: %i[view_payments receive_payments],
title: ->(p) { I18n.t(:label_activity_payment, customer: p.activity_customer, amount: p.activity_money(p.total_amount)) },
description: ->(p) { p.activity_description },
url: ->(p) { { controller: 'qbo_payments', action: 'show', id: p.id } }
# Money not yet applied to an invoice, when there is some
def activity_description
return '' unless unapplied_amount.to_d.positive?
I18n.t(:text_activity_payment_unapplied, amount: activity_money(unapplied_amount))
end
def to_s
"#{txn_date} #{total_amount}"
end
end
+3 -2
View File
@@ -23,16 +23,17 @@ class Qbo < ActiveRecord::Base
return I18n.t(:label_qbo_never_synced) return I18n.t(:label_qbo_never_synced)
end end
# Token expiry times, or nil when QuickBooks isn't connected (the settings page shows N/A)
def self.oauth2_access_token_expires_at def self.oauth2_access_token_expires_at
QboConnectionService.current!.oauth2_access_token_expires_at QboConnectionService.current!.oauth2_access_token_expires_at
rescue rescue
return I18n.t(:label_qbo_never_synced) nil
end end
def self.oauth2_refresh_token_expires_at def self.oauth2_refresh_token_expires_at
QboConnectionService.current!.oauth2_refresh_token_expires_at QboConnectionService.current!.oauth2_refresh_token_expires_at
rescue rescue
return I18n.t(:label_qbo_never_synced) nil
end end
# Updates last sync time stamp # Updates last sync time stamp
+1
View File
@@ -70,6 +70,7 @@ class QboBaseModel < ActiveRecord::Base
# Sync all entities, typically triggered by a scheduled task or manual sync request # Sync all entities, typically triggered by a scheduled task or manual sync request
def self.sync def self.sync
QboSyncStatus.queued(model_name.name)
QboSyncJob.perform_later(entity: model_name.name, full_sync: true) QboSyncJob.perform_later(entity: model_name.name, full_sync: true)
end end
+74
View File
@@ -0,0 +1,74 @@
#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)
}
def self.writable_document?(document, user = User.current)
case document.to_s
when 'estimate' then RedmineQboBilling.writer?(user)
when 'invoice' then RedmineQboBilling.invoice_writer?(user)
else false
end
end
# The editor's fields as posted (estimate[...])
def fields
parsed = JSON.parse(data.presence || '{}')
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
+54
View File
@@ -0,0 +1,54 @@
#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
class QboRefund < ApplicationRecord
METHODS = %w[check card].freeze
STATUSES = %w[done incomplete].freeze
belongs_to :customer
belongs_to :user, optional: true
validates :customer_id, presence: true
validates :method, inclusion: { in: METHODS }
validates :status, inclusion: { in: STATUSES }
scope :recent, -> { order(created_at: :desc, id: :desc) }
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
# The QuickBooks screen for the refund check or expense
def purchase_url
return nil if purchase_id.blank?
page = check? ? 'check' : 'expense'
"https://#{RedmineQbo.sandbox_mode? ? 'sandbox' : 'app'}.qbo.intuit.com/app/#{page}?txnId=#{purchase_id}"
end
end
+70
View File
@@ -0,0 +1,70 @@
#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 QuickBooks sync that's queued or running, one row per entity (Invoice, Estimate...), with how many records
# it has processed so far. The row is removed when the sync finishes. Rows not touched for STALE are ignored,
# so a sync that died (e.g. Redmine restarted mid-sync) doesn't leave a notice up forever.
class QboSyncStatus < ActiveRecord::Base
STALE = 6.hours
scope :active, -> { where('updated_at > ?', STALE.ago) }
# A sync was asked for and is waiting for the job to start
def self.queued(entity)
record(entity) { |s| s.state = 'queued' unless s.state == 'running' }
end
# The sync started
def self.running(entity)
record(entity) do |s|
s.state = 'running'
s.processed = 0
s.started_at = Time.now
end
end
# count more records were processed
def self.progress(entity, count)
where(entity: entity.to_s).update_all(['processed = processed + ?, updated_at = ?', count.to_i, Time.now])
rescue StandardError => e
Rails.logger.warn "[QboSyncStatus] #{e.message}"
end
def self.finished(entity)
where(entity: entity.to_s).delete_all
rescue StandardError => e
Rails.logger.warn "[QboSyncStatus] #{e.message}"
end
# Active syncs by entity name: { "Invoice" => QboSyncStatus, ... }, optionally only for some entities
def self.by_entity(entities = nil)
scope = active
scope = scope.where(entity: Array(entities).map(&:to_s)) if entities
scope.index_by(&:entity)
rescue StandardError
{}
end
def self.record(entity)
status = find_or_initialize_by(entity: entity.to_s)
status.state ||= 'queued'
yield status
status.updated_at = Time.now
status.save!
rescue StandardError => e
Rails.logger.warn "[QboSyncStatus] #{e.message}"
end
private_class_method :record
def running?
state == 'running'
end
end
+6
View File
@@ -26,6 +26,12 @@ class EstimateSyncService < SyncServiceBase
end end
map_attributes :doc_number, :txn_date map_attributes :doc_number, :txn_date
map_attribute :total_amount, :total
map_attribute :txn_status
# Man-hours: quantities of the labor products/services (plugin settings)
map_attribute(:hours) { |remote| RedmineQboBilling::ManHours.hours(remote) }
# Sales tax, so the business report can compare estimates and invoices without it
map_attribute(:tax_amount) { |remote| RedmineQboBilling::InvoicePaidOn.tax(remote) }
map_belongs_to :customer map_belongs_to :customer
end end
@@ -27,6 +27,7 @@ class InvoiceAttachmentService
unless issue.invoices.exists?(@invoice.id) unless issue.invoices.exists?(@invoice.id)
issue.invoices << @invoice issue.invoices << @invoice
issue.save! if issue.changed? issue.save! if issue.changed?
journalize(issue)
log "Attached invoice ##{@invoice.id} to issue ##{issue.id}" log "Attached invoice ##{@invoice.id} to issue ##{issue.id}"
end end
end end
@@ -34,6 +35,18 @@ class InvoiceAttachmentService
private private
# Records the new invoice in the issue's history (shown by RedmineQbo::Patches::IssuesHelperPatch).
# The webhook has no Redmine user, so the entry is by Anonymous. Saving the journal also sends
# Redmine's usual issue-updated emails.
def journalize(issue)
journal = Journal.new(journalized: issue, user: User.anonymous, notes: '')
journal.details << JournalDetail.new(property: 'invoice', prop_key: @invoice.id.to_s, value: @invoice.to_s.presence || @invoice.id.to_s)
journal.save
rescue => e
# The invoice is attached either way; a missing history entry shouldn't fail the sync
log "Couldn't add invoice ##{@invoice.id} to the history of issue ##{issue.id}: #{e.message}"
end
# Extract issue IDs from the invoice's private note and line descriptions # Extract issue IDs from the invoice's private note and line descriptions
def extract_issue_ids def extract_issue_ids
ids = [] ids = []
+5
View File
@@ -24,7 +24,12 @@ class InvoiceSyncService < SyncServiceBase
map_attributes :balance, :doc_number, :due_date, :txn_date map_attributes :balance, :doc_number, :due_date, :txn_date
map_attribute :total_amount, :total map_attribute :total_amount, :total
# Man-hours: quantities of the labor products/services (plugin settings)
map_attribute(:hours) { |remote| RedmineQboBilling::ManHours.hours(remote) }
map_attribute :qbo_updated_at, "meta_data.last_updated_time" 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
+5 -1
View File
@@ -30,6 +30,10 @@ class ItemSyncService < SyncServiceBase
account_id = remote.income_account_ref&.value account_id = remote.income_account_ref&.value
account_id.present? ? Account.find_by(id: account_id.to_i) : nil account_id.present? ? Account.find_by(id: account_id.to_i) : nil
end end
map_attributes :description, :id, :name, :sku, :type, :unit_price map_attributes :id, :name, :sku, :type
# Services such as Labor often have no description or rate in QuickBooks; they sync as blank and 0
# instead of failing validation and being skipped
map_attribute(:description) { |remote| remote.description.to_s }
map_attribute(:unit_price) { |remote| remote.unit_price || 0 }
end end
+21
View File
@@ -0,0 +1,21 @@
#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.
# Reads a payment's details from QuickBooks for the Payment model (payments are only cached here, never pushed)
class PaymentService < ServiceBase
private
def build_qbo_remote
Quickbooks::Model::Payment.new
end
end
+32
View File
@@ -0,0 +1,32 @@
#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.
# Caches QuickBooks payments: customer, date, amount and what's still unapplied
class PaymentSyncService < SyncServiceBase
private
# Specify the local model this service syncs
def self.model_class
Payment
end
map_attributes :txn_date
map_attribute :total_amount, :total
map_attribute :unapplied_amount
map_attribute :qbo_updated_at, "meta_data.last_updated_time"
# A payment whose customer hasn't synced yet keeps none until the next sync
map_attribute :customer do |remote|
id = remote.customer_ref&.value
id.present? ? Customer.find_by(id: id) : nil
end
end
+1 -1
View File
@@ -12,7 +12,7 @@ class PdfService
require 'combine_pdf' require 'combine_pdf'
# Subclasses should initialize with a QBO client instance # Subclasses should initialize with a QBO client instance
def initialize(entity: entity) def initialize(entity:)
raise "An entity to sync is required" unless entity raise "An entity to sync is required" unless entity
@entity = entity @entity = entity
end end
+11 -2
View File
@@ -38,6 +38,7 @@ class SyncServiceBase
entries.each do |remote| entries.each do |remote|
persist(remote) persist(remote)
end end
QboSyncStatus.progress(@entity.name, entries.size)
end end
end end
@@ -200,8 +201,10 @@ class SyncServiceBase
Rails.logger.info "[#{@entity.name}SyncService] #{msg}" Rails.logger.info "[#{@entity.name}SyncService] #{msg}"
end end
# Create or update a local entity record based on the QBO remote data # Create or update a local entity record based on the QBO remote data. If another sync inserts the same
def persist(remote) # record at the same moment (e.g. a save in Redmine and QuickBooks' webhook), the database's unique id
# refuses the second insert; it's then retried once as an update of the row the other sync created.
def persist(remote, retried: false)
local = @entity.find_or_initialize_by(id: remote.id) local = @entity.find_or_initialize_by(id: remote.id)
if destroy_local?(remote) if destroy_local?(remote)
@@ -222,6 +225,12 @@ class SyncServiceBase
attach_documents(local, remote) attach_documents(local, remote)
end end
rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid => e
if !retried && (e.is_a?(ActiveRecord::RecordNotUnique) || @entity.exists?(id: remote.id))
log "#{@entity.name} #{remote.id} was saved by another sync meanwhile; updating it instead"
return persist(remote, retried: true)
end
log "Failed to sync #{@entity.name} #{remote.id}: #{e.message}"
rescue => e rescue => e
log "Failed to sync #{@entity.name} #{remote.id}: #{e.message}" log "Failed to sync #{@entity.name} #{remote.id}: #{e.message}"
end end
@@ -1,59 +1,45 @@
<%# <%#
Adds the estimate and vehicle ticked on the customer page to the "New issue" link Adds what's ticked on the customer page to the "New issue" link (#dynamic-new-issue-link in the contextual
(#dynamic-new-issue-link in the contextual area). One of each can be ticked. area). Any checkbox with data-new-issue-param="issue[field]" takes part, one ticked per field: this plugin's
estimates (issue[estimate_id]), and other plugins' lists (e.g. redmine_qbo_vehicles' issue[vehicle_id]).
%> %>
<script> <script>
function handleSingleSelect(event, className) { function newIssueParamBoxes(param) {
if (event.target.checked) { return Array.prototype.filter.call(document.querySelectorAll('input[data-new-issue-param]'), function (cb) {
// Uncheck all other checkboxes of the same type return !param || cb.getAttribute('data-new-issue-param') === param;
document.querySelectorAll('.' + className).forEach(cb => { });
if (cb !== event.target) { }
cb.checked = false;
} // One box per field: ticking one unticks the others for the same field
document.addEventListener('change', function (event) {
var box = event.target;
if (!box.matches || !box.matches('input[data-new-issue-param]')) return;
if (box.checked) {
newIssueParamBoxes(box.getAttribute('data-new-issue-param')).forEach(function (cb) {
if (cb !== box) cb.checked = false;
}); });
} }
updateLink(); updateLink();
}
// Bind single-select behavior to checkboxes once the DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.estimate-checkbox').forEach(cb => {
cb.addEventListener('change', (e) => handleSingleSelect(e, 'estimate-checkbox'));
});
document.querySelectorAll('.vehicle-checkbox').forEach(cb => {
cb.addEventListener('change', (e) => handleSingleSelect(e, 'vehicle-checkbox'));
});
}); });
function updateLink() { function updateLink() {
const link = document.getElementById('dynamic-new-issue-link'); var link = document.getElementById('dynamic-new-issue-link');
if (!link) return; if (!link) return;
// Cache the pristine base URL on first run // Cache the pristine base URL on first run
if (!link.dataset.baseUrl) { if (!link.dataset.baseUrl) link.dataset.baseUrl = link.getAttribute('href');
link.dataset.baseUrl = link.getAttribute('href'); var url = new URL(link.dataset.baseUrl, window.location.origin);
}
// Build base URL object newIssueParamBoxes().forEach(function (cb) {
let url = new URL(link.dataset.baseUrl, window.location.origin); var param = cb.getAttribute('data-new-issue-param');
var ticked = newIssueParamBoxes(param).filter(function (b) { return b.checked; })[0];
if (ticked) {
url.searchParams.set(param, ticked.value);
} else {
url.searchParams.delete(param);
}
});
// 1. Handle Single Estimate
const checkedEstimate = document.querySelector('.estimate-checkbox:checked');
if (checkedEstimate) {
url.searchParams.set('issue[estimate_id]', checkedEstimate.value);
} else {
url.searchParams.delete('issue[estimate_id]');
}
// 2. Handle Single Vehicle
const checkedVehicle = document.querySelector('.vehicle-checkbox:checked');
if (checkedVehicle) {
url.searchParams.set('issue[vehicle_id]', checkedVehicle.value);
} else {
url.searchParams.delete('issue[vehicle_id]');
}
// Update the link's href attribute
link.setAttribute('href', url.toString()); link.setAttribute('href', url.toString());
} }
</script> </script>
+66 -19
View File
@@ -1,24 +1,71 @@
<h2><%=t(:field_customers)%> <span style="float:right"> <%= render partial: 'customers/search' %> </span> </h2> <% html_title l(:label_customers) %>
<% if @customers.present? %> <% phone = ->(digits) { digits.present? ? number_to_phone(digits.gsub(/\D/, '').to_i, area_code: true) : '' } %>
<br/>
<% @customers.each do |c| %> <div class="contextual">
<div class="row"> <% if User.current.allowed_to?(:add_customers, nil, global: true) %>
<div class="span6 columns"> <%= link_to sprite_icon('add', l(:label_new_customer)), new_customer_path, class: 'icon icon-add' %>
<%= link_to c, customer_path(c.id) %> <% end %>
</div> <%# Estimate and invoice drafts, for users who may write either %>
</div> <% 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? %>
<%= link_to sprite_icon('reload', l(:label_sync)), qbo_sync_path, class: 'icon icon-reload' %>
<% end %> <% end %>
<p><%=t(:label_matching)%> <%= @customers.count %> <%=t(:field_customers)%> </p>
<div class="actions">
<%= will_paginate @customers %>
</div> </div>
<% else %> <h2><%= l(:label_customers) %></h2>
<p><%=t(:label_no_customers)%> <%= params[:search] %>.</p>
<%= form_tag(customers_path, method: :get, id: 'customer-search-form') do %>
<p class="qbo-customer-search">
<%= text_field_tag :search, @search, class: 'customer-name', size: 40, placeholder: t(:label_search_customers),
autocomplete: 'off', data: { autocomplete_url: '/customers/autocomplete' } %>
<%= submit_tag l(:label_search), name: nil %>
<% if @search.present? %>
<%= link_to sprite_icon('reload', l(:button_clear)), customers_path, class: 'icon icon-reload' %>
<% end %>
</p>
<% end %> <% end %>
<div> <% if @customers.empty? %>
<%= render partial: 'qbo/stats' %> <p class="nodata"><%= @search.present? ? l(:label_no_customers, search: @search) : l(:label_no_data) %></p>
</div> <% else %>
<% if @best_first %>
<p class="info"><%= l(:text_customers_best_match, count: @customer_count) %></p>
<% end %>
<div class="autoscroll">
<table class="list customers odd-even">
<thead>
<tr>
<%= sort_header_tag('name', caption: l(:field_name)) %>
<%= sort_header_tag('phone', caption: l(:label_primary_phone)) %>
<%= sort_header_tag('mobile', caption: l(:label_mobile_phone)) %>
<th><%= l(:label_issue_plural) %></th>
<%= sort_header_tag('updated', caption: l(:field_updated_on), default_order: 'desc') %>
</tr>
</thead>
<tbody>
<% @customers.each do |customer| %>
<tr class="<%= cycle('odd', 'even') %>">
<td class="name"><%= link_to customer.name, customer_path(customer.id) %></td>
<td class="phone"><%= phone.call(customer.phone_number) %></td>
<td class="phone"><%= phone.call(customer.mobile_phone_number) %></td>
<td class="issues"><%= @issue_counts[customer.id] || 0 %></td>
<td class="updated_on"><%= format_time(customer.updated_at) if customer.updated_at %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
<span class="pagination"><%= pagination_links_full @customer_pages, @customer_count %></span>
<% end %>
<p class="qbo-customer-stats"><%= render partial: 'qbo/stats' %></p>
<style>
table.customers td.name { text-align: left; }
table.customers td.phone, table.customers td.updated_on { white-space: nowrap; }
table.customers td.issues { width: 1%; text-align: center; }
.qbo-customer-search input { vertical-align: middle; }
</style>
+43 -6
View File
@@ -1,11 +1,16 @@
<div class="contextual"> <% html_title @customer.to_s %>
<%# New issue for this customer; picks up the estimate / vehicle ticked on this page %>
<h2><%= link_to l(:label_customers), customers_path %> &#187; <%= @customer.to_s %></h2>
<%# Under the title rather than beside it, so a long name and the many actions don't crowd each other %>
<div class="contextual qbo-under-title">
<%# 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 %>
<%# 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. The customer's <%# Estimates, invoices and payments are handled here, each shown to users with its permission; Open in
name below links to their QuickBooks account page as a fallback. %> QuickBooks goes to their QuickBooks account page for anything else. %>
<% if RedmineQboBilling.writer? %> <% if RedmineQboBilling.writer? %>
<%= render partial: 'qbo_estimates/customer_link', locals: { customer: @customer } %> <%= render partial: 'qbo_estimates/customer_link', locals: { customer: @customer } %>
<% end %> <% end %>
@@ -18,13 +23,17 @@
<% 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) %>
<% end %> <% end %>
<%= link_to sprite_icon('link', l(:button_open_in_quickbooks)),
"https://#{RedmineQbo.sandbox_mode? ? 'sandbox' : 'app'}.qbo.intuit.com/app/customerdetail?nameId=#{@customer.id}",
class: 'icon icon-link', target: :_blank, rel: 'noopener' %>
</div> </div>
<h2><%=t(:field_customer)%> #<%= @customer.id %> - <%= link_to @customer.to_s, "https://#{RedmineQbo.sandbox_mode? ? "sandbox" : "app"}.qbo.intuit.com/app/customerdetail?nameId=#{@customer.id}", target: :_blank %> </h2>
<div class="issue"> <div class="issue">
<div class="splitcontent"> <div class="splitcontent">
@@ -52,6 +61,34 @@
</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><%= refund.estimate_id.present? ? link_to("E#{refund.estimate_number}", RedmineQboBilling.writer? ? edit_qbo_estimate_path(refund.estimate_id) : estimate_path(refund.estimate_id)) : '' %></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">
+8 -1
View File
@@ -1,12 +1,19 @@
<% unless estimates.empty? %> <% unless estimates.empty? %>
<%= render partial: 'qbo_estimates/status_styles' %>
<div class="qbo-estimate-list">
<% estimates.sort.reverse.each do |estimate| %> <% estimates.sort.reverse.each do |estimate| %>
<div class="row"> <div class="row">
<%= check_box_tag "estimate_ids[]", estimate.id, false, onchange: "updateLink()", data: { text: "Estimate ##{estimate.doc_number}" }, class: "estimate-checkbox appointment" %> <%= check_box_tag "estimate_ids[]", estimate.id, false, onchange: "updateLink()", data: { text: "Estimate ##{estimate.doc_number}", new_issue_param: 'issue[estimate_id]' }, class: "estimate-checkbox appointment" %>
<b><%= link_to "##{estimate.doc_number}", estimate_path(estimate), target: :_blank %></b> <%= estimate.txn_date %> <b><%= link_to "##{estimate.doc_number}", estimate_path(estimate), target: :_blank %></b> <%= estimate.txn_date %>
<%# QuickBooks status, cached by the estimate sync (kept current by the webhook) %>
<% if estimate.txn_status.present? %>
<span class="qbo-estimate-status qbo-estimate-status-<%= estimate.txn_status.downcase %>"><%= estimate.txn_status %></span>
<% end %>
<%= render partial: 'qbo_estimates/estimate_actions', locals: { estimate: estimate } if RedmineQboBilling.writer? %> <%= render partial: 'qbo_estimates/estimate_actions', locals: { estimate: estimate } if RedmineQboBilling.writer? %>
</div> </div>
<% end %> <% end %>
</div>
<% else %> <% else %>
<p><%=t(:label_no_estimates)%>.</p> <p><%=t(:label_no_estimates)%>.</p>
+7
View File
@@ -1,4 +1,5 @@
<% unless invoices.empty? %> <% unless invoices.empty? %>
<%= render partial: 'qbo_estimates/status_styles' %>
<%= form_with(url: invoice_path, method: :get) do |form| %> <%= form_with(url: invoice_path, method: :get) do |form| %>
@@ -10,13 +11,19 @@
<hr> <hr>
<% end %> <% end %>
<div class="qbo-invoice-list">
<% invoices.sort.reverse.each do |invoice| %> <% invoices.sort.reverse.each do |invoice| %>
<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 %> <%= check_box_tag "invoice_ids[]", invoice.id, false, onchange: "updateLink()", data: { url: invoice_path(invoice), text: "Invoice ##{invoice.to_s}" }, class: "invoice-checkbox appointment" if invoices.count > 1 %>
<b><%= link_to "##{invoice.doc_number}", invoice_path(invoice), target: :_blank %></b> <%= invoice.txn_date %> <b><%= link_to "##{invoice.doc_number}", invoice_path(invoice), target: :_blank %></b> <%= invoice.txn_date %>
<%# Paid / partially paid / overdue / open / voided, from the cached balance and due date %>
<% if (status = invoice.status) %>
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status, paid_on: invoice.paid_on) %></span>
<% end %>
<%= render partial: 'qbo_invoices/invoice_actions', locals: { invoice: invoice } if RedmineQboBilling.invoice_writer? %> <%= render partial: 'qbo_invoices/invoice_actions', locals: { invoice: invoice } if RedmineQboBilling.invoice_writer? %>
</div> </div>
<% end %> <% end %>
</div>
<% if invoices.count > 1 %> <% if invoices.count > 1 %>
<%= form.submit t(:button_bulk_pdf) %> <%= form.submit t(:button_bulk_pdf) %>
+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>
+66 -44
View File
@@ -5,26 +5,52 @@
min: 0, step: 1, size: 6 %> min: 0, step: 1, size: 6 %>
<em class="info"><%= l(:text_estimate_expiration_days) %></em> <em class="info"><%= l(:text_estimate_expiration_days) %></em>
</p> </p>
<%# Labor: issues from estimates, lines imported time replaces on invoices, and hours for the business report.
While none are chosen, items named "Labor" are used and shown selected. %>
<p> <p>
<label for="settings_replaceable_item_ids"><%= l(:label_replaceable_items) %></label> <label for="settings_labor_item_ids"><%= l(:label_labor_items) %></label>
<%= hidden_field_tag 'settings[replaceable_item_ids][]', '', id: nil %> <%= hidden_field_tag 'settings[labor_item_ids][]', '', id: nil %>
<%= select_tag 'settings[replaceable_item_ids][]', <%= select_tag 'settings[labor_item_ids][]',
options_from_collection_for_select(Item.where(active: true).order(:name), :id, :name, options_from_collection_for_select(Item.sellable.order(:name), :id, :name,
Array(@settings['replaceable_item_ids']).map(&:to_s)), RedmineQboBilling::LaborItems.item_ids),
multiple: true, size: 8, id: 'settings_replaceable_item_ids' %> multiple: true, size: 8, id: 'settings_labor_item_ids' %>
<em class="info"><%= l(:text_replaceable_items) %></em> <em class="info"><%= l(:text_labor_items) %></em>
</p>
<%# QuickBooks custom fields to leave out of estimates and invoices (see RedmineQboBilling::Company). Hidden
fields that aren't found right now (e.g. no recent estimate has them) are kept as hidden. %>
<% company = RedmineQboBilling::Company %>
<% qbo_fields = company.all_custom_fields %>
<% hidden_ids = company.hidden_field_ids %>
<% sales_field = company.sales_person_field %>
<p class="qbo-custom-fields-setting">
<label><%= l(:label_qbo_hidden_custom_fields) %></label>
<%= hidden_field_tag 'settings[hidden_custom_field_ids][]', '', id: nil %>
<% (hidden_ids - qbo_fields.map { |f| f.id.to_i }).each do |id| %>
<%= hidden_field_tag 'settings[hidden_custom_field_ids][]', id, id: nil %>
<% end %>
<% if qbo_fields.empty? %>
<%= l(:label_none) %>
<% else %>
<% qbo_fields.each do |field| %>
<label class="block">
<%= check_box_tag 'settings[hidden_custom_field_ids][]', field.id, hidden_ids.include?(field.id.to_i),
id: "settings_hidden_custom_field_#{field.id}" %>
<%= field.name %>
<% if sales_field && sales_field.id.to_i == field.id.to_i %>
<em>(<%= l(:text_qbo_sales_person_field) %>)</em>
<% end %>
</label>
<% end %>
<% end %>
<%= link_to sprite_icon('reload', l(:button_refresh_quickbooks_fields)), refresh_company_qbo_estimates_path,
method: :post, class: 'icon icon-reload' %>
<em class="info"><%= l(:text_qbo_hidden_custom_fields) %></em>
</p> </p>
</div> </div>
<%# Issues from estimates (moved from redmine_qbo_calendar; its old values are shown until these are saved) %>
<% issue_builder = RedmineQboBilling::EstimateIssueBuilder %> <% issue_builder = RedmineQboBilling::EstimateIssueBuilder %>
<fieldset class="box tabular"> <fieldset class="box tabular">
<legend><%= l(:label_estimate_issue_settings) %></legend> <legend><%= l(:label_estimate_issue_settings) %></legend>
<p>
<label for="settings_issue_item_codes"><%= l(:label_estimate_item_codes) %></label>
<%= text_area_tag 'settings[issue_item_codes]', issue_builder.item_codes.join("\n"), rows: 5, cols: 30, id: 'settings_issue_item_codes' %>
<em class="info"><%= l(:text_estimate_item_codes_info) %></em>
</p>
<p> <p>
<label for="settings_issue_default_project_id"><%= l(:label_default_project) %></label> <label for="settings_issue_default_project_id"><%= l(:label_default_project) %></label>
<%= select_tag 'settings[issue_default_project_id]', <%= select_tag 'settings[issue_default_project_id]',
@@ -41,43 +67,39 @@
</p> </p>
</fieldset> </fieldset>
<%# QuickBooks product/service list and income accounts (moved from redmine_qbo_lineitems) %> <%# Refunds (SOP-OPS-014): the restocking fee, and where the refund check or card refund is recorded %>
<div class="box tabular"> <% refunds = RedmineQboBilling::RefundWriter %>
<% accounts = Account.where(active: true).order(:name).pluck(:name, :id) %>
<fieldset class="box tabular">
<legend><%= l(:label_refund_settings) %></legend>
<p> <p>
<label><strong><%= t(:label_item_count) %></strong></label> <label for="settings_restocking_fee_rate"><%= l(:label_restocking_fee_rate) %></label>
<%= Item.count %> <%= number_field_tag 'settings[restocking_fee_rate]', refunds.plain(refunds.fee_rate), id: 'settings_restocking_fee_rate',
<em style="color: #777; font-size: 0.9em; margin-left: 8px;"> min: 0, max: 100, step: 0.01, style: 'width: 6em' %>%
(@ <%= Item.last_sync %>) <em class="info"><%= l(:text_restocking_fee_rate) %></em>
</em>
</p> </p>
<p> <p>
<label><strong><%= t(:label_account_count) %></strong></label> <label for="settings_restocking_item_id"><%= l(:label_restocking_item) %></label>
<%= Account.count %> <%= select_tag 'settings[restocking_item_id]', options_from_collection_for_select(Item.sellable.order(:name), :id, :name, @settings['restocking_item_id']),
<em style="color: #777; font-size: 0.9em; margin-left: 8px;"> include_blank: true, id: 'settings_restocking_item_id' %>
(@ <%= Account.last_sync %>) <em class="info"><%= l(:text_restocking_item) %></em>
</em>
</p> </p>
<p> <p>
<label><strong><%= t(:label_last_sync) %> (QBO)</strong></label> <label for="settings_refund_check_account_id"><%= l(:label_refund_check_account) %></label>
<%= Qbo.exists? ? Qbo.last_sync : l(:label_never_synced) %> <%= 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>
<p> <p>
<label><strong><%= t(:label_default_account) %></strong></label> <label for="settings_refund_card_account_id"><%= l(:label_refund_card_account) %></label>
<%= Account.get_default %> <%= 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> </p>
</div>
<fieldset class="box">
<legend><%= l(:label_management_and_sync) %></legend>
<div style="margin-bottom: 15px;">
<%= link_to t(:label_sync_now_items), sync_items_path, class: 'button icon icon-reload' %>
<%= link_to t(:label_sync_now_accounts), sync_accounts_path, class: 'button icon icon-reload' %>
</div>
<div>
<%= link_to t(:label_items), items_path, class: 'icon icon-list' %>
<span style="margin: 0 10px; color: #ccc;">|</span>
<%= link_to t(:label_accounts), accounts_path, class: 'icon icon-list' %>
</div>
</fieldset> </fieldset>
+70 -47
View File
@@ -3,81 +3,104 @@
intuit.ipp.anywhere.setup({menuProxy: '/path/to/blue-dot', grantUrl: '<%= qbo_authenticate_path %>'}); intuit.ipp.anywhere.setup({menuProxy: '/path/to/blue-dot', grantUrl: '<%= qbo_authenticate_path %>'});
</script> </script>
<%# QuickBooks connection: app keys, webhook token, sandbox, and the OAuth connection %>
<h3><%= l(:label_qbo_connection) %></h3>
<div class="box tabular"> <div class="box tabular">
<p> <p>
<label><%= t(:label_client_id) %></label> <label><%= t(:label_client_id) %></label>
<%= text_field_tag 'settings[oauth_consumer_key]', settings[:oauth_consumer_key], size: 50 %> <%= text_field_tag 'settings[oauth_consumer_key]', settings[:oauth_consumer_key], size: 50 %>
</p> </p>
<p> <p>
<label><%= t(:label_client_secret) %></label> <label><%= t(:label_client_secret) %></label>
<%= password_field_tag 'settings[oauth_consumer_secret]', settings[:oauth_consumer_secret], size: 50 %> <%= password_field_tag 'settings[oauth_consumer_secret]', settings[:oauth_consumer_secret], size: 50 %>
</p> </p>
<p> <p>
<label><%= t(:label_webhook_token) %></label> <label><%= t(:label_webhook_token) %></label>
<%= text_field_tag 'settings[webhook_token]', settings[:webhook_token], size: 50 %> <%= text_field_tag 'settings[webhook_token]', settings[:webhook_token], size: 50 %>
</p> </p>
<p> <p>
<label><%= t(:label_sandbox) %></label> <label><%= t(:label_sandbox) %></label>
<%= check_box_tag 'settings[sandbox]', 1, settings[:sandbox] %> <%= check_box_tag 'settings[sandbox]', 1, settings[:sandbox] %>
</p> </p>
<hr />
<p> <p>
<label><%= t(:label_oauth_expires) %></label> <label><%= t(:label_oauth_expires) %></label>
<span class="icon <%= Qbo.oauth2_access_token_expires_at&.future? ? 'icon-ok' : 'icon-warning' %>"> <span class="icon <%= Qbo.oauth2_access_token_expires_at&.future? ? 'icon-ok' : 'icon-warning' %>">
<%= Qbo.oauth2_access_token_expires_at || 'N/A' %> <%= Qbo.oauth2_access_token_expires_at ? format_time(Qbo.oauth2_access_token_expires_at) : 'N/A' %>
</span> </span>
</p> </p>
<p> <p>
<label><%= t(:label_customer_count) %></label> <label></label>
<%= Customer.count %> <ipp:connectToIntuit></ipp:connectToIntuit>
<em style="color: #777; font-size: 0.9em; margin-left: 8px;">(@ <%= Customer.last_sync %>)</em>
</p>
<p>
<label><%= t(:label_employee_count) %></label>
<%= Employee.count %>
<em style="color: #777; font-size: 0.9em; margin-left: 8px;">(@ <%= Employee.last_sync %>)</em>
</p>
<p>
<label><%= t(:label_invoice_count) %></label>
<%= Invoice.count %>
<em style="color: #777; font-size: 0.9em; margin-left: 8px;">(@ <%= Invoice.last_sync %>)</em>
</p>
<p>
<label><%= t(:label_estimate_count) %></label>
<%= Estimate.count %>
<em style="color: #777; font-size: 0.9em; margin-left: 8px;">(@ <%= Estimate.last_sync %>)</em>
</p>
<p>
<label><%= t(:label_last_sync) %> (QBO)</label>
<%= Qbo.exists? ? Qbo.last_sync : 'Never synced' %>
</p> </p>
</div> </div>
<fieldset class="box"> <%# Everything kept in step with QuickBooks: how many records there are, when each last changed, and a sync
<legend>Management & Synchronization</legend> button for each. A type's sync re-reads all of its records from QuickBooks. %>
<% sync_rows = [
[l(:label_customers), Customer, sync_customers_path, customers_path],
[l(:label_employee_plural), Employee, employees_sync_path, nil],
[l(:label_estimates), Estimate, estimates_sync_path, nil],
[l(:label_invoices), Invoice, invoices_sync_path, nil],
[l(:label_payments), Payment, sync_qbo_payments_path, nil],
[l(:label_items), Item, sync_items_path, items_path],
[l(:label_accounts), Account, sync_accounts_path, accounts_path]
] %>
<% sync_statuses = QboSyncStatus.by_entity %>
<h3><%= l(:label_management_and_sync) %></h3>
<div class="box">
<table class="list qbo-sync-table">
<thead>
<tr>
<th class="name"></th>
<th class="count"><%= l(:label_qbo_records) %></th>
<th class="updated"><%= l(:label_last_sync) %></th>
<th class="buttons"></th>
</tr>
</thead>
<tbody>
<% sync_rows.each do |label, model, sync_path, list_path| %>
<tr>
<td class="name"><%= list_path ? link_to(label, list_path) : label %></td>
<td class="count"><%= model.count %></td>
<td class="updated">
<% status = sync_statuses[model.name] %>
<% if status&.running? %>
<span class="icon icon-reload qbo-sync-busy"><%= l(:text_qbo_sync_running_short, count: number_with_delimiter(status.processed)) %></span>
<% elsif status %>
<span class="qbo-sync-busy"><%= l(:text_qbo_sync_queued) %></span>
<% else %>
<%= model.last_sync %>
<% end %>
</td>
<td class="buttons"><%= link_to sprite_icon('reload', l(:label_sync)), sync_path, class: 'icon icon-reload' %></td>
</tr>
<% end %>
</tbody>
</table>
<div style="margin-bottom: 20px;"> <p class="qbo-sync-default-account">
<ipp:connectToIntuit></ipp:connectToIntuit> <strong><%= t(:label_default_account) %>:</strong> <%= Account.get_default || '–' %>
</div> <em class="info"><%= l(:text_default_account_info) %></em>
</p>
<div style="margin-bottom: 15px;"> <p class="qbo-sync-all">
<%= link_to t(:label_sync_now_customers), sync_customers_path, class: 'button icon icon-reload' %> <strong><%= t(:label_last_sync) %> (QBO):</strong> <%= Qbo.exists? ? Qbo.last_sync : l(:label_never_synced) %>
<%= link_to t(:label_sync_now_employees), employees_sync_path, class: 'button icon icon-reload' %> <%= link_to sprite_icon('reload', l(:label_sync_changes)), qbo_sync_path, class: 'button icon icon-reload' %>
<%= link_to t(:label_sync_now_invoices), invoices_sync_path, class: 'button icon icon-reload' %> <%= link_to sprite_icon('reload', l(:label_full_sync)), qbo_sync_path(full_sync: true), class: 'button icon icon-reload' %>
<%= link_to t(:label_sync_now_estimate), estimates_sync_path, class: 'button icon icon-reload' %> </p>
</div> <em class="info"><%= l(:text_qbo_sync_info) %></em>
</fieldset> </div>
<%# Billing: estimates, issues from estimates, invoices, the product/service list and accounts %> <style>
table.qbo-sync-table { margin-bottom: 10px; }
table.qbo-sync-table td.name, table.qbo-sync-table th.name { text-align: left; }
table.qbo-sync-table td.count { text-align: right; width: 8em; }
table.qbo-sync-table td.updated { width: 14em; }
table.qbo-sync-table td.buttons { width: 6em; }
.qbo-sync-all .button { margin-left: 8px; }
.qbo-sync-busy { font-style: italic; color: #b06d00; }
</style>
<%# Billing: estimates, issues from estimates and invoices %>
<h3><%= l(:label_billing_settings) %></h3> <h3><%= l(:label_billing_settings) %></h3>
<%= render partial: 'qbo/billing_settings', locals: { settings: settings } %> <%= render partial: 'qbo/billing_settings', locals: { settings: settings } %>
@@ -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 %>
@@ -1,5 +1,5 @@
<%# Estimates linked to an issue are read-only here, so they get a View link instead of Edit %> <%# Billed estimates and estimates linked to an issue are read-only here, so they get a View link instead of Edit %>
<% if estimate.issues.exists? %> <% if estimate.billed? || estimate.issues.exists? %>
<%= link_to sprite_icon('zoom-in', l(:button_view_estimate)), edit_qbo_estimate_path(estimate.id), <%= link_to sprite_icon('zoom-in', l(:button_view_estimate)), edit_qbo_estimate_path(estimate.id),
class: 'icon-only icon-zoom-in qbo-estimate-edit-link', title: l(:button_view_estimate) %> class: 'icon-only icon-zoom-in qbo-estimate-edit-link', title: l(:button_view_estimate) %>
<% else %> <% else %>
+58 -32
View File
@@ -1,14 +1,20 @@
<% <%
company = RedmineQboBilling::Company company = RedmineQboBilling::Company
sales_field = company.sales_person_field sales_field = company.sales_person_field
vin_field = company.vin_field # A box for every other text custom field QuickBooks has enabled (e.g. VIN, Mileage, Crew #)
mileage_field = company.mileage_field custom_fields = company.editable_custom_fields
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?
vehicles = customer.respond_to?(:vehicles) ? customer.vehicles.select { |v| v.vin.present? } : [] # Suggestions other plugins give for those boxes (e.g. redmine_qbo_vehicles: the customer's vehicles' VINs)
field_options = RedmineQboBilling.field_options(customer)
# When QuickBooks' settings couldn't be read at all, the page header says so instead of each field # When QuickBooks' settings couldn't be read at all, the page header says so instead of each field
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 =
@@ -26,7 +32,7 @@
data: { data: {
document: form.document, document: form.document,
import_url: (import_options_qbo_invoices_path if invoice), import_url: (import_options_qbo_invoices_path if invoice),
replaceable_item_ids: (RedmineQboBilling::InvoiceWriter.replaceable_item_ids if invoice), labor_item_ids: (RedmineQboBilling::LaborItems.item_ids if invoice),
items_url: items_qbo_estimates_path, items_url: items_qbo_estimates_path,
customer_info_url: customer_info_qbo_estimates_path, customer_info_url: customer_info_qbo_estimates_path,
saved_subtotal: (form.persisted? ? form.subtotal.to_s('F') : ''), saved_subtotal: (form.persisted? ? form.subtotal.to_s('F') : ''),
@@ -37,6 +43,7 @@
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 %>
@@ -45,6 +52,11 @@
<%= 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? %>
<% 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| %>
@@ -116,28 +128,21 @@
<em class="info"><%= l(:text_no_sales_person_field) %></em> <em class="info"><%= l(:text_no_sales_person_field) %></em>
<% end %> <% end %>
</div> </div>
<div class="qbo-field qbo-field-vin"> <%# Plugins' editor scripts find a box by its field id or name (qboEditor.field / fieldNamed) %>
<label for="qbo_estimate_vin"><%= vin_field&.name || l(:label_vin) %></label> <% custom_fields.each do |field| %>
<%= text_field_tag 'estimate[vin]', form.vin, id: 'qbo_estimate_vin', list: 'qbo-estimate-vins', maxlength: 31, <div class="qbo-field qbo-field-custom" data-qbo-field-id="<%= field.id %>" data-qbo-field-name="<%= field.name %>">
autocomplete: 'off', spellcheck: false, disabled: vin_field.nil? %> <label for="qbo_custom_field_<%= field.id %>"><%= field.name %></label>
<datalist id="qbo-estimate-vins"> <%= text_field_tag "estimate[custom_fields][#{field.id}]", form.custom_field(field), id: "qbo_custom_field_#{field.id}",
<% vehicles.each do |vehicle| %> list: "qbo-custom-field-options-#{field.id}", maxlength: 31, autocomplete: 'off', spellcheck: false,
<option value="<%= vehicle.vin %>"><%= vehicle.to_s %></option> class: 'qbo-custom-field' %>
<% end %> <datalist id="qbo-custom-field-options-<%= field.id %>">
</datalist> <% Array(field_options[field.id.to_s]).each do |option| %>
<% if settings_read && !vin_field %> <option value="<%= option[:value] %>"><%= option[:label] %></option>
<em class="info"><%= l(:text_no_vin_field) %></em> <% end %>
<% end %> </datalist>
</div>
<%# Mileage only shows when QuickBooks has a text field named like "Mileage" %>
<% if mileage_field %>
<div class="qbo-field qbo-field-mileage">
<label for="qbo_estimate_mileage"><%= mileage_field.name %></label>
<%= text_field_tag 'estimate[mileage]', form.mileage, id: 'qbo_estimate_mileage', maxlength: 31,
inputmode: 'numeric', autocomplete: 'off' %>
</div> </div>
<% end %> <% end %>
<% if settings_read && (sales_field.nil? || vin_field.nil?) && User.current.admin? %> <% if settings_read && (sales_field.nil? || custom_fields.empty?) && User.current.admin? %>
<div class="qbo-field qbo-field-refresh"> <div class="qbo-field qbo-field-refresh">
<%= link_to sprite_icon('reload', l(:button_refresh_quickbooks_fields)), refresh_company_qbo_estimates_path, <%= link_to sprite_icon('reload', l(:button_refresh_quickbooks_fields)), refresh_company_qbo_estimates_path,
method: :post, class: 'icon icon-reload' %> method: :post, class: 'icon icon-reload' %>
@@ -196,8 +201,7 @@
<%# Import: billable QuickBooks time (replacing the lines ticked) and open estimates. Filled by the script. %> <%# Import: billable QuickBooks time (replacing the lines ticked) and open estimates. Filled by the script. %>
<div class="qbo-import-panel" id="qbo-import-panel" hidden <div class="qbo-import-panel" id="qbo-import-panel" hidden
data-loading-text="<%= l(:label_loading) %>" data-none-text="<%= l(:label_none) %>" data-loading-text="<%= l(:label_loading) %>" data-none-text="<%= l(:label_none) %>"
data-need-customer-text="<%= l(:error_estimate_needs_customer) %>" data-need-customer-text="<%= l(:error_estimate_needs_customer) %>">
data-many-vehicles-text="<%= l(:text_invoice_many_vehicles) %>">
<div class="qbo-import-columns"> <div class="qbo-import-columns">
<section class="qbo-import-time"> <section class="qbo-import-time">
<h4><%= l(:label_billable_time) %></h4> <h4><%= l(:label_billable_time) %></h4>
@@ -266,10 +270,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>
@@ -286,14 +298,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 %>
@@ -302,3 +326,5 @@
<%= render partial: 'qbo_estimates/styles' %> <%= render partial: 'qbo_estimates/styles' %>
<%= render partial: 'qbo_estimates/script' %> <%= render partial: 'qbo_estimates/script' %>
<%# Plugins add their editor scripts here (see window.qboEditor and the qbo:* events in qbo_estimates/_script) %>
<%= call_hook(:view_qbo_estimate_form_bottom, { form: form, document: form.document }) %>
+32 -18
View File
@@ -15,10 +15,15 @@
<% if form.sent? %> <% if form.sent? %>
<span class="qbo-estimate-status qbo-estimate-status-sent"><%= l(:label_estimate_sent) %></span> <span class="qbo-estimate-status qbo-estimate-status-sent"><%= l(:label_estimate_sent) %></span>
<% end %> <% end %>
<% if invoice && form.locked == :paid %> <% if invoice %>
<% fully_paid = form.balance.to_d.zero? %> <% status = RedmineQboBilling::InvoiceStatus.status(total: form.total, balance: form.balance,
<span class="qbo-estimate-status qbo-estimate-status-<%= fully_paid ? 'closed' : 'accepted' %>"><%= l(fully_paid ? :label_invoice_paid : :label_invoice_partially_paid) %></span> due_date: RedmineQboBilling::EstimateForm.date(form.due_date),
<% elsif !invoice && form.txn_status.present? && form.txn_status != 'Pending' %> today: User.current.today) %>
<% if status %>
<% paid_on = Invoice.where(id: form.id).pick(:paid_on) if status == :paid && form.id.present? %>
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status, paid_on: paid_on) %></span>
<% end %>
<% elsif !invoice && form.txn_status.present? %>
<span class="qbo-estimate-status qbo-estimate-status-<%= form.txn_status.downcase %>"><%= form.txn_status %></span> <span class="qbo-estimate-status qbo-estimate-status-<%= form.txn_status.downcase %>"><%= form.txn_status %></span>
<% end %> <% end %>
<% else %> <% else %>
@@ -35,16 +40,6 @@
</p> </p>
<% end %> <% end %>
<% if !invoice && Array(form.invoiced_on).any? %>
<div class="warning qbo-estimate-notice">
<%= l(:text_estimate_billed_on) %>
<ul>
<% form.invoiced_on.each do |invoice_id, number| %>
<li><%= link_to "#{l(:label_invoice)} ##{number}", RedmineQboBilling.invoice_writer? ? edit_qbo_invoice_path(invoice_id) : invoice_path(invoice_id) %></li>
<% end %>
</ul>
</div>
<% end %>
<% if form.duplicated_from.present? %> <% if form.duplicated_from.present? %>
<div class="flash notice"><%= l(:text_estimate_duplicated_from, number: form.duplicated_from) %></div> <div class="flash notice"><%= l(:text_estimate_duplicated_from, number: form.duplicated_from) %></div>
@@ -53,7 +48,18 @@
<div class="flash notice"><%= l(:text_invoice_from_estimate, number: form.converted_from) %></div> <div class="flash notice"><%= l(:text_invoice_from_estimate, number: form.converted_from) %></div>
<% end %> <% end %>
<% if form.locked == :linked %> <% if form.locked == :billed %>
<div class="warning qbo-estimate-notice">
<%= l(:error_estimate_billed) %>
<% if Array(form.invoiced_on).any? %>
<ul>
<% form.invoiced_on.each do |invoice_id, number| %>
<li><%= link_to "#{l(:label_invoice)} ##{number}", RedmineQboBilling.invoice_writer? ? edit_qbo_invoice_path(invoice_id) : invoice_path(invoice_id) %></li>
<% end %>
</ul>
<% end %>
</div>
<% elsif form.locked == :linked %>
<div class="warning qbo-estimate-notice"> <div class="warning qbo-estimate-notice">
<%= l(:error_estimate_linked_to_issues) %> <%= l(:error_estimate_linked_to_issues) %>
<ul> <ul>
@@ -63,11 +69,19 @@
</ul> </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>
<% elsif !invoice && %w[Converted Closed].include?(form.txn_status.to_s) && Array(form.invoiced_on).empty? %>
<p class="warning"><%= l(:text_estimate_closed) %></p>
<% end %> <% end %>
<% if RedmineQboBilling::Company.settings.empty? %> <% if RedmineQboBilling::Company.settings.empty? %>
+315 -68
View File
@@ -4,27 +4,89 @@ $(function () {
var $form = $('#qbo-estimate-form'); var $form = $('#qbo-estimate-form');
if (!$form.length) return; if (!$form.length) return;
// For other plugins' editor scripts (added through the view_qbo_estimate_form_bottom hook). The form also
// triggers these events (listen with $(document).on('qbo:imported', '#qbo-estimate-form', fn)):
// qbo:customer-changed (event, { customer_id, info }) info includes field_options
// qbo:imported (event, { issue_ids, estimates, issue_values }) after time/estimates are
// imported into an invoice; issue_values is { issue_id => { field_id => value } }
// and each estimate has its own custom_fields { field_id => value }
window.qboEditor = {
form: $form,
document: $form.data('document'),
// A QuickBooks custom field's box, by field id or by a name pattern (RegExp)
field: function (id) { return $('#qbo_custom_field_' + id); },
fieldNamed: function (pattern) {
var $box = $();
$form.find('.qbo-field-custom').each(function () {
if (!$box.length && pattern.test(String($(this).data('qboFieldName')))) $box = $(this).find('input.qbo-custom-field');
});
return $box;
},
fieldId: function ($box) { return $box.closest('.qbo-field-custom').data('qboFieldId'); },
// Replaces a box's suggestion list: [{ value, label }]
setFieldOptions: function (id, options) {
var $list = $('#qbo-custom-field-options-' + id).empty();
(options || []).forEach(function (o) { $('<option>').attr('value', o.value).text(o.label || o.value).appendTo($list); });
}
};
var $tbody = $('#qbo-estimate-lines tbody'); var $tbody = $('#qbo-estimate-lines tbody');
var template = document.getElementById('qbo-estimate-line-template').innerHTML; var template = document.getElementById('qbo-estimate-line-template').innerHTML;
var subtotalTemplate = document.getElementById('qbo-estimate-subtotal-template').innerHTML; var subtotalTemplate = document.getElementById('qbo-estimate-subtotal-template').innerHTML;
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();
var dirty = false; var dirty = false;
// ---- numbers ---- // ---- numbers ----
// A number, or simple arithmetic typed into a quantity or rate box (e.g. 33*1.3, (120+15)/2): + - * / and
// parentheses only, worked out here (never run as code). null when empty, NaN when it can't be read.
function isMath(text) { return /[*\/()+x×]/.test(text) || /.-/.test(text); }
function evaluateMath(text) {
var tokens = text.replace(/[x×]/g, '*').match(/\d*\.?\d+|[-+*\/()]/g);
if (!tokens || tokens.join('') !== text.replace(/[x×]/g, '*')) return NaN;
var i = 0;
var peek = function () { return tokens[i]; };
var expr, term, factor;
factor = function () {
var t = tokens[i++];
if (t === '-') return -factor();
if (t === '+') return factor();
if (t === '(') { var v = expr(); if (tokens[i++] !== ')') return NaN; return v; }
return t !== undefined && /^\d*\.?\d+$/.test(t) ? parseFloat(t) : NaN;
};
term = function () {
var v = factor();
while (peek() === '*' || peek() === '/') { var op = tokens[i++], r = factor(); v = op === '*' ? v * r : v / r; }
return v;
};
expr = function () {
var v = term();
while (peek() === '+' || peek() === '-') { var op = tokens[i++], r = term(); v = op === '+' ? v + r : v - r; }
return v;
};
var result = expr();
return i === tokens.length && isFinite(result) ? result : NaN;
}
function parseNumber(value) { function parseNumber(value) {
var text = String(value == null ? '' : value).replace(/[$,\s]/g, ''); var text = String(value == null ? '' : value).replace(/[$,\s]/g, '');
if (text === '') return null; if (text === '') return null;
if (isMath(text)) return evaluateMath(text);
var n = Number(text); var n = Number(text);
return isFinite(n) ? n : NaN; return isFinite(n) ? n : NaN;
} }
function round(n, places) { var f = Math.pow(10, places); return Math.round(n * f) / f; } // Rounds half up exactly (1.005 -> 1.01; multiplying first would give 1.00)
function round(n, places) {
if (/e/i.test(String(n))) { var f = Math.pow(10, places); return Math.round(n * f) / f; }
return Number(Math.round(Number(n + 'e' + places)) + 'e-' + places);
}
function plain(n, places) { return String(round(n, places)); } function plain(n, places) { return String(round(n, places)); }
// ---- rows ---- // ---- rows ----
@@ -71,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 () {
@@ -94,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 {
@@ -109,6 +181,70 @@ $(function () {
} }
// ---- product/service search ---- // ---- product/service search ----
// Fills a line from a product/service: name, id, description (unless the user typed their own), rate,
// quantity 1 if empty, taxable
function applyItem($input, item) {
var $row = $input.closest('tr');
var $description = $row.find('.qbo-line-description-input');
var previous = $row.data('itemDescription');
$input.val(item.name);
$row.find('.qbo-line-item-id').val(item.id);
$row.removeClass('qbo-line-unmatched');
// Keep a description the user typed; replace one that came from the previous product
if (!$description.val().trim() || $description.val() === previous) {
$description.val(item.description || '');
autoGrow($description[0]);
// Tabbed into it already (the product was filled in after the search came back): keep it selected
if (document.activeElement === $description[0]) $description[0].select();
}
$row.data('itemDescription', item.description || '');
if (item.price !== null && item.price !== undefined && item.price !== '') {
$row.find('.qbo-line-rate-input').val(plain(parseFloat(item.price), 5));
tidyNumbers($row);
}
if (!$row.find('.qbo-line-qty-input').val().trim()) $row.find('.qbo-line-qty-input').val('1');
$row.find('.qbo-line-taxable').prop('checked', item.taxable !== false);
changed();
}
// Keyboard subtotal: typed in a line's product box, then Tab or Enter
var SUBTOTAL_SHORTCUTS = ['sub', 'subtotal', '='];
// Puts a subtotal where the shortcut was typed: an otherwise empty line becomes the subtotal; a line with a
// description, quantity or rate keeps them (the shortcut text is cleared) and the subtotal goes after it.
// Then the next line's product box gets the focus, to carry on typing.
function insertSubtotalAt($row) {
var $subtotal = $(subtotalTemplate.replace(/__KEY__/g, String(nextKey++)));
var $product = $row.find('.qbo-line-item-name');
var otherwiseEmpty = !$row.find('.qbo-line-description-input').val().trim() &&
!$row.find('.qbo-line-qty-input').val().trim() && !$row.find('.qbo-line-rate-input').val().trim();
if (otherwiseEmpty) {
$row.replaceWith($subtotal);
} else {
$product.val('');
$row.removeClass('qbo-line-unmatched').after($subtotal);
}
renumber();
changed();
var $next = $subtotal.nextAll('tr.qbo-line').not('.qbo-line-subtotal').first();
if (!$next.length) $next = addRow();
$next.find('.qbo-line-item-name').trigger('focus');
}
// The product typed text points to: an exact name match, else the only result, else the only one whose name
// starts with the text (e.g. "lab" -> Labor). Nothing when it's ambiguous.
function bestItem(term, items) {
var t = term.trim().toLowerCase();
if (!t || !items || !items.length) return null;
var exact = items.filter(function (i) { return String(i.name).toLowerCase() === t; });
if (exact.length === 1) return exact[0];
if (items.length === 1) return items[0];
var starts = items.filter(function (i) { return String(i.name).toLowerCase().indexOf(t) === 0; });
return starts.length === 1 ? starts[0] : null;
}
function setupItemSearch($input) { function setupItemSearch($input) {
$input.autocomplete({ $input.autocomplete({
appendTo: 'body', appendTo: 'body',
@@ -117,6 +253,7 @@ $(function () {
source: function (request, response) { source: function (request, response) {
$.getJSON($form.data('itemsUrl'), { q: request.term }) $.getJSON($form.data('itemsUrl'), { q: request.term })
.done(function (items) { .done(function (items) {
$input.data('qboResults', { term: request.term, items: items });
response(items.map(function (item) { response(items.map(function (item) {
return { label: item.name, value: item.name, item: item }; return { label: item.name, value: item.name, item: item };
})); }));
@@ -124,31 +261,48 @@ $(function () {
.fail(function () { response([]); }); .fail(function () { response([]); });
}, },
select: function (event, ui) { select: function (event, ui) {
var $row = $input.closest('tr'); applyItem($input, ui.item.item);
var item = ui.item.item;
var $description = $row.find('.qbo-line-description-input');
var previous = $row.data('itemDescription');
$input.val(item.name);
$row.find('.qbo-line-item-id').val(item.id);
$row.removeClass('qbo-line-unmatched');
// Keep a description the user typed; replace one that came from the previous product
if (!$description.val().trim() || $description.val() === previous) {
$description.val(item.description || '');
autoGrow($description[0]);
}
$row.data('itemDescription', item.description || '');
if (item.price !== null && item.price !== undefined && item.price !== '') {
$row.find('.qbo-line-rate-input').val(plain(parseFloat(item.price), 5));
tidyNumbers($row);
}
if (!$row.find('.qbo-line-qty-input').val().trim()) $row.find('.qbo-line-qty-input').val('1');
$row.find('.qbo-line-taxable').prop('checked', item.taxable !== false);
changed();
return false; return false;
} }
}); });
// Typing "sub", "subtotal" or "=" then Tab or Enter makes a subtotal here (see insertSubtotalAt)
$input.on('keydown', function (event) {
if ((event.key !== 'Tab' && event.key !== 'Enter') || event.shiftKey) return;
var $row = $input.closest('tr');
if (SUBTOTAL_SHORTCUTS.indexOf($input.val().trim().toLowerCase()) < 0 || $row.find('.qbo-line-item-id').val()) return;
event.preventDefault();
event.stopImmediatePropagation();
var search = $input.autocomplete('instance');
clearTimeout(search.searching);
search.cancelSearch = true;
$input.autocomplete('close');
insertSubtotalAt($row);
});
// Tab picks the product the text points to (an item highlighted in the list is picked by the
// autocomplete itself). If the search hasn't come back yet, the line is filled in when it does.
$input.on('keydown', function (event) {
if (event.key !== 'Tab' || event.shiftKey) return;
var menu = $input.autocomplete('instance').menu;
if (menu && menu.active) return;
var $row = $input.closest('tr');
var term = $input.val();
if ($row.find('.qbo-line-item-id').val() || !term.trim()) return;
var known = $input.data('qboResults');
if (known && known.term.trim().toLowerCase() === term.trim().toLowerCase()) {
var pick = bestItem(term, known.items);
if (pick) applyItem($input, pick);
$input.autocomplete('close');
return;
}
$.getJSON($form.data('itemsUrl'), { q: term }).done(function (items) {
var pick = bestItem(term, items);
if (pick && $input.val() === term && !$row.find('.qbo-line-item-id').val()) applyItem($input, pick);
});
});
$input.autocomplete('instance')._renderItem = function (ul, entry) { $input.autocomplete('instance')._renderItem = function (ul, entry) {
var item = entry.item; var item = entry.item;
var $div = $('<div>'); var $div = $('<div>');
@@ -188,16 +342,42 @@ $(function () {
ensureSpareRow(); ensureSpareRow();
} }
// ---- keyboard ----
// Tabbing into a line's description, quantity or rate selects what's there, so typing replaces it (a click
// still places the cursor)
var tabbedAt = 0;
$(document).on('keydown', function (event) { if (event.key === 'Tab') tabbedAt = Date.now(); });
// A click right after a Tab is still a click
$(document).on('mousedown touchstart', function () { tabbedAt = 0; });
$tbody.on('focus', '.qbo-line-description-input, .qbo-line-qty-input, .qbo-line-rate-input', function () {
if (Date.now() - tabbedAt > 500) return;
// Right away, so the first key typed already replaces the text; and again once the browser has placed
// its cursor (a textarea, the description, puts it back at the start), unless typing has begun
var box = this, before = box.value;
$(box).data('qboTabbedValue', before);
box.select();
setTimeout(function () { if (document.activeElement === box && box.value === before) box.select(); }, 0);
});
// Some browsers (Safari, Firefox) place the cursor after that; the Tab key's release arrives here once they
// have, so select again if nothing was typed yet
$tbody.on('keyup', '.qbo-line-description-input, .qbo-line-qty-input, .qbo-line-rate-input', function (event) {
if (event.key !== 'Tab') return;
var tabbed = $(this).data('qboTabbedValue');
$(this).removeData('qboTabbedValue');
if (tabbed !== undefined && this.value === tabbed) this.select();
});
// ---- line events ---- // ---- line events ----
$tbody.on('input', '.qbo-line-qty-input, .qbo-line-rate-input, .qbo-line-description-input, .qbo-line-item-name', changed); $tbody.on('input', '.qbo-line-qty-input, .qbo-line-rate-input, .qbo-line-description-input, .qbo-line-item-name', changed);
$tbody.on('change', '.qbo-line-taxable', changed); $tbody.on('change', '.qbo-line-taxable', changed);
$tbody.on('input', '.qbo-line-description-input', function () { autoGrow(this); }); $tbody.on('input', '.qbo-line-description-input', function () { autoGrow(this); });
// Typing an amount works out the rate from the quantity // Typing an amount (or math, e.g. 300*1.1, rounded to the penny) works out the rate from the quantity
$tbody.on('input', '.qbo-line-amount-input', function () { $tbody.on('input', '.qbo-line-amount-input', function () {
var $row = $(this).closest('tr'); var $row = $(this).closest('tr');
var amount = parseNumber($(this).val()); var amount = parseNumber($(this).val());
if (amount === null || isNaN(amount)) return; if (amount === null || isNaN(amount)) return;
if (isMath($(this).val().replace(/[$,\s]/g, ''))) amount = round(amount, 2);
var qty = parseNumber($row.find('.qbo-line-qty-input').val()); var qty = parseNumber($row.find('.qbo-line-qty-input').val());
if (qty === null || isNaN(qty) || qty === 0) qty = 1; if (qty === null || isNaN(qty) || qty === 0) qty = 1;
$row.find('.qbo-line-rate-input').val(plain(amount / qty, 5)); $row.find('.qbo-line-rate-input').val(plain(amount / qty, 5));
@@ -210,6 +390,8 @@ $(function () {
var n = parseNumber(this.value); var n = parseNumber(this.value);
if (n === null || isNaN(n)) return; if (n === null || isNaN(n)) return;
var isRate = $(this).hasClass('qbo-line-rate-input'); var isRate = $(this).hasClass('qbo-line-rate-input');
// Math in the rate box is rounded to the nearest penny
if (isRate && isMath(this.value.replace(/[$,\s]/g, ''))) n = round(n, 2);
this.value = isRate && round(n, 2) === round(n, 5) ? n.toFixed(2) : plain(n, 5); this.value = isRate && round(n, 2) === round(n, 5) ? n.toFixed(2) : plain(n, 5);
}); });
} }
@@ -245,10 +427,18 @@ $(function () {
}); });
$('#qbo-estimate-clear-lines').on('click', function () { $('#qbo-estimate-clear-lines').on('click', function () {
if (!window.confirm($(this).data('confirmText'))) return; function clearLines() {
rows().remove(); rows().remove();
addRow(); addRow(); addRow(); addRow();
changed(); changed();
}
// redmine_dark_mode asks in a dark dialog on dark pages; otherwise the browser's own box
var message = $(this).data('confirmText');
if (window.RedmineDarkMode && window.RedmineDarkMode.confirm) {
window.RedmineDarkMode.confirm(message, clearLines);
} else if (window.confirm(message)) {
clearLines();
}
}); });
// Drag lines by the handle to reorder them; they're saved in table order // Drag lines by the handle to reorder them; they're saved in table order
@@ -270,26 +460,27 @@ $(function () {
// ---- customer ---- // ---- customer ----
var $email = $('#qbo_estimate_email'); var $email = $('#qbo_estimate_email');
var $vin = $('#qbo_estimate_vin');
var loadedEmail = $email.val(); var loadedEmail = $email.val();
$('#customer_id').on('change', function () { $('#customer_id').on('change', function () {
var id = $(this).val(); var id = $(this).val();
if (!id) return; if (!id) return;
dirty = true; dirty = true;
$.getJSON($form.data('customerInfoUrl'), { customer_id: id }).done(function (info) { $.getJSON($form.data('customerInfoUrl'), { customer_id: id, document: $form.data('document') }).done(function (info) {
// A new invoice's open issues notice follows the customer
if (info.open_issues_html !== undefined) $('#qbo-open-issues').replaceWith(info.open_issues_html);
// Replace the email only if it was the previous customer's (or empty) // Replace the email only if it was the previous customer's (or empty)
if (!$email.val().trim() || $email.val() === loadedEmail) $email.val(info.email || ''); if (!$email.val().trim() || $email.val() === loadedEmail) $email.val(info.email || '');
loadedEmail = info.email || ''; loadedEmail = info.email || '';
$('#qbo-estimate-address').text(info.billing_address || ''); $('#qbo-estimate-address').text(info.billing_address || '');
var $list = $('#qbo-estimate-vins').empty(); // Plugins' suggestions for this customer go in the custom field boxes' lists; the boxes themselves
(info.vehicles || []).forEach(function (vehicle) { // stay as they are (a new document starts blank)
$('<option>').attr('value', vehicle.vin).text(vehicle.name).appendTo($list); $form.find('.qbo-field-custom').each(function () {
var fieldId = $(this).data('qboFieldId');
window.qboEditor.setFieldOptions(fieldId, (info.field_options || {})[String(fieldId)]);
}); });
if ($vin.length && !$vin.prop('disabled') && !$vin.val().trim() && (info.vehicles || []).length === 1) { $form.trigger('qbo:customer-changed', [{ customer_id: id, info: info }]);
$vin.val(info.vehicles[0].vin);
}
}); });
}); });
@@ -298,8 +489,6 @@ $(function () {
if (!this.value.trim()) $('#customer_id').val(''); if (!this.value.trim()) $('#customer_id').val('');
}); });
$vin.on('blur', function () { this.value = this.value.trim().toUpperCase(); });
// New estimates expire a set number of days after the estimate date (plugin setting) // New estimates expire a set number of days after the estimate date (plugin setting)
var expirationDays = parseInt($form.data('expirationDays'), 10) || 0; var expirationDays = parseInt($form.data('expirationDays'), 10) || 0;
var $txnDate = $('#qbo_estimate_txn_date'); var $txnDate = $('#qbo_estimate_txn_date');
@@ -381,22 +570,22 @@ $(function () {
return ids; return ids;
}; };
// VIN and mileage from the work orders (via plugins such as redmine_qbo_vehicles and redmine_mileage_cp): // Pairs imported time with the invoice lines ticked under "Replace these lines": first by description,
// one vehicle fills the VIN box; the highest mileage fills the mileage box // since issues created from an estimate take the line's description as their subject and the time names
var updateVehicleFields = function (issueIds) { // it ("Install #134: Install Lift Kit" <-> "Install Lift Kit"); what's left is paired in order.
var values = (importData && importData.issue_values) || {}; // Returns { pairs: [{ time, line }], extraTimes: [...], extraLines: [...] }.
var vins = [], mileage = null; var pairTimeWithLines = function (times, lines) {
issueIds.forEach(function (id) { var norm = function (text) { return String(text || '').split('\n')[0].toLowerCase().replace(/\s+/g, ' ').trim(); };
var v = values[id] || {}; var subject = function (activity) { return norm(String(activity.description || '').replace(/^[^\n]*?#\d+:\s*/, '')); };
if (v.vin && vins.indexOf(v.vin.toUpperCase()) < 0) vins.push(v.vin.toUpperCase()); var lineText = function (line) { return norm($(line).find('.qbo-line-description-input').val()); };
var miles = parseNumber(v.mileage); var freeTimes = times.slice(), freeLines = [], pairs = [];
if (miles !== null && !isNaN(miles) && (mileage === null || miles > mileage)) mileage = miles; lines.forEach(function (line) {
var text = lineText(line);
var i = text ? freeTimes.findIndex(function (t) { return subject(t) === text; }) : -1;
if (i >= 0) { pairs.push({ time: freeTimes[i], line: line }); freeTimes.splice(i, 1); } else { freeLines.push(line); }
}); });
var $vinBox = $('#qbo_estimate_vin'); while (freeTimes.length && freeLines.length) pairs.push({ time: freeTimes.shift(), line: freeLines.shift() });
if (vins.length === 1 && $vinBox.length && !$vinBox.prop('disabled')) $vinBox.val(vins[0]); return { pairs: pairs, extraTimes: freeTimes, extraLines: freeLines };
var $mileageBox = $('#qbo_estimate_mileage');
if (mileage !== null && $mileageBox.length) $mileageBox.val(String(mileage));
return vins;
}; };
// Rows go after the last filled line, above the spare empty rows // Rows go after the last filled line, above the spare empty rows
@@ -414,9 +603,9 @@ $(function () {
}; };
// The invoice's lines, for ticking the ones the time replaces (e.g. the estimate's labor lines). // The invoice's lines, for ticking the ones the time replaces (e.g. the estimate's labor lines).
// When products/services are set as replaceable by time in the plugin settings, only lines with one of // Only lines with one of the labor products/services (plugin settings) are offered; if none are known,
// them are offered; with none set, every line is. // every line is.
var replaceable = ($form.data('replaceableItemIds') || []).map(String); var replaceable = ($form.data('laborItemIds') || []).map(String);
var fillReplaceList = function () { var fillReplaceList = function () {
var $list = $('#qbo-import-replace').empty(); var $list = $('#qbo-import-replace').empty();
rows().each(function () { rows().each(function () {
@@ -493,15 +682,24 @@ $(function () {
// Kept so the import can be undone before saving (clones keep what was typed) // Kept so the import can be undone before saving (clones keep what was typed)
undoState = { rows: rows().clone(), linked: $('#qbo-linked-estimates').children().clone() }; undoState = { rows: rows().clone(), linked: $('#qbo-linked-estimates').children().clone() };
// Time goes where the first ticked line was; the ticked lines are removed // Each time entry replaces one ticked line, in that line's place (see pairTimeWithLines). Time left over
// goes after the last replaced line; ticked lines left over are removed (ticked means replace).
if (times.length) { if (times.length) {
var $timeRows = $(times.map(function (activity) { var ticked = $('#qbo-import-replace input:checked').map(function () { return $(this).data('row')[0]; }).get();
return makeRow($.extend({}, activity, { time_activity_id: activity.id }))[0]; ticked = rows().get().filter(function (row) { return ticked.indexOf(row) >= 0; }); // table order
})); var pairing = pairTimeWithLines(times, ticked);
var $replaced = $('#qbo-import-replace input:checked').map(function () { return $(this).data('row')[0]; }); var timeRow = function (activity) { return makeRow($.extend({}, activity, { time_activity_id: activity.id })); };
var $anchor = rows().filter(function () { return $replaced.index(this) >= 0; }).first(); var $last = $();
if ($anchor.length) { $anchor.before($timeRows); } else { insertAfterFilled($timeRows); } pairing.pairs.forEach(function (pair) {
$replaced.remove(); var $row = timeRow(pair.time);
$(pair.line).replaceWith($row);
if (!$last.length || $row.index() > $last.index()) $last = $row;
});
pairing.extraLines.forEach(function (line) { $(line).remove(); });
if (pairing.extraTimes.length) {
var $extra = $(pairing.extraTimes.map(function (activity) { return timeRow(activity)[0]; }));
if ($last.length) { $last.after($extra); } else { insertAfterFilled($extra); }
}
} }
// Each estimate's lines go right after the time for the same issue (e.g. lineitems' "Added from: // Each estimate's lines go right after the time for the same issue (e.g. lineitems' "Added from:
@@ -538,9 +736,10 @@ $(function () {
estimates.forEach(function (estimate) { estimates.forEach(function (estimate) {
if (estimate.issue_id && issueIds.indexOf(String(estimate.issue_id)) < 0) issueIds.push(String(estimate.issue_id)); if (estimate.issue_id && issueIds.indexOf(String(estimate.issue_id)) < 0) issueIds.push(String(estimate.issue_id));
}); });
var vins = updateVehicleFields(issueIds);
$panel.prop('hidden', true); $panel.prop('hidden', true);
if (vins.length > 1) window.alert($panel.data('manyVehiclesText') + ' ' + vins.join(', ')); // Plugins fill their custom fields from the work orders (e.g. redmine_qbo_vehicles: VIN and mileage)
$form.trigger('qbo:imported', [{ issue_ids: issueIds, estimates: estimates,
issue_values: (importData && importData.issue_values) || {} }]);
$('#qbo-import-undo').prop('hidden', false); $('#qbo-import-undo').prop('hidden', false);
}); });
@@ -556,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; });
@@ -564,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();
@@ -572,7 +785,41 @@ $(function () {
$email.trigger('focus'); $email.trigger('focus');
return; return;
} }
// Math still in a box is worked out before saving
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) {
@@ -0,0 +1,17 @@
<%# QuickBooks status badges: the estimate page's header and the estimate lists (customer and vehicle pages) %>
<style>
.qbo-estimate-status { display: inline-block; font-size: .6em; font-weight: 600; vertical-align: middle; padding: 2px 8px; border-radius: 10px;
background: #eceef1; color: #393a3d; margin-left: 6px; }
.qbo-estimate-status-sent { background: #e6f4e4; color: #108000; }
.qbo-estimate-status-accepted { background: #e6f4e4; color: #108000; }
.qbo-estimate-status-closed, .qbo-estimate-status-converted { background: #e8eefa; color: #0d47a1; }
.qbo-estimate-status-rejected { background: #fdecea; color: #b71c1c; }
.qbo-estimate-list .qbo-estimate-status { font-size: .8em; padding: 1px 7px; margin-left: 4px; }
/* Invoices (RedmineQboBilling::InvoiceStatus) */
.qbo-invoice-status-paid { background: #e6f4e4; color: #108000; }
.qbo-invoice-status-partial { background: #fff4d6; color: #8a6100; }
.qbo-invoice-status-overdue { background: #fdecea; color: #b71c1c; }
.qbo-invoice-status-open { background: #e8eefa; color: #0d47a1; }
.qbo-invoice-status-voided { background: #eceef1; color: #6b6c72; text-decoration: line-through; }
.qbo-invoice-list .qbo-estimate-status { font-size: .8em; padding: 1px 7px; margin-left: 4px; }
</style>
+22 -9
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; }
@@ -24,8 +29,7 @@
.qbo-field-date input { width: 150px; } .qbo-field-date input { width: 150px; }
.qbo-field-number input { width: 160px; } .qbo-field-number input { width: 160px; }
.qbo-field-sales-person input { width: 200px; } .qbo-field-sales-person input { width: 200px; }
.qbo-field-vin input { width: 220px; font-family: monospace; text-transform: uppercase; } .qbo-field-custom input { width: 200px; }
.qbo-field-mileage input { width: 120px; }
.qbo-field-refresh { align-self: flex-end; padding-bottom: 6px; max-width: 420px; } .qbo-field-refresh { align-self: flex-end; padding-bottom: 6px; max-width: 420px; }
.qbo-address { min-width: 220px; min-height: 4.5em; white-space: pre-line; color: #393a3d; padding: 6px 0; line-height: 1.4; } .qbo-address { min-width: 220px; min-height: 4.5em; white-space: pre-line; color: #393a3d; padding: 6px 0; line-height: 1.4; }
.qbo-estimate-amount { text-align: right; flex-shrink: 0; } .qbo-estimate-amount { text-align: right; flex-shrink: 0; }
@@ -96,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; }
@@ -112,16 +119,21 @@
.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; }
.qbo-estimate-status { display: inline-block; font-size: .6em; font-weight: 600; vertical-align: middle; padding: 2px 8px; border-radius: 10px; /* While saving: the buttons are locked and a spinner says what's happening */
background: #eceef1; color: #393a3d; margin-left: 6px; } .qbo-estimate .qbo-saving .qbo-button[disabled],
.qbo-estimate-status-sent { background: #e6f4e4; color: #108000; } .qbo-estimate .qbo-saving .qbo-button-disabled { opacity: .6; cursor: progress; pointer-events: none; }
.qbo-estimate-status-accepted { background: #e6f4e4; color: #108000; } .qbo-estimate .qbo-saving-status { display: inline-flex; align-items: center; gap: 8px; color: #fff; font-weight: 600; margin-right: 8px; }
.qbo-estimate-status-closed, .qbo-estimate-status-converted { background: #e8eefa; color: #0d47a1; } .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; }
div.warning.qbo-estimate-notice li { margin: 2px 0; } div.warning.qbo-estimate-notice li { margin: 2px 0; }
.qbo-estimate-status-rejected { background: #fdecea; color: #b71c1c; }
.qbo-estimate-edit-link { margin-left: 4px; vertical-align: middle; } .qbo-estimate-edit-link { margin-left: 4px; vertical-align: middle; }
/* Phones: each line becomes a small card (number, product and delete; description; qty, rate, amount and tax) */ /* Phones: each line becomes a small card (number, product and delete; description; qty, rate, amount and tax) */
@@ -161,3 +173,4 @@
.qbo-estimate-actions { padding: 10px 14px; } .qbo-estimate-actions { padding: 10px 14px; }
} }
</style> </style>
<%= render partial: 'qbo_estimates/status_styles' %>
+2 -2
View File
@@ -2,9 +2,9 @@
<div class="contextual"> <div class="contextual">
<%# Plugins add estimate actions here (e.g. redmine_qbo_calendar's Add appointment) %> <%# Plugins add estimate actions here (e.g. redmine_qbo_calendar's Add appointment) %>
<%= call_hook :view_qbo_estimate_contextual, { estimate_id: @form.id, customer_id: @form.customer_id, vin: @form.vin, doc_number: @form.doc_number } %> <%= call_hook :view_qbo_estimate_contextual, { estimate_id: @form.id, customer_id: @form.customer_id, custom_fields: @form.custom_fields, doc_number: @form.doc_number } %>
<%# An estimate is billed once: no Create invoice once it's on an invoice, closed or rejected %> <%# An estimate is billed once: no Create invoice once it's on an invoice, closed or rejected %>
<% if RedmineQboBilling.invoice_writer? && Array(@form.invoiced_on).empty? && !%w[Converted Closed Rejected].include?(@form.txn_status.to_s) %> <% if RedmineQboBilling.invoice_writer? && @form.locked != :billed && @form.txn_status.to_s != 'Rejected' %>
<%= link_to sprite_icon('document', l(:button_create_invoice)), new_qbo_invoice_path(estimate_id: @form.id), class: 'icon icon-document' %> <%= link_to sprite_icon('document', l(:button_create_invoice)), new_qbo_invoice_path(estimate_id: @form.id), class: 'icon icon-document' %>
<% end %> <% end %>
<% if User.current.allowed_to?(:create_estimate_issues, nil, global: true) %> <% if User.current.allowed_to?(:create_estimate_issues, nil, global: true) %>
+68 -15
View File
@@ -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, vehicle and custom field values) %>
<%= 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>
@@ -45,7 +77,7 @@
<% if proposals.empty? %> <% if proposals.empty? %>
<p class="nodata"> <p class="nodata">
<%= l(:error_no_labor_lines_found) %> <%= l(:error_no_labor_lines_found) %>
(<%= l(:label_estimate_item_codes) %>: <%= RedmineQboBilling::EstimateIssueBuilder.item_codes.join(', ') %>) (<%= l(:label_labor_items) %>: <%= RedmineQboBilling::LaborItems.names.join(', ') %>)
<% if User.current.admin? %> <% if User.current.admin? %>
&middot; <%= link_to l(:label_settings), plugin_settings_path(id: 'redmine_qbo') %> &middot; <%= link_to l(:label_settings), plugin_settings_path(id: 'redmine_qbo') %>
<% end %> <% end %>
@@ -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,12 +169,30 @@
</tbody> </tbody>
</table> </table>
<%# Custom fields for the chosen trackers, entered once and applied to every issue that uses them %> <%# Dates for every issue: from the appointment the page was opened from, else the parent task; blank means none %>
<% if @field_set&.any? %> <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
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 }) %>
<% if @field_set&.any? || plugin_fields.present? %>
<fieldset class="box tabular estimate-issue-fields" id="estimate-issue-fields"> <fieldset class="box tabular estimate-issue-fields" id="estimate-issue-fields">
<legend><%= l(:label_estimate_issue_fields) %></legend> <legend><%= l(:label_estimate_issue_fields) %></legend>
<p class="estimate-issue-fields-info"><em class="info"><%= l(:text_estimate_issue_fields_info) %></em></p> <p class="estimate-issue-fields-info"><em class="info"><%= l(:text_estimate_issue_fields_info) %></em></p>
<% @field_set.fields.each do |field| %> <%= plugin_fields %>
<% Array(@field_set&.fields).each do |field| %>
<p class="estimate-issue-field" <p class="estimate-issue-field"
data-tracker-ids="<%= field.tracker_ids.join(',') %>" data-tracker-ids="<%= field.tracker_ids.join(',') %>"
data-required-tracker-ids="<%= field.required_tracker_ids.join(',') %>"> data-required-tracker-ids="<%= field.required_tracker_ids.join(',') %>">
@@ -231,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 } %>
@@ -0,0 +1,17 @@
<%# A new invoice's customer still has open issues (work orders), so they're not left behind once billed.
Replaced when the customer is changed (customer_info's open_issues_html). %>
<%
issues = customer ? customer.issues.open.visible.order(id: :desc).to_a : []
%>
<div id="qbo-open-issues">
<% if issues.any? %>
<div class="warning qbo-estimate-notice">
<%= l(:text_invoice_customer_open_issues, count: issues.size) %>
<ul>
<% issues.each do |issue| %>
<li><%= link_to_issue(issue, truncate: 60) %> (<%= issue.status %>)</li>
<% end %>
</ul>
</div>
<% end %>
</div>
+2
View File
@@ -1,6 +1,8 @@
<% 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 %>
+3 -1
View File
@@ -1,4 +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_estimates/form', 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_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,15 @@
<% 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.estimate_number.present? ? "E#{@refund.estimate_number}" : t(:label_refund_your_order)) %>
<% 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) %>
<%= t(:text_refund_email_terms) %>
<%= @shop_name %>
+122
View File
@@ -0,0 +1,122 @@
<%# 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>
<% 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 %>
+64
View File
@@ -0,0 +1,64 @@
<%# 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? %>
<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">
<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>
<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>
<%= money.(@refund.fee_amount) %>
<% 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.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.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>
+496
View File
@@ -0,0 +1,496 @@
<% html_title l(:label_business_report) %>
<% money = @report.money %>
<% hours = @report.hours %>
<% ratios = @report.ratios %>
<% max_money = [money[:estimates][:total], money[:invoices][:total], money[:paid][:total], money[:payments][:total]].max.to_f %>
<% max_hours = hours.values.max.to_f %>
<% bar = ->(value, max) { max > 0 ? (value.to_f / max * 100).round(1) : 0 } %>
<% fmt_hours = ->(h) { format('%.1f', h.to_f) } %>
<% pct = ->(v) { v.nil? ? '–' : "#{v}%" } %>
<%# Line charts: a label and a tooltip title per point, from the chart's granularity %>
<% chart = @report.chart %>
<% months_abbr = ::I18n.t('date.abbr_month_names') %>
<% days_abbr = ::I18n.t('date.abbr_day_names') %>
<% one_year = @report.from.year == @report.to.year %>
<% point_label = lambda do |date|
case chart[:granularity]
when :day then "#{days_abbr[date.wday]} #{date.day}"
when :week then "#{months_abbr[date.month]} #{date.day}"
else one_year ? months_abbr[date.month] : "#{months_abbr[date.month]} #{date.year}"
end
end %>
<% point_title = lambda do |first, last|
case chart[:granularity]
when :day then format_date(first)
when :week then "#{format_date(first)} – #{format_date(last)}"
else "#{::I18n.t('date.month_names')[first.month]} #{first.year}"
end
end %>
<% previous_ends = chart[:previous_points].each_with_index.map { |p, i| Date.parse(p) + (Date.parse(chart[:ends][i]) - Date.parse(chart[:points][i])) } %>
<% chart_points = {
labels: chart[:points].map { |p| point_label.call(Date.parse(p)) },
titles: chart[:points].each_with_index.map { |p, i| point_title.call(Date.parse(p), Date.parse(chart[:ends][i])) },
previous_titles: chart[:previous_points].each_with_index.map { |p, i| point_title.call(Date.parse(p), previous_ends[i]) },
last_year: l(:label_report_last_year)
} %>
<% chart_series = lambda do |keys|
keys.map do |key, label, color|
{ label: label, color: color, current: chart[:current][key], previous: chart[:previous][key] }
end
end %>
<% sales_series = chart_series.call([[:estimates, l(:label_report_estimates_written), '#628db6'],
[:invoices, l(:label_report_invoices_written), '#e8a33d'],
[:paid, l(:label_report_invoices_paid), '#c0504d'],
[:payments, l(:label_report_payments_received), '#5aa05a']]) %>
<% taxes = @report.taxes %>
<% max_tax = taxes.values.map { |t| t[:total] }.max.to_f %>
<% tax_series = chart_series.call([[:tax_invoiced, l(:label_report_tax_invoiced), '#e8a33d'],
[:tax_collected, l(:label_report_tax_collected), '#c0504d']]) %>
<% hours_series = chart_series.call([[:estimate_hours, l(:label_report_estimate_hours), '#628db6'],
[:issue_hours, l(:label_report_issue_hours), '#9b7fc0'],
[:invoice_hours, l(:label_report_invoice_hours), '#e8a33d'],
[:spent_hours, l(:label_report_spent_hours), '#5aa05a']]) %>
<h2><%= l(:label_business_report) %></h2>
<%= form_tag qbo_reports_path, method: :get, id: 'qbo-report-form' do %>
<fieldset class="box">
<legend><%= l(:label_report_period) %></legend>
<%= select_tag 'period',
options_for_select(RedmineQboBilling::BusinessReport::PERIODS.map { |p| [l("label_report_period_#{p}"), p] }, @report.period),
id: 'qbo-report-period' %>
<span id="qbo-report-dates">
<%= date_field_tag 'from', @report.from.iso8601, id: 'qbo-report-from' %>
&ndash;
<%= date_field_tag 'to', @report.to.iso8601, id: 'qbo-report-to' %>
</span>
<%= submit_tag l(:button_apply), name: nil %>
<label class="qbo-report-compare">
<%= check_box_tag 'compare', '1', @compare, id: 'qbo-report-compare' %>
<%= l(:label_report_compare_last_year) %>
</label>
<%# Projects for the issues and spent time; the blank value sends project_ids when none are picked (every project) %>
<div class="qbo-report-projects">
<label for="qbo-report-project-ids"><%= l(:label_project_plural) %></label>
<%= hidden_field_tag 'project_ids[]', '', id: nil %>
<%= select_tag 'project_ids[]',
project_tree_options_for_select(@projects, selected: @projects.select { |p| @project_ids.include?(p.id) }),
multiple: true, size: [[@projects.size, 3].max, 8].min, id: 'qbo-report-project-ids' %>
<span class="qbo-report-projects-options">
<em class="info"><%= l(:text_report_projects) %></em>
<label>
<%= check_box_tag 'save_projects', '1', false, id: 'qbo-report-save-projects' %>
<%= l(:label_report_remember_projects) %>
</label>
<% if @saved_project_ids.any? %>
<em class="info"><%= l(:text_report_saved_projects, projects: @projects.select { |p| @saved_project_ids.include?(p.id) }.map(&:name).join(', ')) %></em>
<% end %>
</span>
</div>
</fieldset>
<% end %>
<p class="qbo-report-range">
<%= format_date(@report.from) %> &ndash; <%= format_date(@report.to) %>
<% if @report.projects_filtered? %>
&middot; <%= l(:label_project_plural) %>: <%= @projects.select { |p| @project_ids.include?(p.id) }.map(&:name).join(', ') %>
<% end %>
</p>
<% if @report.projects_filtered? %>
<p class="info qbo-report-projects-note"><%= l(:text_report_projects_filtered) %></p>
<% end %>
<% if Array(@syncing).any? %>
<% sync_labels = { 'Estimate' => l(:label_estimates), 'Invoice' => l(:label_invoices), 'Payment' => l(:label_payments) } %>
<div class="warning qbo-report-syncing">
<%= l(:text_report_syncing) %>
<ul>
<% @syncing.each do |status| %>
<li>
<strong><%= sync_labels[status.entity] || status.entity %></strong>:
<% if status.running? %>
<%= l(:text_qbo_sync_running, count: number_with_delimiter(status.processed),
time: format_time(status.started_at)) %>
<% else %>
<%= l(:text_qbo_sync_queued) %>
<% end %>
</li>
<% end %>
</ul>
</div>
<%= javascript_tag do %>
// Refresh while QuickBooks is syncing, so the figures fill in
setTimeout(function () { window.location.reload(); }, 30000);
<% end %>
<% end %>
<% if @report.unsynced_count > 0 %>
<p class="warning"><%= l(:text_report_needs_sync, count: @report.unsynced_count) %></p>
<% end %>
<div class="splitcontent">
<div class="splitcontentleft">
<h3><%= l(:label_report_money) %></h3>
<div class="qbo-report-chart">
<canvas id="qbo-chart-sales" data-kind="money" data-series="<%= sales_series.to_json %>"></canvas>
</div>
<table class="list qbo-report">
<tbody>
<% [[:estimates, l(:label_report_estimates_written)], [:invoices, l(:label_report_invoices_written)],
[:paid, l(:label_report_invoices_paid)], [:payments, l(:label_report_payments_received)]].each do |key, label| %>
<tr>
<td class="name"><%= label %> <span class="count">(<%= money[key][:count] %>)</span></td>
<td class="bar"><div class="qbo-bar qbo-bar-<%= key %>" style="width: <%= bar.call(money[key][:total], max_money) %>%"></div></td>
<td class="value"><%= number_to_currency(money[key][:total]) %></td>
</tr>
<% end %>
</tbody>
</table>
<p class="qbo-report-ratios">
<%= l(:label_report_invoiced_of_estimated) %>: <strong><%= pct.call(ratios[:invoiced_of_estimated]) %></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>
</p>
<p><em class="info"><%= l(:text_report_without_tax) %></em></p>
</div>
<div class="splitcontentright">
<h3><%= l(:label_report_hours) %></h3>
<div class="qbo-report-chart">
<canvas id="qbo-chart-hours" data-kind="hours" data-series="<%= hours_series.to_json %>"></canvas>
</div>
<table class="list qbo-report">
<tbody>
<% [[:estimate_hours, l(:label_report_estimate_hours)], [:issue_hours, l(:label_report_issue_hours)],
[:invoice_hours, l(:label_report_invoice_hours)], [:spent_hours, l(:label_report_spent_hours)]].each do |key, label| %>
<tr>
<td class="name"><%= label %></td>
<td class="bar"><div class="qbo-bar qbo-bar-<%= key %>" style="width: <%= bar.call(hours[key], max_hours) %>%"></div></td>
<td class="value"><%= fmt_hours.call(hours[key]) %></td>
</tr>
<% end %>
</tbody>
</table>
<% cpi_badge = lambda do |cpi|
level = RedmineQboBilling::BusinessReport.cpi_level(cpi)
content_tag(:span, cpi.nil? ? '–' : format('%.2f', cpi), class: "qbo-cpi qbo-cpi-#{level || 'none'}")
end %>
<p class="qbo-report-cpi">
<span class="qbo-cpi-label" title="<%= l(:text_report_cpi) %>"><%= l(:label_report_cpi) %></span>
<%= cpi_badge.call(@report.cpi) %>
<em class="info"><%= l(:text_report_cpi) %></em>
</p>
<p class="qbo-report-ratios">
<%= l(:label_report_spent_of_estimated) %>: <strong><%= pct.call(ratios[:spent_of_estimated]) %></strong>
</p>
</div>
</div>
<h3><%= l(:label_report_by_month) %></h3>
<div class="autoscroll">
<table class="list qbo-report-months">
<thead>
<tr>
<th class="month"><%= l(:label_month) %></th>
<th><%= l(:label_report_estimates_written) %></th>
<th><%= l(:label_report_invoices_written) %></th>
<th><%= l(:label_report_invoices_paid) %></th>
<th><%= l(:label_report_payments_received) %></th>
<th class="hours-start"><%= l(:label_report_estimate_hours) %></th>
<th><%= l(:label_report_issue_hours) %></th>
<th><%= l(:label_report_invoice_hours) %></th>
<th><%= l(:label_report_spent_hours) %></th>
<th class="cpi"><%= l(:label_report_cpi_short) %></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[:estimates]) %></td>
<td><%= number_to_currency(row[:invoices]) %></td>
<td><%= number_to_currency(row[:paid]) %></td>
<td><%= number_to_currency(row[:payments]) %></td>
<td class="hours-start"><%= fmt_hours.call(row[:estimate_hours]) %></td>
<td><%= fmt_hours.call(row[:issue_hours]) %></td>
<td><%= fmt_hours.call(row[:invoice_hours]) %></td>
<td><%= fmt_hours.call(row[:spent_hours]) %></td>
<td class="cpi"><%= cpi_badge.call(RedmineQboBilling::BusinessReport.cpi(row[:invoice_hours], row[:spent_hours])) %></td>
</tr>
<% end %>
</tbody>
<tfoot>
<tr class="total">
<td class="month"><strong><%= l(:label_total) %></strong></td>
<td><strong><%= number_to_currency(money[:estimates][:total]) %></strong></td>
<td><strong><%= number_to_currency(money[:invoices][:total]) %></strong></td>
<td><strong><%= number_to_currency(money[:paid][:total]) %></strong></td>
<td><strong><%= number_to_currency(money[:payments][:total]) %></strong></td>
<td class="hours-start"><strong><%= fmt_hours.call(hours[:estimate_hours]) %></strong></td>
<td><strong><%= fmt_hours.call(hours[:issue_hours]) %></strong></td>
<td><strong><%= fmt_hours.call(hours[:invoice_hours]) %></strong></td>
<td><strong><%= fmt_hours.call(hours[:spent_hours]) %></strong></td>
<td class="cpi"><%= cpi_badge.call(@report.cpi) %></td>
</tr>
</tfoot>
</table>
</div>
<h3><%= l(:label_report_taxes) %></h3>
<div class="splitcontent">
<div class="splitcontentleft">
<div class="qbo-report-chart">
<canvas id="qbo-chart-taxes" data-kind="money" data-series="<%= tax_series.to_json %>"></canvas>
</div>
<table class="list qbo-report">
<tbody>
<% [[:tax_invoiced, l(:label_report_tax_invoiced)], [:tax_collected, l(:label_report_tax_collected)]].each do |key, label| %>
<tr>
<td class="name"><%= label %> <span class="count">(<%= l(:label_report_taxed_invoices, count: taxes[key][:count]) %>)</span></td>
<td class="bar"><div class="qbo-bar qbo-bar-<%= key %>" style="width: <%= bar.call(taxes[key][:total], max_tax) %>%"></div></td>
<td class="value"><%= number_to_currency(taxes[key][:total]) %></td>
</tr>
<% end %>
</tbody>
</table>
<p><em class="info"><%= l(:text_report_taxes) %></em></p>
</div>
<div class="splitcontentright">
<table class="list qbo-report-months qbo-report-tax-months">
<thead>
<tr>
<th class="month"><%= l(:label_month) %></th>
<th><%= l(:label_report_tax_invoiced) %></th>
<th><%= l(:label_report_tax_collected) %></th>
</tr>
</thead>
<tbody>
<% @report.months.each do |row| %>
<tr>
<td class="month"><%= ::I18n.t('date.abbr_month_names')[row[:month].month] %> <%= row[:month].year %></td>
<td><%= number_to_currency(row[:tax_invoiced]) %></td>
<td><%= number_to_currency(row[:tax_collected]) %></td>
</tr>
<% end %>
</tbody>
<tfoot>
<tr class="total">
<td class="month"><strong><%= l(:label_total) %></strong></td>
<td><strong><%= number_to_currency(taxes[:tax_invoiced][:total]) %></strong></td>
<td><strong><%= number_to_currency(taxes[:tax_collected][:total]) %></strong></td>
</tr>
</tfoot>
</table>
</div>
</div>
<p class="info"><%= l(:text_report_notes) %></p>
<style>
table.qbo-report td { padding: 6px 4px; }
table.qbo-report td.name { text-align: left; white-space: nowrap; width: 1%; }
table.qbo-report td.name .count { color: #888; }
table.qbo-report td.bar { width: 100%; }
table.qbo-report td.value { text-align: right; white-space: nowrap; font-weight: bold; width: 1%; }
.qbo-bar { height: 14px; border-radius: 2px; min-width: 1px; background: #628db6; }
.qbo-bar-invoices, .qbo-bar-invoice_hours { background: #e8a33d; }
.qbo-bar-payments, .qbo-bar-spent_hours { background: #5aa05a; }
.qbo-bar-paid, .qbo-bar-tax_collected { background: #c0504d; }
.qbo-bar-tax_invoiced { background: #e8a33d; }
.qbo-bar-issue_hours { background: #9b7fc0; }
.qbo-report-ratios { margin: 8px 4px; line-height: 1.7; }
.qbo-report-cpi { margin: 10px 4px 4px; }
.qbo-report-cpi .qbo-cpi-label { font-weight: 600; margin-right: 6px; }
.qbo-report-cpi .qbo-cpi { font-size: 1.3em; padding: 3px 12px; }
.qbo-report-cpi em.info { display: block; margin-top: 4px; }
.qbo-cpi { display: inline-block; font-weight: 700; padding: 1px 8px; border-radius: 10px; background: #eceef1; color: #393a3d; }
.qbo-cpi-poor { background: #fdecea; color: #b71c1c; }
.qbo-cpi-under { background: #fff4d6; color: #8a6100; }
.qbo-cpi-good { background: #e6f4e4; color: #108000; }
table.qbo-report-months td.cpi, table.qbo-report-months th.cpi { text-align: center; }
.qbo-report-range { color: #666; margin: 4px 0 10px; }
.qbo-report-syncing ul { display: inline-block; text-align: left; margin: 6px 0 0; }
table.qbo-report-months td, table.qbo-report-months th { text-align: right; white-space: nowrap; }
table.qbo-report-months .month { text-align: left; }
table.qbo-report-months .hours-start { border-left: 2px solid #ddd; }
table.qbo-report-months tfoot td { border-top: 2px solid #ccc; }
#qbo-report-form select, #qbo-report-form input { vertical-align: middle; }
#qbo-report-form .qbo-report-compare { margin-left: 12px; white-space: nowrap; }
#qbo-report-form .qbo-report-projects { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 6px 10px; margin-top: 8px; }
#qbo-report-form .qbo-report-projects select { min-width: 220px; max-width: 100%; }
#qbo-report-form .qbo-report-projects-options { display: flex; flex-direction: column; gap: 4px; }
#qbo-report-form .qbo-report-projects-options label { white-space: nowrap; }
.qbo-report-chart { position: relative; height: 260px; margin: 4px 4px 16px; }
</style>
<%= javascript_tag do %>
$(function() {
var $period = $('#qbo-report-period'), $dates = $('#qbo-report-from, #qbo-report-to');
// Picking a preset fills its dates on Apply; changing a date switches to Custom
$dates.on('change', function() { $period.val('custom'); });
$period.on('change', function() { if ($period.val() !== 'custom') { $('#qbo-report-form').submit(); } });
});
// Line charts (Chart.js 4): the same figures and colors as the bars, a point per day,
// week or month. "Compare with last year" adds last year's lines, dashed and faded, without reloading.
(function() {
var points = <%= raw chart_points.to_json %>;
// The currency layout the tables use, e.g. "$%n"
var currencyFormat = <%= raw number_to_currency(0, precision: 0).to_s.sub('0', '%n').to_json %>;
var charts = [];
function money(v, decimals) {
var n = Number(v || 0).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
return currencyFormat.replace('%n', n);
}
function hours(v) { return Number(v || 0).toFixed(1); }
function faded(hex) {
var n = parseInt(hex.slice(1), 16);
return 'rgba(' + (n >> 16 & 255) + ',' + (n >> 8 & 255) + ',' + (n & 255) + ',0.45)';
}
// Grid lines and text from the page's colours, so a dark mode (e.g. redmine_dark_mode) can set
// --qbo-chart-grid and --qbo-chart-text; Chart.js' own colours otherwise
function chartColors() {
var style = getComputedStyle(document.documentElement);
return { grid: style.getPropertyValue('--qbo-chart-grid').trim() || 'rgba(0,0,0,0.1)',
text: style.getPropertyValue('--qbo-chart-text').trim() || '#666' };
}
function applyColors(chart) {
var c = chartColors();
['x', 'y'].forEach(function(axis) {
var scale = chart.options.scales[axis];
scale.grid.color = c.grid;
scale.border.color = c.grid;
scale.ticks.color = c.text;
});
chart.options.plugins.legend.labels.color = c.text;
}
function draw(Chart, canvas, compare) {
var series = JSON.parse(canvas.getAttribute('data-series'));
var isMoney = canvas.getAttribute('data-kind') === 'money';
var colors = chartColors();
var datasets = [];
series.forEach(function(s) {
datasets.push({ label: s.label, data: s.current, borderColor: s.color, backgroundColor: s.color,
fill: false, cubicInterpolationMode: 'monotone', pointRadius: 3, pointHoverRadius: 5, spanGaps: false, order: 1 });
});
series.forEach(function(s) {
datasets.push({ label: s.label + ' (' + points.last_year + ')', data: s.previous, previous: true,
borderColor: faded(s.color), backgroundColor: faded(s.color), borderDash: [6, 4],
borderWidth: 2, fill: false, cubicInterpolationMode: 'monotone', pointRadius: 2, pointHoverRadius: 4,
hidden: !compare, order: 2 });
});
return new Chart(canvas, {
type: 'line',
data: { labels: points.labels, datasets: datasets },
options: {
responsive: true,
maintainAspectRatio: false,
interaction: { mode: 'index', intersect: false },
plugins: {
// One entry per figure (clicking it hides this year's and last year's line), plus a single
// dashed "last year" entry while comparing (clicking it turns comparing off)
legend: {
position: 'bottom',
labels: {
boxWidth: 12,
color: colors.text,
generateLabels: function(chart) {
var items = Chart.defaults.plugins.legend.labels.generateLabels(chart).filter(function(item) {
return !chart.data.datasets[item.datasetIndex].previous;
});
if (chart.data.datasets.some(function(ds) { return ds.previous && !ds.hidden; })) {
items.push({ text: points.last_year, fillStyle: 'rgba(0,0,0,0)', strokeStyle: '#999', lineWidth: 2,
lineDash: [4, 3], hidden: false, datasetIndex: -1 });
}
return items;
}
},
onClick: function(e, item, legend) {
var chart = legend.chart;
if (item.datasetIndex === -1) { $('#qbo-report-compare').prop('checked', false).trigger('change'); return; }
var visible = !chart.isDatasetVisible(item.datasetIndex);
chart.setDatasetVisibility(item.datasetIndex, visible);
// last year's line follows (shown only while comparing)
chart.getDatasetMeta(item.datasetIndex + series.length).hidden = visible ? null : true;
chart.update();
}
},
tooltip: {
callbacks: {
title: function(items) {
if (!items.length) { return ''; }
var i = items[0].dataIndex, lines = [points.titles[i]];
if (items.some(function(it) { return it.dataset.previous; })) {
lines.push(points.last_year + ': ' + points.previous_titles[i]);
}
return lines;
},
label: function(item) {
return item.dataset.label + ': ' + (isMoney ? money(item.raw, 2) : hours(item.raw));
}
}
}
},
scales: {
x: { grid: { color: colors.grid }, border: { color: colors.grid }, ticks: { color: colors.text } },
y: { beginAtZero: true, grid: { color: colors.grid }, border: { color: colors.grid },
ticks: { color: colors.text, precision: isMoney ? 0 : 1, callback: function(v) { return isMoney ? money(v, 0) : v; } } }
}
}
});
}
// Chart.js from the module: its default export or a named one. Chart.js 2 has no register() and is skipped.
function chartClass(mod) {
var found = [mod && mod.default, mod && mod.Chart, mod && mod.default && mod.default.Chart];
for (var i = 0; i < found.length; i++) {
if (typeof found[i] === 'function' && typeof found[i].register === 'function') { return found[i]; }
}
return null;
}
function setCompare(on) {
charts.forEach(function(chart) {
var n = chart.data.datasets.length / 2;
for (var j = 0; j < n; j++) {
chart.data.datasets[j + n].hidden = !on;
// a figure hidden from the legend keeps last year's line hidden too
chart.getDatasetMeta(j + n).hidden = chart.isDatasetVisible(j) ? null : true;
}
chart.update();
});
// Keep the choice in the address, so reloading or changing the period keeps it
if (window.history && history.replaceState) {
var url = new URL(window.location.href);
if (on) { url.searchParams.set('compare', '1'); } else { url.searchParams.delete('compare'); }
history.replaceState(null, '', url);
}
}
$(function() {
var $compare = $('#qbo-report-compare');
// Chart.js 4 ships with this plugin (assets/javascripts), so the charts don't depend on how Redmine or
// other plugins provide it (redmine_indicator puts Chart.js 2 on every page)
import(<%= raw asset_path('plugin_assets/redmine_qbo/chart-4.5.1.min.js').to_json %>).then(function(mod) {
var Chart = chartClass(mod);
if (!Chart) {
console.warn('Business report: Chart.js did not load', Object.keys(mod || {}));
$('.qbo-report-chart').hide();
return;
}
$('.qbo-report-chart canvas').each(function() { charts.push(draw(Chart, this, $compare.is(':checked'))); });
window.qboReportCharts = charts;
}).catch(function(error) {
console.warn('Business report: Chart.js did not load', error);
$('.qbo-report-chart').hide();
});
$compare.on('change', function() { setCompare(this.checked); });
// Switching between light and dark (redmine_dark_mode) recolours the charts
document.addEventListener('redmine:color-scheme', function() {
charts.forEach(function(chart) { applyColors(chart); chart.update('none'); });
});
});
})();
<% end %>
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0"?>
<!-- Activity icons (Tabler outline icons, MIT), in the layout of Redmine's own sprite -->
<svg xmlns="http://www.w3.org/2000/svg" class="icon--sprite">
<defs>
<symbol viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" id="icon--qbo-estimate">
<path d="M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2"/>
<path d="M9 5a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2a2 2 0 0 1 -2 2h-2a2 2 0 0 1 -2 -2z"/>
<path d="M9 12h.01"/>
<path d="M13 12h2"/>
<path d="M9 16h.01"/>
<path d="M13 16h2"/>
</symbol>
<symbol viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" id="icon--qbo-invoice">
<path d="M14 3v4a1 1 0 0 0 1 1h4"/>
<path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"/>
<path d="M9 7h1"/>
<path d="M9 13h6"/>
<path d="M13 17h2"/>
</symbol>
<symbol viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" id="icon--qbo-payment">
<path d="M7 11a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v6a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z"/>
<path d="M12 14a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"/>
<path d="M17 9v-2a2 2 0 0 0 -2 -2h-10a2 2 0 0 0 -2 2v6a2 2 0 0 0 2 2h2"/>
</symbol>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+14
View File
@@ -0,0 +1,14 @@
/*!
* Chart.js v4.5.1
* https://www.chartjs.org
* (c) 2025 Chart.js Contributors
* Released under the MIT License
*/
function t(){}const e=(()=>{let t=0;return()=>t++})();function i(t){return null==t}function s(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function n(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function o(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function a(t,e){return o(t)?t:e}function r(t,e){return void 0===t?e:t}const l=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function h(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function c(t,e,i,o){let a,r,l;if(s(t))if(r=t.length,o)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;a<r;a++)e.call(i,t[a],a);else if(n(t))for(l=Object.keys(t),r=l.length,a=0;a<r;a++)e.call(i,t[l[a]],l[a])}function d(t,e){let i,s,n,o;if(!t||!e||t.length!==e.length)return!1;for(i=0,s=t.length;i<s;++i)if(n=t[i],o=e[i],n.datasetIndex!==o.datasetIndex||n.index!==o.index)return!1;return!0}function u(t){if(s(t))return t.map(u);if(n(t)){const e=Object.create(null),i=Object.keys(t),s=i.length;let n=0;for(;n<s;++n)e[i[n]]=u(t[i[n]]);return e}return t}function f(t){return-1===["__proto__","prototype","constructor"].indexOf(t)}function g(t,e,i,s){if(!f(t))return;const o=e[t],a=i[t];n(o)&&n(a)?p(o,a,s):e[t]=u(a)}function p(t,e,i){const o=s(e)?e:[e],a=o.length;if(!n(t))return t;const r=(i=i||{}).merger||g;let l;for(let e=0;e<a;++e){if(l=o[e],!n(l))continue;const s=Object.keys(l);for(let e=0,n=s.length;e<n;++e)r(s[e],t,l,i)}return t}function m(t,e){return p(t,e,{merger:x})}function x(t,e,i){if(!f(t))return;const s=e[t],o=i[t];n(s)&&n(o)?m(s,o):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=u(o))}const b={"":t=>t,x:t=>t.x,y:t=>t.y};function _(t,e){const i=b[e]||(b[e]=function(t){const e=function(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function y(t){return t.charAt(0).toUpperCase()+t.slice(1)}const v=t=>void 0!==t,M=t=>"function"==typeof t,w=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};const k=Math.PI,S=2*k,P=S+k,D=Number.POSITIVE_INFINITY,O=k/180,C=k/2,A=k/4,T=2*k/3,L=Math.log10,E=Math.sign;function R(t,e,i){return Math.abs(t-e)<i}function I(t){const e=Math.round(t);t=R(t,e,t/1e3)?e:t;const i=Math.pow(10,Math.floor(L(t))),s=t/i;return(s<=1?1:s<=2?2:s<=5?5:10)*i}function F(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function z(t,e,i){let s,n,o;for(s=0,n=t.length;s<n;s++)o=t[s][i],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function V(t){return t*(k/180)}function B(t){return t*(180/k)}function W(t){if(!o(t))return;let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function N(t,e){const i=e.x-t.x,s=e.y-t.y,n=Math.sqrt(i*i+s*s);let o=Math.atan2(s,i);return o<-.5*k&&(o+=S),{angle:o,distance:n}}function H(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function j(t,e){return(t-e+P)%S-k}function $(t){return(t%S+S)%S}function Y(t,e,i,s){const n=$(t),o=$(e),a=$(i),r=$(o-n),l=$(a-n),h=$(n-o),c=$(n-a);return n===o||n===a||s&&o===a||r>l&&h<c}function U(t,e,i){return Math.max(e,Math.min(i,t))}function X(t,e,i,s=1e-6){return t>=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function q(t,e,i){i=i||(i=>t[i]<e);let s,n=t.length-1,o=0;for(;n-o>1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const K=(t,e,i,s)=>q(t,i,s?s=>{const n=t[s][e];return n<i||n===i&&t[s+1][e]===i}:s=>t[s][e]<i),G=(t,e,i)=>q(t,i,(s=>t[s][e]>=i));const J=["push","pop","shift","splice","unshift"];function Z(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(J.forEach((e=>{delete t[e]})),delete t._chartjs)}function Q(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const tt="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function et(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,tt.call(window,(()=>{s=!1,t.apply(e,i)})))}}const it=t=>"start"===t?"left":"end"===t?"right":"center",st=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2;function nt(t,e,s){const n=e.length;let o=0,a=n;if(t._sorted){const{iScale:r,vScale:l,_parsed:h}=t,c=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null,d=r.axis,{min:u,max:f,minDefined:g,maxDefined:p}=r.getUserBounds();if(g){if(o=Math.min(K(h,d,u).lo,s?n:K(e,d,r.getPixelForValue(u)).lo),c){const t=h.slice(0,o+1).reverse().findIndex((t=>!i(t[l.axis])));o-=Math.max(0,t)}o=U(o,0,n-1)}if(p){let t=Math.max(K(h,r.axis,f,!0).hi+1,s?0:K(e,d,r.getPixelForValue(f),!0).hi+1);if(c){const e=h.slice(t-1).findIndex((t=>!i(t[l.axis])));t+=Math.max(0,e)}a=U(t,o,n)-o}else a=n-o}return{start:o,count:a}}function ot(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.Line truncated
/*!
* @kurkle/color v0.3.2
* https://github.com/kurkle/color#readme
* (c) 2023 Jukka Kurkela
* Released under the MIT License
*/
function ut(t){return t+.5|0}const ft=(t,e,i)=>Math.max(Math.min(t,i),e);function gt(t){return ft(ut(2.55*t),0,255)}function pt(t){return ft(ut(255*t),0,255)}function mt(t){return ft(ut(t/2.55)/100,0,1)}function xt(t){return ft(ut(100*t),0,100)}const bt={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},_t=[..."0123456789ABCDEF"],yt=t=>_t[15&t],vt=t=>_t[(240&t)>>4]+_t[15&t],Mt=t=>(240&t)>>4==(15&t);function wt(t){var e=(t=>Mt(t.r)&&Mt(t.g)&&Mt(t.b)&&Mt(t.a))(t)?yt:vt;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const kt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function St(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Pt(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Dt(t,e,i){const s=St(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function Ot(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e<i?6:0):e===n?(i-t)/s+2:(t-e)/s+4}(e,i,s,h,n),r=60*r+.5),[0|r,l||0,a]}function Ct(t,e,i,s){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,i,s)).map(pt)}function At(t,e,i){return Ct(St,t,e,i)}function Tt(t){return(t%360+360)%360}function Lt(t){const e=kt.exec(t);let i,s=255;if(!e)return;e[5]!==i&&(s=e[6]?gt(+e[5]):pt(+e[5]));const n=Tt(+e[2]),o=+e[3]/100,a=+e[4]/100;return i="hwb"===e[1]?function(t,e,i){return Ct(Dt,t,e,i)}(n,o,a):"hsv"===e[1]?function(t,e,i){return Ct(Pt,t,e,i)}(n,o,a):At(n,o,a),{r:i[0],g:i[1],b:i[2],a:s}}const Et={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},Rt={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};let It;function Ft(t){It||(It=function(){const t={},e=Object.keys(Rt),i=Object.keys(Et);let s,n,o,a,r;for(s=0;s<e.length;s++){for(a=r=e[s],n=0;n<i.length;n++)o=i[n],r=r.replace(o,Et[o]);o=parseInt(Rt[a],16),t[r]=[o>>16&255,o>>8&255,255&o]}return t}(),It.transparent=[0,0,0,0]);const e=It[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const zt=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Vt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Bt=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Wt(t,e,i){if(t){let s=Ot(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=ALine truncated
+14
View File
@@ -3,3 +3,17 @@
color: #888; color: #888;
font-size: 0.9em; font-size: 0.9em;
} }
/* Contextual links on their own line under the page title (customer and vehicle pages), where a long title and
many links would otherwise crowd each other */
#content .contextual.qbo-under-title {
float: none;
text-align: right;
white-space: normal;
margin: -4px 0 10px;
padding-left: 0;
}
/* Estimates, invoices and payments on the activity page belong to no project: no " - " after an empty name */
div#activity span.project:empty:after {
content: none;
}
+243 -27
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 vehicle and custom field values 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"
@@ -37,7 +42,6 @@ en:
label_closed_issues: "Closed Issues" label_closed_issues: "Closed Issues"
label_connected: "Successfully connected to QuickBooks" label_connected: "Successfully connected to QuickBooks"
label_create_estimate: "Create Estimate" label_create_estimate: "Create Estimate"
label_customer_count: "Customer Count"
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"
@@ -49,15 +53,12 @@ en:
label_edit: "Edit" label_edit: "Edit"
label_edit_customer: "Edit Customer" label_edit_customer: "Edit Customer"
label_email: "Email" label_email: "Email"
label_employee_count: "Employee Count"
label_error: "Error" label_error: "Error"
label_estimate_404: "Estimate not found" label_estimate_404: "Estimate not found"
label_estimate_count: "Estimate Count"
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_invoice_404: "Invoice not found"
label_invoice_count: "Invoice Count"
label_invoices: "Invoices" label_invoices: "Invoices"
label_last_sync: "Last Sync" label_last_sync: "Last Sync"
label_load_customer: "Load Customer" label_load_customer: "Load Customer"
@@ -69,7 +70,8 @@ en:
label_new_customer: "New Customer" label_new_customer: "New Customer"
label_new_issue: "New Issue" label_new_issue: "New Issue"
label_qbo_never_synced: "Never Synced" label_qbo_never_synced: "Never Synced"
label_no_customers: "There are no customers matching the search term(s)." label_no_customers: "No customers match \"%{search}\"."
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_oauth2_refresh_token_expires_at: "Refresh Token Expires At"
@@ -87,11 +89,6 @@ en:
label_share: "Share" label_share: "Share"
label_shipping_address: "Shipping Address" label_shipping_address: "Shipping Address"
label_sync: "Sync" label_sync: "Sync"
label_sync_now: "Sync Now"
label_sync_now_customers: "Sync Customers"
label_sync_now_employees: "Sync Employees"
label_sync_now_invoices: "Sync Invoices"
label_sync_now_estimate: "Sync Estimates"
label_syncing: "Syncing QuickBooks" label_syncing: "Syncing QuickBooks"
label_trim: "Trim" label_trim: "Trim"
label_webhook_token: "Intuit QBO Webhook Token" label_webhook_token: "Intuit QBO Webhook Token"
@@ -125,6 +122,9 @@ 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"
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"
@@ -137,12 +137,44 @@ en:
button_email_estimate: "Email" button_email_estimate: "Email"
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"
# 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_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"
error_estimate_linked_to_issues: "This estimate is linked to these issues, so it can't be changed here. Duplicate it to make a new estimate:" error_estimate_linked_to_issues: "This estimate is linked to these issues, so it can't be changed here. Duplicate it to make a new estimate:"
error_estimate_billed: "This estimate has been billed (turned into an invoice), so it can't be changed here. Duplicate it to make a new estimate."
error_estimate_has_bundles: "This estimate has bundles, which can only be edited in QuickBooks." error_estimate_has_bundles: "This estimate has bundles, which can only be edited in QuickBooks."
error_estimate_line_description: "Line %{line} needs a description, a product or service, or a rate" error_estimate_line_description: "Line %{line} needs a description, a product or service, or a rate"
error_estimate_line_number: "Line %{line} has a quantity or rate that isn't a number" error_estimate_line_number: "Line %{line} has a quantity or rate that isn't a number"
@@ -156,6 +188,14 @@ 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"
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)"
@@ -175,7 +215,6 @@ en:
label_subtotal: "Subtotal" label_subtotal: "Subtotal"
label_tax: "Tax" label_tax: "Tax"
label_taxable_subtotal: "Taxable subtotal" label_taxable_subtotal: "Taxable subtotal"
label_vin: "VIN"
notice_estimate_saved_and_sent: "Estimate #%{number} saved in QuickBooks and emailed to %{email}" notice_estimate_saved_and_sent: "Estimate #%{number} saved in QuickBooks and emailed to %{email}"
notice_estimate_saved_in_quickbooks: "Estimate #%{number} saved in QuickBooks" notice_estimate_saved_in_quickbooks: "Estimate #%{number} saved in QuickBooks"
@@ -186,13 +225,11 @@ en:
text_clear_all_lines_confirmation: "Clear all lines?" text_clear_all_lines_confirmation: "Clear all lines?"
text_email_estimate_confirmation: "Email estimate #%{number} to %{email}?" text_email_estimate_confirmation: "Email estimate #%{number} to %{email}?"
text_estimate_duplicated_from: "Copied from estimate #%{number}. It's saved as a new estimate." text_estimate_duplicated_from: "Copied from estimate #%{number}. It's saved as a new estimate."
text_estimate_closed: "This estimate is closed (it was turned into an invoice). Changes here won't change the invoice."
text_estimate_expiration_days: "New estimates get an expiration date this many days after the estimate date, e.g. 30. Leave blank for no expiration date." text_estimate_expiration_days: "New estimates get an expiration date this many days after the estimate date, e.g. 30. Leave blank for no expiration date."
text_estimate_reload: "Reloading shows the latest version from QuickBooks; changes made on this page will be lost." text_estimate_reload: "Reloading shows the latest version from QuickBooks; changes made on this page will be lost."
text_estimate_send_needs_email: "Enter the customer's email to send it." text_estimate_send_needs_email: "Enter the customer's email to send it."
text_memo_is_private: "Internal, not shown to the customer" text_memo_is_private: "Internal, not shown to the customer"
text_no_sales_person_field: "QuickBooks isn't sharing a text custom field named Sales Person, so this isn't saved." text_no_sales_person_field: "QuickBooks isn't sharing a text custom field named Sales Person, so this isn't saved."
text_no_vin_field: "QuickBooks isn't sharing a text custom field named VIN."
text_quickbooks_custom_fields_found: "Custom fields QuickBooks shares with apps: %{fields}. QuickBooks only shares its first three text fields; a field it doesn't list in its settings shows up here once it's filled in on an estimate." text_quickbooks_custom_fields_found: "Custom fields QuickBooks shares with apps: %{fields}. QuickBooks only shares its first three text fields; a field it doesn't list in its settings shows up here once it's filled in on an estimate."
text_quickbooks_settings_unavailable: "QuickBooks' estimate settings couldn't be read, so custom fields and the default message are missing. Check the QuickBooks connection." text_quickbooks_settings_unavailable: "QuickBooks' estimate settings couldn't be read, so custom fields and the default message are missing. Check the QuickBooks connection."
text_separate_emails_with_comma: "Separate emails with a comma" text_separate_emails_with_comma: "Separate emails with a comma"
@@ -206,20 +243,25 @@ en:
label_active: "Active" label_active: "Active"
label_account: "Account" label_account: "Account"
label_accounts: "Accounts" label_accounts: "Accounts"
label_account_count: "Number of Accounts:"
label_back: "Back" label_back: "Back"
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: "Item"
label_item_count: "Item Count:"
label_item_new: "New Item" label_item_new: "New Item"
label_items: "Items" label_items: "Items"
label_management_and_sync: "Management & Synchronization" label_management_and_sync: "Synchronization"
label_labor_items: "Labor products/services"
text_labor_items: "Products/services billed as labor hours, e.g. Labor. Used to create issues from an estimate's labor lines (and an appointment's minimum hours), to offer an invoice's labor lines to be replaced by imported time, and to total hours on estimates and invoices for the business report (sync estimates and invoices after changing). While none are chosen, products/services named Labor are used. Ctrl/Cmd-click to pick several."
label_qbo_connection: "QuickBooks connection"
label_qbo_records: "Records"
label_employee_plural: "Employees"
label_sync_changes: "Sync changes"
label_full_sync: "Full sync"
text_qbo_sync_info: "Sync changes reads what changed in QuickBooks since the last sync; Full sync and each type's Sync re-read every record (e.g. after changing the labor products/services, sync estimates and invoices). Webhooks keep things current in between."
text_default_account_info: "New products/services go in this income account; set it on the Accounts page."
label_never_synced: "Never synced" label_never_synced: "Never synced"
label_no: "No" label_no: "No"
label_sync_now_accounts: "Sync Accounts"
label_sync_now_items: "Sync Items"
label_type: "Type" label_type: "Type"
label_yes: "Yes" 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."
@@ -235,7 +277,6 @@ en:
error_estimate_already_invoiced: "Estimate #%{number} is already billed on invoice #%{invoice}." error_estimate_already_invoiced: "Estimate #%{number} is already billed on invoice #%{invoice}."
error_estimate_closed_billed: "Estimate #%{number} is already billed (%{status})." error_estimate_closed_billed: "Estimate #%{number} is already billed (%{status})."
error_estimate_rejected: "Estimate #%{number} was rejected, so it can't be billed." error_estimate_rejected: "Estimate #%{number} was rejected, so it can't be billed."
text_estimate_billed_on: "This estimate is billed on:"
error_invoice_changed_in_quickbooks: "This invoice was changed in QuickBooks after you opened it, so it wasn't saved." error_invoice_changed_in_quickbooks: "This invoice was changed in QuickBooks after you opened it, so it wasn't saved."
error_invoice_has_bundles: "This invoice has bundles, which can only be edited in QuickBooks." error_invoice_has_bundles: "This invoice has bundles, which can only be edited in QuickBooks."
error_invoice_not_saved: "QuickBooks didn't save the invoice" error_invoice_not_saved: "QuickBooks didn't save the invoice"
@@ -247,23 +288,27 @@ en:
label_invoice_balance: "Balance due %{balance}" label_invoice_balance: "Balance due %{balance}"
label_invoice_date: "Invoice date" label_invoice_date: "Invoice date"
label_invoice_no: "Invoice no." label_invoice_no: "Invoice no."
label_invoice_paid: "Paid" label_invoice_status_paid: "Paid"
label_invoice_partially_paid: "Partially paid" label_invoice_status_paid_on: "Paid %{date}"
label_invoice_status_partial: "Partially paid"
label_invoice_status_overdue: "Overdue"
label_invoice_status_open: "Open"
label_invoice_status_voided: "Voided"
label_message_on_invoice: "Message displayed on invoice" label_message_on_invoice: "Message displayed on invoice"
label_new_invoice: "New invoice" label_new_invoice: "New invoice"
label_open_estimates: "Open estimates" label_open_estimates: "Open estimates"
label_replace_lines: "Replace these lines" label_replace_lines: "Replace these lines"
label_replaceable_items: "Replaced by imported time"
label_time_badge: "Time" label_time_badge: "Time"
notice_invoice_saved_and_sent: "Invoice #%{number} saved in QuickBooks and emailed to %{email}" notice_invoice_saved_and_sent: "Invoice #%{number} saved in QuickBooks and emailed to %{email}"
notice_invoice_saved_in_quickbooks: "Invoice #%{number} saved in QuickBooks" notice_invoice_saved_in_quickbooks: "Invoice #%{number} saved in QuickBooks"
notice_invoice_sent: "Invoice #%{number} emailed to %{email}" notice_invoice_sent: "Invoice #%{number} emailed to %{email}"
text_email_invoice_confirmation: "Email invoice #%{number} to %{email}?" text_email_invoice_confirmation: "Email invoice #%{number} to %{email}?"
text_invoice_from_estimate: "Made from estimate #%{number}. The estimate is closed when the invoice is saved." text_invoice_from_estimate: "Made from estimate #%{number}. The estimate is closed when the invoice is saved."
text_invoice_many_vehicles: "These work orders are for more than one vehicle:" text_invoice_customer_open_issues:
one: "This customer has an open issue. Make sure its work is finished and billed so it isn't left open:"
other: "This customer has %{count} open issues. Make sure their work is finished and billed so none are left open:"
text_line_bills_time: "Bills a QuickBooks time activity; saving marks the time as billed" text_line_bills_time: "Bills a QuickBooks time activity; saving marks the time as billed"
text_replaceable_items: "Products/services that billable time can replace on invoices, e.g. Labor. Only invoice lines with these are offered under Replace these lines when time is imported. Leave empty to offer every line. Ctrl/Cmd-click to pick several." text_replace_lines: "Tick the lines the time replaces (e.g. the estimate's labor lines). Each time entry takes the place of the line with its issue's description (e.g. Install Lift Kit), then any others in order."
text_replace_lines: "Tick the lines the time replaces (e.g. the estimate's labor lines). The time goes where the first ticked line is."
# Issues from estimates (moved from redmine_qbo_calendar) # Issues from estimates (moved from redmine_qbo_calendar)
button_create_estimate_issues_submit: "Create issues" button_create_estimate_issues_submit: "Create issues"
@@ -274,12 +319,15 @@ 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_item_codes: "Estimate item codes"
label_estimate_line_already_created: "Already created" label_estimate_line_already_created: "Already created"
label_issue_template: "Template" label_issue_template: "Template"
label_no_issue_template: "(no template)" label_no_issue_template: "(no template)"
notice_estimate_accepted: "Estimate #%{number} is now Accepted in QuickBooks."
warning_estimate_not_accepted: "The issues were created, but estimate #%{number} couldn't be marked Accepted in QuickBooks: %{message}"
error_estimate_not_accepted: "QuickBooks kept its status as %{status}"
notice_estimate_issues_created: notice_estimate_issues_created:
one: "1 issue created from the estimate" one: "1 issue created from the estimate"
other: "%{count} issues created from the estimate" other: "%{count} issues created from the estimate"
@@ -288,12 +336,17 @@ en:
text_estimate_issue_fields_info: "Entered once and applied to every created issue whose tracker uses the field. Fields marked * are required by the selected trackers." text_estimate_issue_fields_info: "Entered once and applied to every created issue whose tracker uses the field. Fields marked * are required by the selected trackers."
text_estimate_issues_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. Edit anything before creating. New issues are related to each other and to issues already created from this estimate." text_estimate_issues_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. Edit anything before creating. New issues are related to each other and to issues already created from this estimate."
text_estimate_issues_template_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. A template supplies the issue's description. New issues are related to each other and to issues already created from this estimate." text_estimate_issues_template_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. A template supplies the issue's description. New issues are related to each other and to issues already created from this estimate."
text_estimate_item_codes_info: "QBO item names that can become issues, one per line (e.g. Labor, Alignments). Matches the full item name or any part of a Category:Item name, ignoring case. Their quantities are also an estimate's labor hours (an appointment's hours can't be less)."
# Payments # Payments
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"
@@ -311,6 +364,57 @@ en:
label_no_payments: "No payments from this customer in QuickBooks" label_no_payments: "No payments from this customer in QuickBooks"
label_payment_totals: "Total" label_payment_totals: "Total"
permission_view_payments: "View payments" permission_view_payments: "View payments"
# ---- Business report ----
permission_view_business_reports: "View business reports"
label_business_report: "Business report"
label_report_period: "Period"
label_report_period_this_week: "This week"
label_report_period_last_week: "Last week"
label_report_period_this_month: "This month"
label_report_period_last_month: "Last month"
label_report_period_this_quarter: "This quarter"
label_report_period_last_quarter: "Last quarter"
label_report_period_this_year: "This year"
label_report_period_last_year: "Last year"
label_report_period_custom: "Custom dates"
label_report_money: "Sales"
label_report_hours: "Hours"
label_report_by_month: "By month"
label_report_compare_last_year: "Compare with last year"
label_report_last_year: "last year"
label_report_estimates_written: "Estimates written"
label_report_invoices_written: "Invoices written"
label_report_invoices_paid: "Invoices paid in full"
label_report_taxes: "Sales tax"
label_report_tax_invoiced: "Tax invoiced"
label_report_tax_collected: "Tax collected"
label_report_taxed_invoices:
one: "1 invoice"
other: "%{count} invoices"
text_report_taxes: "Tax invoiced is the sales tax on invoices dated in the period (accrual); tax collected is the sales tax on invoices paid in full in the period (cash), counted on the day each was paid in full. Sales receipts and refunds aren't included: file from QuickBooks' Sales Tax Liability report."
text_report_without_tax: "Estimates and invoices are without sales tax; invoices paid in full count on the day they were paid in full. Payments are as received, so collected vs. invoiced compares them with the invoices' totals with tax."
label_report_payments_received: "Payments received"
label_report_estimate_hours: "Estimated (estimates)"
label_report_issue_hours: "Estimated (issues)"
label_report_invoice_hours: "Invoiced (invoices)"
label_report_spent_hours: "Spent (issues)"
label_report_invoiced_of_estimated: "Invoiced vs. estimated"
label_report_collected_of_invoiced: "Collected vs. invoiced"
label_report_open_balance: "Still owed on these invoices"
label_report_cpi: "Cost performance index (CPI)"
label_report_cpi_short: "CPI"
text_report_cpi: "Invoiced hours ÷ spent hours. 1.00 or more (green): every hour worked was billed; below 1 (yellow): some time wasn't billed; below 0.80 (red): a fifth or more wasn't."
label_report_spent_of_estimated: "Spent vs. issues' estimated hours"
text_report_syncing: "QuickBooks is still syncing, so these figures are incomplete until it finishes. This page refreshes every 30 seconds."
text_qbo_sync_running: "syncing, %{count} read so far (started %{time})"
text_qbo_sync_running_short: "Syncing… %{count} read"
text_qbo_sync_queued: "waiting to sync"
text_report_needs_sync: "%{count} estimates or invoices in this period don't have their total or hours yet. Run a full sync from QuickBooks to fill them in."
text_report_notes: "Estimates, invoices and payments count by their QuickBooks date; their hours are the quantities of the labor products/services. Issues' estimated time counts issues created in the period, without subtasks. Spent time counts time logged in the period."
label_report_remember_projects: "Remember these projects"
text_report_projects: "For issues' estimated time and spent time. None picked: every project. Ctrl/Cmd-click to pick several."
text_report_saved_projects: "Opens with: %{projects}"
text_report_projects_filtered: "Only issues' estimated time and spent time are limited to these projects. Estimates, invoices and payments come from QuickBooks, which has no projects, so they cover the whole business (and so does the CPI's invoiced hours)."
notice_payment_not_found: "Payment not found in QuickBooks" notice_payment_not_found: "Payment not found in QuickBooks"
notice_payment_saved: "Payment of %{amount} saved in QuickBooks" notice_payment_saved: "Payment of %{amount} saved in QuickBooks"
text_no_payment_methods: "QuickBooks' payment methods couldn't be read. Check the QuickBooks connection." text_no_payment_methods: "QuickBooks' payment methods couldn't be read. Check the QuickBooks connection."
@@ -318,3 +422,115 @@ en:
text_payment_pick_invoices: "Tick invoices to fill in the amount and pay just those. With none ticked, the payment goes on the oldest invoices first." text_payment_pick_invoices: "Tick invoices to fill in the amount and pay just those. With none ticked, the payment goes on the oldest invoices first."
text_payment_reference: "e.g. the check number" text_payment_reference: "e.g. the check number"
text_payment_unapplied_deposit: "Not applied to any invoice: it's a credit on the customer's account." text_payment_unapplied_deposit: "Not applied to any invoice: it's a credit on the customer's account."
# Activity page
label_qbo_estimate_plural: "Estimates"
label_qbo_invoice_plural: "Invoices"
label_qbo_payment_plural: "Payments"
label_activity_estimate: "Estimate #%{number}: %{customer}"
label_activity_invoice: "Invoice #%{number}: %{customer}"
label_activity_payment: "Payment from %{customer}: %{amount}"
text_activity_invoice_owed: "%{amount} owed"
text_activity_payment_unapplied: "%{amount} not applied to an invoice"
# ---- Refunds (SOP-OPS-014) ----
permission_issue_refunds: "Issue refunds"
label_refund: "Refund"
label_refunds: "Refunds"
label_refund_incomplete: "Incomplete"
label_refund_estimate: "Canceled order"
label_refund_no_estimate: "None (customer credit only)"
label_refund_your_order: "your order"
label_refund_parts: "Parts"
label_refund_method: "Refund by"
label_refund_method_check: "Company check"
label_refund_method_card: "Card (on the terminal)"
label_refund_check_number: "Check no."
label_refund_date: "Refund date"
label_refund_reason: "Reason"
label_refund_also: "Also"
label_refund_close_estimate: "Mark the estimate Rejected in QuickBooks"
label_refund_cancel_issues: "Cancel the order's work orders"
label_refund_email_customer: "Email the customer a summary"
label_refund_summary: "Refund"
label_refund_credit_from: "Credit from payment"
label_refund_credit: "Customer credit"
label_refund_fee_rate: "Restocking fee (%{rate}% of parts)"
label_refund_amount: "Refund"
label_refund_fee_invoice: "Invoice #%{number}"
label_refund_open_check: "Check in QuickBooks"
label_refund_open_expense: "Expense in QuickBooks"
label_refund_settings: "Refunds"
label_refund_balance_after: "Customer balance afterwards"
label_refund_recorded_by: "Recorded by"
label_refund_received_by: "Received by (customer signature)"
label_refund_fee_invoice_pdf: "Fee invoice PDF"
label_refund_pdf_fee: "Restocking fee: %{rate}% × %{parts} parts"
label_refund_pdf_work_orders: "Work orders canceled"
label_refund_pdf_estimate: "Estimate"
text_refund_pdf_estimate_rejected: "E%{number} marked Rejected in QuickBooks"
label_restocking_fee_rate: "Restocking fee"
label_restocking_item: "Restocking fee product/service"
label_refund_check_account: "Refund checks from"
label_refund_card_account: "Card refunds from"
label_refund_first_bank_account: "The first bank account"
label_refund_canceled_status: "Canceled work order status"
button_refund: "Refund"
button_refund_email: "Email the customer"
button_refund_email_again: "Email again"
notice_refund_emailed: "Refund summary emailed to %{email}."
notice_refund_done: "Refund of %{amount} recorded in QuickBooks."
error_refund_method: "Choose how the refund is paid: company check or card."
error_refund_check_number: "Enter the check number."
error_refund_reason: "Enter the reason for the refund."
error_refund_parts_amount: "Parts must be an amount of $0.00 or more."
error_refund_estimate_customer: "That estimate is for another customer."
error_refund_no_fee_item: "Pick the restocking fee product/service in the QuickBooks plugin settings (Billing » Refunds)."
error_refund_no_credit: "This customer has no credit (unapplied payments) to refund."
error_refund_fee_over_credit: "The restocking fee (%{fee}) isn't less than the customer's credit (%{credit}), so there's nothing to refund."
error_refund_no_ar_account: "QuickBooks has no Accounts Receivable account."
error_refund_no_bank_account: "QuickBooks has no bank account to record the refund from. Pick one in the plugin settings."
error_refund_fee_not_saved: "QuickBooks didn't save the restocking fee invoice."
error_refund_fee_unpaid: "The customer's credit didn't cover the restocking fee invoice (%{amount} still open)."
error_refund_nothing_left: "No credit is left to refund after the restocking fee."
error_refund_not_saved: "QuickBooks didn't save the refund."
error_refund_step_fee: "The restocking fee invoice couldn't be made or paid from the customer's credit: %{error}. Nothing was refunded. Finish or undo it in QuickBooks."
error_refund_step_refund: "The refund couldn't be recorded in QuickBooks: %{error}. The restocking fee invoice (if any) is made. Record the refund in QuickBooks (Check or Expense, category Accounts Receivable) and apply the customer's credit to it."
text_refund_final_sale: "Custom fabricated assemblies and discontinued or closeout items are final sale. Don't refund them without Shop Manager approval (SOP-OPS-014). No cash refunds: card payments are refunded on the terminal, everything else by company check."
text_refund_no_credit: "This customer has no credit (unapplied payments) to refund."
text_refund_estimate: "The order being canceled. Its parts fill in the restocking fee, and the refund refers to it."
text_refund_parts: "The parts returned or canceled, before tax. The restocking fee is %{rate}% of this; labor carries no fee. Enter 0 to refund without a fee."
text_refund_method: "The way the order was paid: card payments are refunded on the card terminal (a partial refund, of the amount below); cash and check payments by company check."
text_refund_reason: "Goes on the refund in QuickBooks and on the canceled work orders."
text_refund_summary: "The restocking fee invoice is paid from the customer's credit, and the rest is refunded. Refund exactly this amount on the terminal or check."
text_refund_email_confirm: "Email the customer this refund's summary?"
text_refund_confirm: "Make the restocking fee invoice and record the refund in QuickBooks?"
text_refund_no_email: "The customer has no email in QuickBooks."
text_refund_balance: "Done. The customer's QuickBooks balance is now %{balance}."
text_refund_balance_unknown: "Done, but the customer's QuickBooks balance couldn't be read. Check it's $0.00 in QuickBooks."
text_refund_incomplete: "This refund is incomplete. See below which step failed, and finish it in QuickBooks."
text_refund_fee_line: "Restocking fee: %{rate}% × %{parts} parts%{on} = %{fee}"
text_refund_line: "Refund for deposit on E%{number}"
text_refund_line_credit: "Refund of customer credit"
text_refund_line_card: "(card refund on the terminal)"
text_refund_private_note: "Refund made in Redmine (SOP-OPS-014). Reason: %{reason}"
text_refund_issue_note: "Order canceled and refunded: %{reason}. Restocking fee %{fee}, refunded %{refund} by %{method}."
text_refund_issues_not_canceled: "Some work orders couldn't be set to canceled: %{issues}"
text_refund_no_canceled_status: "The work orders weren't canceled: pick the canceled status in the plugin settings."
text_refund_estimate_not_closed: "The estimate couldn't be marked Rejected in QuickBooks: %{error}"
text_refund_email_failed: "The customer wasn't emailed: %{error}"
text_refund_email_off: "Redmine's email delivery is turned off."
text_refund_email_subject: "Your refund from %{shop}: %{amount}"
text_refund_email_greeting: "Hello %{name},"
text_refund_email_intro: "We've processed the refund for %{order}."
text_refund_email_check: "It's being paid by company check (no. %{number})."
text_refund_email_card: "It's been refunded to the card you paid with. It can take a few business days to show on your statement."
text_refund_email_terms: "As in our posted terms, returned and canceled parts carry a restocking fee. Labor that wasn't done isn't charged."
text_restocking_fee_rate: "Of the parts returned or canceled (SOP-OPS-014: 30%)."
text_restocking_item: "The QuickBooks product/service on the restocking fee invoice (e.g. \"Restocking Fee\"). It sets the income account the fee is booked to."
text_refund_check_account: "The bank account refund checks are written from."
text_refund_card_account: "The account card refunds come out of (where card payments are deposited)."
text_refund_canceled_status: "Work orders of a canceled order are set to this status, with the reason as a note."
+16 -1
View File
@@ -68,12 +68,24 @@ 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
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
collection do collection do
get :sync
get :open_invoices get :open_invoices
end end
end end
@@ -93,3 +105,6 @@ resources :accounts do
get :sync get :sync
end end
end end
# Business report (estimates, invoices, payments and hours for a period)
get 'qbo_reports', to: 'qbo_reports#index', as: :qbo_reports
@@ -0,0 +1,33 @@
#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.
# Cached from QuickBooks by the sync and the webhook: each estimate's total and status (Converted or Closed
# estimates are billed, so they're shown as View instead of Edit), and the man-hours on estimates and invoices
# (quantities of the labor products/services) for the business report.
class AddEstimateTotalsAndHours < ActiveRecord::Migration[7.0]
def up
add_column :estimates, :total_amount, :decimal, precision: 15, scale: 2 unless column_exists?(:estimates, :total_amount)
add_column :estimates, :hours, :float unless column_exists?(:estimates, :hours)
add_column :estimates, :txn_status, :string unless column_exists?(:estimates, :txn_status)
add_column :invoices, :hours, :float unless column_exists?(:invoices, :hours)
add_index :estimates, :txn_date unless index_exists?(:estimates, :txn_date)
add_index :invoices, :txn_date unless index_exists?(:invoices, :txn_date)
end
def down
remove_index :invoices, :txn_date if index_exists?(:invoices, :txn_date)
remove_index :estimates, :txn_date if index_exists?(:estimates, :txn_date)
remove_column :invoices, :hours if column_exists?(:invoices, :hours)
remove_column :estimates, :txn_status if column_exists?(:estimates, :txn_status)
remove_column :estimates, :hours if column_exists?(:estimates, :hours)
remove_column :estimates, :total_amount if column_exists?(:estimates, :total_amount)
end
end
+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.
# Customer payments cached from QuickBooks (id, customer, date and amount) for reporting
class CreatePayments < ActiveRecord::Migration[7.0]
def up
return if table_exists?(:payments)
create_table :payments do |t|
t.references :customer, index: true
t.date :txn_date
t.decimal :total_amount, precision: 15, scale: 2
t.decimal :unapplied_amount, precision: 15, scale: 2
t.datetime :qbo_updated_at
t.timestamps null: true
end
add_index :payments, :txn_date
end
def down
drop_table :payments if table_exists?(:payments)
end
end
@@ -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.
# Which QuickBooks syncs are queued or running, and how far along they are (shown on the business report and
# the settings page while a long sync runs)
class CreateQboSyncStatuses < ActiveRecord::Migration[7.0]
def up
return if table_exists?(:qbo_sync_statuses)
create_table :qbo_sync_statuses do |t|
t.string :entity, null: false
t.string :state, null: false
t.integer :processed, null: false, default: 0
t.datetime :started_at
t.timestamps
end
add_index :qbo_sync_statuses, :entity, unique: true
end
def down
drop_table :qbo_sync_statuses if table_exists?(:qbo_sync_statuses)
end
end
+64
View File
@@ -0,0 +1,64 @@
#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.
# The customers, employees, estimates and invoices tables were created with
# `t.integer :id, options: 'PRIMARY KEY'`, which Rails ignores, so their id (the QuickBooks id) was never unique.
# Two syncs of the same record at once (e.g. saving an estimate in Redmine, then QuickBooks' webhook) could
# both insert it, and it showed twice. This keeps one row per id (the most recently updated) and adds a unique
# index so the database refuses a second one. Other tables point at these by the same id, so nothing breaks.
class UniqueQboIds < ActiveRecord::Migration[7.0]
TABLES = %i[customers employees estimates invoices].freeze
def up
TABLES.each do |table|
next unless table_exists?(table)
remove_duplicates(table)
add_index table, :id, unique: true, name: "index_#{table}_on_qbo_id" unless index_name_exists?(table, "index_#{table}_on_qbo_id")
end
end
def down
TABLES.each do |table|
remove_index table, name: "index_#{table}_on_qbo_id" if table_exists?(table) && index_name_exists?(table, "index_#{table}_on_qbo_id")
end
end
private
def remove_duplicates(table)
quoted = quote_table_name(table)
ids = select_values("SELECT id FROM #{quoted} WHERE id IS NOT NULL GROUP BY id HAVING COUNT(*) > 1")
say "#{table}: #{ids.size} duplicated ids" if ids.any?
ids.each do |id|
rows = select_all("SELECT * FROM #{quoted} WHERE id = #{quote(id)}").to_a
keep = rows.max_by { |row| [row['updated_at'].to_s, row.values.compact.size] }
columns = keep.keys
values = columns.map { |c| sql_value(keep[c]) }
# Both or neither: a failed insert must not leave the record deleted
transaction do
execute "DELETE FROM #{quoted} WHERE id = #{quote(id)}"
execute "INSERT INTO #{quoted} (#{columns.map { |c| quote_column_name(c) }.join(', ')}) VALUES (#{values.join(', ')})"
end
end
end
# A value read back from the table, quoted for writing it again. Dates and times are formatted the way
# Rails writes them (e.g. '2026-10-31 14:06:08'), not with a time zone offset, which MySQL refuses.
def sql_value(value)
return 'NULL' if value.nil?
return quote(connection.quoted_date(value)) if value.is_a?(Time) || value.is_a?(Date) || value.is_a?(DateTime)
quote(value)
end
end
+22
View File
@@ -0,0 +1,22 @@
#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.
# Each estimate's QuickBooks status (Converted and Closed estimates are billed, so lists show View instead of
# Edit). Added to migration 047 after some databases had already run it, so it's added here for those.
class AddEstimateStatus < ActiveRecord::Migration[7.0]
def up
add_column :estimates, :txn_status, :string unless column_exists?(:estimates, :txn_status)
end
def down
remove_column :estimates, :txn_status if column_exists?(:estimates, :txn_status)
end
end
+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
+21 -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.1' version '2026.11.22'
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'
@@ -27,9 +27,6 @@ Redmine::Plugin.register :redmine_qbo do
User.safe_attributes :employee_id User.safe_attributes :employee_id
TimeEntry.safe_attributes :billed TimeEntry.safe_attributes :billed
# set per_page globally
WillPaginate.per_page = 20
# Global Permissions # Global Permissions
# autocomplete and the filter_* actions feed the customer, estimate and invoice pickers on issue forms # autocomplete and the filter_* actions feed the customer, estimate and invoice pickers on issue forms
permission :view_customers, { customers: [:index, :show, :autocomplete, permission :view_customers, { customers: [:index, :show, :autocomplete,
@@ -43,19 +40,36 @@ 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
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 and returned parts (SOP-OPS-014): restocking fee, refund check or card refund
permission :issue_refunds, { qbo_refunds: [:new, :create, :show, :pdf, :email] }, global: true
permission :view_business_reports, { qbo_reports: [:index] }, global: true
# The product/service list, accounts and their syncs are admin-only (see ItemsController, AccountsController) # The product/service list, accounts and their syncs are admin-only (see ItemsController, AccountsController)
# Estimates, invoices and payments on the activity page (QboActivity): the overall page only, for users with
# View customers or Write estimates / invoices, and View or Receive payments
# (plugin: picks their icons from this plugin's sprite, assets/images/icons.svg)
activity_provider :qbo_estimates, class_name: 'Estimate', plugin: :redmine_qbo
activity_provider :qbo_invoices, class_name: 'Invoice', plugin: :redmine_qbo
activity_provider :qbo_payments, class_name: 'Payment', plugin: :redmine_qbo
# Register top menu items # Register top menu items
menu :top_menu, :customers, { controller: :customers, action: :index }, caption: :label_customers, if: Proc.new {User.current.allowed_to?(:view_customers, nil, global: true)} menu :top_menu, :customers, { controller: :customers, action: :index }, caption: :label_customers, if: Proc.new {User.current.allowed_to?(:view_customers, nil, global: true)}
menu :top_menu, :qbo_reports, { controller: :qbo_reports, action: :index }, caption: :label_business_report,
after: :customers, if: Proc.new { User.current.allowed_to?(:view_business_reports, nil, global: true) }
Redmine::Search.map do |search| Redmine::Search.map do |search|
search.register :customers search.register :customers
+5
View File
@@ -18,11 +18,16 @@ module RedmineQbo
IssueQuery.prepend RedmineQbo::Patches::QueryPatch IssueQuery.prepend RedmineQbo::Patches::QueryPatch
TimeEntryQuery.prepend RedmineQbo::Patches::TimeEntryQueryPatch TimeEntryQuery.prepend RedmineQbo::Patches::TimeEntryQueryPatch
# === Activity: estimates, invoices and payments, for users who may see them ===
Redmine::Activity::Fetcher.prepend RedmineQbo::Patches::ActivityFetcherPatch
# === Controllers === # === Controllers ===
RedmineQbo::Patches::IssuesControllerPatch.apply RedmineQbo::Patches::IssuesControllerPatch.apply
RedmineQbo::Patches::AttachmentsControllerPatch.apply RedmineQbo::Patches::AttachmentsControllerPatch.apply
# === Helpers / Exports === # === Helpers / Exports ===
IssuesHelper.prepend RedmineQbo::Patches::IssuesHelperPatch
QueriesHelper.prepend RedmineQbo::Patches::QueriesHelperPatch
Redmine::Export::PDF::IssuesPdfHelper.prepend RedmineQbo::Patches::PdfPatch Redmine::Export::PDF::IssuesPdfHelper.prepend RedmineQbo::Patches::PdfPatch
# === Hooks === # === Hooks ===
@@ -0,0 +1,29 @@
#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.
module RedmineQbo
module Patches
# The activity page lists every activity type for the whole site, and a project's page those its members may
# see. QuickBooks estimates, invoices and payments (QboActivity) belong to no project: they're kept to the
# overall page, and to users with one of their permissions, so nobody gets a checkbox for activity they can't see.
module ActivityFetcherPatch
def event_types
return @event_types if @qbo_activity_checked
@qbo_activity_checked = true
@event_types = super.select do |event_type|
providers = Redmine::Activity.providers[event_type].map(&:constantize)
qbo = providers.select { |provider| provider.respond_to?(:qbo_activity_visible_to?) }
qbo.empty? || (project.nil? && qbo.any? { |provider| provider.qbo_activity_visible_to?(user) })
end
end
end
end
end
@@ -0,0 +1,69 @@
#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 RedmineQbo
module Patches
# Shows the customer and estimate by name, and invoices attached by the QuickBooks webhook, in an
# issue's history, emails and PDF. Redmine records the customer and estimate by id, like its own
# fields, but only looks up names for the fields it knows about. The ids stay in the database, so
# existing history entries show names too.
module IssuesHelperPatch
JOURNAL_NAMED_FIELDS = { 'customer_id' => 'Customer', 'estimate_id' => 'Estimate' }.freeze
def show_detail(detail, no_html = false, options = {})
return qbo_invoice_detail(detail, no_html, options) if detail.property == 'invoice'
model = detail.property == 'attr' && JOURNAL_NAMED_FIELDS[detail.prop_key]
return super unless model
# Hand Redmine a copy with names in place of ids, so it formats it like any other change
named = JournalDetail.new(property: detail.property, prop_key: detail.prop_key,
old_value: qbo_journal_name(model, detail.old_value),
value: qbo_journal_name(model, detail.value))
named.id = detail.id
named.journal_id = detail.journal_id
super(named, no_html, options)
end
private
# "Invoice 1042 added", recorded when the QuickBooks webhook attaches an invoice to the issue
# (see InvoiceAttachmentService). The number links to the invoice PDF while the invoice exists.
def qbo_invoice_detail(detail, no_html, options)
label = l(:field_invoice)
value = detail.value
old_value = detail.old_value
unless no_html
label = content_tag('strong', label)
if value.present?
value = Invoice.exists?(detail.prop_key) ? link_to(value, invoice_url(detail.prop_key, only_path: options[:only_path] != false)) : content_tag('i', value)
end
old_value = content_tag('del', content_tag('i', old_value)) if old_value.present?
end
if detail.value.present?
l(:text_journal_added, label: label, value: value).html_safe
else
l(:text_journal_deleted, label: label, old: old_value).html_safe
end
end
# The record's name, or the id when it no longer exists. Cached for the request, since a
# history can mention the same customer many times.
def qbo_journal_name(model, id)
return id if id.blank?
@qbo_journal_names ||= {}
@qbo_journal_names[[model, id]] ||= model.constantize.find_by(id: id)&.to_s.presence || id
end
end
end
end
+3
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"
@@ -8,25 +8,24 @@
# #
#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 RedmineQbo
module Hooks module Patches
# Links the Customer column in issue lists to the customer's page, for users who may open it
# (View customers). Others see the name as plain text. CSV and PDF exports are unchanged.
module QueriesHelperPatch
def column_value(column, item, value)
return super unless column.name == :customer && value.is_a?(Customer) && qbo_can_view_customers?
# Each work order's mileage, from Redmine's own issue custom field named "Mileage" (any capitalisation), link_to(value.to_s, customer_path(value))
# so an invoice's mileage box fills in when its time or estimates are imported. Answers the same
# qbo_billing_issue_values hook other plugins use (see IssueValues).
class IssueMileageListener < Redmine::Hook::Listener
def qbo_billing_issue_values(context = {})
issue_ids = Array(context[:issues]).map(&:id)
field = IssueCustomField.all.detect { |f| f.name.to_s.strip.casecmp?('mileage') }
return {} if field.nil? || issue_ids.empty?
values = CustomValue.where(customized_type: 'Issue', customized_id: issue_ids, custom_field_id: field.id)
.where.not(value: [nil, ''])
.pluck(:customized_id, :value)
{ mileage: values.to_h }
end end
private
def qbo_can_view_customers?
return @qbo_can_view_customers if defined?(@qbo_can_view_customers)
@qbo_can_view_customers = User.current.allowed_to?(:view_customers, nil, global: true)
end
end end
end end
end end
-1
View File
@@ -32,7 +32,6 @@ module RedmineQbo
unless @available_columns unless @available_columns
@available_columns = self.class.available_columns.dup @available_columns = self.class.available_columns.dup
@available_columns << QueryColumn.new(:customer, sortable: "#{Issue.table_name}.customer_id", groupable: true, caption: :field_customer) @available_columns << QueryColumn.new(:customer, sortable: "#{Issue.table_name}.customer_id", groupable: true, caption: :field_customer)
@available_columns << QueryColumn.new(:billed, sortable: "#{TimeEntry.table_name}.billed", groupable: true, caption: :field_billed)
end end
super super
end end
@@ -17,7 +17,7 @@ module RedmineQbo
def available_columns def available_columns
unless @available_columns unless @available_columns
@available_columns = self.class.available_columns.dup @available_columns = self.class.available_columns.dup
@available_columns << QueryColumn.new(:billed, sortable: "#{TimeEntry.table_name}.name", groupable: true, caption: :field_billed) @available_columns << QueryColumn.new(:billed, sortable: "#{TimeEntry.table_name}.billed", groupable: "#{TimeEntry.table_name}.billed", caption: :field_billed)
end end
super super
end end
+53 -1
View File
@@ -19,7 +19,6 @@ module RedmineQboBilling
# Hooks # Hooks
RedmineQboBilling::Hooks::QboHookListener RedmineQboBilling::Hooks::QboHookListener
RedmineQboBilling::Hooks::IssueMileageListener
# Administration menu: the QuickBooks product/service list (accounts are reached from it) # Administration menu: the QuickBooks product/service list (accounts are reached from it)
Redmine::MenuManager.map :admin_menu do |menu| Redmine::MenuManager.map :admin_menu do |menu|
@@ -28,6 +27,47 @@ module RedmineQboBilling
end end
end end
# Suggestions for the editor's custom field boxes for a customer, from plugins answering
# :qbo_billing_field_options, { customer: } => { field_id => [{ value:, label: }, ...] }
# (e.g. redmine_qbo_vehicles: the customer's vehicles for its VIN field). Returns { "2" => [...] }.
def self.field_options(customer)
return {} unless customer
Redmine::Hook.call_hook(:qbo_billing_field_options, { customer: customer }).each_with_object({}) do |result, merged|
next unless result.is_a?(Hash)
result.each do |field, options|
id = (field.respond_to?(:id) ? field.id : field).to_s
list = Array(options).filter_map do |option|
option = option.to_h.symbolize_keys
value = option[:value].to_s.strip
{ value: value, label: option[:label].to_s.presence || value } unless value.empty?
end
(merged[id] ||= []).concat(list).uniq! { |o| o[:value].upcase }
end
end
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Custom field suggestions failed: #{e.message}"
{}
end
# Custom field values for a document's work orders, from plugins answering
# :qbo_billing_field_defaults, { customer:, issues: } => { field_id => value }
# (e.g. redmine_qbo_vehicles: the work orders' VIN). Used for an invoice made from an estimate, for the
# fields the estimate leaves blank. New estimates and invoices start blank. Returns { "2" => "..." }.
def self.field_defaults(customer, issues: [])
return {} unless customer
Redmine::Hook.call_hook(:qbo_billing_field_defaults, { customer: customer, issues: Array(issues) })
.each_with_object({}) do |result, merged|
next unless result.is_a?(Hash)
EstimateForm.custom_field_hash(result).each { |id, value| merged[id] ||= value if value.present? }
end
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Custom field defaults failed: #{e.message}"
{}
end
# True when the user may write estimates # True when the user may write estimates
def self.writer?(user = User.current) def self.writer?(user = User.current)
user.allowed_to?(:write_estimates, nil, global: true) user.allowed_to?(:write_estimates, nil, global: true)
@@ -43,6 +83,11 @@ 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)
@@ -53,6 +98,13 @@ module RedmineQboBilling
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)
+344
View File
@@ -0,0 +1,344 @@
#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
# Business figures for a date range, from the estimates, invoices and payments cached from QuickBooks and from
# Redmine's issues and spent time:
# money: estimates written, invoices written, invoices paid in full, payments received (totals and counts);
# estimates and invoices without sales tax (it isn't the shop's revenue), payments as received
# taxes: sales tax on invoices written (by their date) and on invoices paid in full (by that day)
# hours: man-hours on estimates, issues' estimated time, man-hours invoiced, time spent
# with a month-by-month breakdown. Estimates, invoices and payments count by their QuickBooks date, issues by
# the day they were created (only issues without subtasks, so parents' totals aren't counted twice), and
# spent time by the day it was spent. project_ids limits the issues and spent time to those projects; the
# QuickBooks figures have no project, so they always cover the whole business.
class BusinessReport
PERIODS = %w[this_week last_week this_month last_month this_quarter last_quarter this_year last_year custom].freeze
WEEK_DAYS = { 1 => :monday, 6 => :saturday, 7 => :sunday }.freeze
# Chart points: a day each for up to two weeks, a week each up to about three months, else a month each
DAILY_UP_TO = 14
WEEKLY_UP_TO = 93
MONEY = %i[estimates invoices paid payments].freeze
HOURS = %i[estimate_hours issue_hours invoice_hours spent_hours].freeze
TAXES = %i[tax_invoiced tax_collected].freeze
attr_reader :from, :to, :period, :project_ids
# The dates for a period, from today: [from, to]. "custom" uses the given dates (either can be blank).
def self.range_for(period, today: Date.current, from: nil, to: nil, week_start: :monday)
case period.to_s
when 'this_week' then [today.beginning_of_week(week_start), today.end_of_week(week_start)]
when 'last_week' then w = today - 7; [w.beginning_of_week(week_start), w.end_of_week(week_start)]
when 'this_month' then [today.beginning_of_month, today.end_of_month]
when 'last_month' then m = today.prev_month; [m.beginning_of_month, m.end_of_month]
when 'this_quarter' then [today.beginning_of_quarter, today.end_of_quarter]
when 'last_quarter' then q = today.beginning_of_quarter.prev_month; [q.beginning_of_quarter, q.end_of_quarter]
when 'last_year' then y = today.prev_year; [y.beginning_of_year, y.end_of_year]
when 'custom'
f = parse_date(from) || today.beginning_of_year
t = parse_date(to) || today
f > t ? [t, f] : [f, t]
else [today.beginning_of_year, today.end_of_year]
end
end
def self.parse_date(value)
return value if value.is_a?(Date)
Date.iso8601(value.to_s) if value.present?
rescue ArgumentError
nil
end
# data (for tests): { estimates: [[date, total, hours, tax]], invoices: [[date, total, hours, balance, tax]],
# paid: [[paid_on, total, tax]], payments: [[date, total]], issues: [[date, estimated_hours]],
# time_entries: [[date, hours]] }. Tax may be left off (none).
# week_start: the first day of a week (:monday, :saturday or :sunday); see week_start_from_setting.
# previous_data (for tests): last year's data, like data.
# project_ids: the projects whose issues and spent time count; blank for every project.
def initialize(period: 'this_year', from: nil, to: nil, today: Date.current, data: nil, week_start: :monday,
previous_data: nil, project_ids: nil)
@period = PERIODS.include?(period.to_s) ? period.to_s : 'this_year'
@week_start = week_start
@from, @to = self.class.range_for(@period, today: today, from: from, to: to, week_start: week_start)
@today = today
@data = data
@previous_data = previous_data
@project_ids = Array(project_ids).map(&:to_i).select(&:positive?).uniq
end
# Whether the issues and spent time are limited to some projects
def projects_filtered?
project_ids.any?
end
# Redmine's "Start calendars on" setting (1 Monday, 6 Saturday, 7 Sunday); Monday when it follows the language
def self.week_start_from_setting(value)
WEEK_DAYS[value.to_i] || :monday
end
# ---- charts ----
# :day, :week or :month, from the length of the period
def granularity
days = (to - from).to_i + 1
return :day if days <= DAILY_UP_TO
days <= WEEKLY_UP_TO ? :week : :month
end
# The chart's points as [first day, last day] pairs covering the period
def buckets
@buckets ||= begin
list = []
case granularity
when :day
(from..to).each { |day| list << [day, day] }
when :week
start = from.beginning_of_week(@week_start)
while start <= to
list << [[start, from].max, [start + 6, to].min]
start += 7
end
else
start = from.beginning_of_month
while start <= to
list << [[start, from].max, [start.end_of_month, to].min]
start = start.next_month
end
end
list
end
end
# The same points a year earlier. Days and weeks go back 52 weeks, so a Monday lines up with a Monday;
# months go back to the same month.
def previous_buckets
@previous_buckets ||= if granularity == :month
buckets.map { |a, b| [a.prev_year, b.prev_year] }
else
buckets.map { |a, b| [a - 364, b - 364] }
end
end
# Everything the line charts need: the points' start dates, this period's figures per point (nil after
# today, so the line stops there), and last year's for the same points (the toggle shows them).
# { granularity:, points: ["2026-10-26", ...],
# current: { estimates: [...], invoices:, payments:, estimate_hours:, issue_hours:, invoice_hours:, spent_hours: },
# previous: { same keys } }
def chart
current = sums_by_bucket(data, buckets)
current.each_value { |values| buckets.each_with_index { |(a, _), i| values[i] = nil if a > @today } }
{
granularity: granularity,
points: buckets.map { |a, _| a.iso8601 },
ends: buckets.map { |_, b| b.iso8601 },
previous_points: previous_buckets.map { |a, _| a.iso8601 },
current: current,
previous: sums_by_bucket(previous_data, previous_buckets)
}
end
# Last year's data for the chart's points
def previous_data
@previous_data ||= load_data(previous_buckets.first[0], previous_buckets.last[1])
end
def data
@data ||= load_data
end
# Where each money figure's rows are and how much each row counts: estimates, invoices and invoices paid in
# full without their sales tax, payments as received
MONEY_ROWS = {
estimates: [:estimates, ->(r) { to_money(r[1]) - to_money(r[3]) }],
invoices: [:invoices, ->(r) { to_money(r[1]) - to_money(r[4]) }],
paid: [:paid, ->(r) { to_money(r[1]) - to_money(r[2]) }],
payments: [:payments, ->(r) { to_money(r[1]) }]
}.freeze
# Sales tax on invoices written (by their date) and on invoices paid in full (by that day)
TAX_ROWS = {
tax_invoiced: [:invoices, ->(r) { to_money(r[4]) }],
tax_collected: [:paid, ->(r) { to_money(r[2]) }]
}.freeze
def self.to_money(value)
BigDecimal(value.to_s.presence || '0')
rescue ArgumentError
BigDecimal('0')
end
# { estimates: { total:, count: }, invoices: { total:, count:, balance:, with_tax: }, paid: { total:, count: },
# payments: { total:, count: } }. Invoices' balance (still owed) and with_tax are what the customers pay.
def money
@money ||= MONEY_ROWS.to_h do |key, (source, value)|
rows = Array(data[source])
[key, { total: rows.sum(BigDecimal('0')) { |r| value.call(r) }, count: rows.size }]
end.tap do |figures|
figures[:invoices][:balance] = money_sum(data[:invoices], 3)
figures[:invoices][:with_tax] = money_sum(data[:invoices], 1)
end
end
# { tax_invoiced: { total:, count: }, tax_collected: { total:, count: } }: count is the invoices that had tax
def taxes
@taxes ||= TAX_ROWS.to_h do |key, (source, value)|
amounts = Array(data[source]).map { |r| value.call(r) }
[key, { total: amounts.sum(BigDecimal('0')), count: amounts.count(&:positive?) }]
end
end
# { estimate_hours:, issue_hours:, invoice_hours:, spent_hours: }
def hours
@hours ||= {
estimate_hours: hour_sum(data[:estimates], 2),
issue_hours: hour_sum(data[:issues], 1),
invoice_hours: hour_sum(data[:invoices], 2),
spent_hours: hour_sum(data[:time_entries], 1)
}
end
# Cost performance index: invoiced hours / spent hours (e.g. 0.85), or nil without spent time. Below
# CPI_WARNING (0.8) is poor, below 1 is under, 1 or more is on or over (more billed than worked).
CPI_WARNING = 0.8
def self.cpi(invoice_hours, spent_hours)
spent = spent_hours.to_f
spent.positive? ? (invoice_hours.to_f / spent).round(2) : nil
end
# :poor (below 0.8), :under (below 1) or :good (1 or more); nil without a CPI
def self.cpi_level(cpi)
return nil if cpi.nil?
return :poor if cpi < CPI_WARNING
cpi < 1 ? :under : :good
end
def cpi
self.class.cpi(hours[:invoice_hours], hours[:spent_hours])
end
# Percentages comparing the figures (nil when there's nothing to compare against)
def ratios
{
invoiced_of_estimated: percent(money[:invoices][:total], money[:estimates][:total]),
# Payments include sales tax, so they're compared with the invoices' totals with tax
collected_of_invoiced: percent(money[:payments][:total], money[:invoices][:with_tax]),
invoiced_of_spent: percent(hours[:invoice_hours], hours[:spent_hours]),
spent_of_estimated: percent(hours[:spent_hours], hours[:issue_hours])
}
end
# One row per month in the range, up to the current month: { month: Date (1st), estimates:, invoices:,
# payments:, estimate_hours:, issue_hours:, invoice_hours:, spent_hours: }
def months
@months ||= begin
rows = []
month = from.beginning_of_month
last = [to, @today].min
last = from if last < from
while month <= last
rows << { month: month }.merge((MONEY + HOURS + TAXES).index_with { |_| 0 })
month = month.next_month
end
index = rows.index_by { |r| [r[:month].year, r[:month].month] }
add = lambda do |list, key, col, kind|
list.each do |row|
r = index[[row[0].year, row[0].month]] or next
r[key] += kind == :money ? to_d(row[col]) : row[col].to_f
end
end
MONEY_ROWS.merge(TAX_ROWS).each do |key, (source, value)|
Array(data[source]).each do |row|
r = index[[row[0].year, row[0].month]] or next
r[key] += value.call(row)
end
end
add.call(data[:estimates], :estimate_hours, 2, :hours)
add.call(data[:issues], :issue_hours, 1, :hours)
add.call(data[:invoices], :invoice_hours, 2, :hours)
add.call(data[:time_entries], :spent_hours, 1, :hours)
rows
end
end
# Estimates and invoices in the range that synced before totals, hours and sales tax were cached (a full sync
# fills them)
def unsynced_count
data[:estimates].count { |r| r[1].nil? || r[2].nil? || (r.size > 3 && r[3].nil?) } +
data[:invoices].count { |r| r[1].nil? || r[2].nil? || (r.size > 4 && r[4].nil?) }
end
private
# { money key or hours key => [sum per bucket] } for the data, in buckets ([first day, last day] pairs)
def sums_by_bucket(rows, bucket_list)
sums = (MONEY + HOURS + TAXES).index_with { |_| Array.new(bucket_list.size, 0.0) }
find = lambda do |date|
bucket_list.index { |a, b| date >= a && date <= b }
end
MONEY_ROWS.merge(TAX_ROWS).each do |key, (source, value)|
Array(rows[source]).each do |row|
i = find.call(row[0]) or next
sums[key][i] += value.call(row).to_f
end
end
columns = { estimate_hours: [:estimates, 2], issue_hours: [:issues, 1], invoice_hours: [:invoices, 2],
spent_hours: [:time_entries, 1] }
columns.each do |key, (source, col)|
Array(rows[source]).each do |row|
i = find.call(row[0]) or next
sums[key][i] += row[col].to_f
end
end
sums.transform_values { |values| values.map { |v| v.round(2) } }
end
def load_data(from = self.from, to = self.to)
dates = from..to
times = from.in_time_zone.beginning_of_day..to.in_time_zone.end_of_day
leaf = "#{Issue.table_name}.rgt IS NULL OR #{Issue.table_name}.rgt - #{Issue.table_name}.lft = 1"
issues = Issue.where(created_on: times).where(leaf).where.not(estimated_hours: nil)
time_entries = TimeEntry.where(spent_on: dates)
if projects_filtered?
issues = issues.where(project_id: project_ids)
time_entries = time_entries.where(project_id: project_ids)
end
{
estimates: Estimate.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours, :tax_amount),
invoices: Invoice.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours, :balance, :tax_amount),
paid: Invoice.where(paid_on: dates).where('total_amount > 0').pluck(:paid_on, :total_amount, :tax_amount),
payments: Payment.where(txn_date: dates).pluck(:txn_date, :total_amount),
issues: issues.pluck(:created_on, :estimated_hours).map { |t, h| [t.in_time_zone.to_date, h] },
time_entries: time_entries.pluck(:spent_on, :hours)
}
end
def money_sum(rows, col)
rows.sum(BigDecimal('0')) { |r| to_d(r[col]) }
end
def hour_sum(rows, col)
rows.sum(0.0) { |r| r[col].to_f }.round(2)
end
def to_d(value)
BigDecimal(value.to_s.presence || '0')
rescue ArgumentError
BigDecimal('0')
end
def percent(part, whole)
whole = whole.to_f
return nil if whole <= 0
(part.to_f / whole * 100).round
end
end
end
+48 -17
View File
@@ -10,44 +10,64 @@
module RedmineQboBilling module RedmineQboBilling
# What the QuickBooks company is set up with, read from its Preferences so nothing has to be configured # What the QuickBooks company is set up with, read from its Preferences so nothing has to be configured
# in Redmine: the estimate custom fields (found by name), whether estimate numbers are typed by hand, # in Redmine: the sales form custom fields, whether estimate numbers are typed by hand, and the default
# and the default message shown on estimates. # messages. Every enabled text custom field gets a box on the estimate/invoice editor; the sales person
# (found by name) is filled in automatically. Other plugins find the fields they fill by name
# (custom_field_matching), e.g. redmine_qbo_vehicles' VIN.
# #
# QuickBooks only shares its first three text custom fields with apps (dropdown fields aren't # QuickBooks only shares its first three text custom fields with apps (dropdown fields aren't
# available), so a "Sales Person" dropdown has to be changed to a text field to be filled in here. # available), so a "Sales Person" dropdown has to be changed to a text field to be filled in here.
module Company module Company
CACHE_KEY = 'redmine_qbo_billing:company' CACHE_KEY = 'redmine_qbo_billing:company'
CACHE_TIME = 1.hour CACHE_TIME = 1.hour
# While the VIN or sales person field is missing, look again sooner (e.g. right after adding it in QuickBooks) # While no custom fields are found, look again sooner (e.g. right after adding one in QuickBooks)
MISSING_FIELD_CACHE_TIME = 5.minutes MISSING_FIELD_CACHE_TIME = 5.minutes
# Recent estimates also show which custom fields exist, for companies whose preferences don't list them # Recent estimates also show which custom fields exist, for companies whose preferences don't list them
RECENT_ESTIMATES = 20 RECENT_ESTIMATES = 20
# QuickBooks' legacy sales form custom fields; its newer custom fields have larger DefinitionIds
LEGACY_FIELD_IDS = (1..3).freeze
# Custom field names are matched loosely, e.g. "VIN", "Vin #", "Sales Person", "Salesperson", "Sales Rep" # The sales person field is found loosely, e.g. "Sales Person", "Salesperson", "Sales Rep"
VIN_NAME = /\bvin\b/i
SALES_PERSON_NAME = /sales|\brep\b/i SALES_PERSON_NAME = /sales|\brep\b/i
MILEAGE_NAME = /mileage|odometer|\bmiles\b/i
Field = Struct.new(:id, :name) Field = Struct.new(:id, :name)
module_function module_function
# All enabled sales form custom fields, in QuickBooks' order # The sales form custom fields the plugin uses, in QuickBooks' order: all those found, except the ones
# hidden in the plugin settings. Everything else (the editor, the sales person, other plugins' VIN and
# mileage) goes through here, so a hidden field is never shown or filled in.
def custom_fields def custom_fields
hidden = hidden_field_ids
all_custom_fields.reject { |f| hidden.include?(f.id.to_i) }
end
# Every custom field found, hidden ones included (listed on the plugin settings page)
def all_custom_fields
Array(settings[:custom_fields]).map { |f| Field.new(f[:id], f[:name]) } Array(settings[:custom_fields]).map { |f| Field.new(f[:id], f[:name]) }
end end
def vin_field # Fields hidden in the plugin settings. QuickBooks doesn't tell apps which custom fields are inactive,
custom_fields.detect { |f| f.name.to_s =~ VIN_NAME } # and a field stays on its old estimates after it's turned off (e.g. a renamed "Sales Rep old"), so the
# plugin can't leave those out by itself.
def hidden_field_ids
Array((Setting.plugin_redmine_qbo || {})['hidden_custom_field_ids']).map(&:to_i).reject(&:zero?)
end end
# Optional: a text field named like "Mileage" or "Odometer" # The first enabled custom field whose name matches, e.g. a plugin's VIN field (/\bvin\b/i), or nil
def mileage_field def custom_field_matching(pattern)
custom_fields.detect { |f| f.name.to_s =~ MILEAGE_NAME && f.name.to_s !~ VIN_NAME } custom_fields.detect { |f| f.name.to_s =~ pattern }
end
# The custom fields edited on the estimate/invoice editor: all of them except the sales person, which is
# filled in automatically
def editable_custom_fields
sales = sales_person_field
custom_fields.reject { |f| sales && f.id.to_i == sales.id.to_i }
end end
def sales_person_field def sales_person_field
custom_fields.detect { |f| f.name.to_s =~ SALES_PERSON_NAME && f.name.to_s !~ VIN_NAME } custom_fields.detect { |f| f.name.to_s =~ SALES_PERSON_NAME }
end end
# When on, QuickBooks leaves estimate numbers to the user; when off it numbers them itself # When on, QuickBooks leaves estimate numbers to the user; when off it numbers them itself
@@ -55,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
@@ -79,8 +104,7 @@ module RedmineQboBilling
fresh = fetch_settings fresh = fetch_settings
return {} unless fresh return {} unless fresh
names = fresh[:custom_fields].map { |f| f[:name].to_s } complete = Array(fresh[:custom_fields]).any?
complete = names.any? { |n| n =~ VIN_NAME } && names.any? { |n| n =~ SALES_PERSON_NAME && n !~ VIN_NAME }
Rails.cache.write(CACHE_KEY, fresh, expires_in: complete ? CACHE_TIME : MISSING_FIELD_CACHE_TIME) Rails.cache.write(CACHE_KEY, fresh, expires_in: complete ? CACHE_TIME : MISSING_FIELD_CACHE_TIME)
fresh fresh
end end
@@ -94,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
} }
@@ -103,9 +128,15 @@ module RedmineQboBilling
nil nil
end end
# Fields named in the preferences come first; fields only seen on estimates are added after them. # QuickBooks' newer custom fields (made under Settings > Custom fields) aren't in the preferences, which
# QuickBooks' newer custom fields (e.g. on Advanced and sandbox companies) may not be in the preferences. # keep listing the legacy fields (DefinitionIds 1-3) after a company moves to the newer ones, often
# renamed or inactive (e.g. "Sales Rep old"). Once estimates show any newer field, those are the
# company's fields and the legacy ones are left out. Otherwise the legacy fields named in the
# preferences come first, then any only seen on estimates.
def merge_fields(from_preferences, from_estimates) def merge_fields(from_preferences, from_estimates)
newer = from_estimates.reject { |f| LEGACY_FIELD_IDS.cover?(f[:id]) }
return newer if newer.any?
ids = from_preferences.map { |f| f[:id] } ids = from_preferences.map { |f| f[:id] }
from_preferences + from_estimates.reject { |f| ids.include?(f[:id]) } from_preferences + from_estimates.reject { |f| ids.include?(f[:id]) }
end end
+69 -2
View File
@@ -92,18 +92,28 @@ 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 vin mileage 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
attr_accessor :id, :sync_token, *HEADER_ATTRIBUTES, :sales_person, :lines, attr_accessor :id, :sync_token, *HEADER_ATTRIBUTES, :sales_person, :lines,
# QuickBooks custom field values by field id: { "2" => "1FTFW1E50NFA12345" } (the sales person
# is kept apart, in sales_person)
:custom_fields,
# 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
: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
@@ -114,6 +124,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
@@ -121,6 +132,21 @@ module RedmineQboBilling
super super
self.lines ||= [] self.lines ||= []
self.linked_estimate_ids ||= [] self.linked_estimate_ids ||= []
self.custom_fields = self.class.custom_field_hash(custom_fields)
end
# { "2" => "value" } from a hash keyed by field id (string, integer or Company::Field)
def self.custom_field_hash(values)
(values || {}).to_h.each_with_object({}) do |(field, value), hash|
id = field.respond_to?(:id) ? field.id : field
hash[id.to_s] = value.to_s.strip if id.to_s =~ /\A\d+\z/
end
end
# A custom field's value (by field id or Company::Field)
def custom_field(field)
id = field.respond_to?(:id) ? field.id : field
custom_fields[id.to_s].to_s
end end
def document def document
@@ -142,6 +168,7 @@ module RedmineQboBilling
form.txn_status = params['txn_status'].presence form.txn_status = params['txn_status'].presence
form.balance = params['balance'].presence form.balance = params['balance'].presence
form.linked_estimate_ids = Array(params['linked_estimate_ids']).map(&:to_s).reject(&:blank?).uniq form.linked_estimate_ids = Array(params['linked_estimate_ids']).map(&:to_s).reject(&:blank?).uniq
form.custom_fields = custom_field_hash(params['custom_fields'])
form.lines = params['lines'].to_h.values.map { |row| Line.from_params(row) } form.lines = params['lines'].to_h.values.map { |row| Line.from_params(row) }
form form
end end
@@ -174,6 +201,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
@@ -221,6 +277,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
@@ -12,71 +12,56 @@ module RedmineQboBilling
# Turns the labor lines of a QuickBooks estimate into proposed issues, and creates the ones the user selects # Turns the labor lines of a QuickBooks estimate into proposed issues, and creates the ones the user selects
# on the "Create issues from estimate" page (moved here from redmine_qbo_calendar). # on the "Create issues from estimate" page (moved here from redmine_qbo_calendar).
# #
# - Only lines whose item matches a configured item code (e.g. "Labor", "Alignments") are proposed # - Only lines with a labor product/service (LaborItems, e.g. "Labor") are proposed
# - Subject = the line's description; estimated hours = the line's quantity # - Subject = the line's description; estimated hours = the line's quantity
# - 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 vehicle and
# custom field values where the page left them empty (the same rules as the subtask_field_copier plugin,
# which is used when installed)
# #
# 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: } => a hash of start_date, due_date, assignee,
# vehicle_id, description, project, return_path, return_label (e.g. redmine_qbo_calendar, when the page is # description, project, return_path, return_label, plus anything a plugin's own fields need (e.g.
# opened from an appointment) # redmine_qbo_calendar's vehicle_id, when the page is opened from an appointment)
# :qbo_billing_build_issue, { issue:, estimate:, defaults: } for each new issue before it's saved, to set
# plugins' own fields (e.g. redmine_qbo_vehicles sets the vehicle)
# :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
# in defaults (e.g. redmine_qbo_vehicles' Vehicle, preselected from the estimate's VIN)
# :qbo_billing_issues_created, { estimate:, issues:, params: } after issues are created # :qbo_billing_issues_created, { estimate:, issues:, params: } after issues are created
class EstimateIssueBuilder class EstimateIssueBuilder
include Redmine::I18n include Redmine::I18n
DEFAULT_ITEM_CODES = ['Labor'].freeze
Proposal = Struct.new(:line_id, :item_name, :description, :hours, :existing_issue, keyword_init: true) do Proposal = Struct.new(:line_id, :item_name, :description, :hours, :existing_issue, keyword_init: true) do
def created? def created?
existing_issue.present? existing_issue.present?
end end
end end
# Item codes from the plugin settings, one per line (commas also accepted). Until they're set here, the
# ones redmine_qbo_calendar used are kept.
def self.item_codes
raw = setting('issue_item_codes', 'item_codes').to_s
codes = raw.split(/[\n,]/).map(&:strip).reject(&:blank?)
codes.presence || DEFAULT_ITEM_CODES
end
def self.default_tracker_id def self.default_tracker_id
setting('issue_default_tracker_id', 'default_tracker_id').to_i setting('issue_default_tracker_id').to_i
end end
def self.default_project_id def self.default_project_id
setting('issue_default_project_id', 'default_project_id').to_i setting('issue_default_project_id').to_i
end end
# This plugin's setting, or redmine_qbo_calendar's old one while this one is blank def self.setting(key)
def self.setting(key, calendar_key) (Setting.plugin_redmine_qbo || {})[key]
ours = (Setting.plugin_redmine_qbo || {})[key]
return ours if ours.present?
calendar = Setting.respond_to?(:plugin_redmine_qbo_calendar) ? (Setting.plugin_redmine_qbo_calendar || {}) : {}
calendar[calendar_key]
rescue StandardError rescue StandardError
nil nil
end end
# A line matches a code if its QBO item name equals the code, or any part of a # The estimate's labor hours: the quantities of its labor lines (LaborItems)
# "Category:Item" name does. Case-insensitive.
def self.item_matches?(item_name, codes = item_codes)
name = item_name.to_s.strip.downcase
parts = name.split(':').map(&:strip)
codes.map { |c| c.strip.downcase }.any? { |code| name == code || parts.include?(code) }
end
# The estimate's labor hours: the quantities of its lines whose item matches an item code
# (e.g. for an appointment's hours, which shouldn't be less) # (e.g. for an appointment's hours, which shouldn't be less)
def self.labor_hours(estimate) def self.labor_hours(estimate)
return 0.0 if estimate.nil? return 0.0 if estimate.nil?
Array(estimate.line_items).sum do |line| Array(estimate.line_items).sum do |line|
detail = line.respond_to?(:sales_line_item_detail) ? line.sales_line_item_detail : nil detail = line.respond_to?(:sales_line_item_detail) ? line.sales_line_item_detail : nil
next 0.0 if detail.nil? || detail.item_ref.nil? || !item_matches?(detail.item_ref.name) next 0.0 if detail.nil? || !LaborItems.match?(detail.item_ref)
detail.quantity.to_f detail.quantity.to_f
end end
end end
@@ -109,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, vehicle_id, description (from another plugin's hook) # 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
@@ -172,7 +159,8 @@ module RedmineQboBilling
def build_proposals def build_proposals
return [] if estimate.blank? return [] if estimate.blank?
codes = self.class.item_codes ids = LaborItems.ids
codes = LaborItems.codes
links = QboEstimateLineIssue.where(estimate_id: estimate.id).includes(:issue).index_by(&:line_id) links = QboEstimateLineIssue.where(estimate_id: estimate.id).includes(:issue).index_by(&:line_id)
Array(estimate.line_items).each_with_index.filter_map do |line, index| Array(estimate.line_items).each_with_index.filter_map do |line, index|
@@ -180,7 +168,7 @@ module RedmineQboBilling
next if detail.nil? || detail.item_ref.nil? next if detail.nil? || detail.item_ref.nil?
item_name = detail.item_ref.name.to_s.strip item_name = detail.item_ref.name.to_s.strip
next unless self.class.item_matches?(item_name, codes) next unless LaborItems.match?(detail.item_ref, ids: ids, codes: codes)
# The subject comes from the line's description, so lines without one are skipped # The subject comes from the line's description, so lines without one are skipped
description = line.description.to_s.strip description = line.description.to_s.strip
@@ -207,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)
@@ -240,27 +230,43 @@ 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)
# Customer / vehicle / estimate fields are added to issues by redmine_qbo and redmine_qbo_vehicles # A subtask belongs to its parent's customer; otherwise the estimate's
issue.customer_id = estimate.customer_id if issue.respond_to?(:customer_id=) if issue.respond_to?(:customer_id=)
issue.vehicle_id = vehicle_id if issue.respond_to?(:vehicle_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)
Redmine::Hook.call_hook(:qbo_billing_build_issue, { issue: issue, estimate: estimate, defaults: defaults })
if parent
issue.parent_issue_id = parent.id
copy_from_parent(issue, author)
end
issue issue
end end
# The vehicle from the hook, or the customer's vehicle whose VIN is on the estimate # Fills the subtask's empty fields from the parent: custom fields (those the author can see on the parent
def vehicle_id # and edit on the subtask) and plugins' registered fields (customer, vehicle). Values entered on the page win.
return defaults[:vehicle_id] if defaults[:vehicle_id].present? def copy_from_parent(issue, author)
if defined?(::SubtaskFieldCopier)
::SubtaskFieldCopier.copy_from_parent(issue, parent, author, {})
return
end
customer = estimate.customer parent_values = parent.visible_custom_field_values(author).index_by(&:custom_field_id)
return nil unless customer.respond_to?(:vehicles) 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?)
vin = EstimateWriter.custom_value(estimate.details, Company.vin_field, Company::VIN_NAME).to_s.strip values[custom_value.custom_field_id.to_s] = value
return nil if vin.empty? end
issue.custom_field_values = copied if copied.any?
customer.vehicles.detect { |v| v.vin.to_s.casecmp?(vin) }&.id if issue.respond_to?(:vehicle_id=) && issue.vehicle_id.blank? && parent.respond_to?(:vehicle_id)
rescue StandardError issue.vehicle_id = parent.vehicle_id
nil end
end end
def default_description def default_description
+165 -30
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.
@@ -47,15 +48,15 @@ module RedmineQboBilling
# Creates an estimate for another plugin (e.g. redmine_qbo_lineitems billing an issue's line items), so # Creates an estimate for another plugin (e.g. redmine_qbo_lineitems billing an issue's line items), so
# estimates are only ever built here. Each line is a hash of :description, :item_id, :quantity, :rate, # estimates are only ever built here. Each line is a hash of :description, :item_id, :quantity, :rate,
# :taxable (a line with only a description is a note line). Returns the saved QuickBooks estimate. # :taxable (a line with only a description is a note line). Returns the saved QuickBooks estimate.
def create_estimate(customer:, lines:, private_note: nil, vin: nil, mileage: nil, user: nil, txn_date: Date.today) # custom_fields: QuickBooks custom field values by field id (see Company.custom_field_matching)
def create_estimate(customer:, lines:, private_note: nil, custom_fields: {}, user: nil, txn_date: Date.today)
form = EstimateForm.new( form = EstimateForm.new(
customer_id: customer.id, customer_id: customer.id,
customer_name: customer.name, customer_name: customer.name,
email: customer_email(customer), email: customer_email(customer),
txn_date: txn_date.iso8601, txn_date: txn_date.iso8601,
expiration_date: default_expiration_date(txn_date)&.iso8601, expiration_date: default_expiration_date(txn_date)&.iso8601,
vin: vin.to_s, custom_fields: custom_fields,
mileage: mileage.to_s,
customer_memo: Company.estimate_message, customer_memo: Company.estimate_message,
private_note: private_note.to_s, private_note: private_note.to_s,
lines: lines.map do |line| lines: lines.map do |line|
@@ -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, VIN 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
@@ -85,10 +86,11 @@ module RedmineQboBilling
txn_date: today.iso8601, txn_date: today.iso8601,
expiration_date: default_expiration_date(today)&.iso8601, expiration_date: default_expiration_date(today)&.iso8601,
sales_person: user.name, sales_person: user.name,
vin: source.vin, custom_fields: source.custom_fields.dup,
mileage: source.mileage,
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,
@@ -121,6 +123,7 @@ module RedmineQboBilling
remote = service.fetch_by_id(form.id) remote = service.fetch_by_id(form.id)
raise Error, I18n.t(:notice_estimate_not_found) unless remote raise Error, I18n.t(:notice_estimate_not_found) unless remote
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_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? raise Error, I18n.t(:error_estimate_linked_to_issues) if linked_issues(form.id).any?
@@ -141,6 +144,85 @@ module RedmineQboBilling
saved saved
end end
# An estimate's custom field value (by field id or Company::Field), read with QuickBooks' newer custom
# fields (a plain fetch, e.g. Estimate#details, leaves them out), or nil. Cached for a minute, since
# creating issues from an estimate may ask once per issue.
def custom_field_value(estimate_id, field)
return nil if estimate_id.blank? || field.nil?
id = field.respond_to?(:id) ? field.id : field
values = Rails.cache.fetch("redmine_qbo:estimate_custom_fields:#{estimate_id}", expires_in: 1.minute) do
remote = QboEstimateService.with_service { |service| service.fetch_by_id(estimate_id) }
remote ? custom_field_values(remote) : {}
end
values[id.to_s].presence
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not read estimate #{estimate_id}'s custom fields: #{e.message}"
nil
end
# A QuickBooks estimate's or invoice's text custom field values by field id: { "2" => "..." }
def custom_field_values(remote)
Array(remote.custom_fields).each_with_object({}) do |f, values|
next unless f.type.to_s == 'StringType' || f.string_value.present?
values[f.id.to_s] = f.string_value.to_s
end
end
# Statuses an estimate moves from to Accepted when the work starts (issues are created from it)
ACCEPTABLE_STATUSES = ['', 'Pending'].freeze
# A sparse update that only changes an estimate's status. QuickBooks still requires the estimate's lines
# in it ("At least 1 line item is required"), so they're sent back exactly as QuickBooks returned them.
def status_update(estimate, status)
update = Quickbooks::Model::Estimate.new
update.id = estimate.id
update.sync_token = estimate.sync_token
update.customer_ref = estimate.customer_ref
update.line_items = Array(estimate.line_items)
update.txn_status = status
update
end
AcceptResult = Struct.new(:outcome, :message) do
def accepted?; outcome == :accepted; end
def failed?; outcome == :failed; end
end
# Marks the estimate Accepted in QuickBooks when issues are created from it (the customer went ahead with
# the work), accepted today by the customer, as QuickBooks' own Accept does. Only a pending estimate
# changes; Accepted, Closed, Converted or Rejected ones are left as they are. Returns an AcceptResult:
# :accepted, :unchanged, or :failed with QuickBooks' message (never raised: the issues stand).
def accept(estimate_id, user: User.current)
outcome, status = QboEstimateService.with_service do |service|
estimate = service.fetch_by_id(estimate_id)
next [:failed, I18n.t(:notice_estimate_not_found)] if estimate.nil?
next [:unchanged, estimate.txn_status.to_s] unless ACCEPTABLE_STATUSES.include?(estimate.txn_status.to_s)
update = status_update(estimate, 'Accepted')
update.accepted_date = user.today
update.accepted_by = estimate.customer_ref&.name.presence ||
Customer.find_by(id: estimate.customer_ref&.value)&.name
saved = service.update(update, sparse: true)
saved&.txn_status.to_s == 'Accepted' ? [:accepted, nil] : [:failed, saved&.txn_status.to_s.presence || 'no answer']
end
if outcome == :accepted
sync_local(Struct.new(:id).new(estimate_id))
AcceptResult.new(:accepted, nil)
elsif outcome == :unchanged
AcceptResult.new(:unchanged, status)
else
message = I18n.t(:error_estimate_not_accepted, status: status)
Rails.logger.warn "[RedmineQboBilling] Estimate #{estimate_id}: #{message}"
AcceptResult.new(:failed, message)
end
rescue StandardError => e
message = e.respond_to?(:detail) && e.detail.present? ? "#{e.message}: #{e.detail}" : e.message
Rails.logger.warn "[RedmineQboBilling] Could not mark estimate #{estimate_id} accepted: #{message}"
AcceptResult.new(:failed, message)
end
# Emails the estimate; QuickBooks uses its own estimate email template # Emails the estimate; QuickBooks uses its own estimate email template
def send_email(id, email) def send_email(id, email)
sent = QboEstimateService.with_service { |service| service.send_estimate(id, email) } sent = QboEstimateService.with_service { |service| service.send_estimate(id, email) }
@@ -150,6 +232,16 @@ module RedmineQboBilling
# ---- QuickBooks estimate -> form ---- # ---- QuickBooks estimate -> form ----
# Statuses QuickBooks gives an estimate that has been turned into an invoice
BILLED_STATUSES = %w[Converted Closed].freeze
# True once the estimate is billed: converted or closed, or linked to an invoice. Billed estimates (including
# redmine_qbo_lineitems' once they're invoiced) can't be changed here.
def billed?(remote)
BILLED_STATUSES.include?(remote.txn_status.to_s) ||
Array(remote.linked_transactions).any? { |t| t.txn_type.to_s == 'Invoice' }
end
def form_from_remote(remote) def form_from_remote(remote)
EstimateForm.new( EstimateForm.new(
id: remote.id.to_s, id: remote.id.to_s,
@@ -162,21 +254,23 @@ module RedmineQboBilling
expiration_date: remote.expiration_date&.iso8601, expiration_date: remote.expiration_date&.iso8601,
doc_number: remote.doc_number.to_s, doc_number: remote.doc_number.to_s,
sales_person: custom_value(remote, Company.sales_person_field, Company::SALES_PERSON_NAME), sales_person: custom_value(remote, Company.sales_person_field, Company::SALES_PERSON_NAME),
vin: custom_value(remote, Company.vin_field, Company::VIN_NAME), custom_fields: custom_field_values(remote),
mileage: custom_value(remote, Company.mileage_field, Company::MILEAGE_NAME),
customer_memo: remote.customer_memo.to_s, customer_memo: remote.customer_memo.to_s,
private_note: remote.private_note.to_s, private_note: remote.private_note.to_s,
lines: tidy_subtotals(Array(remote.line_items).filter_map { |line| line_from_remote(line) }), lines: tidy_subtotals(Array(remote.line_items).filter_map { |line| line_from_remote(line) }),
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|
[t.txn_id.to_s, InvoiceWriter.invoice_number(t.txn_id)] [t.txn_id.to_s, InvoiceWriter.invoice_number(t.txn_id)]
}.uniq, }.uniq,
# Read-only when it has bundles, or once an issue is linked to it (the work is under way) # Read-only once it's billed (converted, closed or on an invoice), when it has bundles, or once an issue
locked: (:bundles if group_lines?(remote)) || (:linked if linked_issues(remote.id).any?) # is linked to it (the work is under way)
locked: (:billed if billed?(remote)) || (:bundles if group_lines?(remote)) ||
(:linked if linked_issues(remote.id).any?)
) )
end end
@@ -201,11 +295,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) 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
fields.detect { |f| f.name.to_s =~ name_pattern && (name_pattern == Company::VIN_NAME || f.name.to_s !~ Company::VIN_NAME) } # 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
@@ -229,10 +329,18 @@ 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
# Keeps every custom field already on the estimate, then sets the VIN, and the sales person on create # 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
# 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)
# sales_person: who to name instead of the user (e.g. an invoice names the estimate's sales person) # sales_person: who to name instead of the user (e.g. an invoice names the estimate's sales person)
def build_custom_fields(form, remote, user, sales_person: nil) def build_custom_fields(form, remote, user, sales_person: nil)
@@ -242,12 +350,9 @@ module RedmineQboBilling
fields[f.id.to_i] = string_field(f.id, f.name, f.string_value) fields[f.id.to_i] = string_field(f.id, f.name, f.string_value)
end end
if (vin = Company.vin_field) Company.editable_custom_fields.each do |field|
fields[vin.id.to_i] = string_field(vin.id, vin.name, form.vin.to_s.strip.upcase) next unless form.custom_fields.key?(field.id.to_s)
end fields[field.id.to_i] = string_field(field.id, field.name, form.custom_field(field))
if (mileage = Company.mileage_field)
fields[mileage.id.to_i] = string_field(mileage.id, mileage.name, form.mileage.to_s.strip)
end end
sales = Company.sales_person_field sales = Company.sales_person_field
@@ -277,14 +382,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
@@ -355,7 +490,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
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more