Polish: permissions, billed-line locking, sync and billing fixes

Permissions
- Item catalog and accounts pages, and their syncs, are admin-only (they
  push to / pull from QuickBooks); shown in the Administration layout
- Item autocomplete is allowed with Add or Edit line items
- Permissions now map to real actions (they pointed at a non-existent
  line_items controller); line_items_attributes is only accepted from
  users with a line item permission
- Line item changes are checked on the server: adding, editing and
  deleting each need their permission, and billed lines (already on a
  QBO estimate) can't be changed or removed

Bugs
- Billing on close now runs from an Issue after_commit, so closing via
  bulk edit or the context menu bills too (replaces the save hook);
  the job takes an issue id
- Full sync runs Accounts before Items, and item sync no longer fails
  when an item has no income account or its account hasn't synced
- New QBO items default to Non-inventory in the default income account
  (the account ref was being assigned to the item type)
- Choosing a blank account on an item no longer raises; set_default
  handles no selection
- Item autocomplete escapes item names, SKUs and descriptions (they were
  inserted into the page as HTML)
- Items list showed "translation missing" for Yes/No

Polish
- Fractional quantities allowed (0.5 hrs, 2.5 qts)
- Billed lines show a Billed badge and are read-only; remove button only
  where allowed; add button only with Add line items
- Removed dead code (Item belongs_to :issue, Item#ref, no-op in new,
  swallowed errors); validation failures return 422

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
This commit is contained in:
Claude committed 2026-10-28 22:37:41 -04:00
1 parent f0d6b08a3d
commit 39f6b64049
20 files changed
+170 -126

No files matched your search

+13 -3
View File
@@ -9,15 +9,25 @@
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class AccountsController < ApplicationController class AccountsController < ApplicationController
layout 'admin'
menu_item :redmine_qbo_lineitems
# Accounts come from QuickBooks; choosing the default and syncing are admin-only
before_action :require_admin
def index def index
@accounts = Account.where(classification: 'Revenue').order(:name) @accounts = Account.where(classification: 'Revenue').order(:name)
end end
def set_default def set_default
account = Account.find(params[:default_account_id]) account = Account.find_by(id: params[:default_account_id])
account.update(default: true)
redirect_to accounts_path, notice: "Default account updated." if account&.update(default: true)
flash[:notice] = l(:notice_default_account_updated)
else
flash[:error] = l(:error_default_account_not_selected)
end
redirect_to accounts_path
end end
def sync def sync
+10 -11
View File
@@ -9,7 +9,13 @@
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class ItemsController < ApplicationController class ItemsController < ApplicationController
before_action :require_login layout 'admin'
menu_item :redmine_qbo_lineitems
# The item catalog is pushed to QuickBooks, so managing it is admin-only. The autocomplete feeds the
# line item form on issues and is allowed with the "Add line items" or "Edit line items" permission.
before_action :require_admin, except: :autocomplete
before_action :authorize_global, only: :autocomplete
before_action :find_item, only: [:show, :edit, :update, :destroy] before_action :find_item, only: [:show, :edit, :update, :destroy]
# Used for autocomplete form # Used for autocomplete form
@@ -32,7 +38,7 @@ class ItemsController < ApplicationController
if @item.save if @item.save
redirect_to item_path(@item), notice: l(:notice_successful_create) redirect_to item_path(@item), notice: l(:notice_successful_create)
else else
render :new render :new, status: :unprocessable_entity
end end
rescue => e rescue => e
log "Unexpected error creating item: #{e.message}" log "Unexpected error creating item: #{e.message}"
@@ -55,10 +61,6 @@ class ItemsController < ApplicationController
end end
def edit def edit
rescue => e
log "Failed to edit item"
flash[:error] = e.message
render_404
end end
def index def index
@@ -67,7 +69,6 @@ class ItemsController < ApplicationController
def new def new
@item = Item.new @item = Item.new
@item.taxable.nil? ? true : @item.taxable
end end
def show def show
@@ -82,7 +83,7 @@ class ItemsController < ApplicationController
if @item.update(item_params) if @item.update(item_params)
redirect_to item_path(@item), notice: l(:notice_successful_update) redirect_to item_path(@item), notice: l(:notice_successful_update)
else else
render :edit render :edit, status: :unprocessable_entity
end end
end end
@@ -90,9 +91,7 @@ class ItemsController < ApplicationController
def find_item def find_item
@item = Item.find(params[:id]) @item = Item.find(params[:id])
rescue => e rescue ActiveRecord::RecordNotFound
log "Failed to find item"
flash[:error] = e.message
render_404 render_404
end end
+5 -3
View File
@@ -14,8 +14,10 @@ class BillLineItemsJob < ActiveJob::Base
# Creates an estimate for a line items attached to an issue, and then marking those entries as billed in Redmine. # Creates an estimate for a line items attached to an issue, and then marking those entries as billed in Redmine.
# This job is typically triggered after an issue is closed. # This job is typically triggered after an issue is closed.
def perform(issue) # Takes an issue id (jobs queued by older versions pass the Issue itself, which still works)
return unless issue.customer def perform(issue_or_id)
issue = issue_or_id.is_a?(Issue) ? issue_or_id : Issue.find_by(id: issue_or_id)
return unless issue&.customer
log "Starting billing for issue ##{issue.id}" log "Starting billing for issue ##{issue.id}"
issue.with_lock do issue.with_lock do
@@ -34,7 +36,7 @@ class BillLineItemsJob < ActiveJob::Base
log "Completed billing of for issue ##{issue.id}" log "Completed billing of for issue ##{issue.id}"
Qbo.update_time_stamp Qbo.update_time_stamp
rescue => e rescue => e
log "Billing failed for issue ##{issue.id} - #{e.message}" log "Billing failed for issue ##{issue&.id || issue_or_id} - #{e.message}"
raise e raise e
end end
+4 -8
View File
@@ -9,8 +9,7 @@
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Item < QboBaseModel class Item < QboBaseModel
belongs_to :issue belongs_to :account, optional: true
belongs_to :account
validates_presence_of :id, :description validates_presence_of :id, :description
validates :unit_price, numericality: { greater_than_or_equal_to: 0 } validates :unit_price, numericality: { greater_than_or_equal_to: 0 }
@@ -20,9 +19,10 @@ class Item < QboBaseModel
after_initialize :set_defaults, if: :new_record? after_initialize :set_defaults, if: :new_record?
before_destroy :make_inactive before_destroy :make_inactive
# Updates Both local & remote DB account ref # Updates Both local & remote DB account ref (a blank or unknown account leaves QBO's ref unchanged)
def account_id=(id) def account_id=(id)
details.income_account_ref = Account.find(id).ref account = Account.find_by(id: id) if id.present?
details.income_account_ref = account.ref if account
super super
end end
@@ -43,10 +43,6 @@ class Item < QboBaseModel
push_to_qbo push_to_qbo
end end
def ref
Quickbooks::Model::BaseReference.new
end
def set_defaults def set_defaults
self.taxable = true if taxable.nil? self.taxable = true if taxable.nil?
end end
+7 -1
View File
@@ -14,7 +14,13 @@ class ItemService < ServiceBase
def build_qbo_remote def build_qbo_remote
log "Building new QBO Item" log "Building new QBO Item"
Quickbooks::Model::Item.new(type: Account.get_default&.ref) # New items default to a non-inventory item in the default income account; the item form then
# sets the type and account the user chose.
item = Quickbooks::Model::Item.new
item.type = Quickbooks::Model::Item::NON_INVENTORY_TYPE
default_account = Account.get_default
item.income_account_ref = default_account.ref if default_account
item
end end
end end
+4 -1
View File
@@ -24,8 +24,11 @@ class ItemSyncService < SyncServiceBase
map_attribute :active, :active? map_attribute :active, :active?
map_attribute :taxable, :taxable? map_attribute :taxable, :taxable?
# Items without an income account (e.g. categories), or whose account hasn't synced yet, get none
# instead of failing the whole sync; the next sync fills it in.
map_attribute :account do |remote| map_attribute :account do |remote|
Account.find remote.income_account_ref.value.to_i account_id = remote.income_account_ref&.value
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 :description, :id, :name, :sku, :type, :unit_price
+4 -4
View File
@@ -27,16 +27,16 @@
<td class="unit_price"><%= number_to_currency(item.unit_price) %></td> <td class="unit_price"><%= number_to_currency(item.unit_price) %></td>
<td class="taxable center"> <td class="taxable center">
<% if item.taxable %> <% if item.taxable %>
<span class="icon icon-ok" style="color: green;"><%=t(:yes)%></span> <span class="icon icon-ok" style="color: green;"><%= l(:general_text_Yes) %></span>
<% else %> <% else %>
<span class="icon icon-not-ok" style="color: #999;"><%=t(:no)%></span> <span class="icon icon-not-ok" style="color: #999;"><%= l(:general_text_No) %></span>
<% end %> <% end %>
</td> </td>
<td class="active center"> <td class="active center">
<% if item.active %> <% if item.active %>
<span class="icon icon-ok" style="color: green;"><%=t(:yes)%></span> <span class="icon icon-ok" style="color: green;"><%= l(:general_text_Yes) %></span>
<% else %> <% else %>
<span class="icon icon-not-ok" style="color: #999;"><%=t(:no)%></span> <span class="icon icon-not-ok" style="color: #999;"><%= l(:general_text_No) %></span>
<% end %> <% end %>
</td> </td>
<td class="buttons"> <td class="buttons">
+13 -8
View File
@@ -1,6 +1,12 @@
<% readonly = @issue.status.is_closed? %> <%
readonly = @issue.status.is_closed?
can_add = User.current.allowed_to?(:add_line_items, nil, global: true)
can_edit = User.current.allowed_to?(:edit_line_items, nil, global: true)
can_delete = User.current.allowed_to?(:delete_line_items, nil, global: true)
permissions = { can_edit: can_edit, can_delete: can_delete }
%>
<% @issue.line_items.build if @issue.line_items.empty? && !readonly %> <% @issue.line_items.build if @issue.line_items.empty? && !readonly && can_add %>
<div class="box tabular" <div class="box tabular"
data-nested-form data-nested-form
@@ -25,7 +31,8 @@
<%= f.fields_for :line_items do |item_form| %> <%= f.fields_for :line_items do |item_form| %>
<%= render "line_items/line_item_fields", <%= render "line_items/line_item_fields",
f: item_form, f: item_form,
readonly: readonly %> readonly: readonly,
**permissions %>
<% end %> <% end %>
</tbody> </tbody>
</table> </table>
@@ -35,24 +42,22 @@
<span id="line-items-grand-total">0.00</span> <span id="line-items-grand-total">0.00</span>
</p> </p>
<% unless readonly %> <% if !readonly && can_add %>
<template data-nested-form-template> <template data-nested-form-template>
<%= f.fields_for :line_items, LineItem.new, child_index: "NEW_RECORD" do |item_form| %> <%= f.fields_for :line_items, LineItem.new, child_index: "NEW_RECORD" do |item_form| %>
<%= render "line_items/line_item_fields", <%= render "line_items/line_item_fields",
f: item_form, f: item_form,
readonly: false %> readonly: false,
**permissions %>
<% end %> <% end %>
</template> </template>
<p> <p>
<% if User.current.allowed_to?(:add_line_items, nil, global: true) %>
<button type="button" <button type="button"
class="icon icon-add" class="icon icon-add"
data-nested-form-add> data-nested-form-add>
<%= l(:button_add) %> <%= l(:button_add) %>
</button> </button>
<% end %>
</p> </p>
<% end %> <% end %>
@@ -1,11 +1,11 @@
<% if @issue.line_items.any? || @issue.descendant_line_items_total > 0%> <% if issue.line_items.any? || issue.descendant_line_items_total > 0%>
<hr/> <hr/>
<div> <div>
<p><strong><%= t :label_line_items %></strong></p> <p><strong><%= t :label_line_items %></strong></p>
<% total = 0 %> <% total = 0 %>
<% if @issue.line_items.any?%> <% if issue.line_items.any?%>
<table class="list line-items-table"> <table class="list line-items-table">
<thead> <thead>
@@ -19,7 +19,7 @@
<tbody> <tbody>
<% @issue.line_items.each do |item| %> <% issue.line_items.each do |item| %>
<% line_total = item.quantity.to_f * item.unit_price.to_f %> <% line_total = item.quantity.to_f * item.unit_price.to_f %>
<% total += line_total %> <% total += line_total %>
@@ -35,7 +35,7 @@
<% end %> <% end %>
<tfoot> <tfoot>
<% if @issue.line_items.any?%> <% if issue.line_items.any?%>
<tr> <tr>
<td colspan="3" style="text-align:right;"><strong><%= t :label_total %></strong></td> <td colspan="3" style="text-align:right;"><strong><%= t :label_total %></strong></td>
<td> <td>
@@ -44,11 +44,11 @@
</tr> </tr>
<% end %> <% end %>
<% if @issue.descendant_line_items_total > 0 %> <% if issue.descendant_line_items_total > 0 %>
<tr> <tr>
<td colspan="3" style="text-align:right;"><strong><%= t :label_running_total %></strong></td> <td colspan="3" style="text-align:right;"><strong><%= t :label_running_total %></strong></td>
<td> <td>
<strong>(<%= number_to_currency(@issue.descendant_line_items_total + total) %>)</strong> <strong>(<%= number_to_currency(issue.descendant_line_items_total + total) %>)</strong>
</td> </td>
</tr> </tr>
<% end %> <% end %>
@@ -1,4 +1,12 @@
<tr class="line-item"> <%
item = f.object
billed = item.persisted? && item.billed?
# Billed lines are on a QuickBooks estimate already; existing lines need "Edit line items" to change
locked = readonly || billed || (item.persisted? && !can_edit)
# Unsaved rows can always be removed; saved ones need "Delete line items"
removable = !readonly && !billed && (item.new_record? || can_delete)
%>
<tr class="line-item<%= ' billed' if billed %>">
<%= f.hidden_field :id %> <%= f.hidden_field :id %>
<%= f.hidden_field :_destroy %> <%= f.hidden_field :_destroy %>
<%= f.hidden_field :item_id, class: "item-id-field" %> <%= f.hidden_field :item_id, class: "item-id-field" %>
@@ -9,17 +17,21 @@
class: "line-item-description", class: "line-item-description",
autocomplete: "off", autocomplete: "off",
no_label: true, no_label: true,
disabled: readonly %> disabled: locked %>
<% if billed %>
<span class="line-item-billed-badge" title="<%= l(:text_line_item_billed) %>"><%= l(:label_billed) %></span>
<% end %>
</td> </td>
<td data-label="<%= t :label_qty %>"> <td data-label="<%= t :label_qty %>">
<%# Fractional quantities are allowed (e.g. 0.5 hours, 2.5 quarts) %>
<%= f.number_field :quantity, <%= f.number_field :quantity,
step: 1, step: "any",
min: 1, min: 0,
value: (f.object.quantity.to_i > 0) ? f.object.quantity : 1, value: (item.quantity.to_f > 0) ? number_with_precision(item.quantity, precision: 4, strip_insignificant_zeros: true) : 1,
class: "qty-field", class: "qty-field",
no_label: true, no_label: true,
disabled: readonly %> disabled: locked %>
</td> </td>
<td data-label="<%= t :label_price %>"> <td data-label="<%= t :label_price %>">
@@ -28,22 +40,22 @@
inputmode: "decimal", inputmode: "decimal",
autocomplete: "off", autocomplete: "off",
no_label: true, no_label: true,
disabled: readonly %> disabled: locked %>
</td> </td>
<td class="line-total" data-label="<%= t :label_total %>"> <td class="line-total" data-label="<%= t :label_total %>">
0.00 0.00
</td> </td>
<% if User.current.allowed_to?(:delete_line_items, nil, global: true) %>
<% unless readonly %> <% unless readonly %>
<td class="actions"> <td class="actions">
<% if removable %>
<button type="button" <button type="button"
class="icon-only icon-del" class="icon-only icon-del"
title="<%= l(:label_remove) %>" title="<%= l(:label_remove) %>"
data-nested-form-remove> data-nested-form-remove>
</button> </button>
<% end %>
</td> </td>
<% end %> <% end %>
<% end %>
</tr> </tr>
+2 -2
View File
@@ -15,7 +15,7 @@
</p> </p>
<p> <p>
<label><strong><%= t(:label_last_sync) %> (QBO)</strong></label> <label><strong><%= t(:label_last_sync) %> (QBO)</strong></label>
<%= Qbo.exists? ? Qbo.last_sync : 'Never synced' %> <%= Qbo.exists? ? Qbo.last_sync : l(:label_never_synced) %>
</p> </p>
<p> <p>
<label><strong><%= t(:label_default_account) %></strong></label> <label><strong><%= t(:label_default_account) %></strong></label>
@@ -24,7 +24,7 @@
</div> </div>
<fieldset class="box"> <fieldset class="box">
<legend>Management & Synchronization</legend> <legend><%= l(:label_management_and_sync) %></legend>
<div style="margin-bottom: 15px;"> <div style="margin-bottom: 15px;">
<%= link_to t(:label_sync_now_items), sync_items_path, class: 'button icon icon-reload' %> <%= link_to t(:label_sync_now_items), sync_items_path, class: 'button icon icon-reload' %>
+10 -10
View File
@@ -61,17 +61,17 @@
}); });
// Custom rendering of autocomplete suggestions // Custom rendering of autocomplete suggestions. Values are set with .text() so item names,
// SKUs and descriptions from QuickBooks can never be interpreted as HTML.
ac.autocomplete("instance")._renderItem = function(ul, item) { ac.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>") let $box = $("<div>").addClass("autocomplete-item");
.append( $("<div>").addClass("item-name").text(item.name || "").appendTo($box);
"<div class='autocomplete-item'>" + if (item.sku) {
"<div class='item-name'>" + item.name + "</div>" + $("<div>").addClass("item-sku").text(item.sku).appendTo($box);
"<div class='item-sku'>" + item.sku + "</div>" + }
"<div class='item-description'>" + item.description + "</div>" + $("<div>").addClass("item-description").text(item.description || "").appendTo($box);
"</div>"
) return $("<li>").append($box).appendTo(ul);
.appendTo(ul);
}; };
}); });
+15
View File
@@ -74,3 +74,18 @@
} }
} }
/* Billed line items are locked: they're already on a QuickBooks estimate */
.line-item.billed input {
background-color: #f6f6f6;
}
.line-item-billed-badge {
display: inline-block;
margin-left: 6px;
padding: 1px 6px;
border-radius: 3px;
font-size: 0.8em;
font-weight: bold;
color: #3e7b3e;
background-color: #e5f2e5;
border: 1px solid #c6e0c6;
}
+6
View File
@@ -42,3 +42,9 @@ en:
notice_added_from: "Added from issue #" notice_added_from: "Added from issue #"
error_default_account_not_selected: "Select an account to make it the default."
label_billed: "Billed"
label_management_and_sync: "Management & Synchronization"
label_never_synced: "Never synced"
notice_default_account_updated: "Default account updated."
text_line_item_billed: "Already added to a QuickBooks estimate, so it can't be changed or removed."
+11 -7
View File
@@ -27,14 +27,18 @@ Redmine::Plugin.register :redmine_qbo_lineitems do
raise 'Please install the redmine_qbo plugin (https://github.com/rickbarrette/redmine_qbo)' raise 'Please install the redmine_qbo plugin (https://github.com/rickbarrette/redmine_qbo)'
end end
# Add safe attributes for core models # Line items can be submitted with an issue only by users who may add, edit or delete them.
Issue.safe_attributes :line_items_attributes # Which changes are applied is checked per line in Issue#line_items_attributes= (see IssuePatch).
Issue.safe_attributes :line_items_attributes, if: lambda { |_issue, user|
%i[add_line_items edit_line_items delete_line_items].any? { |p| user.allowed_to?(p, nil, global: true) }
}
# Global Permissions # Global Permissions. Line items live on issues; these control what users can do with them there.
permission :view_line_items, { line_items: [:index, :show] }, global: true # Managing the QBO item catalog, accounts and syncs is admin-only.
permission :add_line_items, { line_items: [:new, :create] }, global: true permission :view_line_items, {}, global: true
permission :edit_line_items, { line_items: [:edit, :update] }, global: true permission :add_line_items, { items: [:autocomplete] }, global: true
permission :delete_line_items, { line_items: [:destroy] }, global: true permission :edit_line_items, { items: [:autocomplete] }, global: true
permission :delete_line_items, {}, global: true
end end
RedmineQboLineItems.setup RedmineQboLineItems.setup
@@ -1,31 +0,0 @@
#The MIT License (MIT)
#
#Copyright (c) 2017 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module LineItems
module Hooks
class IssuesSaveHookListener < Redmine::Hook::Listener
# Called After Issue Saved
def controller_issues_edit_after_save(context={})
log "Enqueuing billing of item items for issue ##{context[:issue]}"
issue = context[:issue]
BillLineItemsJob.perform_later(issue) if issue.status.is_closed?
end
private
def log(msg)
Rails.logger.info "[IssuesSaveHookListener] #{msg}"
end
end
end
end
+3 -2
View File
@@ -21,8 +21,9 @@ module LineItems
# Called by the QboSyncDispatcher # Called by the QboSyncDispatcher
def qbo_full_sync (context={}) def qbo_full_sync (context={})
log "Adding Item to QBO sync dispatcher" log "Adding Account and Item to QBO sync dispatcher"
return [Item, Account] # Accounts first: items reference their income account
return [Account, Item]
end end
private private
+1 -1
View File
@@ -27,7 +27,7 @@ module LineItems
# Add the line items form to the issue edit page # Add the line items form to the issue edit page
def view_issues_edit_notes_bottom(context = {}) def view_issues_edit_notes_bottom(context = {})
return if context[:issue].closed? return if context[:issue].closed?
return unless User.current.allowed_to?(:edit_line_items, nil, global: true) return unless %i[add_line_items edit_line_items delete_line_items].any? { |p| User.current.allowed_to?(p, nil, global: true) }
context[:controller].send(:render_to_string, { partial: 'line_items/issue_form', locals: { f: context[:form] } }) context[:controller].send(:render_to_string, { partial: 'line_items/issue_form', locals: { f: context[:form] } })
end end
+35 -18
View File
@@ -14,6 +14,18 @@ module LineItems
prepended do prepended do
has_many :line_items, dependent: :destroy has_many :line_items, dependent: :destroy
# Bill unbilled line items to a QBO estimate when the issue is closed, however it was closed
# (issue form, bulk edit, context menu or API)
after_commit :enqueue_line_items_billing, on: :update
def enqueue_line_items_billing
return unless closed?
return unless line_items.where(billed: [false, nil]).exists?
Rails.logger.info "[LineItems::IssuePatch] Enqueuing line item billing for issue ##{id}"
BillLineItemsJob.perform_later(id)
end
accepts_nested_attributes_for :line_items, allow_destroy: true, reject_if: proc { |attrs| attrs['description'].blank? } accepts_nested_attributes_for :line_items, allow_destroy: true, reject_if: proc { |attrs| attrs['description'].blank? }
# Returns line items for immediate children # Returns line items for immediate children
@@ -40,33 +52,38 @@ module LineItems
line_items.sum(:line_total) line_items.sum(:line_total)
end end
# Applies line item changes from the issue form, enforcing permissions on the server (the form
# hides buttons, but a request can be crafted by hand or sent through the API):
# - new lines need "Add line items", changes need "Edit line items", removals need "Delete line items"
# - billed lines are already on a QuickBooks estimate, so they can't be changed or removed
# Lines left out of the submission are untouched (Rails never deletes omitted nested records).
def line_items_attributes=(attrs) def line_items_attributes=(attrs)
attrs = attrs.stringify_keys user = User.current
can_add = user.allowed_to?(:add_line_items, nil, global: true)
can_edit = user.allowed_to?(:edit_line_items, nil, global: true)
can_delete = user.allowed_to?(:delete_line_items, nil, global: true)
billed_ids = line_items.select(&:billed?).map { |li| li.id.to_s }
# IDs submitted in the form attrs = attrs.each_with_index.to_h { |a, i| [i.to_s, a] } if attrs.is_a?(Array)
submitted_ids = attrs.values.map { |a| a['id'] }.compact.map(&:to_s)
# Existing IDs in DB filtered = {}
existing_ids = line_items.pluck(:id).map(&:to_s) attrs.to_h.each do |key, item_attrs|
item_attrs = item_attrs.to_h.stringify_keys
id = item_attrs['id'].to_s.presence
destroy = ActiveModel::Type::Boolean.new.cast(item_attrs['_destroy'])
# Find missing ones (these would be implicitly deleted by Rails) if id
missing_ids = existing_ids - submitted_ids next if billed_ids.include?(id)
next if destroy ? !can_delete : !can_edit
# Re-add missing records so Rails doesn't delete them else
missing_ids.each do |id| # New rows: removed-before-saving or blank rows are dropped
attrs["preserve_#{id}"] = { 'id' => id } next if destroy || !can_add || item_attrs['description'].blank?
end end
# Only allow explicit deletes or valid updates/creates filtered[key.to_s] = item_attrs
filtered = attrs.select do |_, item_attrs|
item_attrs['_destroy'] == '1' ||
item_attrs['id'].present? ||
item_attrs['description'].present?
end end
super(filtered) super(filtered)
rescue => e
logger.error "Error processing line items attributes: #{e.message}"
end end
end end
-1
View File
@@ -16,7 +16,6 @@ module RedmineQboLineItems
Issue.prepend LineItems::Patches::IssuePatch Issue.prepend LineItems::Patches::IssuePatch
# Hooks # Hooks
LineItems::Hooks::IssuesSaveHookListener
LineItems::Hooks::QboHookListener LineItems::Hooks::QboHookListener
LineItems::Hooks::ViewHookListener LineItems::Hooks::ViewHookListener