mirror of
https://github.com/rickbarrette/redmine_qbo.git
synced 2026-11-18 02:20:37 -05:00
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
This commit is contained in:
14 files changed
+192
-164
No files matched your search
@@ -103,7 +103,7 @@ 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.
|
||||
* **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.
|
||||
* **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 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.
|
||||
@@ -116,14 +116,14 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
|
||||
|
||||
### 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).
|
||||
* 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.
|
||||
* **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.
|
||||
* 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 (or, for an imported estimate whose work orders give none, the estimate's own VIN) 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, both supplied by redmine_qbo_vehicles. 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.
|
||||
* 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.
|
||||
|
||||
@@ -148,16 +148,16 @@ Estimates, invoices and payments count by their QuickBooks date. Issues' estimat
|
||||
|
||||
### 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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -218,18 +218,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
|
||||
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_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` value (redmine_qbo_vehicles reads it 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_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_default_vin, { customer:, issues: } | Return the VIN for a document's work orders: used when an invoice is made from an estimate that has no VIN (`issues` are the estimate's work orders). New estimates and invoices start with a blank VIN. redmine_qbo_vehicles: the work orders' vehicle when they share one
|
||||
Hook|:qbo_billing_vin_options, { customer: } | Return `[{ vin:, name: }, ...]` to suggest in the estimate/invoice VIN box; one suggestion fills an empty box (redmine_qbo_vehicles: the customer's vehicles)
|
||||
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:, vin:, doc_number: } | Adds links to an estimate page's action area (e.g. redmine_qbo_calendar's Add appointment)
|
||||
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`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -106,8 +106,8 @@ class QboEstimatesController < ApplicationController
|
||||
end
|
||||
end
|
||||
|
||||
# Customer details for the editor when a customer is picked: email, billing address and the VINs plugins
|
||||
# suggest for the VIN box (RedmineQboBilling.vin_options)
|
||||
# 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
|
||||
customer = Customer.find_by(id: params[:customer_id])
|
||||
return render(json: {}, status: :not_found) unless customer
|
||||
@@ -117,7 +117,7 @@ class QboEstimatesController < ApplicationController
|
||||
name: customer.name,
|
||||
email: RedmineQboBilling::EstimateWriter.customer_email(customer),
|
||||
billing_address: RedmineQboBilling::EstimateWriter.customer_address(customer),
|
||||
vin_options: RedmineQboBilling.vin_options(customer)
|
||||
field_options: RedmineQboBilling.field_options(customer)
|
||||
}
|
||||
end
|
||||
|
||||
@@ -205,6 +205,7 @@ class QboEstimatesController < ApplicationController
|
||||
params.require(:estimate).permit(
|
||||
:sync_token, :total_tax, :discount, :email_status, :txn_status,
|
||||
*RedmineQboBilling::EstimateForm::HEADER_ATTRIBUTES,
|
||||
custom_fields: {},
|
||||
lines: RedmineQboBilling::EstimateForm::Line::PARAMS
|
||||
)
|
||||
end
|
||||
|
||||
@@ -94,6 +94,7 @@ class QboInvoicesController < ApplicationController
|
||||
:sync_token, :total_tax, :discount, :email_status, :txn_status, :balance,
|
||||
*RedmineQboBilling::EstimateForm::HEADER_ATTRIBUTES,
|
||||
linked_estimate_ids: [],
|
||||
custom_fields: {},
|
||||
lines: RedmineQboBilling::EstimateForm::Line::PARAMS
|
||||
)
|
||||
end
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<%
|
||||
company = RedmineQboBilling::Company
|
||||
sales_field = company.sales_person_field
|
||||
vin_field = company.vin_field
|
||||
mileage_field = company.mileage_field
|
||||
# A box for every other text custom field QuickBooks has enabled (e.g. VIN, Mileage, Crew #)
|
||||
custom_fields = company.editable_custom_fields
|
||||
customer = Customer.find_by(id: form.customer_id) if form.customer_id.present?
|
||||
# VINs other plugins suggest for the VIN box (e.g. redmine_qbo_vehicles: the customer's vehicles)
|
||||
vin_options = RedmineQboBilling.vin_options(customer)
|
||||
# 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
|
||||
settings_read = company.settings.present?
|
||||
# The same editor writes estimates and invoices
|
||||
@@ -117,28 +117,21 @@
|
||||
<em class="info"><%= l(:text_no_sales_person_field) %></em>
|
||||
<% end %>
|
||||
</div>
|
||||
<div class="qbo-field qbo-field-vin">
|
||||
<label for="qbo_estimate_vin"><%= vin_field&.name || l(:label_vin) %></label>
|
||||
<%= text_field_tag 'estimate[vin]', form.vin, id: 'qbo_estimate_vin', list: 'qbo-estimate-vins', maxlength: 31,
|
||||
autocomplete: 'off', spellcheck: false, disabled: vin_field.nil? %>
|
||||
<datalist id="qbo-estimate-vins">
|
||||
<% vin_options.each do |option| %>
|
||||
<option value="<%= option[:vin] %>"><%= option[:name] %></option>
|
||||
<% end %>
|
||||
</datalist>
|
||||
<% if settings_read && !vin_field %>
|
||||
<em class="info"><%= l(:text_no_vin_field) %></em>
|
||||
<% end %>
|
||||
</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' %>
|
||||
<%# Plugins' editor scripts find a box by its field id or name (qboEditor.field / fieldNamed) %>
|
||||
<% custom_fields.each do |field| %>
|
||||
<div class="qbo-field qbo-field-custom" data-qbo-field-id="<%= field.id %>" data-qbo-field-name="<%= field.name %>">
|
||||
<label for="qbo_custom_field_<%= field.id %>"><%= field.name %></label>
|
||||
<%= text_field_tag "estimate[custom_fields][#{field.id}]", form.custom_field(field), id: "qbo_custom_field_#{field.id}",
|
||||
list: "qbo-custom-field-options-#{field.id}", maxlength: 31, autocomplete: 'off', spellcheck: false,
|
||||
class: 'qbo-custom-field' %>
|
||||
<datalist id="qbo-custom-field-options-<%= field.id %>">
|
||||
<% Array(field_options[field.id.to_s]).each do |option| %>
|
||||
<option value="<%= option[:value] %>"><%= option[:label] %></option>
|
||||
<% end %>
|
||||
</datalist>
|
||||
</div>
|
||||
<% 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">
|
||||
<%= link_to sprite_icon('reload', l(:button_refresh_quickbooks_fields)), refresh_company_qbo_estimates_path,
|
||||
method: :post, class: 'icon icon-reload' %>
|
||||
@@ -197,8 +190,7 @@
|
||||
<%# 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
|
||||
data-loading-text="<%= l(:label_loading) %>" data-none-text="<%= l(:label_none) %>"
|
||||
data-need-customer-text="<%= l(:error_estimate_needs_customer) %>"
|
||||
data-many-vehicles-text="<%= l(:text_invoice_many_vehicles) %>">
|
||||
data-need-customer-text="<%= l(:error_estimate_needs_customer) %>">
|
||||
<div class="qbo-import-columns">
|
||||
<section class="qbo-import-time">
|
||||
<h4><%= l(:label_billable_time) %></h4>
|
||||
@@ -303,3 +295,5 @@
|
||||
|
||||
<%= render partial: 'qbo_estimates/styles' %>
|
||||
<%= 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 }) %>
|
||||
@@ -4,6 +4,32 @@ $(function () {
|
||||
var $form = $('#qbo-estimate-form');
|
||||
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 template = document.getElementById('qbo-estimate-line-template').innerHTML;
|
||||
var subtotalTemplate = document.getElementById('qbo-estimate-subtotal-template').innerHTML;
|
||||
@@ -270,7 +296,6 @@ $(function () {
|
||||
|
||||
// ---- customer ----
|
||||
var $email = $('#qbo_estimate_email');
|
||||
var $vin = $('#qbo_estimate_vin');
|
||||
var loadedEmail = $email.val();
|
||||
|
||||
$('#customer_id').on('change', function () {
|
||||
@@ -283,12 +308,13 @@ $(function () {
|
||||
loadedEmail = info.email || '';
|
||||
$('#qbo-estimate-address').text(info.billing_address || '');
|
||||
|
||||
// VINs plugins suggest for this customer (e.g. their vehicles), offered in the VIN box's list; the box
|
||||
// itself stays as it is (a new document starts blank)
|
||||
var $list = $('#qbo-estimate-vins').empty();
|
||||
(info.vin_options || []).forEach(function (option) {
|
||||
$('<option>').attr('value', option.vin).text(option.name).appendTo($list);
|
||||
// Plugins' suggestions for this customer go in the custom field boxes' lists; the boxes themselves
|
||||
// stay as they are (a new document starts blank)
|
||||
$form.find('.qbo-field-custom').each(function () {
|
||||
var fieldId = $(this).data('qboFieldId');
|
||||
window.qboEditor.setFieldOptions(fieldId, (info.field_options || {})[String(fieldId)]);
|
||||
});
|
||||
$form.trigger('qbo:customer-changed', [{ customer_id: id, info: info }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -297,8 +323,6 @@ $(function () {
|
||||
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)
|
||||
var expirationDays = parseInt($form.data('expirationDays'), 10) || 0;
|
||||
var $txnDate = $('#qbo_estimate_txn_date');
|
||||
@@ -380,33 +404,6 @@ $(function () {
|
||||
return ids;
|
||||
};
|
||||
|
||||
// VIN and mileage from the work orders (via plugins such as redmine_qbo_vehicles): one vehicle fills the
|
||||
// VIN box; the highest mileage fills the mileage box. Imported estimates whose work orders give no VIN
|
||||
// add their own.
|
||||
var updateVehicleFields = function (issueIds, importedEstimates) {
|
||||
var values = (importData && importData.issue_values) || {};
|
||||
var vins = [], mileage = null;
|
||||
var addVin = function (vin) {
|
||||
vin = (vin || '').trim().toUpperCase();
|
||||
if (vin && vins.indexOf(vin) < 0) vins.push(vin);
|
||||
};
|
||||
issueIds.forEach(function (id) {
|
||||
var v = values[id] || {};
|
||||
addVin(v.vin);
|
||||
var miles = parseNumber(v.mileage);
|
||||
if (miles !== null && !isNaN(miles) && (mileage === null || miles > mileage)) mileage = miles;
|
||||
});
|
||||
(importedEstimates || []).forEach(function (estimate) {
|
||||
var fromIssue = estimate.issue_id && (values[String(estimate.issue_id)] || {}).vin;
|
||||
if (!fromIssue) addVin(estimate.vin);
|
||||
});
|
||||
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
|
||||
var insertAfterFilled = function ($rows) {
|
||||
var $filled = rows().filter(function () { return !rowIsBlank($(this)); });
|
||||
@@ -546,9 +543,10 @@ $(function () {
|
||||
estimates.forEach(function (estimate) {
|
||||
if (estimate.issue_id && issueIds.indexOf(String(estimate.issue_id)) < 0) issueIds.push(String(estimate.issue_id));
|
||||
});
|
||||
var vins = updateVehicleFields(issueIds, estimates);
|
||||
$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);
|
||||
});
|
||||
|
||||
|
||||
@@ -24,8 +24,7 @@
|
||||
.qbo-field-date input { width: 150px; }
|
||||
.qbo-field-number input { width: 160px; }
|
||||
.qbo-field-sales-person input { width: 200px; }
|
||||
.qbo-field-vin input { width: 220px; font-family: monospace; text-transform: uppercase; }
|
||||
.qbo-field-mileage input { width: 120px; }
|
||||
.qbo-field-custom input { width: 200px; }
|
||||
.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-estimate-amount { text-align: right; flex-shrink: 0; }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<div class="contextual">
|
||||
<%# 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 %>
|
||||
<% 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' %>
|
||||
|
||||
@@ -167,7 +167,6 @@ en:
|
||||
label_subtotal: "Subtotal"
|
||||
label_tax: "Tax"
|
||||
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_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_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_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_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"
|
||||
@@ -254,7 +252,6 @@ en:
|
||||
notice_invoice_sent: "Invoice #%{number} emailed 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_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_replace_lines: "Tick the lines the time replaces (e.g. the estimate's labor lines). The time goes where the first ticked line is."
|
||||
|
||||
|
||||
+33
-23
@@ -27,35 +27,45 @@ module RedmineQboBilling
|
||||
end
|
||||
end
|
||||
|
||||
# VINs to suggest in the estimate/invoice VIN box for a customer, from plugins answering
|
||||
# :qbo_billing_vin_options, { customer: } => [{ vin:, name: }, ...] (e.g. redmine_qbo_vehicles: the
|
||||
# customer's vehicles)
|
||||
def self.vin_options(customer)
|
||||
return [] unless customer
|
||||
# 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_vin_options, { customer: customer }).flatten.compact.filter_map do |option|
|
||||
option = option.to_h.symbolize_keys
|
||||
vin = option[:vin].to_s.strip
|
||||
{ vin: vin, name: option[:name].to_s.presence || vin } unless vin.empty?
|
||||
end.uniq { |o| o[:vin].upcase }
|
||||
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] VIN suggestions failed: #{e.message}"
|
||||
[]
|
||||
Rails.logger.warn "[RedmineQboBilling] Custom field suggestions failed: #{e.message}"
|
||||
{}
|
||||
end
|
||||
|
||||
# The VIN for a document's work orders, from plugins answering
|
||||
# :qbo_billing_default_vin, { customer:, issues: } => a VIN or nil (e.g. redmine_qbo_vehicles: the work
|
||||
# orders' vehicle when they share one)
|
||||
# Used for an invoice made from an estimate that has no VIN (issues: the estimate's work orders). New
|
||||
# estimates and invoices start with a blank VIN.
|
||||
def self.default_vin(customer, issues: [])
|
||||
return nil unless customer
|
||||
# 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_default_vin, { customer: customer, issues: Array(issues) })
|
||||
.flatten.compact.map { |vin| vin.to_s.strip }.reject(&:empty?).first
|
||||
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] Default VIN failed: #{e.message}"
|
||||
nil
|
||||
Rails.logger.warn "[RedmineQboBilling] Custom field defaults failed: #{e.message}"
|
||||
{}
|
||||
end
|
||||
|
||||
# True when the user may write estimates
|
||||
|
||||
@@ -10,23 +10,23 @@
|
||||
|
||||
module RedmineQboBilling
|
||||
# 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,
|
||||
# and the default message shown on estimates.
|
||||
# in Redmine: the sales form custom fields, whether estimate numbers are typed by hand, and the default
|
||||
# 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
|
||||
# available), so a "Sales Person" dropdown has to be changed to a text field to be filled in here.
|
||||
module Company
|
||||
CACHE_KEY = 'redmine_qbo_billing:company'
|
||||
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
|
||||
# Recent estimates also show which custom fields exist, for companies whose preferences don't list them
|
||||
RECENT_ESTIMATES = 20
|
||||
|
||||
# Custom field names are matched loosely, e.g. "VIN", "Vin #", "Sales Person", "Salesperson", "Sales Rep"
|
||||
VIN_NAME = /\bvin\b/i
|
||||
# The sales person field is found loosely, e.g. "Sales Person", "Salesperson", "Sales Rep"
|
||||
SALES_PERSON_NAME = /sales|\brep\b/i
|
||||
MILEAGE_NAME = /mileage|odometer|\bmiles\b/i
|
||||
|
||||
Field = Struct.new(:id, :name)
|
||||
|
||||
@@ -37,17 +37,20 @@ module RedmineQboBilling
|
||||
Array(settings[:custom_fields]).map { |f| Field.new(f[:id], f[:name]) }
|
||||
end
|
||||
|
||||
def vin_field
|
||||
custom_fields.detect { |f| f.name.to_s =~ VIN_NAME }
|
||||
# The first enabled custom field whose name matches, e.g. a plugin's VIN field (/\bvin\b/i), or nil
|
||||
def custom_field_matching(pattern)
|
||||
custom_fields.detect { |f| f.name.to_s =~ pattern }
|
||||
end
|
||||
|
||||
# Optional: a text field named like "Mileage" or "Odometer"
|
||||
def mileage_field
|
||||
custom_fields.detect { |f| f.name.to_s =~ MILEAGE_NAME && f.name.to_s !~ VIN_NAME }
|
||||
# The custom fields edited on the estimate/invoice editor: all of them except the sales person, which is
|
||||
# filled in automatically
|
||||
def editable_custom_fields
|
||||
sales = sales_person_field
|
||||
custom_fields.reject { |f| sales && f.id.to_i == sales.id.to_i }
|
||||
end
|
||||
|
||||
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
|
||||
|
||||
# When on, QuickBooks leaves estimate numbers to the user; when off it numbers them itself
|
||||
@@ -79,8 +82,7 @@ module RedmineQboBilling
|
||||
fresh = fetch_settings
|
||||
return {} unless fresh
|
||||
|
||||
names = fresh[:custom_fields].map { |f| f[:name].to_s }
|
||||
complete = names.any? { |n| n =~ VIN_NAME } && names.any? { |n| n =~ SALES_PERSON_NAME && n !~ VIN_NAME }
|
||||
complete = Array(fresh[:custom_fields]).any?
|
||||
Rails.cache.write(CACHE_KEY, fresh, expires_in: complete ? CACHE_TIME : MISSING_FIELD_CACHE_TIME)
|
||||
fresh
|
||||
end
|
||||
|
||||
@@ -93,12 +93,15 @@ module RedmineQboBilling
|
||||
end
|
||||
|
||||
# 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"
|
||||
attr_writer :document
|
||||
|
||||
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)
|
||||
:linked_estimate_ids,
|
||||
# Read-only details shown on the editor
|
||||
@@ -121,6 +124,21 @@ module RedmineQboBilling
|
||||
super
|
||||
self.lines ||= []
|
||||
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
|
||||
|
||||
def document
|
||||
@@ -142,6 +160,7 @@ module RedmineQboBilling
|
||||
form.txn_status = params['txn_status'].presence
|
||||
form.balance = params['balance'].presence
|
||||
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
|
||||
end
|
||||
|
||||
@@ -47,15 +47,15 @@ module RedmineQboBilling
|
||||
# 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,
|
||||
# :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(
|
||||
customer_id: customer.id,
|
||||
customer_name: customer.name,
|
||||
email: customer_email(customer),
|
||||
txn_date: txn_date.iso8601,
|
||||
expiration_date: default_expiration_date(txn_date)&.iso8601,
|
||||
vin: vin.to_s,
|
||||
mileage: mileage.to_s,
|
||||
custom_fields: custom_fields,
|
||||
customer_memo: Company.estimate_message,
|
||||
private_note: private_note.to_s,
|
||||
lines: lines.map do |line|
|
||||
@@ -72,7 +72,7 @@ module RedmineQboBilling
|
||||
save(form, user: user)
|
||||
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)
|
||||
def duplicate_form(id, user: User.current)
|
||||
source = load(id)
|
||||
@@ -85,8 +85,7 @@ module RedmineQboBilling
|
||||
txn_date: today.iso8601,
|
||||
expiration_date: default_expiration_date(today)&.iso8601,
|
||||
sales_person: user.name,
|
||||
vin: source.vin,
|
||||
mileage: source.mileage,
|
||||
custom_fields: source.custom_fields.dup,
|
||||
customer_memo: source.customer_memo,
|
||||
private_note: source.private_note,
|
||||
lines: source.lines.map do |line|
|
||||
@@ -142,20 +141,31 @@ module RedmineQboBilling
|
||||
saved
|
||||
end
|
||||
|
||||
# The VIN on an estimate, read with QuickBooks' newer custom fields (a plain fetch, e.g. Estimate#details,
|
||||
# leaves them out). Cached for a minute, since creating issues asks once per issue.
|
||||
def vin_for(estimate_id)
|
||||
return nil if estimate_id.blank?
|
||||
# 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?
|
||||
|
||||
Rails.cache.fetch("redmine_qbo:estimate_vin:#{estimate_id}", expires_in: 1.minute) do
|
||||
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_value(remote, Company.vin_field, Company::VIN_NAME).to_s.strip : ''
|
||||
end.presence
|
||||
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 VIN: #{e.message}"
|
||||
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
|
||||
|
||||
# Emails the estimate; QuickBooks uses its own estimate email template
|
||||
def send_email(id, email)
|
||||
sent = QboEstimateService.with_service { |service| service.send_estimate(id, email) }
|
||||
@@ -187,8 +197,7 @@ module RedmineQboBilling
|
||||
expiration_date: remote.expiration_date&.iso8601,
|
||||
doc_number: remote.doc_number.to_s,
|
||||
sales_person: custom_value(remote, Company.sales_person_field, Company::SALES_PERSON_NAME),
|
||||
vin: custom_value(remote, Company.vin_field, Company::VIN_NAME),
|
||||
mileage: custom_value(remote, Company.mileage_field, Company::MILEAGE_NAME),
|
||||
custom_fields: custom_field_values(remote),
|
||||
customer_memo: remote.customer_memo.to_s,
|
||||
private_note: remote.private_note.to_s,
|
||||
lines: tidy_subtotals(Array(remote.line_items).filter_map { |line| line_from_remote(line) }),
|
||||
@@ -229,10 +238,10 @@ module RedmineQboBilling
|
||||
end
|
||||
|
||||
# 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)
|
||||
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
|
||||
end
|
||||
|
||||
@@ -259,7 +268,8 @@ module RedmineQboBilling
|
||||
estimate
|
||||
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)
|
||||
# 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)
|
||||
@@ -269,12 +279,9 @@ module RedmineQboBilling
|
||||
fields[f.id.to_i] = string_field(f.id, f.name, f.string_value)
|
||||
end
|
||||
|
||||
if (vin = Company.vin_field)
|
||||
fields[vin.id.to_i] = string_field(vin.id, vin.name, form.vin.to_s.strip.upcase)
|
||||
end
|
||||
|
||||
if (mileage = Company.mileage_field)
|
||||
fields[mileage.id.to_i] = string_field(mileage.id, mileage.name, form.mileage.to_s.strip)
|
||||
Company.editable_custom_fields.each do |field|
|
||||
next unless form.custom_fields.key?(field.id.to_s)
|
||||
fields[field.id.to_i] = string_field(field.id, field.name, form.custom_field(field))
|
||||
end
|
||||
|
||||
sales = Company.sales_person_field
|
||||
|
||||
@@ -55,7 +55,7 @@ module RedmineQboBilling
|
||||
end
|
||||
|
||||
# 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)
|
||||
remote = QboEstimateService.with_service { |service| service.fetch_by_id(estimate_id) }
|
||||
raise Error, I18n.t(:notice_estimate_not_found) unless remote
|
||||
@@ -70,10 +70,10 @@ module RedmineQboBilling
|
||||
form.customer_id = source.customer_id
|
||||
form.email = source.email.presence || form.email
|
||||
form.billing_address = source.billing_address.presence || form.billing_address
|
||||
# The estimate's VIN, or else a plugin's for the estimate's work orders (e.g. their vehicle)
|
||||
form.vin = source.vin.presence ||
|
||||
RedmineQboBilling.default_vin(customer, issues: Issue.where(estimate_id: source.id.to_s).to_a)
|
||||
form.mileage = source.mileage
|
||||
# The estimate's custom fields; ones it leaves blank come from plugins for its work orders (e.g.
|
||||
# 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
|
||||
form.sales_person = source.sales_person.presence || user.name
|
||||
form.private_note = source.private_note
|
||||
@@ -146,8 +146,7 @@ module RedmineQboBilling
|
||||
due_date: remote.due_date&.iso8601,
|
||||
doc_number: remote.doc_number.to_s,
|
||||
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),
|
||||
mileage: writer.custom_value(remote, Company.mileage_field, Company::MILEAGE_NAME),
|
||||
custom_fields: writer.custom_field_values(remote),
|
||||
customer_memo: remote.customer_memo.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) }),
|
||||
@@ -286,8 +285,8 @@ module RedmineQboBilling
|
||||
|
||||
# ---- importing ----
|
||||
|
||||
# What can be pulled into an invoice for the customer: billable time and open estimates, and the VIN and
|
||||
# mileage plugins give for their work orders (and for issues already on the invoice: issue_ids)
|
||||
# What can be pulled into an invoice for the customer: billable time and open estimates, and the custom
|
||||
# field values plugins give for their work orders (and for issues already on the invoice: issue_ids)
|
||||
def import_options(customer, issue_ids: [])
|
||||
times = open_time_activities(customer)
|
||||
estimates = open_estimates(customer)
|
||||
@@ -361,8 +360,8 @@ module RedmineQboBilling
|
||||
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
|
||||
issue_id: issue_reference(lines.detect { |l| l.description.present? }&.description) || linked_issue&.id&.to_s,
|
||||
# The estimate's own VIN, used when its work orders give none
|
||||
vin: writer.custom_value(e, Company.vin_field, Company::VIN_NAME).to_s.strip,
|
||||
# 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) }
|
||||
}
|
||||
end
|
||||
|
||||
@@ -13,10 +13,10 @@ module RedmineQboBilling
|
||||
# them:
|
||||
#
|
||||
# :qbo_billing_issue_values, { issues: [Issue, ...] }
|
||||
# Return a hash of field => { issue_id => value }, e.g. redmine_qbo_vehicles returns
|
||||
# { vin: { 116 => "1C4HJXDG5JW123456" }, mileage: { 116 => "48210" } } (mileage from the issue custom
|
||||
# field named "Mileage"). The invoice's VIN and mileage boxes are filled from them when time or
|
||||
# estimates are imported (the highest mileage wins).
|
||||
# Return a hash of QuickBooks custom field id => { issue_id => value }, e.g. redmine_qbo_vehicles returns
|
||||
# { "2" => { 116 => "1C4HJXDG5JW123456" } } for the VIN field. They're given to the editor's script with
|
||||
# imported time and estimates (the qbo:imported event), and to other plugins (e.g. redmine_qbo_lineitems'
|
||||
# estimates); the plugin's own editor script decides how to fill its fields.
|
||||
#
|
||||
# :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
|
||||
@@ -51,7 +51,7 @@ module RedmineQboBilling
|
||||
ids.empty? ? [] : Issue.where(id: ids).to_a
|
||||
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)
|
||||
issues = Array(issues)
|
||||
return {} if issues.empty?
|
||||
@@ -60,12 +60,12 @@ module RedmineQboBilling
|
||||
next unless result.is_a?(Hash)
|
||||
result.each do |field, by_issue|
|
||||
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
|
||||
|
||||
# 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)
|
||||
values_for(issues).each_with_object({}) do |(field, by_id), result|
|
||||
by_id.each { |id, value| (result[id] ||= {})[field] = value }
|
||||
|
||||
Reference in new issue
Block a user