From 4f8e5d9b2ce099ca16613abe232740bdca053553 Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Wed, 11 Mar 2026 23:39:24 -0400 Subject: [PATCH] implemented some basic CRUD for QBO Items --- app/controllers/items_controller.rb | 49 +++++++++++++++ app/models/item.rb | 77 +++++++++++++++++++++++- app/services/item_service.rb | 93 +++++++++++++++++++++++++++++ app/views/items/_form.html.erb | 43 +++++++++++++ app/views/items/edit.html.erb | 5 ++ app/views/items/index.html.erb | 37 ++++++++++++ app/views/items/new.html.erb | 5 ++ app/views/items/show.html.erb | 26 ++++++++ config/routes.rb | 8 ++- 9 files changed, 340 insertions(+), 3 deletions(-) create mode 100644 app/services/item_service.rb create mode 100644 app/views/items/_form.html.erb create mode 100644 app/views/items/edit.html.erb create mode 100644 app/views/items/index.html.erb create mode 100644 app/views/items/new.html.erb create mode 100644 app/views/items/show.html.erb diff --git a/app/controllers/items_controller.rb b/app/controllers/items_controller.rb index 82548bd..09b8dd0 100644 --- a/app/controllers/items_controller.rb +++ b/app/controllers/items_controller.rb @@ -10,6 +10,7 @@ class ItemsController < ApplicationController before_action :require_login + before_action :find_item, only: [:show, :edit, :update, :destroy] def autocomplete term = ActiveRecord::Base.sanitize_sql_like(params[:q].to_s) @@ -18,13 +19,61 @@ class ItemsController < ApplicationController .where(active: true) .order(:description) .limit(20) + render json: items.map { |i| { id: i.id, name: i.name, sku: i.sku, description: i.description, price: i.unit_price } } end + def create + @item = Item.new(item_params) + + if @item.save + redirect_to item_path(@item), notice: l(:notice_successful_create) + else + render :new + end + end + + def destroy + @item.destroy + redirect_to items_path, notice: l(:notice_successful_delete) + end + + def edit + end + + def index + @items = Item.order(:name) + end + + def new + @item = Item.new + end + + def show + end + def sync Item.sync redirect_to :home, flash: { notice: I18n.t(:label_syncing) } end + + def update + if @item.update(item_params) + redirect_to item_path(@item), notice: l(:notice_successful_update) + else + render :edit + end + end + + private + + def find_item + @item = Item.find(params[:id]) + end + + def item_params + params.require(:item).permit(:name, :description, :sku, :unit_price, :active) + end end \ No newline at end of file diff --git a/app/models/item.rb b/app/models/item.rb index 15087ef..5ad2b43 100644 --- a/app/models/item.rb +++ b/app/models/item.rb @@ -15,12 +15,60 @@ class Item < ApplicationRecord validates :unit_price, numericality: { greater_than_or_equal_to: 0 } self.primary_key = :id + # Returns the details of the item. 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 item'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 + Quickbooks::Model::Item.from_xml(xml) + end + end + + # Generates a unique cache key for storing this customer's QBO details. + def details_cache_key + "item:#{id}:qbo_details:#{updated_at.to_i}" + end + + + # Updates Both local & remote DB description + def description=(s) + details + @details.description = s + super + 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 item object + def method_missing(method_name, *args, &block) + if Quickbooks::Model::Item.method_defined?(method_name) + details + @details.public_send(method_name, *args, &block) + else + super + end + end + + # Updates Both local & remote DB name + def name=(s) + details + @details.name = s + super + end + + # Updates Both local & remote DB sku + def sku=(s) + details + @details.sku = s + super + end + # Sync all items, typically triggered by a scheduled task or manual sync request def self.sync ItemSyncJob.perform_later(full_sync: true) @@ -31,10 +79,37 @@ class Item < ApplicationRecord ItemSyncJob.perform_later(id: id) end + # Push the updates + def save_with_push + log "Starting push for item ##{self.id}..." + qbo = QboConnectionService.current! + ItemService.new(qbo: qbo, item: self).push() + Rails.cache.delete(details_cache_key) + save_without_push + end + + alias_method :save_without_push, :save + alias_method :save, :save_with_push + + # Updates Both local & remote DB price + def unit_price=(s) + details + @details.unit_price = s + super + end + private def log(msg) - Rails.logger.info "[LineItem] #{msg}" + Rails.logger.info "[Item] #{msg}" end + # Fetches the item's details from QuickBooks Online. + def fetch_details + log "Fetching details for item ##{id} from QBO..." + qbo = QboConnectionService.current! + ItemService.new(qbo: qbo, item: self).pull() + end + + end \ No newline at end of file diff --git a/app/services/item_service.rb b/app/services/item_service.rb new file mode 100644 index 0000000..49ef09b --- /dev/null +++ b/app/services/item_service.rb @@ -0,0 +1,93 @@ +#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 ItemService + + # Initializes the service with a QBO client and an optional item record. The QBO client is used to communicate with QuickBooks Online, while the item record contains the data that needs to be pushed to QBO. If no item is provided, the service will not perform any operations. + def initialize(qbo:, item: nil) + raise "No QBO configuration found" unless qbo + raise "Item record is required for push operation" unless item + @qbo = qbo + @item = item + end + + def build_qbo_item + log "Building new QBO Item" + account = default_income_account + log "Account: #{account.id} - #{account.name}" + income = Quickbooks::Model::BaseReference.new + income.value = account.id + income.name = account.name + + Quickbooks::Model::Item.new( + type: Quickbooks::Model::Item::NON_INVENTORY_TYPE, + income_account_ref: income + ) + end + + def default_income_account + log "Looking up sales income account" + qbo = QboConnectionService.current! + qbo.perform_authenticated_request do |token| + service = Quickbooks::Service::Account.new( + company_id: qbo.realm_id, + access_token: token + ) + service.query("SELECT * FROM Account WHERE AccountType='Income' AND Name LIKE '%Sales%'").first + end + end + + # Pulls the Item data from QuickBooks Online. + def pull + return Quickbooks::Model::Item.new unless @item.present? + return build_qbo_item unless @item.id + log "Fetching details for item ##{@item.id} from QBO..." + qbo = QboConnectionService.current! + qbo.perform_authenticated_request do |access_token| + service = Quickbooks::Service::Item.new( + company_id: qbo.realm_id, + access_token: access_token + ) + service.fetch_by_id(@item.id) + end + rescue => e + log "Fetch failed for #{@item.id}: #{e.message}" + build_qbo_item + 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 item data and logs the process for monitoring and debugging purposes. If the push is successful, it returns the item record; otherwise, it logs the error and returns false. + def push + log "Pushing item ##{@item.id} to QBO..." + + item = @qbo.perform_authenticated_request do |access_token| + service = Quickbooks::Service::Item.new( + company_id: @qbo.realm_id, + access_token: access_token + ) + if @item.id.present? + service.update(@item.details) + else + service.create(@item.details) + end + end + + @item.id = item.id unless @item.persisted? + log "Push for item ##{@item.id} completed." + return @item + end + + private + + # Log messages with the entity type for better traceability + def log(msg) + Rails.logger.info "[ItemService] #{msg}" + end + +end \ No newline at end of file diff --git a/app/views/items/_form.html.erb b/app/views/items/_form.html.erb new file mode 100644 index 0000000..b2afcb4 --- /dev/null +++ b/app/views/items/_form.html.erb @@ -0,0 +1,43 @@ +<%= form_with model: @item, local: true do |f| %> + + <% if @item.errors.any? %> +
+

<%= pluralize(@item.errors.count, "error") %>

+ +
+ <% end %> + +

+ <%= f.label :name %>
+ <%= f.text_field :name, required: true %> +

+ +

+ <%= f.label :sku %>
+ <%= f.text_field :sku %> +

+ +

+ <%= f.label :description %>
+ <%= f.text_area :description, rows: 3 %> +

+ +

+ <%= f.label :unit_price %>
+ <%= f.number_field :unit_price, step: 0.01 %> +

+ +

+ <%= f.label :active %> + <%= f.check_box :active %> +

+ +

+ <%= f.submit %> +

+ +<% end %> \ No newline at end of file diff --git a/app/views/items/edit.html.erb b/app/views/items/edit.html.erb new file mode 100644 index 0000000..2ec4112 --- /dev/null +++ b/app/views/items/edit.html.erb @@ -0,0 +1,5 @@ +

Edit Item

+ +<%= render "form" %> + +<%= link_to "Back", items_path %> \ No newline at end of file diff --git a/app/views/items/index.html.erb b/app/views/items/index.html.erb new file mode 100644 index 0000000..0b884a8 --- /dev/null +++ b/app/views/items/index.html.erb @@ -0,0 +1,37 @@ +

Items

+ +
+ <%= link_to "New Item", new_item_path, class: "icon icon-add" %> +
+ + + + + + + + + + + + + + + <% @items.each do |item| %> + + + + + + + + + <% end %> + +
NameSKUDescriptionPriceActive
<%= link_to item.name, item_path(item) %><%= item.sku %><%= item.description %><%= number_to_currency(item.unit_price) %><%= item.active ? "Yes" : "No" %> + <%= link_to "Edit", edit_item_path(item), class: "icon icon-edit" %> + <%= link_to "Delete", item_path(item), + method: :delete, + data: { confirm: "Are you sure?" }, + class: "icon icon-del" %> +
\ No newline at end of file diff --git a/app/views/items/new.html.erb b/app/views/items/new.html.erb new file mode 100644 index 0000000..f3b008e --- /dev/null +++ b/app/views/items/new.html.erb @@ -0,0 +1,5 @@ +

New Item

+ +<%= render "form" %> + +<%= link_to "Back", items_path %> \ No newline at end of file diff --git a/app/views/items/show.html.erb b/app/views/items/show.html.erb new file mode 100644 index 0000000..bbc4e29 --- /dev/null +++ b/app/views/items/show.html.erb @@ -0,0 +1,26 @@ +

<%= @item.name %>

+ +

+ SKU: + <%= @item.sku %> +

+ +

+ Description: + <%= @item.description %> +

+ +

+ Unit Price: + <%= number_to_currency(@item.unit_price) %> +

+ +

+ Active: + <%= @item.active ? "Yes" : "No" %> +

+ +

+ <%= link_to "Edit", edit_item_path(@item), class: "icon icon-edit" %> + <%= link_to "Back", items_path %> +

\ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 86fde68..71f8108 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -8,5 +8,9 @@ # #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. -get 'items/autocomplete', to: 'items#autocomplete' -get 'items/sync', to: 'items#sync' \ No newline at end of file +resources :items do + collection do + get :autocomplete + post :sync + end +end \ No newline at end of file