Compare commits

..

5 Commits

Author SHA1 Message Date
a97d867610 Fixed the UI, now working 2026-03-05 07:53:23 -05:00
021a9ec0c6 Added Issue safe attributes for line items 2026-03-05 07:28:30 -05:00
f056c27bc5 Merge branch 'master' into lineitems 2026-03-05 07:08:30 -05:00
681747e08b Got the UI working 2026-03-04 07:55:35 -05:00
eb6beea5fa Initial line item idea 2026-03-01 15:04:25 -05:00
25 changed files with 490 additions and 524 deletions

304
README.md
View File

@@ -1,21 +1,14 @@
# Redmine QuickBooks Online Plugin # Redmine QuickBooks Online
A plugin for **Redmine** that integrates with **QuickBooks Online (QBO)** to automatically create **Time Activity entries** from billable hours logged on Issues. A plugin for Redmine to connect to QuickBooks Online.
When an Issue associated with a Customer is closed, the plugin generates corresponding Time Activities in QuickBooks based on the Redmine Time Entries recorded for that Issue. The goal of this project is to allow Redmine to connect with QuickBooks Online to create Time Activity Entries for billable hours logged when an Issue is closed.
--- ## Disclaimer
# Disclaimer **Note:** Although the core functionality is complete, this project is still under development and the master branch may be unstable. Tags should be stable and are recommended.
The core functionality is implemented, but the project is **under active development**. ## Compatibility
The `master` branch may contain unstable changes.
For production deployments, **use a tagged release**.
---
# Compatibility
| Plugin Version | Redmine Version | | Plugin Version | Redmine Version |
| :--- | :--- | | :--- | :--- |
@@ -24,244 +17,85 @@ For production deployments, **use a tagged release**.
| Version 1.0.0+ | Redmine 4 | | Version 1.0.0+ | Redmine 4 |
| Version 0.8.1 | Redmine 3 | | Version 0.8.1 | Redmine 3 |
--- ## Features
# Features * **Customer Assignment:** Issues can be assigned to a Customer via a dropdown in the edit Issue form.
* Once a customer is attached to an Issue, you can attach an Estimate to the issue via a dropdown menu.
* **Employee Mapping:** An Employee is assigned to a Redmine User via a dropdown in the User Administration page.
* **Automatic Billing:** If an Issue has been assigned a Customer, the following happens when the Issue is closed:
* A new Time Activity will be billed against the Customer assigned to the issue for each Redmine Time Entry.
* Time Entries will be totalled up by Activity name. This allows billing for different activities without having to create separate Issues.
* The Time Activity names are used to dynamically lookup Items in QuickBooks.
* If there are no Items that match the Activity name, it will be skipped and will not be billed to the Customer.
* Labor Rates are set by the corresponding Item in QuickBooks.
* **Customer Management:** Customers can be created via the New Customer Page.
* Customers can be searched by name or phone number.
* Basic information for the Customer can be viewed/edited via the Customer page.
* **Webhook Support:**
* **Invoices:** Automatically attached to an Issue if a line item contains a hashtag number (e.g., `#123`).
* **Custom Fields:** Invoice Custom Fields are matched to Issue Custom Fields and are automatically updated in QuickBooks. (Useful for extracting Mileage In/Out from the Issue to update the Invoice).
* **Sync:** Customers are automatically updated in the local database.
* **Plugin View Hooks** Allows intergration of other features supported by companion plugins, for example [redmine_qbo_vehicles](https://github.com/rickbarrette/redmine_qbo_vehicles) adds customer vehicle interation
## Issue Billing Integration ## Prerequisites
* Assign a **QuickBooks Customer** to a Redmine Issue. * Sign up to become a developer for Intuit: https://developer.intuit.com/
* Create your own application to obtain your API keys.
* Set up the webhook service to `https://redmine.yourdomain.com/qbo/webhook`
## Installation
1. **Clone the plugin:**
Clone this repo into your plugin folder and checkout a tagged version.
```bash
cd path/to/redmine/plugins
git clone git@github.com:rickbarrette/redmine_qbo.git
cd redmine_qbo
git checkout <tag>
```
2. **Install dependencies:** *Crucial for Redmine 6 / Rails 7 compatibility.*
* Optionally associate a **QuickBooks Estimate** with the Issue. Bash
* Automatically associates a **QuickBooks Invoice** with the Issue.
```
--- bundle install
```
## Automatic Time Activity Creation
When an Issue with an assigned Customer is closed:
* A **Time Activity** is created in QuickBooks for each relevant Redmine Time Entry.
* Time Entries are **grouped by Activity name**. 3. **Migrate your database:**
* Activity names are used to **dynamically match Items in QuickBooks**. Bash
* If no matching Item exists, the activity is **skipped**. ```
bundle exec rake redmine:plugins:migrate RAILS_ENV=production
```
* **Labor rates** are determined by the associated QuickBooks Item. 4. **Restart Redmine:** You must restart your Redmine server instance for the plugin and hooks to load.
5. **Configuration:**
---
## Employee Mapping
Redmine Users can be mapped to **QuickBooks Employees** through the **User Administration** page.
This ensures Time Activities are recorded under the correct employee in QuickBooks.
---
## Customer Management
The plugin provides basic Customer management:
* Create Customers directly from Redmine
* Search Customers by **name or phone number** * Navigate to the plugin configuration page (`Administration > Plugins > Configure`).
* View and edit Customer information * Supply your own OAuth Key & Secret.
* After saving the Key & Secret, click the **Authenticate** link on the configuration page to connect to QBO.
6. **User Mapping:**
* Assign an Employee to each of your users via the **User Administration Page**.
Customers are synchronized with QuickBooks. ## Usage
--- To enable automatic Time Activity entries for an Issue, you simply need to assign a Customer to an Issue via the dropdowns in the issue creation/update form.
## Webhook Support **Note:** After the initial synchronization, this plugin will receive push notifications via Intuit's webhook service.
The plugin listens for **QuickBooks webhook events**. ## Companion Plugin Hooks
* :pdf_left, { issue: issue }
Supported automation: * :pdf_right, { issue: issue }
* :process_invoice_custom_fields, { issue: issue, invoice: invoice }
### Invoice Linking * :show_customer_view_right, {customer: @customer}
Invoices containing an Issue reference (e.g. `#123`) automatically attach to the corresponding Issue.
### Custom Field Synchronization
Invoice custom fields can be mapped to Issue custom fields.
Example use case:
* Mileage In/Out recorded in Redmine
* Automatically synchronized to the QuickBooks invoice.
### Customer Synchronization
Customer records are automatically updated in the local database when changes occur in QuickBooks.
---
## Plugin Hooks
The plugin exposes several hooks for extending functionality through companion plugins.
Example:
`redmine_qbo_vehicles`
Adds support for tracking **customer vehicles** associated with Issues.
Available hooks:
|Type|Hook|Note
|--|--|--|
View Hook|:pdf_left, { issue: issue } | Used to add text to left side of PDF
View Hook|:pdf_right, { issue: issue } | Used to add text to right side of PDF
Hook|process_invoice_custom_fields, { issue: issue, invoice: invoice } | Used to process invoice custom fields
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
---
# Prerequisites
Before installing the plugin:
1. Create a QuickBooks developer account:
[https://developer.intuit.com/](https://developer.intuit.com/)
2. Create an **Intuit application** to obtain:
* Client ID
* Client Secret
3. Configure the QuickBooks webhook endpoint:
https://redmine.yourdomain.com/qbo/webhook
---
# Installation
## 1\. Clone the Plugin
Install the plugin into your Redmine plugins directory.
```bash
cd /path/to/redmine/plugins
git clone https://github.com/rickbarrette/redmine_qbo.git
cd redmine_qbo
git checkout <tag>
```
Use a **tagged release** for stability.
---
## 2\. Install Dependencies
```bash
bundle install
```
Required for **Redmine 6 / Rails 7 compatibility**.
---
## 3\. Run Database Migrations
```bash
bundle exec rake redmine:plugins:migrate RAILS_ENV=production
```
---
## 4\. Restart Redmine
Restart your Redmine server so the plugin and hooks are loaded.
---
# Configuration
1. Navigate to:
Administration → Plugins → Configure
2. Enter your **QuickBooks Client ID and Client Secret**.
3. Save the configuration.
4. Click **Authenticate** to complete the OAuth connection with QuickBooks Online.
Once authentication succeeds, the plugin performs an **initial synchronization**.
---
# User Mapping
Each Redmine user must be mapped to a QuickBooks Employee.
Navigate to:
Administration → Users
Then assign the corresponding **QuickBooks Employee** to each user.
---
# Usage
To enable automatic billing:
1. Assign a **Customer** to an Issue.
2. Log billable time using **Redmine Time Entries**.
3. Close the Issue.
When the Issue is closed, the plugin automatically generates the corresponding **Time Activity entries in QuickBooks Online**.
After the initial synchronization, the plugin receives updates through **Intuit webhooks**.
---
# Troubleshooting
### Time Activities Not Created
Verify that:
* The Issue has a **Customer assigned**
* Time Entries exist for the Issue
* Activity names match **QuickBooks Item names**
---
### Webhooks Not Triggering
Ensure the QuickBooks webhook endpoint is reachable:
https://redmine.yourdomain.com/qbo/webhook
Also verify webhook configuration in the Intuit developer dashboard.
## License ## License

View File

View File

@@ -17,8 +17,10 @@ class BillIssueTimeJob < ActiveJob::Base
issue = Issue.find(issue_id) issue = Issue.find(issue_id)
log "Starting billing for issue ##{issue.id}" log "Starting billing for issue ##{issue.id}"
issue.with_lock do issue.with_lock do
unbilled_entries = issue.time_entries.where(billed: [false, nil]).lock unbilled_entries = issue.time_entries.where(billed: [false, nil]).lock
return if unbilled_entries.blank? return if unbilled_entries.blank?
totals = aggregate_hours(unbilled_entries) totals = aggregate_hours(unbilled_entries)
@@ -26,6 +28,8 @@ class BillIssueTimeJob < ActiveJob::Base
log "Aggregated hours for billing: #{totals.inspect}" log "Aggregated hours for billing: #{totals.inspect}"
qbo = QboConnectionService.current! qbo = QboConnectionService.current!
raise "No QBO configuration found" unless qbo
qbo.perform_authenticated_request do |access_token| qbo.perform_authenticated_request do |access_token|
create_time_activities(issue, totals, access_token, qbo) create_time_activities(issue, totals, access_token, qbo)
end end

View File

@@ -19,23 +19,6 @@ class QboSyncDispatcher
# Dispatches all synchronization jobs to perform a full sync of QuickBooks entities with the local database. Each job is enqueued with the `full_sync` flag set to true. # Dispatches all synchronization jobs to perform a full sync of QuickBooks entities with the local database. Each job is enqueued with the `full_sync` flag set to true.
def self.full_sync! def self.full_sync!
SYNC_JOBS.each { |job| job.perform_later(full_sync: true) }
jobs = SYNC_JOBS.dup
# Allow other plugins to add addtional sync jobs via Hooks
Redmine::Hook.call_hook( :qbo_full_sync ).each do |context|
next unless context
jobs.push context
log "Added additionals QBO Sync Job for #{contex.to_s}"
end
jobs.each { |job| job.perform_later(full_sync: true) }
end end
private
def self.log(msg)
Rails.logger.info "[QboSyncDispatcher] #{msg}"
end
end end

View File

@@ -43,14 +43,7 @@ class WebhookProcessJob < ActiveJob::Base
name = entity['name'] name = entity['name']
id = entity['id']&.to_i id = entity['id']&.to_i
entities = ALLOWED_ENTITIES.dup return unless ALLOWED_ENTITIES.include?(name)
# Allow other plugins to add addtional qbo entities via Hooks
Redmine::Hook.call_hook( :qbo_additional_entities ).each do |context|
next unless context
entities.push context
log "Added additional QBO entities: #{context}"
end
return unless entities.include?(name)
model = name.safe_constantize model = name.safe_constantize
return unless model return unless model

View File

@@ -8,18 +8,21 @@
# #
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Customer < QboBaseModel class Customer < ActiveRecord::Base
include Redmine::Acts::Searchable include Redmine::Acts::Searchable
include Redmine::Acts::Event include Redmine::Acts::Event
include Redmine::I18n
has_many :issues has_many :issues
has_many :invoices has_many :invoices
has_many :estimates has_many :estimates
validates_presence_of :name
validates_presence_of :id, :name
before_validation :normalize_phone_numbers before_validation :normalize_phone_numbers
self.primary_key = :id
self.primary_key = :id
acts_as_searchable columns: %w[name phone_number mobile_phone_number ], acts_as_searchable columns: %w[name phone_number mobile_phone_number ],
scope: ->(_context) { left_joins(:project) }, scope: ->(_context) { left_joins(:project) },
date_column: :updated_at date_column: :updated_at
@@ -30,6 +33,24 @@ class Customer < QboBaseModel
:description => Proc.new {|o| "#{I18n.t :label_primary_phone}: #{o.phone_number} #{I18n.t:label_mobile_phone}: #{o.mobile_phone_number}"}, :description => Proc.new {|o| "#{I18n.t :label_primary_phone}: #{o.phone_number} #{I18n.t:label_mobile_phone}: #{o.mobile_phone_number}"},
:datetime => Proc.new {|o| o.updated_at || o.created_at} :datetime => Proc.new {|o| o.updated_at || o.created_at}
# Returns the details of the customer. If the details have already been fetched, it returns the cached version. Otherwise, it fetches the details from QuickBooks Online and caches them for future use. This method is used to access the customer's information in a way that minimizes unnecessary API calls to QBO, improving performance and reducing latency.
def details
return Quickbooks::Model::Customer.new unless id.present?
@details ||= begin
xml = Rails.cache.fetch(details_cache_key, expires_in: 10.minutes) do
fetch_details.to_xml_ns
end
Quickbooks::Model::Customer.from_xml(xml)
end
end
# Generates a unique cache key for storing this customer's QBO details.
def details_cache_key
"customer:#{id}:qbo_details:#{updated_at.to_i}"
end
# Returns the customer's email address # Returns the customer's email address
def email def email
details details
@@ -42,12 +63,30 @@ class Customer < QboBaseModel
@details.email_address = s @details.email_address = s
end end
# Returns the last sync time formatted for display. If no sync has occurred, returns a default message.
def self.last_sync
return I18n.t(:label_qbo_never_synced) unless maximum(:updated_at)
format_time(maximum(:updated_at))
end
# Customers are not bound by a project # Customers are not bound by a project
# but we need to implement this method for the Redmine::Acts::Searchable interface # but we need to implement this method for the Redmine::Acts::Searchable interface
def project def project
nil nil
end end
# Magic Method
# Maps Get/Set methods to QBO customer object
def method_missing(method_name, *args, &block)
if Quickbooks::Model::Customer.method_defined?(method_name)
details
@details.public_send(method_name, *args, &block)
else
super
end
end
# returns the customer's mobile phone # returns the customer's mobile phone
def mobile_phone def mobile_phone
details details
@@ -95,6 +134,11 @@ class Customer < QboBaseModel
@details.primary_phone = pn @details.primary_phone = pn
end end
# Repsonds to missing methods by delegating to the QBO customer details object if the method is defined there. This allows for dynamic access to any attributes or methods of the QBO customer without having to explicitly define them in the Customer model, providing flexibility and reducing boilerplate code.
def respond_to_missing?(method_name, include_private = false)
Quickbooks::Model::Customer.method_defined?(method_name) || super
end
# Seach for customers by name or phone number # Seach for customers by name or phone number
def self.search(search) def self.search(search)
#return none if search.blank? #return none if search.blank?
@@ -116,10 +160,47 @@ class Customer < QboBaseModel
ids.index_with { |id| id } ids.index_with { |id| id }
end end
# performs a sync operation for all customers
def self.sync
CustomerSyncJob.perform_later(full_sync: false)
end
# performs a sync operation for a specific customer
def self.sync_by_id(id)
CustomerSyncJob.perform_later(id: id)
end
# returns a human readable string # returns a human readable string
def to_s def to_s
last4 = phone_number&.last(4) last4 = phone_number&.last(4)
last4.present? ? "#{name} - #{last4}" : name.to_s last4.present? ? "#{name} - #{last4}" : name.to_s
end end
# Push the updates
def save_with_push
log "Starting push for customer ##{self.id}..."
qbo = QboConnectionService.current!
CustomerService.new(qbo: qbo, customer: self).push()
Rails.cache.delete(details_cache_key)
save_without_push
end
alias_method :save_without_push, :save
alias_method :save, :save_with_push
end private
# Fetches the customer's details from QuickBooks Online. If the customer has an ID, it makes an authenticated request to QBO to retrieve the customer's information. If the customer does not have an ID or if there is an error during the fetch, it returns a new instance of Quickbooks::Model::Customer with default values. This method is used to ensure that the customer object has the most up-to-date information from QBO when needed.
def fetch_details
return Quickbooks::Model::Customer.new unless id.present?
log "Fetching details for customer ##{id} from QBO..."
qbo = QboConnectionService.current!
CustomerService.new(qbo: qbo, customer: self).pull()
end
# Log messages with the entity type for better traceability
def log(msg)
Rails.logger.info "[Customer] #{msg}"
end
end

View File

@@ -8,10 +8,29 @@
# #
#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 Employee < QboBaseModel class Employee < ActiveRecord::Base
include Redmine::I18n
has_many :users has_many :users
validates_presence_of :id, :name validates_presence_of :id, :name
self.primary_key = :id self.primary_key = :id
# Returns the last sync time formatted for display. If no sync has occurred, returns a default message.
def self.last_sync
return I18n.t(:label_qbo_never_synced) unless maximum(:updated_at)
format_time(maximum(:updated_at))
end
end # Sync all employees, typically triggered by a scheduled task or manual sync request
def self.sync
EmployeeSyncJob.perform_later(full_sync: true)
end
# Sync a single employee by ID, typically triggered by a webhook notification or manual sync request
def self.sync_by_id(id)
EmployeeSyncJob.perform_later(id: id)
end
end

View File

@@ -8,21 +8,45 @@
# #
#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 Estimate < QboBaseModel class Estimate < ActiveRecord::Base
include Redmine::I18n
has_and_belongs_to_many :issues has_and_belongs_to_many :issues
belongs_to :customer belongs_to :customer
validates_presence_of :doc_number, :id validates_presence_of :doc_number, :id
self.primary_key = :id self.primary_key = :id
# Returns the last sync time formatted for display. If no sync has occurred, returns a default message.
def self.last_sync
return I18n.t(:label_qbo_never_synced) unless maximum(:updated_at)
format_time(maximum(:updated_at))
end
# returns a human readable string # returns a human readable string
def to_s def to_s
return self[:doc_number] return self[:doc_number]
end end
# sync all estimates
def self.sync
EstimateSyncJob.perform_later(full_sync: false)
end
# sync only one estimate
def self.sync_by_id(id)
EstimateSyncJob.perform_later(id: id)
end
# sync only one estimate # sync only one estimate
def self.sync_by_doc_number(number) def self.sync_by_doc_number(number)
EstimateSyncJob.perform_later(doc_number: number) EstimateSyncJob.perform_later(doc_number: number)
end end
private
def log(msg)
Rails.logger.info "[Estimate] #{msg}"
end
end end

View File

@@ -8,17 +8,37 @@
# #
#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 Invoice < QboBaseModel class Invoice < ActiveRecord::Base
include Redmine::I18n
has_and_belongs_to_many :issues has_and_belongs_to_many :issues
belongs_to :customer belongs_to :customer
validates :id, presence: true, uniqueness: true validates :id, presence: true, uniqueness: true
validates :doc_number, :txn_date, presence: true validates :doc_number, :txn_date, presence: true
self.primary_key = :id self.primary_key = :id
# Returns the last sync time formatted for display. If no sync has occurred, returns a default message.
def self.last_sync
return I18n.t(:label_qbo_never_synced) unless maximum(:updated_at)
format_time(maximum(:updated_at))
end
# Return the invoice's document number as its string representation # Return the invoice's document number as its string representation
def to_s def to_s
doc_number doc_number
end end
# Sync all invoices from QuickBooks, typically triggered by a scheduled task or manual sync request
def self.sync
InvoiceSyncJob.perform_later(full_sync: true)
end
# Sync a single invoice by ID, typically triggered by a webhook notification or manual sync request
def self.sync_by_id(id)
InvoiceSyncJob.perform_later(id: id)
end
end end

7
app/models/line_item.rb Normal file
View File

@@ -0,0 +1,7 @@
class LineItem < ApplicationRecord
belongs_to :issue
validates :description, presence: true
validates :quantity, numericality: { greater_than: 0 }
validates :unit_price, numericality: { greater_than_or_equal_to: 0 }
end

View File

@@ -1,103 +0,0 @@
#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.
class QboBaseModel < ActiveRecord::Base
include Redmine::I18n
self.abstract_class = true
validates_presence_of :id
# Returns the details of the entity.
# If the details have already been fetched, it returns the cached version.
# Otherwise, it fetches the details from QuickBooks Online and caches them for future use.
# This method is used to access the entity's information in a way that minimizes unnecessary API calls to QBO, improving performance and reducing latency.
def details
@details ||= begin
xml = Rails.cache.fetch(details_cache_key, expires_in: 10.minutes) do
fetch_details.to_xml_ns
end
model_class = "Quickbooks::Model::#{model_name.name}".constantize
model_class.from_xml(xml)
end
end
# Generates a unique cache key for storing this customer's QBO details.
def details_cache_key
"#{model_name.name}:#{id}:qbo_details:#{updated_at.to_i}"
end
# Returns the last sync time formatted for display.
# If no sync has occurred, returns a default message.
def self.last_sync
return I18n.t(:label_qbo_never_synced) unless maximum(:updated_at)
format_time(maximum(:updated_at))
end
# Magic Method
# Maps Get/Set methods to QBO entity object
def method_missing(method_name, *args, &block)
model_class = "Quickbooks::Model::#{model_name.name}".constantize
if model_class.method_defined?(method_name)
details
@details.public_send(method_name, *args, &block)
else
super
end
end
# Repsonds to missing methods by delegating to the QBO customer details object if the method is defined there.
# This allows for dynamic access to any attributes or methods of the QBO customer without having to explicitly define them in the Subclass model, providing flexibility and reducing boilerplate code.
def respond_to_missing?(method_name, include_private = false)
model_class = "Quickbooks::Model::#{model_name.name}".constantize
model_class.method_defined?(method_name) || super
end
# Sync all entities, typically triggered by a scheduled task or manual sync request
def self.sync
job = "#{model_name.name}SyncJob".constantize
job.perform_later(full_sync: true)
end
# Sync a single entity by ID, typically triggered by a webhook notification or manual sync request
def self.sync_by_id(id)
job = "#{model_name.name}SyncJob".constantize
job.perform_later(id: id)
end
# Push the updates
def save_with_push
log "Starting push for #{model_name.name} ##{self.id}..."
qbo = QboConnectionService.current!
service = "#{model_name.name}Service".constantize
service.new(qbo: qbo, remote: self).push()
Rails.cache.delete(details_cache_key)
save_without_push
end
alias_method :save_without_push, :save
alias_method :save, :save_with_push
private
def log(msg)
Rails.logger.info "[#{model_name.name}] #{msg}"
end
# Fetches the entity's details from QuickBooks Online.
def fetch_details
log "Fetching details for #{model_name.name} ##{id} from QBO..."
qbo = QboConnectionService.current!
service_class = "#{model_name.name}Service".constantize
service_class.new(qbo: qbo, remote: self).pull()
end
end

View File

@@ -8,13 +8,55 @@
# #
#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 CustomerService < ServiceBase class CustomerService
private # Initializes the service with a QBO client and an optional customer record. The QBO client is used to communicate with QuickBooks Online, while the customer record contains the data that needs to be pushed to QBO. If no customer is provided, the service will not perform any operations.
def initialize(qbo:, customer: nil)
raise "No QBO configuration found" unless qbo
raise "Customer record is required for push operation" unless customer
@qbo = qbo
@customer = customer
end
def build_qbo_remote # Pulls the customer data from QuickBooks Online.
log "Building new QBO Customer" def pull
return Quickbooks::Model::Customer.new unless @customer.present?
log "Fetching details for customer ##{@customer.id} from QBO..."
qbo = QboConnectionService.current!
qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Customer.new(
company_id: qbo.realm_id,
access_token: access_token
)
service.fetch_by_id(@customer.id)
end
rescue => e
log "Fetch failed for #{@customer.id}: #{e.message}"
Quickbooks::Model::Customer.new Quickbooks::Model::Customer.new
end end
# Pushes the customer data to QuickBooks Online. This method handles the communication with QBO, including authentication and error handling. It uses the QBO client to send the customer data and logs the process for monitoring and debugging purposes. If the push is successful, it returns the customer record; otherwise, it logs the error and returns false.
def push
log "Pushing customer ##{@customer.id} to QBO..."
customer = @qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Customer.new(
company_id: @qbo.realm_id,
access_token: access_token
)
service.update(@customer.details)
end
@customer.id = customer.id unless @customer.persisted?
log "Push for customer ##{@customer.id} completed."
return @customer
end
private
# Log messages with the entity type for better traceability
def log(msg)
Rails.logger.info "[CustomerService] #{msg}"
end
end end

View File

@@ -1,82 +0,0 @@
#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.
class ServiceBase
# Subclasses should Initializes the service with a QBO client and an optional remote record.
# The QBO client is used to communicate with QuickBooks Online, while the local record contains the data that needs to be pushed to QBO.
# If no remote is provided, the service will not perform any operations.
def initialize(qbo:, remote: nil)
raise "No QBO configuration found" unless qbo
raise "#{@entity} record is required for push operation" unless remote
@qbo = qbo
@entity = remote.class.name
@remote = remote
end
# # Subclasses must implement this to specify which local model they sync (e.g. Customer, Invoice)
# def self.model_class
# raise NotImplementedError
# end
# Subclasses must implement this to build a new QBO entity if a remote is not found
def build_qbo_remote
raise NotImplementedError
end
# Pulls the Item data from QuickBooks Online.
def pull
return build_qbo_remote unless @remote.present?
return build_qbo_remote unless @remote.id
log "Fetching details for #{@entity} ##{@remote.id} from QBO..."
qbo = QboConnectionService.current!
qbo.perform_authenticated_request do |access_token|
service_class = "Quickbooks::Service::#{@entity}".constantize
service = service_class.new(
company_id: qbo.realm_id,
access_token: access_token
)
service.fetch_by_id(@remote.id)
end
rescue => e
log "Fetch failed for #{@remote.id}: #{e.message}"
build_qbo_remote
end
# Pushes the Item data to QuickBooks Online. This method handles the communication with QBO, including authentication and error handling. It uses the QBO client to send the remote data and logs the process for monitoring and debugging purposes. If the push is successful, it returns the remote record; otherwise, it logs the error and returns false.
def push
log "Pushing #{@entity} ##{@remote.id} to QBO..."
remote = @qbo.perform_authenticated_request do |access_token|
service_class = "Quickbooks::Service::#{@entity}".constantize
service = service_class.new(
company_id: @qbo.realm_id,
access_token: access_token
)
if @remote.id.present?
service.update(@remote.details)
else
service.create(@remote.details)
end
end
@remote.id = remote.id unless @remote.persisted?
log "Push for remote ##{@remote.id} completed."
return @remote
end
private
# Log messages with the entity type for better traceability
def log(msg)
Rails.logger.info "[#{@entity}Service] #{msg}"
end
end

View File

@@ -16,12 +16,6 @@ class SyncServiceBase
raise "No QBO configuration found" unless qbo raise "No QBO configuration found" unless qbo
@qbo = qbo @qbo = qbo
@entity = self.class.model_class @entity = self.class.model_class
@page_size = self.class.page_size
end
# Subclasses can implement this to overide the default page size
def self.page_size
@page_size = PAGE_SIZE
end end
# Subclasses must implement this to specify which local model they sync (e.g. Customer, Invoice) # Subclasses must implement this to specify which local model they sync (e.g. Customer, Invoice)
@@ -31,35 +25,34 @@ class SyncServiceBase
# Sync all entities, or only those updated since the last sync # Sync all entities, or only those updated since the last sync
def sync(full_sync: false) def sync(full_sync: false)
log "Starting #{full_sync ? 'full' : 'incremental'} #{@entity.name} sync with page size of: #{@page_size}" log "Starting #{full_sync ? 'full' : 'incremental'} #{@entity.name} sync"
@qbo.perform_authenticated_request do |access_token| @qbo.perform_authenticated_request do |access_token|
service_class = "Quickbooks::Service::#{@entity.name}".constantize service_class = "Quickbooks::Service::#{@entity.name}".constantize
service = service_class.new(company_id: @qbo.realm_id, access_token: access_token) service = service_class.new(company_id: @qbo.realm_id, access_token: access_token)
page = 1
loop do
collection = fetch_page(service, page, full_sync)
entries = Array(collection&.entries)
break if entries.empty?
query = build_query(full_sync) entries.each { |remote| persist(remote) }
service.query_in_batches(query, per_page: @page_size) do |batch| break if entries.size < PAGE_SIZE
entries = Array(batch) page += 1
log "Processing batch of #{entries.size} #{@entity.name}"
entries.each do |remote|
persist(remote)
end
end end
end end
log "#{@entity.name} sync complete" log "#{@entity.name} sync complete"
end end
# Sync a single entity by its QBO ID (webhook usage) # Sync a single entity by its QBO ID, used for webhook updates
def sync_by_id(id) def sync_by_id(id)
log "Syncing #{@entity.name} with ID #{id}" log "Syncing #{@entity.name} with ID #{id}"
@qbo.perform_authenticated_request do |access_token| @qbo.perform_authenticated_request do |access_token|
service_class = "Quickbooks::Service::#{@entity.name}".constantize service_class = "Quickbooks::Service::#{@entity.name}".constantize
service = service_class.new(company_id: @qbo.realm_id, access_token: access_token) service = service_class.new(company_id: @qbo.realm_id, access_token: access_token)
remote = service.fetch_by_id(id) remote = service.fetch_by_id(id)
persist(remote) persist(remote)
end end
@@ -67,21 +60,6 @@ class SyncServiceBase
private private
# Builds a QBO query for retrieving entities
def build_query(full_sync)
if full_sync
"SELECT * FROM #{@entity.name} ORDER BY Id"
else
last_update = @entity.maximum(:updated_at) || 1.year.ago
<<~SQL.squish
SELECT * FROM #{@entity.name}
WHERE MetaData.LastUpdatedTime > '#{last_update.utc.iso8601}'
ORDER BY MetaData.LastUpdatedTime
SQL
end
end
def attach_documents(local, remote) def attach_documents(local, remote)
# Override in subclasses if the entity has attachments (e.g. Invoice) # Override in subclasses if the entity has attachments (e.g. Invoice)
end end
@@ -96,6 +74,24 @@ class SyncServiceBase
Rails.logger.info "[#{@entity.name}SyncService] #{msg}" Rails.logger.info "[#{@entity.name}SyncService] #{msg}"
end end
# Fetch a page of entities, either all or only those updated since the last sync
def fetch_page(service, page, full_sync)
log "Fetching page #{page} of #{@entity.name} from QBO (#{full_sync ? 'full' : 'incremental'} sync)"
start_position = (page - 1) * PAGE_SIZE + 1
if full_sync
service.query("SELECT * FROM #{@entity.name} STARTPOSITION #{start_position} MAXRESULTS #{PAGE_SIZE}")
else
last_update = @entity.maximum(:updated_at) || 1.year.ago
service.query(<<~SQL.squish)
SELECT * FROM #{@entity.name}
WHERE MetaData.LastUpdatedTime > '#{last_update.utc.iso8601}'
STARTPOSITION #{start_position}
MAXRESULTS #{PAGE_SIZE}
SQL
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
def persist(remote) def persist(remote)
local = @entity.find_or_initialize_by(id: remote.id) local = @entity.find_or_initialize_by(id: remote.id)
@@ -108,20 +104,24 @@ class SyncServiceBase
return return
end end
# Map remote attributes to local model fields, this should be implemented in subclasses
process_attributes(local, remote) process_attributes(local, remote)
if local.changed? if local.changed?
local.save! local.save!
log "Updated #{@entity.name} #{remote.id}" log "Updated #{@entity.name} #{remote.id}"
attach_documents(local, remote)
# Handle attaching documents if applicable to invoices
attach_documents(local, remote)
end end
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
# This method should be implemented in subclasses to map remote attributes to local model # This method should be implemented in subclasses to map remote attributes to local model
def process_attributes(local, remote) def process_attributes(local, remote)
raise NotImplementedError, "Subclasses must implement process_attributes" raise NotImplementedError, "Subclasses must implement process_attributes"
end end
end end

View File

@@ -7,3 +7,6 @@
<p> <p>
<%= select_estimate %> <%= select_estimate %>
</p> </p>
<%= render "line_items/issue_form", f: f %>

View File

@@ -0,0 +1,34 @@
<% @issue.line_items.build if @issue.line_items.empty? %>
<div class="box tabular" data-nested-form data-wrapper-selector=".line-item">
<p><strong>Line Items</strong></p>
<table class="list line-items-table">
<thead>
<tr>
<th>Description</th>
<th style="width:120px;">Quantity</th>
<th style="width:150px;">Unit Price</th>
<th style="width:80px;"></th>
</tr>
</thead>
<tbody data-nested-form-container>
<%= f.fields_for :line_items do |item_form| %>
<%= render "line_items/line_item_fields", f: item_form %>
<% end %>
</tbody>
</table>
<template data-nested-form-template>
<%= f.fields_for :line_items, LineItem.new, child_index: "NEW_RECORD" do |item_form| %>
<%= render "line_items/line_item_fields", f: item_form %>
<% end %>
</template>
<p>
<button type="button" class="icon icon-add" data-nested-form-add>
Add Line Item
</button>
</p>
</div>

View File

@@ -0,0 +1,34 @@
<tr class="line-item">
<%= f.hidden_field :id %>
<%= f.hidden_field :_destroy %>
<td>
<%= f.text_field :description,
size: 50,
placeholder: "Description",
:no_label => true %>
</td>
<td>
<%= f.number_field :quantity,
step: 1,
min: 1,
style: "width:90px;",
:no_label => true %>
</td>
<td>
<%= f.number_field :unit_price,
step: 0.01,
style: "width:120px;",
:no_label => true %>
</td>
<td style="text-align:center;">
<button type="button"
class="icon-only icon-del"
title="Remove"
data-nested-form-remove>
</button>
</td>
</tr>

View File

@@ -0,0 +1,53 @@
(function () {
function initNestedForms() {
document.querySelectorAll("[data-nested-form]").forEach(function (wrapper) {
if (wrapper.dataset.initialized === "true") return;
wrapper.dataset.initialized = "true";
const container = wrapper.querySelector("[data-nested-form-container]");
const template = wrapper.querySelector("[data-nested-form-template]");
if (!container || !template) return;
wrapper.addEventListener("click", function (event) {
const addButton = event.target.closest("[data-nested-form-add]");
const removeButton = event.target.closest("[data-nested-form-remove]");
// ADD
if (addButton) {
event.preventDefault();
const content = template.innerHTML.replace(
/NEW_RECORD/g,
Date.now().toString()
);
container.insertAdjacentHTML("beforeend", content);
}
// REMOVE
if (removeButton) {
event.preventDefault();
const lineItem = removeButton.closest(wrapper.dataset.wrapperSelector);
if (!lineItem) return;
const destroyField = lineItem.querySelector("input[name*='_destroy']");
if (destroyField) {
destroyField.value = "1";
lineItem.style.display = "none";
} else {
lineItem.remove();
}
}
});
});
}
// Works for full load
document.addEventListener("DOMContentLoaded", initNestedForms);
// Works for Turbo navigation
document.addEventListener("turbo:load", initNestedForms);
})();

View File

@@ -1,26 +0,0 @@
#The License
#
#Copyright (c) 2016 - 2026 Rick Barrette - All Rights Reserved
#
#Unauthorized copying of this software and associated documentation files (the "Software"), via any medium is strictly prohibited.
#
#Proprietary and confidential
#
#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.
class CreateLineItems < ActiveRecord::Migration[5.1]
def change
create_table :line_items do |t|
t.integer :item_id
t.float :amount
t.string :description
t.float :unit_price
t.float :quantity
t.boolean :billed
end
add_reference :line_items, :issues, index: true
end
end

View File

@@ -12,6 +12,5 @@ class RemoveQboItems < ActiveRecord::Migration[5.1]
def change def change
drop_table :qbo_items drop_table :qbo_items
drop_table :qbo_purchases drop_table :qbo_purchases
drop_table :line_items
end end
end end

View File

@@ -0,0 +1,42 @@
#The MIT License (MIT)
#
#Copyright (c) 2016 - 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class CreateLineItems < ActiveRecord::Migration[7.0]
def change
create_table :line_items do |t|
t.integer :issue_id, null: false
t.text :description, null: false
t.decimal :quantity,
precision: 15,
scale: 4,
null: false,
default: 0
t.decimal :unit_price,
precision: 15,
scale: 4,
null: false,
default: 0
t.decimal :line_total,
precision: 15,
scale: 4,
null: false,
default: 0
t.timestamps
end
add_index :line_items, :issue_id
add_foreign_key :line_items, :issues
end
end

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 to create Time Activity Entries for billable hours logged when an Issue is closed' description 'A pluging for Redmine to connect with QuickBooks Online to create Time Activity Entries for billable hours logged when an Issue is closed'
version '2026.3.6' version '2026.3.1'
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'
@@ -25,6 +25,7 @@ Redmine::Plugin.register :redmine_qbo do
Issue.safe_attributes :estimate_id Issue.safe_attributes :estimate_id
Issue.safe_attributes :invoice_id Issue.safe_attributes :invoice_id
User.safe_attributes :employee_id User.safe_attributes :employee_id
Issue.safe_attributes :line_items_attributes
TimeEntry.safe_attributes :billed TimeEntry.safe_attributes :billed
# set per_page globally # set per_page globally

View File

@@ -62,7 +62,8 @@ module RedmineQbo
locals: { locals: {
search_customer: search_customer, search_customer: search_customer,
customer_id: customer_id, customer_id: customer_id,
select_estimate: select_estimate select_estimate: select_estimate,
f: context[:form]
} }
} }
) )

View File

@@ -18,7 +18,8 @@ module RedmineQbo
safe_join([ safe_join([
javascript_include_tag( 'application.js', plugin: :redmine_qbo), javascript_include_tag( 'application.js', plugin: :redmine_qbo),
javascript_include_tag( 'autocomplete-rails.js', plugin: :redmine_qbo), javascript_include_tag( 'autocomplete-rails.js', plugin: :redmine_qbo),
javascript_include_tag( 'checkbox_controller.js', plugin: :redmine_qbo) javascript_include_tag( 'checkbox_controller.js', plugin: :redmine_qbo),
javascript_include_tag( 'nested_form_controller.js', plugin: :redmine_qbo)
]) ])
end end

View File

@@ -23,6 +23,8 @@ module RedmineQbo
belongs_to :customer_token, primary_key: :id belongs_to :customer_token, primary_key: :id
belongs_to :estimate, primary_key: :id belongs_to :estimate, primary_key: :id
has_and_belongs_to_many :invoices has_and_belongs_to_many :invoices
has_many :line_items, dependent: :destroy
accepts_nested_attributes_for :line_items, allow_destroy: true
before_save :titlize_subject before_save :titlize_subject
after_commit :enqueue_billing, on: :update after_commit :enqueue_billing, on: :update