Compare commits

...
20 Commits
Author SHA1 Message Date
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
41 changed files with 782 additions and 256 deletions

No files matched your search

+19 -12
View File
@@ -103,10 +103,11 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
* **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; the customer's name still 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.
* **Read-only once billed**: an estimate that's Converted or Closed in QuickBooks, or linked to an invoice, can't be changed here either (including redmine_qbo_lineitems' estimates once they're invoiced). Its page lists the invoices it's on; it can still be viewed, emailed and duplicated, and it shows View instead of Edit in lists. * **Read-only once billed**: an estimate that's Converted or Closed in QuickBooks, or linked to an invoice, can't be changed here either (including redmine_qbo_lineitems' estimates once they're invoiced). Its page lists the invoices it's on; it can still be viewed, emailed and duplicated, and it shows View instead of Edit in lists.
* **Create issues** from an estimate's labor lines (moved here from redmine_qbo_calendar): each line with one of the **labor products/services** (e.g. Labor) becomes an issue with the line's description as subject and its quantity as estimated hours. Pick the project, trackers, templates and shared custom fields first. Lines already turned into issues can't be created twice, and issues from the same estimate are related to each other. Opened from an appointment, the issues get the appointment's dates, technician and vehicle. * **Create issues** from an estimate's labor lines (moved here from redmine_qbo_calendar): each line with one of the **labor products/services** (e.g. Labor) becomes an issue with the line's description as subject and its quantity as estimated hours. Pick the project, trackers, templates and shared custom fields first. Lines already turned into issues can't be created twice, and issues from the same estimate are related to each other. Creating issues marks a pending estimate **Accepted** in QuickBooks (dated today), since the work is going ahead; estimates that are already accepted, closed, converted or rejected keep their status. Opened from an appointment, the issues get the appointment's dates, technician and vehicle.
* **Email** the estimate with QuickBooks' own estimate email, with **Save and send** or the Email link. * **Email** the estimate with QuickBooks' own estimate email, with **Save and send** or the Email link.
* 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.
@@ -116,14 +117,14 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
### 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). Only lines with one of the **labor products/services** from the plugin settings are offered there. 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. The time goes where the first ticked line was and the ticked lines are removed, so the invoice reads in the same order.
* 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 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.
@@ -144,20 +145,20 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
* **Hours**: estimated hours on estimates, issues' estimated time, invoiced hours on invoices and time spent, with invoiced vs. spent and spent vs. estimated. * **Hours**: estimated hours on estimates, issues' estimated time, invoiced hours on invoices and time spent, with invoiced vs. spent and spent vs. estimated.
* **By month**: every figure month by month, with totals. * **By month**: every figure month by month, with totals.
Estimates, invoices and payments count by their QuickBooks date. Issues' estimated time counts issues created in the period, leaving out parents so subtasks aren't counted twice. Spent time counts time logged in the period. Estimates and invoices synced before these figures were added have no total or hours until a full sync (the report says how many); run one again after changing the labor products/services. Estimates, invoices and payments count by their QuickBooks date. Issues' estimated time counts issues created in the period, leaving out parents so subtasks aren't counted twice. Spent time counts time logged in the period. While estimates, invoices or payments are syncing, the report says so (with how many have been read) and refreshes every 30 seconds; the settings page's Synchronization table shows the same per type. Estimates and invoices synced before these figures were added have no total or hours until a full sync (the report says how many); run one again after changing the labor products/services.
### 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.
@@ -218,13 +219,19 @@ 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 }`
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`.
--- ---
+1 -1
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)
+20 -5
View File
@@ -96,7 +96,11 @@ class QboEstimatesController < ApplicationController
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,18 +110,18 @@ 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 : []
render json: { 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)
} }
end end
@@ -125,7 +129,7 @@ class QboEstimatesController < ApplicationController
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,7 +159,8 @@ class QboEstimatesController < ApplicationController
end end
return render_404 unless @estimate return render_404 unless @estimate
@defaults = issue_defaults # Values plugins' fields posted with the form (e.g. redmine_qbo_vehicles' vehicle) override their defaults
@defaults = issue_defaults.merge(submitted_plugin_fields)
@builder = RedmineQboBilling::EstimateIssueBuilder.new(@estimate, defaults: @defaults) @builder = RedmineQboBilling::EstimateIssueBuilder.new(@estimate, defaults: @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}"
@@ -185,6 +190,15 @@ class QboEstimatesController < ApplicationController
(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 +209,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
@@ -94,6 +94,7 @@ 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
@@ -18,5 +18,7 @@ class QboReportsController < ApplicationController
def index def index
@report = RedmineQboBilling::BusinessReport.new(period: params[:period].presence || 'this_year', @report = RedmineQboBilling::BusinessReport.new(period: params[:period].presence || 'this_year',
from: params[:from], to: params[:to], today: User.current.today) from: params[:from], to: params[:to], today: User.current.today)
# 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 end
end end
+4 -1
View File
@@ -40,7 +40,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
@@ -18,6 +18,7 @@ class Customer < QboBaseModel
has_many :estimates has_many :estimates
has_many :payments 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
+1
View File
@@ -13,6 +13,7 @@ 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
+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
+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
+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
+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
+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>
+1 -1
View File
@@ -1,5 +1,5 @@
<div class="contextual"> <div class="contextual">
<%# New issue for this customer; picks up the estimate / vehicle ticked on this page %> <%# 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) %>
+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>
+1 -1
View File
@@ -11,7 +11,7 @@
<label for="settings_labor_item_ids"><%= l(:label_labor_items) %></label> <label for="settings_labor_item_ids"><%= l(:label_labor_items) %></label>
<%= hidden_field_tag 'settings[labor_item_ids][]', '', id: nil %> <%= hidden_field_tag 'settings[labor_item_ids][]', '', id: nil %>
<%= select_tag 'settings[labor_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,
RedmineQboBilling::LaborItems.item_ids), RedmineQboBilling::LaborItems.item_ids),
multiple: true, size: 8, id: 'settings_labor_item_ids' %> multiple: true, size: 8, id: 'settings_labor_item_ids' %>
<em class="info"><%= l(:text_labor_items) %></em> <em class="info"><%= l(:text_labor_items) %></em>
+12 -1
View File
@@ -45,6 +45,7 @@
[l(:label_items), Item, sync_items_path, items_path], [l(:label_items), Item, sync_items_path, items_path],
[l(:label_accounts), Account, sync_accounts_path, accounts_path] [l(:label_accounts), Account, sync_accounts_path, accounts_path]
] %> ] %>
<% sync_statuses = QboSyncStatus.by_entity %>
<h3><%= l(:label_management_and_sync) %></h3> <h3><%= l(:label_management_and_sync) %></h3>
<div class="box"> <div class="box">
<table class="list qbo-sync-table"> <table class="list qbo-sync-table">
@@ -61,7 +62,16 @@
<tr> <tr>
<td class="name"><%= list_path ? link_to(label, list_path) : label %></td> <td class="name"><%= list_path ? link_to(label, list_path) : label %></td>
<td class="count"><%= model.count %></td> <td class="count"><%= model.count %></td>
<td class="updated"><%= model.last_sync %></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> <td class="buttons"><%= link_to sprite_icon('reload', l(:label_sync)), sync_path, class: 'icon icon-reload' %></td>
</tr> </tr>
<% end %> <% end %>
@@ -88,6 +98,7 @@
table.qbo-sync-table td.updated { width: 14em; } table.qbo-sync-table td.updated { width: 14em; }
table.qbo-sync-table td.buttons { width: 6em; } table.qbo-sync-table td.buttons { width: 6em; }
.qbo-sync-all .button { margin-left: 8px; } .qbo-sync-all .button { margin-left: 8px; }
.qbo-sync-busy { font-style: italic; color: #b06d00; }
</style> </style>
<%# Billing: estimates, issues from estimates and invoices %> <%# Billing: estimates, issues from estimates and invoices %>
+20 -25
View File
@@ -1,10 +1,11 @@
<% <%
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
@@ -116,28 +117,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 +190,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>
@@ -302,3 +295,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 }) %>
+1 -1
View File
@@ -18,7 +18,7 @@
<% if invoice && form.locked == :paid %> <% if invoice && form.locked == :paid %>
<% fully_paid = form.balance.to_d.zero? %> <% fully_paid = form.balance.to_d.zero? %>
<span class="qbo-estimate-status qbo-estimate-status-<%= fully_paid ? 'closed' : 'accepted' %>"><%= l(fully_paid ? :label_invoice_paid : :label_invoice_partially_paid) %></span> <span class="qbo-estimate-status qbo-estimate-status-<%= fully_paid ? 'closed' : 'accepted' %>"><%= l(fully_paid ? :label_invoice_paid : :label_invoice_partially_paid) %></span>
<% elsif !invoice && form.txn_status.present? && form.txn_status != 'Pending' %> <% 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 %>
+204 -52
View File
@@ -4,6 +4,32 @@ $(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;
@@ -18,13 +44,47 @@ $(function () {
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 ----
@@ -109,6 +169,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 +241,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 +249,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 +330,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 +378,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);
}); });
} }
@@ -270,7 +440,6 @@ $(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 () {
@@ -283,13 +452,13 @@ $(function () {
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 +467,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,24 +548,6 @@ $(function () {
return ids; return ids;
}; };
// VIN and mileage from the work orders (via plugins such as redmine_qbo_vehicles and redmine_mileage_cp):
// one vehicle fills the VIN box; the highest mileage fills the mileage box
var updateVehicleFields = function (issueIds) {
var values = (importData && importData.issue_values) || {};
var vins = [], mileage = null;
issueIds.forEach(function (id) {
var v = values[id] || {};
if (v.vin && vins.indexOf(v.vin.toUpperCase()) < 0) vins.push(v.vin.toUpperCase());
var miles = parseNumber(v.mileage);
if (miles !== null && !isNaN(miles) && (mileage === null || miles > mileage)) mileage = miles;
});
var $vinBox = $('#qbo_estimate_vin');
if (vins.length === 1 && $vinBox.length && !$vinBox.prop('disabled')) $vinBox.val(vins[0]);
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
var insertAfterFilled = function ($rows) { var insertAfterFilled = function ($rows) {
var $filled = rows().filter(function () { return !rowIsBlank($(this)); }); var $filled = rows().filter(function () { return !rowIsBlank($(this)); });
@@ -538,9 +687,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);
}); });
@@ -572,6 +722,8 @@ $(function () {
$email.trigger('focus'); $email.trigger('focus');
return; return;
} }
// Math still in a box is worked out before saving
rows().each(function () { tidyNumbers($(this)); });
dirty = false; dirty = false;
}); });
@@ -0,0 +1,10 @@
<%# 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; }
</style>
+2 -8
View File
@@ -24,8 +24,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; }
@@ -112,16 +111,10 @@
.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;
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; }
/* 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 +154,4 @@
.qbo-estimate-actions { padding: 10px 14px; } .qbo-estimate-actions { padding: 10px 14px; }
} }
</style> </style>
<%= render partial: 'qbo_estimates/status_styles' %>
+1 -1
View File
@@ -2,7 +2,7 @@
<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? && @form.locked != :billed && @form.txn_status.to_s != 'Rejected' %> <% 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' %>
@@ -136,12 +136,15 @@
</tbody> </tbody>
</table> </table>
<%# Custom fields for the chosen trackers, entered once and applied to every issue that uses them %> <%# Fields entered once and applied to every issue: plugins' own (e.g. redmine_qbo_vehicles' vehicle, posted as
<% if @field_set&.any? %> 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(',') %>">
+25
View File
@@ -27,6 +27,30 @@
<p class="qbo-report-range"><%= format_date(@report.from) %> &ndash; <%= format_date(@report.to) %></p> <p class="qbo-report-range"><%= format_date(@report.from) %> &ndash; <%= format_date(@report.to) %></p>
<% 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 %> <% if @report.unsynced_count > 0 %>
<p class="warning"><%= l(:text_report_needs_sync, count: @report.unsynced_count) %></p> <p class="warning"><%= l(:text_report_needs_sync, count: @report.unsynced_count) %></p>
<% end %> <% end %>
@@ -131,6 +155,7 @@
.qbo-bar-issue_hours { background: #9b7fc0; } .qbo-bar-issue_hours { background: #9b7fc0; }
.qbo-report-ratios { margin: 8px 4px; line-height: 1.7; } .qbo-report-ratios { margin: 8px 4px; line-height: 1.7; }
.qbo-report-range { color: #666; margin: 4px 0 10px; } .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 td, table.qbo-report-months th { text-align: right; white-space: nowrap; }
table.qbo-report-months .month { text-align: left; } table.qbo-report-months .month { text-align: left; }
table.qbo-report-months .hours-start { border-left: 2px solid #ddd; } table.qbo-report-months .hours-start { border-left: 2px solid #ddd; }
+7 -3
View File
@@ -167,7 +167,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"
@@ -183,7 +182,6 @@ en:
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"
@@ -254,7 +252,6 @@ en:
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_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_replace_lines: "Tick the lines the time replaces (e.g. the estimate's labor lines). The time goes where the first ticked line is." 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."
@@ -272,6 +269,9 @@ en:
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"
@@ -328,6 +328,10 @@ en:
label_report_open_balance: "Still owed on these invoices" label_report_open_balance: "Still owed on these invoices"
label_report_invoiced_of_spent: "Invoiced vs. spent hours" label_report_invoiced_of_spent: "Invoiced vs. spent hours"
label_report_spent_of_estimated: "Spent vs. issues' estimated hours" 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_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." 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."
notice_payment_not_found: "Payment not found in QuickBooks" notice_payment_not_found: "Payment not found in QuickBooks"
@@ -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 Hooks
# Each work order's mileage, from Redmine's own issue custom field named "Mileage" (any capitalisation), # Which QuickBooks syncs are queued or running, and how far along they are (shown on the business report and
# so an invoice's mileage box fills in when its time or estimates are imported. Answers the same # the settings page while a long sync runs)
# qbo_billing_issue_values hook other plugins use (see IssueValues). class CreateQboSyncStatuses < ActiveRecord::Migration[7.0]
class IssueMileageListener < Redmine::Hook::Listener def up
return if table_exists?(:qbo_sync_statuses)
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
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 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
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
+1 -1
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.3'
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'
+41 -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)
+16 -14
View File
@@ -10,23 +10,23 @@
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
# 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)
@@ -37,17 +37,20 @@ module RedmineQboBilling
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 # The first enabled custom field whose name matches, e.g. a plugin's VIN field (/\bvin\b/i), or nil
custom_fields.detect { |f| f.name.to_s =~ VIN_NAME } def custom_field_matching(pattern)
custom_fields.detect { |f| f.name.to_s =~ pattern }
end end
# Optional: a text field named like "Mileage" or "Odometer" # The custom fields edited on the estimate/invoice editor: all of them except the sales person, which is
def mileage_field # filled in automatically
custom_fields.detect { |f| f.name.to_s =~ MILEAGE_NAME && f.name.to_s !~ VIN_NAME } 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
@@ -79,8 +82,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
+20 -1
View File
@@ -93,12 +93,15 @@ module RedmineQboBilling
end end
# due_date is an invoice's; expiration_date an estimate's # due_date is an invoice's; expiration_date an estimate's
HEADER_ATTRIBUTES = %i[customer_id customer_name email txn_date expiration_date due_date doc_number vin mileage customer_memo private_note].freeze HEADER_ATTRIBUTES = %i[customer_id customer_name email txn_date expiration_date due_date doc_number customer_memo private_note].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
@@ -121,6 +124,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 +160,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
@@ -12,7 +12,7 @@ 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
@@ -20,8 +20,13 @@ module RedmineQboBilling
# #
# 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
@@ -89,7 +94,7 @@ module RedmineQboBilling
attr_reader :estimate, :defaults, :errors attr_reader :estimate, :defaults, :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: {}) def initialize(estimate, defaults: {})
@estimate = estimate @estimate = estimate
@defaults = (defaults || {}).to_h.symbolize_keys @defaults = (defaults || {}).to_h.symbolize_keys
@@ -218,29 +223,15 @@ 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
issue.customer_id = estimate.customer_id if issue.respond_to?(:customer_id=) issue.customer_id = estimate.customer_id if issue.respond_to?(:customer_id=)
issue.vehicle_id = vehicle_id if issue.respond_to?(:vehicle_id=)
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 })
issue issue
end end
# The vehicle from the hook, or the customer's vehicle whose VIN is on the estimate
def vehicle_id
return defaults[:vehicle_id] if defaults[:vehicle_id].present?
customer = estimate.customer
return nil unless customer.respond_to?(:vehicles)
vin = EstimateWriter.custom_value(estimate.details, Company.vin_field, Company::VIN_NAME).to_s.strip
return nil if vin.empty?
customer.vehicles.detect { |v| v.vin.to_s.casecmp?(vin) }&.id
rescue StandardError
nil
end
def default_description def default_description
defaults[:description].presence || defaults[:description].presence ||
"The purpose of this work is to bill the time spent on this issue for Estimate ##{estimate.doc_number}" "The purpose of this work is to bill the time spent on this issue for Estimate ##{estimate.doc_number}"
+92 -17
View File
@@ -47,15 +47,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,7 +72,7 @@ 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, custom fields and messages, dated today, with a
# new number, the current user as sales person, and no discounts or bundles (those stay in QuickBooks) # new number, the current user as sales person, and no discounts or bundles (those stay in QuickBooks)
def duplicate_form(id, user: User.current) def duplicate_form(id, user: User.current)
source = load(id) source = load(id)
@@ -85,8 +85,7 @@ 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,
lines: source.lines.map do |line| lines: source.lines.map do |line|
@@ -142,6 +141,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) }
@@ -173,8 +251,7 @@ 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) }),
@@ -215,10 +292,10 @@ module RedmineQboBilling
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, found by the field QuickBooks' preferences name, or by name on the estimate
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 } || match = fields.detect { |f| field && f.id.to_i == field.id.to_i } ||
fields.detect { |f| f.name.to_s =~ name_pattern && (name_pattern == Company::VIN_NAME || f.name.to_s !~ Company::VIN_NAME) } (name_pattern && fields.detect { |f| f.name.to_s =~ name_pattern })
match&.string_value.to_s match&.string_value.to_s
end end
@@ -245,7 +322,8 @@ module RedmineQboBilling
estimate estimate
end end
# Keeps every custom field already on the estimate, then sets the VIN, and the sales person on create # 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)
@@ -255,12 +333,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
+11 -13
View File
@@ -55,7 +55,7 @@ module RedmineQboBilling
end end
# A new invoice from an estimate, like QuickBooks' "Create invoice" on an estimate: the estimate's # A new invoice from an estimate, like QuickBooks' "Create invoice" on an estimate: the estimate's
# customer, lines, subtotals and VIN. The estimate is linked and closed when the invoice is saved. # customer, lines, subtotals and custom fields. The estimate is linked and closed when the invoice is saved.
def from_estimate(estimate_id, user: User.current) def from_estimate(estimate_id, user: User.current)
remote = QboEstimateService.with_service { |service| service.fetch_by_id(estimate_id) } remote = QboEstimateService.with_service { |service| service.fetch_by_id(estimate_id) }
raise Error, I18n.t(:notice_estimate_not_found) unless remote raise Error, I18n.t(:notice_estimate_not_found) unless remote
@@ -70,8 +70,10 @@ module RedmineQboBilling
form.customer_id = source.customer_id form.customer_id = source.customer_id
form.email = source.email.presence || form.email form.email = source.email.presence || form.email
form.billing_address = source.billing_address.presence || form.billing_address form.billing_address = source.billing_address.presence || form.billing_address
form.vin = source.vin # The estimate's custom fields; ones it leaves blank come from plugins for its work orders (e.g.
form.mileage = source.mileage # redmine_qbo_vehicles: their VIN)
defaults = RedmineQboBilling.field_defaults(customer, issues: Issue.where(estimate_id: source.id.to_s).to_a)
form.custom_fields = defaults.merge(source.custom_fields.reject { |_, value| value.blank? })
# The estimate's writer sells the job; with no one on the estimate, whoever writes the invoice # The estimate's writer sells the job; with no one on the estimate, whoever writes the invoice
form.sales_person = source.sales_person.presence || user.name form.sales_person = source.sales_person.presence || user.name
form.private_note = source.private_note form.private_note = source.private_note
@@ -144,8 +146,7 @@ module RedmineQboBilling
due_date: remote.due_date&.iso8601, due_date: remote.due_date&.iso8601,
doc_number: remote.doc_number.to_s, doc_number: remote.doc_number.to_s,
sales_person: writer.custom_value(remote, Company.sales_person_field, Company::SALES_PERSON_NAME), sales_person: writer.custom_value(remote, Company.sales_person_field, Company::SALES_PERSON_NAME),
vin: writer.custom_value(remote, Company.vin_field, Company::VIN_NAME), custom_fields: writer.custom_field_values(remote),
mileage: writer.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: writer.tidy_subtotals(Array(remote.line_items).filter_map { |line| writer.line_from_remote(line) }), lines: writer.tidy_subtotals(Array(remote.line_items).filter_map { |line| writer.line_from_remote(line) }),
@@ -269,12 +270,7 @@ module RedmineQboBilling
# Already Converted or Closed is left as QuickBooks set it # Already Converted or Closed is left as QuickBooks set it
next if estimate.nil? || BILLED_ESTIMATE_STATUSES.include?(estimate.txn_status.to_s) next if estimate.nil? || BILLED_ESTIMATE_STATUSES.include?(estimate.txn_status.to_s)
update = Quickbooks::Model::Estimate.new service.update(writer.status_update(estimate, 'Closed'), sparse: true)
update.id = estimate.id
update.sync_token = estimate.sync_token
update.customer_ref = estimate.customer_ref
update.txn_status = 'Closed'
service.update(update, sparse: true)
end end
EstimateSyncService.new.sync_by_id(id) EstimateSyncService.new.sync_by_id(id)
rescue StandardError => e rescue StandardError => e
@@ -284,8 +280,8 @@ module RedmineQboBilling
# ---- importing ---- # ---- importing ----
# What can be pulled into an invoice for the customer: billable time and open estimates, and the VIN and # What can be pulled into an invoice for the customer: billable time and open estimates, and the custom
# mileage plugins give for their work orders (and for issues already on the invoice: issue_ids) # field values plugins give for their work orders (and for issues already on the invoice: issue_ids)
def import_options(customer, issue_ids: []) def import_options(customer, issue_ids: [])
times = open_time_activities(customer) times = open_time_activities(customer)
estimates = open_estimates(customer) estimates = open_estimates(customer)
@@ -359,6 +355,8 @@ module RedmineQboBilling
issue: linked_issue&.then { |i| "#{i.tracker} ##{i.id}: #{i.subject}" }, issue: linked_issue&.then { |i| "#{i.tracker} ##{i.id}: #{i.subject}" },
# Lines from this estimate go next to the invoice's time for the same issue # Lines from this estimate go next to the invoice's time for the same issue
issue_id: issue_reference(lines.detect { |l| l.description.present? }&.description) || linked_issue&.id&.to_s, issue_id: issue_reference(lines.detect { |l| l.description.present? }&.description) || linked_issue&.id&.to_s,
# The estimate's own custom field values (plugins' editor scripts may use them, e.g. its VIN)
custom_fields: writer.custom_field_values(e),
lines: lines.map { |l| line_hash(l) } lines: lines.map { |l| line_hash(l) }
} }
end end
+7 -7
View File
@@ -13,10 +13,10 @@ module RedmineQboBilling
# them: # them:
# #
# :qbo_billing_issue_values, { issues: [Issue, ...] } # :qbo_billing_issue_values, { issues: [Issue, ...] }
# Return a hash of field => { issue_id => value }, e.g. redmine_qbo_vehicles returns # Return a hash of QuickBooks custom field id => { issue_id => value }, e.g. redmine_qbo_vehicles returns
# { vin: { 116 => "1C4HJXDG5JW123456" } }. This plugin answers it too with { mileage: ... } from the # { "2" => { 116 => "1C4HJXDG5JW123456" } } for the VIN field. They're given to the editor's script with
# issue custom field named "Mileage" (Hooks::IssueMileageListener). # imported time and estimates (the qbo:imported event), and to other plugins (e.g. redmine_qbo_lineitems'
# The invoice's VIN and mileage boxes are filled from them when time or estimates are imported. # estimates); the plugin's own editor script decides how to fill its fields.
# #
# :qbo_billing_validate, { document: "invoice" or "estimate", form: EstimateForm, issues: [Issue, ...] } # :qbo_billing_validate, { document: "invoice" or "estimate", form: EstimateForm, issues: [Issue, ...] }
# Return an error message (or a list of them) to stop the save, e.g. redmine_qbo_vehicles refuses an # Return an error message (or a list of them) to stop the save, e.g. redmine_qbo_vehicles refuses an
@@ -51,7 +51,7 @@ module RedmineQboBilling
ids.empty? ? [] : Issue.where(id: ids).to_a ids.empty? ? [] : Issue.where(id: ids).to_a
end end
# { vin: { "116" => "..." }, mileage: { "116" => "..." } } from every plugin listening # { "2" => { "116" => "..." } } (custom field id => values by issue) from every plugin listening
def values_for(issues) def values_for(issues)
issues = Array(issues) issues = Array(issues)
return {} if issues.empty? return {} if issues.empty?
@@ -60,12 +60,12 @@ module RedmineQboBilling
next unless result.is_a?(Hash) next unless result.is_a?(Hash)
result.each do |field, by_issue| result.each do |field, by_issue|
next unless by_issue.is_a?(Hash) next unless by_issue.is_a?(Hash)
(merged[field.to_sym] ||= {}).merge!(by_issue.transform_keys(&:to_s).transform_values(&:to_s).reject { |_, v| v.strip.empty? }) (merged[field.to_s] ||= {}).merge!(by_issue.transform_keys(&:to_s).transform_values(&:to_s).reject { |_, v| v.strip.empty? })
end end
end end
end end
# The same values by issue, for the import panel: { "116" => { vin: "...", mileage: "..." } } # The same values by issue, for the editor: { "116" => { "2" => "..." } }
def by_issue(issues) def by_issue(issues)
values_for(issues).each_with_object({}) do |(field, by_id), result| values_for(issues).each_with_object({}) do |(field, by_id), result|
by_id.each { |id, value| (result[id] ||= {})[field] = value } by_id.each { |id, value| (result[id] ||= {})[field] = value }
+1 -1
View File
@@ -55,7 +55,7 @@ module RedmineQboBilling
return chosen if chosen.any? return chosen if chosen.any?
list = codes list = codes
Item.where(active: true).pluck(:id, :name).select { |_, name| name_matches?(name, list) }.map { |id, _| id.to_s } Item.sellable.pluck(:id, :name).select { |_, name| name_matches?(name, list) }.map { |id, _| id.to_s }
rescue StandardError rescue StandardError
[] []
end end