diff --git a/Capfile b/Capfile index 9cfa1807..20d02533 100644 --- a/Capfile +++ b/Capfile @@ -22,10 +22,15 @@ require "capistrano/bundler" require "capistrano/rails" require "capistrano/rails/assets" require "capistrano/rails/migrations" -# require "capistrano/passenger" +require "capistrano/scm/git" +install_plugin Capistrano::SCM::Git + +require 'capistrano/puma' +install_plugin Capistrano::Puma, load_hooks: false # Default puma tasks +install_plugin Capistrano::Puma::Monit # if you need the monit tasks +install_plugin Capistrano::Puma::Jungle # if you need the jungle tasks # Load custom tasks from `lib/capistrano/tasks` if you have any defined Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r } Dir.glob('lib/capistrano/tasks/*.cap').each { |r| import r } Dir.glob('lib/capistrano/**/*.rb').each { |r| import r } - diff --git a/Gemfile b/Gemfile index 4a447a6e..cc6611ed 100644 --- a/Gemfile +++ b/Gemfile @@ -1,6 +1,8 @@ source 'https://rubygems.org' + #ruby '2.4.1' ruby '2.5.7' + git_source(:github) do |repo_name| repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") "https://github.com/#{repo_name}.git" @@ -45,7 +47,8 @@ gem 'mini_magick' gem 'jquery-fileupload-rails', '~> 0.4.7' #Report and Printing gems -gem 'cups' +#gem 'cups' #remove for cloud installation +gem 'cups', '~>0.0.7' gem 'prawn' gem 'prawn-table' gem 'prawn-qrcode' @@ -115,6 +118,7 @@ group :development do gem 'capistrano-bundler' gem 'capistrano-rails' gem 'capistrano-rbenv', github: "capistrano/rbenv" + gem 'capistrano3-puma' end group :test do diff --git a/Gemfile.lock b/Gemfile.lock index 856497b0..858ce67d 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -72,11 +72,15 @@ GEM capistrano-rails (1.4.0) capistrano (~> 3.1) capistrano-bundler (~> 1.1) + capistrano3-puma (3.1.1) + capistrano (~> 3.7) + capistrano-bundler + puma (~> 3.4) carrierwave (1.3.1) activemodel (>= 4.0.0) activesupport (>= 4.0.0) mime-types (>= 1.16) - chartkick (3.2.1) + chartkick (3.2.2) chronic (0.10.2) chunky_png (1.3.11) coffee-rails (4.2.2) @@ -89,7 +93,7 @@ GEM concurrent-ruby (1.1.5) connection_pool (2.2.2) crass (1.0.5) - cups (0.1.10) + cups (0.0.7) database_cleaner (1.7.0) diff-lcs (1.3) erubi (1.9.0) @@ -265,7 +269,7 @@ GEM simple_form (5.0.1) actionpack (>= 5.0) activemodel (>= 5.0) - spreadsheet (1.2.4) + spreadsheet (1.2.5) ruby-ole (>= 1.0) spring (2.1.0) spring-watcher-listen (2.0.1) @@ -321,10 +325,11 @@ DEPENDENCIES capistrano-bundler capistrano-rails capistrano-rbenv! + capistrano3-puma carrierwave (~> 1.0) chartkick coffee-rails (~> 4.2) - cups + cups (~> 0.0.7) database_cleaner factory_girl_rails (~> 4.0) faker @@ -370,6 +375,7 @@ DEPENDENCIES whenever RUBY VERSION + ruby 2.4.1p111 BUNDLED WITH diff --git a/app/controllers/api/api_controller.rb b/app/controllers/api/api_controller.rb index ad38376a..0e8ea909 100755 --- a/app/controllers/api/api_controller.rb +++ b/app/controllers/api/api_controller.rb @@ -1,5 +1,6 @@ class Api::ApiController < ActionController::API - # include TokenVerification + include TokenVerification + include ActionController::MimeResponds # before_action :lookup_domain helper_method :current_token, :current_login_employee, :get_cashier @@ -23,25 +24,25 @@ class Api::ApiController < ActionController::API @employee = Employee.find_by_token_session(current_token) end - # def lookup_domain - # if request.subdomain.present? && request.subdomain != "www" - # from = request.subdomain.downcase + "." + request.domain.downcase + # def lookup_domain + # if request.subdomain.present? && request.subdomain != "www" + # from = request.subdomain.downcase + "." + request.domain.downcase # @license = cache_license(ENV["SX_PROVISION_URL"], from) # request.subdomain.downcase # if (!@license.nil?) - # logger.info "Location - " + @license.dbhost - # ActiveRecord::Base.establish_connection(website_connection(@license)) - # # authenticate_session_token + # logger.info "Location - " + @license.dbhost + # ActiveRecord::Base.establish_connection(website_connection(@license)) + # # authenticate_session_token # # logger.info "Connecting to - " + @license.subdomain + " - "+ @license.dbhost + "@" + @license.dbschema # else # # reconnect_default_db # logger.info 'License is nil' # # redirect_to root_url(:host => request.domain) + "store_error" # render :json => [{ status: false, message: 'Invalid Access!'}] - # end - # end + # end + # end # end - # def website_connection(license) + # def website_connection(license) # default_connection.dup.update(:host => license.dbhost, :database => license.dbschema.to_s.downcase, # :username => license.dbusername, :password => license.dbpassword) # end @@ -55,8 +56,8 @@ class Api::ApiController < ActionController::API # @default_config ||= ActiveRecord::Base.connection.instance_variable_get("@config").dup # end - # def cache_license(url, lookup) - # @license = License.new(url, lookup) + # def cache_license(url, lookup) + # @license = License.new(url, lookup) # if (@license.detail_with_local_cache(lookup) == true) # return @license diff --git a/app/controllers/api/authenticate_controller.rb b/app/controllers/api/authenticate_controller.rb index 8fb10040..aad8607c 100755 --- a/app/controllers/api/authenticate_controller.rb +++ b/app/controllers/api/authenticate_controller.rb @@ -40,7 +40,7 @@ class Api::AuthenticateController < Api::ApiController @status = false @error_message = "This employee is not active!" # render json: JSON.generate({:status => false, :error_message => "This employee is not active!"}) - end + end else @status = false @error_message = "Bad Emp_ID or Password!" diff --git a/app/controllers/api/loader_service/load_data_controller.rb b/app/controllers/api/loader_service/load_data_controller.rb new file mode 100644 index 00000000..58b89c3d --- /dev/null +++ b/app/controllers/api/loader_service/load_data_controller.rb @@ -0,0 +1,90 @@ +require "net/http" +class Api::LoaderService::LoadDataController < Api::ApiController + skip_before_action :authenticate + + def get_sale_data_rage + load_time_start = params[:load_time] + load_time_end = params[:load_time_end] + unless load_time_start.nil? || load_time_end.nil? + @sale_data = Sale.get_load_sale_range(load_time_start.to_datetime,load_time_end.to_datetime) + if !@sale_data.empty? + @out = {general_status: true, data: @sale_data} + else + @out = {general_status: false, data: "Data is empty."} + end + else + @out = {general_status: false, data: "load_time is missing."} + end + render :json => @out + end + + # SFTP for BreadTalk Start + + # Detail Sale + def get_detail_sale_data + data = params['data'] + transaction_date = data[:transaction_date].to_s + detail_sale_data = SaleItem.get_detail_sale_data(transaction_date) + json = detail_sale_data.to_json + trans_count = JSON.parse(json).count + unless detail_sale_data.empty? + out = { :status => "success", :transaction_count => trans_count, :data => detail_sale_data } + else + out = { :status => "fail", :data => "Data is empty" } + end + respond_to do |format| + format.json {render json: out } + end + end + + # Tender sale + def get_tender_sale_data + data = params['data'] + transaction_date = data['transaction_date'].to_s + tender_sale_data = Sale.get_tender_sale_data(transaction_date) + json = tender_sale_data.to_json + trans_count = JSON.parse(json).count + unless tender_sale_data.empty? + out = { :status => "success", :transaction_count => trans_count, :data => tender_sale_data } + else + out = { :status => "fail", :data => "Data is empty" } + end + respond_to do |format| + format.json { render json: out } + end + end + + # Daily_Sale summary + def get_daily_sale_data + data = params['data'] + transaction_date = data['transaction_date'].to_s + daily_sale_data = Sale.get_daily_sale_data(transaction_date) + unless daily_sale_data.empty? + out = { :status => "success", :data => daily_sale_data} + else + out = { :status => "fail", :data => "Data is empty"} + end + respond_to do |format| + format.json { render json: out } + end + end + + # Check Sale Data + def get_check_sale_data + data = params['data'] + transaction_date = data['transaction_date'].to_s + check_sale_data = Sale.get_check_sale_data(transaction_date) + json = check_sale_data.to_json + trans_count = JSON.parse(json).count + unless check_sale_data.empty? + out = { :status => "success", :transaction_count => trans_count, :data => check_sale_data} + else + out = { :status => "fail", :data => "Data is empty"} + end + respond_to do |format| + format.json { render json: out } + end + end + + # SFTP for BreadTalk End +end diff --git a/app/controllers/api/void_controller.rb b/app/controllers/api/void_controller.rb index ab5d87f0..80bda5fa 100644 --- a/app/controllers/api/void_controller.rb +++ b/app/controllers/api/void_controller.rb @@ -8,7 +8,7 @@ class Api::VoidController < Api::ApiController if sale.discount_type == "member_discount" sale.update_attributes(total_discount: 0) - sale.compute_by_sale_items(sale_id, sale.sale_items,0,order_source) + sale.compute_by_sale_items(0, nil, order_source) end # update count for shift sale @@ -25,18 +25,17 @@ class Api::VoidController < Api::ApiController shift.save end end - + sale.rounding_adjustment = 0.0 sale.payment_status = 'void' sale.sale_status = 'void' sale.save - + # remark = "Void Sale ID #{sale_id} | Receipt No #{sale.receipt_no} | Receipt No #{sale.receipt_no} | Table ->#{table.name}" sale_audit = SaleAudit.record_audit_for_edit(sale_id,current_login_employee.name, current_login_employee.name,nil,"SALEVOID" ) render json: JSON.generate({:status => true, :message => "Void successful."}) else render json: JSON.generate({:status => false, :error_message => "There is no sale for '#{params[:sale_id]}'!"}) end - end + end end - diff --git a/app/controllers/origami/addorders_controller.rb b/app/controllers/origami/addorders_controller.rb index ba302f88..597b5d28 100755 --- a/app/controllers/origami/addorders_controller.rb +++ b/app/controllers/origami/addorders_controller.rb @@ -305,7 +305,7 @@ class Origami::AddordersController < BaseOrigamiController def getCloudDomain from = "" if ENV["SERVER_MODE"] == 'cloud' - from = request.subdomain + "." + request.domain + from = request.subdomain.to_s + "." + request.domain.to_s end return from diff --git a/app/controllers/origami/customers_controller.rb b/app/controllers/origami/customers_controller.rb index d5e6b524..97f35339 100644 --- a/app/controllers/origami/customers_controller.rb +++ b/app/controllers/origami/customers_controller.rb @@ -48,44 +48,44 @@ class Origami::CustomersController < BaseOrigamiController def add_customer @webview = false if check_mobile - @webview = true + @webview = true end - + @sale_id = params[:sale_id] @cashier_type = params[:type] @page = params[:dir_page] - + if(@sale_id[0,3] == "SAL") @booking = Booking.find_by_sale_id(@sale_id) if @booking.dining_facility_id.to_i > 0 @dining_facility = DiningFacility.find(@booking.dining_facility_id) else - @dining_facility = nil + @dining_facility = nil end - + else @booking_order = BookingOrder.find_by_order_id(@sale_id) @booking = Booking.find(@booking_order.booking_id) if @booking.dining_facility_id.to_i > 0 @dining_facility = DiningFacility.find(@booking.dining_facility_id) else - @dining_facility = nil + @dining_facility = nil end - end + end filter = params[:filter] - + if filter.nil? @crm_customers = Customer.order("customer_id") #.page(params[:page]) #@products = Product.order("name").page(params[:page]).per(5) else - @crm_customers = Customer.search(filter) + @crm_customers = Customer.search(filter) end #@crm_customers = Customer.all @crm_customers = Kaminari.paginate_array(@crm_customers).page(params[:page]).per(20) @crm_customer = Customer.new @count_customer = Customer.count_customer - + # @taxes = TaxProfile.where(:group_type => 'cashier') @taxes = TaxProfile.unscoped.select("id, (CONCAT(name,'(',(SELECT name FROM lookups WHERE lookup_type='tax_profiles' AND value=group_type),')')) as name") .order("group_type ASC,order_by ASC") @@ -100,7 +100,7 @@ class Origami::CustomersController < BaseOrigamiController lookup_customer = Lookup.collection_of('customer_settings') if !lookup_customer.empty? lookup_customer.each do |create_setting| - if create_setting[0].downcase == "create" + if create_setting[0].downcase == "create" if create_setting[1] == '0' && current_login_employee.role == 'cashier' @create_flag = false end @@ -154,13 +154,13 @@ class Origami::CustomersController < BaseOrigamiController if status == true render json: JSON.generate({:status => true}) if(id == "SAL") - sale.compute_by_sale_items(sale.sale_id, sale.sale_items, sale.total_discount, nil, order_source) - end + sale.compute_by_sale_items(sale.total_discount, nil, order_source) + end else render json: JSON.generate({:status => false, :error_message => "Record not found"}) end end - + def send_account amount = params[:amount] account_no = params[:account_no] diff --git a/app/controllers/origami/discounts_controller.rb b/app/controllers/origami/discounts_controller.rb index cd73d174..6f4690f0 100755 --- a/app/controllers/origami/discounts_controller.rb +++ b/app/controllers/origami/discounts_controller.rb @@ -7,9 +7,9 @@ class Origami::DiscountsController < BaseOrigamiController @print_settings = PrintSetting.get_precision_delimiter() @webview = false if check_mobile - @webview = true + @webview = true end - + sale_id = params[:id] @cashier_type = params[:type] if Sale.exists?(sale_id) @@ -32,7 +32,6 @@ class Origami::DiscountsController < BaseOrigamiController discount_items = JSON.parse(params[:discount_items]) overall_discount = params[:overall_discount] sub_total = params[:sub_total] - if Sale.exists?(sale_id) sale = Sale.find(sale_id) @@ -44,26 +43,29 @@ class Origami::DiscountsController < BaseOrigamiController table_id = nil end - - # sale.total_discount = overall_discount.to_f + + # sale.total_discount = overall_discount.to_f # sale.total_amount = sub_total.to_f - # sale.grand_total = (sub_total.to_f - overall_discount.to_f) + sale.total_tax; - # sale.save + # sale.grand_total = (sub_total.to_f - overall_discount.to_f) + sale.total_tax; + # sale.save if discount_items.length > 0 #save sale item for discount discount_items.each do |di| origin_sale_item = SaleItem.find(di["id"]) - + sale_item = SaleItem.new - if !origin_sale_item.nil? - menu_category = MenuCategory.get_menu_category(origin_sale_item.product_code) #get menu category for menu items - if !menu_category.nil? - sale_item.menu_category_code = menu_category.code - sale_item.menu_category_name = menu_category.name - end - end + # if !origin_sale_item.nil? + # menu_category = MenuCategory.get_menu_category(origin_sale_item.product_code) #get menu category for menu items + # if !menu_category.nil? + # sale_item.menu_category_code = menu_category.code + # sale_item.menu_category_name = menu_category.name + # end + # end + + sale_item.menu_category_code = origin_sale_item.menu_category_code + sale_item.menu_category_name = origin_sale_item.menu_category_name sale_item.sale_id = sale_id sale_item.product_code = origin_sale_item != nil ? origin_sale_item.product_code : sale_id @@ -73,7 +75,7 @@ class Origami::DiscountsController < BaseOrigamiController sale_item.status = "Discount" sale_item.qty = -1 - sale_item.unit_price = di["price"].to_f * (-1) + sale_item.unit_price = di["price"].to_f * -1 sale_item.taxable_price = di["price"] sale_item.is_taxable = 1 sale_item.account_id = origin_sale_item.account_id @@ -83,11 +85,11 @@ class Origami::DiscountsController < BaseOrigamiController action_by = current_user.name remark = "Discount Item Name ->#{sale_item.product_name}-Product Code ->#{sale_item.product_code} | Price [#{sale_item.price}] | Receipt No #{sale.receipt_no} " - + sale_audit = SaleAudit.record_audit_discount(sale_item.sale_id,sale.cashier_name, action_by,remark,"ITEMDISCOUNT" ) - - end - end + + end + end # Re-calc All Amount in Sale if overall_discount.to_f > 0 @@ -97,24 +99,24 @@ class Origami::DiscountsController < BaseOrigamiController else remark = "Discount Overall Price [#{overall_discount}]| Receipt No #{sale.receipt_no} | Table- #{table.name} " end - + sale_audit = SaleAudit.record_audit_discount(sale.sale_id,sale.cashier_name, action_by,remark,"OVERALLDISCOUNT" ) - end - sale.compute_by_sale_items(sale_id, sale.sale_items, overall_discount.to_f, nil,order_source) + end + sale.compute_by_sale_items(overall_discount.to_f, nil,order_source) if !table.nil? result = {:status=> "Success", :table_id => table_id, :table_type => table.type } else result = {:status=> "Success" } end - else + else if !table.nil? result = {:status=> "Please, Check Again!", :table_id => table_id, :table_type => table.type } else result = {:status=> "Please, Check Again!" } end - end + end + - render :json => result.to_json end @@ -131,45 +133,45 @@ class Origami::DiscountsController < BaseOrigamiController else table_id = nil table = nil - end - - - if discount_items.length > 0 + end + + + if discount_items.length > 0 #destroy sale item for discount - discount_items.each do |di| - sale_item = SaleItem.find(di["id"]) + discount_items.each do |di| + sale_item = SaleItem.find(di["id"]) sale.total_amount = (sale.total_amount + sale_item.price.abs) action_by = current_user.name if table.nil? remark = "Remove Item Discount Item Name ->#{sale_item.product_name}-Product Code ->#{sale_item.product_code} | Price [#{sale_item.price}] | Receipt No #{sale.receipt_no} | Table- No Table " else - remark = "Remove Item Discount Item Name ->#{sale_item.product_name}-Product Code ->#{sale_item.product_code} | Price [#{sale_item.price}] | Receipt No #{sale.receipt_no} | Table- #{table.name} " + remark = "Remove Item Discount Item Name ->#{sale_item.product_name}-Product Code ->#{sale_item.product_code} | Price [#{sale_item.price}] | Receipt No #{sale.receipt_no} | Table- #{table.name} " end sale_audit = SaleAudit.record_audit_discount(sale.sale_id,sale.cashier_name, action_by,remark,"REMOVEITEMDISCOUNT" ) - - sale_item.destroy - end - end - # sale.grand_total = (sale.total_amount - sale.total_discount) + sale.total_tax; + sale_item.destroy + end + end + + # sale.grand_total = (sale.total_amount - sale.total_discount) + sale.total_tax; # sale.save # Re-calc All Amount in Sale - sale.compute_by_sale_items(sale_id, sale.sale_items, sale.total_discount, nil, order_source) + sale.compute_by_sale_items(sale.total_discount, nil, order_source) if table.nil? result = {:status=> "Success"} else result = {:status=> "Success", :table_id => table_id, :table_type => table.type } end - - else + + else if table.nil? result = {:status=> "Please, Check Again!"} else result = {:status=> "Please, Check Again!", :table_id => table_id, :table_type => table.type } end - - end + + end render :json => result.to_json end @@ -180,29 +182,29 @@ class Origami::DiscountsController < BaseOrigamiController order_source = params[:type] if Sale.exists?(sale_id) - sale = Sale.find(sale_id) - + sale = Sale.find(sale_id) + if sale.bookings[0].dining_facility_id.to_i > 0 table_id = sale.bookings[0].dining_facility_id table = DiningFacility.find(table_id) - table_type = table.type + table_type = table.type else table_id = nil table = nil table_type = nil - end + end - discount_items = [] + discount_items = [] #destroy all discount sale item - sale.sale_items.each do |si| - if si.status == "Discount" && si.price < 0 - sale.total_amount = (sale.total_amount + si.price.abs) - discount_items.push(si) + sale.sale_items.each do |si| + if si.status == "Discount" && si.price < 0 + sale.total_amount = (sale.total_amount + si.price.abs) + discount_items.push(si) end - end + end # sale.total_discount = 0 - # sale.grand_total = (sale.total_amount - sale.total_discount) + sale.total_tax; + # sale.grand_total = (sale.total_amount - sale.total_discount) + sale.total_tax; # sale.save #destroy in sale.sale_items @@ -215,23 +217,23 @@ class Origami::DiscountsController < BaseOrigamiController remark = "Remove Discount Sale Id [#{sale.sale_id}]| Receipt No #{sale.receipt_no} | Table- #{table.name} " end sale_audit = SaleAudit.record_audit_discount(sale.sale_id,sale.cashier_name, action_by,remark,"REMOVEALLDISCOUNT" ) - + # Re-calc All Amount in Sale - sale.compute_by_sale_items(sale_id, sale.sale_items, 0, nil, order_source) + sale.compute_by_sale_items(0, nil, order_source) if table.nil? result = {:status=> "Success"} else - result = {:status=> "Success", :table_id => table_id, :dining => table.name, :table_type => table_type } + result = {:status=> "Success", :table_id => table_id, :dining => table.name, :table_type => table_type } end - - else + + else if table.nil? result = {:status=> "Please, Check Again!"} else - result = {:status=> "Please, Check Again!", :table_id => table_id, :dining => table.name, :table_type => table_type } + result = {:status=> "Please, Check Again!", :table_id => table_id, :dining => table.name, :table_type => table_type } end - - end + + end render :json => result.to_json end @@ -251,7 +253,7 @@ class Origami::DiscountsController < BaseOrigamiController end # Check for Card Payment is_card_payment = SalePayment.get_sale_payments_by_card(sale.sale_payments) - + # if is_card != "true" account_types = Account.where("discount=?",true) table_id = sale.bookings[0].dining_facility_id @@ -267,9 +269,9 @@ class Origami::DiscountsController < BaseOrigamiController str={type:pc[:name],amount:pc[:price]} acc_prices.push(str) end - end + end end - generic_customer_id = sale.customer.membership_id + generic_customer_id = sale.customer.membership_id receipt_no = sale.receipt_no membership = MembershipSetting.find_by_membership_type("paypar_url") memberaction = MembershipAction.find_by_membership_type("member_discount") @@ -282,7 +284,7 @@ class Origami::DiscountsController < BaseOrigamiController # Check for items for Paypar Cloud if acc_prices.length > 0 begin - response = HTTParty.post(url, + response = HTTParty.post(url, :body => { account_no: account_no, generic_customer_id:generic_customer_id , campaign_type_id: campaign_type_id, @@ -307,7 +309,7 @@ class Origami::DiscountsController < BaseOrigamiController rescue SocketError response = {"status": false, "message": "Can't open membership server " } end - else + else response = {"status": false, "message": "You have no selected discount item" } end Rails.logger.debug "-------------- Member Discount Osaka ---------" @@ -318,14 +320,14 @@ class Origami::DiscountsController < BaseOrigamiController if response["discount_bonus_earned"] discount_amount = discount_amount + response["discount_bonus_earned"] end - sale.compute_by_sale_items(sale_id, sale.sale_items, discount_amount, 'member_discount', order_source, tax_type) + sale.compute_by_sale_items(discount_amount, 'member_discount', order_source, tax_type) result = {:status=> "Success",:title=>"Member Discount", :table_id => table_id,:table_type => table_type } elsif response["status"] == "500" result = {:status=> response["error"],:title=>"Alert", :table_id => table_id,:table_type => table_type } else result = {:status=> response["message"],:title=>"Alert", :table_id => table_id,:table_type => table_type } end - + render :json => result.to_json # end #end Is Card Payment @@ -376,5 +378,5 @@ class Origami::DiscountsController < BaseOrigamiController # redirect_to origami_path(sale_id) # end - + end diff --git a/app/controllers/origami/other_charges_controller.rb b/app/controllers/origami/other_charges_controller.rb index 36fbffb8..fbcd2ec1 100755 --- a/app/controllers/origami/other_charges_controller.rb +++ b/app/controllers/origami/other_charges_controller.rb @@ -4,9 +4,9 @@ class Origami::OtherChargesController < BaseOrigamiController def index @webview = false if check_mobile - @webview = true + @webview = true end - + sale_id = params[:sale_id] @cashier_type = params[:type] if Sale.exists?(sale_id) @@ -15,11 +15,11 @@ class Origami::OtherChargesController < BaseOrigamiController @table = DiningFacility.find(@sale_data.bookings[0].dining_facility_id) else @table = nil - end + end end end - def create + def create sale_id = params[:sale_id] other_charges_items = JSON.parse(params[:other_charges_items]) sub_total = params[:sub_total] @@ -34,11 +34,11 @@ class Origami::OtherChargesController < BaseOrigamiController table_id = nil table = nil end - + # sale.total_amount = sub_total.to_f - # sale.grand_total = sub_total.to_f + sale.total_tax; - # sale.save + # sale.grand_total = sub_total.to_f + sale.total_tax; + # sale.save if other_charges_items.length > 0 #save sale item for discount other_charges_items.each do |di| @@ -68,18 +68,18 @@ class Origami::OtherChargesController < BaseOrigamiController else remark = "Add Other Charges - Receipt No #{sale.receipt_no} | Sale ID #{sale.sale_id} |Charges ->#{di["price"]} For ->#{di["name"]}- Table ->#{table.name}" end - + sale_audit = SaleAudit.record_audit_for_edit(sale.sale_id,sale.cashier_name, action_by,remark,"ADDOTHERCHARGES" ) - end - end + end + end # Re-calc All Amount in Sale - sale.compute_by_sale_items(sale_id, sale.sale_items, sale.total_discount, nil, cashier_type) - end + sale.compute_by_sale_items(sale.total_discount, nil, cashier_type) + end if !table.nil? dining = {:table_id => table_id, :table_type => table.type } render :json => dining.to_json - end - end -end \ No newline at end of file + end + end +end diff --git a/app/controllers/origami/payments_controller.rb b/app/controllers/origami/payments_controller.rb index 5de37662..c6c61602 100755 --- a/app/controllers/origami/payments_controller.rb +++ b/app/controllers/origami/payments_controller.rb @@ -64,15 +64,9 @@ class Origami::PaymentsController < BaseOrigamiController customer = Customer.find(sale_data.customer_id) # rounding adjustment if shop_detail.is_rounding_adj - a = sale_data.grand_total % 25 # Modulus - b = sale_data.grand_total / 25 # Division - #not calculate rounding if modulus is 0 and division is even - #calculate rounding if modulus is zero or not zero and division are not even - if (a != 0.0 && b%2 != 0.0) || (a==0.0 && b%2 !=0) - new_total = Sale.get_rounding_adjustment(sale_data.grand_total) - rounding_adj = new_total-sale_data.grand_total - sale_data.update_attributes(grand_total: new_total,old_grand_total: sale_data.grand_total,rounding_adjustment:rounding_adj) - end + new_total = Sale.get_rounding_adjustment(sale_data.grand_total) + rounding_adj = new_total - sale_data.grand_total + sale_data.update_attributes(grand_total: new_total,old_grand_total: sale_data.grand_total,rounding_adjustment:rounding_adj) if rounding_adj > 0 end #end rounding adjustment #record for sale audit @@ -151,15 +145,9 @@ class Origami::PaymentsController < BaseOrigamiController # rounding adjustment if !path.include? ("credit_payment") if shop_detail.is_rounding_adj - a = saleObj.grand_total % 25 # Modulus - b = saleObj.grand_total / 25 # Division - #not calculate rounding if modulus is 0 and division is even - #calculate rounding if modulus is zero or not zero and division are not even - if (a != 0.0 && b%2 != 0.0) || (a==0.0 && b%2 !=0) - new_total = Sale.get_rounding_adjustment(saleObj.grand_total) - rounding_adj = new_total-saleObj.grand_total - saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj) - end + new_total = Sale.get_rounding_adjustment(saleObj.grand_total) + rounding_adj = new_total - saleObj.grand_total + saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj) if rounding_adj > 0 end end #end rounding adjustment @@ -655,7 +643,7 @@ class Origami::PaymentsController < BaseOrigamiController if saleObj.discount_type == "member_discount" saleObj.update_attributes(grand_total: 0, rounding_adjustment: 0, amount_received: 0, amount_changed: 0) - saleObj.compute_by_sale_items(sale_id, saleObj.sale_items,0,order_source) + saleObj.compute_by_sale_items(0, nil, order_source) end saleObj.update_attributes(grand_total: 0, rounding_adjustment: 0, amount_received: 0, amount_changed: 0) @@ -830,7 +818,7 @@ class Origami::PaymentsController < BaseOrigamiController order_source = params[:cashier_type] tax_type = params[:tax_type] sale = Sale.find(sale_id) - sale.compute_by_sale_items(sale.sale_id, sale.sale_items, sale.total_discount,nil,order_source,tax_type) + sale.compute_by_sale_items(sale.total_discount, nil, order_source, tax_type) render json: JSON.generate({:status => true}) end @@ -839,7 +827,7 @@ class Origami::PaymentsController < BaseOrigamiController def getCloudDomain from = "" if ENV["SERVER_MODE"] == 'cloud' - from = request.subdomain + "." + request.domain + from = request.subdomain.to_s + "." + request.domain.to_s end return from diff --git a/app/controllers/origami/pending_order_controller.rb b/app/controllers/origami/pending_order_controller.rb index d05388a2..773a217e 100644 --- a/app/controllers/origami/pending_order_controller.rb +++ b/app/controllers/origami/pending_order_controller.rb @@ -22,7 +22,7 @@ class Origami::PendingOrderController < BaseOrigamiController else redirect_to "/origami/#{params[:type]}" and return end - elsif (id.start_with?("BKI")|| id.start_with?("CBKI")) + elsif (id.start_with?("BKI") || id.start_with?("CBKI")) @bookings = Booking.find(id) @order = @bookings.orders.where(status: "new").first @order_items = @bookings.order_items diff --git a/app/controllers/origami/sale_edit_controller.rb b/app/controllers/origami/sale_edit_controller.rb index 40f79afd..7f456f35 100755 --- a/app/controllers/origami/sale_edit_controller.rb +++ b/app/controllers/origami/sale_edit_controller.rb @@ -59,7 +59,7 @@ class Origami::SaleEditController < BaseOrigamiController remark = "Void Sale Item ID #{saleitemObj.sale_item_id} | Receipt No #{saleObj.receipt_no} | Item Name ->#{saleitemObj.product_name}-Product Code ->#{saleitemObj.product_code}-Instance Code ->#{saleitemObj.item_instance_code}" sale_audit = SaleAudit.record_audit_for_edit(saleitemObj.sale_id,current_user.name, action_by,remark,"SALEITEMVOID" ) - saleObj.compute_by_sale_items(saleObj.sale_id, saleObj.sale_items, saleObj.total_discount,order_source) + saleObj.compute_by_sale_items(saleObj.total_discount, nil, order_source) ProductCommission.create_product_commission(@newsaleitem, saleitemObj) end @@ -72,7 +72,7 @@ class Origami::SaleEditController < BaseOrigamiController saleitemObj.status = 'foc' saleitemObj.remark = remark saleitemObj.save - @newsaleitem = SaleItem.new + @newsaleitem = saleitemObj.dup @newsaleitem.qty = saleitemObj.qty * -1 @newsaleitem.unit_price = saleitemObj.unit_price * 1 @@ -95,7 +95,7 @@ class Origami::SaleEditController < BaseOrigamiController remark = "FOC Sale Item ID #{saleitemObj.sale_item_id} | Receipt No #{saleObj.receipt_no} | Item Name ->#{saleitemObj.product_name}-Product Code ->#{saleitemObj.product_code}-Instance Code ->#{saleitemObj.item_instance_code}Receipt No #{saleObj.receipt_no}" sale_audit = SaleAudit.record_audit_for_edit(saleitemObj.sale_id,current_user.name, action_by,remark,"SALEITEMFOC" ) - saleObj.compute_by_sale_items(saleObj.sale_id, saleObj.sale_items, saleObj.total_discount,order_source) + saleObj.compute_by_sale_items(saleObj.total_discount, nil, order_source) ProductCommission.create_product_commission(@newsaleitem, saleitemObj) end @@ -143,17 +143,17 @@ class Origami::SaleEditController < BaseOrigamiController sale_audit = SaleAudit.record_audit_for_edit(saleitemObj.sale_id,current_user.name, action_by,remark,"SALEITEMEDIT" ) # saleitemObj.remark = 'edit' - unless saleitemObj.product_name.include? 'updated' + unless saleitemObj.product_name.include? 'UPDATED' saleitemObj.product_name = saleitemObj.product_name + ' (UPDATED)' end saleitemObj.save # re-calc tax - saleObj = Sale.find(saleitemObj.sale_id) + # saleObj = Sale.find(saleitemObj.sale_id) - order_id = SaleOrder.find_by_sale_id(saleitemObj.sale_id).order_id - order = Order.find(order_id) + # order_id = SaleOrder.find_by_sale_id(saleitemObj.sale_id).order_id + # order = Order.find(order_id) # order.order_items.each do |o| # if saleitemObj.product_code == o.item_code @@ -163,7 +163,7 @@ class Origami::SaleEditController < BaseOrigamiController # end # end - saleObj.compute_by_sale_items(saleObj.sale_id, saleObj.sale_items, saleObj.total_discount,order_source) + sale.compute_by_sale_items(saleObj.total_discount, nil, order_source) ProductCommission.edit_product_commission(saleitemObj) end @@ -195,8 +195,8 @@ class Origami::SaleEditController < BaseOrigamiController end remark = "Cancle Void Sale Item ID #{saleitemObj.sale_item_id} | Item Name ->#{saleitemObj.product_name}-Product Code ->#{saleitemObj.product_code}-Instance Code ->#{saleitemObj.item_instance_code}|Receipt No #{saleObj.receipt_no}" sale_audit = SaleAudit.record_audit_for_edit(saleitemObj.sale_id,current_user.name, action_by,remark,"ITEMCANCELVOID" ) - - saleObj.compute_by_sale_items(saleObj.sale_id, saleObj.sale_items, saleObj.total_discount, order_source) + + saleObj.compute_by_sale_items(saleObj.total_discount, nil, order_source) ProductCommission.remove_product_commission(saleitemObj) end @@ -214,9 +214,9 @@ class Origami::SaleEditController < BaseOrigamiController item.save ProductCommission.remove_product_commission(item) end - + saleObj.sale_items.reset # re-calc tax - saleObj.compute_by_sale_items(saleObj.sale_id, saleObj.sale_items, saleObj.total_discount,order_source) + saleObj.compute_by_sale_items(saleObj.total_discount,nil, order_source) end def apply_void diff --git a/app/controllers/origami/void_controller.rb b/app/controllers/origami/void_controller.rb index 6af6c275..5352b7c3 100755 --- a/app/controllers/origami/void_controller.rb +++ b/app/controllers/origami/void_controller.rb @@ -10,7 +10,7 @@ class Origami::VoidController < BaseOrigamiController sale = Sale.find_by_sale_id(sale_id) if sale.discount_type == "member_discount" sale.update_attributes(total_discount: 0) - sale.compute_by_sale_items(sale_id, sale.sale_items,0,order_source) + sale.compute_by_sale_items(0, nil, order_source) end # update count for shift sale diff --git a/app/controllers/origami/waste_spoile_controller.rb b/app/controllers/origami/waste_spoile_controller.rb index 2d4c9367..6a68a2b9 100755 --- a/app/controllers/origami/waste_spoile_controller.rb +++ b/app/controllers/origami/waste_spoile_controller.rb @@ -15,7 +15,6 @@ class Origami::WasteSpoileController < BaseOrigamiController sale.sale_status = remark sale.save - # sale.compute_by_sale_items(sale_id, sale.sale_items,0,order_source) # add to sale item with foc # sale_items = SaleItem.where("sale_id='#{ sale_id }' and status is null") diff --git a/app/controllers/transactions/sales_controller.rb b/app/controllers/transactions/sales_controller.rb index e8a2d9e4..83efc401 100755 --- a/app/controllers/transactions/sales_controller.rb +++ b/app/controllers/transactions/sales_controller.rb @@ -6,7 +6,7 @@ class Transactions::SalesController < ApplicationController # GET /transactions/sales # GET /transactions/sales.json def index - + receipt_no = params[:receipt_no] # from = params[:from] # to = params[:to] @@ -19,18 +19,18 @@ class Transactions::SalesController < ApplicationController if receipt_no.nil? && from.nil? && to.nil? if @shift.blank? @sales = Sale.where("NOT sale_status='new'").order("sale_id desc") - else + else @sales = Sale.where("NOT sale_status='new' and shift_sale_id ='#{@shift.id}'").order("sale_id desc") end @sales = Kaminari.paginate_array(@sales).page(params[:page]).per(20) else sale = Sale.search(receipt_no,from,to,@shift) if sale.count > 0 - @sales = sale + @sales = sale @sales = Kaminari.paginate_array(@sales).page(params[:page]).per(20) else @sales = 0 - end + end end @receipt_no = receipt_no @from = from @@ -41,20 +41,20 @@ class Transactions::SalesController < ApplicationController @shift_to = @shift.shift_closed_at.nil? ? '-' : @shift.shift_closed_at.utc.getlocal.strftime("%e %b %I:%M%p") @shift_data = @shift end - + # if receipt_no.nil? && search_date.nil? - # @sales = Sale.where("NOT sale_status = 'void' " ).order("sale_id desc").limit(500) + # @sales = Sale.where("NOT sale_status = 'void' " ).order("sale_id desc").limit(500) # @sales = Kaminari.paginate_array(@sales).page(params[:page]).per(50) # else - # if !search_date.blank? && receipt_no.blank? + # if !search_date.blank? && receipt_no.blank? # sale = Sale.where("DATE_FORMAT(receipt_date,'%d-%m-%Y') = ? and NOT sale_status = 'void' ", search_date).order("sale_id desc").limit(500).page(params[:page]) - # elsif !search_date.blank? && !receipt_no.blank? + # elsif !search_date.blank? && !receipt_no.blank? # sale = Sale.where("receipt_no LIKE ? or DATE_FORMAT(receipt_date,'%d-%m-%Y') = ? and NOT sale_status = 'void' ", "%#{receipt_no}%", search_date).order("sale_id desc").limit(500).page(params[:page]) - # else - # sale = Sale.where("receipt_no LIKE ? and NOT sale_status = 'void' ", receipt_no).order("sale_id desc").limit(500).page(params[:page]) - # end + # else + # sale = Sale.where("receipt_no LIKE ? and NOT sale_status = 'void' ", receipt_no).order("sale_id desc").limit(500).page(params[:page]) + # end # if sale.count > 0 - # @sales = sale + # @sales = sale # @sales = Kaminari.paginate_array(@sales).page(params[:page]).per(50) # else # @sales = 0 @@ -182,7 +182,7 @@ class Transactions::SalesController < ApplicationController period_type = params[:period_type] period = params[:period] from = params[:from] - to = params[:to] + to = params[:to] day_ref = Time.now.utc.getlocal if from.present? && to.present? @@ -191,8 +191,8 @@ class Transactions::SalesController < ApplicationController f_time = Time.mktime(f_date.year,f_date.month,f_date.day,f_date.hour,f_date.min,f_date.sec) t_time = Time.mktime(t_date.year,t_date.month,t_date.day,t_date.hour,t_date.min,t_date.sec) from = f_time.beginning_of_day.utc.getlocal - to = t_time.end_of_day.utc.getlocal - else + to = t_time.end_of_day.utc.getlocal + else case period.to_i when PERIOD["today"] from = day_ref.beginning_of_day.utc @@ -226,10 +226,10 @@ class Transactions::SalesController < ApplicationController when PERIOD["last_year"] from = (day_ref - 1.year).beginning_of_year.utc to = (day_ref - 1.year).end_of_year.utc - end + end end - return from, to + return from, to end def check_user @@ -248,7 +248,7 @@ class Transactions::SalesController < ApplicationController if sale.discount_type == "member_discount" sale.update_attributes(total_discount: 0) - sale.compute_by_sale_items(sale_id, sale.sale_items,0,order_source) + sale.compute_by_sale_items(0, nil, order_source) end # update count for shift sale @@ -265,7 +265,7 @@ class Transactions::SalesController < ApplicationController shift.save end end - + sale.rounding_adjustment = 0.0 sale.payment_status = 'void' sale.sale_status = 'void' @@ -308,16 +308,16 @@ class Transactions::SalesController < ApplicationController table = nil end - # FOr Sale Audit + # FOr Sale Audit action_by = current_user.name if access_code != "null" && current_user.role == "cashier" action_by = Employee.find_by_emp_id(access_code).name end - + # remark = "Void Sale ID #{sale_id} | Receipt No #{sale.receipt_no} | Receipt No #{sale.receipt_no} | Table ->#{table.name}" sale_audit = SaleAudit.record_audit_for_edit(sale_id,sale.cashier_id, action_by,remark,"SALEVOID" ) - # For Print + # For Print member_info = nil rebate_amount = nil @@ -325,7 +325,7 @@ class Transactions::SalesController < ApplicationController # For Cashier by Zone bookings = Booking.where("sale_id='#{sale_id}'") - if bookings.count > 1 + if bookings.count > 1 # for Multiple Booking if bookings[0].dining_facility_id.to_i>0 table = DiningFacility.find(bookings[0].dining_facility_id) @@ -339,12 +339,12 @@ class Transactions::SalesController < ApplicationController shift = ShiftSale.find(sale.shift_sale_id) cashier_terminal = CashierTerminal.find(shift.cashier_terminal_id) end - + # if ENV["SERVER_MODE"] != "cloud" #no print in cloud server unique_code = "ReceiptBillPdf" customer= Customer.find(sale.customer_id) - + #shop detail shop_details = Shop.find_by_id(1) # get member information @@ -363,31 +363,31 @@ class Transactions::SalesController < ApplicationController discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(sale.sale_items) other_amount = SaleItem.calculate_other_charges(sale.sale_items) #other charges - printer = Printer::ReceiptPrinter.new(print_settings) - filename, sale_receipt_no, printer_name = printer.print_receipt_bill(print_settings, false, nil,cashier_terminal,sale.sale_items,sale,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "VOID",current_balance,nil,other_amount,nil,nil,nil) - result = { - :filepath => filename, - :printer_model => print_settings.brand_name, - :printer_url => print_settings.api_settings + printer = Printer::ReceiptPrinter.new(print_settings) + filename, sale_receipt_no, printer_name = printer.print_receipt_bill(print_settings, false, nil,cashier_terminal,sale.sale_items,sale,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "VOID",current_balance,nil,other_amount,nil,nil,nil) + result = { + :filepath => filename, + :printer_model => print_settings.brand_name, + :printer_url => print_settings.api_settings } # Mobile Print render :json => result.to_json # end - + #end print # update complete order items in oqs - SaleOrder.where("sale_id = '#{ sale_id }'").find_each do |sodr| + SaleOrder.where("sale_id = '#{ sale_id }'").find_each do |sodr| AssignedOrderItem.where("order_id = '#{ sodr.order_id }'").find_each do |aoi| aoi.delivery_status = 1 aoi.save end end end - end + end + - private # Use callbacks to share common setup or constraints between actions. def set_transactions_sale diff --git a/app/models/printer/receipt_printer.rb b/app/models/printer/receipt_printer.rb index b45c722b..f7b35a5a 100755 --- a/app/models/printer/receipt_printer.rb +++ b/app/models/printer/receipt_printer.rb @@ -227,8 +227,8 @@ class Printer::ReceiptPrinter < Printer::PrinterWorker count = printer_settings.print_copies # override print copies for print worker loop - print_settings.print_copies = 1 - print_settings.save! + # print_settings.print_copies = 1 + # print_settings.save! end directory_name = 'public/receipts' Dir.mkdir(directory_name) unless File.exists?(directory_name) diff --git a/app/models/promotion.rb b/app/models/promotion.rb index b636a097..6d5a7039 100755 --- a/app/models/promotion.rb +++ b/app/models/promotion.rb @@ -11,37 +11,23 @@ class Promotion < ApplicationRecord PROMO_TYPE3 = "Net_price" # 1800 => 1000 => 1000 PROMO_TYPE4 = "Percentage" + def is_promo_day + promo_day.include? Date.today.wday.to_s + end + def self.promo_activate(saleObj) - array_same =[] current_day = Time.now.strftime("%Y-%m-%d") current_time = Time.now.strftime('%H:%M:%S') day = Date.today.wday promoList = is_between_promo_datetime(current_day,current_time) - puts "promoList - " + promoList.size.to_s - if promoList.size > 0 - itemList = combine_item(saleObj) - itemList.each do|list| - list.each do |l| - array_same.push({ - item_instance_code: l.item_instance_code, - order_id:l.order_id, - qty:l.qty - }) + + promoList.each do |promo| + if promo.is_promo_day + if item = saleObj.qty_of(promo.original_product) + check_promo_type(promo, item, saleObj) end end end - item_list =[] - array_same.group_by do |same| - same.values_at :item_instance_code - end.map do |(item_instance_code), array_same| - quantities = array_same.map { |p| p[:qty] } - qty = quantities.all? ? quantities.reduce(:+) : nil - item_list.push({ item_instance_code: item_instance_code, qty: qty }) - end - Rails.logger.debug "-------promo_activate array_same-------" - puts item_list.to_json - is_promo_day(promoList,day, item_list, saleObj.sale_id) - end def self.is_between_promo_datetime(current_day,current_time) #database is not local time @@ -49,45 +35,7 @@ class Promotion < ApplicationRecord return promoList end - def self.combine_item(saleObj) - # order_id = saleObj.sale_orders[0][0].order_id - # itemList = OrderItem.where("order_id = ?", order_id).group(:item_instance_code).sum(:qty) - # array_same =[] - itemList = [] - saleObj.sale_orders.each do |so| - # itemList << OrderItem.where("order_id = ?",so.order_id).group(["item_instance_code", "order_id"]).sum(:qty) - itemList << OrderItem.where("order_id = ?",so.order_id).select(:item_instance_code,:order_id,:qty) - end - - return itemList - end - - def self.is_promo_day(promoList, day, orderitemList, sale_id) - puts "Today date - " + day.to_s - promoList.each do |promo| - dayresult = promo.promo_day.include?(day.to_s) - if dayresult - orderitemList.each do |item| - find_promo_item(promo, item, sale_id) - end - end - end - end - - def self.find_promo_item(promo, orderitem, sale_id) - item_code = OrderItem.find_by_item_instance_code(orderitem[:item_instance_code]).item_code - # orderitem.each do |odr_item| - if promo.original_product.downcase.to_s == orderitem[:item_instance_code] - if promo.min_qty.to_i > orderitem[:qty].to_i - return false - else - check_promo_type(promo,orderitem, sale_id) - end - end - # end - end - - def self.check_promo_type(promo, orderitem, sale_id) + def self.check_promo_type(promo, orderitem, saleObj) promo.promotion_products.each do |promo_product| if promo_product.item_code.downcase == orderitem[:item_instance_code] same = true @@ -97,20 +45,20 @@ class Promotion < ApplicationRecord end # same, promo_product = check_giveaway_product(promo, orderitem[0][0]) if promo.promo_type == Promotion::PROMO_TYPE1 - if same - give_promotion_same_product(orderitem[:qty], promo.min_qty, promo_product.min_qty, orderitem, sale_id,promo_product.item_code) - else - give_promotion_second_product(orderitem[:qty], promo.min_qty, promo_product.item_code, orderitem, sale_id) + if same + give_promotion_same_product(orderitem[:qty], promo.min_qty, promo_product.min_qty, orderitem, saleObj, promo_product.item_code) + else + give_promotion_second_product(orderitem[:qty], promo.min_qty, promo_product.item_code, orderitem, saleObj) end elsif promo.promo_type == Promotion::PROMO_TYPE2 - give_promotion_nett_off(same,promo_product,promo.min_qty, orderitem, sale_id) + give_promotion_nett_off(same,promo_product,promo.min_qty, orderitem, saleObj) elsif promo.promo_type == Promotion::PROMO_TYPE3 - give_promotion_nett_price(same,promo_product,promo.min_qty, orderitem, sale_id) + give_promotion_nett_price(same,promo_product,promo.min_qty, orderitem, saleObj) elsif promo.promo_type == Promotion::PROMO_TYPE4 - give_promotion_discount(same,promo_product,promo.min_qty, orderitem, sale_id) + give_promotion_discount(same,promo_product,promo.min_qty, orderitem, saleObj) end end end @@ -128,106 +76,66 @@ class Promotion < ApplicationRecord # end end - def self.give_promotion_same_product(qty, promoqty, foc_min_qty, orderitem, sale_id,promo_product) - item ='' - puts " Order qty: " + qty.to_s + " / promoqty: " + promoqty.to_s + " / giveaway: " + foc_min_qty.to_s - multiple = qty.to_i / promoqty.to_i # loop count - charge_qty = 0 - foc_qty = 0 - if multiple > 0 - multiple.times.each do |key| - if qty > promoqty - charge_qty += promoqty - different = qty - promoqty - qty = different - if different == 0 - foc_qty += foc_min_qty - else - foc_qty += foc_min_qty - qty = qty - foc_min_qty - end + def self.give_promotion_same_product(qty, promoqty, foc_min_qty, orderitem, saleObj,promo_product) + puts " Order qty: " + qty.to_s + " / promoqty: " + promoqty.to_s + " / giveaway: " + foc_min_qty.to_s + multiple = qty.to_i / promoqty.to_i # loop count + charge_qty = 0 + foc_qty = 0 + if multiple > 0 + multiple.times.each do |key| + if qty > promoqty + charge_qty += promoqty + different = qty - promoqty + qty = different + if different == 0 + foc_qty += foc_min_qty else - charge_qty += qty + foc_qty += foc_min_qty + qty = qty - foc_min_qty end + else + charge_qty += qty end - if multiple == foc_qty - charge_qty += qty - end - else + end + if multiple == foc_qty charge_qty += qty end - sale_order =SaleOrder.where("sale_id=?",sale_id) - price =0 - source ='' - sale_order.each do|order| - source = Order.find(order.order_id).source - end + else + charge_qty += qty + end - item = OrderItem.where("item_instance_code = ?",orderitem[:item_instance_code]).order("order_items_id DESC").first - item ={ - item_code:item.item_code, - item_instance_code:item.item_instance_code, - item_name:item.item_name, - alt_name:item.alt_name, - account_id:item.account_id, - price:item.price - } - if promo_product.downcase != item[:item_instance_code] + price = 0 + source = saleObj.orders.first.source + item = saleObj.order_items.where(item_instance_code: promo_product).first - sale_order.each do|order| - source = Order.find(order.order_id).source - end - item = OrderItem.where("item_code = ?",promo_product).order("order_items_id DESC").first - item ={ - item_code:item.item_code, - item_instance_code:item.item_instance_code, - item_name:item.item_name, - alt_name:item.alt_name, - account_id:item.account_id, - price:item.price - } - end - if !item.nil? - update_existing_item(foc_qty, item, sale_id, "promotion", item[:price],source) - end + if !item.nil? + update_existing_item(foc_qty, item, saleObj, "promotion", item[:price], source) + end end # AA - 10 # 3 # BB # orderList, #S34345 - def self.give_promotion_second_product(orderitem_count, foc_min_qty, promo_product, orderitem, sale_id) - source ='' - item ='' + def self.give_promotion_second_product(orderitem_count, foc_min_qty, promo_product, orderitem, saleObj) puts "..... orderitem_count: " + orderitem_count.to_s + " / foc_min_qty: " + foc_min_qty.to_s + " /promo_product: " + promo_product + " orderitem: " + orderitem.to_s + promotion_qty = orderitem_count.to_i / foc_min_qty.to_i # get foc item qty - foc_qty = find_second_item_qty(sale_id, promo_product) + foc_qty = saleObj.qty_of(promo_product).qty rescue 0 if (foc_qty < promotion_qty) promotion_qty = foc_qty end # item = OrderItem.find_by_item_instance_code(promo_product) - sale_order =SaleOrder.where("sale_id=?",sale_id) - price =0 - sale_order.each do|order| - source = Order.find(order.order_id).source - end - item = OrderItem.where("item_instance_code = ?",promo_product).order("order_items_id DESC").first - item ={ - item_code:item.item_code, - item_instance_code:item.item_instance_code, - item_name:item.item_name, - alt_name:item.alt_name, - account_id:item.account_id, - price:item.price - } - # item = OrderItem.where("item_instance_code = '#{promo_product}' and order_id = '#{orderitem[0][1]}'").first + + price = 0 + source = saleObj.orders.first.source + item = saleObj.order_items.where(item_instance_code: promo_product).first + if !item.nil? - # source = Order.find(item.order_id).source - update_existing_item(promotion_qty, item, sale_id, "promotion", item[:price],source) + update_existing_item(promotion_qty, item, saleObj, "promotion", item[:price],source) end end - - def self.update_existing_item(qty, item, sale_id, type, item_price,source) - if qty >0 + def self.update_existing_item(qty, item, saleObj, type, item_price,source) + if qty > 0 menu_category = MenuCategory.get_menu_category(item[:item_code]) #get menu category for menu items - + sale_item = SaleItem.new if !menu_category.nil? sale_item.menu_category_code = menu_category.code @@ -247,216 +155,85 @@ class Promotion < ApplicationRecord sale_item.price = qty * item_price * (-1) sale_item.is_taxable = 1 - sale_item.sale_id = sale_id + sale_item.sale = saleObj sale_item.save - sale = Sale.find(sale_id) - sale.compute_by_sale_items(sale.id, sale.sale_items, sale.total_discount,nil,source) - end - end - - - def self.give_promotion_nett_off(same, promo_product, foc_min_qty, orderitem, sale_id) - item ='' - source ='' - puts " same: " + same.to_s + " promo_product: " + promo_product.item_code.to_s + " foc_min_qty: " + foc_min_qty.to_s + " orderitem: " + orderitem.to_s - sale_order =SaleOrder.where("sale_id=?",sale_id) - if same - foc_qty = orderitem[:qty].to_i / foc_min_qty - # item = OrderItem.find_by_item_instance_code(orderitem[0][0]) - - price =0 - sale_order.each do|order| - source = Order.find(order.order_id).source - end - item = OrderItem.where("item_instance_code = ?",orderitem[:item_instance_code]).order("order_items_id DESC").first - item ={ - item_code:item.item_code, - item_instance_code:item.item_instance_code, - item_name:item.item_name, - alt_name:item.alt_name, - account_id:item.account_id, - price:item.price - } - # item = OrderItem.where("item_instance_code = '#{orderitem[0][0]}' and order_id = '#{orderitem[0][1]}'").first - if !item.nil? - # source = Order.find(item.order_id).source - update_existing_item(foc_qty, item, sale_id, "promotion nett off", promo_product.net_off,source) - end - else - foc_qty = orderitem[:qty].to_i / foc_min_qty - # foc_qty = find_second_item_qty(sale_id, promo_product.item_code) - # item = OrderItem.find_by_item_instance_code(promo_product.item_code) - # item = OrderItem.where("item_instance_code = '#{promo_product.item_code}' and order_id = '#{orderitem[0][1]}'").first - sale_order.each do|order| - source = Order.find(order.order_id).source - end - item = OrderItem.where("item_instance_code = ?",promo_product.item_code).order("order_items_id DESC").first - item ={ - item_code:item.item_code, - item_instance_code:item.item_instance_code, - item_name:item.item_name, - alt_name:item.alt_name, - account_id:item.account_id, - price:item.price - } - if !item.nil? - # source = Order.find(item.order_id).source - update_existing_item(foc_qty, item, sale_id, "promotion nett off", promo_product.net_off,source) - end - + saleObj.sale_items << sale_item + saleObj.compute_by_sale_items(saleObj.total_discount, nil, source) end end - def self.give_promotion_nett_price(same, promo_product, foc_min_qty, orderitem, sale_id) + + def self.give_promotion_nett_off(same, promo_product, foc_min_qty, orderitem, saleObj) puts " same: " + same.to_s + " promo_product: " + promo_product.item_code.to_s + " foc_min_qty: " + foc_min_qty.to_s + " orderitem: " + orderitem.to_s - sale_order =SaleOrder.where("sale_id=?",sale_id) - source ='' - item ='' - if same - foc_qty = orderitem[:qty].to_i / foc_min_qty - # item = OrderItem.find_by_item_instance_code(orderitem[0][0]) # need to specify with menu item instance - # item = OrderItem.where("item_instance_code = '#{orderitem[0][0]}' and order_id = '#{orderitem[0][1]}'").first - sale_order.each do|order| - source = Order.find(order.order_id).source - end - item = OrderItem.where("item_instance_code = ?",orderitem[:item_instance_code]).order("order_items_id DESC").first - item ={ - item_code:item.item_code, - item_instance_code:item.item_instance_code, - item_name:item.item_name, - alt_name:item.alt_name, - account_id:item.account_id, - price:item.price - } - if !item.nil? - price = item[:price].to_i - promo_product.net_price.to_i - # source = Order.find(item.order_id).source - update_existing_item(foc_qty, item, sale_id, "promotion nett price", price,source) - end - - else - order_qty = find_second_item_qty(sale_id, promo_product.item_code)# need to check for qty + + foc_qty = orderitem[:qty].to_i / foc_min_qty + if !same + order_qty = saleObj.qty_of(promo_product.item_code).qty rescue 0 foc_qty = orderitem[:qty].to_i / foc_min_qty if foc_qty > order_qty foc_qty = order_qty end - # item = OrderItem.find_by_item_instance_code(promo_product.item_code) - # item = OrderItem.where("item_instance_code = '#{promo_product.item_code}' and order_id = '#{orderitem[0][1]}'").first - sale_order.each do|order| - source = Order.find(order.order_id).source - end - item = OrderItem.where("item_instance_code",promo_product.item_code).order("order_items_id DESC").first - item ={ - item_code:item.item_code, - item_instance_code:item.item_instance_code, - item_name:item.item_name, - alt_name:item.alt_name, - account_id:item.account_id, - price:item.price - } + end - if !item.nil? - price = item[:price].to_i - promo_product.net_price.to_i - # source = Order.find(item.order_id).source - update_existing_item(foc_qty, item, sale_id, "promotion nett price", price,source) - end - + source = saleObj.orders.first.source + item = saleObj.order_items.where(item_instance_code: promo_product.item_code).first + + if !item.nil? + update_existing_item(foc_qty, item, saleObj, "promotion nett off", promo_product.net_off,source) end end - def self.give_promotion_discount(same, promo_product, foc_min_qty, orderitem, sale_id) + def self.give_promotion_nett_price(same, promo_product, foc_min_qty, orderitem, saleObj) puts " same: " + same.to_s + " promo_product: " + promo_product.item_code.to_s + " foc_min_qty: " + foc_min_qty.to_s + " orderitem: " + orderitem.to_s - sale_order =SaleOrder.where("sale_id=?",sale_id) - source ='' - item ='' - if same + + foc_qty = orderitem[:qty].to_i / foc_min_qty + if !same + order_qty = saleObj.qty_of(promo_product.item_code).qty rescue 0 foc_qty = orderitem[:qty].to_i / foc_min_qty - # item = OrderItem.find_by_item_instance_code(orderitem[0][0]) - # item = OrderItem.where("item_instance_code = '#{orderitem[0][0]}' and order_id = '#{orderitem[0][1]}'").first - sale_order.each do|order| - source = Order.find(order.order_id).source - end - item = OrderItem.where("item_instance_code = ?",orderitem[:item_instance_code]).order("order_items_id DESC").first - item ={ - item_code:item.item_code, - item_instance_code:item.item_instance_code, - item_name:item.item_name, - alt_name:item.alt_name, - account_id:item.account_id, - price:item.price - } - # total = orderitem[1].to_i * item.price - if !item.nil? - total = item[:price] - price = calculate_discount(total, promo_product.percentage) - # source = Order.find(item.order_id).source - update_existing_item(foc_qty, item, sale_id, "promotion discount", price,source) - end - - else - order_qty = find_second_item_qty(sale_id, promo_product.item_code) #need to check - foc_qty = orderitem[:qty].to_i / foc_min_qty - # give total qty is 1 - #foc_qty = (foc_qty - foc_qty) + 1 + if foc_qty > order_qty foc_qty = order_qty end - # item = OrderItem.find_by_item_instance_code(promo_product.item_code) - # item = OrderItem.where("item_instance_code = '#{promo_product.item_code}' and order_id = '#{orderitem[0][1]}'").first - sale_order.each do|order| - source = Order.find(order.order_id).source - end - item = OrderItem.where("item_instance_code = ?",promo_product.item_code).order("order_items_id DESC").first - item ={ - item_code:item.item_code, - item_instance_code:item.item_instance_code, - item_name:item.item_name, - alt_name:item.alt_name, - account_id:item.account_id, - price:item.price - } - # total = item.price * foc_qty - if !item.nil? - total = item[:price] - price = calculate_discount(total, promo_product.percentage) - # source = Order.find(item.order_id).source - update_existing_item(foc_qty, item, sale_id, "promotion discount", price,source) - end + end + + source = saleObj.orders.first.source + item = saleObj.order_items.where(item_instance_code: promo_product.item_code).first + + if !item.nil? + price = item[:price].to_i - promo_product.net_price.to_i + update_existing_item(foc_qty, item, saleObj, "promotion nett price", price,source) end end - def self.find_second_item_qty(sale_id, promo_item) - array_same =[] - saleObj = Sale.find_by_sale_id(sale_id) - itemList = combine_item(saleObj) - itemList.each do|list| - list.each do |l| - array_same.push({ - item_instance_code: l.item_instance_code, - order_id:l.order_id, - qty:l.qty - }) + def self.give_promotion_discount(same, promo_product, foc_min_qty, orderitem, saleObj) + puts " same: " + same.to_s + " promo_product: " + promo_product.item_code.to_s + " foc_min_qty: " + foc_min_qty.to_s + " orderitem: " + orderitem.to_s + + foc_qty = orderitem[:qty].to_i / foc_min_qty + if !same + order_qty = saleObj.qty_of(promo_product.item_code).qty rescue 0 + foc_qty = orderitem[:qty].to_i / foc_min_qty + + if foc_qty > order_qty + foc_qty = order_qty end end - item_list =[] - array_same.group_by do |same| - same.values_at :item_instance_code - end.map do |(item_instance_code), array_same| - quantities = array_same.map { |p| p[:qty] } - qty = quantities.all? ? quantities.reduce(:+) : nil - item_list.push({ item_instance_code: item_instance_code, qty: qty }) - end - item_list.each do |item| - if item[:item_instance_code] == promo_item.downcase - return item[:qty].to_i - end - end - return 0 - end - def self.calculate_discount(total, percentage) - return (total.to_i * percentage.to_i) / 100 - end + source = saleObj.orders.first.source + item = saleObj.order_items.where(item_instance_code: promo_product.item_code).first + puts saleObj + puts item + # total = orderitem[1].to_i * item.price + if item + total = item[:price] + price = calculate_discount(total, promo_product.percentage) + # source = Order.find(item.order_id).source + update_existing_item(foc_qty, item, saleObj, "promotion discount", price,source) + end + end + + def self.calculate_discount(total, percentage) + return (total * percentage) / 100 + end end diff --git a/app/models/sale.rb b/app/models/sale.rb index 8be79db3..98457d0e 100644 --- a/app/models/sale.rb +++ b/app/models/sale.rb @@ -14,14 +14,20 @@ class Sale < ApplicationRecord has_many :sale_payments has_many :sale_orders has_many :orders, through: :sale_orders + has_many :order_items, through: :sale_orders has_many :bookings has_many :product_commissions + before_validation :round_to_precision after_update :update_stock_journal scope :open_invoices, -> { where("sale_status = 'new' and receipt_date BETWEEN '#{DateTime.now.utc.end_of_day}' AND '#{DateTime.now.utc.beginning_of_day}'") } scope :complete_sale, -> { where("sale_status = 'completed' and receipt_date BETWEEN '#{DateTime.now.utc.beginning_of_day}' AND '#{DateTime.now.utc.end_of_day}'") } + def qty_of(item_instance_code) + order_items.select(:order_items_id, :item_instance_code, 'SUM(qty) as qty').where(item_instance_code: item_instance_code).group(:item_instance_code).first + end + REPORT_TYPE = { "daily" => 0, "monthly" => 1, @@ -355,8 +361,8 @@ class Sale < ApplicationRecord sale_item.save # Re-calc - sale = Sale.find(self.id) - self.compute_by_sale_items(self.id, sale.sale_items, self.total_discount, nil, order_source) + self.sale_items << sale_item + self.compute_by_sale_items(self.total_discount, nil, order_source) end def create_saleitem_indutycharges(chargeObj, current_checkin_induties_count, induties_pay_amount, dining_name, dining_time, order_source = nil, basic_pay_amount) sale_item = SaleItem.new @@ -374,8 +380,8 @@ class Sale < ApplicationRecord sale_item.price = induties_pay_amount sale_item.save # Re-calc - sale = Sale.find(self.id) - self.compute_by_sale_items(self.id, sale.sale_items, self.total_discount, nil, order_source) + self.sale_items << sale_item + self.compute_by_sale_items(self.total_discount, nil, order_source) end def update_item (item) #save sale_audit @@ -397,14 +403,12 @@ class Sale < ApplicationRecord #compute - invoice total def compute(order_source = nil, tax_type = nil) - sales_items = self.sale_items - #Computation Fields subtotal_price = 0 total_taxable = 0 rounding_adjustment = 0 - sales_items.each do |item| + self.sale_items.each do |item| #compute each item and added to total subtotal_price = subtotal_price + item.price @@ -418,66 +422,59 @@ class Sale < ApplicationRecord apply_tax(total_taxable, order_source, tax_type) self.total_amount = subtotal_price - self.total_discount = total_discount + # self.total_discount = total_discount self.grand_total = (self.total_amount - self.total_discount) + self.total_tax - self.grand_total_round + # self.grand_total_round #compute rounding adjustment - adjust_rounding - + # adjust_rounding self.save! - end #compute - invoice total - def compute_by_sale_items(sale_id, sale_itemss, total_discount,discount_type=nil,order_source=nil,tax_type=nil,type=nil) + def compute_by_sale_items(total_discount, discount_type=nil, order_source=nil, tax_type=nil, type=nil) shop = Shop.first - sale = Sale.find(sale_id) - sales_items = sale_itemss #Computation Fields subtotal_price = 0 total_taxable = 0 rounding_adjustment = 0 - sales_items.each do |item| + self.sale_items.each do |item| #compute each item and added to total - subtotal_price = subtotal_price + item.price + subtotal_price = subtotal_price + item.price # check for item is taxable and calculate if item.is_taxable total_taxable = total_taxable + item.taxable_price end end - compute_tax(sale, total_taxable, total_discount, order_source, tax_type) - sale.total_amount = subtotal_price - sale.total_discount = total_discount + + compute_tax(total_taxable, total_discount, order_source, tax_type) + self.total_amount = subtotal_price + self.total_discount = total_discount if type =="foc" - sale.grand_total = 0 + self.grand_total = 0 else - sale.grand_total = (sale.total_amount - sale.total_discount) + sale.total_tax - sale.grand_total_round + self.grand_total = (self.total_amount - self.total_discount) + self.total_tax + # sale.grand_total_round end if discount_type == "member_discount" - sale.discount_type = discount_type + self.discount_type = discount_type end #compute rounding adjustment # adjust_rounding - sale.rounding_adjustment = compute_adjust_rounding(sale.grand_total) - - sale.save! + self.save! end # No Use too many wrong def compute_without_void(order_source = nil) - sales_items = self.sale_items - #Computation Fields subtotal_price = 0 total_taxable = 0 rounding_adjustment = 0 - sales_items.each do |item| + self.sale_items.each do |item| if item.status != 'void' && item.status != 'foc' #compute each item and added to total subtotal_price = subtotal_price + item.price @@ -491,17 +488,17 @@ class Sale < ApplicationRecord apply_tax(total_taxable, order_source) self.total_amount = subtotal_price - self.total_discount = total_discount + # self.total_discount = total_discount self.grand_total = (self.total_amount - self.total_discount) + self.total_tax - self.grand_total_round + # self.grand_total_round #compute rounding adjustment - adjust_rounding + # adjust_rounding self.save! end # Tax Re-Calculte - def compute_tax(sale, total_taxable, total_discount = 0, order_source = nil, tax_type=nil) + def compute_tax(total_taxable, total_discount = 0, order_source = nil, tax_type=nil) shop = Shop.first #if tax is not apply create new record @@ -509,93 +506,49 @@ class Sale < ApplicationRecord # #delete existing and create new # existing_tax.delete # end - taxes = SaleTax.where("sale_id='#{sale.sale_id}'").pluck(:sale_tax_id) - SaleTax.where("sale_tax_id IN (?)", taxes).destroy_all + taxes = SaleTax.where("sale_id='#{self.sale_id}'").destroy_all total_tax_amount = 0 tax_incl_exec = "exclusive" #tax_profile - list by order_by # tax_profiles = TaxProfile.all.order("order_by asc") # customer = Customer.find(sale.customer_id) - arr_tax = [] - arr_tax = unique_tax_profiles(order_source, self.customer_id) - if !arr_tax.empty? - if tax_type.nil? - tax_profiles = TaxProfile.where(:id => arr_tax) - else - tax_profiles = TaxProfile.where("group_type=?",order_source) - end - else - tax_profiles = TaxProfile.where("group_type=?",order_source) - end - - # #Creat new tax records if order_source.to_s == "emenu" order_source = "cashier" end - if sale.payment_status != 'foc' + tax_profiles = unique_tax_profiles(order_source, self.customer_id) + + # #Creat new tax records + if self.payment_status != 'foc' tax_profiles.each do |tax| - if tax.group_type.to_s == order_source.to_s - if tax_type - if tax_type.to_s == tax.name.to_s || tax_type == 'all' - sale_tax = SaleTax.new(:sale => sale) - sale_tax.tax_name = tax.name - sale_tax.tax_rate = tax.rate + sale_tax = SaleTax.new(:sale => self) + sale_tax.tax_name = tax.name + sale_tax.tax_rate = tax.rate - # substract , to give after discount - total_tax = total_taxable - total_discount - #include or execulive - if tax.inclusive - tax_incl_exec = "inclusive" - rate = tax.rate - divided_value = (100 + rate)/rate - sale_tax.tax_payable_amount = total_tax / divided_value - else - sale_tax.tax_payable_amount = total_tax * tax.rate / 100 - total_tax_amount = total_tax_amount + sale_tax.tax_payable_amount - end - #new taxable amount is standard rule for step by step - if shop.calc_tax_order - total_taxable = total_taxable + sale_tax.tax_payable_amount - end - sale_tax.inclusive = tax.inclusive - sale_tax.save - end - else - # customer.tax_profiles.each do |cus_tax| - # if cus_tax.to_i == tax.id - sale_tax = SaleTax.new(:sale => sale) - sale_tax.tax_name = tax.name - sale_tax.tax_rate = tax.rate - - # substract , to give after discount - total_tax = total_taxable - total_discount - #include or execulive - if tax.inclusive - tax_incl_exec = "inclusive" - rate = tax.rate - divided_value = (100 + rate)/rate - sale_tax.tax_payable_amount = total_tax / divided_value - else - sale_tax.tax_payable_amount = total_tax * tax.rate / 100 - total_tax_amount = total_tax_amount + sale_tax.tax_payable_amount - end - #new taxable amount is standard rule for step by step - if shop.calc_tax_order - total_taxable = total_taxable + sale_tax.tax_payable_amount - end - sale_tax.inclusive = tax.inclusive - sale_tax.save - # end - # end - end + # substract , to give after discount + total_tax = total_taxable - total_discount + #include or execulive + if tax.inclusive + tax_incl_exec = "inclusive" + rate = tax.rate + divided_value = (100 + rate)/rate + sale_tax.tax_payable_amount = total_tax / divided_value + else + sale_tax.tax_payable_amount = total_tax * tax.rate / 100 + total_tax_amount = total_tax_amount + sale_tax.tax_payable_amount end + #new taxable amount is standard rule for step by step + if shop.calc_tax_order + total_taxable = total_taxable + sale_tax.tax_payable_amount + end + sale_tax.inclusive = tax.inclusive + sale_tax.save end end - sale.tax_type = tax_incl_exec - sale.total_tax = total_tax_amount + self.tax_type = tax_incl_exec + self.total_tax = total_tax_amount end # Tax Calculate @@ -608,8 +561,7 @@ class Sale < ApplicationRecord # existing_tax.delete # end - taxes = SaleTax.where("sale_id='#{self.sale_id}'").pluck(:sale_tax_id) - SaleTax.where("sale_tax_id IN (?)", taxes).destroy_all + taxes = SaleTax.where("sale_id='#{self.sale_id}'").destroy_all total_tax_amount = 0 tax_incl_exec = "exclusive" @@ -622,77 +574,34 @@ class Sale < ApplicationRecord # tax_data = TaxProfile.unscoped.where("group_type=?",order_source).pluck(:id) # customer = Customer.find(self.customer_id).tax_profiles - arr_tax = [] - arr_tax = unique_tax_profiles(order_source, self.customer_id) + tax_profiles = unique_tax_profiles(order_source, self.customer_id) - if !arr_tax.empty? - if tax_type.nil? - tax_profiles = TaxProfile.where(:id => arr_tax) - else - tax_profiles = TaxProfile.where("group_type=?",order_source) - end - else - tax_profiles = TaxProfile.where("group_type=?",order_source) - end #Create new tax records tax_profiles.each do |tax| - if tax.group_type.to_s == order_source.to_s - if tax_type - if tax_type.to_s == tax.name.to_s || tax_type == 'all' - sale_tax = SaleTax.new(:sale => self) - sale_tax.tax_name = tax.name - sale_tax.tax_rate = tax.rate + sale_tax = SaleTax.new(:sale => self) + sale_tax.tax_name = tax.name + sale_tax.tax_rate = tax.rate - # substract , to give after discount - total_tax = total_taxable - total_discount - #include or execulive - if tax.inclusive - tax_incl_exec = "inclusive" - rate = tax.rate - divided_value = (100 + rate)/rate - sale_tax.tax_payable_amount = total_tax / divided_value - else - sale_tax.tax_payable_amount = total_tax * tax.rate / 100 - total_tax_amount = total_tax_amount + sale_tax.tax_payable_amount - end - #new taxable amount is standard rule for step by step - if shop.calc_tax_order - total_taxable = total_taxable + sale_tax.tax_payable_amount - end - sale_tax.inclusive = tax.inclusive - sale_tax.save - end - else - # customer.tax_profiles.each do |cus_tax| - # if cus_tax.to_i == tax.id - sale_tax = SaleTax.new(:sale => self) - sale_tax.tax_name = tax.name - sale_tax.tax_rate = tax.rate - - # substract , to give after discount - total_tax = total_taxable - self.total_discount - #include or execulive - if tax.inclusive - tax_incl_exec = "inclusive" - rate = tax.rate - divided_value = (100 + rate)/rate - sale_tax.tax_payable_amount = total_tax / divided_value - else - sale_tax.tax_payable_amount = total_tax * tax.rate / 100 - total_tax_amount = total_tax_amount + sale_tax.tax_payable_amount - end - - #new taxable amount is standard rule for step by step - if shop.calc_tax_order - total_taxable = total_taxable + sale_tax.tax_payable_amount - end - - sale_tax.inclusive = tax.inclusive - sale_tax.save - # end - # end - end + # substract , to give after discount + total_tax = total_taxable - self.total_discount + #include or execulive + if tax.inclusive + tax_incl_exec = "inclusive" + rate = tax.rate + divided_value = (100 + rate)/rate + sale_tax.tax_payable_amount = total_tax / divided_value + else + sale_tax.tax_payable_amount = total_tax * tax.rate / 100 + total_tax_amount = total_tax_amount + sale_tax.tax_payable_amount end + + #new taxable amount is standard rule for step by step + if shop.calc_tax_order + total_taxable = total_taxable + sale_tax.tax_payable_amount + end + + sale_tax.inclusive = tax.inclusive + sale_tax.save end self.tax_type = tax_incl_exec self.total_tax = total_tax_amount @@ -727,42 +636,16 @@ class Sale < ApplicationRecord shop_details = Shop.first # rounding adjustment if shop_details.is_rounding_adj - a = self.grand_total % 25 # Modulus - b = self.grand_total / 25 # Division - #not calculate rounding if modulus is 0 and division is even - #calculate rounding if modulus is zero or not zero and division are not even - if (a != 0.0 && b%2 != 0.0) || (a==0.0 && b%2 !=0) - new_total = Sale.get_rounding_adjustment(self.grand_total) - self.rounding_adjustment = new_total - self.grand_total - else - self.rounding_adjustment = 0.00 - end + new_total = Sale.get_rounding_adjustment(self.grand_total) + self.rounding_adjustment = new_total - self.grand_total + self.old_grand_total = self.grand_total + self.grand_total = new_total else self.rounding_adjustment = 0.00 end end - def compute_adjust_rounding(grand_total) - shop_details = Shop.first - # rounding adjustment - if shop_details.is_rounding_adj - a = grand_total % 25 # Modulus - b = grand_total / 25 # Division - #not calculate rounding if modulus is 0 and division is even - #calculate rounding if modulus is zero or not zero and division are not even - if (a != 0.0 && b%2 != 0.0) || (a==0.0 && b%2 !=0) - new_total = Sale.get_rounding_adjustment(grand_total) - rounding_adjustment = new_total - grand_total - else - rounding_adjustment = 0.00 - end - else - rounding_adjustment = 0.00 - end - return rounding_adjustment - end - #Generate new Receipt No when it is not assigned def generate_receipt_no #shop_code and client_code @@ -857,115 +740,69 @@ class Sale < ApplicationRecord # if get_rounded_amt == true value = 0 - num = num.to_f.round - get_last_no = num.to_s.last(2).to_f - if get_last_no.between?(0,25) - ## down to 0 - num -= get_last_no - else - if get_last_no.between?(26,50) - ## up to 50 - value = 50 - get_last_no.to_f - num += value - puts 'up to 50' - else - if get_last_no.between?(51, 75) - ## down to 50 - value = get_last_no.to_f - 50 - num -= value - puts 'down to 50' - else - ## up to 100 - value = 100 - get_last_no.to_f - num += value - puts 'up to 100' - end - end + # num = num.to_f.round + mod = num % 50 + if mod > 0 && mod <= 25 + num -= mod + elsif mod > 25 + num += 50 - mod end - # end return num end - def self.daily_sales_list(from,to) - sub_query = "SELECT (CASE WHEN SUM(sale_payments.payment_amount) > 0 THEN - (SUM(sale_payments.payment_amount) + SUM(sale_payments.outstanding_amount)) ELSE 0 END) - FROM sale_payments - INNER JOIN sale_audits sa ON SUBSTRING_INDEX(sa.remark,'||',1)=sale_payments.sale_payment_id - INNER JOIN sales s ON s.sale_id=sa.sale_id - WHERE s.sale_status='completed' - AND DATE_FORMAT(CONVERT_TZ(s.receipt_date,'+00:00','+06:30'),'%Y-%m-%d') = DATE_FORMAT(CONVERT_TZ(sales.receipt_date,'+00:00','+06:30'),'%Y-%m-%d')" + sales = select(" + sales.*, + SUM(case when (sale_payments.payment_method='KBZPay') then sale_payments.payment_amount else 0 end) as kbzpay_amount, + SUM(case when (sale_payments.payment_method='mpu') then sale_payments.payment_amount else 0 end) as mpu_amount, + SUM(case when (sale_payments.payment_method='master') then sale_payments.payment_amount else 0 end) as master_amount, + SUM(case when (sale_payments.payment_method='visa') then sale_payments.payment_amount else 0 end) as visa_amount, + SUM(case when (sale_payments.payment_method='jcb') then sale_payments.payment_amount else 0 end) as jcb_amount, + SUM(case when (sale_payments.payment_method='paypar') then sale_payments.payment_amount else 0 end) as paypar_amount, + SUM(case when (sale_payments.payment_method='unionpay') then sale_payments.payment_amount else 0 end) as unionpay_amount, + SUM(case when (sale_payments.payment_method='alipay') then sale_payments.payment_amount else 0 end) as alipay_amount, + SUM(case when (sale_payments.payment_method='paymal') then sale_payments.payment_amount else 0 end) as paymal_amount, + SUM(case when (sale_payments.payment_method='dinga') then sale_payments.payment_amount else 0 end) as dinga_amount, + SUM(case when (sale_payments.payment_method='JunctionPay') then sale_payments.payment_amount else 0 end) as junctionpay_amount, + SUM(case when (sale_payments.payment_method='cash') then sale_payments.payment_amount else 0 end) as cash_amount, + CASE WHEN SUM(case when sale_payments.payment_method not in('creditnote') then sale_payments.payment_amount end) < sales.grand_total + THEN sales.grand_total - SUM(case when sale_payments.payment_method not in('creditnote') then sale_payments.payment_amount end) + ELSE 0 END as credit_amount, + SUM(case when (sale_payments.payment_method='giftvoucher') then sale_payments.payment_amount else 0 end) as giftvoucher_amount, + SUM(case when (sale_payments.payment_method='foc') then sale_payments.payment_amount else 0 end) as foc_amount") + .joins("LEFT JOIN sale_payments on sales.sale_status != 'void' AND sale_payments.sale_id = sales.sale_id AND DATE(CONVERT_TZ(sale_payments.created_at,'+00:00','+06:30')) = DATE(CONVERT_TZ(sales.receipt_date,'+00:00','+06:30'))") + .where("(sale_status = ? OR sale_status = ?) AND sales.receipt_date between ? AND ? ", 'completed', 'void', from, to) + .group("sale_id").to_sql - payments_total = Sale.select("CAST((CONVERT_TZ(sales.receipt_date,'+00:00','+06:30')) AS DATE) as sale_date, - SUM(case when (sale_payments.payment_method='KBZPay') then sale_payments.payment_amount else 0 end) as kbzpay_amount, - SUM(case when (sale_payments.payment_method='mpu') then sale_payments.payment_amount else 0 end) as mpu_amount, - SUM(case when (sale_payments.payment_method='master') then sale_payments.payment_amount else 0 end) as master_amount, - SUM(case when (sale_payments.payment_method='visa') then sale_payments.payment_amount else 0 end) as visa_amount, - SUM(case when (sale_payments.payment_method='jcb') then sale_payments.payment_amount else 0 end) as jcb_amount, - SUM(case when (sale_payments.payment_method='paypar') then sale_payments.payment_amount else 0 end) as paypar_amount, - SUM(case when (sale_payments.payment_method='unionpay') then sale_payments.payment_amount else 0 end) as unionpay_amount, - SUM(case when (sale_payments.payment_method='alipay') then sale_payments.payment_amount else 0 end) as alipay_amount, - SUM(case when (sale_payments.payment_method='paymal') then sale_payments.payment_amount else 0 end) as paymal_amount, - SUM(case when (sale_payments.payment_method='dinga') then sale_payments.payment_amount else 0 end) as dinga_amount, - SUM(case when (sale_payments.payment_method='JunctionPay') then sale_payments.payment_amount else 0 end) as junctionpay_amount, - SUM(case when (sale_payments.payment_method='cash') then sale_payments.payment_amount else 0 end) as cash_amount, - (CASE WHEN (SUM(case when (sale_payments.payment_method='creditnote') then sale_payments.payment_amount else 0 end)) > 0 THEN (SUM(case when (sale_payments.payment_method='creditnote') then sale_payments.payment_amount else 0 end) - (#{sub_query})) ELSE 0 END) as credit_amount, - SUM(case when (sale_payments.payment_method='giftvoucher') then sale_payments.payment_amount else 0 end) as giftvoucher_amount, - SUM(case when (sale_payments.payment_method='foc') then sale_payments.payment_amount else 0 end) as foc_amount") - .joins(" join sale_payments on sale_payments.sale_id = sales.sale_id") - .where("sale_status = ? AND sales.receipt_date between ? and ? ", 'completed', from, to) - .group("DATE_FORMAT((CONVERT_TZ(sales.receipt_date,'+00:00','+06:30')),'%Y-%m-%d')") + daily_total = connection.select_all("SELECT + IFNULL(SUM(case when (sale_status='completed') then grand_total else 0 end),0) as grand_total, + IFNULL(SUM(case when (sale_status='completed') then old_grand_total else 0 end),0) as old_grand_total, + IFNULL(SUM(case when (sale_status='completed') then total_discount else 0 end),0) as total_discount, + IFNULL(SUM(case when (sale_status='completed') then amount_changed else 0 end),0) as total_change_amount, + IFNULL(SUM(case when (sale_status='void') then grand_total else 0 end),0) as void_amount, + IFNULL(SUM(case when (sale_status='completed') then rounding_adjustment else 0 end),0) as rounding_adj, + CAST((CONVERT_TZ(receipt_date,'+00:00','+06:30')) AS DATE) as sale_date, + SUM(kbzpay_amount) as kbzpay_amount, + SUM(mpu_amount) as mpu_amount, + SUM(master_amount) as master_amount, + SUM(visa_amount) as visa_amount, + SUM(jcb_amount) as jcb_amount, + SUM(paypar_amount) as paypar_amount, + SUM(unionpay_amount) as unionpay_amount, + SUM(alipay_amount) as alipay_amount, + SUM(paymal_amount) as paymal_amount, + SUM(dinga_amount) as dinga_amount, + SUM(junctionpay_amount) as junctionpay_amount, + SUM(cash_amount) as cash_amount, + SUM(credit_amount) as credit_amount, + SUM(giftvoucher_amount) as giftvoucher_amount, + SUM(foc_amount) as foc_amount + FROM ( + #{sales} + ) as s + GROUP BY DATE(CONVERT_TZ(receipt_date,'+00:00','+06:30'))").to_hash.map(&:symbolize_keys) - daily_total = Array.new - - payments_total.each do |pay| - sale_date = pay.sale_date - diff_time = payments_total.first.sale_date.beginning_of_day.utc - from - diff = diff_time % 86400 - from_date = sale_date.beginning_of_day.utc - diff - to_date = sale_date.end_of_day.utc - diff - - total_sale = Sale.select("IFNULL(SUM(case when (sale_status='completed') then grand_total else 0 end),0) as grand_total, - IFNULL(SUM(case when (sale_status='completed') then old_grand_total else 0 end),0) as old_grand_total, - IFNULL(SUM(case when (sale_status='completed') then total_discount else 0 end),0) as total_discount, - IFNULL(SUM(case when (sale_status='completed') then amount_changed else 0 end),0) as total_change_amount, - IFNULL(SUM(case when (sale_status='void') then grand_total else 0 end),0) as void_amount, - IFNULL(SUM(case when (sale_status='completed') then rounding_adjustment else 0 end),0) as rounding_adj") - .where("(sale_status = ? OR sale_status = ?) AND receipt_date between ? and ? AND total_amount != 0", 'completed', 'void', from_date, to_date) - - total_sale.each do |sale| - grand_total = sale.grand_total - old_grand_total = sale.old_grand_total - total_discount = sale.total_discount - void_amount = sale.void_amount - total_change_amount = sale.total_change_amount - total = {:sale_date => pay.sale_date, - :mpu_amount => pay.mpu_amount, - :master_amount => pay.master_amount, - :visa_amount => pay.visa_amount, - :jcb_amount => pay.jcb_amount, - :paypar_amount => pay.paypar_amount, - :unionpay_amount => pay.unionpay_amount, - :alipay_amount => pay.alipay_amount, - :kbzpay_amount => pay.kbzpay_amount, - :paymal_amount => pay.paymal_amount, - :dinga_amount => pay.dinga_amount, - :junctionpay_amount => pay.junctionpay_amount, - :cash_amount => pay.cash_amount, - :credit_amount => pay.credit_amount, - :foc_amount => pay.foc_amount, - :giftvoucher_amount => pay.giftvoucher_amount, - :total_discount => total_discount, - :total_change_amount => total_change_amount, - :grand_total => grand_total, - :old_grand_total => old_grand_total, - :void_amount => void_amount, - :rounding_adj => sale.rounding_adj} - daily_total.push(total) - end - - end - return daily_total + return daily_total end def self.get_by_range_by_saleitems(from,to,status,report_type) @@ -1267,73 +1104,64 @@ def self.get_shift_sales_by_receipt_no_detail(shift_sale_range,shift,from,to,pay end def self.get_by_shift_sale_credit_payment(shift_sale_range,shift,from,to,filter,order_source) - sub_query = "SELECT (CASE WHEN SUM(payment_amount) > 0 - THEN DATE_FORMAT(CONVERT_TZ(sale_payments.created_at,'+00:00','+06:30'),'%d %b %y %h:%i%p') ELSE '-' END) - FROM `sale_payments` - INNER JOIN sale_audits ON SUBSTRING_INDEX(sale_audits.remark,'||',1)=sale_payments.sale_payment_id - WHERE sale_audits.sale_id = s.sale_id" + order_sources = Order.select("sale_orders.sale_id, orders.source") + .joins(:sale_orders).to_sql - sub_query1 = "SELECT (CASE WHEN SUM(payment_amount) > 0 THEN SUM(payment_amount) - - (SUM(payment_amount) - (SELECT SUM(payment_amount) FROM sale_payments WHERE payment_method='creditnote' AND sale_id=s.sale_id)) ELSE 0 END) - FROM `sale_payments` - INNER JOIN sale_audits ON SUBSTRING_INDEX(sale_audits.remark,'||',1)=sale_payments.sale_payment_id - WHERE sale_audits.sale_id = s.sale_id" + credit_payments = SalePayment.select(" + sales.sale_id, + DATE_FORMAT(CONVERT_TZ(sale_payments.created_at,'+00:00','+06:30'),'%d %b %y %h:%i%p') as credit_payment_receipt_date, + sale_payments.payment_amount as credit_payment, + employees.name as credit_payment_cashier_name, + CONCAT(DATE_FORMAT(CONVERT_TZ(shift_started_at,'+00:00','+06:30'),'%d %b %y %h:%i%p'),' - ',DATE_FORMAT(CONVERT_TZ(shift_closed_at,'+00:00','+06:30'),'%d %b %y %h:%i%p')) as credit_payment_shift_name") + .joins("JOIN sales ON sales.sale_id = sale_payments.sale_id") + .joins("JOIN sale_audits ON sale_audits.sale_id = sales.sale_id AND SUBSTRING_INDEX(sale_audits.remark,'||',1)=sale_payments.sale_payment_id") + .joins("JOIN shift_sales ON shift_sales.id = sales.shift_sale_id") + .joins("JOIN employees ON employees.id = shift_sales.employee_id").to_sql - sub_query2 = "SELECT (CASE WHEN shift_closed_at IS NOT NULL AND credit_payment > 0 - THEN CONCAT(DATE_FORMAT(CONVERT_TZ(shift_started_at,'+00:00','+06:30'),'%d %b %y %h:%i%p'),' - ',DATE_FORMAT(CONVERT_TZ(shift_closed_at,'+00:00','+06:30'),'%d %b %y %h:%i%p')) - ELSE '-' END) - FROM shift_sales - WHERE shift_sales.id = s.shift_sale_id" + credits = SalePayment.select(" + sale_payments.sale_payment_id, + sale_payments.payment_method, + sale_payments.payment_amount, + sale_payments.payment_status, + sales.sale_id, + sales.receipt_no, + sales.receipt_date as sale_date, + order_sources.source as order_source, + sales.cashier_name, + customers.name as customer_name, + IFNULL(credit_payments.credit_payment_receipt_date, '-') as credit_payment_receipt_date, + IFNULL(credit_payments.credit_payment, 0) as credit_payment, + IFNULL(credit_payments.credit_payment_cashier_name, '-') as credit_payment_cashier_name, + IFNULL(credit_payments.credit_payment_shift_name, '-') as credit_payment_shift_name") + .joins("JOIN sales ON sales.sale_id = sale_payments.sale_id") + .joins("JOIN shift_sales ON shift_sales.id = sales.shift_sale_id") + .joins("JOIN customers ON customers.customer_id = sales.customer_id") + .joins("JOIN (#{order_sources}) order_sources ON order_sources.sale_id = sales.sale_id") + .joins("LEFT JOIN (#{credit_payments}) credit_payments ON credit_payments.sale_id = sales.sale_id") + .where("sale_payments.payment_method= ? AND sales.sale_status = ?", 'creditnote', 'completed') - sub_query3 = "SELECT (CASE WHEN shift_closed_at IS NOT NULL OR shift_closed_at IS NULL AND credit_payment > 0 - THEN employees.name ELSE '-' END) - FROM shift_sales - INNER JOIN employees ON employees.id=shift_sales.employee_id - WHERE shift_sales.id = s.shift_sale_id" - - filter_check = "" - if filter == 'paid' - filter_check = " AND (SELECT (CASE WHEN SUM(payment_amount) > 0 THEN SUM(payment_amount) ELSE 0 END) - FROM `sale_payments` - INNER JOIN sale_audits ON SUBSTRING_INDEX(sale_audits.remark,'||',1)=sale_payments.sale_payment_id - WHERE sale_audits.sale_id = s.sale_id) > 0" - elsif filter == 'unpaid' - filter_check = " AND (SELECT (CASE WHEN SUM(payment_amount) > 0 THEN SUM(payment_amount) ELSE 0 END) - FROM `sale_payments` - INNER JOIN sale_audits ON SUBSTRING_INDEX(sale_audits.remark,'||',1)=sale_payments.sale_payment_id - WHERE sale_audits.sale_id = s.sale_id) = 0" - end - order_source_query = "(select orders.source FROM orders JOIN sale_orders so ON so.order_id=orders.order_id WHERE so.sale_id=s.sale_id GROUP BY so.sale_id)" - - if order_source.blank? - source = "" - else + if order_source.present? if order_source == "cashier" - source = "and #{order_source_query}='cashier' or #{order_source_query}='emenu'" + credits = credits.where("order_sources.source IN (?)", ['cashier', 'emenu']) else - source = "and #{order_source_query}='#{order_source}'" + credits = credits.where("order_sources.source = ?", order_source) end end - query = SalePayment.select("s.receipt_no, sale_payments.*, - SUM(sale_payments.payment_amount) as payment_amount, - s.receipt_date as sale_date, - #{order_source_query} as order_source, - s.cashier_name as cashier_name, - (#{sub_query}) as credit_payment_receipt_date, - (#{sub_query1}) as credit_payment, - (#{sub_query3}) as credit_payment_cashier_name, - (#{sub_query2}) as credit_payment_shift_name") - .joins("INNER JOIN sales s ON s.sale_id = sale_payments.sale_id") - .joins("INNER JOIN shift_sales ss ON ss.id = s.shift_sale_id") + + if filter == 'paid' + credits = credits.where("credit_payment IS NOT NULL") + elsif filter == 'unpaid' + credits = credits.where("credit_payment IS NULL") + end if shift.present? - query = query.where("sale_payments.payment_method= 'creditnote' and s.sale_status = 'completed' #{filter_check} and s.shift_sale_id in (?) #{source}",shift.to_a) + credits = credits.where("sales.shift_sale_id in (?)",shift.to_a) elsif shift_sale_range.present? - query = query.where("sale_payments.payment_method='creditnote' and s.sale_status = 'completed' #{filter_check} and s.shift_sale_id in (?) #{source}",shift_sale_range.to_a) + credits = credits.where("sales.shift_sale_id in (?)",shift_sale_range.to_a) else - query = query.where("sale_payments.payment_method='creditnote' and s.sale_status = 'completed' #{filter_check} and s.receipt_date between ? and ? #{source}",from,to) + credits = credits.where("sales.receipt_date between ? and ?",from,to) end - query = query.group("s.sale_id") + credits = credits.group("sales.sale_id") end def self.get_void_sale(shift,from,to) @@ -2646,20 +2474,15 @@ def self.get_sale_data_for_other_payment_credit(sale_id) end def unique_tax_profiles(order_source, customer_id) - tax_data = TaxProfile.where("group_type='#{order_source}'").pluck(:id) - customer_tax_profiles = Customer.find(customer_id).tax_profiles + tax_data = TaxProfile + .where(group_type: order_source) - arr_data = [] - if !customer_tax_profiles.empty? - customer_tax_profiles.each do |value1| - if tax_data.include? value1.to_i - arr_data.push(value1.to_i) - end - end - return arr_data - else - return tax_data + customer_tax_profiles = Customer.select(:tax_profiles).where(customer_id: customer_id).first + if customer_tax_profiles.present? + tax_data = tax_data.where(id: customer_tax_profiles.tax_profiles) end + + return tax_data end def self.top_bottom(today,shift=nil,from=nil,to=nil,from_time=nil,to_time=nil) @@ -2861,7 +2684,7 @@ def self.get_hourly_item_query(type) "i.status as status_type,i.remark as remark,"+ "i.unit_price,i.price as price,i.product_name as product_name, " + "i.menu_category_name,i.menu_category_code as menu_category_id, " + - + "concat(hour(CONVERT_TZ(receipt_date,'+00:00', '+06:30')), ':00 - ', hour(CONVERT_TZ(receipt_date,'+00:00', '+06:30')) + 1, ':00') as date_format," + "hour(CONVERT_TZ(receipt_date,'+00:00', '+06:30')) as hour") @@ -2885,6 +2708,139 @@ def grand_total_round self.grand_total =self.grand_total.round(print_settings.precision.to_i) end end + +# Loader Service SFTP Start +def self.get_load_sale_range(load_time_start,load_time_end) + query = Sale.select("sales.sale_id, + CONVERT(receipt_date, TIME) as transaction_time, + CONVERT(receipt_date, DATE) as transaction_date, + receipt_no as transaction_no, + SUM(i.qty) as item_no, + 'MMK' as currency_salesamount, + IFNULL((total_amount-total_discount)-((total_amount-total_discount)/21),0) as total_salesamount, + IFNULL(amount_changed,0) as change_amt, + IFNULL(total_amount-total_discount,0) as grand_salesamount, + '5' as tax_percent, + 'MMK' as currency_payment, + IFNULL(amount_received,0) as paymentamount, + sp.payment_amount as payment_method, + CASE + WHEN sales.sale_status='completed' THEN 'Sales' + WHEN sales.sale_status='void' THEN 'Void' + END as sale_type, + sales.updated_at as load_time") + .joins("JOIN sale_items i ON i.sale_id = sales.sale_id" + + " JOIN sale_payments sp ON sp.sale_id = sales.sale_id") + .where("(sale_status=? OR sale_status=?) AND sp.payment_method !=? AND sales.updated_at between ? AND ?", 'completed', 'void', 'foc', load_time_start, load_time_end) + .group("receipt_no") + .order("receipt_date") +end + +def self.get_tender_sale_data(transaction_date) + query = Sale.select("sales.receipt_no as check_num, + DATE_FORMAT(sales.receipt_date, '%d %b %Y') as business_date, + sales.receipt_date as transaction_date, + '36017' as item_id, + 'Cash Received' as item_name, + '1' as qty, + 'Tender' as transaction_type, + '0' as sales, + CASE WHEN sales.sale_status = 'void' THEN '1' ELSE '0' END as is_void + ") + .where("DATE(sales.receipt_date)=? AND sales.sale_status != ?", transaction_date, :void) + .order("sales.receipt_no") +end + +def self.get_daily_sale_data(transaction_date) + query = Sale.connection.select_all("SELECT s.receipt_date as business_date, + (SUM(s.grand_total)+SUM(s.total_discount)) as gross_sales, + SUM(s.total_discount) as discount, + SUM(s.grand_total) as sales, + SUM(s.grand_total)/21 as tax, + 0 as service_charge, + SUM(s.grand_total) - (SUM(s.grand_total)/21) as net_sales, + SUM(s.credit_amount) as credit_amount, + SUM(s.voucher_sales) as voucher_sales, + 0 as staff_meal_amt, + 0 as round_amt, + 0 as raw_wastage_amt, + 0 as semi_wastage_amt, + CASE WHEN s.sale_status='waste' THEN SUM(s.total_amount) ELSE 0 END as wastage_amt, + CASE WHEN s.sale_status='spoile' THEN SUM(s.total_amount) ELSE 0 END as spoilage_amt, + 0 as sampling_amt, + 0 as other_amt, + SUM(s.qty) as total_qty, + (SELECT COUNT(sales.sale_id) FROM sales WHERE DATE(sales.receipt_date)='#{transaction_date}') as total_transaction, + (SELECT COUNT(sales.sale_id) FROM sales WHERE (sales.sale_status='completed' OR sales.sale_status='void') AND DATE(sales.receipt_date)='#{transaction_date}') as valid_transaction_count, + (SELECT COUNT(sales.sale_id) FROM sales WHERE (sales.sale_status IN('new','pending',null)) AND DATE(sales.receipt_date)='#{transaction_date}') as invalid_transaction_count, + 0 as overing_transaction_count, + 0 as cancle_transaction_count, + 0 as no_of_pax, + 0 as no_of_adult, + 0 as no_of_child + FROM ( + SELECT s.*, SUM(qty) as qty + FROM ( + SELECT sales.*, + SUM(CASE WHEN sp.payment_method IN('mpu','master','visa','jcb','unionpay','alipay') THEN sp.payment_amount ELSE 0 END) as credit_amount, + SUM(case when (sp.payment_method='giftvoucher') then sp.payment_amount else 0 end) as voucher_sales + FROM sales + LEFT JOIN sale_payments sp ON sp.sale_id = sales.sale_id + WHERE DATE(sales.receipt_date) = '#{transaction_date}' + AND sales.sale_status!='void' + AND sales.sale_status='completed' + GROUP BY sales.sale_id) AS s + LEFT JOIN sale_items si ON si.sale_id = s.sale_id + GROUP BY s.sale_id) as s + GROUP BY DATE(s.receipt_date)").to_hash + end + +def self.get_check_sale_data(transaction_date) + sale_receivables_subquery = "SELECT sale_payments.sale_id, + CASE WHEN sale_payments.payment_method = 'mpu' OR sale_payments.payment_method = 'visa' OR sale_payments.payment_method = 'master' OR sale_payments.payment_method = 'jcb' OR sale_payments.payment_method = 'paypar' OR sale_payments.payment_method = 'unionpay' OR sale_payments.payment_method = 'alipay' OR sale_payments.payment_method = 'paymal' OR sale_payments.payment_method = 'dinga' OR sale_payments.payment_method = 'JunctionPay' THEN SUM(sale_payments.payment_amount) ELSE SUM(0) END as credit_card_sales, + CASE WHEN sale_payments.payment_method = 'giftvoucher' THEN SUM(sale_payments.payment_amount) ELSE SUM(0) END as voucher_sales + FROM sale_payments + GROUP BY sale_payments.sale_id, sale_payments.payment_method" + + query = Sale.select(" + sales.receipt_no as check_num, + sales.receipt_date as business_date, + sales.requested_at as check_open_time, + sales.updated_at as check_close_time, + (sales.grand_total + sales.total_discount) as gross_sales, + sales.total_discount as discount_amt, + sales.grand_total as sales, + (sales.grand_total/21) as tax_amt, + 0 as service_charges, + (sales.grand_total - (sales.grand_total/21)) as net_sales, + receivables.credit_card_sales as credit_card_sales, + receivables.voucher_sales as voucher_sales, + 0 as staff_meal_amt, + sales.rounding_adjustment as rounding_amt, + CASE WHEN sales.sale_status='waste' THEN sales.total_amount ELSE 0 END as wastage_amt, + CASE WHEN sales.sale_status='spoile' THEN sales.total_amount ELSE 0 END as spoilage_amt, + 0 as sampling_amt, + SUM(i.qty) as qty, + 0 as no_of_pax, + 0 as no_of_adult, + 0 as no_of_child, + shift_sales.cashier_terminal_id as pos_id, + sales.cashier_id as employee_code, + employees.name as employee_name, + CASE WHEN sales.sale_status='completed' THEN 1 ELSE 0 END is_valid, + 0 as overing, + 0 as cancle, + CONCAT( employees.name, ' Cash&Go receipt generated and completed.') as remarks") + .joins("LEFT JOIN shift_sales ON shift_sales.id = sales.shift_sale_id") + .joins("LEFT JOIN sale_items i ON i.sale_id = sales.sale_id") + .joins("LEFT JOIN (" + sale_receivables_subquery + ") as receivables ON receivables.sale_id = sales.sale_id") + .joins("LEFT JOIN employees ON employees.id = sales.cashier_id") + .where("DATE(sales.receipt_date) = ? AND sales.sale_status != ?", transaction_date, :void) + .group("sales.receipt_no,sales.sale_status") +end + +# Loader Service SFTP End + private def generate_custom_id @@ -2893,6 +2849,20 @@ private end end + def round_to_precision + if (self.total_amount != self.total_amount_was || self.total_discount != self.total_discount_was || self.total_tax != self.total_tax_was) + if (self.total_amount % 1 > 0 || self.total_discount % 1 > 0 || self.total_tax % 1 > 0) + precision = PrintSetting.get_precision_delimiter().precision.to_i + + self.total_amount = self.total_amount.round(precision) + self.total_discount = self.total_discount.round(precision) + self.total_tax = self.total_tax.round(precision) + self.grand_total = (self.total_amount - self.total_discount) + self.total_tax + end + adjust_rounding + end + end + def update_stock_journal if self.sale_status == "void" && self.sale_status_before_last_save != "void" self.sale_items.each do |item| diff --git a/app/models/sale_item.rb b/app/models/sale_item.rb index d17edc6e..9a8c3d87 100755 --- a/app/models/sale_item.rb +++ b/app/models/sale_item.rb @@ -11,6 +11,7 @@ class SaleItem < ApplicationRecord def compute_item end + before_validation :round_to_precision after_update :update_stock_journal # Add Sale Items @@ -88,7 +89,7 @@ class SaleItem < ApplicationRecord # sale_item.save if type != "foc" sale = Sale.find(sale_id) - sale.compute_by_sale_items(sale.id, sale.sale_items, sale.total_discount) + sale.compute_by_sale_items(sale.total_discount) end end @@ -231,6 +232,24 @@ class SaleItem < ApplicationRecord end end + def round_to_precision + unit_price_fraction = self.unit_price % 1 + price_fraction = self.unit_price % 1 + # is_dining_charge = self.menu_category_code == 'DingingCharge' + + if self.unit_price != self.unit_price_was || self.price != self.price_was + if unit_price_fraction > 0 || price_fraction > 0 + if ['Discount', 'promotion'].include?(self.status) + precision = PrintSetting.get_precision_delimiter().precision.to_i + + self.unit_price = self.unit_price.round(precision) + self.price = (self.unit_price * self.qty).round(precision) + self.taxable_price = self.price + end + end + end + end + def update_stock_journal is_void = self.status == "void" && self.status_before_last_save != "void" cancel_void = self.status_before_last_save == "void" && self.status.nil? @@ -275,4 +294,57 @@ class SaleItem < ApplicationRecord end end + # Loader Service SFTP Start + # Detail Sale Data + def self.get_detail_sale_data(transaction_date) + query = SaleItem.select(" + sale_items.sale_item_id as id, + sale_items.sale_id as parent_id, + s.receipt_no as check_num, + s.receipt_date as business_date, + s.receipt_date as transaction_date, + '' as item_seq, + sale_items.menu_category_code as category_code, + sale_items.menu_category_name as category_name, + '' as sub_category_code, + '' as sub_category_name, + '' as report_group_code, + '' as report_group_name, + sale_items.product_code as item_id, + sale_items.product_name as item_name, + sale_items.qty as qty, + CASE + WHEN s.sale_status = 'completed' OR s.sale_status = 'void' THEN 'Sales' + WHEN s.sale_status = 'waste' THEN 'Waste' + WHEN s.sale_status = 'spoile' THEN 'Spoil' + END as transaction_type, + sale_items.price as gross_sales, + '' as discount_code, + CASE + WHEN i.unit_price IS NOT NULL THEN i.unit_price ELSE 0 + END as discount_amt, + (sale_items.price - (CASE WHEN i.unit_price IS NOT NULL THEN i.unit_price ELSE 0 END)) as sales, + ((sale_items.price - (CASE WHEN i.unit_price IS NOT NULL THEN i.unit_price ELSE 0 END))/21) as tax_amt, + '' as service_charges, + ((sale_items.price - (CASE WHEN i.unit_price IS NOT NULL THEN i.unit_price ELSE 0 END)) - ((sale_items.price - (CASE WHEN i.unit_price IS NOT NULL THEN i.unit_price ELSE 0 END))/21)) as net_sales, + '0' as is_set_item, + '0' as is_staff_meal, + '0' as is_raw_wastage, + '0' as is_semi_wastage, + CASE WHEN s.sale_status = 'waste' THEN 1 ELSE 0 END as is_wastage, + CASE WHEN s.sale_status = 'spoile' THEN 1 ELSE 0 END as is_spoilage, + '0' as is_sampling, + '1' as tax_able, + CASE + WHEN s.sale_status = 'void' THEN 1 ELSE 0 + END as is_void + ") + .joins("LEFT JOIN sales s ON s.sale_id = sale_items.sale_id") + .joins("LEFT JOIN sale_items i ON sale_items.sale_id = i.sale_id AND sale_items.item_instance_code = i.item_instance_code AND i.status = 'Discount' AND sale_items.qty = abs(i.qty)") + .where("DATE(s.receipt_date) = ? AND s.sale_status != 'void' AND (sale_items.status NOT IN('Discount', 'void','foc') OR sale_items.status IS NULL)", transaction_date) + .order("s.receipt_no") + end + + # Loader Service SFTP End + end diff --git a/app/models/sale_order.rb b/app/models/sale_order.rb index bbd68829..bb1375a8 100755 --- a/app/models/sale_order.rb +++ b/app/models/sale_order.rb @@ -6,8 +6,9 @@ class SaleOrder < ApplicationRecord belongs_to :sale belongs_to :order + has_many :order_items, foreign_key: "order_id", primary_key: "order_id" - def create_sale_order(sale_id, order_id) + def create_sale_order(sale_id, order_id) # sale_order = SaleOrder.new self.sale_id = sale_id self.order_id = order_id @@ -37,6 +38,6 @@ class SaleOrder < ApplicationRecord if self.sale_order_id.nil? self.sale_order_id = SeedGenerator.generate_id(self.class.name, 'SOI') end - + end end diff --git a/app/models/sale_payment.rb b/app/models/sale_payment.rb index 2e1700f8..5a1fdb72 100755 --- a/app/models/sale_payment.rb +++ b/app/models/sale_payment.rb @@ -419,7 +419,7 @@ class SalePayment < ApplicationRecord SaleItem.update_existing_item(item.qty, item, self.sale.sale_id, "foc", item.unit_price, item.price) end sale = Sale.find(self.sale.sale_id) - sale.compute_by_sale_items(sale.id, sale.sale_items, sale.total_discount,'','','',"foc") + sale.compute_by_sale_items(sale.total_discount,'','','',"foc") self.payment_method = "foc" self.payment_amount = self.received_amount diff --git a/app/models/sale_tax.rb b/app/models/sale_tax.rb index 06c73253..2e35d2b5 100755 --- a/app/models/sale_tax.rb +++ b/app/models/sale_tax.rb @@ -5,6 +5,8 @@ class SaleTax < ApplicationRecord before_create :generate_custom_id belongs_to :sale + before_validation :round_to_precision + def self.sync_sale_tax_records(sale_taxes) if !sale_taxes.nil? sale_taxes.each do |t| @@ -38,4 +40,13 @@ class SaleTax < ApplicationRecord self.sale_tax_id = SeedGenerator.generate_id(self.class.name, "STI") end end + + def round_to_precision + if self.tax_payable_amount != self.tax_payable_amount_was + if self.tax_payable_amount % 1 > 0 + precision = PrintSetting.get_precision_delimiter().precision.to_i + self.tax_payable_amount = self.tax_payable_amount.round(precision) + end + end + end end diff --git a/app/pdf/order_item_customise_pdf.rb b/app/pdf/order_item_customise_pdf.rb index 850a9574..b509a01a 100644 --- a/app/pdf/order_item_customise_pdf.rb +++ b/app/pdf/order_item_customise_pdf.rb @@ -129,7 +129,7 @@ class OrderItemCustomisePdf < Prawn::Document # add option y_position = cursor - bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + bounding_box([0,y_position], :width => self.item_width) do text "#{options}", :size => self.item_font_size,:align => :left end end diff --git a/app/pdf/order_item_pdf.rb b/app/pdf/order_item_pdf.rb index 58937093..ed079aeb 100755 --- a/app/pdf/order_item_pdf.rb +++ b/app/pdf/order_item_pdf.rb @@ -130,7 +130,7 @@ class OrderItemPdf < Prawn::Document # add option y_position = cursor - bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + bounding_box([0,y_position], :width => self.item_width) do text "#{options}", :size => self.item_font_size,:align => :left end end diff --git a/app/pdf/order_item_slim_pdf.rb b/app/pdf/order_item_slim_pdf.rb index 33e1e314..3e39644f 100755 --- a/app/pdf/order_item_slim_pdf.rb +++ b/app/pdf/order_item_slim_pdf.rb @@ -130,7 +130,7 @@ class OrderItemSlimPdf < Prawn::Document # add option y_position = cursor - bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + bounding_box([0,y_position], :width => self.item_width) do text "#{options}", :size => self.item_font_size,:align => :left end end diff --git a/app/pdf/order_item_star_pdf.rb b/app/pdf/order_item_star_pdf.rb index 711fb81e..2686efd7 100644 --- a/app/pdf/order_item_star_pdf.rb +++ b/app/pdf/order_item_star_pdf.rb @@ -130,7 +130,7 @@ class OrderItemStarPdf < Prawn::Document # add option y_position = cursor - bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + bounding_box([0,y_position], :width => self.item_width) do text "#{options}", :size => self.item_font_size,:align => :left end end diff --git a/app/pdf/order_set_item_customise_pdf.rb b/app/pdf/order_set_item_customise_pdf.rb index ce3e654f..2e1d0a2c 100644 --- a/app/pdf/order_set_item_customise_pdf.rb +++ b/app/pdf/order_set_item_customise_pdf.rb @@ -144,7 +144,7 @@ class OrderSetItemCustomisePdf < Prawn::Document # add option y_position = cursor - bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + bounding_box([0,y_position], :width => self.item_width) do text "#{options}", :size => self.item_font_size,:align => :left end end diff --git a/app/pdf/order_set_item_pdf.rb b/app/pdf/order_set_item_pdf.rb index a02dc3e2..09cdc6db 100755 --- a/app/pdf/order_set_item_pdf.rb +++ b/app/pdf/order_set_item_pdf.rb @@ -143,7 +143,7 @@ class OrderSetItemPdf < Prawn::Document # add option y_position = cursor - bounding_box([0,y_position], :width => self.item_width, :height => self.item_height) do + bounding_box([0,y_position], :width => self.item_width) do text "#{options}", :size => self.item_font_size,:align => :left end end diff --git a/app/views/origami/discounts/index.html.erb b/app/views/origami/discounts/index.html.erb index 3b14e05a..abeeb442 100755 --- a/app/views/origami/discounts/index.html.erb +++ b/app/views/origami/discounts/index.html.erb @@ -34,7 +34,7 @@ <%end%> - +

Receipt No: <%=@sale_data.receipt_no rescue ' '%>

@@ -44,24 +44,22 @@
-
- - - - - - +
+ +
ItemsQTY
+ + + + - - + + <% sub_total = 0 %> <% @sale_data.sale_items.each do |sale_item| %> - <% - sub_total += sale_item.qty*sale_item.unit_price - if sale_item.price != 0 && sale_item.status != "void" && sale_item.status != "foc" - %> - > + <% sub_total += sale_item.qty * sale_item.unit_price %> + <% if sale_item.price > 0 && sale_item.status.blank? %> + > - <% - end - end - %> - -
ItemsQTY Price
@@ -74,14 +72,26 @@ <%=(sale_item.qty*sale_item.unit_price)%>
-
-
+ <% elsif sale_item.price < 0 && sale_item.status == "Discount" %> + > + + + + <%=sale_item.product_name%>@<%=sale_item.unit_price%> + + + <%=sale_item.qty.abs%> + + + <%=(sale_item.qty*sale_item.unit_price)%> + + + <% end %> + <% end %> + + + +